paiement.class.php 45 KB

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