paiement.class.php 44 KB

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