paiement.class.php 45 KB

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