paiement.php 36 KB

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