dolibarr 25.0.0-alpha
paiement.class.php
Go to the documentation of this file.
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-2025 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2020 Andreu Bisquerra Gaya <jove@bisquerra.com>
13 * Copyright (C) 2021 OpenDsi <support@open-dsi.fr>
14 * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
15 * Copyright (C) 2023 Sylvain Legrand <technique@infras.fr>
16 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 3 of the License, or
21 * (at your option) any later version.
22 *
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <https://www.gnu.org/licenses/>.
30 */
31
37require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
38require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
39
40
45{
49 public $element = 'payment';
50
54 public $table_element = 'paiement';
55
59 public $picto = 'payment';
60
64 public $facid;
65
69 public $socid;
70
74 public $datepaye;
75
79 public $date;
80
86 public $total;
87
93 public $montant;
94
98 public $amount;
99
103 public $multicurrency_amount;
104
108 public $multicurrency_currency;
109
113 public $amounts = array();
114
118 public $multicurrency_amounts = array();
119
123 public $multicurrency_tx = array();
124
128 public $multicurrency_code = array();
129
133 public $pos_change = 0.0;
134
138 public $author;
139
143 public $paiementid;
144
148 public $paiementcode;
149
153 public $type_label;
154
158 public $type_code;
159
165 public $num_paiement;
166
171 public $num_payment;
172
176 public $id_prelevement;
177
181 public $num_prelevement;
182
186 public $ext_payment_id;
187
191 public $ext_payment_site;
192
198 public $bank_account;
199
203 public $fk_account;
204
208 public $bank_line;
209
210 // fk_paiement in llx_paiement is the id of the payment type (7 for CHQ, ...)
211 // fk_paiement in llx_paiement_facture is rowid of payment
215 public $fk_paiement; // Type of payment
216
220 public $ref_ext;
221
222
228 public function __construct($db)
229 {
230 $this->db = $db;
231 }
232
241 public function fetch($id, $ref = '', $fk_bank = 0)
242 {
243 $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,';
244 $sql .= ' c.code as type_code, c.libelle as type_label,';
245 $sql .= ' p.num_paiement as num_payment, p.note,';
246 $sql .= ' b.fk_account';
247 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
248 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
249 $sql .= ' WHERE p.entity IN ('.getEntity('invoice').')';
250 if ($id > 0) {
251 $sql .= ' AND p.rowid = '.((int) $id);
252 } elseif ($ref) {
253 $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
254 } elseif ($fk_bank) {
255 $sql .= ' AND p.fk_bank = '.((int) $fk_bank);
256 }
257
258 $resql = $this->db->query($sql);
259 if ($resql) {
260 if ($this->db->num_rows($resql)) {
261 $obj = $this->db->fetch_object($resql);
262
263 $this->id = $obj->rowid;
264 $this->ref = $obj->ref ? $obj->ref : $obj->rowid;
265 $this->ref_ext = $obj->ref_ext;
266 $this->date = $this->db->jdate($obj->dp);
267 $this->datepaye = $this->db->jdate($obj->dp);
268 $this->num_payment = $obj->num_payment;
269 $this->montant = $obj->amount; // deprecated
270 $this->amount = $obj->amount;
271 $this->multicurrency_amount = $obj->multicurrency_amount;
272 $this->note = $obj->note;
273 $this->note_private = $obj->note;
274 $this->type_label = $obj->type_label;
275 $this->type_code = $obj->type_code;
276 $this->statut = $obj->statut;
277 $this->ext_payment_id = $obj->ext_payment_id;
278 $this->ext_payment_site = $obj->ext_payment_site;
279
280 $this->bank_account = $obj->fk_account; // deprecated
281 $this->fk_account = $obj->fk_account;
282 $this->bank_line = $obj->fk_bank;
283
284 $this->fetch_optionals();
285 $this->db->free($resql);
286 return 1;
287 } else {
288 $this->db->free($resql);
289 return 0;
290 }
291 } else {
292 dol_print_error($this->db);
293 return -1;
294 }
295 }
296
309 public function create($user, $closepaidinvoices = 0, $thirdparty = null)
310 {
311 global $conf, $langs;
312
313 $error = 0;
314 $way = $this->getWay(); // 'dolibarr' to use amount, 'customer' to use foreign multicurrency amount
315
316 $now = dol_now();
317
318 // Clean parameters
319 $totalamount = 0;
320 $totalamount_converted = 0;
321 $atleastonepaymentnotnull = 0;
322
323 if ($way == 'dolibarr') { // Payments were entered into the column of main currency
324 $amounts = &$this->amounts;
325 $amounts_to_update = &$this->multicurrency_amounts;
326 } else { // Payments were entered into the column of foreign currency
327 $amounts = &$this->multicurrency_amounts;
328 $amounts_to_update = &$this->amounts;
329 }
330
331 $currencyofpayment = '';
332 $currencyofinvoices = '';
333 $currencytxofpayment = '';
334
335 foreach ($amounts as $key => $value) { // How payment is dispatched. $key is ID of invoice
336 if (empty($value)) {
337 continue;
338 }
339 $value_converted = false;
340 // getInvoiceRate() returns false when the invoice cannot be read, so the result must
341 // be tested before being indexed, as PaiementFourn::create() already does. Without
342 // this the rate is read from a boolean, which emits a PHP warning and leaves it null,
343 // so no conversion is made and the payment is refused later on with
344 // 'Payment in same currency than company but this->amount != this->multicurrency_amount'.
345 $tmparray = MultiCurrency::getInvoiceRate($key, 'facture');
346 if ($tmparray === false) {
347 $this->error = $langs->trans('FailedToFoundTheConversionRateForInvoice');
348 return -1;
349 }
350 $invoice_multicurrency_tx = $tmparray['invoice_multicurrency_tx'];
351 $invoice_multicurrency_code = $tmparray['invoice_multicurrency_code'];
352
353 // $key is id of invoice, $value is amount, $way is 'dolibarr' if amount is in main currency, 'customer' if in foreign currency
354 if ($invoice_multicurrency_tx) {
355 if ($way == 'dolibarr') {
356 $value_converted = (float) price2num($value * $invoice_multicurrency_tx, 'MU');
357 } else {
358 // A payment that settles the whole remaining amount in the foreign currency must
359 // clear the invoice: dividing by the rate and rounding can leave or take one cent,
360 // which keeps the invoice partially paid, so take the remaining amount directly.
361 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
362 $invoice = new Facture($this->db);
363 $invoice->fetch($key);
364 if ((float) price2num($value, 'MT') == (float) $invoice->getRemainToPay(1)) {
365 $value_converted = (float) $invoice->getRemainToPay(0);
366 } else {
367 $value_converted = (float) price2num($value / $invoice_multicurrency_tx, 'MU');
368 }
369 }
370 } else {
371 $invoice_multicurrency_tx = false;
372 }
373
374 // Add controls of input validity
375 if ($value_converted === false) {
376 // We failed to find the conversion for one invoice
377 $this->error = $langs->trans('FailedToFoundTheConversionRateForInvoice');
378 return -1;
379 }
380
381 // Set the currency of the invoice
382 $currencyofinvoiceforthisline = empty($this->multicurrency_code[$key]) ? $invoice_multicurrency_code : $this->multicurrency_code[$key];
383 // If a payment was entered into the section of the foreign currency of invoice, we want to pay in the currency of invoice
384 $currencyofpaymentforthisline = empty($this->multicurrency_amounts[$key]) ? $conf->currency : $this->multicurrency_code[$key];
385
386 //var_dump("Invoice ID: ".$key.", amount in company cur:".$this->amounts[$key]." amount in invoice cur:".$this->multicurrency_amounts[$key]." => currencyofinvoice= ".$currencyofinvoiceforthisline." - currencyofpaymentforthisline =".$currencyofpaymentforthisline);
387
388 if (empty($currencyofinvoices)) {
389 $currencyofinvoices = $currencyofinvoiceforthisline;
390 } elseif ($currencyofinvoices != $currencyofinvoiceforthisline) {
391 // If we have invoices with different currencies in the payment, we stop here
392 $this->error = 'ErrorYouTryToPayInvoicesWithDifferentCurrenciesInSamePayment';
393 return -1;
394 }
395
396 if (empty($currencyofpayment)) {
397 $currencyofpayment = $currencyofpaymentforthisline;
398 } elseif ($currencyofpayment != $currencyofpaymentforthisline) {
399 // If we have invoices with different currencies in the payment, we stop here
400 $this->error = 'ErrorYouTryToPayInvoicesWithDifferentCurrenciesInSamePayment';
401 return -1;
402 }
403
404 if (empty($currencytxofpayment)) {
405 $currencytxofpayment = isset($this->multicurrency_tx[$key]) ? $this->multicurrency_tx[$key] : "";
406 }
407
408 $totalamount_converted += $value_converted; // Total in currency of the invoice
409 $amounts_to_update[$key] = price2num($value_converted, 'MT');
410
411 $newvalue = price2num($value, 'MT');
412 $amounts[$key] = $newvalue;
413 $totalamount += $newvalue;
414 if (!empty($newvalue)) {
415 $atleastonepaymentnotnull++;
416 }
417
418 //var_dump('currencytxofpayment = '.$currencytxofpayment." totalamount_converted =".$totalamount_converted);
419 //print '<br>';
420 }
421
422 if (empty($currencyofpayment)) { // Should not happen. For the case the multicurrency_code was not saved into invoices
423 $currencyofpayment = $conf->currency;
424 }
425
426 if (!empty($currencyofpayment && !empty($this->fk_account))) {
427 // We must check that the currency of invoices is the same than the currency of the bank
428 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
429 $bankaccount = new Account($this->db);
430 $bankaccount->fetch((int) $this->fk_account);
431 $bankcurrencycode = empty($bankaccount->currency_code) ? $conf->currency : $bankaccount->currency_code;
432
433 if ($bankcurrencycode != $conf->currency) {
434 // If we try to pay on a bank with a different currency
435 if ($bankcurrencycode != $currencyofinvoices && $currencyofinvoices != $conf->currency) {
436 $langs->load("errors");
437 $this->error = $langs->trans('ErrorYouTryToPayInvoicesInACurrencyFromBankWithAnotherCurrency', $currencyofinvoices, $bankcurrencycode);
438 return -1;
439 }
440 if ($bankcurrencycode != $currencyofpayment && $currencyofpayment != $conf->currency) {
441 $langs->load("errors");
442 $this->error = $langs->trans('ErrorYouTryToPayInvoicesInACurrencyFromBankWithAnotherCurrency', $currencyofpayment, $bankcurrencycode);
443 return -1;
444 }
445 } else {
446 // No problem in this case
447 }
448 }
449
450 $totalamount = (float) price2num($totalamount, 'MT');
451 $totalamount_converted = (float) price2num($totalamount_converted, 'MT');
452
453 // Check parameters
454 if (empty($totalamount) && empty($atleastonepaymentnotnull)) { // We accept negative amounts for withdraw reject but not empty arrays
455 $this->errors[] = 'TotalAmountEmpty';
456 $this->error = $langs->trans('TotalAmountEmpty');
457 return -1;
458 }
459
460 dol_syslog(get_class($this)."::create insert paiement (closepaidinvoices = ".$closepaidinvoices.")", LOG_DEBUG);
461
462 $this->db->begin();
463
464 $this->ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : '');
465
466 if (empty($this->ref_ext)) {
467 $this->ref_ext = '';
468 }
469
470 if ($way == 'dolibarr') {
471 $total = $totalamount;
472 $mtotal = $totalamount_converted;
473 } else {
474 $total = $totalamount_converted;
475 $mtotal = $totalamount;
476 }
477
478 $num_payment = $this->num_payment;
479 $note = ($this->note_private ? $this->note_private : $this->note);
480
481 $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)";
482 $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).", ";
483 $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).")";
484
485 $resql = $this->db->query($sql);
486 if ($resql) {
487 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');
488
489 // Insert links amount / invoices
490 foreach ($this->amounts as $key => $amount) {
491 $facid = $key;
492 if (is_numeric($amount) && $amount != 0) {
493 $amount = price2num($amount);
494 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount, multicurrency_amount, multicurrency_code, multicurrency_tx)";
495 $sql .= " VALUES (".((int) $facid).", ".((int) $this->id).", ".((float) $amount).", ".((float) $this->multicurrency_amounts[$key]).", ".($currencyofpayment ? "'".$this->db->escape($currencyofpayment)."'" : 'NULL').", ".(!empty($this->multicurrency_tx) ? (float) $currencytxofpayment : 1).")";
496
497 dol_syslog(get_class($this).'::create Amount line '.$key.' insert paiement_facture', LOG_DEBUG);
498 $resql = $this->db->query($sql);
499 if ($resql) {
500 $invoice = new Facture($this->db);
501 $invoice->fetch($facid);
502
503 // If we want to closed paid invoices
504 if ($closepaidinvoices) {
505 $paiement = $invoice->getSommePaiement();
506 $creditnotes = $invoice->getSumCreditNotesUsed();
507 $deposits = $invoice->getSumDepositsUsed();
508 $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
509 $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
510
511 //var_dump($invoice->total_ttc.' - '.$paiement.' -'.$creditnotes.' - '.$deposits.' - '.$remaintopay);exit;
512
513 //Invoice types that are eligible for changing status to paid
514 $affected_types = array(
520 );
521
522 if (!in_array($invoice->type, $affected_types)) {
523 dol_syslog("Invoice ".$facid." is not a standard, nor replacement invoice, nor credit note, nor deposit invoice, nor situation invoice. We do nothing more.");
524 } elseif ($remaintopay) {
525 // hook to have an option to automatically close a closable invoice with less payment than the total amount (e.g. agreed cash discount terms)
526 global $hookmanager;
527 $hookmanager->initHooks(array('paymentdao'));
528 $parameters = array('facid' => $facid, 'invoice' => $invoice, 'remaintopay' => $remaintopay);
529 $action = 'CLOSEPAIDINVOICE';
530 $reshook = $hookmanager->executeHooks('createPayment', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
531 if ($reshook < 0) {
532 $this->errors[] = $hookmanager->error;
533 $this->error = $hookmanager->error;
534 $error++;
535 } elseif ($reshook == 0) {
536 dol_syslog("Remain to pay for invoice " . $facid . " not null. We do nothing more.");
537 }
538 // } else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
539 } else {
540 // Here $remaintopay is 0.
541
542 // If invoice is a down payment, we also convert down payment to discount
543 if ($invoice->type == Facture::TYPE_DEPOSIT) {
544 $amount_ht = $amount_tva = $amount_ttc = array();
545 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
546 '
547 @phan-var-force array<string,float> $amount_ht
548 @phan-var-force array<string,float> $amount_tva
549 @phan-var-force array<string,float> $amount_ttc
550 @phan-var-force array<string,float> $multicurrency_amount_ht
551 @phan-var-force array<string,float> $multicurrency_amount_tva
552 @phan-var-force array<string,float> $multicurrency_amount_ttc
553 ';
554
555 // Insert one discount by VAT rate category
556 $discount = new DiscountAbsolute($this->db);
557 $discount->fetch(0, $invoice->id);
558 if (empty($discount->id)) { // If the invoice was not yet converted into a discount (this may have been done manually before we come here)
559 $discount->description = '(DEPOSIT)';
560 $discount->fk_soc = $invoice->socid;
561 $discount->socid = $invoice->socid;
562 $discount->fk_facture_source = $invoice->id;
563
564 // Loop on each vat rate
565 // Bucket by tva_tx and vat_src_code so the generated discount keeps the source VAT code
566 $i = 0;
567 foreach ($invoice->lines as $line) {
568 if ($line->product_type != 9 && $line->total_ht != 0) { // no need to create discount if amount is null or is special product
569 $key = $line->tva_tx.'|'.(string) $line->vat_src_code;
570 if (!array_key_exists($key, $amount_ht)) {
571 $amount_ht[$key] = 0.0;
572 $amount_tva[$key] = 0.0;
573 $amount_ttc[$key] = 0.0;
574 $multicurrency_amount_ht[$key] = 0.0;
575 $multicurrency_amount_tva[$key] = 0.0;
576 $multicurrency_amount_ttc[$key] = 0.0;
577 }
578 $amount_ht[$key] += $line->total_ht;
579 $amount_tva[$key] += $line->total_tva;
580 $amount_ttc[$key] += $line->total_ttc;
581 $multicurrency_amount_ht[$key] += $line->multicurrency_total_ht;
582 $multicurrency_amount_tva[$key] += $line->multicurrency_total_tva;
583 $multicurrency_amount_ttc[$key] += $line->multicurrency_total_ttc;
584 $i++;
585 }
586 }
587
588 foreach ($amount_ht as $keyfordiscount => $xxx) {
589 $parts = explode('|', (string) $keyfordiscount, 2);
590 $tva_tx = $parts[0];
591 $vat_src_code = isset($parts[1]) ? $parts[1] : '';
592 $discount->amount_ht = abs($amount_ht[$keyfordiscount]);
593 $discount->total_ht = abs($amount_ht[$keyfordiscount]);
594 $discount->amount_tva = abs($amount_tva[$keyfordiscount]);
595 $discount->total_tva = abs($amount_tva[$keyfordiscount]);
596 $discount->amount_ttc = abs($amount_ttc[$keyfordiscount]);
597 $discount->total_ttc = abs($amount_ttc[$keyfordiscount]);
598 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$keyfordiscount]);
599 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$keyfordiscount]);
600 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$keyfordiscount]);
601 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$keyfordiscount]);
602 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$keyfordiscount]);
603 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$keyfordiscount]);
604 $discount->tva_tx = abs((float) $tva_tx);
605 $discount->vat_src_code = $vat_src_code;
606
607 $result = $discount->create($user);
608 if ($result < 0) {
609 $error++;
610 break;
611 }
612 }
613 }
614
615 if ($error) {
616 $this->error = $discount->error;
617 $this->errors = $discount->errors;
618 $error++;
619 }
620 }
621
622 // Set invoice to paid
623 if (!$error) {
624 $invoice->context['actionmsgmore'] = 'Invoice set to paid by the payment->create() of payment '.$this->ref.' because the remain to pay is 0';
625
626 $result = $invoice->setPaid($user, '', '');
627 if ($result < 0) {
628 $this->error = $invoice->error;
629 $this->errors = $invoice->errors;
630 $error++;
631 }
632 }
633 }
634 }
635
636 // Regenerate documents of invoices
637 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
638 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);
639
640 $newlang = '';
641 $outputlangs = $langs;
642 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
643 $invoice->fetch_thirdparty();
644 $newlang = $invoice->thirdparty->default_lang;
645 }
646 if (!empty($newlang)) {
647 $outputlangs = new Translate("", $conf);
648 $outputlangs->setDefaultLang($newlang);
649 }
650
651 $hidedetails = getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0;
652 $hidedesc = getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0;
653 $hideref = getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0;
654
655 $ret = $invoice->fetch($facid); // Reload to get new records
656
657 $result = $invoice->generateDocument($invoice->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
658
659 dol_syslog(get_class($this).'::create Regenerate end result='.$result, LOG_DEBUG);
660
661 $this->warnings = $invoice->warnings;
662
663 if ($result < 0) {
664 $this->error = $invoice->error;
665 $this->errors = $invoice->errors;
666 $error++;
667 }
668 }
669 } else {
670 $this->error = $this->db->lasterror();
671 $error++;
672 }
673 } else {
674 dol_syslog(get_class($this).'::Create Amount line '.$key.' not a number. We discard it.');
675 }
676 }
677
678 dol_syslog(get_class($this).'::create Now we call the triggers if no error (error = '.$error.')', LOG_DEBUG);
679
680 if (!$error) { // All payments into $this->amounts were recorded without errors
681 // Call triggers
682 $result = $this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user);
683 if ($result < 0) {
684 $error++;
685 }
686 // Fin appel triggers
687 }
688 } else {
689 $this->error = $this->db->lasterror();
690 $error++;
691 }
692
693 if (!$error) {
694 // Set some properties that may be used by other process after calling the create
695 $this->amount = $total;
696 $this->total = $total; // deprecated
697 $this->multicurrency_amount = $mtotal;
698 $this->multicurrency_currency = $currencyofinvoices;
699
700 $this->db->commit();
701 return $this->id;
702 } else {
703 $this->db->rollback();
704 return -1;
705 }
706 }
707
708
718 public function delete($user, $notrigger = 0)
719 {
720 $bank_line_id = $this->bank_line;
721
722 $this->db->begin();
723
724 // Check if payment is completely paid, if payments are shared, we refuse deletion.
725 // TODO Check also if partially paid
726 $billsarray = $this->getBillsArray('f.fk_statut:>:1');
727 if (is_array($billsarray)) {
728 if (count($billsarray)) {
729 $this->error = "ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible";
730 $this->db->rollback();
731 return -1;
732 }
733 } else {
734 $this->db->rollback();
735 return -2;
736 }
737
738 // Delete bank urls. If payment is on a conciliated line, return error.
739 if ($bank_line_id > 0) {
740 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
741 $accline = new AccountLine($this->db);
742
743 $result = $accline->fetch($bank_line_id);
744 if ($result == 0) {
745 $accline->id = $accline->rowid = $bank_line_id; // If not found, we set artificially rowid to allow delete of llx_bank_url
746 }
747
748 // Delete bank account url lines linked to payment
749 $result = $accline->delete_urls($user);
750 if ($result < 0) {
751 $this->error = $accline->error;
752 $this->db->rollback();
753 return -3;
754 }
755
756 // Delete bank account lines linked to payment
757 $result = $accline->delete($user);
758 if ($result < 0) {
759 $this->error = $accline->error;
760 $this->db->rollback();
761 return -4;
762 }
763 }
764
765 if (!$notrigger) {
766 // Call triggers
767 $result = $this->call_trigger('PAYMENT_CUSTOMER_DELETE', $user);
768 if ($result < 0) {
769 $this->db->rollback();
770 return -1;
771 }
772 // End call triggers
773 }
774
775 $this->deleteExtraFields();
776 // Delete payment (into paiement_facture and paiement)
777 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement_facture';
778 $sql .= ' WHERE fk_paiement = '.((int) $this->id);
779 dol_syslog($sql);
780 $result = $this->db->query($sql);
781 if ($result) {
782 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement';
783 $sql .= " WHERE rowid = ".((int) $this->id);
784 dol_syslog($sql);
785 $result = $this->db->query($sql);
786 if (!$result) {
787 $this->error = $this->db->lasterror();
788 $this->db->rollback();
789 return -3;
790 }
791
792 $this->db->commit();
793 return 1;
794 } else {
795 $this->error = $this->db->error;
796 $this->db->rollback();
797 return -5;
798 }
799 }
800
801
817 public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger = 0, $accountancycode = '', $addbankurl = '')
818 {
819 global $conf, $user;
820
821 $error = 0;
822 $bank_line_id = 0;
823
824 // Note: ->amount (amount in company currency) ant multicurrency_amount (amount in )was set by the ->create beforecalling this.
825 // The create had also checked that currency of payment is same than currency of bank account
826
827 if (isModEnabled("bank")) {
828 if ($accountid <= 0) {
829 $this->error = 'Bad value for parameter accountid='.$accountid;
830 dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR);
831 return -1;
832 }
833
834 $this->fk_account = $accountid;
835
836 dol_syslog("addPaymentToBank ".$user->id.", ".$mode.", ".$label.", ".$this->fk_account.", ".$emetteur_nom.", ".$emetteur_banque);
837
838 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
839 $acc = new Account($this->db);
840 $result = $acc->fetch($this->fk_account);
841 if ($result < 0) {
842 $this->error = $acc->error;
843 $this->errors = $acc->errors;
844 $error++;
845 return -1;
846 }
847
848 $this->db->begin();
849
850 $totalamount = $this->amount;
851 $totalamount_main_currency = null;
852 if (empty($totalamount)) {
853 $totalamount = $this->total; // For backward compatibility
854 }
855
856 // this->amount is amount of payment in company currency
857 // this->multicurrency_amount of payment in other currency
858 // this->multicurrency_currency is the currency of the payment (may be same than the company one)
859 if ($this->multicurrency_currency == $conf->currency) {
860 if ($this->amount != $this->multicurrency_amount) {
861 // Add protection, should not happen
862 $error++;
863 $this->error = 'Payment in same currency than company but this->amount != this->multicurrency_amount';
864 }
865 }
866
867 // if company 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)
868 if ($conf->currency != $acc->currency_code) {
869 $totalamount = $this->multicurrency_amount; // We will insert into llx_bank.amount in foreign currency of invoice
870 $totalamount_main_currency = $this->amount; // We will also save the amount in main currency into column llx_bank.amount_main_currency
871 }
872
873 if ($mode == 'payment_supplier') {
874 $totalamount = -$totalamount;
875 if (isset($totalamount_main_currency)) {
876 $totalamount_main_currency = -$totalamount_main_currency;
877 }
878 }
879
880 // Insert payment into llx_bank
881 $bank_line_id = $acc->addline(
882 $this->datepaye,
883 $this->paiementcode ? $this->paiementcode : $this->paiementid, // Payment mode code ('CB', 'CHQ' or 'VIR' for example). Use payment id if not defined for backward compatibility.
884 $label,
885 $totalamount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note)
886 $this->num_payment,
887 0,
888 $user,
889 $emetteur_nom,
890 $emetteur_banque,
891 $accountancycode,
892 0,
893 '',
894 (float) $totalamount_main_currency
895 );
896
897 // Update fk_bank in llx_paiement
898 // This way we know the payment that generated the bank entry
899 if ($bank_line_id > 0) {
900 $result = $this->update_fk_bank($bank_line_id);
901 if ($result <= 0) {
902 $error++;
903 dol_print_error($this->db);
904 }
905
906 // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction
907 if (!$error) {
908 $url = '';
909 if ($mode == 'payment') {
910 $url = DOL_URL_ROOT.'/compta/paiement/card.php?id=';
911 }
912 if ($mode == 'payment_supplier') {
913 $url = DOL_URL_ROOT.'/fourn/paiement/card.php?id=';
914 }
915 if ($url) {
916 $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode);
917 if ($result <= 0) {
918 $error++;
919 dol_print_error($this->db);
920 }
921 }
922 }
923
924 // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
925 if (!$error) {
926 $linkaddedforthirdparty = array();
927 foreach ($this->amounts as $key => $value) { // We should have invoices always for same third party but we loop in case of.
928 // Skip the invoices that were listed but not paid, the same way create() does. Without this,
929 // a 'company' link is added to the bank line for a third party that received no payment.
930 if (!is_numeric($value) || $value == 0) {
931 continue;
932 }
933 if ($mode == 'payment') {
934 $fac = new Facture($this->db);
935 $fac->fetch($key);
936 $fac->fetch_thirdparty();
937 if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty @phan-suppress-current-line PhanPossiblyUndeclaredVariable
938 $result = $acc->add_url_line(
939 $bank_line_id,
940 $fac->thirdparty->id,
941 DOL_URL_ROOT.'/comm/card.php?socid=',
942 (string) $fac->thirdparty->name,
943 'company'
944 );
945 if ($result <= 0) {
946 $error++;
947 dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
948 }
949 $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty
950 }
951 }
952 if ($mode == 'payment_supplier') {
953 $fac = new FactureFournisseur($this->db);
954 $fac->fetch($key);
955 $fac->fetch_thirdparty();
956 if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { // Not yet done for this thirdparty
957 $result = $acc->add_url_line(
958 $bank_line_id,
959 $fac->thirdparty->id,
960 DOL_URL_ROOT.'/fourn/card.php?socid=',
961 (string) $fac->thirdparty->name,
962 'company'
963 );
964 if ($result <= 0) {
965 $error++;
966 dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror());
967 }
968 $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty
969 }
970 }
971 }
972 }
973
974 // Add a link to the Direct Debit ('direct-debit') or Credit transfer ('credit-transfer') file in bank_url
975 if (!$error && $addbankurl && in_array($addbankurl, array('direct-debit', 'credit-transfer'))) {
976 $result = $acc->add_url_line(
977 $bank_line_id,
978 $this->id_prelevement,
979 DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
980 $this->num_payment,
981 $addbankurl
982 );
983 }
984
985 // Add link to the Direct Debit if invoice refused ('InvoiceRefused') in bank_url
986 if (!$error && $label == '(InvoiceRefused)') {
987 $result = $acc->add_url_line(
988 $bank_line_id,
989 $this->id_prelevement,
990 DOL_URL_ROOT.'/compta/prelevement/card.php?id=',
991 $this->num_prelevement,
992 'withdraw'
993 );
994 }
995
996 if (!$error && !$notrigger) {
997 // Call triggers
998 $result = $this->call_trigger('PAYMENT_ADD_TO_BANK', $user);
999 if ($result < 0) {
1000 $error++;
1001 }
1002 // Fin appel triggers
1003 }
1004 } else {
1005 $this->error = $acc->error;
1006 $this->errors = $acc->errors;
1007 $error++;
1008 }
1009
1010 if (!$error) {
1011 $this->db->commit();
1012 } else {
1013 $this->db->rollback();
1014 }
1015 }
1016
1017 if (!$error) {
1018 return $bank_line_id;
1019 } else {
1020 return -1;
1021 }
1022 }
1023
1024
1025 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1032 public function update_fk_bank($id_bank)
1033 {
1034 // phpcs:enable
1035 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.((int) $id_bank);
1036 $sql .= " WHERE rowid = ".((int) $this->id);
1037
1038 dol_syslog(get_class($this).'::update_fk_bank', LOG_DEBUG);
1039 $result = $this->db->query($sql);
1040 if ($result) {
1041 return 1;
1042 } else {
1043 $this->error = $this->db->lasterror();
1044 dol_syslog(get_class($this).'::update_fk_bank '.$this->error);
1045 return -1;
1046 }
1047 }
1048
1049 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1056 public function update_date($date)
1057 {
1058 // phpcs:enable
1059 $error = 0;
1060
1061 if (!empty($date) && $this->statut != 1) {
1062 $this->db->begin();
1063
1064 dol_syslog(get_class($this)."::update_date with date = ".$date, LOG_DEBUG);
1065
1066 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1067 $sql .= " SET datep = '".$this->db->idate($date)."'";
1068 $sql .= " WHERE rowid = ".((int) $this->id);
1069
1070 $result = $this->db->query($sql);
1071 if (!$result) {
1072 $error++;
1073 $this->error = 'Error -1 '.$this->db->error();
1074 }
1075
1076 $type = $this->element;
1077
1078 $sql = "UPDATE ".MAIN_DB_PREFIX.'bank';
1079 $sql .= " SET dateo = '".$this->db->idate($date)."', datev = '".$this->db->idate($date)."'";
1080 $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).")";
1081 $sql .= " AND rappro = 0";
1082
1083 $result = $this->db->query($sql);
1084 if (!$result) {
1085 $error++;
1086 $this->error = 'Error -1 '.$this->db->error();
1087 }
1088
1089 if (!$error) {
1090 $this->datepaye = $date;
1091 $this->date = $date;
1092
1093 $this->db->commit();
1094 return 0;
1095 } else {
1096 $this->db->rollback();
1097 return -2;
1098 }
1099 }
1100 return -1; //no date given or already validated
1101 }
1102
1103 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1110 public function update_num($num_payment)
1111 {
1112 // phpcs:enable
1113 if (!empty($num_payment) && $this->statut != 1) {
1114 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1115 $sql .= " SET num_paiement = '".$this->db->escape($num_payment)."'";
1116 $sql .= " WHERE rowid = ".((int) $this->id);
1117
1118 dol_syslog(get_class($this)."::update_num", LOG_DEBUG);
1119 $result = $this->db->query($sql);
1120 if ($result) {
1121 $this->num_payment = $this->db->escape($num_payment);
1122
1123 // Update Num in bank
1124 $type = $this->element;
1125 $sql = "UPDATE ".MAIN_DB_PREFIX.'bank';
1126 $sql .= " SET num_chq = '".$this->db->escape($num_payment)."'";
1127 $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).")";
1128 $sql .= " AND rappro = 0";
1129 $result = $this->db->query($sql);
1130 if (!$result) {
1131 $this->error = 'Error -1 '.$this->db->error();
1132 }
1133 return 0;
1134 } else {
1135 $this->error = 'Error -1 '.$this->db->error();
1136 return -2;
1137 }
1138 }
1139 return -1; //no num given or already validated
1140 }
1141
1149 public function valide($user = null)
1150 {
1151 return $this->validate($user);
1152 }
1153
1160 public function validate($user = null)
1161 {
1162 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.((int) $this->id);
1163
1164 dol_syslog(get_class($this).'::valide', LOG_DEBUG);
1165 $result = $this->db->query($sql);
1166 if ($result) {
1167 return 1;
1168 } else {
1169 $this->error = $this->db->lasterror();
1170 dol_syslog(get_class($this).'::valide '.$this->error);
1171 return -1;
1172 }
1173 }
1174
1181 public function reject($user = null)
1182 {
1183 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 2 WHERE rowid = '.((int) $this->id);
1184
1185 dol_syslog(get_class($this).'::reject', LOG_DEBUG);
1186 $result = $this->db->query($sql);
1187 if ($result) {
1188 return 1;
1189 } else {
1190 $this->error = $this->db->lasterror();
1191 dol_syslog(get_class($this).'::reject '.$this->error);
1192 return -1;
1193 }
1194 }
1195
1202 public function info($id)
1203 {
1204 $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms';
1205 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p';
1206 $sql .= ' WHERE p.rowid = '.((int) $id);
1207
1208 dol_syslog(get_class($this).'::info', LOG_DEBUG);
1209 $result = $this->db->query($sql);
1210
1211 if ($result) {
1212 if ($this->db->num_rows($result)) {
1213 $obj = $this->db->fetch_object($result);
1214
1215 $this->id = $obj->rowid;
1216
1217 $this->user_creation_id = $obj->fk_user_creat;
1218 $this->user_modification_id = $obj->fk_user_modif;
1219 $this->date_creation = $this->db->jdate($obj->datec);
1220 $this->date_modification = $this->db->jdate($obj->tms);
1221 }
1222 $this->db->free($result);
1223 } else {
1224 dol_print_error($this->db);
1225 }
1226 }
1227
1235 public function getBillsArray($filter = '')
1236 {
1237 $sql = 'SELECT pf.fk_facture';
1238 $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
1239 $sql .= ' WHERE pf.fk_facture = f.rowid AND pf.fk_paiement = '.((int) $this->id);
1240 if ($filter) {
1241 $sql .= forgeSQLFromUniversalSearchCriteria($filter);
1242 }
1243 $resql = $this->db->query($sql);
1244 if ($resql) {
1245 $i = 0;
1246 $num = $this->db->num_rows($resql);
1247 $billsarray = array();
1248
1249 while ($i < $num) {
1250 $obj = $this->db->fetch_object($resql);
1251 $billsarray[$i] = $obj->fk_facture;
1252 $i++;
1253 }
1254
1255 return $billsarray;
1256 } else {
1257 $this->error = $this->db->error();
1258 dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG);
1259 return -1;
1260 }
1261 }
1262
1269 public function getAmountsArray()
1270 {
1271 $sql = 'SELECT pf.fk_facture, pf.amount';
1272 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
1273 $sql .= ' WHERE pf.fk_paiement = '.((int) $this->id);
1274 $resql = $this->db->query($sql);
1275 if ($resql) {
1276 $i = 0;
1277 $num = $this->db->num_rows($resql);
1278 $amounts = array();
1279
1280 while ($i < $num) {
1281 $obj = $this->db->fetch_object($resql);
1282 $amounts[$obj->fk_facture] = $obj->amount;
1283 $i++;
1284 }
1285
1286 return $amounts;
1287 } else {
1288 $this->error = $this->db->error();
1289 dol_syslog(get_class($this).'::getAmountsArray Error '.$this->error.' -', LOG_DEBUG);
1290 return -1;
1291 }
1292 }
1293
1302 public function getNextNumRef($soc, $mode = 'next')
1303 {
1304 global $conf, $db, $langs;
1305 $langs->load("bills");
1306
1307 // Clean parameters (if not defined or using deprecated value)
1308 if (!getDolGlobalString('PAYMENT_ADDON')) {
1309 $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
1310 } elseif (getDolGlobalString('PAYMENT_ADDON') == 'ant') {
1311 $conf->global->PAYMENT_ADDON = 'mod_payment_ant';
1312 } elseif (getDolGlobalString('PAYMENT_ADDON') == 'cicada') {
1313 $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
1314 }
1315
1316 if (getDolGlobalString('PAYMENT_ADDON')) {
1317 $mybool = false;
1318
1319 $file = getDolGlobalString('PAYMENT_ADDON') . ".php";
1320 $classname = getDolGlobalString('PAYMENT_ADDON');
1321
1322 // Include file with class
1323 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1324
1325 foreach ($dirmodels as $reldir) {
1326 $dir = dol_buildpath($reldir."core/modules/payment/");
1327
1328 // Load file with numbering class (if found)
1329 if (is_file($dir.$file) && is_readable($dir.$file)) {
1330 $mybool = (include_once $dir.$file) || $mybool;
1331 }
1332 }
1333
1334 // For compatibility
1335 if (!$mybool) {
1336 $file = getDolGlobalString('PAYMENT_ADDON') . ".php";
1337 $classname = "mod_payment_" . getDolGlobalString('PAYMENT_ADDON');
1338 $classname = preg_replace('/\-.*$/', '', $classname);
1339 // Include file with class
1340 foreach ($conf->file->dol_document_root as $dirroot) {
1341 $dir = $dirroot."/core/modules/payment/";
1342
1343 // Load file with numbering class (if found)
1344 if (is_file($dir.$file) && is_readable($dir.$file)) {
1345 $mybool = (include_once $dir.$file) || $mybool;
1346 }
1347 }
1348 }
1349
1350 if (!$mybool) {
1351 dol_print_error(null, "Failed to include file ".$file);
1352 return '';
1353 }
1354
1355 $obj = new $classname();
1356 '@phan-var-force ModeleNumRefPayments $obj';
1357
1358 $numref = $obj->getNextValue($soc, $this);
1359
1364 if ($mode != 'last' && !$numref) {
1365 dol_print_error($db, "Payment::getNextNumRef ".$obj->error);
1366 return "";
1367 }
1368
1369 return $numref;
1370 } else {
1371 $langs->load("errors");
1372 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Invoice"));
1373 return "";
1374 }
1375 }
1376
1382 public function getWay()
1383 {
1384 $way = 'dolibarr';
1385 if (isModEnabled('multicurrency')) {
1386 foreach ($this->multicurrency_amounts as $value) {
1387 if (!empty($value)) { // one value found into multicurrency_amounts so payment is in invoice currency
1388 $way = 'customer';
1389 break;
1390 }
1391 }
1392 }
1393
1394 return $way;
1395 }
1396
1405 public function initAsSpecimen($option = '')
1406 {
1407 global $user, $langs, $conf;
1408
1409 $now = dol_now();
1410 $arraynow = dol_getdate($now);
1411 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
1412
1413 // Initialize parameters
1414 $this->id = 0;
1415 $this->ref = 'SPECIMEN';
1416 $this->specimen = 1;
1417 $this->facid = 1;
1418 $this->datepaye = $nownotime;
1419
1420 return 1;
1421 }
1422
1423
1431 public function getTooltipContentArray($params)
1432 {
1433 global $conf, $langs;
1434
1435 $datas = array();
1436 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("Payment").'</u>';
1437 $datas['ref'] = '<br><strong>'.$langs->trans("Ref").':</strong> '.$this->ref;
1438 $dateofpayment = ($this->datepaye ? $this->datepaye : $this->date);
1439 if ($dateofpayment) {
1440 $tmparray = dol_getdate($dateofpayment);
1441 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
1442 $datas['date'] = '<br><strong>'.$langs->trans("Date").':</strong> '.dol_print_date($dateofpayment, 'day');
1443 } else { // Hours was set to real date of payment (special case for POS for example)
1444 $datas['date'] = '<br><strong>'.$langs->trans("Date").':</strong> '.dol_print_date($dateofpayment, 'dayhour', 'tzuser');
1445 }
1446 }
1447 if ($this->amount) {
1448 $datas['amount'] = '<br><strong>'.$langs->trans("Amount").':</strong> '.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency);
1449 }
1450
1451 return $datas;
1452 }
1453
1464 public function getNomUrl($withpicto = 0, $option = '', $mode = 'withlistofinvoices', $notooltip = 0, $morecss = '')
1465 {
1466 global $conf, $langs, $hookmanager;
1467
1468 if (!empty($conf->dol_no_mouse_hover)) {
1469 $notooltip = 1; // Force disable tooltips
1470 }
1471
1472 $result = '';
1473
1474 $params = array();
1475 $label = $this->getTooltipContent($params);
1476 if ($mode == 'withlistofinvoices') {
1477 $arraybill = $this->getBillsArray();
1478 if (is_array($arraybill) && count($arraybill) > 0) {
1479 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1480 $facturestatic = new Facture($this->db);
1481 foreach ($arraybill as $billid) {
1482 $facturestatic->fetch($billid);
1483 $label .= '<br> '.$facturestatic->getNomUrl(1, '', 0, 0, '', 1).' '.$facturestatic->getLibStatut(2, -1);
1484 }
1485 }
1486 }
1487
1488 $linkclose = '';
1489 if (empty($notooltip)) {
1490 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1491 $label = $langs->trans("Payment");
1492 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1493 }
1494 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
1495 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1496 } else {
1497 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1498 }
1499
1500 $url = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$this->id;
1501
1502 $linkstart = '<a href="'.$url.'"';
1503 $linkstart .= $linkclose.'>';
1504 $linkend = '</a>';
1505
1506 $result .= $linkstart;
1507 if ($withpicto) {
1508 $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);
1509 }
1510 if ($withpicto && $withpicto != 2) {
1511 $result .= ($this->ref ? $this->ref : $this->id);
1512 }
1513 $result .= $linkend;
1514 global $action;
1515 $hookmanager->initHooks(array($this->element . 'dao'));
1516 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1517 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1518 if ($reshook > 0) {
1519 $result = $hookmanager->resPrint;
1520 } else {
1521 $result .= $hookmanager->resPrint;
1522 }
1523 return $result;
1524 }
1525
1532 public function getLibStatut($mode = 0)
1533 {
1534 return $this->LibStatut($this->statut, $mode);
1535 }
1536
1537 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1545 public function LibStatut($status, $mode = 0)
1546 {
1547 // phpcs:enable
1548 global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
1549
1550 $langs->load('compta');
1551 /*if ($mode == 0)
1552 {
1553 if ($status == 0) return $langs->trans('ToValidate');
1554 if ($status == 1) return $langs->trans('Validated');
1555 }
1556 if ($mode == 1)
1557 {
1558 if ($status == 0) return $langs->trans('ToValidate');
1559 if ($status == 1) return $langs->trans('Validated');
1560 }
1561 if ($mode == 2)
1562 {
1563 if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
1564 if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
1565 }
1566 if ($mode == 3)
1567 {
1568 if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
1569 if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
1570 }
1571 if ($mode == 4)
1572 {
1573 if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
1574 if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
1575 }
1576 if ($mode == 5)
1577 {
1578 if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
1579 if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
1580 }
1581 if ($mode == 6)
1582 {
1583 if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
1584 if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
1585 }*/
1586 return '';
1587 }
1588
1589 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1597 public function fetch_thirdparty($force_thirdparty_id = 0)
1598 {
1599 // phpcs:enable
1600 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1601
1602 if (empty($force_thirdparty_id)) {
1603 $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him
1604 if (!empty($billsarray)) {
1605 $invoice = new Facture($this->db);
1606 if ($invoice->fetch($billsarray[0]) > 0) {
1607 $force_thirdparty_id = $invoice->socid;
1608 }
1609 }
1610 }
1611
1612 return parent::fetch_thirdparty($force_thirdparty_id);
1613 }
1614
1615
1621 public function isReconciled()
1622 {
1623 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
1624 $accountline = new AccountLine($this->db);
1625 $accountline->fetch($this->bank_line);
1626 return $accountline->rappro ? true : false;
1627 }
1628}
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage bank accounts.
Class to manage bank transaction lines.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
getTooltipContent($params)
getTooltipContent
deleteExtraFields()
Delete all extra fields values for the current object.
Class to manage absolute discounts.
Class to manage suppliers invoices.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
static getInvoiceRate($fk_facture, $table='facture')
Get current invoite rate.
Class to manage payments of customer invoices.
addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger=0, $accountancycode='', $addbankurl='')
Add a record into bank for payment + links between this bank record and sources of payment.
__construct($db)
Constructor.
update_num($num_payment)
Updates the payment number.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id into this->thirdparty.
create($user, $closepaidinvoices=0, $thirdparty=null)
Create payment of invoices into database.
getAmountsArray()
Return list of amounts of payments.
getNomUrl($withpicto=0, $option='', $mode='withlistofinvoices', $notooltip=0, $morecss='')
Return clickable name (with picto eventually)
isReconciled()
Return if payment is reconciled.
fetch($id, $ref='', $fk_bank=0)
Load payment from database.
update_fk_bank($id_bank)
Update the link between the Payment and the line generated in llx_bank.
getWay()
get the right way of payment
validate($user=null)
Validate payment.
reject($user=null)
Reject payment.
initAsSpecimen($option='')
Initialise an instance with random values.
LibStatut($status, $mode=0)
Return the label of a given status.
getTooltipContentArray($params)
Return array with content of the tooltip, so the getNomUrl() tooltip becomes hookable (a module can t...
update_date($date)
Updates the payment date.
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
getBillsArray($filter='')
Return list of invoices the payment is related to.
valide($user=null)
Validate payment.
info($id)
Information sur l'objet.
getLibStatut($mode=0)
Return the label of the status.
Class to manage translations.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as p p num_paiement as f pf amount as amount
Definition receipt.php:494
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492