paiement.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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 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 <http://www.gnu.org/licenses/>.
  25. */
  26. /**
  27. * \file htdocs/compta/paiement.php
  28. * \ingroup facture
  29. * \brief Payment page for customers invoices
  30. */
  31. require '../main.inc.php';
  32. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  34. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  36. // Load translation files required by the page
  37. $langs->loadLangs(array('companies', 'bills', 'banks', 'multicurrency'));
  38. $action = GETPOST('action','alpha');
  39. $confirm = GETPOST('confirm');
  40. $facid = GETPOST('facid','int');
  41. $socname = GETPOST('socname');
  42. $accountid = GETPOST('accountid');
  43. $paymentnum = GETPOST('num_paiement');
  44. $sortfield = GETPOST('sortfield','alpha');
  45. $sortorder = GETPOST('sortorder','alpha');
  46. $page = GETPOST('page','int');
  47. $amounts=array();
  48. $amountsresttopay=array();
  49. $addwarning=0;
  50. $multicurrency_amounts=array();
  51. $multicurrency_amountsresttopay=array();
  52. // Security check
  53. $socid=0;
  54. if ($user->societe_id > 0)
  55. {
  56. $socid = $user->societe_id;
  57. }
  58. $object=new Facture($db);
  59. // Load object
  60. if ($facid > 0)
  61. {
  62. $ret=$object->fetch($facid);
  63. }
  64. // Initialize technical object to manage hooks of paiements. Note that conf->hooks_modules contains array array
  65. $hookmanager->initHooks(array('paiementcard','globalcard'));
  66. /*
  67. * Actions
  68. */
  69. $parameters=array('socid'=>$socid);
  70. $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
  71. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  72. if (empty($reshook))
  73. {
  74. if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes'))
  75. {
  76. $error = 0;
  77. $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth','int'), GETPOST('reday','int'), GETPOST('reyear','int'));
  78. $paiement_id = 0;
  79. $totalpayment = 0;
  80. $multicurrency_totalpayment = 0;
  81. $atleastonepaymentnotnull = 0;
  82. // Generate payment array and check if there is payment higher than invoice and payment date before invoice date
  83. $tmpinvoice=new Facture($db);
  84. foreach ($_POST as $key => $value)
  85. {
  86. if (substr($key,0,7) == 'amount_' && GETPOST($key) != '')
  87. {
  88. $cursorfacid = substr($key,7);
  89. $amounts[$cursorfacid] = price2num(trim(GETPOST($key)));
  90. $totalpayment = $totalpayment + $amounts[$cursorfacid];
  91. if (! empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++;
  92. $result=$tmpinvoice->fetch($cursorfacid);
  93. if ($result <= 0) dol_print_error($db);
  94. $amountsresttopay[$cursorfacid]=price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement());
  95. if ($amounts[$cursorfacid])
  96. {
  97. // Check amount
  98. if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid])))
  99. {
  100. $addwarning=1;
  101. $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
  102. }
  103. // Check date
  104. if ($datepaye && ($datepaye < $tmpinvoice->date))
  105. {
  106. $langs->load("errors");
  107. //$error++;
  108. setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye,'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
  109. }
  110. }
  111. $formquestion[$i++]=array('type' => 'hidden','name' => $key, 'value' => $_POST[$key]);
  112. }
  113. elseif (substr($key,0,21) == 'multicurrency_amount_')
  114. {
  115. $cursorfacid = substr($key,21);
  116. $multicurrency_amounts[$cursorfacid] = price2num(trim(GETPOST($key)));
  117. $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid];
  118. if (! empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++;
  119. $result=$tmpinvoice->fetch($cursorfacid);
  120. if ($result <= 0) dol_print_error($db);
  121. $multicurrency_amountsresttopay[$cursorfacid]=price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1));
  122. if ($multicurrency_amounts[$cursorfacid])
  123. {
  124. // Check amount
  125. if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid])))
  126. {
  127. $addwarning=1;
  128. $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
  129. }
  130. // Check date
  131. if ($datepaye && ($datepaye < $tmpinvoice->date))
  132. {
  133. $langs->load("errors");
  134. //$error++;
  135. setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye,'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
  136. }
  137. }
  138. $formquestion[$i++]=array('type' => 'hidden','name' => $key, 'value' => GETPOST($key, 'int'));
  139. }
  140. }
  141. // Check parameters
  142. if (! GETPOST('paiementcode'))
  143. {
  144. setEventMessages($langs->transnoentities('ErrorFieldRequired',$langs->transnoentities('PaymentMode')), null, 'errors');
  145. $error++;
  146. }
  147. if (! empty($conf->banque->enabled))
  148. {
  149. // If bank module is on, account is required to enter a payment
  150. if (GETPOST('accountid') <= 0)
  151. {
  152. setEventMessages($langs->transnoentities('ErrorFieldRequired',$langs->transnoentities('AccountToCredit')), null, 'errors');
  153. $error++;
  154. }
  155. }
  156. if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull))
  157. {
  158. setEventMessages($langs->transnoentities('ErrorFieldRequired',$langs->trans('PaymentAmount')), null, 'errors');
  159. $error++;
  160. }
  161. if (empty($datepaye))
  162. {
  163. setEventMessages($langs->transnoentities('ErrorFieldRequired',$langs->transnoentities('Date')), null, 'errors');
  164. $error++;
  165. }
  166. // Check if payments in both currency
  167. if ($totalpayment > 0 && $multicurrency_totalpayment > 0)
  168. {
  169. setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors');
  170. $error++;
  171. }
  172. }
  173. /*
  174. * Action add_paiement
  175. */
  176. if ($action == 'add_paiement')
  177. {
  178. if ($error)
  179. {
  180. $action = 'create';
  181. }
  182. // Le reste propre a cette action s'affiche en bas de page.
  183. }
  184. /*
  185. * Action confirm_paiement
  186. */
  187. if ($action == 'confirm_paiement' && $confirm == 'yes')
  188. {
  189. $error=0;
  190. $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  191. $db->begin();
  192. // Clean parameters amount if payment is for a credit note
  193. if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE)
  194. {
  195. foreach ($amounts as $key => $value) // How payment is dispatch
  196. {
  197. $newvalue = price2num($value,'MT');
  198. $amounts[$key] = -$newvalue;
  199. }
  200. foreach ($multicurrency_amounts as $key => $value) // How payment is dispatch
  201. {
  202. $newvalue = price2num($value,'MT');
  203. $multicurrency_amounts[$key] = -$newvalue;
  204. }
  205. }
  206. if (! empty($conf->banque->enabled))
  207. {
  208. // Si module bank actif, un compte est obligatoire lors de la saisie d'un paiement
  209. if (GETPOST('accountid') <= 0)
  210. {
  211. setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('AccountToCredit')), null, 'errors');
  212. $error++;
  213. }
  214. }
  215. // Creation of payment line
  216. $paiement = new Paiement($db);
  217. $paiement->datepaye = $datepaye;
  218. $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
  219. $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
  220. $paiement->paiementid = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement','code','id',1);
  221. $paiement->num_paiement = GETPOST('num_paiement');
  222. $paiement->note = GETPOST('comment');
  223. if (! $error)
  224. {
  225. $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0)); // This include closing invoices and regenerating documents
  226. if ($paiement_id < 0)
  227. {
  228. setEventMessages($paiement->error, $paiement->errors, 'errors');
  229. $error++;
  230. }
  231. }
  232. if (! $error)
  233. {
  234. $label='(CustomerInvoicePayment)';
  235. if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)'; // Refund of a credit note
  236. $result=$paiement->addPaymentToBank($user,'payment',$label,GETPOST('accountid'),GETPOST('chqemetteur'),GETPOST('chqbank'));
  237. if ($result < 0)
  238. {
  239. setEventMessages($paiement->error, $paiement->errors, 'errors');
  240. $error++;
  241. }
  242. }
  243. if (! $error)
  244. {
  245. $db->commit();
  246. // If payment dispatching on more than one invoice, we keep on summary page, otherwise jump on invoice card
  247. $invoiceid=0;
  248. foreach ($paiement->amounts as $key => $amount)
  249. {
  250. $facid = $key;
  251. if (is_numeric($amount) && $amount <> 0)
  252. {
  253. if ($invoiceid != 0) $invoiceid=-1; // There is more than one invoice payed by this payment
  254. else $invoiceid=$facid;
  255. }
  256. }
  257. if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$invoiceid;
  258. else $loc = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$paiement_id;
  259. header('Location: '.$loc);
  260. exit;
  261. }
  262. else
  263. {
  264. $db->rollback();
  265. }
  266. }
  267. }
  268. /*
  269. * View
  270. */
  271. $form=new Form($db);
  272. llxHeader('', $langs->trans("Payment"));
  273. if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement')
  274. {
  275. $facture = new Facture($db);
  276. $result = $facture->fetch($facid);
  277. if ($result >= 0)
  278. {
  279. $facture->fetch_thirdparty();
  280. $title='';
  281. if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentReceivedFromCustomer");
  282. if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentDueToCustomer");
  283. print load_fiche_titre($title);
  284. // Initialize data for confirmation (this is used because data can be change during confirmation)
  285. if ($action == 'add_paiement')
  286. {
  287. $i=0;
  288. $formquestion[$i++]=array('type' => 'hidden','name' => 'facid', 'value' => $facture->id);
  289. $formquestion[$i++]=array('type' => 'hidden','name' => 'socid', 'value' => $facture->socid);
  290. $formquestion[$i++]=array('type' => 'hidden','name' => 'type', 'value' => $facture->type);
  291. }
  292. // Invoice with Paypal transaction
  293. // TODO add hook possibility (regis)
  294. if (! empty($conf->paypalplus->enabled) && $conf->global->PAYPAL_ENABLE_TRANSACTION_MANAGEMENT && ! empty($facture->ref_int))
  295. {
  296. if (! empty($conf->global->PAYPAL_BANK_ACCOUNT)) $accountid=$conf->global->PAYPAL_BANK_ACCOUNT;
  297. $paymentnum=$facture->ref_int;
  298. }
  299. // Add realtime total information
  300. if (! empty($conf->use_javascript_ajax))
  301. {
  302. print "\n".'<script type="text/javascript" language="javascript">';
  303. print '$(document).ready(function () {
  304. setPaiementCode();
  305. $("#selectpaiementcode").change(function() {
  306. setPaiementCode();
  307. });
  308. function setPaiementCode()
  309. {
  310. var code = $("#selectpaiementcode option:selected").val();
  311. if (code == \'CHQ\' || code == \'VIR\')
  312. {
  313. if (code == \'CHQ\')
  314. {
  315. $(\'.fieldrequireddyn\').addClass(\'fieldrequired\');
  316. }
  317. if ($(\'#fieldchqemetteur\').val() == \'\')
  318. {
  319. var emetteur = ('.$facture->type.' == '.Facture::TYPE_CREDIT_NOTE.') ? \''.dol_escape_js(dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM)).'\' : jQuery(\'#thirdpartylabel\').val();
  320. $(\'#fieldchqemetteur\').val(emetteur);
  321. }
  322. }
  323. else
  324. {
  325. $(\'.fieldrequireddyn\').removeClass(\'fieldrequired\');
  326. $(\'#fieldchqemetteur\').val(\'\');
  327. }
  328. }
  329. function _elemToJson(selector)
  330. {
  331. var subJson = {};
  332. $.map(selector.serializeArray(), function(n,i)
  333. {
  334. subJson[n["name"]] = n["value"];
  335. });
  336. return subJson;
  337. }
  338. function callForResult(imgId)
  339. {
  340. var json = {};
  341. var form = $("#payment_form");
  342. json["invoice_type"] = $("#invoice_type").val();
  343. json["amountPayment"] = $("#amountpayment").attr("value");
  344. json["amounts"] = _elemToJson(form.find("input.amount"));
  345. json["remains"] = _elemToJson(form.find("input.remain"));
  346. if (imgId != null) {
  347. json["imgClicked"] = imgId;
  348. }
  349. $.post("'.DOL_URL_ROOT.'/compta/ajaxpayment.php", json, function(data)
  350. {
  351. json = $.parseJSON(data);
  352. form.data(json);
  353. for (var key in json)
  354. {
  355. if (key == "result") {
  356. if (json["makeRed"]) {
  357. $("#"+key).addClass("error");
  358. } else {
  359. $("#"+key).removeClass("error");
  360. }
  361. json[key]=json["label"]+" "+json[key];
  362. $("#"+key).text(json[key]);
  363. } else {console.log(key);
  364. form.find("input[name*=\""+key+"\"]").each(function() {
  365. $(this).attr("value", json[key]);
  366. });
  367. }
  368. }
  369. });
  370. }
  371. $("#payment_form").find("input.amount").change(function() {
  372. callForResult();
  373. });
  374. $("#payment_form").find("input.amount").keyup(function() {
  375. callForResult();
  376. });
  377. ';
  378. print ' });'."\n";
  379. //Add js for AutoFill
  380. print ' $(document).ready(function () {';
  381. print ' $(".AutoFillAmout").on(\'click touchstart\', function(){
  382. $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
  383. });';
  384. print ' });'."\n";
  385. print ' </script>'."\n";
  386. }
  387. print '<form id="payment_form" name="add_paiement" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  388. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  389. print '<input type="hidden" name="action" value="add_paiement">';
  390. print '<input type="hidden" name="facid" value="'.$facture->id.'">';
  391. print '<input type="hidden" name="socid" value="'.$facture->socid.'">';
  392. print '<input type="hidden" name="type" id="invoice_type" value="'.$facture->type.'">';
  393. print '<input type="hidden" name="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($facture->thirdparty->name).'">';
  394. dol_fiche_head();
  395. print '<table class="border" width="100%">';
  396. // Third party
  397. print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans('Company').'</span></td><td>'.$facture->thirdparty->getNomUrl(4)."</td></tr>\n";
  398. // Date payment
  399. print '<tr><td><span class="fieldrequired">'.$langs->trans('Date').'</span></td><td>';
  400. $datepayment = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  401. $datepayment= ($datepayment == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'') : $datepayment);
  402. print $form->selectDate($datepayment, '', '', '', 0, "add_paiement", 1, 1, 0, '', '', $facture->date);
  403. print '</td></tr>';
  404. // Payment mode
  405. print '<tr><td><span class="fieldrequired">'.$langs->trans('PaymentMode').'</span></td><td>';
  406. $form->select_types_paiements((GETPOST('paiementcode')?GETPOST('paiementcode'):$facture->mode_reglement_code),'paiementcode','',2);
  407. print "</td>\n";
  408. print '</tr>';
  409. // Bank account
  410. print '<tr>';
  411. if (! empty($conf->banque->enabled))
  412. {
  413. if ($facture->type != 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToCredit').'</span></td>';
  414. if ($facture->type == 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToDebit').'</span></td>';
  415. print '<td>';
  416. $form->select_comptes($accountid,'accountid',0,'',2);
  417. print '</td>';
  418. }
  419. else
  420. {
  421. print '<td>&nbsp;</td>';
  422. }
  423. print "</tr>\n";
  424. // Cheque number
  425. print '<tr><td>'.$langs->trans('Numero');
  426. print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
  427. print '</td>';
  428. print '<td><input name="num_paiement" type="text" value="'.$paymentnum.'"></td></tr>';
  429. // Check transmitter
  430. print '<tr><td class="'.(GETPOST('paiementcode')=='CHQ'?'fieldrequired ':'').'fieldrequireddyn">'.$langs->trans('CheckTransmitter');
  431. print ' <em>('.$langs->trans("ChequeMaker").')</em>';
  432. print '</td>';
  433. print '<td><input id="fieldchqemetteur" name="chqemetteur" size="30" type="text" value="'.GETPOST('chqemetteur','alphanohtml').'"></td></tr>';
  434. // Bank name
  435. print '<tr><td>'.$langs->trans('Bank');
  436. print ' <em>('.$langs->trans("ChequeBank").')</em>';
  437. print '</td>';
  438. print '<td><input name="chqbank" size="30" type="text" value="'.GETPOST('chqbank','alphanohtml').'"></td></tr>';
  439. // Comments
  440. print '<tr><td>'.$langs->trans('Comments').'</td>';
  441. print '<td class="tdtop">';
  442. print '<textarea name="comment" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.GETPOST('comment','none').'</textarea></td></tr>';
  443. print '</table>';
  444. dol_fiche_end();
  445. /*
  446. * List of unpaid invoices
  447. */
  448. $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type,';
  449. $sql.= ' f.datef as df, f.fk_soc as socid, f.date_lim_reglement as dlr';
  450. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
  451. $sql.= ' WHERE f.entity IN ('.getEntity('facture', $conf->entity).')';
  452. $sql.= ' AND (f.fk_soc = '.$facture->socid;
  453. // Can pay invoices of all child of parent company
  454. if(!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) {
  455. $sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')';
  456. }
  457. // Can pay invoices of all child of myself
  458. if(!empty($conf->global->FACTURE_PAYMENTS_ON_SUBSIDIARY_COMPANIES)){
  459. $sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->id.')';
  460. }
  461. $sql.= ') AND f.paye = 0';
  462. $sql.= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled
  463. if ($facture->type != 2)
  464. {
  465. $sql .= ' AND type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation
  466. }
  467. else
  468. {
  469. $sql .= ' AND type = 2'; // If paying back a credit note, we show all credit notes
  470. }
  471. // Sort invoices by date and serial number: the older one comes first
  472. $sql.=' ORDER BY f.datef ASC, f.facnumber ASC';
  473. $resql = $db->query($sql);
  474. if ($resql)
  475. {
  476. $num = $db->num_rows($resql);
  477. if ($num > 0)
  478. {
  479. $sign=1;
  480. if ($facture->type == 2) $sign=-1;
  481. $arraytitle=$langs->trans('Invoice');
  482. if ($facture->type == 2) $arraytitle=$langs->trans("CreditNotes");
  483. $alreadypayedlabel=$langs->trans('Received');
  484. $multicurrencyalreadypayedlabel=$langs->trans('MulticurrencyReceived');
  485. if ($facture->type == 2) { $alreadypayedlabel=$langs->trans("PaidBack"); $multicurrencyalreadypayedlabel=$langs->trans("MulticurrencyPaidBack"); }
  486. $remaindertopay=$langs->trans('RemainderToTake');
  487. $multicurrencyremaindertopay=$langs->trans('MulticurrencyRemainderToTake');
  488. if ($facture->type == 2) { $remaindertopay=$langs->trans("RemainderToPayBack"); $multicurrencyremaindertopay=$langs->trans("MulticurrencyRemainderToPayBack"); }
  489. $i = 0;
  490. //print '<tr><td colspan="3">';
  491. print '<br>';
  492. print '<table class="noborder" width="100%">';
  493. print '<tr class="liste_titre">';
  494. print '<td>'.$arraytitle.'</td>';
  495. print '<td align="center">'.$langs->trans('Date').'</td>';
  496. print '<td align="center">'.$langs->trans('DateMaxPayment').'</td>';
  497. if (!empty($conf->multicurrency->enabled)) {
  498. print '<td>'.$langs->trans('Currency').'</td>';
  499. print '<td align="right">'.$langs->trans('MulticurrencyAmountTTC').'</td>';
  500. print '<td align="right">'.$multicurrencyalreadypayedlabel.'</td>';
  501. print '<td align="right">'.$multicurrencyremaindertopay.'</td>';
  502. print '<td align="right">'.$langs->trans('MulticurrencyPaymentAmount').'</td>';
  503. }
  504. print '<td align="right">'.$langs->trans('AmountTTC').'</td>';
  505. print '<td align="right">'.$alreadypayedlabel.'</td>';
  506. print '<td align="right">'.$remaindertopay.'</td>';
  507. print '<td align="right">'.$langs->trans('PaymentAmount').'</td>';
  508. print '<td align="right">&nbsp;</td>';
  509. print "</tr>\n";
  510. $total=0;
  511. $totalrecu=0;
  512. $totalrecucreditnote=0;
  513. $totalrecudeposits=0;
  514. while ($i < $num)
  515. {
  516. $objp = $db->fetch_object($resql);
  517. $soc = new Societe($db);
  518. $soc->fetch($objp->socid);
  519. $invoice=new Facture($db);
  520. $invoice->fetch($objp->facid);
  521. $paiement = $invoice->getSommePaiement();
  522. $creditnotes=$invoice->getSumCreditNotesUsed();
  523. $deposits=$invoice->getSumDepositsUsed();
  524. $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
  525. $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
  526. // Multicurrency Price
  527. if (!empty($conf->multicurrency->enabled)) {
  528. $multicurrency_payment = $invoice->getSommePaiement(1);
  529. $multicurrency_creditnotes=$invoice->getSumCreditNotesUsed(1);
  530. $multicurrency_deposits=$invoice->getSumDepositsUsed(1);
  531. $multicurrency_alreadypayed=price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits,'MT');
  532. $multicurrency_remaintopay=price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits,'MT');
  533. }
  534. print '<tr class="oddeven">';
  535. print '<td>';
  536. print $invoice->getNomUrl(1,'');
  537. if($objp->socid != $facture->thirdparty->id) print ' - '.$soc->getNomUrl(1).' ';
  538. print "</td>\n";
  539. // Date
  540. print '<td align="center">'.dol_print_date($db->jdate($objp->df),'day')."</td>\n";
  541. // Date Max Payment
  542. if ($objp->dlr > 0 )
  543. {
  544. print '<td align="center">';
  545. print dol_print_date($db->jdate($objp->dlr), 'day');
  546. if ($invoice->hasDelay())
  547. {
  548. print img_warning($langs->trans('Late'));
  549. }
  550. print '</td>';
  551. }
  552. else
  553. {
  554. print '<td align="center"><b>--</b></td>';
  555. }
  556. // Currency
  557. if (!empty($conf->multicurrency->enabled)) print '<td align="center">'.$objp->multicurrency_code."</td>\n";
  558. // Multicurrency Price
  559. if (!empty($conf->multicurrency->enabled))
  560. {
  561. print '<td align="right">';
  562. if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $objp->multicurrency_total_ttc);
  563. print '</td>';
  564. // Multicurrency Price
  565. print '<td align="right">';
  566. if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency)
  567. {
  568. print price($sign * $multicurrency_payment);
  569. if ($multicurrency_creditnotes) print '+'.price($multicurrency_creditnotes);
  570. if ($multicurrency_deposits) print '+'.price($multicurrency_deposits);
  571. }
  572. print '</td>';
  573. // Multicurrency Price
  574. print '<td align="right">';
  575. if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $multicurrency_remaintopay);
  576. print '</td>';
  577. print '<td align="right">';
  578. // Add remind multicurrency amount
  579. $namef = 'multicurrency_amount_'.$objp->facid;
  580. $nameRemain = 'multicurrency_remain_'.$objp->facid;
  581. if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency)
  582. {
  583. if ($action != 'add_paiement')
  584. {
  585. if (!empty($conf->use_javascript_ajax))
  586. print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'");
  587. print '<input type=hidden class="multicurrency_remain" name="'.$nameRemain.'" value="'.$multicurrency_remaintopay.'">';
  588. print '<input type="text" size="8" class="multicurrency_amount" name="'.$namef.'" value="'.$_POST[$namef].'">';
  589. }
  590. else
  591. {
  592. print '<input type="text" size="8" name="'.$namef.'_disabled" value="'.$_POST[$namef].'" disabled>';
  593. print '<input type="hidden" name="'.$namef.'" value="'.$_POST[$namef].'">';
  594. }
  595. }
  596. print "</td>";
  597. }
  598. // Price
  599. print '<td align="right">'.price($sign * $objp->total_ttc).'</td>';
  600. // Received or paid back
  601. print '<td align="right">'.price($sign * $paiement);
  602. if ($creditnotes) print '+'.price($creditnotes);
  603. if ($deposits) print '+'.price($deposits);
  604. print '</td>';
  605. // Remain to take or to pay back
  606. print '<td align="right">'.price($sign * $remaintopay).'</td>';
  607. //$test= price(price2num($objp->total_ttc - $paiement - $creditnotes - $deposits));
  608. // Amount
  609. print '<td align="right">';
  610. // Add remind amount
  611. $namef = 'amount_'.$objp->facid;
  612. $nameRemain = 'remain_'.$objp->facid;
  613. if ($action != 'add_paiement')
  614. {
  615. if (!empty($conf->use_javascript_ajax))
  616. print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'");
  617. print '<input type="hidden" class="remain" name="'.$nameRemain.'" value="'.$remaintopay.'">';
  618. print '<input type="text" size="8" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">';
  619. }
  620. else
  621. {
  622. print '<input type="text" size="8" name="'.$namef.'_disabled" value="'.dol_escape_htmltag(GETPOST($namef)).'" disabled>';
  623. print '<input type="hidden" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">';
  624. }
  625. print "</td>";
  626. // Warning
  627. print '<td align="center" width="16">';
  628. //print "xx".$amounts[$invoice->id]."-".$amountsresttopay[$invoice->id]."<br>";
  629. if ($amounts[$invoice->id] && (abs($amounts[$invoice->id]) > abs($amountsresttopay[$invoice->id]))
  630. || $multicurrency_amounts[$invoice->id] && (abs($multicurrency_amounts[$invoice->id]) > abs($multicurrency_amountsresttopay[$invoice->id])))
  631. {
  632. print ' '.img_warning($langs->trans("PaymentHigherThanReminderToPay"));
  633. }
  634. print '</td>';
  635. $parameters=array();
  636. $reshook=$hookmanager->executeHooks('printObjectLine',$parameters,$objp,$action); // Note that $action and $object may have been modified by hook
  637. print "</tr>\n";
  638. $total+=$objp->total;
  639. $total_ttc+=$objp->total_ttc;
  640. $totalrecu+=$paiement;
  641. $totalrecucreditnote+=$creditnotes;
  642. $totalrecudeposits+=$deposits;
  643. $i++;
  644. }
  645. if ($i > 1)
  646. {
  647. // Print total
  648. print '<tr class="liste_total">';
  649. print '<td colspan="2" align="left">'.$langs->trans('TotalTTC').'</td>';
  650. if (!empty($conf->multicurrency->enabled)) {
  651. print '<td></td>';
  652. print '<td></td>';
  653. print '<td></td>';
  654. print '<td></td>';
  655. print '<td align="right" id="multicurrency_result" style="font-weight: bold;"></td>';
  656. }
  657. print '<td align="right"><b>'.price($sign * $total_ttc).'</b></td>';
  658. print '<td align="right"><b>'.price($sign * $totalrecu);
  659. if ($totalrecucreditnote) print '+'.price($totalrecucreditnote);
  660. if ($totalrecudeposits) print '+'.price($totalrecudeposits);
  661. print '</b></td>';
  662. print '<td align="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits,'MT')).'</b></td>';
  663. print '<td align="right" id="result" style="font-weight: bold;"></td>'; // Autofilled
  664. print '<td align="center">&nbsp;</td>';
  665. print "</tr>\n";
  666. }
  667. print "</table>";
  668. //print "</td></tr>\n";
  669. }
  670. $db->free($resql);
  671. }
  672. else
  673. {
  674. dol_print_error($db);
  675. }
  676. // Bouton Enregistrer
  677. if ($action != 'add_paiement')
  678. {
  679. $checkboxlabel=$langs->trans("ClosePaidInvoicesAutomatically");
  680. if ($facture->type == 2) $checkboxlabel=$langs->trans("ClosePaidCreditNotesAutomatically");
  681. $buttontitle=$langs->trans('ToMakePayment');
  682. if ($facture->type == 2) $buttontitle=$langs->trans('ToMakePaymentBack');
  683. print '<br><div class="center">';
  684. print '<input type="checkbox" checked name="closepaidinvoices"> '.$checkboxlabel;
  685. /*if (! empty($conf->prelevement->enabled))
  686. {
  687. $langs->load("withdrawals");
  688. if (! empty($conf->global->WITHDRAW_DISABLE_AUTOCREATE_ONPAYMENTS)) print '<br>'.$langs->trans("IfInvoiceNeedOnWithdrawPaymentWontBeClosed");
  689. }*/
  690. print '<br><input type="submit" class="button" value="'.dol_escape_htmltag($buttontitle).'"><br><br>';
  691. print '</div>';
  692. }
  693. // Form to confirm payment
  694. if ($action == 'add_paiement')
  695. {
  696. $preselectedchoice=$addwarning?'no':'yes';
  697. print '<br>';
  698. if (!empty($totalpayment)) $text=$langs->trans('ConfirmCustomerPayment',$totalpayment,$langs->trans("Currency".$conf->currency));
  699. if (!empty($multicurrency_totalpayment))
  700. {
  701. $text.='<br>'.$langs->trans('ConfirmCustomerPayment',$multicurrency_totalpayment,$langs->trans("paymentInInvoiceCurrency"));
  702. }
  703. if (GETPOST('closepaidinvoices'))
  704. {
  705. $text.='<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
  706. print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">';
  707. }
  708. print $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$facture->id.'&socid='.$facture->socid.'&type='.$facture->type,$langs->trans('ReceivedCustomersPayments'),$text,'confirm_paiement',$formquestion,$preselectedchoice);
  709. }
  710. print "</form>\n";
  711. }
  712. }
  713. /**
  714. * Show list of payments
  715. */
  716. if (! GETPOST('action','aZ09'))
  717. {
  718. if ($page == -1) $page = 0 ;
  719. $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
  720. $offset = $limit * $page ;
  721. if (! $sortorder) $sortorder='DESC';
  722. if (! $sortfield) $sortfield='p.datep';
  723. $sql = 'SELECT p.datep as dp, p.amount, f.amount as fa_amount, f.facnumber';
  724. $sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement';
  725. $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  726. $sql.= ', '.MAIN_DB_PREFIX.'facture as f';
  727. $sql.= ' WHERE p.fk_facture = f.rowid';
  728. $sql.= ' AND f.entity IN (' . getEntity('facture').')';
  729. if ($socid)
  730. {
  731. $sql.= ' AND f.fk_soc = '.$socid;
  732. }
  733. $sql.= ' ORDER BY '.$sortfield.' '.$sortorder;
  734. $sql.= $db->plimit($limit+1, $offset);
  735. $resql = $db->query($sql);
  736. if ($resql)
  737. {
  738. $num = $db->num_rows($resql);
  739. $i = 0;
  740. print_barre_liste($langs->trans('Payments'), $page, $_SERVER["PHP_SELF"],'',$sortfield,$sortorder,'',$num);
  741. print '<table class="noborder" width="100%">';
  742. print '<tr class="liste_titre">';
  743. print_liste_field_titre('Invoice',$_SERVER["PHP_SELF"],'facnumber','','','',$sortfield,$sortorder);
  744. print_liste_field_titre('Date',$_SERVER["PHP_SELF"],'dp','','','',$sortfield,$sortorder);
  745. print_liste_field_titre('Type',$_SERVER["PHP_SELF"],'libelle','','','',$sortfield,$sortorder);
  746. print_liste_field_titre('Amount',$_SERVER["PHP_SELF"],'fa_amount','','','align="right"',$sortfield,$sortorder);
  747. print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch ');
  748. print "</tr>\n";
  749. while ($i < min($num,$limit))
  750. {
  751. $objp = $db->fetch_object($resql);
  752. print '<tr class="oddeven">';
  753. print '<td><a href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$objp->facid.'">'.$objp->facnumber."</a></td>\n";
  754. print '<td>'.dol_print_date($db->jdate($objp->dp))."</td>\n";
  755. print '<td>'.$objp->paiement_type.' '.$objp->num_paiement."</td>\n";
  756. print '<td align="right">'.price($objp->amount).'</td><td>&nbsp;</td>';
  757. $parameters=array();
  758. $reshook=$hookmanager->executeHooks('printObjectLine',$parameters,$objp,$action); // Note that $action and $object may have been modified by hook
  759. print '</tr>';
  760. $i++;
  761. }
  762. print '</table>';
  763. }
  764. }
  765. llxFooter();
  766. $db->close();