paiement.php 31 KB

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