paiement.php 37 KB

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