You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

875 lines
36 KiB

<!-- Content Wrapper. Contains page content -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<div class="content-wrapper">
<section class="content-header">
<h1>
Gérer les
<small>Avances</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
<li class="active">Avances</li>
</ol>
</section>
<section class="content">
<div id="messages"></div>
<?php if (in_array('createAvance', $user_permission)): ?>
<button class="btn btn-primary" data-toggle="modal" data-target="#createModal">AJOUTER UNE AVANCE</button>
<br /><br />
<?php endif; ?>
<div class="row">
<div class="col-md-3">
<button id="avance_no_order" class="btn btn-warning w-100 rounded-pill shadow-sm py-2">
<i class="fa fa-hourglass-half me-2"></i> Avances Incomplètes
</button>
</div>
<div class="col-md-3">
<button id="avance_order" class="btn btn-success w-100 rounded-pill shadow-sm py-2">
<i class="fa fa-check-circle me-2"></i> Avances Complètes
</button>
</div>
<div class="col-md-3">
<button id="avance_expired" class="btn btn-outline-danger w-100 rounded-pill shadow-sm py-2 fw-bold border-2">
<i class="fa fa-exclamation-circle me-2"></i> Avances Expirées
</button>
</div>
</div>
<br>
<div class="box">
<div class="box-header"><h3 class="box-title">Liste des avances</h3></div>
<div class="box-body">
<table id="avanceTable" class="table table-bordered table-striped">
<thead>
<?php $session = session();
$users = $session->get('user');
$isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
$isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
$isCaissier = in_array($users['group_name'], ['Caissier']);
if ($isAdmin): ?>
<tr>
<th>Client</th>
<th>Téléphone</th>
<th>Adresse</th>
<th>Produit</th>
<th>Prix</th>
<th>Avance</th>
<th>Reste à payer</th>
<th>Date</th>
<?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission)): ?>
<th>Action</th>
<?php endif;?>
</tr>
<?php endif;?>
<?php $session = session();
$users = $session->get('user');
$isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
$isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
$isCaissier = in_array($users['group_name'], ['Caissier']);
if ($isCommerciale || $isCaissier): ?>
<tr>
<th>#</th>
<th>Produit</th>
<th>Avance</th>
<th>Reste à payer</th>
<th>Date</th>
<?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission) ||in_array('viewAvance', $user_permission)): ?>
<th>Action</th>
<?php endif;?>
</tr>
<?php endif;?>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
</div>
<!-- Modal Création -->
<?php if (in_array('createAvance', $user_permission)): ?>
<div class="modal fade" id="createModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form id="create_avance_form">
<div class="modal-header">
<h4 class="modal-title">Ajouter une avance</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<div class="row">
<!-- Type d'avance -->
<div class="form-group col-md-6">
<label for="type_avance" class="form-label">Type d'avance</label>
<select name="type_avance" id="type_avance" class="form-control" required>
<option value="" disabled selected>Sélectionnez un type d'avance</option>
<option value="terre">Avance sur terre</option>
<option value="mere">Avance sur mer</option>
</select>
</div>
<!-- Moyen de paiement -->
<div class="form-group col-md-6">
<label for="type_payment" class="form-label">Moyen de paiement</label>
<select class="form-control" id="type_payment" name="type_payment">
<option value="" disabled selected>Sélectionnez un moyen de paiement</option>
<option value="MVOLA">MVOLA</option>
<option value="Virement Bancaire">Virement Bancaire</option>
<option value="En espèce">En espèce</option>
</select>
</div>
<!-- Nom client -->
<div class="form-group col-md-6">
<label>Nom du client</label>
<input type="text" name="customer_name_avance" id="customer_name_avance" class="form-control" required>
</div>
<!-- Téléphone client -->
<div class="form-group col-md-6">
<label>Téléphone du client</label>
<input type="text" name="customer_phone_avance" id="customer_phone_avance" class="form-control" required>
</div>
<!-- Adresse client -->
<div class="form-group col-md-6">
<label>Adresse du client</label>
<input type="text" name="customer_address_avance" id="customer_address_avance" class="form-control" required>
</div>
<!-- CIN client -->
<div class="form-group col-md-6">
<label>CIN du client</label>
<input type="text" name="customer_cin_avance" id="customer_cin_avance" class="form-control" required>
</div>
</div>
<div class="row">
<!-- Produit avec sélection (pour "terre") -->
<div class="form-group col-md-6" id="product_select_container">
<label for="id_product" class="form-label">Produit</label>
<select name="id_product" id="id_product" class="form-control" onchange="getProductDataCreate()">
<option value="">Sélectionnez un produit</option>
<?php foreach($products as $p): ?>
<option value="<?= $p['id'] ?>" <?= $p['product_sold'] ? 'disabled' : '' ?>>
<?= esc($p['name']) ?>|<?= esc($p['sku']) ?> <?= $p['product_sold'] ? '(Rupture)' : '' ?>
</option>
<?php endforeach; ?>
</select>
</div>
<!-- Produit avec texte libre (pour "mère") -->
<div class="form-group col-md-6" id="product_text_container" style="display:none;">
<label>Produit (à compléter)</label>
<input type="text" name="product_name_text" id="product_name_text" class="form-control" placeholder="Entrez le nom du produit">
</div>
<!-- Prix du produit -->
<div class="form-group col-md-6">
<label>Prix du produit</label>
<input type="number" name="gross_amount" id="gross_amount" class="form-control" placeholder="Entrez le prix">
</div>
</div>
<div class="row">
<!-- Avance -->
<div class="form-group col-md-6">
<label>Avance</label>
<input type="number" name="avance_amount" id="avance_amount" class="form-control" placeholder="Entrez l'avance">
</div>
<!-- Reste à payer -->
<div class="form-group col-md-6">
<label>Reste à payer</label>
<input type="text" name="amount_due" id="amount_due" class="form-control" readonly>
</div>
</div>
<!-- Commentaire (affiché uniquement pour "mère") -->
<div class="row">
<div class="form-group col-md-12" id="commentaire_container" style="display:none;">
<label>Commentaire</label>
<textarea name="commentaire" id="commentaire" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Enregistrer</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
</div>
</form>
</div>
</div>
</div>
<?php endif; ?>
<!-- Modal Modification -->
<?php if (in_array('updateAvance', $user_permission)): ?>
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form id="update_avance_form" method="post">
<input type="hidden" name="id" id="avance_id_edit">
<div class="modal-header">
<h4 class="modal-title">Modifier une avance</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<div class="row">
<!-- Type d'avance -->
<div class="form-group col-md-6">
<label for="type_avance_edit" class="form-label">Type d'avance</label>
<select name="type_avance_edit" id="type_avance_edit" class="form-control" required>
<option value="" disabled>Sélectionnez un type d'avance</option>
<option value="terre">Avance sur terre</option>
<option value="mere">Avance sur mer</option>
</select>
</div>
<!-- Moyen de paiement -->
<div class="form-group col-md-6">
<label for="type_payment_edit" class="form-label">Moyen de paiement</label>
<select class="form-control" id="type_payment_edit" name="type_payment_edit">
<option value="" disabled>Sélectionnez un moyen de paiement</option>
<option value="MVOLA">MVOLA</option>
<option value="Virement Bancaire">Virement Bancaire</option>
<option value="En espèce">En espèce</option>
</select>
</div>
<!-- Nom client -->
<div class="form-group col-md-6">
<label>Nom du client</label>
<input type="text" name="customer_name_avance_edit" id="customer_name_avance_edit" class="form-control" required>
</div>
<!-- Téléphone client -->
<div class="form-group col-md-6">
<label>Téléphone du client</label>
<input type="text" name="customer_phone_avance_edit" id="customer_phone_avance_edit" class="form-control" required>
</div>
<!-- Adresse client -->
<div class="form-group col-md-6">
<label>Adresse du client</label>
<input type="text" name="customer_address_avance_edit" id="customer_address_avance_edit" class="form-control" required>
</div>
<!-- CIN client -->
<div class="form-group col-md-6">
<label>CIN du client</label>
<input type="text" name="customer_cin_avance_edit" id="customer_cin_avance_edit" class="form-control" required>
</div>
</div>
<div class="row">
<!-- Produit avec sélection (pour "terre") -->
<div class="form-group col-md-6" id="product_select_container_edit">
<label class="form_label">Produit</label>
<select name="id_product_edit" id="id_product_edit" class="form-control" onchange="getProductDataUpdate()">
<option value="">Sélectionnez un produit</option>
<?php foreach($products as $p): ?>
<option value="<?= $p['id'] ?>" <?= $p['product_sold'] ? 'disabled' : '' ?>>
<?= esc($p['sku']) ?> | <?= esc($p['name']) ?> | <?= esc($p['numero_de_moteur']) ?> | <?= esc($p['puissance']) ?>
<?= $p['product_sold'] ? ' (Rupture)' : '' ?>
</option>
<?php endforeach; ?>
</select>
</div>
<!-- Produit avec texte libre (pour "mère") -->
<div class="form-group col-md-6" id="product_text_container_edit" style="display:none;">
<label>Produit (à compléter)</label>
<input type="text" name="product_name_text_edit" id="product_name_text_edit" class="form-control" placeholder="Entrez le nom du produit">
</div>
<!-- Prix du produit -->
<div class="form-group col-md-6">
<label>Prix du produit</label>
<input type="number" name="gross_amount_edit" id="gross_amount_edit" class="form-control" placeholder="Entrez le prix">
</div>
</div>
<div class="row">
<!-- Avance -->
<div class="form-group col-md-6">
<label>Avance</label>
<input type="number" name="avance_amount_edit" id="avance_amount_edit" class="form-control" placeholder="Entrez l'avance">
</div>
<!-- Reste à payer -->
<div class="form-group col-md-6">
<label>Reste à payer</label>
<input type="text" name="amount_due_edit" id="amount_due_edit" class="form-control" readonly>
</div>
</div>
<!-- Commentaire (affiché uniquement pour "mère") -->
<div class="row">
<div class="form-group col-md-12" id="commentaire_container_edit" style="display:none;">
<label>Commentaire</label>
<textarea name="commentaire_edit" id="commentaire_edit" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Modifier</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
</div>
</form>
</div>
</div>
</div>
<?php endif;?>
<?php if (in_array('deleteAvance', $user_permission)): ?>
<!-- remove brand modal -->
<div class="modal fade" tabindex="-1" role="dialog" id="removeModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title">Supprimer cette avance</h4>
</div>
<form role="form" action="<?php echo base_url('avances/deleteAvance') ?>" method="post" id="removeForm">
<input type="hidden" name="avance_id" value="">
<input type="hidden" name="product_id" value="">
<div class="modal-body">
<p>Voulez-vous vraiment supprimer ?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn btn-primary">Oui</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<?php endif; ?>
<script>
var base_url = "<?= base_url() ?>", brutCreate = 0, brutEdit = 0;
$(document).ready(function() {
$('#avance_menu').addClass("active");
$('.select2').select2();
// 📌 Configuration langue FR
var datatableLangFr = {
lengthMenu: "Afficher _MENU_ enregistrements par page",
zeroRecords: "Aucun résultat trouvé",
info: "Affichage de _START_ à _END_ sur _TOTAL_ enregistrements",
infoEmpty: "Aucun enregistrement disponible",
infoFiltered: "(filtré depuis _MAX_ enregistrements au total)",
search: "Rechercher :",
paginate: {
first: "Premier",
last: "Dernier",
next: "Suivant",
previous: "Précédent"
}
};
// 📌 Fonction pour initialiser la DataTable
function initAvanceTable(url, columns) {
if ($.fn.DataTable.isDataTable('#avanceTable')) {
$('#avanceTable').DataTable().destroy();
}
return $('#avanceTable').DataTable({
ajax: url,
columns: columns,
language: datatableLangFr
});
}
// 🔄 FONCTION DE MISE À JOUR DYNAMIQUE DE LA DATATABLE
function refreshDataTable() {
if (typeof manageTable !== 'undefined' && manageTable) {
manageTable.ajax.reload(null, false);
}
}
// ✅ INITIALISATION : Définir "terre" par défaut au chargement du modal création
$('#createModal').on('show.bs.modal', function() {
$('#create_avance_form')[0].reset();
// Par défaut : mode "terre"
$('#product_select_container').show();
$('#id_product').prop('required', true);
$('#product_text_container').hide();
$('#product_name_text').prop('required', false);
$('#gross_amount').prop('readonly', true).prop('type', 'text');
$('#commentaire_container').hide();
// Réattacher les événements
$('#avance_amount').off('keyup').on('keyup', updateDueCreate);
});
<?php if ($isAdmin): ?>
var adminColumns = [
{ title: "Client" },
{ title: "Téléphone" },
{ title: "Adresse" },
{ title: "Produit" },
{ title: "Prix" },
{ title: "Avance" },
{ title: "Reste à payer" },
{ title: "Date" }
<?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission)): ?>
,{ title: "Action", orderable: false, searchable: false }
<?php endif; ?>
];
var manageTable = initAvanceTable(base_url + 'avances/fetchAvanceData', adminColumns);
$('#avance_order').on('click', function () {
manageTable = initAvanceTable(base_url + 'avances/fetchAvanceBecameOrder', adminColumns);
});
$('#avance_expired').on('click', function () {
manageTable = initAvanceTable(base_url + 'avances/fetchExpiredAvance', adminColumns);
});
$('#avance_no_order').on('click', function () {
manageTable = initAvanceTable(base_url + 'avances/fetchAvanceData', adminColumns);
});
<?php endif; ?>
<?php if ($isCaissier || $isCommerciale): ?>
var userColumns = [
{ title: "#" },
{ title: "Produit" },
{ title: "Avance" },
{ title: "Reste à payer" },
{ title: "Date" }
<?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission)): ?>
,{ title: "Action", orderable: false, searchable: false }
<?php endif; ?>
];
var manageTable = initAvanceTable('fetchAvanceData', userColumns);
$('#avance_order').on('click', function () {
manageTable = initAvanceTable('fetchAvanceBecameOrder', userColumns);
});
$('#avance_no_order').on('click', function () {
manageTable = initAvanceTable('fetchAvanceData', userColumns);
});
<?php endif; ?>
// =====================================================
// 🔥 GESTION DU TYPE D'AVANCE - CRÉATION
// =====================================================
$('#type_avance').on('change', function() {
var typeAvance = $(this).val();
if (typeAvance === 'mere') {
// MASQUER le select de produit
$('#product_select_container').hide();
$('#id_product').prop('required', false).val('');
// AFFICHER le champ texte pour produit
$('#product_text_container').show();
$('#product_name_text').prop('required', true);
// RENDRE le prix modifiable ET changer en type="number"
$('#gross_amount').prop('readonly', false).prop('type', 'number').val('').prop('required', true);
// AFFICHER le commentaire
$('#commentaire_container').show();
// Calcul simple : Prix - Avance
$('#avance_amount, #gross_amount').off('keyup').on('keyup', function() {
var prix = parseFloat($('#gross_amount').val()) || 0;
var avance = parseFloat($('#avance_amount').val()) || 0;
var reste = prix - avance;
$('#amount_due').val(reste >= 0 ? reste.toFixed(0) : 0);
});
} else if (typeAvance === 'terre') {
// AFFICHER le select de produit
$('#product_select_container').show();
$('#id_product').prop('required', true);
// MASQUER le champ texte
$('#product_text_container').hide();
$('#product_name_text').prop('required', false).val('');
// RENDRE le prix readonly ET en type="text"
$('#gross_amount').prop('readonly', true).prop('type', 'text').prop('required', false);
// MASQUER le commentaire
$('#commentaire_container').hide();
$('#commentaire').val('');
// Restaurer le comportement normal avec validation 25%
$('#avance_amount').off('keyup').on('keyup', updateDueCreate);
$('#gross_amount').off('keyup');
}
// Réinitialiser les champs
$('#gross_amount').val('');
$('#avance_amount').val('');
$('#amount_due').val('');
});
// =====================================================
// 🔥 GESTION DU TYPE D'AVANCE - ÉDITION
// =====================================================
$('#type_avance_edit').on('change', function() {
var typeAvance = $(this).val();
if (typeAvance === 'mere') {
$('#product_select_container_edit').hide();
$('#id_product_edit').prop('required', false).val('');
$('#product_text_container_edit').show();
$('#product_name_text_edit').prop('required', true);
$('#gross_amount_edit').prop('readonly', false).prop('type', 'number').prop('required', true);
$('#commentaire_container_edit').show();
$('#avance_amount_edit, #gross_amount_edit').off('keyup').on('keyup', function() {
var prix = parseFloat($('#gross_amount_edit').val()) || 0;
var avance = parseFloat($('#avance_amount_edit').val()) || 0;
var reste = prix - avance;
$('#amount_due_edit').val(reste >= 0 ? reste.toFixed(0) : 0);
});
} else if (typeAvance === 'terre') {
$('#product_select_container_edit').show();
$('#id_product_edit').prop('required', true);
$('#product_text_container_edit').hide();
$('#product_name_text_edit').prop('required', false).val('');
$('#gross_amount_edit').prop('readonly', true).prop('type', 'text').prop('required', false);
$('#commentaire_container_edit').hide();
$('#commentaire_edit').val('');
$('#avance_amount_edit').off('keyup').on('keyup', updateDueEdit);
$('#gross_amount_edit').off('keyup');
}
});
// ✅ CRÉATION avec actualisation automatique
$('#create_avance_form').on('submit', function(e) {
e.preventDefault();
const $form = $(this);
var typeAvance = $('#type_avance').val();
var brut = parseFloat($('#gross_amount').val()) || 0;
var avance = parseFloat($('#avance_amount').val()) || 0;
if (typeAvance === 'terre') {
var minAvance = brut * 0.25;
if (avance < minAvance) {
Swal.fire({
icon: 'error',
title: 'Avance insuffisante',
html: `L'avance doit être au minimum de <b>25%</b> du prix du produit (<b>${minAvance.toFixed(2)} Ar</b>).`,
confirmButtonText: 'OK',
confirmButtonColor: '#d33'
});
return;
}
}
// Validation pour "mère"
if (typeAvance === 'mere') {
if (!$('#product_name_text').val() || brut === 0 || avance === 0) {
Swal.fire({
icon: 'warning',
title: 'Champs manquants',
text: 'Veuillez remplir tous les champs : produit, prix et avance.'
});
return;
}
}
$form.find('button[type="submit"]').prop('disabled', true).text('Enregistrement...');
$.post('/avances/createAvance', $form.serialize(), function(res) {
if (res.success === true) {
Swal.fire({
icon: 'success',
title: 'Succès',
text: res.messages,
timer: 1500,
showConfirmButton: false
}).then(() => {
$("#createModal").modal('hide');
$form[0].reset();
location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: 'Erreur',
text: res.messages
});
$form.find('button[type="submit"]').prop('disabled', false).text('Enregistrer');
}
}, 'json');
});
// 🔥 SUPPRESSION
window.removeFunc = function(id, product_id) {
$('#removeModal').modal('show');
$('#removeForm input[name="avance_id"]').val(id);
$('#removeForm input[name="product_id"]').val(product_id);
};
$('#removeForm').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var submitButton = form.find('button[type="submit"]');
submitButton.prop('disabled', true).text('Suppression...');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success === true) {
$('#removeModal').modal('hide');
$("#messages").html(`
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong><span class="glyphicon glyphicon-ok-sign"></span></strong> ${response.messages}
</div>
`);
refreshDataTable();
setTimeout(function() {
$("#messages .alert").fadeOut();
location.reload();
}, 3000);
} else {
$('#removeModal').modal('hide');
$("#messages").html(`
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong><span class="glyphicon glyphicon-exclamation-sign"></span></strong> ${response.messages}
</div>
`);
}
},
complete: function() {
submitButton.prop('disabled', false).text('Oui');
}
});
return false;
});
}); // Fin document.ready
// --- Fonctions utilitaires ---
function getProductDataCreate() {
var id = $('#id_product').val();
if (!id) {
brutCreate = 0;
$('#gross_amount,#amount_due,#avance_amount').val('');
return;
}
$.post(base_url + 'orders/getProductValueById', { product_id: id }, function(r) {
brutCreate = parseFloat(r.prix_vente) || 0;
$('#gross_amount').val(brutCreate.toFixed(0));
var avance25 = brutCreate * 0.25;
$('#avance_amount').val(avance25.toFixed(0));
$('#amount_due').val((brutCreate - avance25).toFixed(0));
}, 'json');
}
function updateDueCreate() {
var av = parseFloat($('#avance_amount').val()) || 0;
var brutAmount = parseFloat($('#gross_amount').val()) || 0;
$('#amount_due').val(Math.max(brutAmount - av, 0).toFixed(0));
}
function getProductDataUpdate() {
var id = $('#id_product_edit').val();
if (!id) {
brutEdit = 0;
$('#gross_amount_edit,#amount_due_edit,#avance_amount_edit').val('');
return;
}
$.ajax({
url: base_url + 'orders/getProductValueById',
type: 'POST',
data: { product_id: id },
dataType: 'json',
success: function(r) {
brutEdit = parseFloat(r.prix_vente) || 0;
$('#gross_amount_edit').val(brutEdit.toFixed(0));
var avance25 = brutEdit * 0.25;
$('#avance_amount_edit').val(avance25.toFixed(0));
$('#amount_due_edit').val((brutEdit - avance25).toFixed(0));
}
});
}
function updateDueEdit() {
var av = parseFloat($('#avance_amount_edit').val()) || 0;
$('#amount_due_edit').val(Math.max(brutEdit - av, 0).toFixed(0));
}
// ✅ MODIFICATION
function editFunc(id) {
$('#update_avance_form')[0].reset();
$.ajax({
url: base_url + 'avances/fetchSingleAvance/' + id,
type: 'GET',
dataType: 'json',
success: function(r) {
$('#avance_id_edit').val(r.id || id);
$('#customer_name_avance_edit').val(r.customer_name || '');
$('#customer_phone_avance_edit').val(r.customer_phone || '');
$('#customer_address_avance_edit').val(r.customer_address || r.customer_adress || '');
$('#customer_cin_avance_edit').val(r.customer_cin || '');
$('#type_avance_edit').val(r.type_avance || '');
$('#type_payment_edit').val(r.type_payment || '');
$('#gross_amount_edit').val(r.gross_amount || '');
$('#avance_amount_edit').val(r.avance_amount || '');
$('#amount_due_edit').val(r.amount_due || '');
$('#commentaire_edit').val(r.commentaire || '');
// Gérer le produit selon le type
if (r.type_avance === 'mere' && r.product_name) {
$('#product_name_text_edit').val(r.product_name);
}
var productId = r.product_id || r.id_product;
brutEdit = parseFloat(r.gross_amount || 0);
$('#updateModal').modal('show');
$('#updateModal').on('shown.bs.modal', function(e) {
// Déclencher le change pour afficher les bons champs
$('#type_avance_edit').trigger('change');
if (productId && r.type_avance === 'terre') {
setTimeout(function() {
$('#id_product_edit').val(productId).trigger('change');
}, 100);
}
$(this).off('shown.bs.modal');
});
$('#update_avance_form').off('submit').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var $submitBtn = $form.find('button[type="submit"]');
var typeAvance = $('#type_avance_edit').val();
var avance = parseFloat($('#avance_amount_edit').val()) || 0;
var brut = parseFloat($('#gross_amount_edit').val()) || 0;
// Validation pour "terre"
if (typeAvance === 'terre') {
var minAvance = brutEdit * 0.25;
if (avance < minAvance) {
$("#messages").html(`
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong><span class="glyphicon glyphicon-exclamation-sign"></span></strong>
L'avance doit être au minimum de 25% du prix du produit (${minAvance.toFixed(2)} Ar).
</div>
`);
return;
}
}
// Validation pour "mère"
if (typeAvance === 'mere') {
if (!$('#product_name_text_edit').val() || brut === 0 || avance === 0) {
$("#messages").html(`
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong><span class="glyphicon glyphicon-exclamation-sign"></span></strong>
Veuillez remplir tous les champs requis.
</div>
`);
return;
}
}
$submitBtn.prop('disabled', true).text('Modification...');
$.ajax({
url: base_url + 'avances/updateAvance/' + id,
type: 'POST',
data: $form.serialize(),
dataType: 'json',
success: function(res) {
if (res.success === true) {
$('#updateModal').modal('hide');
$("#messages").html(`
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong><span class="glyphicon glyphicon-ok-sign"></span></strong> ${res.messages}
</div>
`);
if (typeof manageTable !== 'undefined' && manageTable) {
manageTable.ajax.reload(null, false);
}
setTimeout(function() {
location.reload();
}, 1000);
} else {
$("#messages").html(`
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong><span class="glyphicon glyphicon-exclamation-sign"></span></strong> ${res.messages}
</div>
`);
}
},
complete: function() {
$submitBtn.prop('disabled', false).text('Modifier');
}
});
});
}
});
}
</script>