dolibarr  13.0.2
paiement.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2001-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
5  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
6  * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
7  * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
8  * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9  * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com>
10  * Copyright (C) 2015 Juanjo Menent <jmenent@2byte.es>
11  * Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program. If not, see <https://www.gnu.org/licenses/>.
25  */
26 
33 require '../main.inc.php';
34 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
37 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
38 
39 // Load translation files required by the page
40 $langs->loadLangs(array('companies', 'bills', 'banks', 'multicurrency'));
41 
42 $action = GETPOST('action', 'alpha');
43 $confirm = GETPOST('confirm', 'alpha');
44 
45 $facid = GETPOST('facid', 'int');
46 $accountid = GETPOST('accountid', 'int');
47 $paymentnum = GETPOST('num_paiement', 'alpha');
48 $socid = GETPOST('socid', 'int');
49 
50 $sortfield = GETPOST('sortfield', 'aZ09comma');
51 $sortorder = GETPOST('sortorder', 'alpha');
52 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
53 
54 $amounts = array();
55 $amountsresttopay = array();
56 $addwarning = 0;
57 
58 $multicurrency_amounts = array();
59 $multicurrency_amountsresttopay = array();
60 
61 // Security check
62 if ($user->socid > 0)
63 {
64  $socid = $user->socid;
65 }
66 
67 $object = new Facture($db);
68 
69 // Load object
70 if ($facid > 0)
71 {
72  $ret = $object->fetch($facid);
73 }
74 
75 // Initialize technical object to manage hooks of paiements. Note that conf->hooks_modules contains array array
76 $hookmanager->initHooks(array('paiementcard', 'globalcard'));
77 
78 $formquestion = array();
79 
80 
81 /*
82  * Actions
83  */
84 
85 $parameters = array('socid'=>$socid);
86 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
87 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
88 
89 if (empty($reshook))
90 {
91  if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes'))
92  {
93  $error = 0;
94 
95  $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
96  $paiement_id = 0;
97  $totalpayment = 0;
98  $multicurrency_totalpayment = 0;
99  $atleastonepaymentnotnull = 0;
100  $formquestion = array();
101  $i = 0;
102 
103  // Generate payment array and check if there is payment higher than invoice and payment date before invoice date
104  $tmpinvoice = new Facture($db);
105  foreach ($_POST as $key => $value)
106  {
107  if (substr($key, 0, 7) == 'amount_' && GETPOST($key) != '')
108  {
109  $cursorfacid = substr($key, 7);
110  $amounts[$cursorfacid] = price2num(GETPOST($key));
111  $totalpayment = $totalpayment + $amounts[$cursorfacid];
112  if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++;
113  $result = $tmpinvoice->fetch($cursorfacid);
114  if ($result <= 0) dol_print_error($db);
115  $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement());
116  if ($amounts[$cursorfacid])
117  {
118  // Check amount
119  if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid])))
120  {
121  $addwarning = 1;
122  $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
123  }
124  // Check date
125  if ($datepaye && ($datepaye < $tmpinvoice->date))
126  {
127  $langs->load("errors");
128  //$error++;
129  setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
130  }
131  }
132 
133  $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]);
134  } elseif (substr($key, 0, 21) == 'multicurrency_amount_')
135  {
136  $cursorfacid = substr($key, 21);
137  $multicurrency_amounts[$cursorfacid] = price2num(GETPOST($key));
138  $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid];
139  if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++;
140  $result = $tmpinvoice->fetch($cursorfacid);
141  if ($result <= 0) dol_print_error($db);
142  $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1));
143  if ($multicurrency_amounts[$cursorfacid])
144  {
145  // Check amount
146  if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid])))
147  {
148  $addwarning = 1;
149  $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
150  }
151  // Check date
152  if ($datepaye && ($datepaye < $tmpinvoice->date))
153  {
154  $langs->load("errors");
155  //$error++;
156  setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
157  }
158  }
159 
160  $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key, 'int'));
161  }
162  }
163 
164  // Check parameters
165  if (!GETPOST('paiementcode'))
166  {
167  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors');
168  $error++;
169  }
170 
171  if (!empty($conf->banque->enabled))
172  {
173  // If bank module is on, account is required to enter a payment
174  if (GETPOST('accountid') <= 0)
175  {
176  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors');
177  $error++;
178  }
179  }
180 
181  if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull))
182  {
183  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors');
184  $error++;
185  }
186 
187  if (empty($datepaye))
188  {
189  setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors');
190  $error++;
191  }
192 
193  // Check if payments in both currency
194  if ($totalpayment > 0 && $multicurrency_totalpayment > 0)
195  {
196  setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors');
197  $error++;
198  }
199  }
200 
201  /*
202  * Action add_paiement
203  */
204  if ($action == 'add_paiement')
205  {
206  if ($error)
207  {
208  $action = 'create';
209  }
210  // The next of this action is displayed at the page's bottom.
211  }
212 
213  /*
214  * Action confirm_paiement
215  */
216  if ($action == 'confirm_paiement' && $confirm == 'yes')
217  {
218  $error = 0;
219 
220  $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
221 
222  $db->begin();
223 
224  $thirdparty = new Societe($db);
225  if ($socid > 0) $thirdparty->fetch($socid);
226 
227  // Clean parameters amount if payment is for a credit note
228  foreach ($amounts as $key => $value) // How payment is dispatched
229  {
230  $tmpinvoice = new Facture($db);
231  $tmpinvoice->fetch($key);
232  if ($tmpinvoice->type == Facture::TYPE_CREDIT_NOTE)
233  {
234  $newvalue = price2num($value, 'MT');
235  $amounts[$key] = - abs($newvalue);
236  }
237  }
238 
239  foreach ($multicurrency_amounts as $key => $value) // How payment is dispatched
240  {
241  $tmpinvoice = new Facture($db);
242  $tmpinvoice->fetch($key);
243  if ($tmpinvoice->type == Facture::TYPE_CREDIT_NOTE)
244  {
245  $newvalue = price2num($value, 'MT');
246  $multicurrency_amounts[$key] = - abs($newvalue);
247  }
248  }
249 
250  if (!empty($conf->banque->enabled))
251  {
252  // If the bank module is active, an account is required to input a payment
253  if (GETPOST('accountid', 'int') <= 0)
254  {
255  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors');
256  $error++;
257  }
258  }
259 
260  // Creation of payment line
261  $paiement = new Paiement($db);
262  $paiement->datepaye = $datepaye;
263  $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
264  $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
265  $paiement->paiementid = dol_getIdFromCode($db, GETPOST('paiementcode'), 'c_paiement', 'code', 'id', 1);
266  $paiement->num_payment = GETPOST('num_paiement', 'alpha');
267  $paiement->note_private = GETPOST('comment', 'alpha');
268 
269  if (!$error)
270  {
271  // Create payment and update this->multicurrency_amounts if this->amounts filled or
272  // this->amounts if this->multicurrency_amounts filled.
273  $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty); // This include closing invoices and regenerating documents
274  if ($paiement_id < 0)
275  {
276  setEventMessages($paiement->error, $paiement->errors, 'errors');
277  $error++;
278  }
279  }
280 
281  if (!$error)
282  {
283  $label = '(CustomerInvoicePayment)';
284  if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
285  $result = $paiement->addPaymentToBank($user, 'payment', $label, GETPOST('accountid'), GETPOST('chqemetteur'), GETPOST('chqbank'));
286  if ($result < 0)
287  {
288  setEventMessages($paiement->error, $paiement->errors, 'errors');
289  $error++;
290  }
291  }
292 
293  if (!$error)
294  {
295  $db->commit();
296 
297  // If payment dispatching on more than one invoice, we stay on summary page, otherwise jump on invoice card
298  $invoiceid = 0;
299  foreach ($paiement->amounts as $key => $amount)
300  {
301  $facid = $key;
302  if (is_numeric($amount) && $amount <> 0)
303  {
304  if ($invoiceid != 0) $invoiceid = -1; // There is more than one invoice payed by this payment
305  else $invoiceid = $facid;
306  }
307  }
308  if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$invoiceid;
309  else $loc = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$paiement_id;
310  header('Location: '.$loc);
311  exit;
312  } else {
313  $db->rollback();
314  }
315  }
316 }
317 
318 
319 /*
320  * View
321  */
322 
323 $form = new Form($db);
324 
325 
326 llxHeader('', $langs->trans("Payment"));
327 
328 
329 
330 if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement')
331 {
332  $facture = new Facture($db);
333  $result = $facture->fetch($facid);
334 
335  if ($result >= 0)
336  {
337  $facture->fetch_thirdparty();
338 
339  $title = '';
340  if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title .= $langs->trans("EnterPaymentReceivedFromCustomer");
341  if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title .= $langs->trans("EnterPaymentDueToCustomer");
342  print load_fiche_titre($title);
343 
344  // Initialize data for confirmation (this is used because data can be change during confirmation)
345  if ($action == 'add_paiement')
346  {
347  $i = 0;
348 
349  $formquestion[$i++] = array('type' => 'hidden', 'name' => 'facid', 'value' => $facture->id);
350  $formquestion[$i++] = array('type' => 'hidden', 'name' => 'socid', 'value' => $facture->socid);
351  $formquestion[$i++] = array('type' => 'hidden', 'name' => 'type', 'value' => $facture->type);
352  }
353 
354  // Invoice with Paypal transaction
355  // TODO add hook here
356  if (!empty($conf->paypalplus->enabled) && $conf->global->PAYPAL_ENABLE_TRANSACTION_MANAGEMENT && !empty($facture->ref_ext))
357  {
358  if (!empty($conf->global->PAYPAL_BANK_ACCOUNT)) $accountid = $conf->global->PAYPAL_BANK_ACCOUNT;
359  $paymentnum = $facture->ref_ext;
360  }
361 
362  // Add realtime total information
363  if (!empty($conf->use_javascript_ajax))
364  {
365  print "\n".'<script type="text/javascript" language="javascript">';
366  print '$(document).ready(function () {
367  setPaiementCode();
368 
369  $("#selectpaiementcode").change(function() {
370  setPaiementCode();
371  });
372 
373  function setPaiementCode()
374  {
375  var code = $("#selectpaiementcode option:selected").val();
376 
377  if (code == \'CHQ\' || code == \'VIR\')
378  {
379  if (code == \'CHQ\')
380  {
381  $(\'.fieldrequireddyn\').addClass(\'fieldrequired\');
382  }
383  if ($(\'#fieldchqemetteur\').val() == \'\')
384  {
385  var emetteur = ('.$facture->type.' == '.Facture::TYPE_CREDIT_NOTE.') ? \''.dol_escape_js(dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM)).'\' : jQuery(\'#thirdpartylabel\').val();
386  $(\'#fieldchqemetteur\').val(emetteur);
387  }
388  }
389  else
390  {
391  $(\'.fieldrequireddyn\').removeClass(\'fieldrequired\');
392  $(\'#fieldchqemetteur\').val(\'\');
393  }
394  }
395 
396  function _elemToJson(selector)
397  {
398  var subJson = {};
399  $.map(selector.serializeArray(), function(n,i)
400  {
401  subJson[n["name"]] = n["value"];
402  });
403 
404  return subJson;
405  }
406  function callForResult(imgId)
407  {
408  var json = {};
409  var form = $("#payment_form");
410 
411  json["invoice_type"] = $("#invoice_type").val();
412  json["amountPayment"] = $("#amountpayment").attr("value");
413  json["amounts"] = _elemToJson(form.find("input.amount"));
414  json["remains"] = _elemToJson(form.find("input.remain"));
415 
416  if (imgId != null) {
417  json["imgClicked"] = imgId;
418  }
419 
420  $.post("'.DOL_URL_ROOT.'/compta/ajaxpayment.php", json, function(data)
421  {
422  json = $.parseJSON(data);
423 
424  form.data(json);
425 
426  for (var key in json)
427  {
428  if (key == "result") {
429  if (json["makeRed"]) {
430  $("#"+key).addClass("error");
431  } else {
432  $("#"+key).removeClass("error");
433  }
434  json[key]=json["label"]+" "+json[key];
435  $("#"+key).text(json[key]);
436  } else {console.log(key);
437  form.find("input[name*=\""+key+"\"]").each(function() {
438  $(this).attr("value", json[key]);
439  });
440  }
441  }
442  });
443  }
444  $("#payment_form").find("input.amount").change(function() {
445  callForResult();
446  });
447  $("#payment_form").find("input.amount").keyup(function() {
448  callForResult();
449  });
450  ';
451 
452  print ' });'."\n";
453 
454  //Add js for AutoFill
455  print ' $(document).ready(function () {';
456  print ' $(".AutoFillAmout").on(\'click touchstart\', function(){
457  $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
458  });';
459  print ' });'."\n";
460 
461  print ' </script>'."\n";
462  }
463 
464  print '<form id="payment_form" name="add_paiement" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
465  print '<input type="hidden" name="token" value="'.newToken().'">';
466  print '<input type="hidden" name="action" value="add_paiement">';
467  print '<input type="hidden" name="facid" value="'.$facture->id.'">';
468  print '<input type="hidden" name="socid" value="'.$facture->socid.'">';
469  print '<input type="hidden" name="type" id="invoice_type" value="'.$facture->type.'">';
470  print '<input type="hidden" name="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($facture->thirdparty->name).'">';
471 
473 
474  print '<table class="border centpercent">';
475 
476  // Third party
477  print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans('Company').'</span></td><td>'.$facture->thirdparty->getNomUrl(4)."</td></tr>\n";
478 
479  // Date payment
480  print '<tr><td><span class="fieldrequired">'.$langs->trans('Date').'</span></td><td>';
481  $datepayment = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
482  $datepayment = ($datepayment == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datepayment);
483  print $form->selectDate($datepayment, '', '', '', 0, "add_paiement", 1, 1, 0, '', '', $facture->date);
484  print '</td></tr>';
485 
486  // Payment mode
487  print '<tr><td><span class="fieldrequired">'.$langs->trans('PaymentMode').'</span></td><td>';
488  $form->select_types_paiements((GETPOST('paiementcode') ?GETPOST('paiementcode') : $facture->mode_reglement_code), 'paiementcode', '', 2);
489  print "</td>\n";
490  print '</tr>';
491 
492  // Bank account
493  print '<tr>';
494  if (!empty($conf->banque->enabled))
495  {
496  if ($facture->type != 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToCredit').'</span></td>';
497  if ($facture->type == 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToDebit').'</span></td>';
498  print '<td>';
499  $form->select_comptes($accountid, 'accountid', 0, '', 2);
500  print '</td>';
501  } else {
502  print '<td>&nbsp;</td>';
503  }
504  print "</tr>\n";
505 
506  // Bank check number
507  print '<tr><td>'.$langs->trans('Numero');
508  print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
509  print '</td>';
510  print '<td><input name="num_paiement" type="text" class="maxwidth200" value="'.$paymentnum.'"></td></tr>';
511 
512  // Check transmitter
513  print '<tr><td class="'.(GETPOST('paiementcode') == 'CHQ' ? 'fieldrequired ' : '').'fieldrequireddyn">'.$langs->trans('CheckTransmitter');
514  print ' <em>('.$langs->trans("ChequeMaker").')</em>';
515  print '</td>';
516  print '<td><input id="fieldchqemetteur" class="maxwidth300" name="chqemetteur" type="text" value="'.GETPOST('chqemetteur', 'alphanohtml').'"></td></tr>';
517 
518  // Bank name
519  print '<tr><td>'.$langs->trans('Bank');
520  print ' <em>('.$langs->trans("ChequeBank").')</em>';
521  print '</td>';
522  print '<td><input name="chqbank" class="maxwidth300" type="text" value="'.GETPOST('chqbank', 'alphanohtml').'"></td></tr>';
523 
524  // Comments
525  print '<tr><td>'.$langs->trans('Comments').'</td>';
526  print '<td class="tdtop">';
527  print '<textarea name="comment" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.GETPOST('comment', 'restricthtml').'</textarea></td></tr>';
528 
529  print '</table>';
530 
532 
533 
534  /*
535  * List of unpaid invoices
536  */
537 
538  $sql = 'SELECT f.rowid as facid, f.ref, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type,';
539  $sql .= ' f.datef as df, f.fk_soc as socid, f.date_lim_reglement as dlr';
540  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
541  $sql .= ' WHERE f.entity IN ('.getEntity('facture').')';
542  $sql .= ' AND (f.fk_soc = '.$facture->socid;
543  // Can pay invoices of all child of parent company
544  if (!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) {
545  $sql .= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')';
546  }
547  // Can pay invoices of all child of myself
548  if (!empty($conf->global->FACTURE_PAYMENTS_ON_SUBSIDIARY_COMPANIES)) {
549  $sql .= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->id.')';
550  }
551  $sql .= ') AND f.paye = 0';
552  $sql .= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled
553  if ($facture->type != Facture::TYPE_CREDIT_NOTE)
554  {
555  $sql .= ' AND type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation
556  } else {
557  $sql .= ' AND type = 2'; // If paying back a credit note, we show all credit notes
558  }
559  // Sort invoices by date and serial number: the older one comes first
560  $sql .= ' ORDER BY f.datef ASC, f.ref ASC';
561 
562  $resql = $db->query($sql);
563  if ($resql)
564  {
565  $num = $db->num_rows($resql);
566  if ($num > 0)
567  {
568  $arraytitle = $langs->trans('Invoice');
569  if ($facture->type == 2) $arraytitle = $langs->trans("CreditNotes");
570  $alreadypayedlabel = $langs->trans('Received');
571  $multicurrencyalreadypayedlabel = $langs->trans('MulticurrencyReceived');
572  if ($facture->type == 2) { $alreadypayedlabel = $langs->trans("PaidBack"); $multicurrencyalreadypayedlabel = $langs->trans("MulticurrencyPaidBack"); }
573  $remaindertopay = $langs->trans('RemainderToTake');
574  $multicurrencyremaindertopay = $langs->trans('MulticurrencyRemainderToTake');
575  if ($facture->type == 2) { $remaindertopay = $langs->trans("RemainderToPayBack"); $multicurrencyremaindertopay = $langs->trans("MulticurrencyRemainderToPayBack"); }
576 
577  $i = 0;
578  //print '<tr><td colspan="3">';
579  print '<br>';
580 
581  print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
582  print '<table class="noborder centpercent">';
583 
584  print '<tr class="liste_titre">';
585  print '<td>'.$arraytitle.'</td>';
586  print '<td class="center">'.$langs->trans('Date').'</td>';
587  print '<td class="center">'.$langs->trans('DateMaxPayment').'</td>';
588  if (!empty($conf->multicurrency->enabled)) {
589  print '<td>'.$langs->trans('Currency').'</td>';
590  print '<td class="right">'.$langs->trans('MulticurrencyAmountTTC').'</td>';
591  print '<td class="right">'.$multicurrencyalreadypayedlabel.'</td>';
592  print '<td class="right">'.$multicurrencyremaindertopay.'</td>';
593  print '<td class="right">'.$langs->trans('MulticurrencyPaymentAmount').'</td>';
594  }
595  print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
596  print '<td class="right">'.$alreadypayedlabel.'</td>';
597  print '<td class="right">'.$remaindertopay.'</td>';
598  print '<td class="right">'.$langs->trans('PaymentAmount').'</td>';
599 
600  $parameters = array();
601  $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $facture, $action); // Note that $action and $object may have been modified by hook
602 
603  print '<td align="right">&nbsp;</td>';
604  print "</tr>\n";
605 
606  $total = 0;
607  $totalrecu = 0;
608  $totalrecucreditnote = 0;
609  $totalrecudeposits = 0;
610 
611  while ($i < $num)
612  {
613  $objp = $db->fetch_object($resql);
614 
615  $sign = 1;
616  if ($facture->type == Facture::TYPE_CREDIT_NOTE) $sign = -1;
617 
618  $soc = new Societe($db);
619  $soc->fetch($objp->socid);
620 
621  $invoice = new Facture($db);
622  $invoice->fetch($objp->facid);
623  $paiement = $invoice->getSommePaiement();
624  $creditnotes = $invoice->getSumCreditNotesUsed();
625  $deposits = $invoice->getSumDepositsUsed();
626  $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
627  $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
628 
629  // Multicurrency Price
630  if (!empty($conf->multicurrency->enabled)) {
631  $multicurrency_payment = $invoice->getSommePaiement(1);
632  $multicurrency_creditnotes = $invoice->getSumCreditNotesUsed(1);
633  $multicurrency_deposits = $invoice->getSumDepositsUsed(1);
634  $multicurrency_alreadypayed = price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits, 'MT');
635  $multicurrency_remaintopay = price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits, 'MT');
636  }
637 
638 
639  print '<tr class="oddeven'.(($invoice->id == $facid) ? ' highlight' : '').'">';
640 
641  print '<td class="nowraponall">';
642  print $invoice->getNomUrl(1, '');
643  if ($objp->socid != $facture->thirdparty->id) print ' - '.$soc->getNomUrl(1).' ';
644  print "</td>\n";
645 
646  // Date
647  print '<td class="center">'.dol_print_date($db->jdate($objp->df), 'day')."</td>\n";
648 
649  // Due date
650  if ($objp->dlr > 0)
651  {
652  print '<td class="nowraponall center">';
653  print dol_print_date($db->jdate($objp->dlr), 'day');
654 
655  if ($invoice->hasDelay())
656  {
657  print img_warning($langs->trans('Late'));
658  }
659 
660  print '</td>';
661  } else {
662  print '<td align="center"></td>';
663  }
664 
665  // Currency
666  if (!empty($conf->multicurrency->enabled)) print '<td class="center">'.$objp->multicurrency_code."</td>\n";
667 
668  // Multicurrency Price
669  if (!empty($conf->multicurrency->enabled))
670  {
671  print '<td class="right">';
672  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $objp->multicurrency_total_ttc);
673  print '</td>';
674 
675  // Multicurrency Price
676  print '<td class="right">';
677  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency)
678  {
679  print price($sign * $multicurrency_payment);
680  if ($multicurrency_creditnotes) print '+'.price($multicurrency_creditnotes);
681  if ($multicurrency_deposits) print '+'.price($multicurrency_deposits);
682  }
683  print '</td>';
684 
685  // Multicurrency remain to pay
686  print '<td class="right">';
687  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $multicurrency_remaintopay);
688  print '</td>';
689 
690  print '<td class="right nowraponall">';
691 
692  // Add remind multicurrency amount
693  $namef = 'multicurrency_amount_'.$objp->facid;
694  $nameRemain = 'multicurrency_remain_'.$objp->facid;
695 
696  if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency)
697  {
698  if ($action != 'add_paiement')
699  {
700  if (!empty($conf->use_javascript_ajax))
701  print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'");
702  print '<input type="text" class="maxwidth75 multicurrency_amount" name="'.$namef.'" value="'.$_POST[$namef].'">';
703  print '<input type="hidden" class="multicurrency_remain" name="'.$nameRemain.'" value="'.$multicurrency_remaintopay.'">';
704  } else {
705  print '<input type="text" class="maxwidth75" name="'.$namef.'_disabled" value="'.$_POST[$namef].'" disabled>';
706  print '<input type="hidden" name="'.$namef.'" value="'.$_POST[$namef].'">';
707  }
708  }
709  print "</td>";
710  }
711 
712  // Price
713  print '<td class="right">'.price($sign * $objp->total_ttc).'</td>';
714 
715  // Received + already paid
716  print '<td class="right">'.price($sign * $paiement);
717  if ($creditnotes) print '<span class="opacitymedium">+'.price($creditnotes).'</span>';
718  if ($deposits) print '<span class="opacitymedium">+'.price($deposits).'</span>';
719  print '</td>';
720 
721  // Remain to take or to pay back
722  print '<td class="right">'.price($sign * $remaintopay).'</td>';
723  //$test= price(price2num($objp->total_ttc - $paiement - $creditnotes - $deposits));
724 
725  // Amount
726  print '<td class="right nowraponall">';
727 
728  // Add remind amount
729  $namef = 'amount_'.$objp->facid;
730  $nameRemain = 'remain_'.$objp->facid;
731 
732  if ($action != 'add_paiement')
733  {
734  if (!empty($conf->use_javascript_ajax))
735  print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'");
736  print '<input type="text" class="maxwidth75 amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">';
737  print '<input type="hidden" class="remain" name="'.$nameRemain.'" value="'.$remaintopay.'">';
738  } else {
739  print '<input type="text" class="maxwidth75" name="'.$namef.'_disabled" value="'.dol_escape_htmltag(GETPOST($namef)).'" disabled>';
740  print '<input type="hidden" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">';
741  }
742  print "</td>";
743 
744  $parameters = array();
745  $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook
746 
747  // Warning
748  print '<td align="center" width="16">';
749  //print "xx".$amounts[$invoice->id]."-".$amountsresttopay[$invoice->id]."<br>";
750  if ($amounts[$invoice->id] && (abs($amounts[$invoice->id]) > abs($amountsresttopay[$invoice->id]))
751  || $multicurrency_amounts[$invoice->id] && (abs($multicurrency_amounts[$invoice->id]) > abs($multicurrency_amountsresttopay[$invoice->id])))
752  {
753  print ' '.img_warning($langs->trans("PaymentHigherThanReminderToPay"));
754  }
755  print '</td>';
756 
757  print "</tr>\n";
758 
759  $total += $objp->total;
760  $total_ttc += $objp->total_ttc;
761  $totalrecu += $paiement;
762  $totalrecucreditnote += $creditnotes;
763  $totalrecudeposits += $deposits;
764  $i++;
765  }
766 
767  if ($i > 1)
768  {
769  // Print total
770  print '<tr class="liste_total">';
771  print '<td colspan="3" class="left">'.$langs->trans('TotalTTC').'</td>';
772  if (!empty($conf->multicurrency->enabled)) {
773  print '<td></td>';
774  print '<td></td>';
775  print '<td></td>';
776  print '<td></td>';
777  print '<td class="right" id="multicurrency_result" style="font-weight: bold;"></td>';
778  }
779  print '<td class="right"><b>'.price($sign * $total_ttc).'</b></td>';
780  print '<td class="right"><b>'.price($sign * $totalrecu);
781  if ($totalrecucreditnote) print '+'.price($totalrecucreditnote);
782  if ($totalrecudeposits) print '+'.price($totalrecudeposits);
783  print '</b></td>';
784  print '<td class="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'</b></td>';
785  print '<td class="right" id="result" style="font-weight: bold;"></td>'; // Autofilled
786  print '<td align="center">&nbsp;</td>';
787  print "</tr>\n";
788  }
789  print "</table>";
790  print "</div>\n";
791  }
792  $db->free($resql);
793  } else {
794  dol_print_error($db);
795  }
796 
797 
798  // Save button
799  if ($action != 'add_paiement')
800  {
801  $checkboxlabel = $langs->trans("ClosePaidInvoicesAutomatically");
802  if ($facture->type == Facture::TYPE_CREDIT_NOTE) $checkboxlabel = $langs->trans("ClosePaidCreditNotesAutomatically");
803  $buttontitle = $langs->trans('ToMakePayment');
804  if ($facture->type == Facture::TYPE_CREDIT_NOTE) $buttontitle = $langs->trans('ToMakePaymentBack');
805 
806  print '<br><div class="center">';
807  print '<input type="checkbox" checked name="closepaidinvoices"> '.$checkboxlabel;
808  /*if (! empty($conf->prelevement->enabled))
809  {
810  $langs->load("withdrawals");
811  if (! empty($conf->global->WITHDRAW_DISABLE_AUTOCREATE_ONPAYMENTS)) print '<br>'.$langs->trans("IfInvoiceNeedOnWithdrawPaymentWontBeClosed");
812  }*/
813  print '<br><input type="submit" class="button" value="'.dol_escape_htmltag($buttontitle).'"><br><br>';
814  print '</div>';
815  }
816 
817  // Form to confirm payment
818  if ($action == 'add_paiement')
819  {
820  $preselectedchoice = $addwarning ? 'no' : 'yes';
821 
822  print '<br>';
823  if (!empty($totalpayment)) $text = $langs->trans('ConfirmCustomerPayment', $totalpayment, $langs->trans("Currency".$conf->currency));
824  if (!empty($multicurrency_totalpayment))
825  {
826  $text .= '<br>'.$langs->trans('ConfirmCustomerPayment', $multicurrency_totalpayment, $langs->trans("paymentInInvoiceCurrency"));
827  }
828  if (GETPOST('closepaidinvoices'))
829  {
830  $text .= '<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
831  print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">';
832  }
833  print $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$facture->id.'&socid='.$facture->socid.'&type='.$facture->type, $langs->trans('ReceivedCustomersPayments'), $text, 'confirm_paiement', $formquestion, $preselectedchoice);
834  }
835 
836  print "</form>\n";
837  }
838 }
839 
840 
844 if (!GETPOST('action', 'aZ09'))
845 {
846  if (empty($page) || $page == -1) $page = 0;
847  $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
848  $offset = $limit * $page;
849 
850  if (!$sortorder) $sortorder = 'DESC';
851  if (!$sortfield) $sortfield = 'p.datep';
852 
853  $sql = 'SELECT p.datep as dp, p.amount, f.total_ttc as fa_amount, f.ref';
854  $sql .= ', f.rowid as facid, c.libelle as paiement_type, p.num_paiement as num_payment';
855  $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
856  $sql .= ', '.MAIN_DB_PREFIX.'facture as f';
857  $sql .= ' WHERE p.fk_facture = f.rowid';
858  $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
859  if ($socid)
860  {
861  $sql .= ' AND f.fk_soc = '.$socid;
862  }
863 
864  $sql .= ' ORDER BY '.$sortfield.' '.$sortorder;
865  $sql .= $db->plimit($limit + 1, $offset);
866  $resql = $db->query($sql);
867 
868  if ($resql)
869  {
870  $num = $db->num_rows($resql);
871  $i = 0;
872 
873  print_barre_liste($langs->trans('Payments'), $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', $num);
874  print '<table class="noborder centpercent">';
875  print '<tr class="liste_titre">';
876  print_liste_field_titre('Invoice', $_SERVER["PHP_SELF"], 'f.ref', '', '', '', $sortfield, $sortorder);
877  print_liste_field_titre('Date', $_SERVER["PHP_SELF"], 'p.datep', '', '', '', $sortfield, $sortorder);
878  print_liste_field_titre('Type', $_SERVER["PHP_SELF"], 'c.libelle', '', '', '', $sortfield, $sortorder);
879  print_liste_field_titre('Amount', $_SERVER["PHP_SELF"], 'p.amount', '', '', '', $sortfield, $sortorder, 'right ');
880  print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch ');
881  print "</tr>\n";
882 
883  while ($i < min($num, $limit))
884  {
885  $objp = $db->fetch_object($resql);
886 
887  print '<tr class="oddeven">';
888  print '<td><a href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$objp->facid.'">'.$objp->ref."</a></td>\n";
889  print '<td>'.dol_print_date($db->jdate($objp->dp))."</td>\n";
890  print '<td>'.$objp->paiement_type.' '.$objp->num_payment."</td>\n";
891  print '<td class="right">'.price($objp->amount).'</td>';
892  print '<td>&nbsp;</td>';
893  print '</tr>';
894 
895  $parameters = array();
896  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook
897 
898  $i++;
899  }
900  print '</table>';
901  }
902 }
903 
904 llxFooter();
905 
906 $db->close();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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...
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
img_warning($titlealt= 'default', $moreatt= '', $morecss= 'pictowarning')
Show warning logo.
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...
const TYPE_CREDIT_NOTE
Credit note invoice.
llxHeader()
Empty header.
Definition: wrapper.php:45
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
print_barre_liste($titre, $page, $file, $options= '', $sortfield= '', $sortorder= '', $morehtmlcenter= '', $num=-1, $totalnboflines= '', $picto= 'generic', $pictoisfullpath=0, $morehtmlright= '', $morecss= '', $limit=-1, $hideselectlimit=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow= '')
Print a title with navigation controls for pagination.
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname.
Class to manage third parties objects (customers, suppliers, prospects...)
print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
load_fiche_titre($titre, $morehtmlright= '', $picto= 'generic', $pictoisfullpath=0, $id= '', $morecssontable= '', $morehtmlcenter= '')
Load a title with picto.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
Class to manage payments of customer invoices.
print $_SERVER["PHP_SELF"]
Edit parameters.
dol_getIdFromCode($db, $key, $tablename, $fieldkey= 'code', $fieldid= 'id', $entityfilter=0)
Return an id or code from a code or id.
dol_get_fiche_head($links=array(), $active= '', $title= '', $notab=0, $picto= '', $pictoisfullpath=0, $morehtmlright= '', $morecss= '', $limittoshow=0, $moretabssuffix= '')
Show tabs of a record.
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Class to manage invoices.
llxFooter()
Empty footer.
Definition: wrapper.php:59
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...