paiement.class.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. <?php
  2. /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  5. * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
  6. * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  7. * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2015 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  10. * Copyright (C) 2018 Thibault FOUCART <support@ptibogxiv.net>
  11. * Copyright (C) 2018-2022 Frédéric France <frederic.france@netlogic.fr>
  12. * Copyright (C) 2020 Andreu Bisquerra Gaya <jove@bisquerra.com>
  13. * Copyright (C) 2021 OpenDsi <support@open-dsi.fr>
  14. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  15. * Copyright (C) 2023 Sylvain Legrand <technique@infras.fr>
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation; either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  29. */
  30. /**
  31. * \file htdocs/compta/paiement/class/paiement.class.php
  32. * \ingroup facture
  33. * \brief File of class to manage payments of customers invoices
  34. */
  35. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  37. /**
  38. * Class to manage payments of customer invoices
  39. */
  40. class Paiement extends CommonObject
  41. {
  42. /**
  43. * @var string ID to identify managed object
  44. */
  45. public $element = 'payment';
  46. /**
  47. * @var string Name of table without prefix where object is stored
  48. */
  49. public $table_element = 'paiement';
  50. /**
  51. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  52. */
  53. public $picto = 'payment';
  54. public $facid;
  55. public $socid;
  56. public $datepaye;
  57. public $date; // same than $datepaye
  58. /**
  59. * @deprecated
  60. * @see $amount, $amounts
  61. */
  62. public $total;
  63. /**
  64. * @deprecated
  65. * @see $amount, $amounts
  66. */
  67. public $montant;
  68. public $amount; // Total amount of payment (in the main currency)
  69. public $multicurrency_amount; // Total amount of payment (in the currency of the bank account)
  70. public $amounts = array(); // array: invoice ID => amount for that invoice (in the main currency)
  71. public $multicurrency_amounts = array(); // array: invoice ID => amount for that invoice (in the invoice's currency)
  72. public $multicurrency_tx = array(); // array: invoice ID => currency tx for that invoice
  73. public $multicurrency_code = array(); // array: invoice ID => currency code for that invoice
  74. public $pos_change = 0; // Excess received in TakePOS cash payment
  75. public $author;
  76. public $paiementid; // ID of mode of payment. Is saved into fields fk_paiement on llx_paiement = id of llx_c_paiement
  77. public $paiementcode; // Code of mode of payment.
  78. /**
  79. * @var string Type of payment label
  80. */
  81. public $type_label;
  82. /**
  83. * @var string Type of payment code (seems duplicate with $paiementcode);
  84. */
  85. public $type_code;
  86. /**
  87. * @var string Numero du CHQ, VIR, etc...
  88. * @deprecated
  89. * @see $num_payment
  90. */
  91. public $num_paiement;
  92. /**
  93. * @var string Numero du CHQ, VIR, etc...
  94. */
  95. public $num_payment;
  96. /**
  97. * @var string Id of external payment mode
  98. */
  99. public $ext_payment_id;
  100. /**
  101. * @var string Id of prelevement
  102. */
  103. public $id_prelevement;
  104. /**
  105. * @var string num_prelevement
  106. */
  107. public $num_prelevement;
  108. /**
  109. * @var string Name of external payment mode
  110. */
  111. public $ext_payment_site;
  112. /**
  113. * @var int bank account id of payment
  114. * @deprecated
  115. * @see $fk_account
  116. */
  117. public $bank_account;
  118. /**
  119. * @var int bank account id of payment
  120. */
  121. public $fk_account;
  122. /**
  123. * @var int id of payment line in bank account
  124. */
  125. public $bank_line;
  126. // fk_paiement dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...)
  127. // fk_paiement dans llx_paiement_facture est le rowid du paiement
  128. /**
  129. * @var int payment id
  130. */
  131. public $fk_paiement; // Type of payment
  132. /**
  133. * @var string payment external reference
  134. */
  135. public $ref_ext;
  136. /**
  137. * Constructor
  138. *
  139. * @param DoliDB $db Database handler
  140. */
  141. public function __construct($db)
  142. {
  143. $this->db = $db;
  144. }
  145. /**
  146. * Load payment from database
  147. *
  148. * @param int $id Id of payment to get
  149. * @param string $ref Ref of payment to get (currently ref = id but this may change in future)
  150. * @param int $fk_bank Id of bank line associated to payment
  151. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  152. */
  153. public function fetch($id, $ref = '', $fk_bank = 0)
  154. {
  155. $sql = 'SELECT p.rowid, p.ref, p.ref_ext, p.datep as dp, p.amount, p.statut, p.ext_payment_id, p.ext_payment_site, p.fk_bank, p.multicurrency_amount,';
  156. $sql .= ' c.code as type_code, c.libelle as type_label,';
  157. $sql .= ' p.num_paiement as num_payment, p.note,';
  158. $sql .= ' b.fk_account';
  159. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  160. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
  161. $sql .= ' WHERE p.entity IN ('.getEntity('invoice').')';
  162. if ($id > 0) {
  163. $sql .= ' AND p.rowid = '.((int) $id);
  164. } elseif ($ref) {
  165. $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
  166. } elseif ($fk_bank) {
  167. $sql .= ' AND p.fk_bank = '.((int) $fk_bank);
  168. }
  169. $resql = $this->db->query($sql);
  170. if ($resql) {
  171. if ($this->db->num_rows($resql)) {
  172. $obj = $this->db->fetch_object($resql);
  173. $this->id = $obj->rowid;
  174. $this->ref = $obj->ref ? $obj->ref : $obj->rowid;
  175. $this->ref_ext = $obj->ref_ext;
  176. $this->date = $this->db->jdate($obj->dp);
  177. $this->datepaye = $this->db->jdate($obj->dp);
  178. $this->num_payment = $obj->num_payment;
  179. $this->montant = $obj->amount; // deprecated
  180. $this->amount = $obj->amount;
  181. $this->multicurrency_amount = $obj->multicurrency_amount;
  182. $this->note = $obj->note;
  183. $this->note_private = $obj->note;
  184. $this->type_label = $obj->type_label;
  185. $this->type_code = $obj->type_code;
  186. $this->statut = $obj->statut;
  187. $this->ext_payment_id = $obj->ext_payment_id;
  188. $this->ext_payment_site = $obj->ext_payment_site;
  189. $this->bank_account = $obj->fk_account; // deprecated
  190. $this->fk_account = $obj->fk_account;
  191. $this->bank_line = $obj->fk_bank;
  192. $this->db->free($resql);
  193. return 1;
  194. } else {
  195. $this->db->free($resql);
  196. return 0;
  197. }
  198. } else {
  199. dol_print_error($this->db);
  200. return -1;
  201. }
  202. }
  203. /**
  204. * Create payment of invoices into database.
  205. * Use this->amounts to have list of invoices for the payment.
  206. * For payment of a customer invoice, amounts are positive, for payment of credit note, amounts are negative
  207. *
  208. * @param User $user Object user
  209. * @param int $closepaidinvoices 1=Also close payed invoices to paid, 0=Do nothing more
  210. * @param Societe $thirdparty Thirdparty
  211. * @return int id of created payment, < 0 if error
  212. */
  213. public function create($user, $closepaidinvoices = 0, $thirdparty = null)
  214. {
  215. global $conf, $langs;
  216. $error = 0;
  217. $way = $this->getWay(); // 'dolibarr' to use amount, 'customer' to use foreign multicurrency amount
  218. $now = dol_now();
  219. // Clean parameters
  220. $totalamount = 0;
  221. $totalamount_converted = 0;
  222. $atleastonepaymentnotnull = 0;
  223. if ($way == 'dolibarr') { // Payments were entered into the column of main currency
  224. $amounts = &$this->amounts;
  225. $amounts_to_update = &$this->multicurrency_amounts;
  226. } else { // Payments were entered into the column of foreign currency
  227. $amounts = &$this->multicurrency_amounts;
  228. $amounts_to_update = &$this->amounts;
  229. }
  230. $currencyofpayment = '';
  231. $currencytxofpayment = '';
  232. foreach ($amounts as $key => $value) { // How payment is dispatched
  233. if (empty($value)) {
  234. continue;
  235. }
  236. // $key is id of invoice, $value is amount, $way is a 'dolibarr' if amount is in main currency, 'customer' if in foreign currency
  237. $value_converted = MultiCurrency::getAmountConversionFromInvoiceRate($key, $value, $way);
  238. // Add controls of input validity
  239. if ($value_converted === false) {
  240. // We failed to find the conversion for one invoice
  241. $this->error = $langs->trans('FailedToFoundTheConversionRateForInvoice');
  242. return -1;
  243. }
  244. if (empty($currencyofpayment)) {
  245. $currencyofpayment = isset($this->multicurrency_code[$key]) ? $this->multicurrency_code[$key] : "";
  246. } elseif ($currencyofpayment != $this->multicurrency_code[$key]) {
  247. // If we have invoices with different currencies in the payment, we stop here
  248. $this->error = 'ErrorYouTryToPayInvoicesWithDifferentCurrenciesInSamePayment';
  249. return -1;
  250. }
  251. if (empty($currencytxofpayment)) {
  252. $currencytxofpayment = isset($this->multicurrency_tx[$key]) ? $this->multicurrency_tx[$key] : "";
  253. }
  254. $totalamount_converted += $value_converted;
  255. $amounts_to_update[$key] = price2num($value_converted, 'MT');
  256. $newvalue = price2num($value, 'MT');
  257. $amounts[$key] = $newvalue;
  258. $totalamount += $newvalue;
  259. if (!empty($newvalue)) {
  260. $atleastonepaymentnotnull++;
  261. }
  262. }
  263. if (empty($currencyofpayment)) { // Should not happen. For the case the multicurrency_code was not saved into invoices
  264. $currencyofpayment = $conf->currency;
  265. }
  266. if (!empty($currencyofpayment)) {
  267. // We must check that the currency of invoices is the same than the currency of the bank
  268. include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  269. $bankaccount = new Account($this->db);
  270. $bankaccount->fetch($this->fk_account);
  271. $bankcurrencycode = empty($bankaccount->currency_code) ? $conf->currency : $bankaccount->currency_code;
  272. if ($currencyofpayment != $bankcurrencycode && $currencyofpayment != $conf->currency && $bankcurrencycode != $conf->currency) {
  273. $langs->load("errors");
  274. $this->error = $langs->trans('ErrorYouTryToPayInvoicesInACurrencyFromBankWithAnotherCurrency', $currencyofpayment, $bankcurrencycode);
  275. return -1;
  276. }
  277. }
  278. $totalamount = price2num($totalamount);
  279. $totalamount_converted = price2num($totalamount_converted);
  280. // Check parameters
  281. if (empty($totalamount) && empty($atleastonepaymentnotnull)) { // We accept negative amounts for withdraw reject but not empty arrays
  282. $this->errors[] = 'TotalAmountEmpty';
  283. $this->error = $langs->trans('TotalAmountEmpty');
  284. return -1;
  285. }
  286. dol_syslog(get_class($this)."::create insert paiement (closepaidinvoices = ".$closepaidinvoices.")", LOG_DEBUG);
  287. $this->db->begin();
  288. $this->ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : '');
  289. if (empty($this->ref_ext)) {
  290. $this->ref_ext = '';
  291. }
  292. if ($way == 'dolibarr') {
  293. $total = $totalamount;
  294. $mtotal = $totalamount_converted; // Maybe use price2num with MT for the converted value
  295. } else {
  296. $total = $totalamount_converted; // Maybe use price2num with MT for the converted value
  297. $mtotal = $totalamount;
  298. }
  299. $num_payment = $this->num_payment;
  300. $note = ($this->note_private ? $this->note_private : $this->note);
  301. $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, ref, ref_ext, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, ext_payment_id, ext_payment_site, fk_user_creat, pos_change)";
  302. $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', ".((float) $total).", ".((float) $mtotal).", ".((int) $this->paiementid).", ";
  303. $sql .= "'".$this->db->escape($num_payment)."', '".$this->db->escape($note)."', ".($this->ext_payment_id ? "'".$this->db->escape($this->ext_payment_id)."'" : "null").", ".($this->ext_payment_site ? "'".$this->db->escape($this->ext_payment_site)."'" : "null").", ".((int) $user->id).", ".((float) $this->pos_change).")";
  304. $resql = $this->db->query($sql);
  305. if ($resql) {
  306. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');
  307. // Insert links amount / invoices
  308. foreach ($this->amounts as $key => $amount) {
  309. $facid = $key;
  310. if (is_numeric($amount) && $amount != 0) {
  311. $amount = price2num($amount);
  312. $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount, multicurrency_amount, multicurrency_code, multicurrency_tx)";
  313. $sql .= " VALUES (".((int) $facid).", ".((int) $this->id).", ".((float) $amount).", ".((float) $this->multicurrency_amounts[$key]).", ".($currencyofpayment ? "'".$this->db->escape($currencyofpayment)."'" : 'NULL').", ".(!empty($this->multicurrency_tx) ? (float) $currencytxofpayment : 1).")";
  314. dol_syslog(get_class($this).'::create Amount line '.$key.' insert paiement_facture', LOG_DEBUG);
  315. $resql = $this->db->query($sql);
  316. if ($resql) {
  317. $invoice = new Facture($this->db);
  318. $invoice->fetch($facid);
  319. // If we want to closed payed invoices
  320. if ($closepaidinvoices) {
  321. $paiement = $invoice->getSommePaiement();
  322. $creditnotes = $invoice->getSumCreditNotesUsed();
  323. $deposits = $invoice->getSumDepositsUsed();
  324. $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
  325. $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
  326. //var_dump($invoice->total_ttc.' - '.$paiement.' -'.$creditnotes.' - '.$deposits.' - '.$remaintopay);exit;
  327. //Invoice types that are eligible for changing status to paid
  328. $affected_types = array(
  329. Facture::TYPE_STANDARD,
  330. Facture::TYPE_REPLACEMENT,
  331. Facture::TYPE_CREDIT_NOTE,
  332. Facture::TYPE_DEPOSIT,
  333. Facture::TYPE_SITUATION
  334. );
  335. if (!in_array($invoice->type, $affected_types)) {
  336. dol_syslog("Invoice ".$facid." is not a standard, nor replacement invoice, nor credit note, nor deposit invoice, nor situation invoice. We do nothing more.");
  337. } elseif ($remaintopay) {
  338. // hook to have an option to automatically close a closable invoice with less payment than the total amount (e.g. agreed cash discount terms)
  339. global $hookmanager;
  340. $hookmanager->initHooks(array('paymentdao'));
  341. $parameters = array('facid' => $facid, 'invoice' => $invoice, 'remaintopay' => $remaintopay);
  342. $action = 'CLOSEPAIDINVOICE';
  343. $reshook = $hookmanager->executeHooks('createPayment', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  344. if ($reshook < 0) {
  345. $this->errors[] = $hookmanager->error;
  346. $this->error = $hookmanager->error;
  347. $error++;
  348. } elseif ($reshook == 0) {
  349. dol_syslog("Remain to pay for invoice " . $facid . " not null. We do nothing more.");
  350. }
  351. // } else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
  352. } else {
  353. // If invoice is a down payment, we also convert down payment to discount
  354. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  355. $amount_ht = $amount_tva = $amount_ttc = array();
  356. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  357. // Insert one discount by VAT rate category
  358. $discount = new DiscountAbsolute($this->db);
  359. $discount->fetch('', $invoice->id);
  360. if (empty($discount->id)) { // If the invoice was not yet converted into a discount (this may have been done manually before we come here)
  361. $discount->description = '(DEPOSIT)';
  362. $discount->fk_soc = $invoice->socid;
  363. $discount->fk_facture_source = $invoice->id;
  364. // Loop on each vat rate
  365. $i = 0;
  366. foreach ($invoice->lines as $line) {
  367. if ($line->total_ht != 0) { // no need to create discount if amount is null
  368. $amount_ht[$line->tva_tx] += $line->total_ht;
  369. $amount_tva[$line->tva_tx] += $line->total_tva;
  370. $amount_ttc[$line->tva_tx] += $line->total_ttc;
  371. $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
  372. $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
  373. $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
  374. $i++;
  375. }
  376. }
  377. foreach ($amount_ht as $tva_tx => $xxx) {
  378. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  379. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  380. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  381. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  382. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  383. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  384. $discount->tva_tx = abs($tva_tx);
  385. $result = $discount->create($user);
  386. if ($result < 0) {
  387. $error++;
  388. break;
  389. }
  390. }
  391. }
  392. if ($error) {
  393. $this->error = $discount->error;
  394. $this->errors = $discount->errors;
  395. $error++;
  396. }
  397. }
  398. // Set invoice to paid
  399. if (!$error) {
  400. $result = $invoice->setPaid($user, '', '');
  401. if ($result < 0) {
  402. $this->error = $invoice->error;
  403. $this->errors = $invoice->errors;
  404. $error++;
  405. }
  406. }
  407. }
  408. }
  409. // Regenerate documents of invoices
  410. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  411. dol_syslog(get_class($this).'::create Regenerate the document after inserting payment for thirdparty default_lang='.(is_object($invoice->thirdparty) ? $invoice->thirdparty->default_lang : 'null'), LOG_DEBUG);
  412. $newlang = '';
  413. $outputlangs = $langs;
  414. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  415. $invoice->fetch_thirdparty();
  416. $newlang = $invoice->thirdparty->default_lang;
  417. }
  418. if (!empty($newlang)) {
  419. $outputlangs = new Translate("", $conf);
  420. $outputlangs->setDefaultLang($newlang);
  421. }
  422. $hidedetails = getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0;
  423. $hidedesc = getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0;
  424. $hideref = getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0;
  425. $ret = $invoice->fetch($facid); // Reload to get new records
  426. $result = $invoice->generateDocument($invoice->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  427. dol_syslog(get_class($this).'::create Regenerate end result='.$result, LOG_DEBUG);
  428. if ($result < 0) {
  429. $this->error = $invoice->error;
  430. $this->errors = $invoice->errors;
  431. $error++;
  432. }
  433. }
  434. } else {
  435. $this->error = $this->db->lasterror();
  436. $error++;
  437. }
  438. } else {
  439. dol_syslog(get_class($this).'::Create Amount line '.$key.' not a number. We discard it.');
  440. }
  441. }
  442. dol_syslog(get_class($this).'::create Now we call the triggers if no error (error = '.$error.')', LOG_DEBUG);
  443. if (!$error) { // All payments into $this->amounts were recorded without errors
  444. // Appel des triggers
  445. $result = $this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user);
  446. if ($result < 0) {
  447. $error++;
  448. }
  449. // Fin appel triggers
  450. }
  451. } else {
  452. $this->error = $this->db->lasterror();
  453. $error++;
  454. }
  455. if (!$error) {
  456. $this->amount = $total;
  457. $this->total = $total; // deprecated
  458. $this->multicurrency_amount = $mtotal;
  459. $this->db->commit();
  460. return $this->id;
  461. } else {
  462. $this->db->rollback();
  463. return -1;
  464. }
  465. }
  466. /**
  467. * Delete a payment and generated links into account
  468. * - Si le paiement porte sur un ecriture compte qui est rapprochee, on refuse
  469. * - Si le paiement porte sur au moins une facture a "payee", on refuse
  470. * @TODO Add first param User $user
  471. *
  472. * @param int $notrigger No trigger
  473. * @return int Return integer <0 if KO, >0 if OK
  474. */
  475. public function delete($notrigger = 0)
  476. {
  477. global $user;
  478. $error = 0;
  479. $bank_line_id = $this->bank_line;
  480. $this->db->begin();
  481. // Verifier si paiement porte pas sur une facture classee
  482. // Si c'est le cas, on refuse la suppression
  483. $billsarray = $this->getBillsArray('f.fk_statut > 1');
  484. if (is_array($billsarray)) {
  485. if (count($billsarray)) {
  486. $this->error = "ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible";
  487. $this->db->rollback();
  488. return -1;
  489. }
  490. } else {
  491. $this->db->rollback();
  492. return -2;
  493. }
  494. // Delete bank urls. If payment is on a conciliated line, return error.
  495. if ($bank_line_id > 0) {
  496. $accline = new AccountLine($this->db);
  497. $result = $accline->fetch($bank_line_id);
  498. if ($result == 0) {
  499. $accline->id = $accline->rowid = $bank_line_id; // If not found, we set artificially rowid to allow delete of llx_bank_url
  500. }
  501. // Delete bank account url lines linked to payment
  502. $result = $accline->delete_urls($user);
  503. if ($result < 0) {
  504. $this->error = $accline->error;
  505. $this->db->rollback();
  506. return -3;
  507. }
  508. // Delete bank account lines linked to payment
  509. $result = $accline->delete($user);
  510. if ($result < 0) {
  511. $this->error = $accline->error;
  512. $this->db->rollback();
  513. return -4;
  514. }
  515. }
  516. if (!$notrigger) {
  517. // Call triggers
  518. $result = $this->call_trigger('PAYMENT_CUSTOMER_DELETE', $user);
  519. if ($result < 0) {
  520. $this->db->rollback();
  521. return -1;
  522. }
  523. // End call triggers
  524. }
  525. // Delete payment (into paiement_facture and paiement)
  526. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement_facture';
  527. $sql .= ' WHERE fk_paiement = '.((int) $this->id);
  528. dol_syslog($sql);
  529. $result = $this->db->query($sql);
  530. if ($result) {
  531. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement';
  532. $sql .= " WHERE rowid = ".((int) $this->id);
  533. dol_syslog($sql);
  534. $result = $this->db->query($sql);
  535. if (!$result) {
  536. $this->error = $this->db->lasterror();
  537. $this->db->rollback();
  538. return -3;
  539. }
  540. $this->db->commit();
  541. return 1;
  542. } else {
  543. $this->error = $this->db->error;
  544. $this->db->rollback();
  545. return -5;
  546. }
  547. }
  548. /**
  549. * Add a record into bank for payment + links between this bank record and sources of payment.
  550. * All payment properties (this->amount, this->amounts, ...) must have been set first like after a call to create().
  551. *
  552. * @param User $user Object of user making payment
  553. * @param string $mode 'payment', 'payment_supplier'
  554. * @param string $label Label to use in bank record
  555. * @param int $accountid Id of bank account to do link with
  556. * @param string $emetteur_nom Name of transmitter
  557. * @param string $emetteur_banque Name of bank
  558. * @param int $notrigger No trigger
  559. * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on.
  560. * @param string $addbankurl 'direct-debit' or 'credit-transfer': Add another entry into bank_url.
  561. * @return int Return integer <0 if KO, bank_line_id if OK
  562. */
  563. public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger = 0, $accountancycode = '', $addbankurl = '')
  564. {
  565. global $conf, $user;
  566. $error = 0;
  567. $bank_line_id = 0;
  568. if (isModEnabled("banque")) {
  569. if ($accountid <= 0) {
  570. $this->error = 'Bad value for parameter accountid='.$accountid;
  571. dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR);
  572. return -1;
  573. }
  574. $this->fk_account = $accountid;
  575. dol_syslog("addPaymentToBank ".$user->id.", ".$mode.", ".$label.", ".$this->fk_account.", ".$emetteur_nom.", ".$emetteur_banque);
  576. include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  577. $acc = new Account($this->db);
  578. $result = $acc->fetch($this->fk_account);
  579. if ($result < 0) {
  580. $this->error = $acc->error;
  581. $this->errors = $acc->errors;
  582. $error++;
  583. return -1;
  584. }
  585. $this->db->begin();
  586. $totalamount = $this->amount;
  587. $totalamount_main_currency = null;
  588. if (empty($totalamount)) {
  589. $totalamount = $this->total; // For backward compatibility
  590. }
  591. // if dolibarr currency != bank currency then we received an amount in customer currency (currently I don't manage the case : my currency is USD, the customer currency is EUR and he paid me in GBP. Seems no sense for me)
  592. if (isModEnabled('multicurrency') && $conf->currency != $acc->currency_code) {
  593. $totalamount = $this->multicurrency_amount; // We will insert into llx_bank.amount in foreign currency
  594. $totalamount_main_currency = $this->amount; // We will also save the amount in main currency into column llx_bank.amount_main_currency
  595. }
  596. if ($mode == 'payment_supplier') {
  597. $totalamount = -$totalamount;
  598. if (isset($totalamount_main_currency)) {
  599. $totalamount_main_currency = -$totalamount_main_currency;
  600. }
  601. }
  602. // Insert payment into llx_bank
  603. $bank_line_id = $acc->addline(
  604. $this->datepaye,
  605. $this->paiementcode ? $this->paiementcode : $this->paiementid, // Payment mode code ('CB', 'CHQ' or 'VIR' for example). Use payment id if not defined for backward compatibility.
  606. $label,
  607. $totalamount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note)
  608. $this->num_payment,
  609. '',
  610. $user,
  611. $emetteur_nom,
  612. $emetteur_banque,
  613. $accountancycode,
  614. null,
  615. '',
  616. $totalamount_main_currency
  617. );
  618. // Mise a jour fk_bank dans llx_paiement
  619. // On connait ainsi le paiement qui a genere l'ecriture bancaire
  620. if ($bank_line_id > 0) {
  621. $result = $this->update_fk_bank($bank_line_id);
  622. if ($result <= 0) {
  623. $error++;
  624. dol_print_error($this->db);
  625. }
  626. // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction
  627. if (!$error) {
  628. $url = '';
  629. if ($mode == 'payment') {
  630. $url = DOL_URL_ROOT.'/compta/paiement/card.php?id=';
  631. }
  632. if ($mode == 'payment_supplier') {
  633. $url = DOL_URL_ROOT.'/fourn/paiement/card.php?id=';
  634. }
  635. if ($url) {
  636. $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode);
  637. if ($result <= 0) {
  638. $error++;
  639. dol_print_error($this->db);
  640. }
  641. }
  642. }
  643. // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
  644. if (!$error) {
  645. $linkaddedforthirdparty = array();
  646. foreach ($this->amounts as $key => $value) { // We should have invoices always for same third party but we loop in case of.
  647. if ($mode == 'payment') {
  648. $fac = new Facture($this->db);
  649. $fac->fetch($key);
  650. $fac->fetch_thirdparty();
  651. if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty
  652. $result = $acc->add_url_line(
  653. $bank_line_id,
  654. $fac->thirdparty->id,
  655. DOL_URL_ROOT.'/comm/card.php?socid=',
  656. $fac->thirdparty->name,
  657. 'company'
  658. );
  659. if ($result <= 0) {
  660. dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
  661. }
  662. $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty
  663. }
  664. }
  665. if ($mode == 'payment_supplier') {
  666. $fac = new FactureFournisseur($this->db);
  667. $fac->fetch($key);
  668. $fac->fetch_thirdparty();
  669. if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty
  670. $result = $acc->add_url_line(
  671. $bank_line_id,
  672. $fac->thirdparty->id,
  673. DOL_URL_ROOT.'/fourn/card.php?socid=',
  674. $fac->thirdparty->name,
  675. 'company'
  676. );
  677. if ($result <= 0) {
  678. dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
  679. }
  680. $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty
  681. }
  682. }
  683. }
  684. }
  685. // Add a link to the Direct Debit ('direct-debit') or Credit transfer ('credit-transfer') file in bank_url
  686. if (!$error && $addbankurl && in_array($addbankurl, array('direct-debit', 'credit-transfer'))) {
  687. $result = $acc->add_url_line(
  688. $bank_line_id,
  689. $this->id_prelevement,
  690. DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
  691. $this->num_payment,
  692. $addbankurl
  693. );
  694. }
  695. // Add link to the Direct Debit if invoice redused ('InvoiceRefused') in bank_url
  696. if (!$error && $label == '(InvoiceRefused)') {
  697. $result=$acc->add_url_line(
  698. $bank_line_id,
  699. $this->id_prelevement,
  700. DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
  701. $this->num_prelevement,
  702. 'withdraw'
  703. );
  704. }
  705. if (!$error && !$notrigger) {
  706. // Appel des triggers
  707. $result = $this->call_trigger('PAYMENT_ADD_TO_BANK', $user);
  708. if ($result < 0) {
  709. $error++;
  710. }
  711. // Fin appel triggers
  712. }
  713. } else {
  714. $this->error = $acc->error;
  715. $this->errors = $acc->errors;
  716. $error++;
  717. }
  718. if (!$error) {
  719. $this->db->commit();
  720. } else {
  721. $this->db->rollback();
  722. }
  723. }
  724. if (!$error) {
  725. return $bank_line_id;
  726. } else {
  727. return -1;
  728. }
  729. }
  730. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  731. /**
  732. * Mise a jour du lien entre le paiement et la ligne generee dans llx_bank
  733. *
  734. * @param int $id_bank Id compte bancaire
  735. * @return int Return integer <0 if KO, >0 if OK
  736. */
  737. public function update_fk_bank($id_bank)
  738. {
  739. // phpcs:enable
  740. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.((int) $id_bank);
  741. $sql .= " WHERE rowid = ".((int) $this->id);
  742. dol_syslog(get_class($this).'::update_fk_bank', LOG_DEBUG);
  743. $result = $this->db->query($sql);
  744. if ($result) {
  745. return 1;
  746. } else {
  747. $this->error = $this->db->lasterror();
  748. dol_syslog(get_class($this).'::update_fk_bank '.$this->error);
  749. return -1;
  750. }
  751. }
  752. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  753. /**
  754. * Updates the payment date
  755. *
  756. * @param int $date New date
  757. * @return int Return integer <0 if KO, 0 if OK
  758. */
  759. public function update_date($date)
  760. {
  761. // phpcs:enable
  762. $error = 0;
  763. if (!empty($date) && $this->statut != 1) {
  764. $this->db->begin();
  765. dol_syslog(get_class($this)."::update_date with date = ".$date, LOG_DEBUG);
  766. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  767. $sql .= " SET datep = '".$this->db->idate($date)."'";
  768. $sql .= " WHERE rowid = ".((int) $this->id);
  769. $result = $this->db->query($sql);
  770. if (!$result) {
  771. $error++;
  772. $this->error = 'Error -1 '.$this->db->error();
  773. }
  774. $type = $this->element;
  775. $sql = "UPDATE ".MAIN_DB_PREFIX.'bank';
  776. $sql .= " SET dateo = '".$this->db->idate($date)."', datev = '".$this->db->idate($date)."'";
  777. $sql .= " WHERE rowid IN (SELECT fk_bank FROM ".MAIN_DB_PREFIX."bank_url WHERE type = '".$this->db->escape($type)."' AND url_id = ".((int) $this->id).")";
  778. $sql .= " AND rappro = 0";
  779. $result = $this->db->query($sql);
  780. if (!$result) {
  781. $error++;
  782. $this->error = 'Error -1 '.$this->db->error();
  783. }
  784. if (!$error) {
  785. }
  786. if (!$error) {
  787. $this->datepaye = $date;
  788. $this->date = $date;
  789. $this->db->commit();
  790. return 0;
  791. } else {
  792. $this->db->rollback();
  793. return -2;
  794. }
  795. }
  796. return -1; //no date given or already validated
  797. }
  798. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  799. /**
  800. * Updates the payment number
  801. *
  802. * @param string $num_payment New num
  803. * @return int Return integer <0 if KO, 0 if OK
  804. */
  805. public function update_num($num_payment)
  806. {
  807. // phpcs:enable
  808. if (!empty($num_payment) && $this->statut != 1) {
  809. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  810. $sql .= " SET num_paiement = '".$this->db->escape($num_payment)."'";
  811. $sql .= " WHERE rowid = ".((int) $this->id);
  812. dol_syslog(get_class($this)."::update_num", LOG_DEBUG);
  813. $result = $this->db->query($sql);
  814. if ($result) {
  815. $this->num_payment = $this->db->escape($num_payment);
  816. return 0;
  817. } else {
  818. $this->error = 'Error -1 '.$this->db->error();
  819. return -2;
  820. }
  821. }
  822. return -1; //no num given or already validated
  823. }
  824. /**
  825. * Validate payment
  826. *
  827. * @param User|null $user User making validation
  828. * @return int Return integer <0 if KO, >0 if OK
  829. * @deprecated
  830. */
  831. public function valide(User $user = null)
  832. {
  833. return $this->validate($user);
  834. }
  835. /**
  836. * Validate payment
  837. *
  838. * @param User|null $user User making validation
  839. * @return int Return integer <0 if KO, >0 if OK
  840. */
  841. public function validate(User $user = null)
  842. {
  843. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.((int) $this->id);
  844. dol_syslog(get_class($this).'::valide', LOG_DEBUG);
  845. $result = $this->db->query($sql);
  846. if ($result) {
  847. return 1;
  848. } else {
  849. $this->error = $this->db->lasterror();
  850. dol_syslog(get_class($this).'::valide '.$this->error);
  851. return -1;
  852. }
  853. }
  854. /**
  855. * Reject payment
  856. *
  857. * @param User|null $user User making reject
  858. * @return int Return integer <0 if KO, >0 if OK
  859. */
  860. public function reject(User $user = null)
  861. {
  862. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 2 WHERE rowid = '.((int) $this->id);
  863. dol_syslog(get_class($this).'::reject', LOG_DEBUG);
  864. $result = $this->db->query($sql);
  865. if ($result) {
  866. return 1;
  867. } else {
  868. $this->error = $this->db->lasterror();
  869. dol_syslog(get_class($this).'::reject '.$this->error);
  870. return -1;
  871. }
  872. }
  873. /**
  874. * Information sur l'objet
  875. *
  876. * @param int $id id du paiement dont il faut afficher les infos
  877. * @return void
  878. */
  879. public function info($id)
  880. {
  881. $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms';
  882. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p';
  883. $sql .= ' WHERE p.rowid = '.((int) $id);
  884. dol_syslog(get_class($this).'::info', LOG_DEBUG);
  885. $result = $this->db->query($sql);
  886. if ($result) {
  887. if ($this->db->num_rows($result)) {
  888. $obj = $this->db->fetch_object($result);
  889. $this->id = $obj->rowid;
  890. $this->user_creation_id = $obj->fk_user_creat;
  891. $this->user_modification_id = $obj->fk_user_modif;
  892. $this->date_creation = $this->db->jdate($obj->datec);
  893. $this->date_modification = $this->db->jdate($obj->tms);
  894. }
  895. $this->db->free($result);
  896. } else {
  897. dol_print_error($this->db);
  898. }
  899. }
  900. /**
  901. * Return list of invoices the payment is related to.
  902. *
  903. * @param string $filter Filter
  904. * @return int|array Return integer <0 if KO or array of invoice id
  905. * @see getAmountsArray()
  906. */
  907. public function getBillsArray($filter = '')
  908. {
  909. $sql = 'SELECT pf.fk_facture';
  910. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'facture as f'; // We keep link on invoice to allow use of some filters on invoice
  911. $sql .= ' WHERE pf.fk_facture = f.rowid AND pf.fk_paiement = '.((int) $this->id);
  912. if ($filter) {
  913. $sql .= ' AND '.$filter;
  914. }
  915. $resql = $this->db->query($sql);
  916. if ($resql) {
  917. $i = 0;
  918. $num = $this->db->num_rows($resql);
  919. $billsarray = array();
  920. while ($i < $num) {
  921. $obj = $this->db->fetch_object($resql);
  922. $billsarray[$i] = $obj->fk_facture;
  923. $i++;
  924. }
  925. return $billsarray;
  926. } else {
  927. $this->error = $this->db->error();
  928. dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG);
  929. return -1;
  930. }
  931. }
  932. /**
  933. * Return list of amounts of payments.
  934. *
  935. * @return int|array Array of amount of payments
  936. * @see getBillsArray()
  937. */
  938. public function getAmountsArray()
  939. {
  940. $sql = 'SELECT pf.fk_facture, pf.amount';
  941. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
  942. $sql .= ' WHERE pf.fk_paiement = '.((int) $this->id);
  943. $resql = $this->db->query($sql);
  944. if ($resql) {
  945. $i = 0;
  946. $num = $this->db->num_rows($resql);
  947. $amounts = array();
  948. while ($i < $num) {
  949. $obj = $this->db->fetch_object($resql);
  950. $amounts[$obj->fk_facture] = $obj->amount;
  951. $i++;
  952. }
  953. return $amounts;
  954. } else {
  955. $this->error = $this->db->error();
  956. dol_syslog(get_class($this).'::getAmountsArray Error '.$this->error.' -', LOG_DEBUG);
  957. return -1;
  958. }
  959. }
  960. /**
  961. * Return next reference of customer invoice not already used (or last reference)
  962. * according to numbering module defined into constant FACTURE_ADDON
  963. *
  964. * @param Societe $soc object company
  965. * @param string $mode 'next' for next value or 'last' for last value
  966. * @return string free ref or last ref
  967. */
  968. public function getNextNumRef($soc, $mode = 'next')
  969. {
  970. global $conf, $db, $langs;
  971. $langs->load("bills");
  972. // Clean parameters (if not defined or using deprecated value)
  973. if (!getDolGlobalString('PAYMENT_ADDON')) {
  974. $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
  975. } elseif (getDolGlobalString('PAYMENT_ADDON') == 'ant') {
  976. $conf->global->PAYMENT_ADDON = 'mod_payment_ant';
  977. } elseif (getDolGlobalString('PAYMENT_ADDON') == 'cicada') {
  978. $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
  979. }
  980. if (getDolGlobalString('PAYMENT_ADDON')) {
  981. $mybool = false;
  982. $file = getDolGlobalString('PAYMENT_ADDON') . ".php";
  983. $classname = $conf->global->PAYMENT_ADDON;
  984. // Include file with class
  985. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  986. foreach ($dirmodels as $reldir) {
  987. $dir = dol_buildpath($reldir."core/modules/payment/");
  988. // Load file with numbering class (if found)
  989. if (is_file($dir.$file) && is_readable($dir.$file)) {
  990. $mybool |= include_once $dir.$file;
  991. }
  992. }
  993. // For compatibility
  994. if (!$mybool) {
  995. $file = getDolGlobalString('PAYMENT_ADDON') . ".php";
  996. $classname = "mod_payment_" . getDolGlobalString('PAYMENT_ADDON');
  997. $classname = preg_replace('/\-.*$/', '', $classname);
  998. // Include file with class
  999. foreach ($conf->file->dol_document_root as $dirroot) {
  1000. $dir = $dirroot."/core/modules/payment/";
  1001. // Load file with numbering class (if found)
  1002. if (is_file($dir.$file) && is_readable($dir.$file)) {
  1003. $mybool |= include_once $dir.$file;
  1004. }
  1005. }
  1006. }
  1007. if (!$mybool) {
  1008. dol_print_error('', "Failed to include file ".$file);
  1009. return '';
  1010. }
  1011. $obj = new $classname();
  1012. $numref = "";
  1013. $numref = $obj->getNextValue($soc, $this);
  1014. /**
  1015. * $numref can be empty in case we ask for the last value because if there is no invoice created with the
  1016. * set up mask.
  1017. */
  1018. if ($mode != 'last' && !$numref) {
  1019. dol_print_error($db, "Payment::getNextNumRef ".$obj->error);
  1020. return "";
  1021. }
  1022. return $numref;
  1023. } else {
  1024. $langs->load("errors");
  1025. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Invoice"));
  1026. return "";
  1027. }
  1028. }
  1029. /**
  1030. * get the right way of payment
  1031. *
  1032. * @return string 'dolibarr' if standard comportment or paid in main currency, 'customer' if payment received from multicurrency inputs
  1033. */
  1034. public function getWay()
  1035. {
  1036. global $conf;
  1037. $way = 'dolibarr';
  1038. if (isModEnabled('multicurrency')) {
  1039. foreach ($this->multicurrency_amounts as $value) {
  1040. if (!empty($value)) { // one value found then payment is in invoice currency
  1041. $way = 'customer';
  1042. break;
  1043. }
  1044. }
  1045. }
  1046. return $way;
  1047. }
  1048. /**
  1049. * Initialise an instance with random values.
  1050. * Used to build previews or test instances.
  1051. * id must be 0 if object instance is a specimen.
  1052. *
  1053. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  1054. * @return void
  1055. */
  1056. public function initAsSpecimen($option = '')
  1057. {
  1058. global $user, $langs, $conf;
  1059. $now = dol_now();
  1060. $arraynow = dol_getdate($now);
  1061. $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  1062. // Initialize parameters
  1063. $this->id = 0;
  1064. $this->ref = 'SPECIMEN';
  1065. $this->specimen = 1;
  1066. $this->facid = 1;
  1067. $this->datepaye = $nownotime;
  1068. }
  1069. /**
  1070. * Return clicable name (with picto eventually)
  1071. *
  1072. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1073. * @param string $option Sur quoi pointe le lien
  1074. * @param string $mode 'withlistofinvoices'=Include list of invoices into tooltip
  1075. * @param int $notooltip 1=Disable tooltip
  1076. * @param string $morecss Add more CSS
  1077. * @return string Chaine avec URL
  1078. */
  1079. public function getNomUrl($withpicto = 0, $option = '', $mode = 'withlistofinvoices', $notooltip = 0, $morecss = '')
  1080. {
  1081. global $conf, $langs, $hookmanager;
  1082. if (!empty($conf->dol_no_mouse_hover)) {
  1083. $notooltip = 1; // Force disable tooltips
  1084. }
  1085. $result = '';
  1086. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Payment").'</u><br>';
  1087. $label .= '<strong>'.$langs->trans("Ref").':</strong> '.$this->ref;
  1088. $dateofpayment = ($this->datepaye ? $this->datepaye : $this->date);
  1089. if ($dateofpayment) {
  1090. $label .= '<br><strong>'.$langs->trans("Date").':</strong> ';
  1091. $tmparray = dol_getdate($dateofpayment);
  1092. if ($tmparray['seconds'] == 0 && $tmparray['minutes'] == 0 && ($tmparray['hours'] == 0 || $tmparray['hours'] == 12)) { // We set hours to 0:00 or 12:00 because we don't know it
  1093. $label .= dol_print_date($dateofpayment, 'day');
  1094. } else { // Hours was set to real date of payment (special case for POS for example)
  1095. $label .= dol_print_date($dateofpayment, 'dayhour', 'tzuser');
  1096. }
  1097. }
  1098. if ($this->amount) {
  1099. $label .= '<br><strong>'.$langs->trans("Amount").':</strong> '.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency);
  1100. }
  1101. if ($mode == 'withlistofinvoices') {
  1102. $arraybill = $this->getBillsArray();
  1103. if (is_array($arraybill) && count($arraybill) > 0) {
  1104. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1105. $facturestatic = new Facture($this->db);
  1106. foreach ($arraybill as $billid) {
  1107. $facturestatic->fetch($billid);
  1108. $label .= '<br> '.$facturestatic->getNomUrl(1, '', 0, 0, '', 1).' '.$facturestatic->getLibStatut(2, 1);
  1109. }
  1110. }
  1111. }
  1112. $linkclose = '';
  1113. if (empty($notooltip)) {
  1114. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  1115. $label = $langs->trans("Payment");
  1116. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1117. }
  1118. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1119. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1120. } else {
  1121. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1122. }
  1123. $url = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$this->id;
  1124. $linkstart = '<a href="'.$url.'"';
  1125. $linkstart .= $linkclose.'>';
  1126. $linkend = '</a>';
  1127. $result .= $linkstart;
  1128. if ($withpicto) {
  1129. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1130. }
  1131. if ($withpicto && $withpicto != 2) {
  1132. $result .= ($this->ref ? $this->ref : $this->id);
  1133. }
  1134. $result .= $linkend;
  1135. global $action;
  1136. $hookmanager->initHooks(array($this->element . 'dao'));
  1137. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1138. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1139. if ($reshook > 0) {
  1140. $result = $hookmanager->resPrint;
  1141. } else {
  1142. $result .= $hookmanager->resPrint;
  1143. }
  1144. return $result;
  1145. }
  1146. /**
  1147. * Return the label of the status
  1148. *
  1149. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1150. * @return string Label of status
  1151. */
  1152. public function getLibStatut($mode = 0)
  1153. {
  1154. return $this->LibStatut($this->statut, $mode);
  1155. }
  1156. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1157. /**
  1158. * Return the label of a given status
  1159. *
  1160. * @param int $status Id status
  1161. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1162. * @return string Label of status
  1163. */
  1164. public function LibStatut($status, $mode = 0)
  1165. {
  1166. // phpcs:enable
  1167. global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
  1168. $langs->load('compta');
  1169. /*if ($mode == 0)
  1170. {
  1171. if ($status == 0) return $langs->trans('ToValidate');
  1172. if ($status == 1) return $langs->trans('Validated');
  1173. }
  1174. if ($mode == 1)
  1175. {
  1176. if ($status == 0) return $langs->trans('ToValidate');
  1177. if ($status == 1) return $langs->trans('Validated');
  1178. }
  1179. if ($mode == 2)
  1180. {
  1181. if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
  1182. if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
  1183. }
  1184. if ($mode == 3)
  1185. {
  1186. if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
  1187. if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
  1188. }
  1189. if ($mode == 4)
  1190. {
  1191. if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
  1192. if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
  1193. }
  1194. if ($mode == 5)
  1195. {
  1196. if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
  1197. if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
  1198. }
  1199. if ($mode == 6)
  1200. {
  1201. if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
  1202. if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
  1203. }*/
  1204. return '';
  1205. }
  1206. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1207. /**
  1208. * Load the third party of object, from id into this->thirdparty.
  1209. * For payments, take the thirdparty linked to the first invoice found. This is enough because payments are done on invoices of the same thirdparty.
  1210. *
  1211. * @param int $force_thirdparty_id Force thirdparty id
  1212. * @return int Return integer <0 if KO, >0 if OK
  1213. */
  1214. public function fetch_thirdparty($force_thirdparty_id = 0)
  1215. {
  1216. // phpcs:enable
  1217. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1218. if (empty($force_thirdparty_id)) {
  1219. $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him
  1220. if (!empty($billsarray)) {
  1221. $invoice = new Facture($this->db);
  1222. if ($invoice->fetch($billsarray[0]) > 0) {
  1223. $force_thirdparty_id = $invoice->socid;
  1224. }
  1225. }
  1226. }
  1227. return parent::fetch_thirdparty($force_thirdparty_id);
  1228. }
  1229. /**
  1230. * Return if payment is reconciled
  1231. *
  1232. * @return boolean True if payment is reconciled
  1233. */
  1234. public function isReconciled()
  1235. {
  1236. $accountline = new AccountLine($this->db);
  1237. $accountline->fetch($this->bank_line);
  1238. return $accountline->rappro;
  1239. }
  1240. }