paiement.php 32 KB

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