paiement.php 37 KB

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