dolibarr 25.0.0-alpha
commoninvoice.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
3 * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
4 * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
5 * Copyright (C) 2023-2026 Nick Fragoulis
6 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
9 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
31require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
32require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
33
37abstract class CommonInvoice extends CommonObject
38{
39 use CommonIncoterm;
40
44 public $title;
45
49 public $type = self::TYPE_STANDARD;
50
54 public $subtype;
55
61 public $fk_soc;
65 public $socid;
66
70 public $paye;
71
77 public $date;
78
82 public $date_lim_reglement;
83
87 public $date_pointoftax;
88
92 public $cond_reglement_id; // Id in llx_c_paiement
96 public $cond_reglement_code; // Code in llx_c_paiement
100 public $cond_reglement_label;
104 public $cond_reglement_doc;
105
109 public $mode_reglement_id;
113 public $mode_reglement_code;
114
118 public $mode_reglement;
119
123 public $total_ht;
127 public $total_tva;
131 public $total_localtax1;
135 public $total_localtax2;
139 public $total_ttc;
143 public $revenuestamp;
144
148 public $totalpaid;
152 public $totaldeposits;
156 public $totalcreditnotes;
157
161 public $remaintopay;
165 public $nbofopendirectdebitorcredittransfer;
166
170 public $creditnote_ids;
171
175 public $stripechargedone;
176
180 public $stripechargeerror;
181
185 public $payment_reference;
186
190 public $dispute_status = 0;
191
192
197 public $description;
198
204 public $ref_client;
205
209 public $situation_cycle_ref;
210
214 public $retained_warranty_fk_cond_reglement;
215
221 public $close_code;
222
227 public $close_note;
228
229
234 public $postactionmessages;
235
236
240 const TYPE_STANDARD = 0;
241
246
251
255 const TYPE_DEPOSIT = 3;
256
261 const TYPE_PROFORMA = 4;
262
266 const TYPE_SITUATION = 5;
267
271 const STATUS_DRAFT = 0;
272
277
285 const STATUS_CLOSED = 2;
286
295
296
297 const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandoned (the remain to pay) - escompte
298 const CLOSECODE_BADDEBT = 'badcustomer'; // Abandoned (the remain to pay) - bad customer
299 const CLOSECODE_BANKCHARGE = 'bankcharge'; // Abandoned (the remain to pay) - bank charge
300 const CLOSECODE_WITHHOLDINGTAX = 'withholdingtax'; // Abandoned (the remain to pay) - source tax
301 const CLOSECODE_OTHER = 'other'; // Abandoned (the remain to pay) - other
302 const CLOSECODE_ABANDONED = 'abandon'; // Abandoned (no payment at all) - other
303 const CLOSECODE_REPLACED = 'replaced'; // Abandoned (no payment at all) - replacedby another invoice (feature disabled by default)
304
305 const ARRAY_OF_DISPUTE_STATUS = array(
306 0 => array('label' => "None"),
307 1 => array('label' => "DisputeOpen"),
308 8 => array('label' => "DisputeLost"),
309 9 => array('label' => "DisputeWon")
310 );
311
312
320 public function getRemainToPay($multicurrency = 0)
321 {
322 $alreadypaid = 0.0;
323 $alreadypaid += $this->getSommePaiement($multicurrency);
324 $alreadypaid += $this->getSumDepositsUsed($multicurrency);
325 $alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
326
327 if ((int) $multicurrency > 0) {
328 $totalamount = $this->multicurrency_total_ttc;
329 } else {
330 $totalamount = $this->total_ttc;
331 }
332 $remaintopay = price2num($totalamount - $alreadypaid, 'MT');
333 if ($this->status == self::STATUS_CLOSED && $this->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment
334 $remaintopay = 0.0;
335 }
336 return $remaintopay;
337 }
338
348 public function getSommePaiement($multicurrency = 0)
349 {
350 $table = 'paiement_facture';
351 $field = 'fk_facture';
352 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
353 $table = 'paiementfourn_facturefourn';
354 $field = 'fk_facturefourn';
355 }
356
357 $sql = "SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount";
358 $sql .= " FROM ".$this->db->prefix().$table;
359 $sql .= " WHERE ".$this->db->sanitize($field)." = ".((int) $this->id);
360
361 dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG);
362
363 $resql = $this->db->query($sql);
364 if ($resql) {
365 $obj = $this->db->fetch_object($resql);
366
367 $this->db->free($resql);
368
369 if ($obj) {
370 if ($multicurrency < 0) {
371 $this->totalpaid = $obj->amount;
372 $this->totalpaid_multicurrency = $obj->multicurrency_amount;
373 return array('alreadypaid' => (float) $obj->amount, 'alreadypaid_multicurrency' => (float) $obj->multicurrency_amount);
374 } elseif ($multicurrency) {
375 $this->totalpaid_multicurrency = $obj->multicurrency_amount;
376 return (float) $obj->multicurrency_amount;
377 } else {
378 $this->totalpaid = $obj->amount;
379 return (float) $obj->amount;
380 }
381 } else {
382 return 0;
383 }
384 } else {
385 $this->error = $this->db->lasterror();
386 return -1;
387 }
388 }
389
399 public function getSumDepositsUsed($multicurrency = 0)
400 {
401 /*if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
402 // FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS was never supported for purchase invoice, so we can return 0 with no need of SQL for this case.
403 return 0.0;
404 }*/
405
406 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
407
408 $discountstatic = new DiscountAbsolute($this->db);
409 $result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
410
411 if ($result >= 0) {
412 if ($multicurrency) {
413 $this->totaldeposits_multicurrency = $result;
414 } else {
415 $this->totaldeposits = $result;
416 }
417
418 return $result;
419 } else {
420 $this->error = $discountstatic->error;
421 return -1;
422 }
423 }
424
432 public function getSumCreditNotesUsed($multicurrency = 0)
433 {
434 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
435
436 $discountstatic = new DiscountAbsolute($this->db);
437 $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
438 if (is_numeric($result)) {
439 if ($multicurrency) {
440 $this->totalcreditnotes_multicurrency = $result;
441 } else {
442 $this->totalcreditnotes = $result;
443 }
444
445 return $result;
446 } else {
447 $this->error = $discountstatic->error;
448 return $result;
449 }
450 }
451
458 public function getSumFromThisCreditNotesNotUsed($multicurrency = 0)
459 {
460 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
461
462 $discountstatic = new DiscountAbsolute($this->db);
463 $result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency);
464 if ($result >= 0) {
465 return $result;
466 } else {
467 $this->error = $discountstatic->error;
468 return -1;
469 }
470 }
471
478 {
479 $idarray = array();
480
481 $sql = "SELECT rowid";
482 $sql .= " FROM ".$this->db->prefix().$this->table_element;
483 $sql .= " WHERE fk_facture_source = ".((int) $this->id);
484 $sql .= " AND type = ".self::TYPE_CREDIT_NOTE;
485
486 $resql = $this->db->query($sql);
487 if ($resql) {
488 $num = $this->db->num_rows($resql);
489 $i = 0;
490 while ($i < $num) {
491 $row = $this->db->fetch_row($resql);
492 $idarray[] = $row[0];
493 $i++;
494 }
495 } else {
496 dol_print_error($this->db);
497 }
498
499 $this->creditnote_ids = $idarray;
500
501 return $idarray;
502 }
503
510 public function getIdReplacingInvoice($option = '')
511 {
512 $sql = "SELECT rowid";
513 $sql .= " FROM ".$this->db->prefix().$this->table_element;
514 $sql .= " WHERE fk_facture_source = ".((int) $this->id);
515 $sql .= " AND type < 2";
516 if ($option == 'validated') {
517 $sql .= ' AND fk_statut = 1';
518 }
519 // PROTECTION BAD DATA
520 // In case the database is corrupted and there is a valid replectement invoice
521 // and another no, priority is given to the valid one.
522 // Should not happen (unless concurrent access and 2 people have created a
523 // replacement invoice for the same invoice at the same time)
524 $sql .= " ORDER BY fk_statut DESC";
525
526 $resql = $this->db->query($sql);
527 if ($resql) {
528 $obj = $this->db->fetch_object($resql);
529 if ($obj) {
530 // If there is any
531 return $obj->rowid;
532 } else {
533 // If no invoice replaces it
534 return 0;
535 }
536 } else {
537 return -1;
538 }
539 }
540
548 {
549 $listofopendirectdebitorcredittransfer = array();
550
551 // TODO Add a cache to store array of open requests for each invoice ID
552
553 $sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande, pfd.date_traite as date_traite, pfd.amount";
554 $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pfd";
555 if ($type == 'bank-transfer') {
556 $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
557 } else {
558 $sql .= " WHERE fk_facture = ".((int) $this->id);
559 }
560 $sql .= " AND pfd.traite = 0";
561 $sql .= " AND pfd.type = 'ban'";
562 $sql .= " ORDER BY pfd.date_demande DESC";
563
564 $resql = $this->db->query($sql);
565 $num = 0;
566 if ($resql) {
567 $num = $this->db->num_rows($resql);
568 $i = 0;
569 while ($i < $num) {
570 $obj = $this->db->fetch_object($resql);
571 if ($obj) {
572 $listofopendirectdebitorcredittransfer[] = array(
573 'id' => (int) $obj->rowid,
574 'invoiceid' => (int) $this->id,
575 'date' => $this->db->jdate($obj->date_demande),
576 'amount' => (float) $obj->amount
577 );
578 }
579
580 $i++;
581 }
582 } else {
583 $this->error = $this->db->lasterror();
584 }
585
586 $this->nbofopendirectdebitorcredittransfer = $num;
587
588 return $listofopendirectdebitorcredittransfer;
589 }
590
598 {
599 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
600 if ($this->status >= 0 || $this->element == 'societe') {
601 $fieldname = 'retained_warranty_fk_cond_reglement';
602
603 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
604 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".((int) $id);
605 $sql .= ' WHERE rowid='.((int) $this->id);
606
607 if ($this->db->query($sql)) {
608 $this->retained_warranty_fk_cond_reglement = $id;
609 return 1;
610 } else {
611 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
612 $this->error = $this->db->error();
613 return -1;
614 }
615 } else {
616 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
617 $this->error = 'Status of the object is incompatible '.$this->status;
618 return -2;
619 }
620 }
621
630 protected function checkPointOfTaxNotChanged()
631 {
632 global $langs;
633
634 if (empty($this->id)) {
635 return 1;
636 }
637
638 $sql = "SELECT fk_statut, date_pointoftax FROM ".$this->db->prefix().$this->table_element;
639 $sql .= " WHERE rowid = ".((int) $this->id);
640 $resql = $this->db->query($sql);
641 if (!$resql) {
642 $this->error = $this->db->lasterror();
643 return -1;
644 }
645 $obj = $this->db->fetch_object($resql);
646 $this->db->free($resql);
647 if (!$obj || (int) $obj->fk_statut == self::STATUS_DRAFT) {
648 return 1;
649 }
650
651 // Compare the days, as stored by update()
652 $olddate = substr((string) $obj->date_pointoftax, 0, 10);
653 $newdate = (dol_strlen((string) $this->date_pointoftax) != 0 ? substr($this->db->idate((int) $this->date_pointoftax), 0, 10) : '');
654 if ($olddate !== $newdate) {
655 $langs->load("bills");
656 $this->error = $langs->trans("ErrorPointOfTaxOfValidatedInvoiceCantBeChanged", $this->ref);
657 return -1;
658 }
659
660 return 1;
661 }
662
673 public function getListOfPayments($filtertype = '', $multicurrency = 0, $mode = 0)
674 {
675 $retarray = array();
676 $this->error = ''; // By default no error, list can be empty.
677
678 $table = 'paiement_facture';
679 $table2 = 'paiement';
680
681 $field = 'fk_facture';
682 $field2 = 'fk_paiement';
683 $field3 = 'p.ref_ext';
684 $field4 = 'p.fk_bank'; // Bank line id
685
686 $sharedentity = 'facture';
687
688 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
689 $table = 'paiementfourn_facturefourn';
690 $table2 = 'paiementfourn';
691
692 $field = 'fk_facturefourn';
693 $field2 = 'fk_paiementfourn';
694 $field3 = '';
695
696 $sharedentity = 'facture_fourn';
697 }
698
699 // List of payments
700 if (empty($mode) || $mode == 1) {
701 $sql = "SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code".($field3 ? ", ".$this->db->sanitize($field3) : "") . (", ".$this->db->sanitize($field4));
702 $sql .= " FROM ".$this->db->prefix().$table." as pf, ".$this->db->prefix().$table2." as p, ".$this->db->prefix()."c_paiement as t";
703 $sql .= " WHERE pf.".$this->db->sanitize($field)." = ".((int) $this->id);
704 $sql .= " AND pf.".$this->db->sanitize($field2)." = p.rowid";
705 $sql .= ' AND p.fk_paiement = t.id';
706 $sql .= ' AND p.entity IN ('.getEntity($sharedentity).')';
707 if ($filtertype) {
708 $sql .= " AND t.code='PRE'";
709 }
710
711 dol_syslog(get_class($this)."::getListOfPayments filtertype=".$filtertype." multicurrency=".$multicurrency." mode=".$mode, LOG_DEBUG);
712
713 $resql = $this->db->query($sql);
714 if ($resql) {
715 $num = $this->db->num_rows($resql);
716 $i = 0;
717 while ($i < $num) {
718 $obj = $this->db->fetch_object($resql);
719 if ($multicurrency) {
720 $tmp = array('amount' => $obj->multicurrency_amount, 'type' => $obj->code, 'typeline' => 'payment', 'date' => $obj->datep, 'num' => $obj->num, 'ref' => $obj->ref);
721 } else {
722 $tmp = array('amount' => $obj->amount, 'type' => $obj->code, 'typeline' => 'payment', 'date' => $obj->datep, 'num' => $obj->num, 'ref' => $obj->ref);
723 }
724 if (!empty($field3)) {
725 $tmp['ref_ext'] = $obj->ref_ext;
726 }
727 if (!empty($field4)) {
728 $tmp['fk_bank_line'] = $obj->fk_bank;
729 }
730 $retarray[] = $tmp;
731 $i++;
732 }
733 $this->db->free($resql);
734 } else {
735 $this->error = $this->db->lasterror();
736 dol_print_error($this->db);
737 return array();
738 }
739 }
740
741 // Look for credit notes and discounts and deposits
742 if (empty($mode) || $mode == 2) {
743 $sql = '';
744 if ($this->element == 'facture' || $this->element == 'invoice') {
745 $sql = "SELECT rc.amount_ttc as amount, rc.multicurrency_amount_ttc as multicurrency_amount, rc.datec as date, f.ref as ref, rc.description as type";
746 $sql .= ' FROM '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture as f';
747 $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.((int) $this->id);
748 $sql .= ' AND (f.type = 2 OR f.type = 0 OR f.type = 3)'; // Find discount coming from credit note or excess received or deposits (payments from deposits are always null except if FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is set)
749 } elseif ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
750 $sql = "SELECT rc.amount_ttc as amount, rc.multicurrency_amount_ttc as multicurrency_amount, rc.datec as date, f.ref as ref, rc.description as type";
751 $sql .= ' FROM '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture_fourn as f';
752 $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.((int) $this->id);
753 $sql .= ' AND (f.type = 2 OR f.type = 0 OR f.type = 3)'; // Find discount coming from credit note or excess received or deposits (payments from deposits are always null except if FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS is set)
754 }
755
756 if ($sql) {
757 $resql = $this->db->query($sql);
758 if ($resql) {
759 $num = $this->db->num_rows($resql);
760 $i = 0;
761 while ($i < $num) {
762 $obj = $this->db->fetch_object($resql);
763 if ($multicurrency) {
764 $retarray[] = array('amount' => $obj->multicurrency_amount, 'type' => $obj->type, 'typeline' => 'discount', 'date' => $obj->date, 'num' => '0', 'ref' => $obj->ref);
765 } else {
766 $retarray[] = array('amount' => $obj->amount, 'type' => $obj->type, 'typeline' => 'discount', 'date' => $obj->date, 'num' => '', 'ref' => $obj->ref);
767 }
768 $i++;
769 }
770 } else {
771 $this->error = $this->db->lasterror();
772 dol_print_error($this->db);
773 return array();
774 }
775 $this->db->free($resql);
776 } else {
777 $this->error = $this->db->lasterror();
778 dol_print_error($this->db);
779 return array();
780 }
781 }
782
783 return $retarray;
784 }
785
800 public function isEditable()
801 {
802 // phpcs:enable
803 global $hookmanager, $action;
804
805 // We check if invoice is a temporary number (PROVxxxx)
806 $tmppart = substr($this->ref, 1, 4);
807
808 if ($this->status == self::STATUS_DRAFT && $tmppart === 'PROV') { // If draft invoice and ref not yet defined
809 return 1;
810 }
811
812 /*
813 if (getDolGlobalInt('INVOICE_CAN_NEVER_BE_REMOVED')) {
814 return 0;
815 }
816 */
817
818 // If not a draft invoice and not temporary invoice
819 if ($tmppart !== 'PROV') {
820 if ($this instanceof Facture) {
821 /* @var Facture $this */
822 // If sent by email, we refuse
823 if ((int) $this->email_sent_counter > 0) {
824 return -5;
825 }
826
827 // If printed, we refuse
828 if ((int) $this->pos_print_counter > 0) {
829 return -6;
830 }
831
832 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
833 if (isALNERunningVersion() && !empty($this->module_source)) {
834 $this->error = 'Action to modify an invoice from an external module like the Point Of Sale is not allowed';
835 return -7;
836 // Note, edit status to draft is also blocked by the trigger of blockedlog module for action BILL_UNVALIDATE that do a test on isEditable().
837 }
838 }
839
840 // If in accountancy, we refuse
841 $ventilExportCompta = $this->getVentilExportCompta();
842 if ($ventilExportCompta != 0) {
843 return -1;
844 }
845
846 // Get last number of validated invoice
847 if ($this->element != 'invoice_supplier') {
848 /*
849 if (empty($this->thirdparty)) {
850 $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of the numbering rule uses tags that depend on thirdparty (like {t} tag).
851 }
852 $maxref = $this->getNextNumRef($this->thirdparty, 'last');
853 // $maxref can be '' (means not found) if there is no invoice yet, but also if there is no invoice for the new period when there is a reset at each period
854
855 // If invoice to delete is not the last one, we refuse
856 if ($maxref != '' && $maxref != $this->ref) {
857 return -2;
858 }
859 */
860
861 // TODO If there is payment in bookkeeping, check the payment is not dispatched in accounting and return -2.
862 // ...
863
864 // If invoice is situation type, we refuse if it is not the last in situation cycle
865 if (!getDolGlobalString('INVOICE_SITUATION_CAN_BE_REMOVED_EVEN_IF_NOT_LAST') && $this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) {
866 $last = $this->is_last_in_cycle();
867 if (!$last) {
868 return -3;
869 }
870 }
871 }
872
873 // Test if there is at least one payment. If yes, we refuse.
874 if ($this->getSommePaiement() > 0) {
875 return -4;
876 }
877
878 $parameters = array();
879 $reshook = $hookmanager->executeHooks('isEditable', $parameters, $this, $action);
880 if (!empty($hookmanager->resArray['result'])) {
881 $this->error = $hookmanager->resArray['error'];
882 if (!empty($hookmanager->resArray['errors'])) {
883 $this->errors = array_merge($this->errors, $hookmanager->resArray['errors']);
884 }
885 if (!in_array($this->error, $this->errors)) {
886 $this->errors[] = $this->error;
887 }
888 return $hookmanager->resArray['result'];
889 }
890 }
891
892 return 2;
893 }
894
900 public function isReplacable()
901 {
902 global $hookmanager, $action;
903
904 // We check if invoice is a temporary number (PROVxxxx)
905 $tmppart = substr($this->ref, 1, 4);
906
907 if ($this->status == self::STATUS_DRAFT) { // If draft invoice, no
908 return -1;
909 }
910
911 // If not a draft invoice and not temporary invoice
912 if ($tmppart !== 'PROV') {
913 // If in accountancy, we refuse
914 $ventilExportCompta = $this->getVentilExportCompta();
915 if ($ventilExportCompta != 0) {
916 return -1;
917 }
918
919 // If invoice is situation type, we refuse if it is not the last in situation cycle
920 if (!getDolGlobalString('INVOICE_SITUATION_CAN_BE_REMOVED_EVEN_IF_NOT_LAST') && $this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) {
921 $last = $this->is_last_in_cycle();
922 if (!$last) {
923 return -3;
924 }
925 }
926
927 // Test if there is at least one payment. If yes, we refuse to delete.
928 if ($this->getSommePaiement() > 0) {
929 return -4;
930 }
931
932 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
933 if (isALNERunningVersion()) {
934 $this->error = 'Action not allowed on a certified version (or candidate for certification)';
935 return -7;
936 }
937
938 $parameters = array();
939 $reshook = $hookmanager->executeHooks('isReplacable', $parameters, $this, $action);
940 if (!empty($hookmanager->resArray['result'])) {
941 $this->error = $hookmanager->resArray['error'];
942 if (!empty($hookmanager->resArray['errors'])) {
943 $this->errors = array_merge($this->errors, $hookmanager->resArray['errors']);
944 }
945 if (!in_array($this->error, $this->errors)) {
946 $this->errors[] = $this->error;
947 }
948 return $hookmanager->resArray['result'];
949 }
950
951 return 1;
952 }
953
954 return 0;
955 }
956
957 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
975 public function is_erasable()
976 {
977 // phpcs:enable
978 global $hookmanager, $action;
979
980 // We check if invoice is a temporary number (PROVxxxx)
981 $tmppart = substr($this->ref, 1, 4);
982
983 if ($this->status == self::STATUS_DRAFT && $tmppart === 'PROV') { // If draft invoice and ref not yet defined
984 return 1;
985 }
986
987 if (getDolGlobalInt('INVOICE_CAN_NEVER_BE_REMOVED')) {
988 return 0;
989 }
990
991 // If not a draft invoice and not temporary invoice
992 if ($tmppart !== 'PROV') {
993 if ($this instanceof Facture) {
994 /* @var Facture $this */
995 // If sent by email, we refuse
996 if ((int) $this->email_sent_counter > 0) {
997 return -5;
998 }
999
1000 // If printed, we refuse
1001 if ((int) $this->pos_print_counter > 0) {
1002 return -6;
1003 }
1004
1005 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
1006 if (isALNERunningVersion()) {
1007 $this->error = 'Action not allowed on the certified version (or candidate for certification)';
1008 return -7;
1009 }
1010 }
1011
1012 // If in accountancy, we refuse
1013 $ventilExportCompta = $this->getVentilExportCompta();
1014 if ($ventilExportCompta != 0) {
1015 return -1;
1016 }
1017
1018 // Get last number of validated invoice
1019 if ($this->element != 'invoice_supplier') {
1020 if (empty($this->thirdparty)) {
1021 $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of the numbering rule uses tags that depend on thirdparty (like {t} tag).
1022 }
1023 $maxref = $this->getNextNumRef($this->thirdparty, 'last');
1024 // $maxref can be '' (means not found) if there is no invoice yet, but also if there is no invoice for the new period when there is a reset at each period
1025
1026 // If invoice to delete is not the last one, we refuse
1027 if ($maxref != '' && $maxref != $this->ref) {
1028 return -2;
1029 }
1030
1031 // TODO If there is payment in bookkeeping, check the payment is not dispatched in accounting and return -2.
1032 // ...
1033
1034 // If invoice is situation type, we refuse if it is not the last in situation cycle
1035 if (!getDolGlobalString('INVOICE_SITUATION_CAN_BE_REMOVED_EVEN_IF_NOT_LAST') && $this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) {
1036 $last = $this->is_last_in_cycle();
1037 if (!$last) {
1038 return -3;
1039 }
1040 }
1041 }
1042
1043 // Test if there is at least one payment. If yes, we refuse.
1044 if ($this->getSommePaiement() > 0) {
1045 return -4;
1046 }
1047
1048 $parameters = array();
1049 $reshook = $hookmanager->executeHooks('isErasable', $parameters, $this, $action);
1050 if (!empty($hookmanager->resArray['result'])) {
1051 $this->error = $hookmanager->resArray['error'];
1052 if (!empty($hookmanager->resArray['errors'])) {
1053 $this->errors = array_merge($this->errors, $hookmanager->resArray['errors']);
1054 }
1055 if (!in_array($this->error, $this->errors)) {
1056 $this->errors[] = $this->error;
1057 }
1058 return $hookmanager->resArray['result'];
1059 }
1060 }
1061
1062 return 2;
1063 }
1064
1072 public function getVentilExportCompta($mode = 0)
1073 {
1074 if (!isModEnabled('accounting')) {
1075 return 0;
1076 }
1077
1078 $alreadydispatched = 0;
1079
1080 $type = 'customer_invoice';
1081 if ($this->element == 'invoice_supplier') {
1082 $type = 'supplier_invoice';
1083 }
1084
1085 $sql = " SELECT ".($mode ? 'DISTINCT piece_num' : 'COUNT(ab.rowid)')." as nb";
1086 $sql .= " FROM ".$this->db->prefix()."accounting_bookkeeping as ab";
1087 $sql .= " WHERE ab.doc_type = '".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
1088
1089 $resql = $this->db->query($sql);
1090 if ($resql) {
1091 $obj = $this->db->fetch_object($resql);
1092 if ($obj) {
1093 $alreadydispatched = $obj->nb;
1094 }
1095 } else {
1096 $this->error = $this->db->lasterror();
1097 return -1;
1098 }
1099
1100 if ($alreadydispatched) {
1101 return $alreadydispatched;
1102 }
1103 return 0;
1104 }
1105
1113 public function getNextNumRef($soc, $mode = 'next')
1114 {
1115 // TODO Must be implemented into main class
1116 return '';
1117 }
1118
1125 public function getLibType($withbadge = 0)
1126 {
1127 global $langs;
1128
1129 $labellong = "Unknown";
1130 $labelshort = "Unknown";
1131 if ($this->type == CommonInvoice::TYPE_STANDARD) {
1132 $labellong = "InvoiceStandard";
1133 $labelshort = "InvoiceStandardShort";
1134 } elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) {
1135 $labellong = "InvoiceReplacement";
1136 $labelshort = "InvoiceReplacementShort";
1137 } elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) {
1138 $labellong = "InvoiceAvoir";
1139 $labelshort = "CreditNote";
1140 } elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) {
1141 $labellong = "InvoiceDeposit";
1142 $labelshort = "Deposit";
1143 } elseif ($this->type == CommonInvoice::TYPE_PROFORMA) { // @phan-suppress-current-line PhanDeprecatedClassConstant
1144 $labellong = "InvoiceProForma"; // Not used.
1145 $labelshort = "ProForma";
1146 } elseif ($this->type == CommonInvoice::TYPE_SITUATION) {
1147 $labellong = "InvoiceSituation";
1148 $labelshort = "Situation";
1149 }
1150
1151 $out = '';
1152 if ($withbadge) {
1153 $out .= '<span class="badgeneutral" title="'.dol_escape_htmltag($langs->trans($labellong)).'">';
1154 }
1155 $out .= $langs->trans($withbadge == 2 ? $labelshort : $labellong);
1156 if ($withbadge) {
1157 $out .= '</span>';
1158 }
1159 return $out;
1160 }
1161
1168 public function getSubtypeLabel($table = '')
1169 {
1170 $subtypeLabel = '';
1171 if ($table === 'facture' || $table === 'facture_fourn') {
1172 $sql = "SELECT s.label FROM " . $this->db->prefix() . $table . " AS f";
1173 $sql .= " INNER JOIN " . $this->db->prefix() . "c_invoice_subtype AS s ON f.subtype = s.rowid";
1174 $sql .= " WHERE f.ref = '".$this->db->escape($this->ref)."'";
1175 } elseif ($table === 'facture_rec' || $table === 'facture_fourn_rec') {
1176 $sql = "SELECT s.label FROM " . $this->db->prefix() . $table . " AS f";
1177 $sql .= " INNER JOIN " . $this->db->prefix() . "c_invoice_subtype AS s ON f.subtype = s.rowid";
1178 $sql .= " WHERE f.titre = '".$this->db->escape($this->title)."'";
1179 } else {
1180 return -1;
1181 }
1182
1183 $resql = $this->db->query($sql);
1184 if ($resql) {
1185 while ($obj = $this->db->fetch_object($resql)) {
1186 $subtypeLabel = $obj->label;
1187 }
1188 } else {
1189 dol_print_error($this->db);
1190 return -1;
1191 }
1192
1193 return $subtypeLabel;
1194 }
1195
1202 public function getArrayOfInvoiceSubtypes($mode = 0)
1203 {
1204 global $mysoc;
1205
1206 $effs = array();
1207
1208 $sql = "SELECT rowid, code, label as label";
1209 $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype';
1210 $sql .= " WHERE active = 1 AND fk_country = ".((int) $mysoc->country_id)." AND entity IN(".getEntity('c_invoice_subtype').")";
1211 $sql .= " ORDER by rowid, code";
1212
1213 dol_syslog(get_class($this) . '::getArrayOfInvoiceSubtypes', LOG_DEBUG);
1214 $resql = $this->db->query($sql);
1215 if ($resql) {
1216 $num = $this->db->num_rows($resql);
1217 $i = 0;
1218
1219 while ($i < $num) {
1220 $objp = $this->db->fetch_object($resql);
1221 if (!$mode) {
1222 $key = $objp->rowid;
1223 $effs[$key] = $objp->label;
1224 } else {
1225 $key = $objp->code;
1226 $effs[$key] = $objp->rowid;
1227 }
1228
1229 $i++;
1230 }
1231 $this->db->free($resql);
1232 }
1233
1234 return $effs;
1235 }
1236
1244 public function getLibStatut($mode = 0, $alreadypaid = -1)
1245 {
1246 $moreparams = array(
1247 'nbofopendirectdebitorcredittransfer' => $this->nbofopendirectdebitorcredittransfer,
1248 'close_code' => $this->close_code,
1249 'close_note' => $this->close_note,
1250 'dispute_status' => $this->dispute_status
1251 );
1252
1253 return $this->LibStatut($this->paye, $this->status, $mode, $alreadypaid, $this->type, $moreparams);
1254 }
1255
1256 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1268 public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = -1, $moreparams = array())
1269 {
1270 // phpcs:enable
1271 global $langs, $hookmanager;
1272 $langs->load('bills');
1273
1274 if ($type == -1) {
1275 $type = $this->type;
1276 }
1277
1278 // For backward compatibility
1279 if (is_int($moreparams)) {
1280 $moreparams = array('nbofopendirectdebitorcredittransfer' => (int) $moreparams);
1281 }
1282
1283 $nbofopendirectdebitorcredittransfer = 0;
1284 foreach ($moreparams as $moreparamkey => $moreparamvalue) {
1285 if ($moreparamkey == 'nbofopendirectdebitorcredittransfer') {
1286 $nbofopendirectdebitorcredittransfer = $moreparamvalue;
1287 }
1288 }
1289
1290 $statusType = 'status0';
1291 $prefix = 'Short';
1292 if (!$paye) {
1293 if ($status == 0) {
1294 $labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft');
1295 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft');
1296 } elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
1297 if ($status == 3) {
1298 $labelStatus = $langs->transnoentitiesnoconv('BillStatusCanceled');
1299 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusCanceled');
1300 } else {
1301 $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid');
1302 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid');
1303 }
1304 $statusType = 'status5';
1305 } elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
1306 $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially');
1307 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially');
1308 $statusType = 'status9';
1309 } elseif ($alreadypaid == 0 && $nbofopendirectdebitorcredittransfer == 0) {
1310 $labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid');
1311 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid');
1312 $statusType = 'status1';
1313 } else {
1314 $labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted');
1315 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted');
1316 $statusType = 'status3';
1317 }
1318 } else {
1319 $statusType = 'status6';
1320 if ($type == self::TYPE_CREDIT_NOTE) {
1321 $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note
1322 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
1323 } elseif ($type == self::TYPE_DEPOSIT) {
1324 $labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice
1325 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice
1326 } else {
1327 $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid');
1328 $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid');
1329 }
1330 }
1331
1332 $paramsBadge = array('badgeParams' => array('attr' => array(
1333 'data-status-element' => $this->element,
1334 'data-already-paid' => $alreadypaid > 0 ? 1 : 0,
1335 'data-status' => (int) $status
1336 )));
1337
1338 $parameters = array(
1339 'status' => $status,
1340 'mode' => $mode,
1341 'paye' => $paye,
1342 'alreadypaid' => $alreadypaid,
1343 'type' => $type,
1344 'paramsBadge' => & $paramsBadge
1345 );
1346
1347 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
1348
1349 if ($reshook > 0) {
1350 return $hookmanager->resPrint;
1351 }
1352
1353 if (!empty($moreparams['close_code'])) {
1354 $titlestringtoshow = '';
1355
1356 if ($moreparams['close_code'] == self::CLOSECODE_DISCOUNTVAT) {
1357 $titlestringtoshow = $langs->trans("HelpEscompte");
1358 } elseif ($moreparams['close_code'] == self::CLOSECODE_BADDEBT) {
1359 $titlestringtoshow = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomer");
1360 } elseif ($moreparams['close_code'] == self::CLOSECODE_BANKCHARGE) {
1361 $titlestringtoshow = $langs->trans("ConfirmClassifyPaidPartiallyReasonBankCharge");
1362 } elseif ($moreparams['close_code'] == self::CLOSECODE_WITHHOLDINGTAX) {
1363 $titlestringtoshow = $langs->trans("ConfirmClassifyPaidPartiallyReasonWithholdingTax");
1364 } elseif ($moreparams['close_code'] == self::CLOSECODE_OTHER) {
1365 $titlestringtoshow = $langs->trans("Other");
1366 }
1367
1368 //$paramsbutton = array('badgeParams' => array('attr' => array('title' => 'rrrr')));
1369 $paramsBadge['badgeParams' ]['attr']['title'] = $titlestringtoshow;
1370 }
1371
1372 if (isset($moreparams['dispute_status']) && $moreparams['dispute_status']) {
1373 $labelStatus .= ' - ';
1374 if ($moreparams['dispute_status'] == 8) {
1375 $labelStatus .= $langs->trans("DisputeLost");
1376 } elseif ($moreparams['dispute_status'] == 9) {
1377 $labelStatus .= $langs->trans("DisputeWon");
1378 } else {
1379 $labelStatus .= $langs->trans("DisputeOpen");
1380 $statusType = 'status8';
1381 }
1382 }
1383
1384 $statusbadge = dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $paramsBadge);
1385
1386 return $statusbadge;
1387 }
1388
1389 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1397 public function calculate_date_lim_reglement($cond_reglement = 0)
1398 {
1399 // phpcs:enable
1400 if (!$cond_reglement) {
1401 $cond_reglement = $this->cond_reglement_code;
1402 }
1403 if (!$cond_reglement) {
1404 $cond_reglement = $this->cond_reglement_id;
1405 }
1406 if (!$cond_reglement) {
1407 return $this->date;
1408 }
1409
1410 $cdr_nbjour = 0;
1411 $cdr_type = 0;
1412 $cdr_decalage = 0;
1413
1414 $sqltemp = "SELECT c.type_cdr, c.nbjour, c.decalage";
1415 $sqltemp .= " FROM ".$this->db->prefix()."c_payment_term as c";
1416 if (is_numeric($cond_reglement)) {
1417 $sqltemp .= " WHERE c.rowid=".((int) $cond_reglement);
1418 } else {
1419 $sqltemp .= " WHERE c.entity IN (".getEntity('c_payment_term').")";
1420 $sqltemp .= " AND c.code = '".$this->db->escape($cond_reglement)."'";
1421 }
1422
1423 dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG);
1424 $resqltemp = $this->db->query($sqltemp);
1425 if ($resqltemp) {
1426 if ($this->db->num_rows($resqltemp)) {
1427 $obj = $this->db->fetch_object($resqltemp);
1428 $cdr_nbjour = $obj->nbjour;
1429 $cdr_type = $obj->type_cdr;
1430 $cdr_decalage = $obj->decalage;
1431 }
1432 } else {
1433 $this->error = $this->db->error();
1434 return -1;
1435 }
1436 $this->db->free($resqltemp);
1437
1438 /* Define date limit */
1439
1440 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1441
1442 // Note: $this->date is midnight in the server timezone, so the delay must be added as calendar days and not as
1443 // a number of seconds. A day is not always 24 hours long: when the delay crosses a daylight saving time change,
1444 // adding 86400 seconds per day shifts the result by one hour and can move it to the previous day.
1445
1446 // 0 : adding the number of days
1447 if ($cdr_type == 0) {
1448 $datelim = dol_time_plus_duree($this->date, $cdr_nbjour, 'd', 0, 'tzserver');
1449
1450 $datelim = dol_time_plus_duree($datelim, $cdr_decalage, 'd', 0, 'tzserver');
1451 } elseif ($cdr_type == 1) {
1452 // 1 : application of the "end of the month" rule
1453 $datelim = dol_time_plus_duree($this->date, $cdr_nbjour, 'd', 0, 'tzserver');
1454
1455 $mois = date('m', $datelim);
1456 $annee = date('Y', $datelim);
1457 if ($mois == 12) {
1458 $mois = 1;
1459 $annee += 1;
1460 } else {
1461 $mois += 1;
1462 }
1463 // We move at the beginning of the next month, and we take a day off
1464 $datelim = dol_mktime(12, 0, 0, $mois, 1, $annee, 'gmt');
1465 $datelim -= (3600 * 24);
1466
1467 $datelim += ($cdr_decalage * 3600 * 24);
1468 } elseif ($cdr_type == 2 && !empty($cdr_decalage)) {
1469 // 2 : application of the rule, the N of the current or next month
1470 $datelim = dol_time_plus_duree($this->date, $cdr_nbjour, 'd', 0, 'tzserver');
1471
1472 $date_piece = dol_mktime(0, 0, 0, (int) date('m', $datelim), (int) date('d', $datelim), (int) date('Y', $datelim), 'gmt'); // without hours, minutes and seconds
1473 $date_lim_current = dol_mktime(0, 0, 0, (int) date('m', $datelim), (int) $cdr_decalage, (int) date('Y', $datelim), 'gmt'); // without hours, minutes and seconds
1474 $date_lim_next = dol_time_plus_duree((int) $date_lim_current, 1, 'm'); // Add 1 month
1475
1476 $diff = $date_piece - $date_lim_current;
1477
1478 if ($diff <= 0) {
1479 $datelim = $date_lim_current;
1480 } else {
1481 $datelim = $date_lim_next;
1482 }
1483 } else {
1484 return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
1485 }
1486
1487 return $datelim;
1488 }
1489
1490 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1503 public function demande_prelevement(User $fuser, float $amount = 0, string $type = 'direct-debit', string $sourcetype = 'facture', int $checkduplicateamongall = 0, int $ribId = 0)
1504 {
1505 // phpcs:enable
1506 global $conf;
1507
1508 $error = 0;
1509
1510 dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
1511
1512 if ($this->status > self::STATUS_DRAFT && $this->paye == 0) {
1513 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
1514 $bac = new CompanyBankAccount($this->db);
1515 $bac->fetch($ribId, '', $this->socid);
1516
1517 // Option to allow multiple partial requests
1518 // If WITHDRAW_STRICT_CHECK_AMOUNT is enabled, we check the sum of amounts instead of just counting requests
1519 if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) {
1520 // Calculate sum of amounts already requested instead of just counting requests
1521 // This allows multiple partial requests as long as the total doesn't exceed the remain to pay
1522 $total_already_requested = 0;
1523 // Step 1: Get pending requests with no transfer receipt yet (traite = 0)
1524 $sql = "SELECT COALESCE(SUM(amount), 0) as total_requested";
1525 $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
1526 if ($type == 'bank-transfer') {
1527 $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
1528 } else {
1529 $sql .= " WHERE fk_facture = ".((int) $this->id);
1530 }
1531 $sql .= " AND type = 'ban'"; // To exclude record done for some online payments
1532 $sql .= " AND traite = 0"; // Not yet in a transfer receipt
1533 dol_syslog(get_class($this)."::demande_prelevement - get pending requests not yet in receipt", LOG_DEBUG);
1534 $resql = $this->db->query($sql);
1535 if ($resql) {
1536 $obj = $this->db->fetch_object($resql);
1537 $total_already_requested += $obj ? (float) $obj->total_requested : 0;
1538 } else {
1539 $this->error = $this->db->error();
1540 dol_syslog(get_class($this).'::demandeprelevement Error -2a');
1541 return -2;
1542 }
1543 // Step 2: Get pending requests in transfer receipt but not yet credited
1544 $sql = "SELECT COALESCE(SUM(pl.amount), 0) as total_requested";
1545 $sql .= " FROM ".$this->db->prefix()."prelevement_lignes as pl";
1546 $sql .= " INNER JOIN ".$this->db->prefix()."prelevement as p ON p.fk_prelevement_lignes = pl.rowid";
1547 if ($type == 'bank-transfer') {
1548 $sql .= " WHERE p.fk_facture_fourn = ".((int) $this->id);
1549 } else {
1550 $sql .= " WHERE p.fk_facture = ".((int) $this->id);
1551 }
1552 $sql .= " AND (pl.statut IS NULL OR pl.statut = 0)"; // Not yet processed (statut 2 = credited)
1553 dol_syslog(get_class($this)."::demande_prelevement - get requests in non-credited receipts", LOG_DEBUG);
1554 $resql = $this->db->query($sql);
1555 if ($resql) {
1556 $obj = $this->db->fetch_object($resql);
1557 $total_already_requested += $obj ? (float) $obj->total_requested : 0;
1558 // Calculate remain to pay
1559 $totalpaid = $this->getSommePaiement();
1560 $totalcreditnotes = $this->getSumCreditNotesUsed();
1561 $totaldeposits = $this->getSumDepositsUsed();
1562 $resteapayer = (float) price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1563 // Calculate remaining amount available for new requests
1564 $remaining_for_request = (float) price2num($resteapayer - $total_already_requested, 'MT');
1565 // If no amount specified, use the remaining available
1566 if (empty($amount)) {
1567 $amount = $remaining_for_request;
1568 }
1569 // Check if there's still room for new requests
1570 $can_create_request = ($remaining_for_request > 0 && $amount <= $remaining_for_request);
1571 } else {
1572 $this->error = $this->db->error();
1573 dol_syslog(get_class($this).'::demandeprelevement Error -2b');
1574 return -2;
1575 }
1576 } else {
1577 // Original behavior: only check if a request already exists (count)
1578 $sql = "SELECT count(rowid) as nb";
1579 $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
1580 if ($type == 'bank-transfer') {
1581 $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
1582 } else {
1583 $sql .= " WHERE fk_facture = ".((int) $this->id);
1584 }
1585 $sql .= " AND type = 'ban'"; // To exclude record done for some online payments
1586 if (empty($checkduplicateamongall)) {
1587 $sql .= " AND traite = 0";
1588 }
1589
1590 dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
1591
1592 $resql = $this->db->query($sql);
1593 if ($resql) {
1594 $obj = $this->db->fetch_object($resql);
1595 $can_create_request = ($obj && $obj->nb == 0);
1596 // Calculate amount if not specified
1597 if (empty($amount)) {
1598 $totalpaid = $this->getSommePaiement();
1599 $totalcreditnotes = $this->getSumCreditNotesUsed();
1600 $totaldeposits = $this->getSumDepositsUsed();
1601 //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
1602 // We can also use bcadd to avoid pb with floating points
1603 // For example print 239.2 - 229.3 - 9.9; does not return 0.
1604 //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
1605 //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
1606 $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1607 }
1608 $remaining_for_request = $amount; // For error message compatibility
1609 } else {
1610 $this->error = $this->db->error();
1611 dol_syslog(get_class($this).'::demandeprelevement Error -2');
1612 return -2;
1613 }
1614 }
1615 // Common code for both modes
1616 if ($can_create_request) {
1617 $now = dol_now();
1618 if (is_numeric($amount) && $amount != 0) {
1619 $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande(';
1620 if ($type == 'bank-transfer') {
1621 $sql .= 'fk_facture_fourn, ';
1622 } else {
1623 $sql .= 'fk_facture, ';
1624 }
1625 $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, type, entity';
1626 if (empty($bac->id)) {
1627 $sql .= ')';
1628 } else {
1629 $sql .= ', fk_societe_rib)';
1630 }
1631 $sql .= " VALUES (".((int) $this->id);
1632 $sql .= ", ".((float) price2num($amount));
1633 $sql .= ", '".$this->db->idate($now)."'";
1634 $sql .= ", ".((int) $fuser->id);
1635 $sql .= ", '".$this->db->escape($bac->code_banque)."'";
1636 $sql .= ", '".$this->db->escape($bac->code_guichet)."'";
1637 $sql .= ", '".$this->db->escape($bac->number)."'";
1638 $sql .= ", '".$this->db->escape($bac->cle_rib)."'";
1639 $sql .= ", '".$this->db->escape($sourcetype)."'";
1640 $sql .= ", 'ban'";
1641 $sql .= ", ".((int) $conf->entity);
1642 if (!empty($bac->id)) {
1643 $sql .= ", '".$this->db->escape((string) $bac->id)."'";
1644 }
1645 $sql .= ")";
1646 dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
1647 $resql = $this->db->query($sql);
1648 if (!$resql) {
1649 $this->error = $this->db->lasterror();
1650 dol_syslog(get_class($this).'::demandeprelevement Erreur');
1651 $error++;
1652 }
1653 } else {
1654 $this->error = 'WithdrawRequestErrorNilAmount';
1655 dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
1656 $error++;
1657 }
1658 if (!$error) {
1659 // Force payment mode of invoice to withdraw
1660 $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
1661 if ($payment_mode_id > 0) {
1662 $result = $this->setPaymentMethods($payment_mode_id);
1663 }
1664 }
1665 if ($error) {
1666 return -1;
1667 }
1668 return 1;
1669 } else {
1670 // Updated error message for when amount exceeds remaining or request already exists
1671 if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) {
1672 if ($remaining_for_request <= 0) {
1673 $this->error = "AmountRequestedAlreadyReachesTotal";
1674 } else {
1675 $this->error = "AmountExceedsRemainingToRequest";
1676 }
1677 } else {
1678 $this->error = "A request already exists";
1679 }
1680 return 0;
1681 }
1682 } else {
1683 $this->error = "Status of invoice does not allow this";
1684 dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->status, $this->paye, $this->mode_reglement_id");
1685 return -3;
1686 }
1687 }
1688
1689
1701 public function makeStripeCardRequest($fuser, $id, $sourcetype = 'facture')
1702 {
1703 // TODO See in sellyoursaas
1704 return 0;
1705 }
1706
1719 public function makeStripeSepaRequest($fuser, $did, $type = 'direct-debit', $sourcetype = 'facture', $service = '', $forcestripe = '')
1720 {
1721 global $conf, $user, $langs;
1722
1723 if ($type != 'bank-transfer' && $type != 'credit-transfer' && !getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT')) {
1724 return 0;
1725 }
1726 if ($type != 'direct-debit' && !getDolGlobalString('STRIPE_SEPA_CREDIT_TRANSFER')) {
1727 return 0;
1728 }
1729 // Set a default value for service if not provided
1730 if (empty($service)) {
1731 $service = 'StripeTest';
1732 if (getDolGlobalString('STRIPE_LIVE')/* && !GETPOST('forcesandbox', 'alpha')*/) {
1733 $service = 'StripeLive';
1734 }
1735 }
1736
1737 $error = 0;
1738
1739 dol_syslog(get_class($this)."::makeStripeSepaRequest start did=".$did." type=".$type." service=".$service." sourcetype=".$sourcetype." forcestripe=".$forcestripe, LOG_DEBUG);
1740
1741 if ($this->status > self::STATUS_DRAFT && $this->paye == 0) {
1742 // Get the default payment mode for BAN payment of the third party
1743 require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
1744 $bac = new CompanyBankAccount($this->db); // Table societe_rib
1745 $result = $bac->fetch(0, '', $this->socid, 1, 'ban');
1746 if ($result <= 0 || empty($bac->id)) {
1747 $this->error = $langs->trans("ThirdpartyHasNoDefaultBankAccount");
1748 $this->errors[] = $this->error;
1749 dol_syslog(get_class($this)."::makeStripeSepaRequest ".$this->error);
1750 return -1;
1751 }
1752
1753 // Load the pending payment request to process (with rowid=$did)
1754 $sql = "SELECT rowid, date_demande, amount, fk_facture, fk_facture_fourn, fk_salary, fk_prelevement_bons";
1755 $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
1756 $sql .= " WHERE rowid = ".((int) $did);
1757 if ($type != 'bank-transfer' && $type != 'credit-transfer') {
1758 $sql .= " AND fk_facture = ".((int) $this->id); // Add a protection to not pay another invoice than current one
1759 }
1760 if ($type != 'direct-debit') {
1761 if ($sourcetype == 'salary') {
1762 $sql .= " AND fk_salary = ".((int) $this->id); // Add a protection to not pay another salary than current one
1763 } else {
1764 $sql .= " AND fk_facture_fourn = ".((int) $this->id); // Add a protection to not pay another invoice than current one
1765 }
1766 }
1767 $sql .= " AND traite = 0"; // To not process payment request that were already converted into a direct debit or credit transfer order (Note: fk_prelevement_bons is also empty when traite = 0)
1768
1769 dol_syslog(get_class($this)."::makeStripeSepaRequest load requests to process", LOG_DEBUG);
1770 $resql = $this->db->query($sql);
1771 if ($resql) {
1772 $obj = $this->db->fetch_object($resql);
1773 if (!$obj) {
1774 dol_print_error($this->db, 'CantFindRequestWithId');
1775 return -2;
1776 }
1777
1778 // amount to pay
1779 $amount = $obj->amount;
1780
1781 if (is_numeric($amount) && $amount != 0) {
1782 require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
1783 $companypaymentmode = new CompanyPaymentMode($this->db); // table societe_rib
1784 $companypaymentmode->fetch($bac->id);
1785 $sepaSequenceType = strtoupper((string) $companypaymentmode->frstrecur);
1786 if (!in_array($sepaSequenceType, array('FRST', 'RCUR', 'OOFF', 'FNAL'), true)) {
1787 $sepaSequenceType = 'FRST';
1788 }
1789
1790 $this->stripechargedone = 0;
1791 $this->stripechargeerror = 0;
1792
1793 $now = dol_now();
1794
1795 $currency = $conf->currency;
1796
1797 $errorforinvoice = 0; // We reset the $errorforinvoice at each invoice loop
1798
1799 $this->fetch_thirdparty();
1800
1801 dol_syslog("makeStripeSepaRequest Process payment request amount=".$amount." thirdparty_id=" . $this->thirdparty->id . ", thirdparty_name=" . $this->thirdparty->name . " ban id=" . $bac->id, LOG_DEBUG);
1802
1803 //$alreadypayed = $this->getSommePaiement();
1804 //$amount_credit_notes_included = $this->getSumCreditNotesUsed();
1805 //$amounttopay = $this->total_ttc - $alreadypayed - $amount_credit_notes_included;
1806 $amounttopay = $amount;
1807
1808 // Correct the amount according to unit of currency
1809 // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support
1810 $arrayzerounitcurrency = ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'];
1811 $amountstripe = $amounttopay;
1812 if (!in_array($currency, $arrayzerounitcurrency)) {
1813 $amountstripe *= 100;
1814 }
1815
1816 $fk_bank_account = getDolGlobalInt('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS'); // Bank account used for SEPA direct debit or credit transfer. Must be the Stripe account in Dolibarr.
1817 if (!($fk_bank_account > 0)) {
1818 $error++;
1819 $errorforinvoice++;
1820 dol_syslog("makeStripeSepaRequest Error no bank account defined for Stripe payments", LOG_ERR);
1821 $this->error = "Error bank account for Stripe payments not defined into Stripe module";
1822 $this->errors[] = $this->error;
1823 }
1824
1825 $this->db->begin();
1826
1827 // Create a prelevement_bon
1828 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
1829 $bon = new BonPrelevement($this->db);
1830 if (!$error) {
1831 if (empty($obj->fk_prelevement_bons)) {
1832 // This creates a record into llx_prelevement_bons and updates link with llx_prelevement_demande
1833 $nbinvoices = $bon->create('0', '0', 'real', $sepaSequenceType, 0, 0, $type, $did, $fk_bank_account);
1834 if ($nbinvoices <= 0) {
1835 $error++;
1836 $errorforinvoice++;
1837 dol_syslog("makeStripeSepaRequest Error on BonPrelevement creation", LOG_ERR);
1838 $this->error = "Error on BonPrelevement creation";
1839 $this->errors[] = $this->error;
1840 }
1841 /*
1842 if (!$error) {
1843 // Update the direct debit payment request of the processed request to save the id of the prelevement_bon
1844 $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_demande SET";
1845 $sql .= " fk_prelevement_bons = ".((int) $bon->id);
1846 $sql .= " WHERE rowid = ".((int) $did);
1847
1848 $result = $this->db->query($sql);
1849 if ($result < 0) {
1850 $error++;
1851 $this->error = "Error on updating fk_prelevement_bons to ".$bon->id;
1852 $this->errors[] = $this->error;
1853 }
1854 }
1855 */
1856 } else {
1857 $error++;
1858 $errorforinvoice++;
1859 dol_syslog("makeStripeSepaRequest Error Line already part of a bank payment order", LOG_ERR);
1860 $this->error = "The line is already included into a bank payment order. Delete the bank payment order first.";
1861 $this->errors[] = $this->error;
1862 }
1863 }
1864
1865 $paymentintent = null;
1866 if (!$error) {
1867 if ($amountstripe > 0) {
1868 try {
1869 global $savstripearrayofkeysbyenv;
1870 global $stripearrayofkeysbyenv;
1871 $servicestatus = 0;
1872 if ($service == 'StripeLive') {
1873 $servicestatus = 1;
1874 }
1875
1876 //var_dump($companypaymentmode);
1877 dol_syslog("makeStripeSepaRequest We will try to pay with companypaymentmodeid=" . $companypaymentmode->id . " stripe_card_ref=" . $companypaymentmode->stripe_card_ref . " mode=" . $companypaymentmode->status, LOG_DEBUG);
1878
1879 $thirdparty = new Societe($this->db);
1880 $resultthirdparty = $thirdparty->fetch($this->socid);
1881
1882 include_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php'; // This include the include of htdocs/stripe/config.php
1883 // So it inits or erases the $stripearrayofkeysbyenv
1884 $stripe = new Stripe($this->db);
1885
1886 if (empty($savstripearrayofkeysbyenv)) {
1887 $savstripearrayofkeysbyenv = $stripearrayofkeysbyenv;
1888 }
1889 dol_syslog("makeStripeSepaRequest Current Stripe environment is " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key']);
1890 dol_syslog("makeStripeSepaRequest Current Saved Stripe environment is ".$savstripearrayofkeysbyenv[$servicestatus]['publishable_key']);
1891
1892 $foundalternativestripeaccount = '';
1893 $stripearrayofkeys = array();
1894
1895 // Force stripe to another value (by default this value is empty)
1896 if (! empty($forcestripe)) {
1897 dol_syslog("makeStripeSepaRequest A dedicated stripe account was forced, so we switch to it.");
1898
1899 $tmparray = explode('@', $forcestripe);
1900 if (! empty($tmparray[1])) {
1901 $tmparray2 = explode(':', $tmparray[1]);
1902 if (! empty($tmparray2[1])) {
1903 $stripearrayofkeysbyenv[$servicestatus]["publishable_key"] = $tmparray2[0];
1904 $stripearrayofkeysbyenv[$servicestatus]["secret_key"] = $tmparray2[1];
1905
1906 $stripearrayofkeys = $stripearrayofkeysbyenv[$servicestatus];
1907 \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']);
1908
1909 $foundalternativestripeaccount = $tmparray[0]; // Store the customer id
1910
1911 dol_syslog("makeStripeSepaRequest We use now customer=".$foundalternativestripeaccount." publishable_key=".$stripearrayofkeys['publishable_key'], LOG_DEBUG);
1912 }
1913 }
1914
1915 if (! $foundalternativestripeaccount) {
1916 $stripearrayofkeysbyenv = $savstripearrayofkeysbyenv;
1917
1918 $stripearrayofkeys = $savstripearrayofkeysbyenv[$servicestatus];
1919 \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']);
1920 dol_syslog("makeStripeSepaRequest We found a bad value for Stripe Account for thirdparty id=".$thirdparty->id.", so we ignore it and keep using the global one, so ".$stripearrayofkeys['publishable_key'], LOG_WARNING);
1921 }
1922 } else {
1923 $stripearrayofkeysbyenv = $savstripearrayofkeysbyenv;
1924
1925 $stripearrayofkeys = $savstripearrayofkeysbyenv[$servicestatus];
1926 \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']);
1927 dol_syslog("makeStripeSepaRequest No dedicated Stripe Account requested, so we use global one, so ".$stripearrayofkeys['publishable_key'], LOG_DEBUG);
1928 }
1929
1930 $stripeacc = $stripe->getStripeAccount($service, $this->socid); // Get Stripe OAuth connect account if it exists (no network access here)
1931
1932 if ($foundalternativestripeaccount) {
1933 if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
1934 $customer = \Stripe\Customer::retrieve(array('id' => "$foundalternativestripeaccount", 'expand[]' => 'sources'));
1935 } else {
1936 $customer = \Stripe\Customer::retrieve(array('id' => "$foundalternativestripeaccount", 'expand[]' => 'sources'), array("stripe_account" => $stripeacc));
1937 }
1938 } else {
1939 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
1940 if (empty($customer) && ! empty($stripe->error)) {
1941 $this->error = $stripe->error;
1942 $this->errors[] = $this->error;
1943 }
1944 /*if (!empty($customer) && empty($customer->sources)) {
1945 $customer = null;
1946 $this->error = '\Stripe\Customer::retrieve did not returned the sources';
1947 $this->errors[] = $this->error;
1948 }*/
1949 }
1950
1951 // $nbhoursbetweentries = (empty($conf->global->SELLYOURSAAS_NBHOURSBETWEENTRIES) ? 49 : $conf->global->SELLYOURSAAS_NBHOURSBETWEENTRIES); // Must have more that 48 hours + 1 between each try (so 1 try every 3 daily batch)
1952 // $nbdaysbeforeendoftries = (empty($conf->global->SELLYOURSAAS_NBDAYSBEFOREENDOFTRIES) ? 35 : $conf->global->SELLYOURSAAS_NBDAYSBEFOREENDOFTRIES);
1953 $postactionmessages = [];
1954
1955 if ($resultthirdparty > 0 && !empty($customer)) {
1956 if (!$error) { // Payment was not canceled
1957 $stripecard = null;
1958 if ($companypaymentmode->type == 'ban') {
1959 // Check into societe_rib if a payment mode for Stripe and ban payment exists
1960 // To make a Stripe SEPA payment request, we must have the payment mode source already saved into societe_rib and retrieved with ->sepaStripe
1961 // The payment mode source is created when we create the bank account on Stripe with paymentmodes.php?action=create
1962 $stripecard = $stripe->sepaStripe($customer, $companypaymentmode, $stripeacc, $servicestatus, 0);
1963 } else {
1964 $error++;
1965 $this->error = 'The payment mode type is not "ban"';
1966 }
1967
1968 if ($stripecard) { // Can be src_... (for sepa) or pm_... (new card mode). Note that card_... (old card mode) should not happen here.
1969 $FULLTAG = 'DID='.$did.'-INV=' . $this->id . '-CUS=' . $thirdparty->id;
1970 $description = 'Stripe payment from makeStripeSepaRequest: ' . $FULLTAG . ' did='.$did.' ref=' . $this->ref;
1971
1972 $stripefailurecode = '';
1973 $stripefailuremessage = '';
1974 $stripefailuredeclinecode = '';
1975
1976 // Using new SCA method
1977 dol_syslog("* Create payment on SEPA " . $stripecard->id . ", amounttopay=" . $amounttopay . ", amountstripe=" . $amountstripe . ", FULLTAG=" . $FULLTAG, LOG_DEBUG);
1978
1979 // Create payment intent and charge payment (confirmnow = true)
1980 $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $this, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1, 1, $did);
1981
1982 $charge = new stdClass();
1983
1984 if ($paymentintent->status === 'succeeded' || $paymentintent->status === 'processing') {
1985 $charge->status = 'ok';
1986 $charge->id = $paymentintent->id;
1987 $charge->customer = $customer->id;
1988 } elseif ($paymentintent->status === 'requires_action') {
1989 //paymentintent->status may be => 'requires_action' (no error in such a case)
1990 dol_syslog(formatLogObject($paymentintent), LOG_DEBUG);
1991
1992 $charge->status = 'failed';
1993 $charge->customer = $customer->id;
1994 $charge->failure_code = $stripe->code;
1995 $charge->failure_message = $stripe->error;
1996 $charge->failure_declinecode = $stripe->declinecode;
1997 $stripefailurecode = $stripe->code;
1998 $stripefailuremessage = 'Action required. Contact the support at ';// . $conf->global->SELLYOURSAAS_MAIN_EMAIL;
1999 $stripefailuredeclinecode = $stripe->declinecode;
2000 } else {
2001 dol_syslog(formatLogObject($paymentintent), LOG_DEBUG);
2002
2003 $charge->status = 'failed';
2004 $charge->customer = $customer->id;
2005 $charge->failure_code = $stripe->code;
2006 $charge->failure_message = $stripe->error;
2007 $charge->failure_declinecode = $stripe->declinecode;
2008 $stripefailurecode = $stripe->code;
2009 $stripefailuremessage = $stripe->error;
2010 $stripefailuredeclinecode = $stripe->declinecode;
2011 }
2012
2013 //var_dump("stripefailurecode=".$stripefailurecode." stripefailuremessage=".$stripefailuremessage." stripefailuredeclinecode=".$stripefailuredeclinecode);
2014 //exit;
2015
2016
2017 // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
2018 if (empty($charge) || $charge->status == 'failed') {
2019 dol_syslog('Failed to charge payment mode ' . $stripecard->id . ' stripefailurecode=' . $stripefailurecode . ' stripefailuremessage=' . $stripefailuremessage . ' stripefailuredeclinecode=' . $stripefailuredeclinecode, LOG_WARNING);
2020
2021 // Save a stripe payment was in error
2022 $this->stripechargeerror++;
2023
2024 $error++;
2025 $errorforinvoice++;
2026 $errmsg = $langs->trans("FailedToChargeSEPA");
2027 if (!empty($charge)) {
2028 if ($stripefailuredeclinecode == 'authentication_required') {
2029 $errauthenticationmessage = $langs->trans("ErrSCAAuthentication");
2030 $errmsg = $errauthenticationmessage;
2031 } elseif (in_array($stripefailuredeclinecode, ['insufficient_funds', 'generic_decline'])) {
2032 $errmsg .= ': ' . $charge->failure_code;
2033 $errmsg .= ($charge->failure_message ? ' - ' : '') . ' ' . $charge->failure_message;
2034 if (empty($stripefailurecode)) {
2035 $stripefailurecode = $charge->failure_code;
2036 }
2037 if (empty($stripefailuremessage)) {
2038 $stripefailuremessage = $charge->failure_message;
2039 }
2040 } else {
2041 $errmsg .= ': failure_code=' . $charge->failure_code;
2042 $errmsg .= ($charge->failure_message ? ' - ' : '') . ' failure_message=' . $charge->failure_message;
2043 if (empty($stripefailurecode)) {
2044 $stripefailurecode = $charge->failure_code;
2045 }
2046 if (empty($stripefailuremessage)) {
2047 $stripefailuremessage = $charge->failure_message;
2048 }
2049 }
2050 } else {
2051 $errmsg .= ': ' . $stripefailurecode . ' - ' . $stripefailuremessage;
2052 $errmsg .= ($stripefailuredeclinecode ? ' - ' . $stripefailuredeclinecode : '');
2053 }
2054
2055 $description = 'Stripe payment ERROR from makeStripeSepaRequest: ' . $FULLTAG;
2056 $postactionmessages[] = $errmsg . ' (' . $stripearrayofkeys['publishable_key'] . ')';
2057
2058 $this->error = $errmsg;
2059 $this->errors[] = $this->error;
2060 } else {
2061 dol_syslog('Successfuly request '.$type.' '.$stripecard->id);
2062
2063 $postactionmessages[] = 'Success to request '.$type.' (' . $charge->id . ' with ' . $stripearrayofkeys['publishable_key'] . ')';
2064
2065 // Save a stripe payment was done in real life so later we will be able to force a commit on recorded payments
2066 // even if in batch mode (method doTakePaymentStripe), we will always make all action in one transaction with a forced commit.
2067 $this->stripechargedone++;
2068
2069 // Default description used for label of event. Will be overwrite by another value later.
2070 $description = 'Stripe payment request OK (' . $charge->id . ') from makeStripeSepaRequest: ' . $FULLTAG;
2071 }
2072
2073 $object = $this;
2074
2075 // Track an event
2076 if (empty($charge) || $charge->status == 'failed') {
2077 $actioncode = 'PAYMENT_STRIPE_KO';
2078 $extraparams = $stripefailurecode;
2079 $extraparams .= (($extraparams && $stripefailuremessage) ? ' - ' : '') . $stripefailuremessage;
2080 $extraparams .= (($extraparams && $stripefailuredeclinecode) ? ' - ' : '') . $stripefailuredeclinecode;
2081 } else {
2082 $actioncode = 'PAYMENT_STRIPE_OK';
2083 $extraparams = array();
2084 }
2085 } else {
2086 $error++;
2087 $errorforinvoice++;
2088 dol_syslog("No ban payment method found for this stripe customer " . $customer->id, LOG_WARNING);
2089
2090 $this->error = 'Failed to get direct debit payment method for stripe customer = ' . $customer->id;
2091 $this->errors[] = $this->error;
2092
2093 $description = 'Failed to find or use the payment mode - no ban defined for the thirdparty account';
2094 $stripefailurecode = 'BADPAYMENTMODE';
2095 $stripefailuremessage = 'Failed to find or use the payment mode - no ban defined for the thirdparty account';
2096 $postactionmessages[] = $description . ' (' . $stripearrayofkeys['publishable_key'] . ')';
2097
2098 $object = $this;
2099
2100 $actioncode = 'PAYMENT_STRIPE_KO';
2101 $extraparams = array();
2102 }
2103 } else {
2104 // If error because payment was canceled for a logical reason, we do nothing (no event added)
2105 $description = '';
2106 $stripefailurecode = '';
2107 $stripefailuremessage = '';
2108
2109 $object = $this;
2110
2111 $actioncode = '';
2112 $extraparams = array();
2113 }
2114 } else { // Else of the if ($resultthirdparty > 0 && ! empty($customer)) {
2115 if ($resultthirdparty <= 0) {
2116 dol_syslog('SellYourSaasUtils Failed to load customer for thirdparty_id = ' . $thirdparty->id, LOG_WARNING);
2117 $this->error = 'Failed to load Stripe account for thirdparty_id = ' . $thirdparty->id;
2118 $this->errors[] = $this->error;
2119 } else { // $customer stripe not found
2120 dol_syslog('SellYourSaasUtils Failed to get Stripe customer id for thirdparty_id = ' . $thirdparty->id . " in mode " . $servicestatus . " in Stripe env " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key'], LOG_WARNING);
2121 $this->error = 'Failed to get Stripe account id for thirdparty_id = ' . $thirdparty->id . " in mode " . $servicestatus . " in Stripe env " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key'];
2122 $this->errors[] = $this->error;
2123 }
2124 $error++;
2125 $errorforinvoice++;
2126
2127 $description = 'Failed to find or use your payment mode (no payment mode for this customer id)';
2128 $stripefailurecode = 'BADPAYMENTMODE';
2129 $stripefailuremessage = 'Failed to find or use your payment mode (no payment mode for this customer id)';
2130 $postactionmessages = [];
2131
2132 $object = $this;
2133
2134 $actioncode = 'PAYMENT_STRIPE_KO';
2135 $extraparams = array();
2136 }
2137
2138 if ($description) {
2139 dol_syslog("* Record event for credit transfer or direct debit request result - " . $description);
2140 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2141
2142 // Insert record of payment (success or error)
2143 $actioncomm = new ActionComm($this->db);
2144
2145 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
2146 $actioncomm->code = 'AC_' . $actioncode;
2147 $actioncomm->label = $description;
2148 $actioncomm->note_private = implode(",\n", $postactionmessages);
2149 $actioncomm->fk_project = $this->fk_project;
2150 $actioncomm->datep = $now;
2151 $actioncomm->datef = $now;
2152 $actioncomm->percentage = -1; // Not applicable
2153 $actioncomm->socid = $thirdparty->id;
2154 $actioncomm->contactid = 0;
2155 $actioncomm->authorid = $user->id; // User saving action
2156 $actioncomm->userownerid = $user->id; // Owner of action
2157 // Fields when action is a real email (content is already into note)
2158 /*$actioncomm->email_msgid = $object->email_msgid;
2159 $actioncomm->email_from = $object->email_from;
2160 $actioncomm->email_sender= $object->email_sender;
2161 $actioncomm->email_to = $object->email_to;
2162 $actioncomm->email_tocc = $object->email_tocc;
2163 $actioncomm->email_tobcc = $object->email_tobcc;
2164 $actioncomm->email_subject = $object->email_subject;
2165 $actioncomm->errors_to = $object->errors_to;*/
2166 $actioncomm->fk_element = $this->id;
2167 $actioncomm->elementid = $this->id;
2168 $actioncomm->elementtype = $this->element;
2169 $actioncomm->extraparams = $extraparams; // Can be null, empty string or array()
2170
2171 $actioncomm->create($user);
2172 }
2173
2174 $this->description = $description;
2175 $this->postactionmessages = $postactionmessages;
2176 } catch (Exception $e) {
2177 $error++;
2178 $errorforinvoice++;
2179 dol_syslog('Error ' . $e->getMessage(), LOG_ERR);
2180 $this->error = 'Error ' . $e->getMessage();
2181 $this->errors[] = $this->error;
2182 }
2183 } else { // If remain to pay is null
2184 $error++;
2185 $errorforinvoice++;
2186 dol_syslog("Remain to pay is null for the invoice " . $this->id . " " . $this->ref . ". Why is the invoice not classified 'Paid' ?", LOG_WARNING);
2187 $this->error = "Remain to pay is null for the invoice " . $this->id . " " . $this->ref . ". Why is the invoice not classified 'Paid' ?";
2188 $this->errors[] = $this->error;
2189 }
2190 }
2191
2192 // Set status of the order to "Transferred" with method 'api'
2193 if (!$error && !$errorforinvoice) {
2194 $result = $bon->set_infotrans($user, $now, 3);
2195 if ($result < 0) {
2196 $error++;
2197 $errorforinvoice++;
2198 dol_syslog("Error on BonPrelevement creation", LOG_ERR);
2199 $this->error = "Error on BonPrelevement creation";
2200 $this->errors[] = $this->error;
2201 }
2202 }
2203
2204 if (!$error && !$errorforinvoice && $paymentintent !== null) {
2205 // Update the direct debit payment request of the processed invoice to save the id of the prelevement_bon
2206 $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_demande SET";
2207 $sql .= " ext_payment_id = '".$this->db->escape($paymentintent->id)."',";
2208 $sql .= " ext_payment_site = '".$this->db->escape($service)."'";
2209 $sql .= " WHERE rowid = ".((int) $did);
2210
2211 dol_syslog(get_class($this)."::makeStripeSepaRequest update to save stripe paymentintent ids", LOG_DEBUG);
2212 $resql = $this->db->query($sql);
2213 if (!$resql) {
2214 $this->error = $this->db->lasterror();
2215 dol_syslog(get_class($this).'::makeStripeSepaRequest Erreur');
2216 $error++;
2217 }
2218 }
2219
2220 if (!$error && !$errorforinvoice) {
2221 $this->db->commit();
2222 } else {
2223 $this->db->rollback();
2224 }
2225 } else {
2226 $this->error = 'WithdrawRequestErrorNilAmount';
2227 dol_syslog(get_class($this).'::makeStripeSepaRequest WithdrawRequestErrorNilAmount');
2228 $error++;
2229 }
2230
2231 /*
2232 if (!$error) {
2233 // Force payment mode of the invoice to withdraw
2234 $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
2235 if ($payment_mode_id > 0) {
2236 $result = $this->setPaymentMethods($payment_mode_id);
2237 }
2238 }*/
2239
2240 if ($error) {
2241 return -1;
2242 }
2243 return 1;
2244 } else {
2245 $this->error = $this->db->error();
2246 dol_syslog(get_class($this).'::makeStripeSepaRequest Erreur -2');
2247 return -2;
2248 }
2249 } else {
2250 $this->error = "Status of invoice does not allow this";
2251 dol_syslog(get_class($this)."::makeStripeSepaRequest ".$this->error." ".$this->status." ,".$this->paye.", ".$this->mode_reglement_id, LOG_WARNING);
2252 return -3;
2253 }
2254 }
2255
2256 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2264 public function demande_prelevement_delete($fuser, $did)
2265 {
2266 // phpcs:enable
2267 $sql = 'DELETE FROM '.$this->db->prefix().'prelevement_demande';
2268 $sql .= ' WHERE rowid = '.((int) $did);
2269 $sql .= ' AND traite = 0';
2270 if ($this->db->query($sql)) {
2271 return 0;
2272 } else {
2273 $this->error = $this->db->lasterror();
2274 dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error);
2275 return -1;
2276 }
2277 }
2278
2284 public function buildEPCQrCodeString()
2285 {
2286 global $mysoc;
2287
2288 // Get the amount to pay
2289 $amount_to_pay = $this->getRemainToPay();
2290
2291 // Prevent negative values (e.g. overpayments)
2292 $amount_to_pay = max(0, $amount_to_pay);
2293
2294 // Ensure numeric formatting for EPC QR code
2295 $amount_to_pay = price2num($amount_to_pay, 'MT');
2296
2297 // Initialize an array to hold the lines of the QR code
2298 $lines = array();
2299
2300 // Add the standard elements to the QR code
2301 $lines = [
2302 'BCD', // Service Tag (optional)
2303 '002', // Version (optional)
2304 '1', // Character set (optional)
2305 'SCT', // Identification (optional)
2306 ];
2307
2308 // Add the bank account information
2309 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
2310
2311 $idofbankaccountouse = $this->fk_account;
2312 if (empty($idofbankaccountouse)) {
2313 $idofbankaccountouse = $this->fk_bank; // for backward compatibility
2314 }
2315 if (empty($idofbankaccountouse)) {
2316 $idofbankaccountouse = getDolGlobalInt('FACTURE_RIB_NUMBER');
2317 }
2318
2319 if ($idofbankaccountouse > 0) {
2320 $bankAccount = new Account($this->db);
2321 $bankAccount->fetch($idofbankaccountouse);
2322 $lines[] = $bankAccount->bic; //BIC (required)
2323 if (!empty($bankAccount->owner_name)) {
2324 $lines[] = $bankAccount->owner_name; //Owner of the bank account, if present (required)
2325 } else {
2326 $lines[] = $mysoc->name; //Name (required)
2327 }
2328 $lines[] = $bankAccount->iban; //IBAN (required)
2329 } else {
2330 $lines[] = ""; //BIC (required)
2331 $lines[] = $mysoc->name; //Name (required)
2332 $lines[] = ""; //IBAN (required)
2333 }
2334
2335 $structuredCommunication = '';
2336 $remittanceInformation = $this->ref;
2337 if (!empty($this->payment_reference)) {
2338 // Structured payment reference stored on the invoice, see core/lib/paymentref.lib.php.
2339 // Spaces are only a reading aid, the code must carry the compact form.
2340 $structuredCommunication = str_replace(' ', '', $this->payment_reference);
2341 $remittanceInformation = '';
2342 } elseif (getDolGlobalString('INVOICE_PAYMENT_ENABLE_STRUCTURED_COMMUNICATION')) {
2343 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_be.lib.php';
2344 $structuredCommunication = dolBECalculateStructuredCommunication((string) $this->ref, $this->type);
2345 $remittanceInformation = '';
2346 }
2347
2348 // Add the amount and reference
2349 $lines[] = 'EUR' . $amount_to_pay; // Amount (optional)
2350 $lines[] = ''; // Purpose (optional)
2351 $lines[] = $structuredCommunication; // Payment reference (optional)
2352 $lines[] = $remittanceInformation; // Remittance Information (optional)
2353
2354 // Join the lines with newline characters and return the result
2355 return implode("\n", $lines);
2356 }
2362 public function buildZATCAQRString()
2363 {
2364 global $conf, $mysoc;
2365
2366 $tmplang = new Translate('', $conf);
2367 $tmplang->setDefaultLang('en_US');
2368 $tmplang->load("main");
2369
2370 $datestring = dol_print_date($this->date, 'dayhourrfc');
2371 //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2);
2372 //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2);
2373 $pricewithtaxstring = price2num($this->total_ttc, 2, 1);
2374 $pricetaxstring = price2num($this->total_tva, 2, 1);
2375
2376 /*
2377 $name = implode(unpack("H*", $this->thirdparty->name));
2378 $vatnumber = implode(unpack("H*", $this->thirdparty->tva_intra));
2379 $date = implode(unpack("H*", $datestring));
2380 $pricewithtax = implode(unpack("H*", price2num($pricewithtaxstring, 2)));
2381 $pricetax = implode(unpack("H*", $pricetaxstring));
2382
2383 //var_dump(strlen($this->thirdparty->name));
2384 //var_dump(str_pad(dechex('9'), 2, '0', STR_PAD_LEFT));
2385 //var_dump($this->thirdparty->name);
2386 //var_dump(implode(unpack("H*", $this->thirdparty->name)));
2387 //var_dump(price($this->total_tva, 0, $tmplang, 0, -1, 2));
2388
2389 $s = '01'.str_pad(dechex(strlen($this->thirdparty->name)), 2, '0', STR_PAD_LEFT).$name;
2390 $s .= '02'.str_pad(dechex(strlen($this->thirdparty->tva_intra)), 2, '0', STR_PAD_LEFT).$vatnumber;
2391 $s .= '03'.str_pad(dechex(strlen($datestring)), 2, '0', STR_PAD_LEFT).$date;
2392 $s .= '04'.str_pad(dechex(strlen($pricewithtaxstring)), 2, '0', STR_PAD_LEFT).$pricewithtax;
2393 $s .= '05'.str_pad(dechex(strlen($pricetaxstring)), 2, '0', STR_PAD_LEFT).$pricetax;
2394 $s .= ''; // Hash of xml invoice
2395 $s .= ''; // ecda signature
2396 $s .= ''; // ecda public key
2397 $s .= ''; // ecda signature of public key stamp
2398 */
2399 $mysocname = $mysoc->name ?? '';
2400 $mysoctva_intra = $mysoc->tva_intra ?? '';
2401 // Using TLV format
2402 $s = pack('C1', 1).pack('C1', strlen($mysocname)).$mysocname;
2403 $s .= pack('C1', 2).pack('C1', strlen($mysoctva_intra)).$mysoctva_intra;
2404 $s .= pack('C1', 3).pack('C1', strlen($datestring)).$datestring;
2405 $s .= pack('C1', 4).pack('C1', strlen($pricewithtaxstring)).$pricewithtaxstring;
2406 $s .= pack('C1', 5).pack('C1', strlen($pricetaxstring)).$pricetaxstring;
2407 $s .= ''; // Hash of xml invoice
2408 $s .= ''; // ecda signature
2409 $s .= ''; // ecda public key
2410 $s .= ''; // ecda signature of public key stamp
2411
2412 $s = base64_encode($s);
2413
2414 return $s;
2415 }
2416
2417
2424 {
2425 global $conf, $mysoc;
2426
2427 $tmplang = new Translate('', $conf);
2428 $tmplang->setDefaultLang('en_US');
2429 $tmplang->load("main");
2430
2431 $pricewithtaxstring = price2num($this->total_ttc, 2, 1);
2432 $pricetaxstring = price2num($this->total_tva, 2, 1);
2433
2434 $complementaryinfo = '';
2435 /*
2436 Example: //S1/10/10201409/11/190512/20/1400.000-53/30/106017086/31/180508/32/7.7/40/2:10;0:30
2437 /10/ Invoice number -- 10201409
2438 /11/ Invoice date -- 12.05.2019
2439 /20/ Customer reference -- 1400.000-53
2440 /30/ VAT IDE number -- CHE-106.017.086 TVA
2441 /31/ Service date for VAT accounting -- 08.05.2018
2442 /32/ VAT rate on total invoice amount -- 7.7%
2443 /40/ Terms -- 2% discount at 10 days, net payment at 30 days
2444 */
2445 $datestring = dol_print_date($this->date, '%y%m%d');
2446 //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2);
2447 //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2);
2448 $complementaryinfo = '//S1/10/'.str_replace('/', '', $this->ref).'/11/'.$datestring;
2449 if ($this->ref_client) {
2450 $complementaryinfo .= '/20/'.$this->ref_client;
2451 }
2452 if ($this->thirdparty->tva_intra) {
2453 $complementaryinfo .= '/30/'.$this->thirdparty->tva_intra;
2454 }
2455
2456 include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
2457 $bankaccount = new Account($this->db);
2458
2459 // Header
2460 $s = '';
2461 $s .= "SPC\n";
2462 $s .= "0200\n";
2463 $s .= "1\n";
2464 // Info Seller ("Account / Payable to")
2465 if ($this->fk_account > 0) {
2466 // Bank BAN if country is LI or CH. TODO Add a test to check than IBAN start with CH or LI
2467 $bankaccount->fetch($this->fk_account);
2468 $s .= $bankaccount->iban."\n";
2469 } else {
2470 $s .= "\n";
2471 }
2472 if ($bankaccount->id > 0 && getDolGlobalString('PDF_SWISS_QRCODE_USE_OWNER_OF_ACCOUNT_AS_CREDITOR')) {
2473 // If a bank account is provided and we ask to use it as creditor, we use the bank address
2474 // TODO In a future, we may always use this address, and if name/address/zip/town/country differs from $mysoc, we can use the address of $mysoc into the final seller field ?
2475 $s .= "S\n";
2476 $s .= dol_trunc($bankaccount->owner_name, 70, 'right', 'UTF-8', 1)."\n";
2477 $addresslinearray = explode("\n", (string) $bankaccount->owner_address);
2478 $s .= dol_trunc(empty($addresslinearray[0]) ? '' : $addresslinearray[0], 70, 'right', 'UTF-8', 1)."\n"; // address line 1
2479 $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 2
2480 /*$s .= dol_trunc($mysoc->zip, 16, 'right', 'UTF-8', 1)."\n";
2481 $s .= dol_trunc($mysoc->town, 35, 'right', 'UTF-8', 1)."\n";
2482 $s .= dol_trunc($mysoc->country_code, 2, 'right', 'UTF-8', 1)."\n";*/
2483 } else {
2484 $s .= "S\n";
2485 $s .= dol_trunc((string) $mysoc->name, 70, 'right', 'UTF-8', 1)."\n";
2486 $addresslinearray = explode("\n", (string) $mysoc->address);
2487 $s .= dol_trunc(empty($addresslinearray[0]) ? '' : $addresslinearray[0], 70, 'right', 'UTF-8', 1)."\n"; // address line 1
2488 $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 2
2489 $s .= dol_trunc($mysoc->zip, 16, 'right', 'UTF-8', 1)."\n";
2490 $s .= dol_trunc($mysoc->town, 35, 'right', 'UTF-8', 1)."\n";
2491 $s .= dol_trunc($mysoc->country_code, 2, 'right', 'UTF-8', 1)."\n";
2492 }
2493 // Final seller (Ultimate seller) ("Final creditor" = "In favour of")
2494 $s .= "\n";
2495 $s .= "\n";
2496 $s .= "\n";
2497 $s .= "\n";
2498 $s .= "\n";
2499 $s .= "\n";
2500 $s .= "\n";
2501 // Amount of payment (to do?)
2502 $s .= price($pricewithtaxstring, 0, 'none', 0, 0, 2)."\n";
2503 $s .= ($this->multicurrency_code ? $this->multicurrency_code : $conf->currency)."\n";
2504 // Buyer
2505 $s .= "S\n";
2506 $s .= dol_trunc((string) $this->thirdparty->name, 70, 'right', 'UTF-8', 1)."\n";
2507 $addresslinearray = explode("\n", (string) $this->thirdparty->address);
2508 $s .= dol_trunc(empty($addresslinearray[0]) ? '' : $addresslinearray[0], 70, 'right', 'UTF-8', 1)."\n"; // address line 1
2509 $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 2
2510 $s .= dol_trunc($this->thirdparty->zip, 16, 'right', 'UTF-8', 1)."\n";
2511 $s .= dol_trunc($this->thirdparty->town, 35, 'right', 'UTF-8', 1)."\n";
2512 $s .= dol_trunc($this->thirdparty->country_code, 2, 'right', 'UTF-8', 1)."\n";
2513 // ID of payment
2514 // A swiss QR bill accepts SCOR with an ISO 11649 reference on an ordinary IBAN,
2515 // QRR with a QR-IBAN, or NON. QRR is not built here because a QR reference and
2516 // its QR-IBAN are assigned by the bank, so only SCOR and NON are produced.
2517 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
2518
2519 $paymentref = empty($this->payment_reference) ? '' : (string) $this->payment_reference;
2520
2521 if ($paymentref !== '' && dolPayRefDetectScheme($paymentref) == 'SCOR') {
2522 $s .= "SCOR\n"; // NON, QRR or SCOR
2523 $s .= dolPayRefStrip($paymentref)."\n"; // ISO 11649 creditor reference
2524 } else {
2525 $s .= "NON\n"; // NON or QRR
2526 $s .= "\n"; // QR Code reference if previous field is QRR
2527 }
2528 // Unstructured message. The structured billing information below carries the
2529 // same details, so this stays empty to avoid printing them twice.
2530 $s .= "\n";
2531 $s .= "EPD\n";
2532 // More text, complementary info
2533 if ($complementaryinfo) {
2534 $s .= $complementaryinfo."\n";
2535 }
2536 $s .= "\n";
2537 //var_dump($s);exit;
2538 return $s;
2539 }
2540}
2541
2542
2543
2544require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
2545
2550{
2556 public $label;
2557
2563 public $ref; // Product ref (deprecated)
2569 public $libelle; // Product label (deprecated)
2570
2575 public $product_type = 0;
2576
2581 public $product_ref;
2582
2587 public $product_label;
2588
2593 public $product_desc;
2594
2599 public $qty;
2600
2605 public $subprice;
2606
2612 public $price;
2613
2618 public $fk_product;
2619
2624 public $vat_src_code;
2625
2630 public $tva_tx;
2631
2636 public $localtax1_tx;
2637
2642 public $localtax2_tx;
2643
2649 public $localtax1_type;
2650
2656 public $localtax2_type;
2657
2662 public $remise_percent;
2663
2668 public $fk_remise_except;
2669
2674 public $total_ht;
2675
2680 public $total_tva;
2681
2686 public $total_localtax1;
2687
2692 public $total_localtax2;
2693
2698 public $total_ttc;
2699
2703 public $revenuestamp;
2704
2705
2709 public $date_start_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_start at creation
2713 public $date_end_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_end at creation
2714
2718 public $buy_price_ht;
2723 public $buyprice;
2728 public $pa_ht;
2729
2733 public $marge_tx;
2737 public $marque_tx;
2738
2745 public $info_bits = 0;
2746
2755 public $special_code = 0;
2756
2761 public $fk_user_author;
2762
2767 public $fk_user_modif;
2768
2772 public $fk_code_ventilation;
2773
2777 public $situation_percent = 100;
2778
2779
2785 public function isDepositLine()
2786 {
2787 // Do not take into account lines of the type "deposit."
2788 $reg = array();
2789 if (preg_match('/^\‍((.*)\‍)$/', $this->desc, $reg)) {
2790 if ($reg[1] == 'DEPOSIT') {
2791 return true;
2792 }
2793 }
2794 return false;
2795 }
2796}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
isALNERunningVersion($blockedlogusagealreadychecked=0, $blockedlogmoduleonalreadychecked=0)
Return if the application is executed with the LNE requirements on.
$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 agenda events (actions)
Class to manage withdrawal receipts.
Superclass for invoice classes.
const TYPE_CREDIT_NOTE
Credit note invoice.
const STATUS_CLOSED
Classified paid.
checkPointOfTaxNotChanged()
Check that the point of tax date of a validated invoice is not changed by an update.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getRemainToPay($multicurrency=0)
Return remain amount to pay.
buildZATCAQRString()
Build string for ZATCA QR Code (Arabi Saudia)
makeStripeCardRequest($fuser, $id, $sourcetype='facture')
Create a payment with Stripe card Must take amount using Stripe and record an event into llx_actionco...
getVentilExportCompta($mode=0)
Return if an invoice was transferred into accountnancy.
const TYPE_STANDARD
Standard invoice.
buildEPCQrCodeString()
Build string for EPC QR Code.
makeStripeSepaRequest($fuser, $did, $type='direct-debit', $sourcetype='facture', $service='', $forcestripe='')
Create a direct debit order into prelevement_bons for a given prelevement_request,...
getSubtypeLabel($table='')
Return label of invoice subtype.
demande_prelevement_delete($fuser, $did)
Remove a direct debit request or a credit transfer request.
const TYPE_PROFORMA
Proforma invoice.
buildSwitzerlandQRString()
Build string for QR-Bill (Switzerland)
const STATUS_VALIDATED
Validated (need to be paid)
getListOfPayments($filtertype='', $multicurrency=0, $mode=0)
Return list of payments.
getListOfOpenDirectDebitOrCreditTransfer($type)
Return list of open direct debit or credit transfer.
const TYPE_SITUATION
Situation invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
LibStatut($paye, $status, $mode=0, $alreadypaid=-1, $type=-1, $moreparams=array())
Return label of a status.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
isReplacable()
Return if an invoice can be replaced by a Replacement invoice (also called "Correction invoice").
demande_prelevement(User $fuser, float $amount=0, string $type='direct-debit', string $sourcetype='facture', int $checkduplicateamongall=0, int $ribId=0)
Create a withdrawal request for a direct debit order or a credit transfer order.
const TYPE_DEPOSIT
Deposit invoice.
const STATUS_ABANDONED
Classified abandoned and no payment done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
const TYPE_REPLACEMENT
Replacement invoice.
isEditable()
Return if an invoice can be set back to draft.
getSumFromThisCreditNotesNotUsed($multicurrency=0)
Return amount (with tax) of all converted amount for this credit note.
getListIdAvoirFromInvoice()
Returns array of credit note ids from the invoice.
setRetainedWarrantyPaymentTerms($id)
Change the retained warranty payments terms.
const STATUS_DRAFT
Draft status.
getIdReplacingInvoice($option='')
Returns the id of the invoice that replaces it.
getLibType($withbadge=0)
Return label of type of invoice.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
getArrayOfInvoiceSubtypes($mode=0)
Retrieve a list of invoice subtype labels or codes.
getLibStatut($mode=0, $alreadypaid=-1)
Return label of object status.
getNextNumRef($soc, $mode='next')
Return next reference of invoice not already used (or last reference)
Parent class of all other business classes for details of elements (invoices, contracts,...
isDepositLine()
Check if a line is a deposit line.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
setPaymentMethods($id)
Change the payments methods.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage bank accounts description of third parties.
Class for CompanyPaymentMode.
Class to manage absolute discounts.
Class to manage invoices.
Class to manage third parties objects (customers, suppliers, prospects...)
Stripe class @TODO No reason to extend CommonObject.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
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...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
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.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
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_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
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.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dolBECalculateStructuredCommunication($invoice_number, $invoice_type)
Calculate Structured Communication / BE Bank payment reference number.
dolPayRefStrip($ref)
Remove formatting spaces from a payment reference (machine form).
dolPayRefDetectScheme($ref)
Detect which structured payment reference scheme a stored value belongs to.
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