paiement.php 36 KB

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