paiement.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. <?php
  2. /* Copyright (C) 2003-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  4. * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  6. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  7. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com>
  9. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  10. * Copyright (C) 2015 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2017 Alexandre Spangaro <aspangaro@open-dsi.fr>
  12. * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
  13. * Copyright (C) 2021 Charlene Benke <charlene@patas-monkey.com>
  14. * Copyright (C) 2022 Udo Tamm <dev@dolibit.de>
  15. * Copyright (C) 2023 Sylvain Legrand <technique@infras.fr>
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation; either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  29. */
  30. /**
  31. * \file htdocs/fourn/facture/paiement.php
  32. * \ingroup fournisseur,facture
  33. * \brief Payment page for supplier invoices
  34. */
  35. // Load Dolibarr environment
  36. require '../../main.inc.php';
  37. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  43. // Load translation files required by the page
  44. $langs->loadLangs(array('companies', 'bills', 'banks', 'compta'));
  45. $action = GETPOST('action', 'alpha');
  46. $confirm = GETPOST('confirm', 'alpha');
  47. $optioncss = GETPOST('optioncss', 'alpha');
  48. $cancel = GETPOST('cancel', 'alpha');
  49. $backtopage = GETPOST('backtopage', 'alpha');
  50. $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
  51. $facid = GETPOST('facid', 'int');
  52. $socid = GETPOST('socid', 'int');
  53. $accountid = GETPOST('accountid', 'int');
  54. $day = GETPOST('day', 'int');
  55. $month = GETPOST('month', 'int');
  56. $year = GETPOST('year', 'int');
  57. $search_ref = GETPOST('search_ref', 'alpha');
  58. $search_account = GETPOST('search_account', 'int');
  59. $search_paymenttype = GETPOST('search_paymenttype');
  60. $search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on "< x"
  61. $search_company = GETPOST('search_company', 'alpha');
  62. $search_payment_num = GETPOST('search_payment_num', 'alpha');
  63. $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
  64. $sortfield = GETPOST('sortfield', 'aZ09comma');
  65. $sortorder = GETPOST('sortorder', 'aZ09comma');
  66. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  67. if (empty($page) || $page == -1) {
  68. $page = 0;
  69. } // If $page is not defined, or '' or -1
  70. $offset = $limit * $page;
  71. $pageprev = $page - 1;
  72. $pagenext = $page + 1;
  73. if (!$sortorder) {
  74. $sortorder = "DESC";
  75. }
  76. if (!$sortfield) {
  77. $sortfield = "p.rowid";
  78. }
  79. $amounts = array();
  80. $amountsresttopay = array();
  81. $addwarning = 0;
  82. $multicurrency_amounts = array();
  83. $multicurrency_amountsresttopay = array();
  84. // Security check
  85. if ($user->socid > 0) {
  86. $socid = $user->socid;
  87. }
  88. $object = new PaiementFourn($db);
  89. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  90. $hookmanager->initHooks(array('paymentsupplierlist'));
  91. $extrafields = new ExtraFields($db);
  92. // fetch optionals attributes and labels
  93. $extrafields->fetch_name_optionals_label($object->table_element);
  94. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  95. $arrayfields = array();
  96. /*
  97. * Actions
  98. */
  99. if ($cancel) {
  100. if (!empty($backtopageforcancel)) {
  101. header("Location: ".$backtopageforcancel);
  102. exit;
  103. } elseif (!empty($backtopage)) {
  104. header("Location: ".$backtopage);
  105. exit;
  106. }
  107. header("Location: ".DOL_URL_ROOT.'/fourn/facture/list.php');
  108. exit;
  109. }
  110. if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
  111. $search_ref = "";
  112. $search_account = "";
  113. $search_amount = "";
  114. $search_paymenttype = "";
  115. $search_payment_num = "";
  116. $search_company = "";
  117. $day = '';
  118. $year = '';
  119. $month = '';
  120. $search_array_options = array();
  121. }
  122. $parameters = array('socid'=>$socid);
  123. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  124. if ($reshook < 0) {
  125. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  126. }
  127. if (empty($reshook)) {
  128. if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) {
  129. $error = 0;
  130. $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  131. $paiement_id = 0;
  132. $totalpayment = 0;
  133. $atleastonepaymentnotnull = 0;
  134. $multicurrency_totalpayment = 0;
  135. // Generate payment array and check if there is payment higher than invoice and payment date before invoice date
  136. $tmpinvoice = new FactureFournisseur($db);
  137. foreach ($_POST as $key => $value) {
  138. if (substr($key, 0, 7) == 'amount_') {
  139. $cursorfacid = substr($key, 7);
  140. $amounts[$cursorfacid] = price2num(GETPOST($key));
  141. if (!empty($amounts[$cursorfacid])) {
  142. $atleastonepaymentnotnull++;
  143. if (is_numeric($amounts[$cursorfacid])) {
  144. $totalpayment = $totalpayment + $amounts[$cursorfacid];
  145. } else {
  146. setEventMessages($langs->transnoentities("InputValueIsNotAnNumber", GETPOST($key)), null, 'warnings');
  147. }
  148. }
  149. $result = $tmpinvoice->fetch($cursorfacid);
  150. if ($result <= 0) {
  151. dol_print_error($db);
  152. }
  153. $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement());
  154. if ($amounts[$cursorfacid]) {
  155. // Check amount
  156. if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) {
  157. $addwarning = 1;
  158. $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier");
  159. }
  160. // Check date
  161. if ($datepaye && ($datepaye < $tmpinvoice->date)) {
  162. $langs->load("errors");
  163. //$error++;
  164. setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
  165. }
  166. }
  167. $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key));
  168. } elseif (substr($key, 0, 21) == 'multicurrency_amount_') {
  169. $cursorfacid = substr($key, 21);
  170. $multicurrency_amounts[$cursorfacid] = (GETPOST($key) ? price2num(GETPOST($key)) : 0);
  171. $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid];
  172. if (!empty($multicurrency_amounts[$cursorfacid])) {
  173. $atleastonepaymentnotnull++;
  174. }
  175. $result = $tmpinvoice->fetch($cursorfacid);
  176. if ($result <= 0) {
  177. dol_print_error($db);
  178. }
  179. $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1));
  180. if ($multicurrency_amounts[$cursorfacid]) {
  181. // Check amount
  182. if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) {
  183. $addwarning = 1;
  184. $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier");
  185. }
  186. // Check date
  187. if ($datepaye && ($datepaye < $tmpinvoice->date)) {
  188. $langs->load("errors");
  189. //$error++;
  190. setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings');
  191. }
  192. }
  193. $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key, 'int'));
  194. }
  195. }
  196. // Check parameters
  197. if (GETPOST('paiementid') <= 0) {
  198. setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors');
  199. $error++;
  200. }
  201. if (isModEnabled("banque")) {
  202. // If bank module is on, account is required to enter a payment
  203. if (GETPOST('accountid') <= 0) {
  204. setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors');
  205. $error++;
  206. }
  207. }
  208. if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) {
  209. setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors');
  210. $error++;
  211. }
  212. if (empty($datepaye)) {
  213. setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors');
  214. $error++;
  215. }
  216. // Check if payments in both currency
  217. if ($totalpayment > 0 && $multicurrency_totalpayment > 0) {
  218. setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors');
  219. $error++;
  220. }
  221. }
  222. /*
  223. * Action add_paiement
  224. */
  225. if ($action == 'add_paiement') {
  226. if ($error) {
  227. $action = 'create';
  228. }
  229. // All the next of this action is displayed at the page's bottom.
  230. }
  231. /*
  232. * Action confirm_paiement
  233. */
  234. if ($action == 'confirm_paiement' && $confirm == 'yes') {
  235. $error = 0;
  236. $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  237. $multicurrency_code = array();
  238. $multicurrency_tx = array();
  239. // Clean parameters amount if payment is for a credit note
  240. foreach ($amounts as $key => $value) { // How payment is dispatched
  241. $tmpinvoice = new FactureFournisseur($db);
  242. $tmpinvoice->fetch($key);
  243. if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  244. $newvalue = price2num($value, 'MT');
  245. $amounts[$key] = - abs($newvalue);
  246. }
  247. $multicurrency_code[$key] = $tmpinvoice->multicurrency_code;
  248. $multicurrency_tx[$key] = $tmpinvoice->multicurrency_tx;
  249. }
  250. foreach ($multicurrency_amounts as $key => $value) { // How payment is dispatched
  251. $tmpinvoice = new FactureFournisseur($db);
  252. $tmpinvoice->fetch($key);
  253. if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  254. $newvalue = price2num($value, 'MT');
  255. $multicurrency_amounts[$key] = - abs($newvalue);
  256. }
  257. $multicurrency_code[$key] = $tmpinvoice->multicurrency_code;
  258. $multicurrency_tx[$key] = $tmpinvoice->multicurrency_tx;
  259. }
  260. //var_dump($amounts);
  261. //var_dump($multicurrency_amounts);
  262. //exit;
  263. if (!$error) {
  264. $db->begin();
  265. $thirdparty = new Societe($db);
  266. if ($socid > 0) {
  267. $thirdparty->fetch($socid);
  268. }
  269. // Creation of payment line
  270. $paiement = new PaiementFourn($db);
  271. $paiement->datepaye = $datepaye;
  272. $paiement->amounts = $amounts; // Array of amounts
  273. $paiement->multicurrency_amounts = $multicurrency_amounts;
  274. $paiement->multicurrency_code = $multicurrency_code; // Array with all currency of payments dispatching
  275. $paiement->multicurrency_tx = $multicurrency_tx; // Array with all currency tx of payments dispatching
  276. $paiement->paiementid = GETPOST('paiementid', 'int');
  277. $paiement->num_payment = GETPOST('num_paiement', 'alphanohtml');
  278. $paiement->note_private = GETPOST('comment', 'alpha');
  279. $paiement->fk_account = GETPOST('accountid', 'int');
  280. if (!$error) {
  281. // Create payment and update this->multicurrency_amounts if this->amounts filled or
  282. // this->amounts if this->multicurrency_amounts filled.
  283. // This also set ->amount and ->multicurrency_amount
  284. $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty);
  285. if ($paiement_id < 0) {
  286. setEventMessages($paiement->error, $paiement->errors, 'errors');
  287. $error++;
  288. }
  289. }
  290. if (!$error) {
  291. $result = $paiement->addPaymentToBank($user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, GETPOST('chqemetteur'), GETPOST('chqbank'));
  292. if ($result < 0) {
  293. setEventMessages($paiement->error, $paiement->errors, 'errors');
  294. $error++;
  295. }
  296. }
  297. if (!$error) {
  298. $db->commit();
  299. // If payment dispatching on more than one invoice, we stay on summary page, otherwise go on invoice card
  300. $invoiceid = 0;
  301. foreach ($paiement->amounts as $key => $amount) {
  302. $facid = $key;
  303. if (is_numeric($amount) && $amount <> 0) {
  304. if ($invoiceid != 0) {
  305. $invoiceid = -1; // There is more than one invoice payed by this payment
  306. } else {
  307. $invoiceid = $facid;
  308. }
  309. }
  310. }
  311. if ($invoiceid > 0) {
  312. $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid;
  313. } else {
  314. $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id;
  315. }
  316. header('Location: '.$loc);
  317. exit;
  318. } else {
  319. $db->rollback();
  320. }
  321. }
  322. }
  323. }
  324. /*
  325. * View
  326. */
  327. $form = new Form($db);
  328. $formother = new FormOther($db);
  329. $supplierstatic = new Societe($db);
  330. $invoicesupplierstatic = new FactureFournisseur($db);
  331. llxHeader('', $langs->trans('ListPayment'));
  332. if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') {
  333. $object = new FactureFournisseur($db);
  334. $result = $object->fetch($facid);
  335. $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  336. $dateinvoice = ($datefacture == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datefacture);
  337. $sql = 'SELECT s.nom as name, s.rowid as socid,';
  338. $sql .= ' f.rowid, f.ref, f.ref_supplier, f.total_ttc as total, f.fk_mode_reglement, f.fk_account';
  339. if (empty($user->rights->societe->client->voir) && !$socid) {
  340. $sql .= ", sc.fk_soc, sc.fk_user ";
  341. }
  342. $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f';
  343. if (empty($user->rights->societe->client->voir) && !$socid) {
  344. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  345. }
  346. $sql .= ' WHERE f.fk_soc = s.rowid';
  347. $sql .= ' AND f.rowid = '.((int) $facid);
  348. if (empty($user->rights->societe->client->voir) && !$socid) {
  349. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  350. }
  351. $resql = $db->query($sql);
  352. if ($resql) {
  353. $num = $db->num_rows($resql);
  354. if ($num) {
  355. $obj = $db->fetch_object($resql);
  356. $total = $obj->total;
  357. print load_fiche_titre($langs->trans('DoPayment'));
  358. // Add realtime total information
  359. if (!empty($conf->use_javascript_ajax)) {
  360. print "\n".'<script type="text/javascript">';
  361. print '$(document).ready(function () {
  362. function _elemToJson(selector)
  363. {
  364. var subJson = {};
  365. $.map(selector.serializeArray(), function(n,i)
  366. {
  367. subJson[n["name"]] = n["value"];
  368. });
  369. return subJson;
  370. }
  371. function callForResult(imgId)
  372. {
  373. console.log("callForResult Calculate total of payment");
  374. var json = {};
  375. var form = $("#payment_form");
  376. json["invoice_type"] = $("#invoice_type").val();
  377. json["amountPayment"] = $("#amountpayment").attr("value");
  378. json["amounts"] = _elemToJson(form.find("input.amount"));
  379. json["remains"] = _elemToJson(form.find("input.remain"));
  380. json["token"] = "'.currentToken().'";
  381. if (imgId != null) {
  382. json["imgClicked"] = imgId;
  383. }
  384. $.post("'.DOL_URL_ROOT.'/compta/ajaxpayment.php", json, function(data)
  385. {
  386. json = $.parseJSON(data);
  387. form.data(json);
  388. for (var key in json)
  389. {
  390. if (key == "result") {
  391. if (json["makeRed"]) {
  392. $("#"+key).addClass("error");
  393. } else {
  394. $("#"+key).removeClass("error");
  395. }
  396. json[key]=json["label"]+" "+json[key];
  397. $("#"+key).text(json[key]);
  398. } else {console.log(key);
  399. form.find("input[name*=\""+key+"\"]").each(function() {
  400. $(this).attr("value", json[key]);
  401. });
  402. }
  403. }
  404. });
  405. }
  406. callForResult();
  407. $("#payment_form").find("input.amount").change(function() {
  408. callForResult();
  409. });
  410. $("#payment_form").find("input.amount").keyup(function() {
  411. callForResult();
  412. });
  413. ';
  414. print ' });'."\n";
  415. //Add js for AutoFill
  416. print ' $(document).ready(function () {';
  417. print ' $(".AutoFillAmout").on(\'click touchstart\', function(){
  418. $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change");
  419. });';
  420. print ' });'."\n";
  421. print ' </script>'."\n";
  422. }
  423. print '<form id="payment_form" name="addpaiement" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  424. print '<input type="hidden" name="token" value="'.newToken().'">';
  425. print '<input type="hidden" name="action" value="add_paiement">';
  426. print '<input type="hidden" name="facid" value="'.$facid.'">';
  427. print '<input type="hidden" name="ref_supplier" value="'.$obj->ref_supplier.'">';
  428. print '<input type="hidden" name="socid" value="'.$obj->socid.'">';
  429. print '<input type="hidden" name="type" id="invoice_type" value="'.$object->type.'">';
  430. print '<input type="hidden" name="societe" value="'.$obj->name.'">';
  431. print dol_get_fiche_head(null);
  432. print '<table class="border centpercent">';
  433. print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans('Company').'</td><td>';
  434. $supplierstatic->id = $obj->socid;
  435. $supplierstatic->name = $obj->name;
  436. print $supplierstatic->getNomUrl(1, 'supplier');
  437. print '</td></tr>';
  438. print '<tr><td class="fieldrequired">'.$langs->trans('Date').'</td><td>';
  439. // $object is default vendor invoice
  440. $adddateof = array(array('adddateof'=>$object->date));
  441. $adddateof[] = array('adddateof'=>$object->date_echeance, 'labeladddateof'=>$langs->transnoentities('DateDue'));
  442. print $form->selectDate($dateinvoice, '', '', '', 0, "addpaiement", 1, 1, 0, '', '', $adddateof);
  443. print '</td></tr>';
  444. print '<tr><td class="fieldrequired">'.$langs->trans('PaymentMode').'</td><td>';
  445. $form->select_types_paiements(!GETPOST('paiementid') ? $obj->fk_mode_reglement : GETPOST('paiementid'), 'paiementid');
  446. print '</td>';
  447. if (isModEnabled("banque")) {
  448. print '<tr><td class="fieldrequired">'.$langs->trans('Account').'</td><td>';
  449. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  450. print $form->select_comptes(empty($accountid) ? $obj->fk_account : $accountid, 'accountid', 0, '', 2, '', 0, 'widthcentpercentminusx maxwidth500', 1);
  451. print '</td></tr>';
  452. } else {
  453. print '<tr><td>&nbsp;</td></tr>';
  454. }
  455. print '<tr><td>'.$langs->trans('Numero').'</td><td><input name="num_paiement" type="text" value="'.(!GETPOST('num_paiement') ? '' : GETPOST('num_paiement')).'"></td></tr>';
  456. print '<tr><td>'.$langs->trans('Comments').'</td>';
  457. print '<td class="tdtop">';
  458. print '<textarea name="comment" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.(!GETPOST('comment') ? '' : GETPOST('comment')).'</textarea></td></tr>';
  459. print '</table>';
  460. print dol_get_fiche_end();
  461. $parameters = array('facid'=>$facid, 'ref'=>$ref, 'objcanvas'=>$objcanvas);
  462. $reshook = $hookmanager->executeHooks('paymentsupplierinvoices', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  463. $error = $hookmanager->error; $errors = $hookmanager->errors;
  464. if (empty($reshook)) {
  465. /*
  466. * All unpaid supplier invoices
  467. */
  468. $sql = 'SELECT f.rowid as facid, f.ref, f.ref_supplier, f.type, f.total_ht, f.total_ttc,';
  469. $sql .= ' f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc,';
  470. $sql .= ' f.datef as df, f.date_lim_reglement as dlr,';
  471. $sql .= ' SUM(pf.amount) as am, SUM(pf.multicurrency_amount) as multicurrency_am';
  472. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as f';
  473. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid';
  474. $sql .= " WHERE f.entity = ".((int) $conf->entity);
  475. $sql .= ' AND f.fk_soc = '.((int) $object->socid);
  476. $sql .= ' AND f.paye = 0';
  477. $sql .= ' AND f.fk_statut = 1'; // Status=0 => unvalidated, Status=2 => canceled
  478. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) {
  479. $sql .= ' AND f.type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation
  480. } else {
  481. $sql .= ' AND f.type = 2'; // If paying back a credit note, we show all credit notes
  482. }
  483. // Group by because we have a total
  484. $sql .= ' GROUP BY f.datef, f.ref, f.ref_supplier, f.rowid, f.type, f.total_ht, f.total_ttc,';
  485. $sql .= ' f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc,';
  486. $sql .= ' f.datef, f.date_lim_reglement';
  487. // Sort invoices by date and serial number: the older one comes first
  488. $sql .= ' ORDER BY f.datef ASC, f.ref ASC';
  489. $resql = $db->query($sql);
  490. if ($resql) {
  491. $num = $db->num_rows($resql);
  492. if ($num > 0) {
  493. $i = 0;
  494. print '<br>';
  495. if (!empty($conf->use_javascript_ajax)) {
  496. //Add js for AutoFill
  497. print "\n".'<script type="text/javascript">';
  498. print ' $(document).ready(function () {';
  499. print ' $(".AutoFillAmout").on(\'click touchstart\', function(){
  500. $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value"));
  501. });';
  502. print ' });'."\n";
  503. print ' </script>'."\n";
  504. }
  505. print '<div class="div-table-responsive-no-min">';
  506. print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
  507. print '<tr class="liste_titre">';
  508. print '<td>'.$langs->trans('Invoice').'</td>';
  509. print '<td>'.$langs->trans('RefSupplier').'</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">'.$langs->trans('MulticurrencyAlreadyPaid').'</td>';
  516. print '<td class="right">'.$langs->trans('MulticurrencyRemainderToPay').'</td>';
  517. print '<td class="center">'.$langs->trans('MulticurrencyPaymentAmount').'</td>';
  518. }
  519. print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
  520. print '<td class="right">'.$langs->trans('AlreadyPaid').'</td>';
  521. print '<td class="right">'.$langs->trans('RemainderToPay').'</td>';
  522. print '<td class="center">'.$langs->trans('PaymentAmount').'</td>';
  523. print '</tr>';
  524. $total = 0;
  525. $total_ttc = 0;
  526. $totalrecu = 0;
  527. while ($i < $num) {
  528. $objp = $db->fetch_object($resql);
  529. $sign = 1;
  530. if ($objp->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  531. $sign = -1;
  532. }
  533. $invoice = new FactureFournisseur($db);
  534. $invoice->fetch($objp->facid);
  535. $invoicesupplierstatic->ref = $objp->ref;
  536. $invoicesupplierstatic->id = $objp->facid;
  537. $paiement = $invoice->getSommePaiement();
  538. $creditnotes = $invoice->getSumCreditNotesUsed();
  539. $deposits = $invoice->getSumDepositsUsed();
  540. $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
  541. $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
  542. // Multicurrency Price
  543. if (isModEnabled("multicurrency")) {
  544. $multicurrency_payment = $invoice->getSommePaiement(1);
  545. $multicurrency_creditnotes = $invoice->getSumCreditNotesUsed(1);
  546. $multicurrency_deposits = $invoice->getSumDepositsUsed(1);
  547. $multicurrency_alreadypayed = price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits, 'MT');
  548. $multicurrency_remaintopay = price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits, 'MT');
  549. }
  550. print '<tr class="oddeven'.(($invoice->id == $facid) ? ' highlight' : '').'">';
  551. // Ref
  552. print '<td class="nowraponall">';
  553. print $invoicesupplierstatic->getNomUrl(1);
  554. print '</td>';
  555. // Ref supplier
  556. print '<td>'.$objp->ref_supplier.'</td>';
  557. // Date
  558. if ($objp->df > 0) {
  559. print '<td class="center nowraponall">';
  560. print dol_print_date($db->jdate($objp->df), 'day').'</td>';
  561. } else {
  562. print '<td class="center"><b>!!!</b></td>';
  563. }
  564. // Date Max Payment
  565. if ($objp->dlr > 0) {
  566. print '<td class="center nowraponall">';
  567. print dol_print_date($db->jdate($objp->dlr), 'day');
  568. if ($invoice->hasDelay()) {
  569. print img_warning($langs->trans('Late'));
  570. }
  571. print '</td>';
  572. } else {
  573. print '<td class="center"><b>--</b></td>';
  574. }
  575. // Multicurrency
  576. if (isModEnabled("multicurrency")) {
  577. // Currency
  578. print '<td class="center">'.$objp->multicurrency_code."</td>\n";
  579. print '<td class="right">';
  580. if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) {
  581. print price($objp->multicurrency_total_ttc);
  582. }
  583. print '</td>';
  584. print '<td class="right">';
  585. if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) {
  586. print price($sign * $multicurrency_payment);
  587. if ($multicurrency_creditnotes) {
  588. print '+'.price($multicurrency_creditnotes);
  589. }
  590. if ($multicurrency_deposits) {
  591. print '+'.price($multicurrency_deposits);
  592. }
  593. }
  594. print '</td>';
  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">';
  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=hidden class="multicurrency_remain" name="'.$nameRemain.'" value="'.$multicurrency_remaintopay.'">';
  610. print '<input type="text" size="8" class="multicurrency_amount" name="'.$namef.'" value="'.GETPOST($namef).'">';
  611. } else {
  612. print '<input type="text" size="8" name="'.$namef.'_disabled" value="'.GETPOST($namef).'" disabled>';
  613. print '<input type="hidden" name="'.$namef.'" value="'.GETPOST($namef).'">';
  614. }
  615. }
  616. print "</td>";
  617. }
  618. print '<td class="right">'.price($sign * $objp->total_ttc).'</td>';
  619. print '<td class="right">'.price($sign * $objp->am);
  620. if ($creditnotes) {
  621. print '+'.price($creditnotes);
  622. }
  623. if ($deposits) {
  624. print '+'.price($deposits);
  625. }
  626. print '</td>';
  627. print '<td class="right">';
  628. print price($sign * $remaintopay);
  629. if (isModEnabled('paymentbybanktransfer')) {
  630. $numdirectdebitopen = 0;
  631. $totaldirectdebit = 0;
  632. $sql = "SELECT COUNT(pfd.rowid) as nb, SUM(pfd.amount) as amount";
  633. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pfd";
  634. $sql .= " WHERE fk_facture_fourn = ".((int) $objp->facid);
  635. $sql .= " AND pfd.traite = 0";
  636. $sql .= " AND pfd.ext_payment_id IS NULL";
  637. $result_sql = $db->query($sql);
  638. if ($result_sql) {
  639. $obj = $db->fetch_object($result_sql);
  640. $numdirectdebitopen = $obj->nb;
  641. $totaldirectdebit = $obj->amount;
  642. } else {
  643. dol_print_error($db);
  644. }
  645. if ($numdirectdebitopen) {
  646. $langs->load("withdrawals");
  647. print img_warning($langs->trans("WarningSomeCreditTransferAlreadyExists", $numdirectdebitopen, price(price2num($totaldirectdebit, 'MT'), 0, $langs, 1, -1, -1, $conf->currency)), '', 'classfortooltip');
  648. }
  649. }
  650. print '</td>';
  651. // Amount
  652. print '<td class="center nowraponall">';
  653. $namef = 'amount_'.$objp->facid;
  654. $nameRemain = 'remain_'.$objp->facid;
  655. if ($action != 'add_paiement') {
  656. if (!empty($conf->use_javascript_ajax)) {
  657. print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'");
  658. }
  659. print '<input type="hidden" class="remain" name="'.$nameRemain.'" value="'.$remaintopay.'">';
  660. print '<input type="text" size="8" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">'; // class is requied to be used by javascript callForResult();
  661. } else {
  662. print '<input type="text" size="8" name="'.$namef.'_disabled" value="'.dol_escape_htmltag(GETPOST($namef)).'" disabled>';
  663. print '<input type="hidden" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">'; // class is requied to be used by javascript callForResult();
  664. }
  665. print "</td>";
  666. print "</tr>\n";
  667. $total += $objp->total_ht;
  668. $total_ttc += $objp->total_ttc;
  669. $totalrecu += $objp->am;
  670. $totalrecucreditnote += $creditnotes;
  671. $totalrecudeposits += $deposits;
  672. $i++;
  673. }
  674. if ($i > 1) {
  675. // Print total
  676. print '<tr class="liste_total">';
  677. print '<td colspan="4" class="left">'.$langs->trans('TotalTTC').':</td>';
  678. if (isModEnabled("multicurrency")) {
  679. print '<td>&nbsp;</td>';
  680. print '<td>&nbsp;</td>';
  681. print '<td>&nbsp;</td>';
  682. print '<td>&nbsp;</td>';
  683. print '<td class="right" id="multicurrency_result" style="font-weight: bold;"></td>';
  684. }
  685. print '<td class="right"><b>'.price($sign * $total_ttc).'</b></td>';
  686. print '<td class="right"><b>'.price($sign * $totalrecu);
  687. if ($totalrecucreditnote) {
  688. print '+'.price($totalrecucreditnote);
  689. }
  690. if ($totalrecudeposits) {
  691. print '+'.price($totalrecudeposits);
  692. }
  693. print '</b></td>';
  694. print '<td class="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'</b></td>';
  695. print '<td class="center" id="result" style="font-weight: bold;"></td>'; // Autofilled
  696. print "</tr>\n";
  697. }
  698. print "</table>\n";
  699. print "</div>";
  700. }
  701. $db->free($resql);
  702. } else {
  703. dol_print_error($db);
  704. }
  705. }
  706. // Save + Cancel Buttons
  707. if ($action != 'add_paiement') {
  708. print '<br><div class="center">';
  709. print '<input type="checkbox" checked id="closepaidinvoices" name="closepaidinvoices"> <label for="closepaidinvoices">'.$langs->trans("ClosePaidInvoicesAutomatically").'</label><br>';
  710. print '<input type="submit" class="button" value="'.$langs->trans('ToMakePayment').'">';
  711. print ' &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  712. print '</div>';
  713. }
  714. // Form to confirm payment
  715. if ($action == 'add_paiement') {
  716. $preselectedchoice = $addwarning ? 'no' : 'yes';
  717. print '<br>';
  718. if (!empty($totalpayment)) {
  719. $text = $langs->trans('ConfirmSupplierPayment', price($totalpayment), $langs->trans("Currency".$conf->currency));
  720. }
  721. if (!empty($multicurrency_totalpayment)) {
  722. $text .= '<br>'.$langs->trans('ConfirmSupplierPayment', price($multicurrency_totalpayment), $langs->trans("paymentInInvoiceCurrency"));
  723. }
  724. if (GETPOST('closepaidinvoices')) {
  725. $text .= '<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
  726. print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">';
  727. }
  728. print $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$facture->id.'&socid='.$facture->socid.'&type='.$facture->type, $langs->trans('PayedSuppliersPayments'), $text, 'confirm_paiement', $formquestion, $preselectedchoice);
  729. }
  730. print '</form>';
  731. }
  732. } else {
  733. dol_print_error($db);
  734. }
  735. }
  736. // End of page
  737. llxFooter();
  738. $db->close();