paiement.class.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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_DEPOSIT,
  324. Facture::TYPE_SITUATION
  325. );
  326. if (!in_array($invoice->type, $affected_types)) {
  327. dol_syslog("Invoice ".$facid." is not a standard, nor replacement invoice, nor credit note, nor deposit invoice, nor situation invoice. We do nothing more.");
  328. } elseif ($remaintopay) {
  329. // hook to have an option to automatically close a closable invoice with less payment than the total amount (e.g. agreed cash discount terms)
  330. global $hookmanager;
  331. $hookmanager->initHooks(array('paymentdao'));
  332. $parameters = array('facid' => $facid, 'invoice' => $invoice, 'remaintopay' => $remaintopay);
  333. $action = 'CLOSEPAIDINVOICE';
  334. $reshook = $hookmanager->executeHooks('createPayment', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  335. if ($reshook < 0) {
  336. $this->errors[] = $hookmanager->error;
  337. $this->error = $hookmanager->error;
  338. $error++;
  339. } elseif ($reshook == 0) {
  340. dol_syslog("Remain to pay for invoice " . $facid . " not null. We do nothing more.");
  341. }
  342. // } else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
  343. } else {
  344. // If invoice is a down payment, we also convert down payment to discount
  345. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  346. $amount_ht = $amount_tva = $amount_ttc = array();
  347. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  348. // Insert one discount by VAT rate category
  349. $discount = new DiscountAbsolute($this->db);
  350. $discount->fetch('', $invoice->id);
  351. if (empty($discount->id)) { // If the invoice was not yet converted into a discount (this may have been done manually before we come here)
  352. $discount->description = '(DEPOSIT)';
  353. $discount->fk_soc = $invoice->socid;
  354. $discount->fk_facture_source = $invoice->id;
  355. // Loop on each vat rate
  356. $i = 0;
  357. foreach ($invoice->lines as $line) {
  358. if ($line->total_ht != 0) { // no need to create discount if amount is null
  359. $amount_ht[$line->tva_tx] += $line->total_ht;
  360. $amount_tva[$line->tva_tx] += $line->total_tva;
  361. $amount_ttc[$line->tva_tx] += $line->total_ttc;
  362. $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
  363. $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
  364. $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
  365. $i++;
  366. }
  367. }
  368. foreach ($amount_ht as $tva_tx => $xxx) {
  369. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  370. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  371. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  372. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  373. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  374. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  375. $discount->tva_tx = abs($tva_tx);
  376. $result = $discount->create($user);
  377. if ($result < 0) {
  378. $error++;
  379. break;
  380. }
  381. }
  382. }
  383. if ($error) {
  384. $this->error = $discount->error;
  385. $this->errors = $discount->errors;
  386. $error++;
  387. }
  388. }
  389. // Set invoice to paid
  390. if (!$error) {
  391. $result = $invoice->setPaid($user, '', '');
  392. if ($result < 0) {
  393. $this->error = $invoice->error;
  394. $this->errors = $invoice->errors;
  395. $error++;
  396. }
  397. }
  398. }
  399. }
  400. // Regenerate documents of invoices
  401. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  402. 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);
  403. $newlang = '';
  404. $outputlangs = $langs;
  405. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  406. $invoice->fetch_thirdparty();
  407. $newlang = $invoice->thirdparty->default_lang;
  408. }
  409. if (!empty($newlang)) {
  410. $outputlangs = new Translate("", $conf);
  411. $outputlangs->setDefaultLang($newlang);
  412. }
  413. $hidedetails = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0;
  414. $hidedesc = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0;
  415. $hideref = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0;
  416. $ret = $invoice->fetch($facid); // Reload to get new records
  417. $result = $invoice->generateDocument($invoice->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  418. if ($result < 0) {
  419. $this->error = $invoice->error;
  420. $this->errors = $invoice->errors;
  421. $error++;
  422. }
  423. }
  424. } else {
  425. $this->error = $this->db->lasterror();
  426. $error++;
  427. }
  428. } else {
  429. dol_syslog(get_class($this).'::Create Amount line '.$key.' not a number. We discard it.');
  430. }
  431. }
  432. if (!$error) { // All payments into $this->amounts were recorded without errors
  433. // Appel des triggers
  434. $result = $this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user);
  435. if ($result < 0) {
  436. $error++;
  437. }
  438. // Fin appel triggers
  439. }
  440. } else {
  441. $this->error = $this->db->lasterror();
  442. $error++;
  443. }
  444. if (!$error) {
  445. $this->amount = $total;
  446. $this->total = $total; // deprecated
  447. $this->multicurrency_amount = $mtotal;
  448. $this->db->commit();
  449. return $this->id;
  450. } else {
  451. $this->db->rollback();
  452. return -1;
  453. }
  454. }
  455. /**
  456. * Delete a payment and generated links into account
  457. * - Si le paiement porte sur un ecriture compte qui est rapprochee, on refuse
  458. * - Si le paiement porte sur au moins une facture a "payee", on refuse
  459. *
  460. * @param int $notrigger No trigger
  461. * @return int <0 si ko, >0 si ok
  462. */
  463. public function delete($notrigger = 0)
  464. {
  465. global $conf, $user, $langs;
  466. $error = 0;
  467. $bank_line_id = $this->bank_line;
  468. $this->db->begin();
  469. // Verifier si paiement porte pas sur une facture classee
  470. // Si c'est le cas, on refuse la suppression
  471. $billsarray = $this->getBillsArray('f.fk_statut > 1');
  472. if (is_array($billsarray)) {
  473. if (count($billsarray)) {
  474. $this->error = "ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible";
  475. $this->db->rollback();
  476. return -1;
  477. }
  478. } else {
  479. $this->db->rollback();
  480. return -2;
  481. }
  482. // Delete bank urls. If payment is on a conciliated line, return error.
  483. if ($bank_line_id > 0) {
  484. $accline = new AccountLine($this->db);
  485. $result = $accline->fetch($bank_line_id);
  486. if ($result == 0) {
  487. $accline->id = $accline->rowid = $bank_line_id; // If not found, we set artificially rowid to allow delete of llx_bank_url
  488. }
  489. // Delete bank account url lines linked to payment
  490. $result = $accline->delete_urls($user);
  491. if ($result < 0) {
  492. $this->error = $accline->error;
  493. $this->db->rollback();
  494. return -3;
  495. }
  496. // Delete bank account lines linked to payment
  497. $result = $accline->delete($user);
  498. if ($result < 0) {
  499. $this->error = $accline->error;
  500. $this->db->rollback();
  501. return -4;
  502. }
  503. }
  504. if (!$notrigger) {
  505. // Call triggers
  506. $result = $this->call_trigger('PAYMENT_CUSTOMER_DELETE', $user);
  507. if ($result < 0) {
  508. $this->db->rollback();
  509. return -1;
  510. }
  511. // End call triggers
  512. }
  513. // Delete payment (into paiement_facture and paiement)
  514. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement_facture';
  515. $sql .= ' WHERE fk_paiement = '.((int) $this->id);
  516. dol_syslog($sql);
  517. $result = $this->db->query($sql);
  518. if ($result) {
  519. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement';
  520. $sql .= " WHERE rowid = ".((int) $this->id);
  521. dol_syslog($sql);
  522. $result = $this->db->query($sql);
  523. if (!$result) {
  524. $this->error = $this->db->lasterror();
  525. $this->db->rollback();
  526. return -3;
  527. }
  528. $this->db->commit();
  529. return 1;
  530. } else {
  531. $this->error = $this->db->error;
  532. $this->db->rollback();
  533. return -5;
  534. }
  535. }
  536. /**
  537. * Add a record into bank for payment + links between this bank record and sources of payment.
  538. * All payment properties (this->amount, this->amounts, ...) must have been set first like after a call to create().
  539. *
  540. * @param User $user Object of user making payment
  541. * @param string $mode 'payment', 'payment_supplier'
  542. * @param string $label Label to use in bank record. Note: If label is '(WithdrawalPayment)', a third entry 'widthdraw' is added into bank_url.
  543. * @param int $accountid Id of bank account to do link with
  544. * @param string $emetteur_nom Name of transmitter
  545. * @param string $emetteur_banque Name of bank
  546. * @param int $notrigger No trigger
  547. * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on.
  548. * @return int <0 if KO, bank_line_id if OK
  549. */
  550. public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger = 0, $accountancycode = '')
  551. {
  552. global $conf, $langs, $user;
  553. $error = 0;
  554. $bank_line_id = 0;
  555. if (isModEnabled("banque")) {
  556. if ($accountid <= 0) {
  557. $this->error = 'Bad value for parameter accountid='.$accountid;
  558. dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR);
  559. return -1;
  560. }
  561. $this->fk_account = $accountid;
  562. dol_syslog("addPaymentToBank ".$user->id.", ".$mode.", ".$label.", ".$this->fk_account.", ".$emetteur_nom.", ".$emetteur_banque);
  563. include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  564. $acc = new Account($this->db);
  565. $result = $acc->fetch($this->fk_account);
  566. if ($result < 0) {
  567. $error++;
  568. return -1;
  569. }
  570. $this->db->begin();
  571. $totalamount = $this->amount;
  572. $totalamount_main_currency = null;
  573. if (empty($totalamount)) {
  574. $totalamount = $this->total; // For backward compatibility
  575. }
  576. // 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)
  577. if (isModEnabled('multicurrency') && $conf->currency != $acc->currency_code) {
  578. $totalamount = $this->multicurrency_amount; // We will insert into llx_bank.amount in foreign currency
  579. $totalamount_main_currency = $this->amount; // We will also save the amount in main currency into column llx_bank.amount_main_currency
  580. }
  581. if ($mode == 'payment_supplier') {
  582. $totalamount = -$totalamount;
  583. if (isset($totalamount_main_currency)) {
  584. $totalamount_main_currency = -$totalamount_main_currency;
  585. }
  586. }
  587. // Insert payment into llx_bank
  588. $bank_line_id = $acc->addline(
  589. $this->datepaye,
  590. $this->paiementcode ? $this->paiementcode : $this->paiementid, // Payment mode code ('CB', 'CHQ' or 'VIR' for example). Use payment id if not defined for backward compatibility.
  591. $label,
  592. $totalamount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note)
  593. $this->num_payment,
  594. '',
  595. $user,
  596. $emetteur_nom,
  597. $emetteur_banque,
  598. $accountancycode,
  599. null,
  600. '',
  601. $totalamount_main_currency
  602. );
  603. // Mise a jour fk_bank dans llx_paiement
  604. // On connait ainsi le paiement qui a genere l'ecriture bancaire
  605. if ($bank_line_id > 0) {
  606. $result = $this->update_fk_bank($bank_line_id);
  607. if ($result <= 0) {
  608. $error++;
  609. dol_print_error($this->db);
  610. }
  611. // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction
  612. if (!$error) {
  613. $url = '';
  614. if ($mode == 'payment') {
  615. $url = DOL_URL_ROOT.'/compta/paiement/card.php?id=';
  616. }
  617. if ($mode == 'payment_supplier') {
  618. $url = DOL_URL_ROOT.'/fourn/paiement/card.php?id=';
  619. }
  620. if ($url) {
  621. $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode);
  622. if ($result <= 0) {
  623. $error++;
  624. dol_print_error($this->db);
  625. }
  626. }
  627. }
  628. // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
  629. //if (! $error && $label != '(WithdrawalPayment)')
  630. if (!$error) {
  631. $linkaddedforthirdparty = array();
  632. foreach ($this->amounts as $key => $value) { // We should have invoices always for same third party but we loop in case of.
  633. if ($mode == 'payment') {
  634. $fac = new Facture($this->db);
  635. $fac->fetch($key);
  636. $fac->fetch_thirdparty();
  637. if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty
  638. $result = $acc->add_url_line(
  639. $bank_line_id,
  640. $fac->thirdparty->id,
  641. DOL_URL_ROOT.'/comm/card.php?socid=',
  642. $fac->thirdparty->name,
  643. 'company'
  644. );
  645. if ($result <= 0) {
  646. dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
  647. }
  648. $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty
  649. }
  650. }
  651. if ($mode == 'payment_supplier') {
  652. $fac = new FactureFournisseur($this->db);
  653. $fac->fetch($key);
  654. $fac->fetch_thirdparty();
  655. if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty
  656. $result = $acc->add_url_line(
  657. $bank_line_id,
  658. $fac->thirdparty->id,
  659. DOL_URL_ROOT.'/fourn/card.php?socid=',
  660. $fac->thirdparty->name,
  661. 'company'
  662. );
  663. if ($result <= 0) {
  664. dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
  665. }
  666. $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty
  667. }
  668. }
  669. }
  670. }
  671. // Add link 'WithdrawalPayment' in bank_url
  672. if (!$error && $label == '(WithdrawalPayment)') {
  673. $result = $acc->add_url_line(
  674. $bank_line_id,
  675. $this->id_prelevement,
  676. DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
  677. $this->num_payment,
  678. 'withdraw'
  679. );
  680. }
  681. // Add link 'InvoiceRefused' in bank_url
  682. if (! $error && $label == '(InvoiceRefused)') {
  683. $result=$acc->add_url_line(
  684. $bank_line_id,
  685. $this->id_prelevement,
  686. DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
  687. $this->num_prelevement,
  688. 'withdraw'
  689. );
  690. }
  691. if (!$error && !$notrigger) {
  692. // Appel des triggers
  693. $result = $this->call_trigger('PAYMENT_ADD_TO_BANK', $user);
  694. if ($result < 0) {
  695. $error++;
  696. }
  697. // Fin appel triggers
  698. }
  699. } else {
  700. $this->error = $acc->error;
  701. $error++;
  702. }
  703. if (!$error) {
  704. $this->db->commit();
  705. } else {
  706. $this->db->rollback();
  707. }
  708. }
  709. if (!$error) {
  710. return $bank_line_id;
  711. } else {
  712. return -1;
  713. }
  714. }
  715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  716. /**
  717. * Mise a jour du lien entre le paiement et la ligne generee dans llx_bank
  718. *
  719. * @param int $id_bank Id compte bancaire
  720. * @return int <0 if KO, >0 if OK
  721. */
  722. public function update_fk_bank($id_bank)
  723. {
  724. // phpcs:enable
  725. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.((int) $id_bank);
  726. $sql .= " WHERE rowid = ".((int) $this->id);
  727. dol_syslog(get_class($this).'::update_fk_bank', LOG_DEBUG);
  728. $result = $this->db->query($sql);
  729. if ($result) {
  730. return 1;
  731. } else {
  732. $this->error = $this->db->lasterror();
  733. dol_syslog(get_class($this).'::update_fk_bank '.$this->error);
  734. return -1;
  735. }
  736. }
  737. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  738. /**
  739. * Updates the payment date
  740. *
  741. * @param int $date New date
  742. * @return int <0 if KO, 0 if OK
  743. */
  744. public function update_date($date)
  745. {
  746. // phpcs:enable
  747. $error = 0;
  748. if (!empty($date) && $this->statut != 1) {
  749. $this->db->begin();
  750. dol_syslog(get_class($this)."::update_date with date = ".$date, LOG_DEBUG);
  751. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  752. $sql .= " SET datep = '".$this->db->idate($date)."'";
  753. $sql .= " WHERE rowid = ".((int) $this->id);
  754. $result = $this->db->query($sql);
  755. if (!$result) {
  756. $error++;
  757. $this->error = 'Error -1 '.$this->db->error();
  758. }
  759. $type = $this->element;
  760. $sql = "UPDATE ".MAIN_DB_PREFIX.'bank';
  761. $sql .= " SET dateo = '".$this->db->idate($date)."', datev = '".$this->db->idate($date)."'";
  762. $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).")";
  763. $sql .= " AND rappro = 0";
  764. $result = $this->db->query($sql);
  765. if (!$result) {
  766. $error++;
  767. $this->error = 'Error -1 '.$this->db->error();
  768. }
  769. if (!$error) {
  770. }
  771. if (!$error) {
  772. $this->datepaye = $date;
  773. $this->date = $date;
  774. $this->db->commit();
  775. return 0;
  776. } else {
  777. $this->db->rollback();
  778. return -2;
  779. }
  780. }
  781. return -1; //no date given or already validated
  782. }
  783. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  784. /**
  785. * Updates the payment number
  786. *
  787. * @param string $num New num
  788. * @return int <0 if KO, 0 if OK
  789. */
  790. public function update_num($num)
  791. {
  792. // phpcs:enable
  793. if (!empty($num) && $this->statut != 1) {
  794. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  795. $sql .= " SET num_paiement = '".$this->db->escape($num)."'";
  796. $sql .= " WHERE rowid = ".((int) $this->id);
  797. dol_syslog(get_class($this)."::update_num", LOG_DEBUG);
  798. $result = $this->db->query($sql);
  799. if ($result) {
  800. $this->num_payment = $this->db->escape($num);
  801. return 0;
  802. } else {
  803. $this->error = 'Error -1 '.$this->db->error();
  804. return -2;
  805. }
  806. }
  807. return -1; //no num given or already validated
  808. }
  809. /**
  810. * Validate payment
  811. *
  812. * @param User $user User making validation
  813. * @return int <0 if KO, >0 if OK
  814. * @deprecated
  815. */
  816. public function valide(User $user = null)
  817. {
  818. return $this->validate($user);
  819. }
  820. /**
  821. * Validate payment
  822. *
  823. * @param User $user User making validation
  824. * @return int <0 if KO, >0 if OK
  825. */
  826. public function validate(User $user = null)
  827. {
  828. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.((int) $this->id);
  829. dol_syslog(get_class($this).'::valide', LOG_DEBUG);
  830. $result = $this->db->query($sql);
  831. if ($result) {
  832. return 1;
  833. } else {
  834. $this->error = $this->db->lasterror();
  835. dol_syslog(get_class($this).'::valide '.$this->error);
  836. return -1;
  837. }
  838. }
  839. /**
  840. * Reject payment
  841. *
  842. * @param User $user User making reject
  843. * @return int <0 if KO, >0 if OK
  844. */
  845. public function reject(User $user = null)
  846. {
  847. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 2 WHERE rowid = '.((int) $this->id);
  848. dol_syslog(get_class($this).'::reject', LOG_DEBUG);
  849. $result = $this->db->query($sql);
  850. if ($result) {
  851. return 1;
  852. } else {
  853. $this->error = $this->db->lasterror();
  854. dol_syslog(get_class($this).'::reject '.$this->error);
  855. return -1;
  856. }
  857. }
  858. /**
  859. * Information sur l'objet
  860. *
  861. * @param int $id id du paiement dont il faut afficher les infos
  862. * @return void
  863. */
  864. public function info($id)
  865. {
  866. $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms';
  867. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p';
  868. $sql .= ' WHERE p.rowid = '.((int) $id);
  869. dol_syslog(get_class($this).'::info', LOG_DEBUG);
  870. $result = $this->db->query($sql);
  871. if ($result) {
  872. if ($this->db->num_rows($result)) {
  873. $obj = $this->db->fetch_object($result);
  874. $this->id = $obj->rowid;
  875. if ($obj->fk_user_creat) {
  876. $cuser = new User($this->db);
  877. $cuser->fetch($obj->fk_user_creat);
  878. $this->user_creation = $cuser;
  879. }
  880. if ($obj->fk_user_modif) {
  881. $muser = new User($this->db);
  882. $muser->fetch($obj->fk_user_modif);
  883. $this->user_modification = $muser;
  884. }
  885. $this->date_creation = $this->db->jdate($obj->datec);
  886. $this->date_modification = $this->db->jdate($obj->tms);
  887. }
  888. $this->db->free($result);
  889. } else {
  890. dol_print_error($this->db);
  891. }
  892. }
  893. /**
  894. * Return list of invoices the payment is related to.
  895. *
  896. * @param string $filter Filter
  897. * @return int|array <0 if KO or array of invoice id
  898. * @see getAmountsArray()
  899. */
  900. public function getBillsArray($filter = '')
  901. {
  902. $sql = 'SELECT pf.fk_facture';
  903. $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
  904. $sql .= ' WHERE pf.fk_facture = f.rowid AND pf.fk_paiement = '.((int) $this->id);
  905. if ($filter) {
  906. $sql .= ' AND '.$filter;
  907. }
  908. $resql = $this->db->query($sql);
  909. if ($resql) {
  910. $i = 0;
  911. $num = $this->db->num_rows($resql);
  912. $billsarray = array();
  913. while ($i < $num) {
  914. $obj = $this->db->fetch_object($resql);
  915. $billsarray[$i] = $obj->fk_facture;
  916. $i++;
  917. }
  918. return $billsarray;
  919. } else {
  920. $this->error = $this->db->error();
  921. dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG);
  922. return -1;
  923. }
  924. }
  925. /**
  926. * Return list of amounts of payments.
  927. *
  928. * @return int|array Array of amount of payments
  929. * @see getBillsArray()
  930. */
  931. public function getAmountsArray()
  932. {
  933. $sql = 'SELECT pf.fk_facture, pf.amount';
  934. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
  935. $sql .= ' WHERE pf.fk_paiement = '.((int) $this->id);
  936. $resql = $this->db->query($sql);
  937. if ($resql) {
  938. $i = 0;
  939. $num = $this->db->num_rows($resql);
  940. $amounts = array();
  941. while ($i < $num) {
  942. $obj = $this->db->fetch_object($resql);
  943. $amounts[$obj->fk_facture] = $obj->amount;
  944. $i++;
  945. }
  946. return $amounts;
  947. } else {
  948. $this->error = $this->db->error();
  949. dol_syslog(get_class($this).'::getAmountsArray Error '.$this->error.' -', LOG_DEBUG);
  950. return -1;
  951. }
  952. }
  953. /**
  954. * Return next reference of customer invoice not already used (or last reference)
  955. * according to numbering module defined into constant FACTURE_ADDON
  956. *
  957. * @param Societe $soc object company
  958. * @param string $mode 'next' for next value or 'last' for last value
  959. * @return string free ref or last ref
  960. */
  961. public function getNextNumRef($soc, $mode = 'next')
  962. {
  963. global $conf, $db, $langs;
  964. $langs->load("bills");
  965. // Clean parameters (if not defined or using deprecated value)
  966. if (empty($conf->global->PAYMENT_ADDON)) {
  967. $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
  968. } elseif ($conf->global->PAYMENT_ADDON == 'ant') {
  969. $conf->global->PAYMENT_ADDON = 'mod_payment_ant';
  970. } elseif ($conf->global->PAYMENT_ADDON == 'cicada') {
  971. $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
  972. }
  973. if (!empty($conf->global->PAYMENT_ADDON)) {
  974. $mybool = false;
  975. $file = $conf->global->PAYMENT_ADDON.".php";
  976. $classname = $conf->global->PAYMENT_ADDON;
  977. // Include file with class
  978. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  979. foreach ($dirmodels as $reldir) {
  980. $dir = dol_buildpath($reldir."core/modules/payment/");
  981. // Load file with numbering class (if found)
  982. if (is_file($dir.$file) && is_readable($dir.$file)) {
  983. $mybool |= include_once $dir.$file;
  984. }
  985. }
  986. // For compatibility
  987. if (!$mybool) {
  988. $file = $conf->global->PAYMENT_ADDON.".php";
  989. $classname = "mod_payment_".$conf->global->PAYMENT_ADDON;
  990. $classname = preg_replace('/\-.*$/', '', $classname);
  991. // Include file with class
  992. foreach ($conf->file->dol_document_root as $dirroot) {
  993. $dir = $dirroot."/core/modules/payment/";
  994. // Load file with numbering class (if found)
  995. if (is_file($dir.$file) && is_readable($dir.$file)) {
  996. $mybool |= include_once $dir.$file;
  997. }
  998. }
  999. }
  1000. if (!$mybool) {
  1001. dol_print_error('', "Failed to include file ".$file);
  1002. return '';
  1003. }
  1004. $obj = new $classname();
  1005. $numref = "";
  1006. $numref = $obj->getNextValue($soc, $this);
  1007. /**
  1008. * $numref can be empty in case we ask for the last value because if there is no invoice created with the
  1009. * set up mask.
  1010. */
  1011. if ($mode != 'last' && !$numref) {
  1012. dol_print_error($db, "Payment::getNextNumRef ".$obj->error);
  1013. return "";
  1014. }
  1015. return $numref;
  1016. } else {
  1017. $langs->load("errors");
  1018. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Invoice"));
  1019. return "";
  1020. }
  1021. }
  1022. /**
  1023. * get the right way of payment
  1024. *
  1025. * @return string 'dolibarr' if standard comportment or paid in main currency, 'customer' if payment received from multicurrency inputs
  1026. */
  1027. public function getWay()
  1028. {
  1029. global $conf;
  1030. $way = 'dolibarr';
  1031. if (isModEnabled('multicurrency')) {
  1032. foreach ($this->multicurrency_amounts as $value) {
  1033. if (!empty($value)) { // one value found then payment is in invoice currency
  1034. $way = 'customer';
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. return $way;
  1040. }
  1041. /**
  1042. * Initialise an instance with random values.
  1043. * Used to build previews or test instances.
  1044. * id must be 0 if object instance is a specimen.
  1045. *
  1046. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  1047. * @return void
  1048. */
  1049. public function initAsSpecimen($option = '')
  1050. {
  1051. global $user, $langs, $conf;
  1052. $now = dol_now();
  1053. $arraynow = dol_getdate($now);
  1054. $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  1055. // Initialize parameters
  1056. $this->id = 0;
  1057. $this->ref = 'SPECIMEN';
  1058. $this->specimen = 1;
  1059. $this->facid = 1;
  1060. $this->datepaye = $nownotime;
  1061. }
  1062. /**
  1063. * Return clicable name (with picto eventually)
  1064. *
  1065. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1066. * @param string $option Sur quoi pointe le lien
  1067. * @param string $mode 'withlistofinvoices'=Include list of invoices into tooltip
  1068. * @param int $notooltip 1=Disable tooltip
  1069. * @param string $morecss Add more CSS
  1070. * @return string Chaine avec URL
  1071. */
  1072. public function getNomUrl($withpicto = 0, $option = '', $mode = 'withlistofinvoices', $notooltip = 0, $morecss = '')
  1073. {
  1074. global $conf, $langs, $hookmanager;
  1075. if (!empty($conf->dol_no_mouse_hover)) {
  1076. $notooltip = 1; // Force disable tooltips
  1077. }
  1078. $result = '';
  1079. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Payment").'</u><br>';
  1080. $label .= '<strong>'.$langs->trans("Ref").':</strong> '.$this->ref;
  1081. $dateofpayment = ($this->datepaye ? $this->datepaye : $this->date);
  1082. if ($dateofpayment) {
  1083. $label .= '<br><strong>'.$langs->trans("Date").':</strong> ';
  1084. $tmparray = dol_getdate($dateofpayment);
  1085. 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
  1086. $label .= dol_print_date($dateofpayment, 'day');
  1087. } else { // Hours was set to real date of payment (special case for POS for example)
  1088. $label .= dol_print_date($dateofpayment, 'dayhour', 'tzuser');
  1089. }
  1090. }
  1091. if ($this->amount) {
  1092. $label .= '<br><strong>'.$langs->trans("Amount").':</strong> '.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency);
  1093. }
  1094. if ($mode == 'withlistofinvoices') {
  1095. $arraybill = $this->getBillsArray();
  1096. if (is_array($arraybill) && count($arraybill) > 0) {
  1097. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1098. $facturestatic = new Facture($this->db);
  1099. foreach ($arraybill as $billid) {
  1100. $facturestatic->fetch($billid);
  1101. $label .= '<br> '.$facturestatic->getNomUrl(1, '', 0, 0, '', 1).' '.$facturestatic->getLibStatut(2, 1);
  1102. }
  1103. }
  1104. }
  1105. $linkclose = '';
  1106. if (empty($notooltip)) {
  1107. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1108. $label = $langs->trans("Payment");
  1109. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1110. }
  1111. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1112. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1113. } else {
  1114. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1115. }
  1116. $url = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$this->id;
  1117. $linkstart = '<a href="'.$url.'"';
  1118. $linkstart .= $linkclose.'>';
  1119. $linkend = '</a>';
  1120. $result .= $linkstart;
  1121. if ($withpicto) {
  1122. $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);
  1123. }
  1124. if ($withpicto && $withpicto != 2) {
  1125. $result .= ($this->ref ? $this->ref : $this->id);
  1126. }
  1127. $result .= $linkend;
  1128. global $action;
  1129. $hookmanager->initHooks(array($this->element . 'dao'));
  1130. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1131. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1132. if ($reshook > 0) {
  1133. $result = $hookmanager->resPrint;
  1134. } else {
  1135. $result .= $hookmanager->resPrint;
  1136. }
  1137. return $result;
  1138. }
  1139. /**
  1140. * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee)
  1141. *
  1142. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1143. * @return string Libelle
  1144. */
  1145. public function getLibStatut($mode = 0)
  1146. {
  1147. return $this->LibStatut($this->statut, $mode);
  1148. }
  1149. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1150. /**
  1151. * Renvoi le libelle d'un statut donne
  1152. *
  1153. * @param int $status Statut
  1154. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1155. * @return string Libelle du statut
  1156. */
  1157. public function LibStatut($status, $mode = 0)
  1158. {
  1159. // phpcs:enable
  1160. global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
  1161. $langs->load('compta');
  1162. /*if ($mode == 0)
  1163. {
  1164. if ($status == 0) return $langs->trans('ToValidate');
  1165. if ($status == 1) return $langs->trans('Validated');
  1166. }
  1167. if ($mode == 1)
  1168. {
  1169. if ($status == 0) return $langs->trans('ToValidate');
  1170. if ($status == 1) return $langs->trans('Validated');
  1171. }
  1172. if ($mode == 2)
  1173. {
  1174. if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
  1175. if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
  1176. }
  1177. if ($mode == 3)
  1178. {
  1179. if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
  1180. if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
  1181. }
  1182. if ($mode == 4)
  1183. {
  1184. if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
  1185. if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
  1186. }
  1187. if ($mode == 5)
  1188. {
  1189. if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
  1190. if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
  1191. }
  1192. if ($mode == 6)
  1193. {
  1194. if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
  1195. if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
  1196. }*/
  1197. return '';
  1198. }
  1199. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1200. /**
  1201. * Load the third party of object, from id into this->thirdparty.
  1202. * For payments, take the thirdparty linked to the first invoice found. This is enough because payments are done on invoices of the same thirdparty.
  1203. *
  1204. * @param int $force_thirdparty_id Force thirdparty id
  1205. * @return int <0 if KO, >0 if OK
  1206. */
  1207. public function fetch_thirdparty($force_thirdparty_id = 0)
  1208. {
  1209. // phpcs:enable
  1210. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1211. if (empty($force_thirdparty_id)) {
  1212. $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him
  1213. if (!empty($billsarray)) {
  1214. $invoice = new Facture($this->db);
  1215. if ($invoice->fetch($billsarray[0]) > 0) {
  1216. $force_thirdparty_id = $invoice->socid;
  1217. }
  1218. }
  1219. }
  1220. return parent::fetch_thirdparty($force_thirdparty_id);
  1221. }
  1222. }