paiement.php 36 KB

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