dolibarr 24.0.3
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 dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...)
211 // fk_paiement dans llx_paiement_facture est le rowid du paiement
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 $tmparray = MultiCurrency::getInvoiceRate($key, 'facture');
341 // getInvoiceRate() returns false when the invoice cannot be read, so the result must
342 // be tested before being indexed, as PaiementFourn::create() already does. Without
343 // this the rate is read from a boolean, which emits a PHP warning and leaves it null,
344 // so no conversion is made and the payment is refused later on with
345 // 'Payment in same currency than company but this->amount != this->multicurrency_amount'.
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 // Appel des 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 // Mise a jour fk_bank dans llx_paiement
898 // On connait ainsi le paiement qui a genere l'ecriture bancaire
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 // Appel des 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 return 0;
1123 } else {
1124 $this->error = 'Error -1 '.$this->db->error();
1125 return -2;
1126 }
1127 }
1128 return -1; //no num given or already validated
1129 }
1130
1138 public function valide($user = null)
1139 {
1140 return $this->validate($user);
1141 }
1142
1149 public function validate($user = null)
1150 {
1151 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.((int) $this->id);
1152
1153 dol_syslog(get_class($this).'::valide', LOG_DEBUG);
1154 $result = $this->db->query($sql);
1155 if ($result) {
1156 return 1;
1157 } else {
1158 $this->error = $this->db->lasterror();
1159 dol_syslog(get_class($this).'::valide '.$this->error);
1160 return -1;
1161 }
1162 }
1163
1170 public function reject($user = null)
1171 {
1172 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 2 WHERE rowid = '.((int) $this->id);
1173
1174 dol_syslog(get_class($this).'::reject', LOG_DEBUG);
1175 $result = $this->db->query($sql);
1176 if ($result) {
1177 return 1;
1178 } else {
1179 $this->error = $this->db->lasterror();
1180 dol_syslog(get_class($this).'::reject '.$this->error);
1181 return -1;
1182 }
1183 }
1184
1191 public function info($id)
1192 {
1193 $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms';
1194 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p';
1195 $sql .= ' WHERE p.rowid = '.((int) $id);
1196
1197 dol_syslog(get_class($this).'::info', LOG_DEBUG);
1198 $result = $this->db->query($sql);
1199
1200 if ($result) {
1201 if ($this->db->num_rows($result)) {
1202 $obj = $this->db->fetch_object($result);
1203
1204 $this->id = $obj->rowid;
1205
1206 $this->user_creation_id = $obj->fk_user_creat;
1207 $this->user_modification_id = $obj->fk_user_modif;
1208 $this->date_creation = $this->db->jdate($obj->datec);
1209 $this->date_modification = $this->db->jdate($obj->tms);
1210 }
1211 $this->db->free($result);
1212 } else {
1213 dol_print_error($this->db);
1214 }
1215 }
1216
1224 public function getBillsArray($filter = '')
1225 {
1226 $sql = 'SELECT pf.fk_facture';
1227 $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
1228 $sql .= ' WHERE pf.fk_facture = f.rowid AND pf.fk_paiement = '.((int) $this->id);
1229 if ($filter) {
1230 $sql .= forgeSQLFromUniversalSearchCriteria($filter);
1231 }
1232 $resql = $this->db->query($sql);
1233 if ($resql) {
1234 $i = 0;
1235 $num = $this->db->num_rows($resql);
1236 $billsarray = array();
1237
1238 while ($i < $num) {
1239 $obj = $this->db->fetch_object($resql);
1240 $billsarray[$i] = $obj->fk_facture;
1241 $i++;
1242 }
1243
1244 return $billsarray;
1245 } else {
1246 $this->error = $this->db->error();
1247 dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG);
1248 return -1;
1249 }
1250 }
1251
1258 public function getAmountsArray()
1259 {
1260 $sql = 'SELECT pf.fk_facture, pf.amount';
1261 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
1262 $sql .= ' WHERE pf.fk_paiement = '.((int) $this->id);
1263 $resql = $this->db->query($sql);
1264 if ($resql) {
1265 $i = 0;
1266 $num = $this->db->num_rows($resql);
1267 $amounts = array();
1268
1269 while ($i < $num) {
1270 $obj = $this->db->fetch_object($resql);
1271 $amounts[$obj->fk_facture] = $obj->amount;
1272 $i++;
1273 }
1274
1275 return $amounts;
1276 } else {
1277 $this->error = $this->db->error();
1278 dol_syslog(get_class($this).'::getAmountsArray Error '.$this->error.' -', LOG_DEBUG);
1279 return -1;
1280 }
1281 }
1282
1291 public function getNextNumRef($soc, $mode = 'next')
1292 {
1293 global $conf, $db, $langs;
1294 $langs->load("bills");
1295
1296 // Clean parameters (if not defined or using deprecated value)
1297 if (!getDolGlobalString('PAYMENT_ADDON')) {
1298 $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
1299 } elseif (getDolGlobalString('PAYMENT_ADDON') == 'ant') {
1300 $conf->global->PAYMENT_ADDON = 'mod_payment_ant';
1301 } elseif (getDolGlobalString('PAYMENT_ADDON') == 'cicada') {
1302 $conf->global->PAYMENT_ADDON = 'mod_payment_cicada';
1303 }
1304
1305 if (getDolGlobalString('PAYMENT_ADDON')) {
1306 $mybool = false;
1307
1308 $file = getDolGlobalString('PAYMENT_ADDON') . ".php";
1309 $classname = getDolGlobalString('PAYMENT_ADDON');
1310
1311 // Include file with class
1312 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1313
1314 foreach ($dirmodels as $reldir) {
1315 $dir = dol_buildpath($reldir."core/modules/payment/");
1316
1317 // Load file with numbering class (if found)
1318 if (is_file($dir.$file) && is_readable($dir.$file)) {
1319 $mybool = (include_once $dir.$file) || $mybool;
1320 }
1321 }
1322
1323 // For compatibility
1324 if (!$mybool) {
1325 $file = getDolGlobalString('PAYMENT_ADDON') . ".php";
1326 $classname = "mod_payment_" . getDolGlobalString('PAYMENT_ADDON');
1327 $classname = preg_replace('/\-.*$/', '', $classname);
1328 // Include file with class
1329 foreach ($conf->file->dol_document_root as $dirroot) {
1330 $dir = $dirroot."/core/modules/payment/";
1331
1332 // Load file with numbering class (if found)
1333 if (is_file($dir.$file) && is_readable($dir.$file)) {
1334 $mybool = (include_once $dir.$file) || $mybool;
1335 }
1336 }
1337 }
1338
1339 if (!$mybool) {
1340 dol_print_error(null, "Failed to include file ".$file);
1341 return '';
1342 }
1343
1344 $obj = new $classname();
1345 '@phan-var-force ModeleNumRefPayments $obj';
1346
1347 $numref = $obj->getNextValue($soc, $this);
1348
1353 if ($mode != 'last' && !$numref) {
1354 dol_print_error($db, "Payment::getNextNumRef ".$obj->error);
1355 return "";
1356 }
1357
1358 return $numref;
1359 } else {
1360 $langs->load("errors");
1361 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Invoice"));
1362 return "";
1363 }
1364 }
1365
1371 public function getWay()
1372 {
1373 $way = 'dolibarr';
1374 if (isModEnabled('multicurrency')) {
1375 foreach ($this->multicurrency_amounts as $value) {
1376 if (!empty($value)) { // one value found into multicurrency_amounts so payment is in invoice currency
1377 $way = 'customer';
1378 break;
1379 }
1380 }
1381 }
1382
1383 return $way;
1384 }
1385
1394 public function initAsSpecimen($option = '')
1395 {
1396 global $user, $langs, $conf;
1397
1398 $now = dol_now();
1399 $arraynow = dol_getdate($now);
1400 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
1401
1402 // Initialize parameters
1403 $this->id = 0;
1404 $this->ref = 'SPECIMEN';
1405 $this->specimen = 1;
1406 $this->facid = 1;
1407 $this->datepaye = $nownotime;
1408
1409 return 1;
1410 }
1411
1412
1423 public function getNomUrl($withpicto = 0, $option = '', $mode = 'withlistofinvoices', $notooltip = 0, $morecss = '')
1424 {
1425 global $conf, $langs, $hookmanager;
1426
1427 if (!empty($conf->dol_no_mouse_hover)) {
1428 $notooltip = 1; // Force disable tooltips
1429 }
1430
1431 $result = '';
1432
1433 $label = img_picto('', $this->picto).' <u>'.$langs->trans("Payment").'</u><br>';
1434 $label .= '<strong>'.$langs->trans("Ref").':</strong> '.$this->ref;
1435 $dateofpayment = ($this->datepaye ? $this->datepaye : $this->date);
1436 if ($dateofpayment) {
1437 $label .= '<br><strong>'.$langs->trans("Date").':</strong> ';
1438 $tmparray = dol_getdate($dateofpayment);
1439 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
1440 $label .= dol_print_date($dateofpayment, 'day');
1441 } else { // Hours was set to real date of payment (special case for POS for example)
1442 $label .= dol_print_date($dateofpayment, 'dayhour', 'tzuser');
1443 }
1444 }
1445 if ($this->amount) {
1446 $label .= '<br><strong>'.$langs->trans("Amount").':</strong> '.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency);
1447 }
1448 if ($mode == 'withlistofinvoices') {
1449 $arraybill = $this->getBillsArray();
1450 if (is_array($arraybill) && count($arraybill) > 0) {
1451 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1452 $facturestatic = new Facture($this->db);
1453 foreach ($arraybill as $billid) {
1454 $facturestatic->fetch($billid);
1455 $label .= '<br> '.$facturestatic->getNomUrl(1, '', 0, 0, '', 1).' '.$facturestatic->getLibStatut(2, -1);
1456 }
1457 }
1458 }
1459
1460 $linkclose = '';
1461 if (empty($notooltip)) {
1462 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1463 $label = $langs->trans("Payment");
1464 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1465 }
1466 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
1467 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1468 } else {
1469 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1470 }
1471
1472 $url = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$this->id;
1473
1474 $linkstart = '<a href="'.$url.'"';
1475 $linkstart .= $linkclose.'>';
1476 $linkend = '</a>';
1477
1478 $result .= $linkstart;
1479 if ($withpicto) {
1480 $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);
1481 }
1482 if ($withpicto && $withpicto != 2) {
1483 $result .= ($this->ref ? $this->ref : $this->id);
1484 }
1485 $result .= $linkend;
1486 global $action;
1487 $hookmanager->initHooks(array($this->element . 'dao'));
1488 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1489 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1490 if ($reshook > 0) {
1491 $result = $hookmanager->resPrint;
1492 } else {
1493 $result .= $hookmanager->resPrint;
1494 }
1495 return $result;
1496 }
1497
1504 public function getLibStatut($mode = 0)
1505 {
1506 return $this->LibStatut($this->statut, $mode);
1507 }
1508
1509 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1517 public function LibStatut($status, $mode = 0)
1518 {
1519 // phpcs:enable
1520 global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
1521
1522 $langs->load('compta');
1523 /*if ($mode == 0)
1524 {
1525 if ($status == 0) return $langs->trans('ToValidate');
1526 if ($status == 1) return $langs->trans('Validated');
1527 }
1528 if ($mode == 1)
1529 {
1530 if ($status == 0) return $langs->trans('ToValidate');
1531 if ($status == 1) return $langs->trans('Validated');
1532 }
1533 if ($mode == 2)
1534 {
1535 if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
1536 if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
1537 }
1538 if ($mode == 3)
1539 {
1540 if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
1541 if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
1542 }
1543 if ($mode == 4)
1544 {
1545 if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
1546 if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
1547 }
1548 if ($mode == 5)
1549 {
1550 if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
1551 if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
1552 }
1553 if ($mode == 6)
1554 {
1555 if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
1556 if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
1557 }*/
1558 return '';
1559 }
1560
1561 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1569 public function fetch_thirdparty($force_thirdparty_id = 0)
1570 {
1571 // phpcs:enable
1572 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1573
1574 if (empty($force_thirdparty_id)) {
1575 $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him
1576 if (!empty($billsarray)) {
1577 $invoice = new Facture($this->db);
1578 if ($invoice->fetch($billsarray[0]) > 0) {
1579 $force_thirdparty_id = $invoice->socid;
1580 }
1581 }
1582 }
1583
1584 return parent::fetch_thirdparty($force_thirdparty_id);
1585 }
1586
1587
1593 public function isReconciled()
1594 {
1595 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
1596 $accountline = new AccountLine($this->db);
1597 $accountline->fetch($this->bank_line);
1598 return $accountline->rappro ? true : false;
1599 }
1600}
$object ref
Definition info.php:90
Class to manage bank accounts.
Class to manage bank transaction lines.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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...
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.
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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