paiement.php 31 KB

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