diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php
index c165adee7a0..742d5e03756 100644
--- a/htdocs/compta/facture/prelevement.php
+++ b/htdocs/compta/facture/prelevement.php
@@ -797,113 +797,116 @@ if ($object->id > 0) {
$buttonlabel = $langs->trans("MakeBankTransferOrder");
$user_perms = $user->hasRight('paymentbybanktransfer', 'create');
}
-
+ // Calculate the remaining amount available for new transfer requests
+ // This takes into account pending requests (traite=0) and requests in non-credited transfer receipts
+ $remaintopaylesspendingdebit = $resteapayer - $pending;
// Add a transfer request
- if ($object->status > $object::STATUS_DRAFT && $object->paid == 0 && $numopen == 0) {
- if ($resteapayer > 0) {
- if ($user_perms) {
- $remaintopaylesspendingdebit = $resteapayer - $pending;
-
- $title = $langs->trans("NewStandingOrder");
- if ($type == 'bank-transfer') {
- $title = $langs->trans("NewPaymentByBankTransfer");
+ // If WITHDRAW_STRICT_CHECK_AMOUNT is enabled, allow multiple partial requests as long as the total requested amount doesn't exceed the invoice total
+ // Otherwise, use original behavior: block if any request is pending
+ if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) {
+ // New behavior: check remaining amount
+ $canCreateRequest = ($object->status > $object::STATUS_DRAFT && $object->paid == 0 && $remaintopaylesspendingdebit > 0);
+ } else {
+ // Original behavior: check if no open requests
+ $canCreateRequest = ($object->status > $object::STATUS_DRAFT && $object->paid == 0 && $numopen == 0 && $resteapayer > 0);
+ }
+ if ($canCreateRequest) {
+ if ($user_perms) {
+ $title = $langs->trans("NewStandingOrder");
+ if ($type == 'bank-transfer') {
+ $title = $langs->trans("NewPaymentByBankTransfer");
+ }
+ print '';
+ print '
';
+ if (getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT_SHOW_OLD_BUTTON')) { // This is hidden, prefer to use mode enabled with STRIPE_SEPA_DIRECT_DEBIT
+ // TODO Replace this with a checkbox for each payment mode: "Send request to XXX immediately..."
+ print " ";
+ // Add stripe sepa button
+ $buttonlabel = $langs->trans("MakeWithdrawRequestStripe");
+ print '';
print ' ';
print ' ';
print ' ';
print ' ';
-
- print '';
-
- //print $langs->trans('CustomerIBAN').' ';
-
- // if societe rib in model invoice, we preselect it
- $selectedRib = '';
- if ($object->element == 'invoice' && $object->fk_fac_rec_source) {
- $facturerec = new FactureRec($db);
- $facturerec->fetch($object->fk_fac_rec_source);
- if ($facturerec->fk_societe_rib) {
- $companyBankAccount = new CompanyBankAccount($db);
- $res = $companyBankAccount->fetch($facturerec->fk_societe_rib);
- $selectedRib = $companyBankAccount->id;
- }
- }
-
- $selectedRib = $form->selectRib($selectedRib, 'accountcustomerid', 'fk_soc='.$object->socid, $langs->trans("CustomerIBAN"), '', 1, 'maxwidth500 maxwidth250onsmartphone');
-
- $defaultRibId = $object->thirdparty->getDefaultRib();
- if ($defaultRibId) {
- $companyBankAccount = new CompanyBankAccount($db);
- $res = $companyBankAccount->fetch($defaultRibId);
- if ($res > 0 && !$companyBankAccount->verif()) {
- print img_warning('Error on default bank number for IBAN : '.$langs->trans($companyBankAccount->error));
- }
- } elseif (($type != 'bank-transfer' && $object->mode_reglement_code == 'PRE') || ($type == 'bank-transfer' && $object->mode_reglement_code == 'VIR')) {
- print img_warning($langs->trans("NoDefaultIBANFound"));
- }
-
-
- // Bank Transfer Amount
- if (getDolOptimizeSmallScreen()) {
- print ' ';
- } else {
- print ' ';
- }
- print '';
- if ($type == 'bank-transfer') {
- print $langs->trans('BankTransferAmount');
- } else {
- print $langs->trans("WithdrawRequestAmount");
- }
- print ' ';
- print ' ';
-
- // Button
- print ' ';
+ print ' ';
+ print ''.$langs->trans('BankTransferAmount').' ';
+ print ' ';
print ' ';
- print ' ';
-
- print '
';
-
print ' ';
-
- if (getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT_SHOW_OLD_BUTTON')) { // This is hidden, prefer to use mode enabled with STRIPE_SEPA_DIRECT_DEBIT
- // TODO Replace this with a checkbox for each payment mode: "Send request to XXX immediately..."
- print " ";
- // Add stripe sepa button
- $buttonlabel = $langs->trans("MakeWithdrawRequestStripe");
- print '';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ''.$langs->trans('BankTransferAmount').' ';
- print ' ';
- print ' ';
- print ' ';
- }
- } else {
- print ''.$buttonlabel.' ';
}
} else {
- print ''.$buttonlabel.' ';
+ print ''.$buttonlabel.' ';
}
} else {
- if ($numopen == 0) {
- if ($object->status > $object::STATUS_DRAFT) {
- print ''.$buttonlabel.' ';
+ // Different error messages based on the mode
+ if ($object->status > $object::STATUS_DRAFT) {
+ if ($object->paid == 0) {
+ if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) {
+ // Total amount has already been requested (pending + in transfer receipts)
+ print ''.$buttonlabel.' ';
+ } else {
+ // Original behavior: request already done or amount must be positive
+ if ($numopen > 0) {
+ print ''.$buttonlabel.' ';
+ } else {
+ print ''.$buttonlabel.' ';
+ }
+ }
} else {
- print ''.$buttonlabel.' ';
+ print ''.$buttonlabel.' ';
}
} else {
- print ''.$buttonlabel.' ';
+ print ''.$buttonlabel.' ';
}
}
-
print "\n";
diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php
index b0717809528..8438da1e5ba 100644
--- a/htdocs/core/class/commoninvoice.class.php
+++ b/htdocs/core/class/commoninvoice.class.php
@@ -1331,102 +1331,170 @@ abstract class CommonInvoice extends CommonObject
$bac = new CompanyBankAccount($this->db);
$bac->fetch($ribId, '', $this->socid);
- $sql = "SELECT count(rowid) as nb";
- $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
- if ($type == 'bank-transfer') {
- $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
- } else {
- $sql .= " WHERE fk_facture = ".((int) $this->id);
- }
- $sql .= " AND type = 'ban'"; // To exclude record done for some online payments
- if (empty($checkduplicateamongall)) {
- $sql .= " AND traite = 0";
- }
-
- dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
-
- $resql = $this->db->query($sql);
- if ($resql) {
- $obj = $this->db->fetch_object($resql);
- if ($obj && $obj->nb == 0) { // If no request found yet
- $now = dol_now();
-
- $totalpaid = $this->getSommePaiement();
- $totalcreditnotes = $this->getSumCreditNotesUsed();
- $totaldeposits = $this->getSumDepositsUsed();
- //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
-
- // We can also use bcadd to avoid pb with floating points
- // For example print 239.2 - 229.3 - 9.9; does not return 0.
- //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
- //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
- if (empty($amount)) {
- $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
- }
-
- if (is_numeric($amount) && $amount != 0) {
- $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande(';
- if ($type == 'bank-transfer') {
- $sql .= 'fk_facture_fourn, ';
- } else {
- $sql .= 'fk_facture, ';
- }
- $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, type, entity';
- if (empty($bac->id)) {
- $sql .= ')';
- } else {
- $sql .= ', fk_societe_rib)';
- }
- $sql .= " VALUES (".((int) $this->id);
- $sql .= ", ".((float) price2num($amount));
- $sql .= ", '".$this->db->idate($now)."'";
- $sql .= ", ".((int) $fuser->id);
- $sql .= ", '".$this->db->escape($bac->code_banque)."'";
- $sql .= ", '".$this->db->escape($bac->code_guichet)."'";
- $sql .= ", '".$this->db->escape($bac->number)."'";
- $sql .= ", '".$this->db->escape($bac->cle_rib)."'";
- $sql .= ", '".$this->db->escape($sourcetype)."'";
- $sql .= ", 'ban'";
- $sql .= ", ".((int) $conf->entity);
- if (!empty($bac->id)) {
- $sql .= ", '".$this->db->escape((string) $bac->id)."'";
- }
- $sql .= ")";
-
- dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) {
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this).'::demandeprelevement Erreur');
- $error++;
- }
- } else {
- $this->error = 'WithdrawRequestErrorNilAmount';
- dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
- $error++;
- }
-
- if (!$error) {
- // Force payment mode of invoice to withdraw
- $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
- if ($payment_mode_id > 0) {
- $result = $this->setPaymentMethods($payment_mode_id);
- }
- }
-
- if ($error) {
- return -1;
- }
- return 1;
+ // Option to allow multiple partial requests
+ // If WITHDRAW_STRICT_CHECK_AMOUNT is enabled, we check the sum of amounts instead of just counting requests
+ if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) {
+ // Calculate sum of amounts already requested instead of just counting requests
+ // This allows multiple partial requests as long as the total doesn't exceed the remain to pay
+ $total_already_requested = 0;
+ // Step 1: Get pending requests with no transfer receipt yet (traite = 0)
+ $sql = "SELECT COALESCE(SUM(amount), 0) as total_requested";
+ $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
+ if ($type == 'bank-transfer') {
+ $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
} else {
- $this->error = "A request already exists";
- dol_syslog(get_class($this).'::demandeprelevement Can t create a request to generate a direct debit, a request already exists.');
- return 0;
+ $sql .= " WHERE fk_facture = ".((int) $this->id);
+ }
+ $sql .= " AND type = 'ban'"; // To exclude record done for some online payments
+ $sql .= " AND traite = 0"; // Not yet in a transfer receipt
+ dol_syslog(get_class($this)."::demande_prelevement - get pending requests not yet in receipt", LOG_DEBUG);
+ $resql= $this->db->query($sql);
+ if ($resql) {
+ $obj = $this->db->fetch_object($resql);
+ $total_already_requested += $obj ? (float) $obj->total_requested : 0;
+ } else {
+ $this->error = $this->db->error();
+ dol_syslog(get_class($this).'::demandeprelevement Error -2a');
+ return -2;
+ }
+ // Step 2: Get pending requests in transfer receipt but not yet credited
+ $sql = "SELECT COALESCE(SUM(pl.amount), 0) as total_requested";
+ $sql .= " FROM ".$this->db->prefix()."prelevement_lignes as pl";
+ $sql .= " INNER JOIN ".$this->db->prefix()."prelevement as p ON p.fk_prelevement_lignes = pl.rowid";
+ if ($type == 'bank-transfer') {
+ $sql .= " WHERE p.fk_facture_fourn = ".((int) $this->id);
+ } else {
+ $sql .= " WHERE p.fk_facture = ".((int) $this->id);
+ }
+ $sql .= " AND (pl.statut IS NULL OR pl.statut = 0)"; // Not yet processed (statut 2 = credited)
+ dol_syslog(get_class($this)."::demande_prelevement - get requests in non-credited receipts", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $obj = $this->db->fetch_object($resql);
+ $total_already_requested += $obj ? (float) $obj->total_requested : 0;
+ // Calculate remain to pay
+ $totalpaid = $this->getSommePaiement();
+ $totalcreditnotes = $this->getSumCreditNotesUsed();
+ $totaldeposits = $this->getSumDepositsUsed();
+ $resteapayer = (float) price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
+ // Calculate remaining amount available for new requests
+ $remaining_for_request = (float) price2num($resteapayer - $total_already_requested, 'MT');
+ // If no amount specified, use the remaining available
+ if (empty($amount)) {
+ $amount = $remaining_for_request;
+ }
+ // Check if there's still room for new requests
+ $can_create_request = ($remaining_for_request > 0 && $amount <= $remaining_for_request);
+ } else {
+ $this->error = $this->db->error();
+ dol_syslog(get_class($this).'::demandeprelevement Error -2b');
+ return -2;
}
} else {
- $this->error = $this->db->error();
- dol_syslog(get_class($this).'::demandeprelevement Error -2');
- return -2;
+ // Original behavior: only check if a request already exists (count)
+ $sql = "SELECT count(rowid) as nb";
+ $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
+ if ($type == 'bank-transfer') {
+ $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
+ } else {
+ $sql .= " WHERE fk_facture = ".((int) $this->id);
+ }
+ $sql .= " AND type = 'ban'"; // To exclude record done for some online payments
+ if (empty($checkduplicateamongall)) {
+ $sql .= " AND traite = 0";
+ }
+
+ dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $obj = $this->db->fetch_object($resql);
+ $can_create_request = ($obj && $obj->nb == 0);
+ // Calculate amount if not specified
+ if (empty($amount)) {
+ $totalpaid = $this->getSommePaiement();
+ $totalcreditnotes = $this->getSumCreditNotesUsed();
+ $totaldeposits = $this->getSumDepositsUsed();
+ //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
+ // We can also use bcadd to avoid pb with floating points
+ // For example print 239.2 - 229.3 - 9.9; does not return 0.
+ //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
+ //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
+ $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
+ }
+ $remaining_for_request = $amount; // For error message compatibility
+ } else {
+ $this->error = $this->db->error();
+ dol_syslog(get_class($this).'::demandeprelevement Error -2');
+ return -2;
+ }
+ }
+ // Common code for both modes
+ if ($can_create_request) {
+ $now = dol_now();
+ if (is_numeric($amount) && $amount != 0) {
+ $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande(';
+ if ($type == 'bank-transfer') {
+ $sql .= 'fk_facture_fourn, ';
+ } else {
+ $sql .= 'fk_facture, ';
+ }
+ $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, type, entity';
+ if (empty($bac->id)) {
+ $sql .= ')';
+ } else {
+ $sql .= ', fk_societe_rib)';
+ }
+ $sql .= " VALUES (".((int) $this->id);
+ $sql .= ", ".((float) price2num($amount));
+ $sql .= ", '".$this->db->idate($now)."'";
+ $sql .= ", ".((int) $fuser->id);
+ $sql .= ", '".$this->db->escape($bac->code_banque)."'";
+ $sql .= ", '".$this->db->escape($bac->code_guichet)."'";
+ $sql .= ", '".$this->db->escape($bac->number)."'";
+ $sql .= ", '".$this->db->escape($bac->cle_rib)."'";
+ $sql .= ", '".$this->db->escape($sourcetype)."'";
+ $sql .= ", 'ban'";
+ $sql .= ", ".((int) $conf->entity);
+ if (!empty($bac->id)) {
+ $sql .= ", '".$this->db->escape((string) $bac->id)."'";
+ }
+ $sql .= ")";
+ dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this).'::demandeprelevement Erreur');
+ $error++;
+ }
+ } else {
+ $this->error = 'WithdrawRequestErrorNilAmount';
+ dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
+ $error++;
+ }
+ if (!$error) {
+ // Force payment mode of invoice to withdraw
+ $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
+ if ($payment_mode_id > 0) {
+ $result = $this->setPaymentMethods($payment_mode_id);
+ }
+ }
+ if ($error) {
+ return -1;
+ }
+ return 1;
+ } else {
+ // Updated error message for when amount exceeds remaining or request already exists
+ if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) {
+ if ($remaining_for_request <= 0) {
+ $this->error = "AmountRequestedAlreadyReachesTotal";
+ } else {
+ $this->error = "AmountExceedsRemainingToRequest";
+ }
+ } else {
+ $this->error = "A request already exists";
+ }
+ return 0;
}
} else {
$this->error = "Status of invoice does not allow this";
diff --git a/htdocs/langs/en_US/withdrawals.lang b/htdocs/langs/en_US/withdrawals.lang
index 03d9e1dced8..2391a75d6dd 100644
--- a/htdocs/langs/en_US/withdrawals.lang
+++ b/htdocs/langs/en_US/withdrawals.lang
@@ -173,3 +173,5 @@ RefSalary=Salary
NoSalaryInvoiceToWithdraw=No salary waiting for a '%s'. Go on tab '%s' on salary card to make a request.
SalaryInvoiceWaitingWithdraw=Salaries waiting for payment by credit transfer
ErrorBankTransferNoPaymentRequestSelected=No payment request selected.
+AmountRequestedAlreadyReachesTotal=The total invoice amount has already been requested for payment
+AmountExceedsRemainingToRequest=The requested amount exceeds the remaining amount available for payment requests
diff --git a/htdocs/langs/fr_FR/withdrawals.lang b/htdocs/langs/fr_FR/withdrawals.lang
index 6c11ebd6aa7..8e1bcba9ff4 100644
--- a/htdocs/langs/fr_FR/withdrawals.lang
+++ b/htdocs/langs/fr_FR/withdrawals.lang
@@ -173,3 +173,5 @@ RefSalary=Salaire
NoSalaryInvoiceToWithdraw=Aucun salaire n'attend un '%s'. Allez sur l'onglet '%s' sur la fiche salaire pour faire une demande.
SalaryInvoiceWaitingWithdraw=Salaires en attente de paiement par virement bancaire
ErrorBankTransferNoPaymentRequestSelected=Aucune demande de paiement sélectionnée.
+AmountRequestedAlreadyReachesTotal=Le montant total de la facture a déjà été demandé
+AmountExceedsRemainingToRequest=Le montant demandé dépasse le montant restant disponible pour les demandes de paiement