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