paiement.php 36 KB

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