dolibarr  16.0.5
paiement.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2003-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
4  * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
5  * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
6  * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
7  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com>
9  * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
10  * Copyright (C) 2015 Juanjo Menent <jmenent@2byte.es>
11  * Copyright (C) 2017 Alexandre Spangaro <aspangaro@open-dsi.fr>
12  * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
13  * Copyright (C) 2021 Charlene Benke <charlene@patas-monkey.com>
14  * Copyright (C) 2022 Udo Tamm <dev@dolibit.de>
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program. If not, see <https://www.gnu.org/licenses/>.
28  */
29 
36 require '../../main.inc.php';
37 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
43 
44 // Load translation files required by the page
45 $langs->loadLangs(array('companies', 'bills', 'banks', 'compta'));
46 
47 $action = GETPOST('action', 'alpha');
48 $confirm = GETPOST('confirm', 'alpha');
49 $optioncss = GETPOST('optioncss', 'alpha');
50 $cancel = GETPOST('cancel', 'alpha');
51 $backtopage = GETPOST('backtopage', 'alpha');
52 $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
53 
54 $facid = GETPOST('facid', 'int');
55 $socid = GETPOST('socid', 'int');
56 $accountid = GETPOST('accountid', 'int');
57 $day = GETPOST('day', 'int');
58 $month = GETPOST('month', 'int');
59 $year = GETPOST('year', 'int');
60 
61 $search_ref = GETPOST('search_ref', 'alpha');
62 $search_account = GETPOST('search_account', 'int');
63 $search_paymenttype = GETPOST('search_paymenttype');
64 $search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on "< x"
65 $search_company = GETPOST('search_company', 'alpha');
66 $search_payment_num = GETPOST('search_payment_num', 'alpha');
67 
68 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
69 $sortfield = GETPOST('sortfield', 'aZ09comma');
70 $sortorder = GETPOST('sortorder', 'aZ09comma');
71 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
72 if (empty($page) || $page == -1) {
73  $page = 0;
74 } // If $page is not defined, or '' or -1
75 $offset = $limit * $page;
76 $pageprev = $page - 1;
77 $pagenext = $page + 1;
78 if (!$sortorder) {
79  $sortorder = "DESC";
80 }
81 if (!$sortfield) {
82  $sortfield = "p.rowid";
83 }
84 
85 $amounts = array();
86 $amountsresttopay = array();
87 $addwarning = 0;
88 
89 $multicurrency_amounts = array();
90 $multicurrency_amountsresttopay = array();
91 
92 // Security check
93 if ($user->socid > 0) {
94  $socid = $user->socid;
95 }
96 
97 $object = new PaiementFourn($db);
98 
99 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
100 $hookmanager->initHooks(array('paymentsupplierlist'));
101 $extrafields = new ExtraFields($db);
102 
103 // fetch optionals attributes and labels
104 $extrafields->fetch_name_optionals_label($object->table_element);
105 
106 $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
107 
108 $arrayfields = array();
109 
110 
111 
112 /*
113  * Actions
114  */
115 
116 if ($cancel) {
117  if (!empty($backtopageforcancel)) {
118  header("Location: ".$backtopageforcancel);
119  exit;
120  } elseif (!empty($backtopage)) {
121  header("Location: ".$backtopage);
122  exit;
123  }
124  header("Location: ".DOL_URL_ROOT.'/fourn/facture/list.php');
125  exit;
126 }
127 
128 if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
129  $search_ref = "";
130  $search_account = "";
131  $search_amount = "";
132  $search_paymenttype = "";
133  $search_payment_num = "";
134  $search_company = "";
135  $day = '';
136  $year = '';
137  $month = '';
138  $search_array_options = array();
139 }
140 
141 $parameters = array('socid'=>$socid);
142 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
143 if ($reshook < 0) {
144  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
145 }
146 
147 if (empty($reshook)) {
148  if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) {
149  $error = 0;
150 
151  $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
152  $paiement_id = 0;
153  $totalpayment = 0;
154  $atleastonepaymentnotnull = 0;
155  $multicurrency_totalpayment = 0;
156 
157  // Generate payment array and check if there is payment higher than invoice and payment date before invoice date
158  $tmpinvoice = new FactureFournisseur($db);
159  foreach ($_POST as $key => $value) {
160  if (substr($key, 0, 7) == 'amount_') {
161  $cursorfacid = substr($key, 7);
162  $amounts[$cursorfacid] = price2num(GETPOST($key));
163  if (!empty($amounts[$cursorfacid])) {
164  $atleastonepaymentnotnull++;
165  if (is_numeric($amounts[$cursorfacid])) {
166  $totalpayment = $totalpayment + $amounts[$cursorfacid];
167  } else {
168  setEventMessages($langs->transnoentities("InputValueIsNotAnNumber", GETPOST($key)), null, 'warnings');
169  }
170  }
171  $result = $tmpinvoice->fetch($cursorfacid);
172  if ($result <= 0) {
173  dol_print_error($db);
174  }
175  $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement());
176  if ($amounts[$cursorfacid]) {
177  // Check amount
178  if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) {
179  $addwarning = 1;
180  $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier");
181  }
182  // Check date
183  if ($datepaye && ($datepaye < $tmpinvoice->date)) {
184  $langs->load("errors");
185  //$error++;
186  setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
187  }
188  }
189 
190  $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key));
191  } elseif (substr($key, 0, 21) == 'multicurrency_amount_') {
192  $cursorfacid = substr($key, 21);
193  $multicurrency_amounts[$cursorfacid] = (GETPOST($key) ? price2num(GETPOST($key)) : 0);
194  $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid];
195  if (!empty($multicurrency_amounts[$cursorfacid])) {
196  $atleastonepaymentnotnull++;
197  }
198  $result = $tmpinvoice->fetch($cursorfacid);
199  if ($result <= 0) {
200  dol_print_error($db);
201  }
202  $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1));
203  if ($multicurrency_amounts[$cursorfacid]) {
204  // Check amount
205  if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) {
206  $addwarning = 1;
207  $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier");
208  }
209  // Check date
210  if ($datepaye && ($datepaye < $tmpinvoice->date)) {
211  $langs->load("errors");
212  //$error++;
213  setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
214  }
215  }
216 
217  $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key, 'int'));
218  }
219  }
220 
221  // Check parameters
222  if (GETPOST('paiementid') <= 0) {
223  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors');
224  $error++;
225  }
226 
227  if (!empty($conf->banque->enabled)) {
228  // If bank module is on, account is required to enter a payment
229  if (GETPOST('accountid') <= 0) {
230  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors');
231  $error++;
232  }
233  }
234 
235  if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) {
236  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors');
237  $error++;
238  }
239 
240  if (empty($datepaye)) {
241  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors');
242  $error++;
243  }
244 
245  // Check if payments in both currency
246  if ($totalpayment > 0 && $multicurrency_totalpayment > 0) {
247  setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors');
248  $error++;
249  }
250  }
251 
252  /*
253  * Action add_paiement
254  */
255  if ($action == 'add_paiement') {
256  if ($error) {
257  $action = 'create';
258  }
259  // All the next of this action is displayed at the page's bottom.
260  }
261 
262 
263  /*
264  * Action confirm_paiement
265  */
266  if ($action == 'confirm_paiement' && $confirm == 'yes') {
267  $error = 0;
268 
269  $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
270 
271  $multicurrency_code = array();
272 
273  // Clean parameters amount if payment is for a credit note
274  foreach ($amounts as $key => $value) { // How payment is dispatched
275  $tmpinvoice = new FactureFournisseur($db);
276  $tmpinvoice->fetch($key);
277  if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
278  $newvalue = price2num($value, 'MT');
279  $amounts[$key] = - abs($newvalue);
280  }
281  $multicurrency_code[$key] = $tmpinvoice->multicurrency_code;
282  }
283 
284  foreach ($multicurrency_amounts as $key => $value) { // How payment is dispatched
285  $tmpinvoice = new FactureFournisseur($db);
286  $tmpinvoice->fetch($key);
287  if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
288  $newvalue = price2num($value, 'MT');
289  $multicurrency_amounts[$key] = - abs($newvalue);
290  }
291  $multicurrency_code[$key] = $tmpinvoice->multicurrency_code;
292  }
293 
294  //var_dump($amounts);
295  //var_dump($multicurrency_amounts);
296  //exit;
297 
298  if (!$error) {
299  $db->begin();
300 
301  $thirdparty = new Societe($db);
302  if ($socid > 0) {
303  $thirdparty->fetch($socid);
304  }
305 
306  // Creation of payment line
307  $paiement = new PaiementFourn($db);
308  $paiement->datepaye = $datepaye;
309  $paiement->amounts = $amounts; // Array of amounts
310  $paiement->multicurrency_amounts = $multicurrency_amounts;
311  $paiement->multicurrency_code = $multicurrency_code; // Array with all currency of payments dispatching
312  $paiement->paiementid = GETPOST('paiementid', 'int');
313  $paiement->num_payment = GETPOST('num_paiement', 'alphanohtml');
314  $paiement->note_private = GETPOST('comment', 'alpha');
315  $paiement->fk_account = GETPOST('accountid', 'int');
316 
317  if (!$error) {
318  // Create payment and update this->multicurrency_amounts if this->amounts filled or
319  // this->amounts if this->multicurrency_amounts filled.
320  // This also set ->amount and ->multicurrency_amount
321  $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty);
322  if ($paiement_id < 0) {
323  setEventMessages($paiement->error, $paiement->errors, 'errors');
324  $error++;
325  }
326  }
327 
328  if (!$error) {
329  $result = $paiement->addPaymentToBank($user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, GETPOST('chqemetteur'), GETPOST('chqbank'));
330  if ($result < 0) {
331  setEventMessages($paiement->error, $paiement->errors, 'errors');
332  $error++;
333  }
334  }
335 
336  if (!$error) {
337  $db->commit();
338 
339  // If payment dispatching on more than one invoice, we stay on summary page, otherwise go on invoice card
340  $invoiceid = 0;
341  foreach ($paiement->amounts as $key => $amount) {
342  $facid = $key;
343  if (is_numeric($amount) && $amount <> 0) {
344  if ($invoiceid != 0) {
345  $invoiceid = -1; // There is more than one invoice payed by this payment
346  } else {
347  $invoiceid = $facid;
348  }
349  }
350  }
351  if ($invoiceid > 0) {
352  $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid;
353  } else {
354  $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id;
355  }
356  header('Location: '.$loc);
357  exit;
358  } else {
359  $db->rollback();
360  }
361  }
362  }
363 }
364 
365 
366 /*
367  * View
368  */
369 
370 $form = new Form($db);
371 $formother = new FormOther($db);
372 
373 $supplierstatic = new Societe($db);
374 $invoicesupplierstatic = new FactureFournisseur($db);
375 
376 llxHeader('', $langs->trans('ListPayment'));
377 
378 if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') {
379  $object = new FactureFournisseur($db);
380  $result = $object->fetch($facid);
381 
382  $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
383  $dateinvoice = ($datefacture == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datefacture);
384 
385  $sql = 'SELECT s.nom as name, s.rowid as socid,';
386  $sql .= ' f.rowid, f.ref, f.ref_supplier, f.total_ttc as total, f.fk_mode_reglement, f.fk_account';
387  if (empty($user->rights->societe->client->voir) && !$socid) {
388  $sql .= ", sc.fk_soc, sc.fk_user ";
389  }
390  $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f';
391  if (empty($user->rights->societe->client->voir) && !$socid) {
392  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
393  }
394  $sql .= ' WHERE f.fk_soc = s.rowid';
395  $sql .= ' AND f.rowid = '.((int) $facid);
396  if (empty($user->rights->societe->client->voir) && !$socid) {
397  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
398  }
399  $resql = $db->query($sql);
400  if ($resql) {
401  $num = $db->num_rows($resql);
402  if ($num) {
403  $obj = $db->fetch_object($resql);
404  $total = $obj->total;
405 
406  print load_fiche_titre($langs->trans('DoPayment'));
407 
408  // Add realtime total information
409  if (!empty($conf->use_javascript_ajax)) {
410  print "\n".'<script type="text/javascript">';
411  print '$(document).ready(function () {
412 
413  function _elemToJson(selector)
414  {
415  var subJson = {};
416  $.map(selector.serializeArray(), function(n,i)
417  {
418  subJson[n["name"]] = n["value"];
419  });
420 
421  return subJson;
422  }
423  function callForResult(imgId)
424  {
425  console.log("callForResult Calculate total of payment");
426  var json = {};
427  var form = $("#payment_form");
428 
429  json["invoice_type"] = $("#invoice_type").val();
430  json["amountPayment"] = $("#amountpayment").attr("value");
431  json["amounts"] = _elemToJson(form.find("input.amount"));
432  json["remains"] = _elemToJson(form.find("input.remain"));
433  json["token"] = "'.currentToken().'";
434  if (imgId != null) {
435  json["imgClicked"] = imgId;
436  }
437 
438  $.post("'.DOL_URL_ROOT.'/compta/ajaxpayment.php", json, function(data)
439  {
440  json = $.parseJSON(data);
441 
442  form.data(json);
443 
444  for (var key in json)
445  {
446  if (key == "result") {
447  if (json["makeRed"]) {
448  $("#"+key).addClass("error");
449  } else {
450  $("#"+key).removeClass("error");
451  }
452  json[key]=json["label"]+" "+json[key];
453  $("#"+key).text(json[key]);
454  } else {console.log(key);
455  form.find("input[name*=\""+key+"\"]").each(function() {
456  $(this).attr("value", json[key]);
457  });
458  }
459  }
460  });
461  }
462  callForResult();
463  $("#payment_form").find("input.amount").change(function() {
464  callForResult();
465  });
466  $("#payment_form").find("input.amount").keyup(function() {
467  callForResult();
468  });
469  ';
470 
471  print ' });'."\n";
472 
473  //Add js for AutoFill
474  print ' $(document).ready(function () {';
475  print ' $(".AutoFillAmout").on(\'click touchstart\', function(){
476  $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
477  });';
478  print ' });'."\n";
479 
480  print ' </script>'."\n";
481  }
482 
483  print '<form id="payment_form" name="addpaiement" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
484  print '<input type="hidden" name="token" value="'.newToken().'">';
485  print '<input type="hidden" name="action" value="add_paiement">';
486  print '<input type="hidden" name="facid" value="'.$facid.'">';
487  print '<input type="hidden" name="ref_supplier" value="'.$obj->ref_supplier.'">';
488  print '<input type="hidden" name="socid" value="'.$obj->socid.'">';
489  print '<input type="hidden" name="type" id="invoice_type" value="'.$object->type.'">';
490  print '<input type="hidden" name="societe" value="'.$obj->name.'">';
491 
492  print dol_get_fiche_head(null);
493 
494  print '<table class="border centpercent">';
495 
496  print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans('Company').'</td><td>';
497  $supplierstatic->id = $obj->socid;
498  $supplierstatic->name = $obj->name;
499  print $supplierstatic->getNomUrl(1, 'supplier');
500  print '</td></tr>';
501  print '<tr><td class="fieldrequired">'.$langs->trans('Date').'</td><td>';
502  print $form->selectDate($dateinvoice, '', '', '', 0, "addpaiement", 1, 1, 0, '', '', $object->date);
503  print '</td></tr>';
504  print '<tr><td class="fieldrequired">'.$langs->trans('PaymentMode').'</td><td>';
505  $form->select_types_paiements(!GETPOST('paiementid') ? $obj->fk_mode_reglement : GETPOST('paiementid'), 'paiementid');
506  print '</td>';
507  if (!empty($conf->banque->enabled)) {
508  print '<tr><td class="fieldrequired">'.$langs->trans('Account').'</td><td>';
509  print img_picto('', 'bank_account', 'class="pictofixedwidth"');
510  print $form->select_comptes(empty($accountid) ? $obj->fk_account : $accountid, 'accountid', 0, '', 2, '', 0, 'widthcentpercentminusx maxwidth500', 1);
511  print '</td></tr>';
512  } else {
513  print '<tr><td>&nbsp;</td></tr>';
514  }
515  print '<tr><td>'.$langs->trans('Numero').'</td><td><input name="num_paiement" type="text" value="'.(!GETPOST('num_paiement') ? '' : GETPOST('num_paiement')).'"></td></tr>';
516  print '<tr><td>'.$langs->trans('Comments').'</td>';
517  print '<td class="tdtop">';
518  print '<textarea name="comment" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.(!GETPOST('comment') ? '' : GETPOST('comment')).'</textarea></td></tr>';
519  print '</table>';
520  print dol_get_fiche_end();
521 
522 
523  $parameters = array('facid'=>$facid, 'ref'=>$ref, 'objcanvas'=>$objcanvas);
524  $reshook = $hookmanager->executeHooks('paymentsupplierinvoices', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
525  $error = $hookmanager->error; $errors = $hookmanager->errors;
526  if (empty($reshook)) {
527  /*
528  * All unpaid supplier invoices
529  */
530  $sql = 'SELECT f.rowid as facid, f.ref, f.ref_supplier, f.type, f.total_ht, f.total_ttc,';
531  $sql .= ' f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc,';
532  $sql .= ' f.datef as df, f.date_lim_reglement as dlr,';
533  $sql .= ' SUM(pf.amount) as am, SUM(pf.multicurrency_amount) as multicurrency_am';
534  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as f';
535  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid';
536  $sql .= " WHERE f.entity = ".((int) $conf->entity);
537  $sql .= ' AND f.fk_soc = '.((int) $object->socid);
538  $sql .= ' AND f.paye = 0';
539  $sql .= ' AND f.fk_statut = 1'; // Status=0 => unvalidated, Status=2 => canceled
540  if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) {
541  $sql .= ' AND f.type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation
542  } else {
543  $sql .= ' AND f.type = 2'; // If paying back a credit note, we show all credit notes
544  }
545  // Group by because we have a total
546  $sql .= ' GROUP BY f.datef, f.ref, f.ref_supplier, f.rowid, f.type, f.total_ht, f.total_ttc,';
547  $sql .= ' f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc,';
548  $sql .= ' f.datef, f.date_lim_reglement';
549  // Sort invoices by date and serial number: the older one comes first
550  $sql .= ' ORDER BY f.datef ASC, f.ref ASC';
551 
552  $resql = $db->query($sql);
553  if ($resql) {
554  $num = $db->num_rows($resql);
555  if ($num > 0) {
556  $i = 0;
557  print '<br>';
558 
559  if (!empty($conf->use_javascript_ajax)) {
560  //Add js for AutoFill
561  print "\n".'<script type="text/javascript">';
562  print ' $(document).ready(function () {';
563  print ' $(".AutoFillAmout").on(\'click touchstart\', function(){
564  $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value"));
565  });';
566  print ' });'."\n";
567  print ' </script>'."\n";
568  }
569 
570  print '<div class="div-table-responsive-no-min">';
571  print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
572 
573  print '<tr class="liste_titre">';
574  print '<td>'.$langs->trans('Invoice').'</td>';
575  print '<td>'.$langs->trans('RefSupplier').'</td>';
576  print '<td class="center">'.$langs->trans('Date').'</td>';
577  print '<td class="center">'.$langs->trans('DateMaxPayment').'</td>';
578  if (!empty($conf->multicurrency->enabled)) {
579  print '<td>'.$langs->trans('Currency').'</td>';
580  print '<td class="right">'.$langs->trans('MulticurrencyAmountTTC').'</td>';
581  print '<td class="right">'.$langs->trans('MulticurrencyAlreadyPaid').'</td>';
582  print '<td class="right">'.$langs->trans('MulticurrencyRemainderToPay').'</td>';
583  print '<td class="center">'.$langs->trans('MulticurrencyPaymentAmount').'</td>';
584  }
585  print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
586  print '<td class="right">'.$langs->trans('AlreadyPaid').'</td>';
587  print '<td class="right">'.$langs->trans('RemainderToPay').'</td>';
588  print '<td class="center">'.$langs->trans('PaymentAmount').'</td>';
589  print '</tr>';
590 
591  $total = 0;
592  $total_ttc = 0;
593  $totalrecu = 0;
594  while ($i < $num) {
595  $objp = $db->fetch_object($resql);
596 
597  $sign = 1;
598  if ($objp->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
599  $sign = -1;
600  }
601 
602  $invoice = new FactureFournisseur($db);
603  $invoice->fetch($objp->facid);
604 
605  $invoicesupplierstatic->ref = $objp->ref;
606  $invoicesupplierstatic->id = $objp->facid;
607 
608  $paiement = $invoice->getSommePaiement();
609  $creditnotes = $invoice->getSumCreditNotesUsed();
610  $deposits = $invoice->getSumDepositsUsed();
611  $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
612  $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
613 
614  // Multicurrency Price
615  if (!empty($conf->multicurrency->enabled)) {
616  $multicurrency_payment = $invoice->getSommePaiement(1);
617  $multicurrency_creditnotes = $invoice->getSumCreditNotesUsed(1);
618  $multicurrency_deposits = $invoice->getSumDepositsUsed(1);
619  $multicurrency_alreadypayed = price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits, 'MT');
620  $multicurrency_remaintopay = price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits, 'MT');
621  }
622 
623  print '<tr class="oddeven'.(($invoice->id == $facid) ? ' highlight' : '').'">';
624 
625  // Ref
626  print '<td class="nowraponall">';
627  print $invoicesupplierstatic->getNomUrl(1);
628  print '</td>';
629 
630  // Ref supplier
631  print '<td>'.$objp->ref_supplier.'</td>';
632 
633  // Date
634  if ($objp->df > 0) {
635  print '<td class="center nowraponall">';
636  print dol_print_date($db->jdate($objp->df), 'day').'</td>';
637  } else {
638  print '<td class="center"><b>!!!</b></td>';
639  }
640 
641  // Date Max Payment
642  if ($objp->dlr > 0) {
643  print '<td class="center nowraponall">';
644  print dol_print_date($db->jdate($objp->dlr), 'day');
645 
646  if ($invoice->hasDelay()) {
647  print img_warning($langs->trans('Late'));
648  }
649 
650  print '</td>';
651  } else {
652  print '<td class="center"><b>--</b></td>';
653  }
654 
655  // Multicurrency
656  if (!empty($conf->multicurrency->enabled)) {
657  // Currency
658  print '<td class="center">'.$objp->multicurrency_code."</td>\n";
659 
660  print '<td class="right">';
661  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) {
662  print price($objp->multicurrency_total_ttc);
663  }
664  print '</td>';
665 
666  print '<td class="right">';
667  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) {
668  print price($sign * $multicurrency_payment);
669  if ($multicurrency_creditnotes) {
670  print '+'.price($multicurrency_creditnotes);
671  }
672  if ($multicurrency_deposits) {
673  print '+'.price($multicurrency_deposits);
674  }
675  }
676  print '</td>';
677 
678  print '<td class="right">';
679  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) {
680  print price($sign * $multicurrency_remaintopay);
681  }
682  print '</td>';
683 
684  print '<td class="right">';
685  // Add remind multicurrency amount
686  $namef = 'multicurrency_amount_'.$objp->facid;
687  $nameRemain = 'multicurrency_remain_'.$objp->facid;
688  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) {
689  if ($action != 'add_paiement') {
690  if (!empty($conf->use_javascript_ajax)) {
691  print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'");
692  }
693  print '<input type=hidden class="multicurrency_remain" name="'.$nameRemain.'" value="'.$multicurrency_remaintopay.'">';
694  print '<input type="text" size="8" class="multicurrency_amount" name="'.$namef.'" value="'.GETPOST($namef).'">';
695  } else {
696  print '<input type="text" size="8" name="'.$namef.'_disabled" value="'.GETPOST($namef).'" disabled>';
697  print '<input type="hidden" name="'.$namef.'" value="'.GETPOST($namef).'">';
698  }
699  }
700  print "</td>";
701  }
702 
703  print '<td class="right">'.price($sign * $objp->total_ttc).'</td>';
704 
705  print '<td class="right">'.price($sign * $objp->am);
706  if ($creditnotes) {
707  print '+'.price($creditnotes);
708  }
709  if ($deposits) {
710  print '+'.price($deposits);
711  }
712  print '</td>';
713 
714  print '<td class="right">';
715  print price($sign * $remaintopay);
716  if (!empty($conf->paymentbybanktransfer->enabled)) {
717  $numdirectdebitopen = 0;
718  $totaldirectdebit = 0;
719  $sql = "SELECT COUNT(pfd.rowid) as nb, SUM(pfd.amount) as amount";
720  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
721  $sql .= " WHERE fk_facture_fourn = ".((int) $objp->facid);
722  $sql .= " AND pfd.traite = 0";
723  $sql .= " AND pfd.ext_payment_id IS NULL";
724 
725  $result_sql = $db->query($sql);
726  if ($result_sql) {
727  $obj = $db->fetch_object($result_sql);
728  $numdirectdebitopen = $obj->nb;
729  $totaldirectdebit = $obj->amount;
730  } else {
731  dol_print_error($db);
732  }
733  if ($numdirectdebitopen) {
734  $langs->load("withdrawals");
735  print img_warning($langs->trans("WarningSomeCreditTransferAlreadyExists", $numdirectdebitopen, price(price2num($totaldirectdebit, 'MT'), 0, $langs, 1, -1, -1, $conf->currency)), '', 'classfortooltip');
736  }
737  }
738  print '</td>';
739 
740  // Amount
741  print '<td class="center nowraponall">';
742 
743  $namef = 'amount_'.$objp->facid;
744  $nameRemain = 'remain_'.$objp->facid;
745 
746  if ($action != 'add_paiement') {
747  if (!empty($conf->use_javascript_ajax)) {
748  print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'");
749  }
750  print '<input type="hidden" class="remain" name="'.$nameRemain.'" value="'.$remaintopay.'">';
751  print '<input type="text" size="8" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">'; // class is requied to be used by javascript callForResult();
752  } else {
753  print '<input type="text" size="8" name="'.$namef.'_disabled" value="'.dol_escape_htmltag(GETPOST($namef)).'" disabled>';
754  print '<input type="hidden" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">'; // class is requied to be used by javascript callForResult();
755  }
756  print "</td>";
757 
758  print "</tr>\n";
759  $total += $objp->total_ht;
760  $total_ttc += $objp->total_ttc;
761  $totalrecu += $objp->am;
762  $totalrecucreditnote += $creditnotes;
763  $totalrecudeposits += $deposits;
764  $i++;
765  }
766  if ($i > 1) {
767  // Print total
768  print '<tr class="liste_total">';
769  print '<td colspan="4" class="left">'.$langs->trans('TotalTTC').':</td>';
770  if (!empty($conf->multicurrency->enabled)) {
771  print '<td>&nbsp;</td>';
772  print '<td>&nbsp;</td>';
773  print '<td>&nbsp;</td>';
774  print '<td>&nbsp;</td>';
775  print '<td class="right" id="multicurrency_result" style="font-weight: bold;"></td>';
776  }
777  print '<td class="right"><b>'.price($sign * $total_ttc).'</b></td>';
778  print '<td class="right"><b>'.price($sign * $totalrecu);
779  if ($totalrecucreditnote) {
780  print '+'.price($totalrecucreditnote);
781  }
782  if ($totalrecudeposits) {
783  print '+'.price($totalrecudeposits);
784  }
785  print '</b></td>';
786  print '<td class="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'</b></td>';
787  print '<td class="center" id="result" style="font-weight: bold;"></td>'; // Autofilled
788  print "</tr>\n";
789  }
790  print "</table>\n";
791 
792  print "</div>";
793  }
794  $db->free($resql);
795  } else {
796  dol_print_error($db);
797  }
798  }
799 
800  // Save + Cancel Buttons
801  if ($action != 'add_paiement') {
802  print '<br><div class="center">';
803  print '<input type="checkbox" checked id="closepaidinvoices" name="closepaidinvoices"> <label for="closepaidinvoices">'.$langs->trans("ClosePaidInvoicesAutomatically").'</label><br>';
804  print '<input type="submit" class="button" value="'.$langs->trans('ToMakePayment').'">';
805  print ' &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
806  print '</div>';
807  }
808 
809  // Form to confirm payment
810  if ($action == 'add_paiement') {
811  $preselectedchoice = $addwarning ? 'no' : 'yes';
812 
813  print '<br>';
814  if (!empty($totalpayment)) {
815  $text = $langs->trans('ConfirmSupplierPayment', price($totalpayment), $langs->trans("Currency".$conf->currency));
816  }
817  if (!empty($multicurrency_totalpayment)) {
818  $text .= '<br>'.$langs->trans('ConfirmSupplierPayment', price($multicurrency_totalpayment), $langs->trans("paymentInInvoiceCurrency"));
819  }
820  if (GETPOST('closepaidinvoices')) {
821  $text .= '<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
822  print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">';
823  }
824  print $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$facture->id.'&socid='.$facture->socid.'&type='.$facture->type, $langs->trans('PayedSuppliersPayments'), $text, 'confirm_paiement', $formquestion, $preselectedchoice);
825  }
826 
827  print '</form>';
828  }
829  } else {
830  dol_print_error($db);
831  }
832 }
833 
834 // End of page
835 llxFooter();
836 $db->close();
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1468
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:73
FactureFournisseur\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: fournisseur.facture.class.php:338
load_fiche_titre
load_fiche_titre($titre, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
Definition: functions.lib.php:5204
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
FactureFournisseur
Class to manage suppliers invoices.
Definition: fournisseur.facture.class.php:53
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
img_warning
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
Definition: functions.lib.php:4521
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
FormOther
Classe permettant la generation de composants html autre Only common components are here.
Definition: html.formother.class.php:39
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
dol_get_fiche_head
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tabs of a record.
Definition: functions.lib.php:1822
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2018
PaiementFourn
Class to manage payments for supplier invoices.
Definition: paiementfourn.class.php:37
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:386
ExtraFields
Class to manage standard extra fields.
Definition: extrafields.class.php:39
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
price
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
Definition: functions.lib.php:5541
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
dol_mktime
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Definition: functions.lib.php:2757
llxHeader
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOCSRFCHECK')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:59