dolibarr 25.0.0-alpha
facture.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
5 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
6 * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
7 * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
9 * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
10 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
11 * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
12 * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
13 * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
14 * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2013 Cedric Gross <c.gross@kreiz-it.fr>
16 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
17 * Copyright (C) 2016-2025 Ferran Marcet <fmarcet@2byte.es>
18 * Copyright (C) 2018-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
19 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
20 * Copyright (C) 2022 Sylvain Legrand <contact@infras.fr>
21 * Copyright (C) 2022-2023 Solution Libre SAS <contact@solution-libre.fr>
22 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
23 * Copyright (C) 2023 Nick Fragoulis
24 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
25 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
26 * Copyright (C) 2025-2026 Lenin Rivas <lenin.rivas777@gmail.com>
27 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
28 * Copyright (C) 2026 Lionel Vessiller <lvessiller@open-dsi.fr>
29 * Copyright (C) 2026 José MARTINEZ <jose.martinez@pichinov.com>
30 *
31 * This program is free software; you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation; either version 3 of the License, or
34 * (at your option) any later version.
35 *
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
40 *
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <https://www.gnu.org/licenses/>.
43 */
44
51require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
52require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/factureligne.class.php';
53require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
54require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
55require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
56require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
57require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
58
59if (isModEnabled('accounting')) {
60 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
61}
62if (isModEnabled('accounting')) {
63 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
64}
65
70{
71 use CommonSubtotal;
72
76 public $element = 'facture';
77
81 public $TRIGGER_PREFIX = 'BILL';
82
86 public $table_element = 'facture';
87
91 public $table_element_line = 'facturedet';
92
96 public $class_element_line = 'FactureLigne';
97
101 public $fk_element = 'fk_facture';
102
106 public $picto = 'bill';
107
112 public $restrictiononfksoc = 1;
113
117 protected $table_ref_field = 'ref';
118
122 public $ref;
123
128 public $fk_user_author;
129
134 public $fk_user_valid;
135
140 public $fk_user_modif;
141
145 public $datem;
146
150 public $delivery_date; // Date expected of shipment (date of start of shipment, not the reception that occurs some days after)
151
157 public $ref_client;
158
162 public $ref_customer;
163
167 public $resteapayer;
168
173 public $paye;
174
178 public $module_source;
182 public $pos_source;
183
187 public $increment;
188
192 public $pos_print_counter = 0;
193
197 public $email_sent_counter = 0;
198
202 public $fk_fac_rec_source;
203
207 public $fk_facture_source;
208
212 public $fk_bank;
213
217 public $lines = array();
218
222 public $line;
226 public $extraparams = array();
227
231 public $fac_rec;
232
236 public $date_pointoftax;
237
238
242 public $situation_cycle_ref;
243
247 public $situation_counter;
248
252 public $situation_final;
253
257 public $tab_previous_situation_invoice = array();
258
262 public $tab_next_situation_invoice = array();
263
267 public $retained_warranty;
268
272 public $retained_warranty_date_limit;
273
277 public $retained_warranty_fk_cond_reglement;
278
282 public $availability_id;
283
287 public $date_closing;
288
292 public $source;
293
298 public $remise_percent;
299
303 public $online_payment_url;
304
308 public $ip;
309
310
336 // BEGIN MODULEBUILDER PROPERTIES
340 public $fields = array(
341 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 1),
342 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 5),
343 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
344 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 10),
345 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 12),
346 'type' => array('type' => 'smallint(6)', 'label' => 'Type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
347 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
348 //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
349 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 50),
350 'datef' => array('type' => 'date', 'label' => 'DateInvoice', 'enabled' => 1, 'visible' => 1, 'position' => 20),
351 'date_valid' => array('type' => 'date', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 22),
352 'date_lim_reglement' => array('type' => 'date', 'label' => 'DateDue', 'enabled' => 1, 'visible' => 1, 'position' => 25),
353 'date_closing' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 30),
354 'paye' => array('type' => 'smallint(6)', 'label' => 'InvoicePaidCompletely', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 80),
355 'close_code' => array('type' => 'varchar(16)', 'label' => 'EarlyClosingReason', 'enabled' => 1, 'visible' => -1, 'position' => 92),
356 'close_note' => array('type' => 'varchar(128)', 'label' => 'EarlyClosingComment', 'enabled' => 1, 'visible' => -1, 'position' => 93),
357 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 95, 'isameasure' => 1),
358 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => -1, 'position' => 100, 'isameasure' => 1),
359 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => -1, 'position' => 110, 'isameasure' => 1),
360 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => -1, 'position' => 120, 'isameasure' => 1),
361 'revenuestamp' => array('type' => 'double(24,8)', 'label' => 'RevenueStamp', 'enabled' => 1, 'visible' => -1, 'position' => 115, 'isameasure' => 1),
362 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
363 'fk_facture_source' => array('type' => 'integer', 'label' => 'SourceInvoice', 'enabled' => 1, 'visible' => -1, 'position' => 170),
364 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => 1, 'visible' => -1, 'position' => 175),
365 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 180),
366 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'CurrencyCode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
367 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 190),
368 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 195),
369 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 205),
370 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 210),
371 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 215),
372 'fk_input_reason' => array('type' => 'integer', 'label' => 'Source', 'enabled' => 1, 'visible' => -1, 'position' => 220),
373 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
374 'situation_cycle_ref' => array('type' => 'smallint(6)', 'label' => 'Situation cycle ref', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 230),
375 'situation_counter' => array('type' => 'smallint(6)', 'label' => 'Situation counter', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 235),
376 'situation_final' => array('type' => 'smallint(6)', 'label' => 'Situation final', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 240),
377 'retained_warranty' => array('type' => 'double', 'label' => 'Retained warranty', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 245),
378 'retained_warranty_date_limit' => array('type' => 'date', 'label' => 'Retained warranty date limit', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 250),
379 'retained_warranty_fk_cond_reglement' => array('type' => 'integer', 'label' => 'Retained warranty fk cond reglement', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 255),
380 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 260),
381 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 265),
382 'date_pointoftax' => array('type' => 'date', 'label' => 'DatePointOfTax', 'enabled' => 'getDolGlobalString("INVOICE_POINTOFTAX_DATE")', 'visible' => -1, 'position' => 270),
383 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyID', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 275),
384 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 280),
385 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 285, 'isameasure' => 1),
386 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 290, 'isameasure' => 1),
387 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 291, 'isameasure' => 1),
388 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 292, 'isameasure' => 1),
389 'fk_fac_rec_source' => array('type' => 'integer', 'label' => 'RecurringInvoiceSource', 'enabled' => 1, 'visible' => -1, 'position' => 305),
390 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 310),
391 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'langfile' => 'cashdesk', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 315),
392 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'langfile' => 'cashdesk', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 320),
393 'pos_print_counter' => array('type' => 'integer', 'label' => 'PrintCount', 'langfile' => 'cashdesk', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => 0, 'position' => 325),
394 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 500),
395 'tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 502),
396 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 506),
397 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModification', 'enabled' => 1, 'visible' => -1, 'notnull' => -1, 'position' => 508),
398 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 510),
399 'fk_user_closing' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 512),
400 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
401 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 1000, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 2 => 'Paid', 3 => 'Abandonned')),
402 );
403 // END MODULEBUILDER PROPERTIES
404
408 const TYPE_STANDARD = 0;
409
414
419
423 const TYPE_DEPOSIT = 3;
424
428 const TYPE_PROFORMA = 4;
429
433 const TYPE_SITUATION = 5;
434
438 const STATUS_DRAFT = 0;
439
444
461 const STATUS_CLOSED = 2;
462
469
470
476 public function __construct(DoliDB $db)
477 {
478 $this->db = $db;
479
480 $this->ismultientitymanaged = 1;
481 $this->isextrafieldmanaged = 1;
482
483 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
484 }
485
497 public function create(User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
498 {
499 global $langs, $conf, $mysoc;
500 $error = 0;
501 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
502 // Clean parameters
503 if (empty($this->type)) {
504 $this->type = self::TYPE_STANDARD;
505 }
506
507 $this->ref_client = trim((string) $this->ref_client); // deprecated
508 $this->ref_customer = trim((string) $this->ref_customer);
509
510 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : '');
511 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private); // deprecated
512 $this->note_public = (isset($this->note_public) ? trim($this->note_public) : '');
513
514 if (!$this->cond_reglement_id) {
515 $this->cond_reglement_id = 0;
516 }
517 if (!$this->mode_reglement_id) {
518 $this->mode_reglement_id = 0;
519 }
520 $this->status = self::STATUS_DRAFT;
521 $this->statut = self::STATUS_DRAFT; // deprecated
522
523 if (!empty($this->multicurrency_code)) {
524 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate of multicurrency_code only if not using original rate)
525 if (empty($this->multicurrency_tx)) {
526 // If original rate is not set, we take a default value from date
527 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
528 } else {
529 // original rate multicurrency_tx and multicurrency_code are already known, so we keep them and we catch only the ID of the currency.
530 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
531 }
532 } else {
533 $this->fk_multicurrency = 0;
534 }
535 if (empty($this->fk_multicurrency)) {
536 $this->multicurrency_code = $conf->currency;
537 $this->fk_multicurrency = 0;
538 $this->multicurrency_tx = 1;
539 }
540 $this->entity = setEntity($this);
541
542 dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
543
544 // Check parameters
545 if (empty($this->date)) {
546 $this->error = "Try to create an invoice with an empty parameter (date)";
547 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
548 return -3;
549 }
550 $soc = new Societe($this->db);
551 $result = $soc->fetch($this->socid);
552 if ($result < 0) {
553 $this->error = "Failed to fetch company: ".$soc->error;
554 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
555 return -2;
556 }
557
558 $now = dol_now();
559 $this->date_creation = $now;
560
561 $this->db->begin();
562
563 $originaldatewhen = null;
564 $nextdatewhen = null;
565 $previousdaynextdatewhen = null;
566
567 $_facrec = null;
568
569 // Erase some properties of the invoice to create with the one of the recurring invoice
570 if ($this->fac_rec > 0) {
571 $this->fk_fac_rec_source = $this->fac_rec;
572
573 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
574 $_facrec = new FactureRec($this->db);
575 $result = $_facrec->fetch($this->fac_rec);
576 $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
577
578 if (getDolGlobalString('MODEL_FAC_REC_AUTHOR')) {
579 // If option MODEL_FAC_REC_AUTHOR is set, we want the same author than the author of recurring invoice instead of current user
580 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
581 }
582
583 // Define some dates
584 $originaldatewhen = $_facrec->date_when;
585 $nextdatewhen = null;
586 $previousdaynextdatewhen = null;
587
588 if ($originaldatewhen) {
589 if ($_facrec->rule_for_lines_dates == 'postpaid') { // Bugged feature, should use different variable nameas we store something different.
590 $previousdaynextdatewhen = dol_time_plus_duree($originaldatewhen, -1, 'd');
591 $originaldatewhen = dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency);
592 } else {
593 $nextdatewhen = dol_time_plus_duree($originaldatewhen, (int) $_facrec->frequency, $_facrec->unit_frequency);
594 $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
595 }
596 }
597
598 // Define thirdparty
599 if (!empty($_facrec->frequency)) { // Invoice are created on same thirdparty than template when there is a recurrence, but not necessarily when there is no recurrence.
600 $this->socid = $_facrec->socid;
601 }
602
603 // Define the entity
604 $this->entity = $_facrec->entity; // Invoice created in same entity than template
605
606 // Fields coming from GUI.
607 // @TODO Value of template should be used as default value on the form on the GUI, and we should here always use the value from GUI
608 // set by posted page with $object->xxx = ... and this section should be removed.
609 $this->fk_project = GETPOSTINT('projectid') > 0 ? GETPOSTINT('projectid') : $_facrec->fk_project;
610 $this->note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
611 $this->note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
612 $this->model_pdf = GETPOSTISSET('model') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
613 $this->cond_reglement_id = GETPOSTINT('cond_reglement_id') > 0 ? GETPOSTINT('cond_reglement_id') : $_facrec->cond_reglement_id;
614 $this->mode_reglement_id = GETPOSTINT('mode_reglement_id') > 0 ? GETPOSTINT('mode_reglement_id') : $_facrec->mode_reglement_id;
615 $this->fk_account = GETPOST('fk_account') > 0 ? GETPOSTINT('fk_account') : $_facrec->fk_account;
616
617 // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
618 $this->total_ht = $_facrec->total_ht;
619 $this->total_ttc = $_facrec->total_ttc;
620
621 // Fields always coming from template
622 $this->fk_incoterms = $_facrec->fk_incoterms;
623 $this->location_incoterms = $_facrec->location_incoterms;
624
625 // Clean parameters
626 if (!$this->type) {
627 $this->type = self::TYPE_STANDARD;
628 }
629 $this->ref_client = trim($this->ref_client);
630 $this->ref_customer = trim($this->ref_customer);
631 $this->note_public = trim($this->note_public);
632 $this->note_private = trim($this->note_private);
633 $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
634
635 // Use template extra fields as fallback only - form values (already set) take precedence
636 foreach ($_facrec->array_options as $key => $val) {
637 if (!isset($this->array_options[$key]) || $this->array_options[$key] === '') {
638 $this->array_options[$key] = $val;
639 }
640 }
641
642 if (!$this->mode_reglement_id) {
643 $this->mode_reglement_id = 0;
644 }
645 $this->status = self::STATUS_DRAFT;
646 $this->statut = self::STATUS_DRAFT; // deprecated
647
648 $this->linked_objects = $_facrec->linkedObjectsIds;
649 // We do not add link to template invoice or next invoice will be linked to all generated invoices
650 //$this->linked_objects['facturerec'][0] = $this->fac_rec;
651
652 // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
653 if ($_facrec->frequency > 0) {
654 dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
655 if (empty($_facrec->date_when)) {
656 $_facrec->date_when = $now;
657 }
658 $next_date = $_facrec->getNextDate(); // Calculate next date
659
660 $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
661 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
662
663 $result = $_facrec->setNextDate($next_date, 1);
664 }
665
666 // Define lang of customer
667 $outputlangs = $langs;
668 $newlang = '';
669
670 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
671 $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
672 }
673 // @phan-suppress-next-line PhanUndeclaredProperty
674 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
675 $newlang = $this->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
676 }
677 if (!empty($newlang)) {
678 $outputlangs = new Translate("", $conf);
679 $outputlangs->setDefaultLang($newlang);
680 }
681
682 // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
683 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
684 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
685 $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
686 $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
687 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
688 $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
689 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
690 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
691 $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
692 $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
693 // Only for template invoice
694 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ? dol_print_date($originaldatewhen, 'dayhour') : '');
695 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ? dol_print_date($nextdatewhen, 'dayhour') : '');
696 $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '');
697 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
698 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
699
700 //var_dump($substitutionarray);exit;
701
702 complete_substitutions_array($substitutionarray, $outputlangs);
703
704 $this->note_public = make_substitutions($this->note_public, $substitutionarray);
705 $this->note_private = make_substitutions($this->note_private, $substitutionarray);
706 }
707
708 // Define due date if not already defined
709 if (empty($forceduedate)) {
710 $duedate = $this->calculate_date_lim_reglement();
711 /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
712 dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
713 return -1;
714 }*/
715 $this->date_lim_reglement = $duedate;
716 } else {
717 $this->date_lim_reglement = $forceduedate;
718 }
719
720 // Insert into database
721 $socid = $this->socid;
722
723 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
724 $sql .= " ref";
725 $sql .= ", entity";
726 $sql .= ", ref_ext";
727 $sql .= ", type";
728 $sql .= ", subtype";
729 $sql .= ", fk_soc";
730 $sql .= ", datec";
731 $sql .= ", datef";
732 $sql .= ", date_pointoftax";
733 $sql .= ", note_private";
734 $sql .= ", note_public";
735 $sql .= ", ref_client";
736 $sql .= ", fk_account";
737 $sql .= ", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
738 $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
739 $sql .= ", fk_input_reason";
740 $sql .= ", situation_cycle_ref, situation_counter, situation_final";
741 $sql .= ", fk_incoterms, location_incoterms";
742 $sql .= ", fk_multicurrency";
743 $sql .= ", multicurrency_code";
744 $sql .= ", multicurrency_tx";
745 $sql .= ", retained_warranty";
746 $sql .= ", retained_warranty_date_limit";
747 $sql .= ", retained_warranty_fk_cond_reglement";
748 $sql .= ", ip";
749 $sql .= ")";
750 $sql .= " VALUES (";
751 $sql .= "'(PROV)'";
752 $sql .= ", ".(int) $this->entity;
753 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
754 $sql .= ", ".((int) $this->type);
755 $sql .= ", ".(isset($this->subtype) ? (int) $this->subtype : "null");
756 $sql .= ", ".((int) $socid);
757 $sql .= ", '".$this->db->idate($this->date_creation)."'";
758 // Date of invoice is a full day, if entered the 27-01 at 22:00 in timezone of user, it must be 27-01 00:00 after the conversion by idate, so when SQL is truncated we keep the 27-01.
759 // So we hope that caller has set the gmt datein ->date to match this.
760 $sql .= ", '".$this->db->idate($this->date)."'";
761 $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
762 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
763 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
764 $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : ($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"));
765 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
766 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
767 $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape((string) $this->pos_source)."'" : "null");
768 $sql .= ", ".(int) $this->pos_print_counter;
769 $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape((string) $this->fk_fac_rec_source)."'" : "null");
770 $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape((string) $this->fk_facture_source)."'" : "null");
771 $sql .= ", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id : "null");
772 $sql .= ", ".($this->fk_project ? (int) $this->fk_project : "null");
773 $sql .= ", ".((int) $this->cond_reglement_id);
774 $sql .= ", ".((int) $this->mode_reglement_id);
775 $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
776 $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
777 $sql .= ", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id : "null");
778 $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape((string) $this->situation_cycle_ref)."'" : "null");
779 $sql .= ", ".($this->situation_counter ? "'".$this->db->escape((string) $this->situation_counter)."'" : "null");
780 $sql .= ", ".($this->situation_final ? (int) $this->situation_final : 0);
781 $sql .= ", ".(int) $this->fk_incoterms;
782 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
783 $sql .= ", ".(int) $this->fk_multicurrency;
784 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
785 $sql .= ", ".(float) $this->multicurrency_tx;
786 $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape((string) $this->retained_warranty));
787 $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
788 $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
789 $sql .= ", ".(!empty($this->ip) ? "'".$this->db->escape($this->ip)."'" : "null");
790 $sql .= ")";
791
792 $resql = $this->db->query($sql);
793 if ($resql) {
794 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
795
796 // Update ref with new one
797 $this->ref = '(PROV'.$this->id.')';
798 $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
799
800 $resql = $this->db->query($sql);
801 if (!$resql) {
802 $error++;
803 }
804
805 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
806 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
807 }
808
809 // Add object linked
810 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
811 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
812 if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
813 foreach ($tmp_origin_id as $origin_id) {
814 $ret = $this->add_object_linked($origin, $origin_id);
815 if (!$ret) {
816 $this->error = $this->db->lasterror();
817 $error++;
818 }
819 }
820 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
821 $origin_id = $tmp_origin_id;
822 $ret = $this->add_object_linked($origin, $origin_id);
823 if (!$ret) {
824 $this->error = $this->db->lasterror();
825 $error++;
826 }
827 }
828 }
829 }
830
831 // Propagate contacts
832 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) { // Get contact from origin object
833 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
834 $originidforcontact = $this->origin_id;
835 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
836 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
837 $exp = new Expedition($this->db);
838 $exp->fetch($this->origin_id);
839 $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
840 if (count($exp->linkedObjectsIds['commande']) > 0) {
841 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
842 $originforcontact = 'commande';
843 if (is_object($value)) {
844 $originidforcontact = $value->id;
845 } else {
846 $originidforcontact = $value;
847 }
848 break; // We take first one
849 }
850 }
851 }
852
853 $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople";
854 $sqlcontact .= " FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
855 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
856
857 $resqlcontact = $this->db->query($sqlcontact);
858 if ($resqlcontact) {
859 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
860 $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
861 }
862 } else {
863 dol_print_error($this->db);
864 }
865 }
866
867 // Insert lines of invoices, if not coming from template invoice, into database
868 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
869 $fk_parent_line = 0;
870
871 dol_syslog("There is ".count($this->lines)." lines into ->lines that are InvoiceLines");
872 foreach ($this->lines as $i => $val) {
873 $newinvoiceline = $this->lines[$i];
874 '@phan-var-force FactureLigne $newinvoiceline';
875
876 $newinvoiceline->context = $this->context;
877
878 $newinvoiceline->fk_facture = $this->id;
879
880 $newinvoiceline->origin = $this->lines[$i]->element;
881 $newinvoiceline->origin_type = $this->lines[$i]->element;
882 $newinvoiceline->origin_id = $this->lines[$i]->id;
883
884 // Auto set date of service ?
885 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
886 $newinvoiceline->date_start = $originaldatewhen;
887 }
888 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
889 $newinvoiceline->date_end = $previousdaynextdatewhen;
890 }
891
892 if ($result >= 0) {
893 // Reset fk_parent_line for no child products and special product
894 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
895 $fk_parent_line = 0;
896 }
897
898 // Complete vat rate with code
899 $vatrate = $newinvoiceline->tva_tx;
900 if ($newinvoiceline->vat_src_code && ! preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
901 $vatrate .= ' ('.$newinvoiceline->vat_src_code.')';
902 }
903
904 $newinvoiceline->fk_parent_line = $fk_parent_line;
905
906 if ($this->type == Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
907 $discount = new DiscountAbsolute($this->db);
908 $discount->fetch($newinvoiceline->fk_remise_except);
909
910 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
911 $newinvoiceline->fk_remise_except = $discountId;
912 }
913
914 // Preserve the original entry mode of the line so the total is computed from the typed value (no rounding drift).
915 $line_price_base_type = $newinvoiceline->getPriceBaseType();
916 $result = $this->addline(
917 $newinvoiceline->desc,
918 (float) $newinvoiceline->subprice,
919 $newinvoiceline->qty,
920 $vatrate,
921 $newinvoiceline->localtax1_tx,
922 $newinvoiceline->localtax2_tx,
923 $newinvoiceline->fk_product,
924 $newinvoiceline->remise_percent,
925 $newinvoiceline->date_start,
926 $newinvoiceline->date_end,
927 $newinvoiceline->fk_code_ventilation,
928 $newinvoiceline->info_bits,
929 $newinvoiceline->fk_remise_except,
930 $line_price_base_type,
931 (float) $newinvoiceline->subprice_ttc,
932 $newinvoiceline->product_type,
933 $newinvoiceline->rang,
934 $newinvoiceline->special_code,
935 $newinvoiceline->element,
936 $newinvoiceline->id,
937 $fk_parent_line,
938 $newinvoiceline->fk_fournprice,
939 $newinvoiceline->pa_ht,
940 $newinvoiceline->label,
941 $newinvoiceline->array_options,
942 $newinvoiceline->situation_percent,
943 $newinvoiceline->fk_prev_id,
944 $newinvoiceline->fk_unit,
945 $newinvoiceline->multicurrency_subprice,
946 $newinvoiceline->ref_ext,
947 1
948 );
949
950 if ($result < 0) {
951 $this->setErrorsFromObject($newinvoiceline);
952 $error++;
953 break;
954 }
955
956 // Defined the new fk_parent_line
957 if ($result > 0 && $newinvoiceline->product_type == 9) {
958 $fk_parent_line = $result;
959 }
960 }
961 }
962 } elseif (!$error && empty($this->fac_rec)) { // If not coming from a template invoice and this->lines is an array of invoice line arrays
963 $fk_parent_line = 0;
964
965 dol_syslog("There is ".count($this->lines)." lines into ->lines as a simple array");
966
967 foreach ($this->lines as $i => $val) {
968 $line = $this->lines[$i];
969 '@phan-var-force FactureLigne $line';
970
971 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
972 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
973 if (!is_object($line)) {
974 $line = (object) $line;
975 }
976
977 if ($result >= 0) {
978 // Reset fk_parent_line for no child products and special product
979 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
980 $fk_parent_line = 0;
981 }
982
983 // Complete vat rate with code
984 $vatrate = $line->tva_tx;
985 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
986 $vatrate .= ' ('.$line->vat_src_code.')';
987 }
988
989 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
990 $originid = $line->origin_id;
991 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
992 } else { // old but bugged version (we store id of line and type of parent object)
993 $originid = $line->id;
994 $origintype = $this->element;
995 }
996
997 // init ref_ext
998 if (empty($line->ref_ext)) {
999 $line->ref_ext = '';
1000 }
1001
1002 $result = $this->addline(
1003 $line->desc,
1004 $line->subprice,
1005 $line->qty,
1006 $vatrate,
1007 $line->localtax1_tx,
1008 $line->localtax2_tx,
1009 $line->fk_product,
1010 $line->remise_percent,
1011 $line->date_start,
1012 $line->date_end,
1013 $line->fk_code_ventilation,
1014 $line->info_bits,
1015 $line->fk_remise_except,
1016 'HT',
1017 0,
1018 $line->product_type,
1019 $line->rang,
1020 $line->special_code,
1021 $origintype,
1022 $originid,
1023 $fk_parent_line,
1024 $line->fk_fournprice,
1025 $line->pa_ht,
1026 $line->label,
1027 $line->array_options,
1028 $line->situation_percent,
1029 $line->fk_prev_id,
1030 $line->fk_unit,
1031 $line->multicurrency_subprice,
1032 $line->ref_ext,
1033 1
1034 );
1035 if ($result < 0) {
1036 $this->error = $this->db->lasterror();
1037 dol_print_error($this->db);
1038 $this->db->rollback();
1039 return -1;
1040 }
1041
1042 // Defined the new fk_parent_line
1043 if ($result > 0 && $line->product_type == 9) {
1044 $fk_parent_line = $result;
1045 }
1046 }
1047 }
1048 }
1049
1050 // Insert lines when coming from a template invoice
1051 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1052 dol_syslog("There is ".count($_facrec->lines)." lines from recurring invoice");
1053 $fk_parent_line = 0;
1054
1055 foreach ($_facrec->lines as $i => $val) {
1056 // Reset fk_parent_line for no child products and special product
1057 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1058 $fk_parent_line = 0;
1059 }
1060
1061 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
1062 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1063 if (empty($tva_tx)) {
1064 $tva_npr = 0;
1065 }
1066 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1067 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1068
1069 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1070 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1071
1072 // If buyprice not defined from template invoice, we try to guess the best value
1073 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1074 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1075 $producttmp = new ProductFournisseur($this->db);
1076 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1077
1078 // If margin module defined on costprice, we try the costprice
1079 // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
1080 // else we get the best supplier price
1081 if (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($producttmp->cost_price)) {
1082 $buyprice = $producttmp->cost_price;
1083 } elseif (isModEnabled('stock') && (getDolGlobalString('MARGIN_TYPE') == 'costprice' || getDolGlobalString('MARGIN_TYPE') == 'pmp') && !empty($producttmp->pmp)) {
1084 $buyprice = $producttmp->pmp;
1085 } else {
1086 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1087 if ($producttmp->product_fourn_price_id > 0) {
1088 $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
1089 }
1090 }
1091 }
1092 }
1093
1094 // Update price according to $updatecurrencyrate
1095 if ($updatecurrencyrate == 1) {
1096 // TODO
1097 } elseif ($updatecurrencyrate == 2) {
1098 // TODO
1099 }
1100
1101 $result_insert = $this->addline(
1102 $_facrec->lines[$i]->desc,
1103 $_facrec->lines[$i]->subprice,
1104 $_facrec->lines[$i]->qty,
1105 $tva_tx,
1106 $localtax1_tx,
1107 $localtax2_tx,
1108 $_facrec->lines[$i]->fk_product,
1109 $_facrec->lines[$i]->remise_percent,
1110 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
1111 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
1112 0,
1113 $tva_npr,
1114 0, // fk_remise_except
1115 'HT',
1116 0,
1117 $_facrec->lines[$i]->product_type,
1118 $_facrec->lines[$i]->rang,
1119 $_facrec->lines[$i]->special_code,
1120 '',
1121 0,
1122 $fk_parent_line,
1123 $fk_product_fournisseur_price,
1124 is_null($buyprice) ? '' : $buyprice, // do not use (float) here, it may be ''
1125 $_facrec->lines[$i]->label,
1126 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1127 100, // situation percent is undefined on recurring invoice lines
1128 0, // fk_prev_id
1129 $_facrec->lines[$i]->fk_unit,
1130 $_facrec->lines[$i]->multicurrency_subprice,
1131 $_facrec->lines[$i]->ref_ext,
1132 1
1133 );
1134
1135 foreach ($this->lines as $line) {
1136 if ($line->id == $result_insert) {
1137 $line->extraparams = $_facrec->lines[$i]->extraparams;
1138 $line->setExtraParameters();
1139 }
1140 }
1141
1142 // Defined the new fk_parent_line
1143 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1144 $fk_parent_line = $result_insert;
1145 }
1146
1147 if ($result_insert < 0) {
1148 $error++;
1149 $this->error = $this->db->error();
1150 break;
1151 }
1152 }
1153 }
1154
1155 if (!$error) {
1156 $result = $this->update_price(1, 'auto', 0, $mysoc);
1157 if ($result <= 0) {
1158 $this->error = $langs->trans('FailedToUpdatePrice');
1159 $this->db->rollback();
1160 return -3;
1161 }
1162 }
1163
1164 $action = 'create';
1165
1166 // Actions on extra fields
1167 if (!$error) {
1168 $result = $this->insertExtraFields();
1169 if ($result < 0) {
1170 $error++;
1171 }
1172 }
1173
1174 if (!$error && !$notrigger) {
1175 // Call trigger
1176 $result = $this->call_trigger('BILL_CREATE', $user);
1177 if ($result < 0) {
1178 $error++;
1179 }
1180 }
1181
1182 if (!$error) {
1183 $this->db->commit();
1184 return $this->id;
1185 } else {
1186 $this->db->rollback();
1187 return -4;
1188 }
1189 } else {
1190 $this->error = $this->db->error();
1191 $this->db->rollback();
1192 return -1;
1193 }
1194 }
1195
1196
1204 public function createFromCurrent(User $user, $invertdetail = 0)
1205 {
1206 // Source invoice load
1207 $facture = new Facture($this->db);
1208
1209 // Avoid updating the row ranks
1210 $facture->context['createfromclone'] = 1;
1211
1212 // Retrieve all extrafield
1213 // fetch optionals attributes and labels
1214 // (unless the caller already set array_options, e.g. from a create form, so we don't overwrite them)
1215 if (empty($this->array_options)) {
1216 $this->fetch_optionals();
1217 }
1218
1219 if (!empty($this->array_options)) {
1220 $facture->array_options = $this->array_options;
1221 }
1222
1223 foreach ($this->lines as &$line) {
1224 $line->fetch_optionals(); //fetch extrafields
1225 }
1226
1227 $facture->fk_facture_source = $this->fk_facture_source;
1228 $facture->type = $this->type;
1229 $facture->subtype = $this->subtype;
1230 $facture->socid = $this->socid;
1231 $facture->date = $this->date;
1232 $facture->date_pointoftax = $this->date_pointoftax;
1233 $facture->note_public = $this->note_public;
1234 $facture->note_private = $this->note_private;
1235 $facture->ref_client = $this->ref_client;
1236 $facture->ref_customer = $this->ref_customer;
1237 $facture->model_pdf = $this->model_pdf;
1238 $facture->fk_project = $this->fk_project;
1239 $facture->cond_reglement_id = $this->cond_reglement_id;
1240 $facture->mode_reglement_id = $this->mode_reglement_id;
1241
1242 $facture->origin = $this->origin;
1243 $facture->origin_id = $this->origin_id;
1244 $facture->fk_account = $this->fk_account;
1245
1246 $facture->lines = $this->lines; // Array of lines of invoice
1247 $facture->situation_counter = $this->situation_counter;
1248 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1249 $facture->situation_final = $this->situation_final;
1250
1251 $facture->retained_warranty = $this->retained_warranty;
1252 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1253 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1254
1255 $facture->fk_user_author = $user->id;
1256 $facture->user_creation_id = $user->id;
1257
1258
1259 // Loop on each line of new invoice
1260 foreach ($facture->lines as $i => $tmpline) {
1261 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1262 if ($invertdetail) {
1263 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1264 $facture->lines[$i]->subprice_ttc = -$facture->lines[$i]->subprice_ttc; // Keep the TTC entry mode with the inverted sign so the credit note has no rounding drift.
1265 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1266 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1267 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1268 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1269 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1270 $facture->lines[$i]->ref_ext = '';
1271 }
1272 }
1273
1274 dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1275
1276 $facid = $facture->create($user);
1277 if ($facid <= 0) {
1278 $this->error = $facture->error;
1279 $this->errors = $facture->errors;
1280 } elseif ($this->type == self::TYPE_SITUATION && getDolGlobalString('INVOICE_USE_SITUATION')) {
1281 $this->fetchObjectLinked(null, '', $this->id, 'facture');
1282
1283 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1284 foreach ($Tfk_object as $fk_object) {
1285 $facture->add_object_linked($typeObject, $fk_object);
1286 }
1287 }
1288
1289 $facture->add_object_linked('facture', $this->fk_facture_source);
1290 }
1291
1292 return $facid;
1293 }
1294
1295
1304 public function createFromClone(User $user, $fromid = 0, $forceentity = null)
1305 {
1306 global $hookmanager;
1307
1308 $error = 0;
1309
1310 $object = new Facture($this->db);
1311
1312 $this->db->begin();
1313
1314 $object->fetch($fromid);
1315 // fetch() clears $object->thirdparty, but the subsequent $object->create() path
1316 // reaches addLine() -> getLocalTaxesFromRate() -> get_localtax() and uses the
1317 // buyer thirdparty to decide whether IRPF/localtax2 applies. Without this fetch,
1318 // get_localtax() sees $thirdparty_buyer = null, returns 0 and the cloned lines
1319 // lose their localtax2_tx (see issue #29052).
1320 $object->fetch_thirdparty();
1321
1322 // Load source object
1323 $objFrom = clone $object;
1324
1325 // Change socid if needed
1326 if (!empty($this->socid) && $this->socid != $object->socid) {
1327 $objsoc = new Societe($this->db);
1328
1329 if ($objsoc->fetch($this->socid) > 0) {
1330 $object->socid = $objsoc->id;
1331 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1332 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1333 $object->fk_project = 0;
1334 $object->fk_delivery_address = 0;
1335 }
1336
1337 // TODO Change product price if multi-prices
1338 }
1339
1340 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1341
1342 $object->id = 0;
1343 $object->statut = self::STATUS_DRAFT;
1344 $object->status = self::STATUS_DRAFT;
1345
1346 // Clear fields
1347 $object->date = (empty($this->date) ? dol_now() : $this->date);
1348 $object->user_creation_id = $user->id;
1349 $object->user_validation_id = null;
1350 $object->user_modification_id = null;
1351 $object->fk_user_author = $user->id;
1352 $object->fk_user_valid = null;
1353 $object->fk_facture_source = 0;
1354 $object->fk_fac_rec_source = 0;
1355 $object->date_creation = '';
1356 $object->date_modification = '';
1357 $object->date_validation = '';
1358 $object->ref_client = '';
1359 $object->ref_customer = '';
1360 $object->close_code = '';
1361 $object->close_note = '';
1362 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1363 $object->note_private = '';
1364 $object->note_public = '';
1365 }
1366
1367 // Loop on each line of new invoice
1368 foreach ($object->lines as $i => $line) {
1369 '@phan-var-force FactureLigne $line';
1370 if (($line->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1371 unset($object->lines[$i]);
1372 continue;
1373 }
1374
1375 // Block to update dates of service (month by month only if previously filled and similar to start and end of month)
1376 // If it's a service with start and end dates
1377 if (getDolGlobalString('INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1378 // Get the dates
1379 $start = dol_getdate($line->date_start);
1380 $end = dol_getdate($line->date_end);
1381
1382 // Get the first and last day of the month
1383 $first = dol_get_first_day($start['year'], $start['mon']);
1384 $last = dol_get_last_day($end['year'], $end['mon']);
1385
1386 //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1387 //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1388 // If start date is first date of month and end date is last date of month
1389 if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1390 && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1391 $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1392 $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1393 $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1394 $object->lines[$i]->date_start = $newFirst;
1395 $object->lines[$i]->date_end = $newLast;
1396 }
1397 }
1398
1399 $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1400
1401 // Do not clone accountancy ventilation: a cloned invoice must reappear in "to dispatch" list
1402 $object->lines[$i]->fk_code_ventilation = 0;
1403 }
1404
1405 // Create clone
1406 $object->context['createfromclone'] = 'createfromclone';
1407 $result = $object->create($user);
1408
1409 if ($result < 0) {
1410 $error++;
1411 $this->setErrorsFromObject($object);
1412 } else {
1413 // copy internal contacts
1414 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1415 $error++;
1416 $this->setErrorsFromObject($object);
1417 } elseif ($object->socid == $objFrom->socid) {
1418 // copy external contacts if same company
1419 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1420 $error++;
1421 $this->setErrorsFromObject($object);
1422 }
1423 }
1424 }
1425
1426 if (!$error) {
1427 // Hook of thirdparty module
1428 if (is_object($hookmanager)) {
1429 $parameters = array('objFrom' => $objFrom, 'clonedObj' => $object);
1430 $action = '';
1431 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1432 if ($reshook < 0) {
1433 $this->setErrorsFromObject($hookmanager);
1434 $error++;
1435 }
1436 }
1437 }
1438
1439 unset($object->context['createfromclone']);
1440
1441 // End
1442 if (!$error) {
1443 $this->db->commit();
1444 return $object->id;
1445 } else {
1446 $this->db->rollback();
1447 return -1;
1448 }
1449 }
1450
1458 public function createFromOrder($object, User $user)
1459 {
1460 global $hookmanager;
1461
1462 $error = 0;
1463
1464 // Closed order
1465 $this->date = dol_now();
1466 $this->source = 0;
1467
1468 // Avoid updating the row ranks
1469 $this->context['createfromclone'] = 1;
1470
1471 $num = count($object->lines);
1472 for ($i = 0; $i < $num; $i++) {
1473 $line = new FactureLigne($this->db);
1474 $src_line = $object->lines[$i];
1475 '@phan-var-force FactureLigne $src_line';
1476 $line->libelle = $src_line->libelle; // deprecated
1477 $line->label = $src_line->label;
1478 $line->desc = $src_line->desc;
1479 $line->subprice = $src_line->subprice;
1480 $line->subprice_ttc = $src_line->subprice_ttc; // Preserve the TTC entry mode so create() keeps the typed value (no rounding drift).
1481 $line->total_ht = $src_line->total_ht;
1482 $line->total_tva = $src_line->total_tva;
1483 $line->total_localtax1 = $src_line->total_localtax1;
1484 $line->total_localtax2 = $src_line->total_localtax2;
1485 $line->total_ttc = $src_line->total_ttc;
1486 $line->vat_src_code = $src_line->vat_src_code;
1487 $line->tva_tx = $src_line->tva_tx;
1488 $line->localtax1_tx = $src_line->localtax1_tx;
1489 $line->localtax2_tx = $src_line->localtax2_tx;
1490 $line->qty = $src_line->qty;
1491 $line->fk_remise_except = $src_line->fk_remise_except;
1492 $line->remise_percent = $src_line->remise_percent;
1493 $line->fk_product = $src_line->fk_product;
1494 $line->info_bits = $src_line->info_bits;
1495 $line->product_type = $src_line->product_type;
1496 $line->rang = $src_line->rang;
1497 $line->special_code = $src_line->special_code;
1498 $line->fk_parent_line = $src_line->fk_parent_line;
1499 $line->fk_unit = $src_line->fk_unit;
1500 $line->date_start = $src_line->date_start;
1501 $line->date_end = $src_line->date_end;
1502
1503 // Multicurrency
1504 $line->fk_multicurrency = $src_line->fk_multicurrency;
1505 $line->multicurrency_code = $src_line->multicurrency_code;
1506 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1507 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1508 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1509 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1510
1511 $line->fk_fournprice = $src_line->fk_fournprice;
1512 $marginInfos = getMarginInfos($src_line->subprice, $src_line->remise_percent, $src_line->tva_tx, $src_line->localtax1_tx, $src_line->localtax2_tx, $src_line->fk_fournprice, $src_line->pa_ht);
1513 $line->pa_ht = $marginInfos[0];
1514
1515 // get extrafields from original line
1516 $src_line->fetch_optionals();
1517 foreach ($src_line->array_options as $options_key => $value) {
1518 $line->array_options[$options_key] = $value;
1519 }
1520
1521 $this->lines[$i] = $line;
1522 }
1523
1524 $this->socid = $object->socid;
1525 $this->fk_project = $object->fk_project;
1526 $this->fk_account = $object->fk_account;
1527 $this->cond_reglement_id = $object->cond_reglement_id;
1528 $this->mode_reglement_id = $object->mode_reglement_id;
1529 $this->fk_incoterms = $object->fk_incoterms;
1530 $this->location_incoterms = $object->location_incoterms;
1531 $this->availability_id = $object->availability_id;
1532 $this->demand_reason_id = $object->demand_reason_id;
1533 $this->delivery_date = $object->delivery_date;
1534 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1535 $this->contact_id = $object->contact_id;
1536 $this->ref_client = $object->ref_client;
1537 $this->ref_customer = $object->ref_client;
1538
1539 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1540 $this->note_private = $object->note_private;
1541 $this->note_public = $object->note_public;
1542 }
1543
1544 $this->module_source = $object->module_source;
1545 $this->pos_source = $object->pos_source;
1546
1547 $this->origin = $object->element;
1548 $this->origin_type = $object->element;
1549 $this->origin_id = $object->id;
1550
1551 $this->fk_user_author = $user->id;
1552 $this->user_creation_id = $user->id;
1553
1554 // get extrafields from original line
1555 $object->fetch_optionals();
1556 foreach ($object->array_options as $options_key => $value) {
1557 $this->array_options[$options_key] = $value;
1558 }
1559
1560 // Possibility to add external linked objects with hooks
1561 $this->linked_objects[$this->origin] = $this->origin_id;
1562 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1563 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1564 }
1565
1566 $ret = $this->create($user);
1567
1568 if ($ret > 0) {
1569 // Actions hooked (by external module)
1570 $hookmanager->initHooks(array('invoicedao'));
1571
1572 $parameters = array('objFrom' => $object);
1573 $action = '';
1574 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1575 if ($reshook < 0) {
1576 $this->setErrorsFromObject($hookmanager);
1577 $error++;
1578 }
1579 } else {
1580 $error++;
1581 }
1582
1583 unset($this->context['createfromclone']);
1584
1585 if (!$error) {
1586 return 1;
1587 } else {
1588 return -1;
1589 }
1590 }
1591
1600 public function createFromContract($object, User $user, $lines = array())
1601 {
1602 global $hookmanager;
1603
1604 $error = 0;
1605
1606 // Closed order
1607 $this->date = dol_now();
1608 $this->source = 0;
1609
1610 $use_all_lines = empty($lines);
1611 $num = count($object->lines);
1612 for ($i = 0; $i < $num; $i++) {
1613 if (!$use_all_lines && !in_array($object->lines[$i]->id, $lines)) {
1614 continue;
1615 }
1616
1617 $line = new FactureLigne($this->db);
1618
1619 $line->libelle = $object->lines[$i]->libelle; // deprecated
1620 $line->label = $object->lines[$i]->label;
1621 $line->desc = $object->lines[$i]->desc;
1622 $line->subprice = $object->lines[$i]->subprice;
1623 $line->subprice_ttc = $object->lines[$i]->subprice_ttc; // Preserve the TTC entry mode so create() keeps the typed value (no rounding drift).
1624 $line->total_ht = $object->lines[$i]->total_ht;
1625 $line->total_tva = $object->lines[$i]->total_tva;
1626 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1627 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1628 $line->total_ttc = $object->lines[$i]->total_ttc;
1629 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1630 $line->tva_tx = $object->lines[$i]->tva_tx;
1631 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1632 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1633 $line->qty = $object->lines[$i]->qty;
1634 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1635 $line->remise_percent = $object->lines[$i]->remise_percent;
1636 $line->fk_product = $object->lines[$i]->fk_product;
1637 $line->info_bits = $object->lines[$i]->info_bits;
1638 $line->product_type = $object->lines[$i]->product_type;
1639 $line->rang = $object->lines[$i]->rang;
1640 $line->special_code = $object->lines[$i]->special_code;
1641 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1642 $line->fk_unit = $object->lines[$i]->fk_unit;
1643 $line->date_start = $object->lines[$i]->date_start;
1644 $line->date_end = $object->lines[$i]->date_end;
1645
1646 // Multicurrency
1647 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1648 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1649 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1650 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1651 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1652 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1653
1654 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1655 $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1656 $line->pa_ht = $marginInfos[0];
1657
1658 // get extrafields from original line
1659 $object->lines[$i]->fetch_optionals();
1660 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1661 $line->array_options[$options_key] = $value;
1662 }
1663
1664 $this->lines[$i] = $line;
1665 }
1666
1667 $this->socid = $object->socid;
1668 $this->fk_project = $object->fk_project;
1669 $this->fk_account = $object->fk_account;
1670 $this->cond_reglement_id = $object->cond_reglement_id;
1671 $this->mode_reglement_id = $object->mode_reglement_id;
1672 //$this->availability_id = $object->availability_id;
1673 $this->demand_reason_id = $object->demand_reason_id;
1674 //$this->delivery_date = $object->delivery_date;
1675 $this->contact_id = $object->contact_id;
1676 $this->ref_customer = $object->ref_customer;
1677 $this->ref_client = $object->ref_customer;
1678
1679 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1680 $this->note_private = $object->note_private;
1681 $this->note_public = $object->note_public;
1682 }
1683
1684 //$this->module_source = $object->module_source;
1685 //$this->pos_source = $object->pos_source;
1686
1687 $this->origin = $object->element;
1688 $this->origin_id = $object->id;
1689
1690 $this->fk_user_author = $user->id;
1691 $this->user_creation_id = $user->id;
1692
1693 // get extrafields from original line
1694 $object->fetch_optionals();
1695 foreach ($object->array_options as $options_key => $value) {
1696 $this->array_options[$options_key] = $value;
1697 }
1698
1699 // Possibility to add external linked objects with hooks
1700 $this->linked_objects[$this->origin] = $this->origin_id;
1701 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1702 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1703 }
1704
1705 $ret = $this->create($user);
1706
1707 if ($ret > 0) {
1708 // Actions hooked (by external module)
1709 $hookmanager->initHooks(array('invoicedao'));
1710
1711 $parameters = array('objFrom' => $object);
1712 $action = '';
1713 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1714 if ($reshook < 0) {
1715 $this->setErrorsFromObject($hookmanager);
1716 $error++;
1717 }
1718
1719 if (!$error) {
1720 return 1;
1721 } else {
1722 return -1;
1723 }
1724 } else {
1725 return -1;
1726 }
1727 }
1728
1741 public static function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1742 {
1743 global $conf, $langs, $hookmanager, $action;
1744
1745 if (! in_array($origin->element, array('propal', 'commande'))) {
1746 $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1747 return null;
1748 }
1749
1750 if (empty($date)) {
1751 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1752 return null;
1753 }
1754
1755 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1756
1757 if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1758 $origin->error = 'ErrorDateIsInFuture';
1759 return null;
1760 }
1761
1762 if ($payment_terms_id <= 0) {
1763 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1764 return null;
1765 }
1766
1767 $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1768
1769 if (empty($payment_conditions_deposit_percent)) {
1770 $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1771 return null;
1772 }
1773
1774 if (empty($origin->deposit_percent)) {
1775 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1776 return null;
1777 }
1778
1779 $deposit = new self($origin->db);
1780 $deposit->socid = $origin->socid;
1781 $deposit->type = self::TYPE_DEPOSIT;
1782 $deposit->fk_project = $origin->fk_project;
1783 $deposit->ref_client = $origin->ref_client;
1784 $deposit->ref_customer = $origin->ref_client;
1785 $deposit->date = $date;
1786 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1787 $deposit->cond_reglement_id = $payment_terms_id;
1788 $deposit->availability_id = $origin->availability_id;
1789 $deposit->demand_reason_id = $origin->demand_reason_id;
1790 $deposit->fk_account = $origin->fk_account;
1791 $deposit->fk_incoterms = $origin->fk_incoterms;
1792 $deposit->location_incoterms = $origin->location_incoterms;
1793 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1794 $deposit->multicurrency_code = $origin->multicurrency_code;
1795 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1796 $deposit->module_source = $origin->module_source;
1797 $deposit->pos_source = $origin->pos_source;
1798 $deposit->model_pdf = 'sponge';
1799
1800 $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1801
1802 if (getDolGlobalString($modelByTypeConfName)) {
1803 $deposit->model_pdf = getDolGlobalString($modelByTypeConfName);
1804 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
1805 $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF');
1806 }
1807
1808 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1809 $deposit->note_private = $origin->note_private;
1810 $deposit->note_public = $origin->note_public;
1811 }
1812
1813 $deposit->origin = $origin->element;
1814 $deposit->origin_type = $origin->element;
1815 $deposit->origin_id = $origin->id;
1816
1817 $origin->fetch_optionals();
1818
1819 foreach ($origin->array_options as $extrakey => $value) {
1820 $deposit->array_options[$extrakey] = $value;
1821 }
1822
1823 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1824
1825 foreach ($overrideFields as $key => $value) {
1826 $deposit->$key = $value;
1827 }
1828
1829 $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1830
1831 $origin->db->begin();
1832
1833 // Facture::create() also imports contact from origin
1834 $createReturn = $deposit->create($user, $notrigger);
1835
1836 if ($createReturn <= 0) {
1837 $origin->db->rollback();
1838 $origin->error = $deposit->error;
1839 $origin->errors = $deposit->errors;
1840 return null;
1841 }
1842
1843 $amount_ttc_diff = 0;
1844 $amountdeposit = array();
1845 $descriptions = array();
1846
1847 // Bucket lines by tva_tx + vat_src_code so addline below receives the rate in
1848 // the "tva (CODE)" format that Facture::addline knows how to parse. Bucketing
1849 // on tva_tx alone wipes out the dictionary Code on the generated deposit line
1850 // and on every downstream document derived from it (see issue #38035).
1851 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1852 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1853
1854 $TTotalByTva = array();
1855 foreach ($origin->lines as &$line) {
1856 if (!empty($line->special_code)) {
1857 continue;
1858 }
1859 $key = $line->tva_tx . ($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
1860 if (!array_key_exists($key, $TTotalByTva)) {
1861 $TTotalByTva[$key] = 0;
1862 $descriptions[$key] = '';
1863 }
1864 $TTotalByTva[$key] += $line->total_ttc;
1865 $descriptions[$key] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1866 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1867 $descriptions[$key] .= $langs->trans('Qty') . ' : ' . $line->qty;
1868 $descriptions[$key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1869 }
1870
1871 foreach ($TTotalByTva as $tva => &$total) {
1872 $tva_rate_only = preg_replace('/\s*\‍(.*\‍)/', '', (string) $tva);
1873 $coef = $total / $origin->total_ttc; // Calc coef
1874 $am = $amount * $coef;
1875 $amount_ttc_diff += $am;
1876 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100); // Convert into HT for the addline
1877 }
1878 } else {
1879 $totalamount = 0;
1880 $lines = $origin->lines;
1881 $numlines = count($lines);
1882 for ($i = 0; $i < $numlines; $i++) {
1883 if (empty($lines[$i]->qty)) {
1884 continue; // We discard qty=0, it is an option
1885 }
1886 if (!empty($lines[$i]->special_code)) {
1887 continue; // We discard special_code (frais port, ecotaxe, option, ...)
1888 }
1889
1890 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1891 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ? ' ('.$lines[$i]->vat_src_code.')' : '');
1892 if (!isset($amountdeposit[$tva_key])) {
1893 $amountdeposit[$tva_key] = 0;
1894 $descriptions[$tva_key] = '';
1895 }
1896 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (float) $origin->deposit_percent) / 100;
1897 $descriptions[$tva_key] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1898 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1899 $descriptions[$tva_key] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1900 $descriptions[$tva_key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1901 }
1902
1903 if ($totalamount == 0) {
1904 $amountdeposit[0] = 0;
1905 }
1906
1907 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1908 }
1909
1910 foreach ($amountdeposit as $tva => $amount) {
1911 if (empty($amount)) {
1912 continue;
1913 }
1914
1915 $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1916
1917 // Hidden conf
1918 if (getDolGlobalString('INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1919 $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1920 }
1921
1922 $addlineResult = $deposit->addline(
1923 $descline,
1924 $amount, // subprice
1925 1, // quantity
1926 $tva, // vat rate
1927 0, // localtax1_tx
1928 0, // localtax2_tx
1929 (!getDolGlobalString('INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1930 0, // remise_percent
1931 0, // date_start
1932 0, // date_end
1933 0,
1934 0, // info_bits
1935 0,
1936 'HT',
1937 0,
1938 0, // product_type
1939 1,
1940 0, // special_code
1941 $deposit->origin,
1942 0,
1943 0,
1944 0,
1945 0
1946 //,$langs->trans('Deposit') //Deprecated
1947 );
1948
1949 if ($addlineResult < 0) {
1950 $origin->db->rollback();
1951 $origin->error = $deposit->error;
1952 $origin->errors = $deposit->errors;
1953 return null;
1954 }
1955 }
1956
1957 $diff = $deposit->total_ttc - $amount_ttc_diff;
1958
1959 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1960 $deposit->fetch_lines();
1961 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1962
1963 // Pass tva_tx in the "rate (CODE)" form so updateline preserves the vat_src_code
1964 // it received from addline; passing the bare rate would wipe the code.
1965 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ? ' ('.$deposit->lines[0]->vat_src_code.')' : '');
1966 $updatelineResult = $deposit->updateline(
1967 $deposit->lines[0]->id,
1968 $deposit->lines[0]->desc,
1969 $subprice_diff,
1970 $deposit->lines[0]->qty,
1971 $deposit->lines[0]->remise_percent,
1972 $deposit->lines[0]->date_start,
1973 $deposit->lines[0]->date_end,
1974 $tva_tx_with_code,
1975 0,
1976 0,
1977 'HT',
1978 $deposit->lines[0]->info_bits,
1979 $deposit->lines[0]->product_type,
1980 0,
1981 0,
1982 0,
1983 $deposit->lines[0]->pa_ht,
1984 $deposit->lines[0]->label,
1985 0,
1986 array(),
1987 100
1988 );
1989
1990 if ($updatelineResult < 0) {
1991 $origin->db->rollback();
1992 $origin->error = $deposit->error;
1993 $origin->errors = $deposit->errors;
1994 return null;
1995 }
1996 }
1997
1998 $hookmanager->initHooks(array('invoicedao'));
1999
2000 $parameters = array('objFrom' => $origin);
2001 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
2002 // modified by hook
2003 if ($reshook < 0) {
2004 $origin->db->rollback();
2005 $origin->error = $hookmanager->error;
2006 $origin->errors = $hookmanager->errors;
2007 return null;
2008 }
2009
2010 if (!empty($autoValidateDeposit)) {
2011 $validateReturn = $deposit->validate($user, '', 0, $notrigger);
2012
2013 if ($validateReturn < 0) {
2014 $origin->db->rollback();
2015 $origin->error = $deposit->error;
2016 $origin->errors = $deposit->errors;
2017 return null;
2018 }
2019 }
2020
2021 unset($deposit->context['createdepositfromorigin']);
2022
2023 $origin->db->commit();
2024
2025 return $deposit;
2026 }
2027
2035 public function getTooltipContentArray($params)
2036 {
2037 global $conf, $langs, $mysoc, $user;
2038
2039 $langs->load('bills');
2040
2041 $datas = [];
2042 $moretitle = $params['moretitle'] ?? '';
2043
2044 $picto = $this->picto;
2045 if ($this->type == self::TYPE_REPLACEMENT) {
2046 $picto .= 'r'; // Replacement invoice
2047 }
2048 if ($this->type == self::TYPE_CREDIT_NOTE) {
2049 $picto .= 'a'; // Credit note
2050 }
2051 if ($this->type == self::TYPE_DEPOSIT) {
2052 $picto .= 'd'; // Deposit invoice
2053 }
2054
2055 if ($user->hasRight("facture", "read")) {
2056 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
2057
2058 $datas['picto'] .= '&nbsp;'.$this->getLibType(1);
2059
2060 // Complete datas
2061 if (!empty($params['fromajaxtooltip']) && !isset($this->totalpaid)) {
2062 $this->totalpaid = $this->getSommePaiement(0);
2063 }
2064 if (!empty($params['fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2065 $this->totalcreditnotes = $this->getSumCreditNotesUsed(0);
2066 }
2067 if (!empty($params['fromajaxtooltip']) && !isset($this->totaldeposits)) {
2068 $this->totaldeposits = $this->getSumDepositsUsed(0);
2069 }
2070 if (isset($this->status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2071 $datas['picto'] .= ' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2072 }
2073 if ($moretitle) {
2074 $datas['picto'] .= ' - '.$moretitle;
2075 }
2076 if (!empty($this->ref)) {
2077 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2078 }
2079 if (!empty($this->ref_customer)) {
2080 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
2081 }
2082 if (!empty($this->date)) {
2083 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
2084 }
2085 if (!empty($this->total_ht)) {
2086 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2087 }
2088 if (!empty($this->total_tva)) {
2089 $datas['amountvat'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2090 }
2091 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2092 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2093 }
2094 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2095 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
2096 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2097 }
2098 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2099 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2100 }
2101 if (!empty($this->total_ttc)) {
2102 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2103 }
2104 }
2105
2106 return $datas;
2107 }
2108
2123 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
2124 {
2125 global $langs, $conf, $user;
2126
2127 if (!empty($conf->dol_no_mouse_hover)) {
2128 $notooltip = 1; // Force disable tooltips
2129 }
2130
2131 $result = '';
2132
2133 if ($option == 'withdraw') {
2134 $baseurl = DOL_URL_ROOT.'/compta/facture/prelevement.php';
2135 $query = ['facid' => $this->id];
2136 } else {
2137 $baseurl = DOL_URL_ROOT.'/compta/facture/card.php';
2138 $query = ['id' => $this->id];
2139 }
2140
2141 if (!$user->hasRight("facture", "read")) {
2142 $option = 'nolink';
2143 }
2144
2145 if ($option !== 'nolink') {
2146 // Add param to save lastsearch_values or not
2147 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2148 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2149 $add_save_lastsearch_values = 1;
2150 }
2151 if ($add_save_lastsearch_values) {
2152 $query = array_merge($query, ['save_lastsearch_values' => 1]);
2153 }
2154 }
2155 $url = dolBuildUrl($baseurl, $query);
2156
2157 if ($short) {
2158 return $url;
2159 }
2160
2161 $picto = $this->picto;
2162 if ($this->type == self::TYPE_REPLACEMENT) {
2163 $picto .= 'r'; // Replacement invoice
2164 }
2165 if ($this->type == self::TYPE_CREDIT_NOTE) {
2166 $picto .= 'a'; // Credit note
2167 }
2168 if ($this->type == self::TYPE_DEPOSIT) {
2169 $picto .= 'd'; // Deposit invoice
2170 }
2171
2172 $params = [
2173 'id' => $this->id,
2174 'objecttype' => $this->element,
2175 'moretitle' => $moretitle,
2176 'option' => $option,
2177 ];
2178 $classfortooltip = 'classfortooltip';
2179 $dataparams = '';
2180 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2181 $classfortooltip = 'classforajaxtooltip';
2182 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2183 $label = '';
2184 } else {
2185 $label = implode($this->getTooltipContentArray($params));
2186 }
2187
2188 $linkclose = ($target ? ' target="'.$target.'"' : '');
2189 if (empty($notooltip) && $user->hasRight("facture", "read")) {
2190 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2191 $label = $langs->trans("Invoice");
2192 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2193 }
2194 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2195 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2196 }
2197
2198 $linkstart = '<a href="'.$url.'"';
2199 $linkstart .= $linkclose.'>';
2200 $linkend = '</a>';
2201
2202 if ($option == 'nolink') {
2203 $linkstart = '';
2204 $linkend = '';
2205 }
2206
2207 $result .= $linkstart;
2208 if ($withpicto) {
2209 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2210 }
2211 if ($withpicto != 2) {
2212 $result .= ($max ? dol_trunc($this->ref, $max) : $this->ref);
2213 }
2214 $result .= $linkend;
2215
2216 if ($addlinktonotes) {
2217 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2218 if ($txttoshow) {
2219 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
2220 $result .= ' <span class="note inline-block">';
2221 $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dolPrintHTMLForAttribute($notetoshow).'">';
2222 $result .= img_picto('', 'note');
2223 $result .= '</a>';
2224 $result .= '</span>';
2225 }
2226 }
2227
2228 global $action, $hookmanager;
2229 $hookmanager->initHooks(array('invoicedao'));
2230 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value' => $save_lastsearch_value, 'target' => $target);
2231 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2232 if ($reshook > 0) {
2233 $result = $hookmanager->resPrint;
2234 } else {
2235 $result .= $hookmanager->resPrint;
2236 }
2237
2238 return $result;
2239 }
2240
2251 public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false)
2252 {
2253 global $conf, $extrafields;
2254
2255 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2256 return -1;
2257 }
2258
2259 $extraFieldsCheck = false;
2260 $doFetchInOneSqlRequest = getDolGlobalInt('MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2261
2262 if ($doFetchInOneSqlRequest) {
2263 // If $extrafields is not a known object, we initialize it
2264 if (!isset($extrafields) || !is_object($extrafields)) {
2265 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2266 $extrafields = new ExtraFields($this->db);
2267 }
2268
2269 // Load array of extrafields for elementype = $this->table_element
2270 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
2271 $extrafields->fetch_name_optionals_label($this->table_element);
2272 }
2273
2274 $extraFieldsCheck = (
2275 !empty($extrafields->attributes[$this->table_element]['label'])
2276 && is_array($extrafields->attributes[$this->table_element]['label'])
2277 && count($extrafields->attributes[$this->table_element]['label']) > 0
2278 );
2279 }
2280
2281
2282 // Original SQL query from fetch()
2283 $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2284 $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2285 $sql .= ', f.datef as df, f.date_pointoftax';
2286 $sql .= ', f.date_lim_reglement as dlr';
2287 $sql .= ', f.datec as datec';
2288 $sql .= ', f.date_valid as datev';
2289 $sql .= ', f.tms as datem';
2290 $sql .= ', f.note_private, f.note_public, f.fk_statut as status, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.fk_user_modif, f.model_pdf, f.last_main_doc';
2291 $sql .= ", f.fk_input_reason";
2292 $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
2293 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2294 $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2295 $sql .= ', f.fk_account';
2296 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2297 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2298 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2299 $sql .= ', f.fk_incoterms, f.location_incoterms';
2300 $sql .= ', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2301 $sql .= ", i.libelle as label_incoterms";
2302 $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement";
2303 $sql .= ", f.payment_reference, f.dispute_status";
2304
2305 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2306 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2307 $type = !empty($extrafields->attributes[$this->table_element]['type'][$key])
2308 ? $extrafields->attributes[$this->table_element]['type'][$key]
2309 : '';
2310
2311 if ($type !== 'separate') {
2312 if (in_array($type, array('point','multipts','linestrg','polygon'))) {
2313 $sql .= ", ST_AsWKT(ef.".$this->db->sanitize($key).") as ".$this->db->sanitize($key);
2314 } else {
2315 $sql .= ", ef.".$this->db->sanitize($key);
2316 }
2317 }
2318 }
2319 }
2320
2321 $sql .= ' FROM '.$this->db->prefix().'facture as f';
2322
2323 // Add extrafields table to the join if we have extrafields for this entity
2324 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2325 // Add LEFT JOIN for extrafields
2326 $sql .= ' LEFT JOIN '.$this->db->prefix().$this->table_element.'_extrafields as ef ON f.rowid = ef.fk_object';
2327 }
2328
2329 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2330 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_paiement as p ON f.fk_mode_reglement = p.id';
2331 $sql .= " LEFT JOIN ".$this->db->prefix()."c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2332 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_incoterms as i ON f.fk_incoterms = i.rowid';
2333
2334 if ($rowid) {
2335 $sql .= " WHERE f.rowid = ".((int) $rowid);
2336 } else {
2337 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
2338 if ($ref) {
2339 $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
2340 }
2341 if ($ref_ext) {
2342 $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
2343 }
2344 }
2345
2346 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2347 $resql = $this->db->query($sql);
2348 if ($resql) {
2349 if ($this->db->num_rows($resql)) {
2350 $obj = $this->db->fetch_object($resql);
2351
2352 $this->id = $obj->rowid;
2353 $this->entity = $obj->entity;
2354
2355 $this->ref = $obj->ref;
2356 $this->ref_client = $obj->ref_client;
2357 $this->ref_customer = $obj->ref_client;
2358 $this->ref_ext = $obj->ref_ext;
2359 $this->type = $obj->type;
2360 $this->subtype = $obj->subtype;
2361 $this->date = $this->db->jdate($obj->df);
2362 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2363 $this->date_creation = $this->db->jdate($obj->datec);
2364 $this->date_validation = $this->db->jdate($obj->datev);
2365 $this->date_modification = $this->db->jdate($obj->datem);
2366 $this->datem = $this->db->jdate($obj->datem);
2367 $this->total_ht = $obj->total_ht;
2368 $this->total_tva = $obj->total_tva;
2369 $this->total_localtax1 = $obj->localtax1;
2370 $this->total_localtax2 = $obj->localtax2;
2371 $this->total_ttc = $obj->total_ttc;
2372 $this->revenuestamp = $obj->revenuestamp;
2373 $this->paye = $obj->paye;
2374 $this->close_code = $obj->close_code;
2375 $this->close_note = $obj->close_note;
2376
2377 $this->socid = $obj->fk_soc;
2378 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2379
2380 $this->fk_project = $obj->fk_project;
2381 $this->project = null; // Clear if another value was already set by fetch_projet
2382
2383 $this->statut = $obj->status; // deprecated
2384 $this->status = $obj->status;
2385
2386 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2387 $this->mode_reglement_id = $obj->fk_mode_reglement;
2388 $this->mode_reglement_code = $obj->mode_reglement_code;
2389 $this->mode_reglement = $obj->mode_reglement_libelle;
2390 $this->cond_reglement_id = $obj->fk_cond_reglement;
2391 $this->cond_reglement_code = $obj->cond_reglement_code;
2392 $this->cond_reglement = $obj->cond_reglement_libelle;
2393 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2394 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2395 $this->fk_facture_source = $obj->fk_facture_source;
2396 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2397 $this->note = $obj->note_private; // deprecated
2398 $this->note_private = $obj->note_private;
2399 $this->note_public = $obj->note_public;
2400 $this->user_creation_id = $obj->fk_user_author;
2401 $this->user_validation_id = $obj->fk_user_valid;
2402 $this->user_modification_id = $obj->fk_user_modif;
2403 $this->fk_user_author = $obj->fk_user_author;
2404 $this->fk_user_valid = $obj->fk_user_valid;
2405 $this->fk_user_modif = $obj->fk_user_modif;
2406 $this->model_pdf = $obj->model_pdf;
2407 $this->last_main_doc = $obj->last_main_doc;
2408 $this->demand_reason_id = $obj->fk_input_reason;
2409 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2410 $this->situation_counter = $obj->situation_counter;
2411 $this->situation_final = $obj->situation_final;
2412 $this->retained_warranty = $obj->retained_warranty;
2413 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2414 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2415
2416 $this->payment_reference = $obj->payment_reference;
2417 $this->dispute_status = $obj->dispute_status;
2418
2419 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2420
2421 //Incoterms
2422 $this->fk_incoterms = $obj->fk_incoterms;
2423 $this->location_incoterms = $obj->location_incoterms;
2424 $this->label_incoterms = $obj->label_incoterms;
2425
2426 $this->module_source = $obj->module_source;
2427 $this->pos_source = $obj->pos_source;
2428 $this->pos_print_counter = (int) $obj->pos_print_counter;
2429 $this->email_sent_counter = $obj->email_sent_counter;
2430
2431 // Multicurrency
2432 $this->fk_multicurrency = $obj->fk_multicurrency;
2433 $this->multicurrency_code = $obj->multicurrency_code;
2434 $this->multicurrency_tx = $obj->multicurrency_tx;
2435 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2436 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2437 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2438
2439 // Now process extrafields
2440 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2441 $this->array_options = array();
2442
2443 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2444 $type = !empty($extrafields->attributes[$this->table_element]['type'][$key])
2445 ? $extrafields->attributes[$this->table_element]['type'][$key]
2446 : '';
2447
2448 if ($type !== 'separate') {
2449 $rawval = $obj->$key;
2450
2451 // date/datetime
2452 if (in_array($type, array('date', 'datetime'))) {
2453 $this->array_options['options_' . $key] = $this->db->jdate($rawval);
2454 } elseif ($type == 'password') {
2455 if (!empty($rawval) && preg_match('/^dolcrypt:/', $rawval)) {
2456 $this->array_options['options_' . $key] = dolDecrypt($rawval);
2457 } else {
2458 $this->array_options['options_' . $key] = $rawval;
2459 }
2460 } else {
2461 $this->array_options['options_' . $key] = $rawval;
2462 }
2463 }
2464 }
2465
2466 // Champs "computed"
2467 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2468 if (!empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
2469 if (empty($conf->disable_compute)) {
2470 global $objectoffield;
2471 $objectoffield = $this;
2472 $this->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
2473 }
2474 }
2475 }
2476 }
2477
2478 if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2480 }
2481
2482 if (!$doFetchInOneSqlRequest) {
2483 // Retrieve all extrafield
2484 // fetch optionals attributes and labels
2485 $this->fetch_optionals();
2486 }
2487
2488 // Lines
2489 $this->lines = array();
2490
2491 $result = $this->fetch_lines();
2492 if ($result < 0) {
2493 $this->error = $this->db->error();
2494 return -3;
2495 }
2496
2497 $this->db->free($resql);
2498
2499 return 1;
2500 } else {
2501 $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2502
2503 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2504 return 0;
2505 }
2506 } else {
2507 $this->error = $this->db->lasterror();
2508 return -1;
2509 }
2510 }
2511
2512
2513 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2521 public function fetch_lines($only_type_product = '', $loadalsotranslation = 0)
2522 {
2523 global $conf, $extrafields;
2524
2525 // phpcs:enable
2526 $this->lines = array();
2527
2528 $extraFieldsCheck = false;
2529 $doFetchInOneSqlRequest = getDolGlobalInt('MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2530
2531 if ($doFetchInOneSqlRequest) {
2532 // If $extrafields is not a known object, we initialize it
2533 if (!isset($extrafields) || !is_object($extrafields)) {
2534 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2535 $extrafields = new ExtraFields($this->db);
2536 }
2537
2538 // Load array of extrafields for elementype = $this->table_element_line
2539 if (empty($extrafields->attributes[$this->table_element_line]['loaded'])) {
2540 $extrafields->fetch_name_optionals_label($this->table_element_line);
2541 }
2542
2543 $extraFieldsCheck = (
2544 !empty($extrafields->attributes[$this->table_element_line]['label'])
2545 && is_array($extrafields->attributes[$this->table_element_line]['label'])
2546 && count($extrafields->attributes[$this->table_element_line]['label']) > 0
2547 );
2548 }
2549
2550 $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
2551 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.subprice_ttc, l.ref_ext,';
2552 $sql .= ' l.situation_percent, l.fk_prev_id,';
2553 $sql .= ' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2554 $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2555 $sql .= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
2556 $sql .= ' l.fk_unit, l.extraparams,';
2557 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2558 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc, p.barcode as product_barcode';
2559
2560 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2561 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2562 $type = !empty($extrafields->attributes[$this->table_element_line]['type'][$key])
2563 ? $extrafields->attributes[$this->table_element_line]['type'][$key]
2564 : '';
2565
2566 if ($type !== 'separate') {
2567 if (in_array($type, array('point','multipts','linestrg','polygon'))) {
2568 $sql .= ", ST_AsWKT(ef.".$this->db->sanitize($key).") as ".$this->db->sanitize($key);
2569 } else {
2570 $sql .= ", ef.".$this->db->sanitize($key);
2571 }
2572 }
2573 }
2574 }
2575
2576 $sql .= ' FROM '.$this->db->prefix().'facturedet as l';
2577
2578 // Add extrafields table to the join if we have extrafields for this entity
2579 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2580 // Add LEFT JOIN for extrafields
2581 $sql .= ' LEFT JOIN '.$this->db->prefix().$this->table_element_line.'_extrafields as ef ON l.rowid = ef.fk_object';
2582 }
2583
2584 $sql .= ' LEFT JOIN '.$this->db->prefix().'product as p ON l.fk_product = p.rowid';
2585 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2586 if (is_int($only_type_product)) {
2587 $sql .= " AND p.fk_product_type = ".((int) $only_type_product);
2588 }
2589 $sql .= ' ORDER BY l.rang, l.rowid';
2590
2591 dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2592 $result = $this->db->query($sql);
2593 if ($result) {
2594 $num = $this->db->num_rows($result);
2595 $i = 0;
2596 while ($i < $num) {
2597 $objp = $this->db->fetch_object($result);
2598 $line = new FactureLigne($this->db);
2599
2600 $line->id = $objp->rowid;
2601 $line->rowid = $objp->rowid; // deprecated
2602 $line->fk_facture = $objp->fk_facture;
2603 $line->label = $objp->custom_label; // deprecated
2604 $line->desc = $objp->description; // Description line
2605 $line->description = $objp->description; // Description line
2606 $line->product_type = $objp->product_type; // Type of line
2607 $line->ref = $objp->product_ref; // Ref product
2608 $line->product_ref = $objp->product_ref; // Ref product
2609 $line->libelle = $objp->product_label; // deprecated
2610 $line->product_label = $objp->product_label; // Label product
2611 $line->product_barcode = $objp->product_barcode; // Barcode number product
2612 $line->product_desc = $objp->product_desc; // Description product
2613 $line->fk_product_type = $objp->fk_product_type; // Type of product
2614 $line->qty = $objp->qty;
2615 $line->subprice = $objp->subprice;
2616 $line->subprice_ttc = $objp->subprice_ttc;
2617 $line->ref_ext = $objp->ref_ext; // line external ref
2618
2619 $line->vat_src_code = $objp->vat_src_code;
2620 $line->tva_tx = $objp->tva_tx;
2621 $line->localtax1_tx = $objp->localtax1_tx;
2622 $line->localtax2_tx = $objp->localtax2_tx;
2623 $line->localtax1_type = $objp->localtax1_type;
2624 $line->localtax2_type = $objp->localtax2_type;
2625 $line->remise_percent = $objp->remise_percent;
2626 $line->fk_remise_except = $objp->fk_remise_except;
2627 $line->fk_product = $objp->fk_product;
2628 $line->date_start = $this->db->jdate($objp->date_start);
2629 $line->date_end = $this->db->jdate($objp->date_end);
2630 $line->info_bits = $objp->info_bits;
2631 $line->total_ht = $objp->total_ht;
2632 $line->total_tva = $objp->total_tva;
2633 $line->total_localtax1 = $objp->total_localtax1;
2634 $line->total_localtax2 = $objp->total_localtax2;
2635 $line->total_ttc = $objp->total_ttc;
2636
2637 $line->fk_fournprice = $objp->fk_fournprice;
2638 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2639 $line->pa_ht = $marginInfos[0];
2640 $line->marge_tx = (string) $marginInfos[1];
2641 $line->marque_tx = (string) $marginInfos[2];
2642 $line->rang = $objp->rang;
2643 $line->special_code = $objp->special_code;
2644 $line->fk_parent_line = $objp->fk_parent_line;
2645 $line->situation_percent = $objp->situation_percent;
2646 $line->fk_prev_id = $objp->fk_prev_id;
2647 $line->fk_unit = $objp->fk_unit;
2648
2649 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2650
2651 $line->batch = $objp->batch;
2652 $line->fk_warehouse = $objp->fk_warehouse;
2653
2654 // Accountancy
2655 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2656
2657 // Multicurrency
2658 $line->fk_multicurrency = $objp->fk_multicurrency;
2659 $line->multicurrency_code = $objp->multicurrency_code;
2660 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2661 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2662 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2663 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2664
2665 $line->array_options = array();
2666 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2667 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2668 $type = !empty($extrafields->attributes[$this->table_element_line]['type'][$key])
2669 ? $extrafields->attributes[$this->table_element_line]['type'][$key]
2670 : '';
2671
2672 if ($type !== 'separate') {
2673 $rawval = $objp->$key;
2674
2675 // date/datetime
2676 if (in_array($type, array('date', 'datetime'))) {
2677 $line->array_options['options_' . $key] = $this->db->jdate($rawval);
2678 } elseif ($type == 'password') {
2679 if (!empty($rawval) && preg_match('/^dolcrypt:/', $rawval)) {
2680 $line->array_options['options_' . $key] = dolDecrypt($rawval);
2681 } else {
2682 $line->array_options['options_' . $key] = $rawval;
2683 }
2684 } else {
2685 $line->array_options['options_' . $key] = $rawval;
2686 }
2687 }
2688 }
2689
2690 // Champs "computed"
2691 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2692 if (!empty($extrafields->attributes[$this->table_element_line]['computed'][$key])) {
2693 if (empty($conf->disable_compute)) {
2694 global $objectoffield;
2695 $objectoffield = $line;
2696 $line->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element_line]['computed'][$key], 1, 0, '2');
2697 }
2698 }
2699 }
2700 }
2701
2702 if (!$doFetchInOneSqlRequest) {
2703 // Retrieve all extrafield
2704 $line->fetch_optionals();
2705 }
2706
2707 // multilangs
2708 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2709 $tmpproduct = new Product($this->db);
2710 $tmpproduct->fetch($objp->fk_product);
2711 $tmpproduct->getMultiLangs();
2712
2713 $line->multilangs = $tmpproduct->multilangs;
2714 }
2715
2716 $this->lines[$i] = $line;
2717
2718 $i++;
2719 }
2720 $this->db->free($result);
2721 return 1;
2722 } else {
2723 $this->error = $this->db->error();
2724 return -3;
2725 }
2726 }
2727
2735 {
2736 $this->tab_previous_situation_invoice = array();
2737 $this->tab_next_situation_invoice = array();
2738
2739 $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2740 $sql .= " WHERE rowid <> ".((int) $this->id);
2741 $sql .= ' AND entity = '.((int) $this->entity);
2742 $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2743 $sql .= ' ORDER BY situation_counter ASC';
2744
2745 dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2746 $result = $this->db->query($sql);
2747 if ($result && $this->db->num_rows($result) > 0) {
2748 while ($objp = $this->db->fetch_object($result)) {
2749 $invoice = new Facture($this->db);
2750 if ($invoice->fetch($objp->rowid) > 0) {
2751 if ($objp->situation_counter < $this->situation_counter
2752 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2753 ) {
2754 $this->tab_previous_situation_invoice[] = $invoice;
2755 } else {
2756 $this->tab_next_situation_invoice[] = $invoice;
2757 }
2758 }
2759 }
2760 }
2761 }
2762
2770 public function update(User $user, $notrigger = 0)
2771 {
2772 $error = 0;
2773
2774 $this->oldcopy = dol_clone($this, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
2775
2776 // Clean parameters
2777 if (empty($this->type)) {
2778 $this->type = self::TYPE_STANDARD;
2779 }
2780 if (isset($this->subtype)) {
2781 $this->subtype = (int) $this->subtype;
2782 }
2783 if (isset($this->ref)) {
2784 $this->ref = trim($this->ref);
2785 }
2786 if (isset($this->ref_ext)) {
2787 $this->ref_ext = trim($this->ref_ext);
2788 }
2789 if (!empty($this->ref_customer)) {
2790 $this->ref_customer = trim($this->ref_customer);
2791 }
2792 if (isset($this->increment)) {
2793 $this->increment = trim($this->increment);
2794 }
2795 if (isset($this->close_code)) {
2796 $this->close_code = trim($this->close_code);
2797 }
2798 if (isset($this->close_note)) {
2799 $this->close_note = trim($this->close_note);
2800 }
2801 if (isset($this->note) || isset($this->note_private)) {
2802 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2803 }
2804 if (isset($this->note) || isset($this->note_private)) {
2805 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2806 }
2807 if (isset($this->note_public)) {
2808 $this->note_public = trim($this->note_public);
2809 }
2810 if (isset($this->model_pdf)) {
2811 $this->model_pdf = trim($this->model_pdf);
2812 }
2813 if (isset($this->import_key)) {
2814 $this->import_key = trim($this->import_key);
2815 }
2816 if (isset($this->retained_warranty)) {
2817 $this->retained_warranty = (float) $this->retained_warranty;
2818 }
2819 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2820 $this->user_creation_id = $this->fk_user_author;
2821 }
2822 if (!isset($this->user_modification_id) && !empty($user->id)) {
2823 $this->user_modification_id = $user->id;
2824 }
2825 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2826 $this->user_validation_id = $this->fk_user_valid;
2827 }
2828
2829 // Update request
2830 // TODO Use the invoice->update() method.
2831 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2832 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2833 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2834 $sql .= " type=".(isset($this->type) ? ((int) $this->type) : "null").",";
2835 $sql .= " subtype=".(isset($this->subtype) ? (int) $this->subtype : "null").",";
2836 $sql .= " ref_client=".(!empty($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : (isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null")).",";
2837 $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2838 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
2839 $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2840 $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2841 $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2842 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2843 $sql .= " paye=".(isset($this->paye) ? ((int) $this->paye) : 0).",";
2844 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2845 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2846 $sql .= " total_tva=".((float) $this->total_tva).",";
2847 $sql .= " localtax1=".((float) $this->total_localtax1).",";
2848 $sql .= " localtax2=".((float) $this->total_localtax2).",";
2849 $sql .= " total_ht=".((float) $this->total_ht).",";
2850 $sql .= " total_ttc=".((float) $this->total_ttc).",";
2851 $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? (float) $this->revenuestamp : "null").",";
2852 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
2853 $sql .= " fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) : "null").",";
2854 $sql .= " fk_user_modif=".(!empty($user->id) ? ((int) $user->id) : "null").",";
2855 $sql .= " fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
2856 $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source : "null").",";
2857 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
2858 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
2859 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
2860 $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2861 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2862 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2863 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2864 $sql .= " import_key = ".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2865 $sql .= " module_source = ".(isset($this->module_source) ? "'".$this->db->escape($this->module_source)."'" : "null").",";
2866 $sql .= " pos_source = ".(isset($this->pos_source) ? "'".$this->db->escape($this->pos_source)."'" : "null").",";
2867 $sql .= " pos_print_counter = ".(int) $this->pos_print_counter.",";
2868 $sql .= " situation_cycle_ref = ".(empty($this->situation_cycle_ref) ? "null" : (int) $this->situation_cycle_ref).",";
2869 $sql .= " situation_counter = ".(empty($this->situation_counter) ? "null" : (int) $this->situation_counter).",";
2870 $sql .= " situation_final = ".(empty($this->situation_final) ? "0" : (int) $this->situation_final).",";
2871 $sql .= " retained_warranty = ".(empty($this->retained_warranty) ? "0" : (float) $this->retained_warranty).",";
2872 $sql .= " retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2873 $sql .= " retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement : "null");
2874 $sql .= " WHERE rowid = ".((int) $this->id);
2875
2876 $this->db->begin();
2877
2878 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2879 $resql = $this->db->query($sql);
2880 if (!$resql) {
2881 $error++;
2882 $this->errors[] = "Error ".$this->db->lasterror();
2883 }
2884
2885 if (!$error) {
2886 $result = $this->insertExtraFields();
2887 if ($result < 0) {
2888 $error++;
2889 }
2890 }
2891
2892 if (!$error && !$notrigger) {
2893 // Call trigger
2894 $result = $this->call_trigger('BILL_MODIFY', $user);
2895 if ($result < 0) {
2896 $error++;
2897 }
2898 // End call triggers
2899 }
2900
2901 // Commit or rollback
2902 if ($error) {
2903 foreach ($this->errors as $errmsg) {
2904 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2905 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2906 }
2907 $this->db->rollback();
2908 return -1 * $error;
2909 } else {
2910 $this->db->commit();
2911 return 1;
2912 }
2913 }
2914
2915
2916 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2923 public function insert_discount($idremise)
2924 {
2925 // phpcs:enable
2926 global $langs;
2927
2928 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2929 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2930
2931 $this->db->begin();
2932
2933 $remise = new DiscountAbsolute($this->db);
2934 $result = $remise->fetch($idremise);
2935
2936 if ($result > 0) {
2937 if ($this->socid > 0 && $remise->fk_soc != $this->socid) { // The discount must belong to the thirdparty of the invoice
2938 $this->error = $langs->trans("ErrorDiscountNotSameCompany");
2939 $this->db->rollback();
2940 return -6;
2941 }
2942 if ($remise->fk_facture) { // Protection against multiple submission
2943 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2944 $this->db->rollback();
2945 return -5;
2946 }
2947
2948 $facligne = new FactureLigne($this->db);
2949 $facligne->fk_facture = $this->id;
2950 $facligne->fk_remise_except = $remise->id;
2951 $facligne->desc = $remise->description; // Description of the invoice line
2952 $facligne->vat_src_code = $remise->vat_src_code;
2953 $facligne->tva_tx = $remise->tva_tx;
2954 $facligne->localtax1_tx = $remise->localtax1_tx;
2955 $facligne->localtax1_type = (int) $remise->localtax1_type;
2956 $facligne->localtax2_tx = $remise->localtax2_tx;
2957 $facligne->localtax2_type = (int) $remise->localtax2_type;
2958 $facligne->subprice = -(float) $remise->total_ht;
2959 $facligne->fk_product = 0; // Predefined Product ID
2960 $facligne->qty = 1;
2961 $facligne->remise_percent = 0;
2962 $facligne->rang = -1;
2963 $facligne->info_bits = 2;
2964
2965 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
2966 $facligne->rang = 1;
2967 $linecount = count($this->lines);
2968 for ($ii = 1; $ii <= $linecount; $ii++) {
2969 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2970 }
2971 }
2972
2973 // Get buy/cost price of invoice that is source of discount
2974 if ($remise->fk_facture_source > 0) {
2975 $srcinvoice = new Facture($this->db);
2976 $srcinvoice->fetch($remise->fk_facture_source);
2977 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2978 $formmargin = new FormMargin($this->db);
2979 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2980 $facligne->pa_ht = $arraytmp['pa_total'];
2981 }
2982
2983 $facligne->total_ht = -(float) $remise->total_ht;
2984 $facligne->total_tva = -(float) $remise->total_tva;
2985 $facligne->total_ttc = -(float) $remise->total_ttc;
2986 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
2987 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
2988
2989 // The discount line must carry the currency of the invoice, like any other line
2990 $facligne->fk_multicurrency = $this->fk_multicurrency;
2991 $facligne->multicurrency_code = $this->multicurrency_code;
2992 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2993 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
2994 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
2995 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
2996
2997 $lineid = $facligne->insert();
2998 if ($lineid > 0) {
2999 $result = $this->update_price(1);
3000 if ($result > 0) {
3001 // Create link between discount and invoice line
3002 $result = $remise->link_to_invoice($lineid, 0);
3003 if ($result < 0) {
3004 $this->error = $remise->error;
3005 $this->db->rollback();
3006 return -4;
3007 }
3008
3009 $this->db->commit();
3010 return 1;
3011 } else {
3012 $this->error = $facligne->error;
3013 $this->db->rollback();
3014 return -1;
3015 }
3016 } else {
3017 $this->error = $facligne->error;
3018 $this->db->rollback();
3019 return -2;
3020 }
3021 } else {
3022 $this->db->rollback();
3023 return -3;
3024 }
3025 }
3026
3027 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3035 public function set_ref_client($ref_client, $notrigger = 0)
3036 {
3037 // phpcs:enable
3038 global $user;
3039
3040 $error = 0;
3041
3042 $this->db->begin();
3043
3044 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3045 if (empty($ref_client)) {
3046 $sql .= " SET ref_client = NULL";
3047 } else {
3048 $sql .= " SET ref_client = '".$this->db->escape($ref_client)."'";
3049 }
3050 $sql .= " WHERE rowid = ".((int) $this->id);
3051
3052 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
3053 $resql = $this->db->query($sql);
3054 if (!$resql) {
3055 $this->errors[] = $this->db->error();
3056 $error++;
3057 }
3058
3059 if (!$error) {
3060 $this->ref_client = $ref_client; //deprecated
3061 $this->ref_customer = $ref_client;
3062 }
3063
3064 if (!$notrigger && empty($error)) {
3065 // Call trigger
3066 $result = $this->call_trigger('BILL_MODIFY', $user);
3067 if ($result < 0) {
3068 $error++;
3069 }
3070 // End call triggers
3071 }
3072
3073 if (!$error) {
3074 $this->ref_client = $ref_client; //deprecated
3075 $this->ref_customer = $ref_client;
3076
3077 $this->db->commit();
3078 return 1;
3079 } else {
3080 foreach ($this->errors as $errmsg) {
3081 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3082 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3083 }
3084 $this->db->rollback();
3085 return -1 * $error;
3086 }
3087 }
3088
3089 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3097 public function setInputReason($inputReasonId, $notrigger = 0)
3098 {
3099 // phpcs:enable
3100 global $user;
3101
3102 $error = 0;
3103
3104 dol_syslog(__METHOD__.' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3105 if ($this->status >= self::STATUS_DRAFT) {
3106 $this->oldcopy = dol_clone($this, 2);
3107 $this->demand_reason_id = $inputReasonId;
3108
3109 $this->db->begin();
3110
3111 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3112 $sql .= " SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId : 'null');
3113 $sql .= " WHERE rowid = ".((int) $this->id);
3114
3115 dol_syslog(__METHOD__, LOG_DEBUG);
3116 $res = $this->db->query($sql);
3117 if (!$res) {
3118 $error++;
3119 $this->error = $this->db->lasterror();
3120 $this->errors[] = $this->error;
3121 }
3122
3123 if (!$error) {
3124 if (!$notrigger) {
3125 // Call trigger
3126 $result = $this->call_trigger('BILL_MODIFY', $user);
3127 if ($result < 0) {
3128 $error++;
3129 }
3130 // End call triggers
3131 }
3132 }
3133
3134 if (!$error) {
3135 $this->db->commit();
3136 } else {
3137 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3138 $this->db->rollback();
3139 dol_syslog(__METHOD__.' Error : '.$this->errorsToString(), LOG_ERR);
3140 }
3141
3142 if (!$error) {
3143 return 1;
3144 } else {
3145 return -1;
3146 }
3147 }
3148
3149 return 0;
3150 }
3151
3160 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3161 {
3162 global $langs, $conf;
3163 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3164
3165 $rowid = $this->id;
3166
3167 dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
3168
3169 // Test to avoid invoice deletion (allowed if draft)
3170 $result = $this->is_erasable();
3171
3172 if ($result <= 0) {
3173 return 0;
3174 }
3175
3176 $error = 0;
3177
3178 $this->db->begin();
3179
3180 if (!$error && !$notrigger) {
3181 // Call trigger
3182 $result = $this->call_trigger('BILL_DELETE', $user);
3183 if ($result < 0) {
3184 $error++;
3185 }
3186 // End call triggers
3187 }
3188
3189 // Remove linked categories.
3190 if (!$error) {
3191 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_invoice";
3192 $sql .= " WHERE fk_invoice = ".((int) $this->id);
3193
3194 $result = $this->db->query($sql);
3195 if (!$result) {
3196 $error++;
3197 $this->errors[] = $this->db->lasterror();
3198 }
3199 }
3200
3201 // Removed extrafields
3202 if (!$error) {
3203 $result = $this->deleteExtraFields();
3204 if ($result < 0) {
3205 $error++;
3206 dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
3207 }
3208 }
3209
3210 if (!$error) {
3211 // Delete linked object
3212 $res = $this->deleteObjectLinked();
3213 if ($res < 0) {
3214 $error++;
3215 }
3216 }
3217
3218 if (!$error) {
3219 // If invoice was converted into a discount not yet consumed, we remove discount
3220 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
3221 $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
3222 $sql .= ' AND fk_facture_line IS NULL';
3223 $resql = $this->db->query($sql);
3224
3225 // If invoice has consumed discounts
3226 $this->fetch_lines();
3227 $list_rowid_det = array();
3228 foreach ($this->lines as $key => $invoiceline) {
3229 $list_rowid_det[] = $invoiceline->id;
3230 }
3231
3232 // Consumed discounts are freed
3233 if (count($list_rowid_det)) {
3234 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3235 $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
3236 $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
3237
3238 if (!$this->db->query($sql)) {
3239 $this->error = $this->db->error()." sql=".$sql;
3240 $this->errors[] = $this->error;
3241 $this->db->rollback();
3242 return -5;
3243 }
3244 }
3245
3246 // Remove other links to the deleted invoice
3247
3248 $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
3249 $sql .= ' SET fk_invoice = NULL';
3250 $sql .= ' WHERE fk_invoice = '.((int) $rowid);
3251
3252 if (!$this->db->query($sql)) {
3253 $this->error = $this->db->error()." sql=".$sql;
3254 $this->errors[] = $this->error;
3255 $this->db->rollback();
3256 return -5;
3257 }
3258
3259 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
3260 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
3261 $sql .= ' WHERE invoice_id = '.((int) $rowid);
3262
3263 if (!$this->db->query($sql)) {
3264 $this->error = $this->db->error()." sql=".$sql;
3265 $this->errors[] = $this->error;
3266 $this->db->rollback();
3267 return -5;
3268 }
3269
3270 // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
3271 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
3272 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3273 $langs->load("agenda");
3274
3275 $num = count($this->lines);
3276 for ($i = 0; $i < $num; $i++) {
3277 if ($this->lines[$i]->fk_product > 0) {
3278 $mouvP = new MouvementStock($this->db);
3279 $mouvP->origin = &$this;
3280 $mouvP->setOrigin($this->element, $this->id);
3281 // We decrease stock for product
3282 if ($this->type == self::TYPE_CREDIT_NOTE) {
3283 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
3284 } else {
3285 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
3286 }
3287 }
3288 }
3289 }
3290
3291 // Invoice line extrafields
3292 $sql_main_table = MAIN_DB_PREFIX.'facturedet';
3293 $sql_ef_table = $sql_main_table."_extrafields";
3294 $sqlef = "DELETE FROM ".$sql_ef_table." WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table." WHERE fk_facture = ".((int) $rowid).")";
3295 // Delete invoice line
3296 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
3297
3298 if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact() >= 0) {
3299 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
3300
3301 $resql = $this->db->query($sql);
3302 if ($resql) {
3303 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
3304 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3305 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3306
3307 // On efface le repertoire de pdf provisoire
3308 $ref = dol_sanitizeFileName($this->ref);
3309 if ($conf->facture->dir_output && !empty($this->ref)) {
3310 $dir = $conf->facture->dir_output."/".$ref;
3311 $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
3312 if (file_exists($file)) { // We must delete all files before deleting directory
3313 $ret = dol_delete_preview($this);
3314
3315 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
3316 $langs->load("errors");
3317 $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
3318 $this->errors[] = $this->error;
3319 $this->db->rollback();
3320 return 0;
3321 }
3322 }
3323 if (file_exists($dir)) {
3324 if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
3325 $langs->load("errors");
3326 $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
3327 $this->errors[] = $this->error;
3328 $this->db->rollback();
3329 return 0;
3330 }
3331 }
3332 }
3333
3334 $this->db->commit();
3335 return 1;
3336 } else {
3337 $this->error = $this->db->lasterror()." sql=".$sql;
3338 $this->errors[] = $this->error;
3339 $this->db->rollback();
3340 return -6;
3341 }
3342 } else {
3343 $this->error = $this->db->lasterror()." sql=".$sql;
3344 $this->errors[] = $this->error;
3345 $this->db->rollback();
3346 return -4;
3347 }
3348 } else {
3349 $this->db->rollback();
3350 return -2;
3351 }
3352 }
3353
3354 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3366 public function set_paid($user, $close_code = '', $close_note = '')
3367 {
3368 // phpcs:enable
3369 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3370 return $this->setPaid($user, $close_code, $close_note);
3371 }
3372
3383 public function setPaid($user, $close_code = '', $close_note = '')
3384 {
3385 $error = 0;
3386
3387 if ($this->paye != 1 || $this->status != self::STATUS_CLOSED) {
3388 $this->db->begin();
3389
3390 $now = dol_now();
3391
3392 dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
3393
3394 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3395 $sql .= ' fk_statut = '.self::STATUS_CLOSED;
3396 if (!$close_code) {
3397 $sql .= ', paye = 1';
3398 }
3399 if ($close_code) {
3400 $sql .= ", close_code = '".$this->db->escape($close_code)."'";
3401 }
3402 if ($close_note) {
3403 $sql .= ", close_note = '".$this->db->escape($close_note)."'";
3404 }
3405 $sql .= ', fk_user_closing = '.((int) $user->id);
3406 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3407 $sql .= " WHERE rowid = ".((int) $this->id);
3408
3409 $resql = $this->db->query($sql);
3410 if ($resql) {
3411 // Call trigger
3412 $result = $this->call_trigger('BILL_PAYED', $user);
3413 if ($result < 0) {
3414 $error++;
3415 }
3416 // End call triggers
3417 } else {
3418 $error++;
3419 $this->error = $this->db->lasterror();
3420 }
3421
3422 if (!$error) {
3423 $this->paye = 1;
3424 $this->status = self::STATUS_CLOSED;
3425 $this->db->commit();
3426 return 1;
3427 } else {
3428 $this->db->rollback();
3429 return -1;
3430 }
3431 } else {
3432 return 0;
3433 }
3434 }
3435
3436
3437 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3448 public function set_unpaid($user)
3449 {
3450 // phpcs:enable
3451 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3452 return $this->setUnpaid($user);
3453 }
3454
3463 public function setUnpaid($user)
3464 {
3465 $error = 0;
3466
3467 $this->db->begin();
3468
3469 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3470 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
3471 $sql .= ' date_closing=null,';
3472 $sql .= ' fk_user_closing=null';
3473 $sql .= " WHERE rowid = ".((int) $this->id);
3474
3475 dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
3476 $resql = $this->db->query($sql);
3477 if ($resql) {
3478 // Call trigger
3479 $result = $this->call_trigger('BILL_UNPAYED', $user);
3480 if ($result < 0) {
3481 $error++;
3482 }
3483 // End call triggers
3484 } else {
3485 $error++;
3486 $this->error = $this->db->error();
3487 dol_print_error($this->db);
3488 }
3489
3490 if (!$error) {
3491 $this->db->commit();
3492 return 1;
3493 } else {
3494 $this->db->rollback();
3495 return -1;
3496 }
3497 }
3498
3499
3500 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3513 public function set_canceled($user, $close_code = '', $close_note = '')
3514 {
3515 // phpcs:enable
3516 dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3517 return $this->setCanceled($user, $close_code, $close_note);
3518 }
3519
3530 public function setCanceled($user, $close_code = '', $close_note = '')
3531 {
3532 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
3533
3534 $this->db->begin();
3535 $now = dol_now();
3536
3537 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3538 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
3539 if ($close_code) {
3540 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3541 }
3542 if ($close_note) {
3543 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3544 }
3545 $sql .= ', fk_user_closing = '.((int) $user->id);
3546 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3547 $sql .= " WHERE rowid = ".((int) $this->id);
3548
3549 $resql = $this->db->query($sql);
3550 if ($resql) {
3551 // Bound discounts are deducted from the invoice
3552 // as they have not been used since the invoice is abandoned.
3553 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3554 $sql .= ' SET fk_facture = NULL';
3555 $sql .= ' WHERE fk_facture = '.((int) $this->id);
3556
3557 $resql = $this->db->query($sql);
3558 if ($resql) {
3559 // Call trigger
3560 $result = $this->call_trigger('BILL_CANCEL', $user);
3561 if ($result < 0) {
3562 $this->db->rollback();
3563 return -1;
3564 }
3565 // End call triggers
3566
3567 $this->db->commit();
3568 return 1;
3569 } else {
3570 $this->error = $this->db->error()." sql=".$sql;
3571 $this->db->rollback();
3572 return -1;
3573 }
3574 } else {
3575 $this->error = $this->db->error()." sql=".$sql;
3576 $this->db->rollback();
3577 return -2;
3578 }
3579 }
3580
3593 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3594 {
3595 global $conf, $langs, $mysoc;
3596 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3597
3598 $productStatic = null;
3599 $warehouseStatic = null;
3600 $productbatch = null;
3601 if ($batch_rule > 0) {
3602 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3603 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3604 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3605 $productStatic = new Product($this->db);
3606 $warehouseStatic = new Entrepot($this->db);
3607 $productbatch = new Productbatch($this->db);
3608 }
3609
3610 $now = dol_now();
3611
3612 $error = 0;
3613 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3614
3615 // Force to have object complete for checks
3616 $this->fetch_thirdparty();
3617 $this->fetch_lines();
3618
3619 // Check parameters
3620 if ($this->status != self::STATUS_DRAFT) {
3621 dol_syslog(get_class($this)."::validate Current status is not draft. operation canceled.", LOG_WARNING);
3622 return 0;
3623 }
3624 if (count($this->lines) <= 0) {
3625 $langs->load("errors");
3626 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3627 return -1;
3628 }
3629 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'creer'))
3630 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'invoice_advance', 'validate'))) {
3631 $this->error = 'Permission denied';
3632 dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS=' . getDolGlobalString('MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3633 return -1;
3634 }
3635 if ((preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) && // empty should not happened, but when it occurs, the test save life
3636 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
3637 ) {
3638 $this->date = dol_now();
3639 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3640 }
3641 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
3642 $last_of_type = $this->willBeLastOfSameType(true);
3643 if (!$last_of_type[0]) {
3644 $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3645 return -1;
3646 }
3647 }
3648
3649 // Check for mandatory fields in thirdparty (defined into setup)
3650 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3651 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER');
3652 foreach ($array_to_check as $key) {
3653 $keymin = strtolower($key);
3654 if (!property_exists($this->thirdparty, $keymin)) {
3655 continue;
3656 }
3657 $vallabel = $this->thirdparty->$keymin;
3658
3659 $i = (int) preg_replace('/[^0-9]/', '', $key);
3660 if ($i > 0) {
3661 if ($this->thirdparty->isACompany()) {
3662 // Check for mandatory prof id (but only if country is other than ours)
3663 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3664 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3665 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
3666 $langs->load("errors");
3667 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3668 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3669 return -1;
3670 }
3671 }
3672 }
3673 } else {
3674 if ($key == 'EMAIL') {
3675 // Check for mandatory
3676 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
3677 $langs->load("errors");
3678 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3679 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3680 return -1;
3681 }
3682 }
3683 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3684 // Check for mandatory
3685 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3686 $langs->load("errors");
3687 $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3688 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3689 return -1;
3690 }
3691 }
3692 if ($key == 'TVA_INTRA') {
3693 // Check for mandatory vat number
3694 if (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') == 'eeconly') {
3695 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3696 $langs->load("errors");
3697 $this->error = $langs->trans('ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3698 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3699 return -1;
3700 }
3701 } elseif (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3702 $langs->load("errors");
3703 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3704 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3705 return -1;
3706 }
3707 }
3708 }
3709 }
3710 }
3711
3712 // Check for mandatory fields in $this
3713 $array_to_check = array('REF_CLIENT' => 'RefCustomer');
3714 foreach ($array_to_check as $key => $val) {
3715 $keymin = strtolower($key);
3716 $vallabel = $this->$keymin;
3717
3718 // Check for mandatory
3719 $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3720 if (!$vallabel && getDolGlobalString($keymandatory)) {
3721 $langs->load("errors");
3722 $error++;
3723 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3724 }
3725 }
3726
3727 $this->db->begin();
3728
3729 // Check parameters
3730 if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3731 // Check that source invoice is known
3732 if ($this->fk_facture_source <= 0) {
3733 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3734 $this->db->rollback();
3735 return -10;
3736 }
3737
3738 // Load source invoice that has been replaced
3739 $facreplaced = new Facture($this->db);
3740 $result = $facreplaced->fetch($this->fk_facture_source);
3741 if ($result <= 0) {
3742 $this->error = $langs->trans("ErrorBadInvoice");
3743 $this->db->rollback();
3744 return -11;
3745 }
3746
3747 // Check that source invoice not already replaced by another one.
3748 $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3749 if ($idreplacement && $idreplacement != $this->id) {
3750 $facreplacement = new Facture($this->db);
3751 $facreplacement->fetch($idreplacement);
3752 $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3753 $this->db->rollback();
3754 return -12;
3755 }
3756
3757 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3758 if ($result < 0) {
3759 $this->error = $facreplaced->error;
3760 $this->db->rollback();
3761 return -13;
3762 }
3763 }
3764
3765 // Define new ref
3766 if ($force_number) {
3767 $num = $force_number;
3768 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3769 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3770 $this->date = dol_now();
3771 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3772 }
3773 $num = $this->getNextNumRef($this->thirdparty);
3774 } else {
3775 $num = (string) $this->ref;
3776 }
3777
3778 if (!$num) {
3779 $error++;
3780 } else {
3781 $this->oldref = $this->ref;
3782 $this->newref = dol_sanitizeFileName($num);
3783 }
3784
3785 if (!$error) {
3786 $this->update_price(1);
3787
3788 // Validate
3789 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3790 $sql .= " SET ref = '".$this->db->escape($num)."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? ((int) $user->id) : "null").", date_valid = '".$this->db->idate($now)."'";
3791 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3792 $sql .= ", datef='".$this->db->idate($this->date)."'";
3793 $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3794 }
3795 $sql .= " WHERE rowid = ".((int) $this->id);
3796
3797 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3798 $resql = $this->db->query($sql);
3799 if (!$resql) {
3800 $this->error = $this->db->lasterror();
3801 $error++;
3802 }
3803 }
3804
3805 if (!$error) {
3806 // Define third party as a customer
3807 $result = $this->thirdparty->setAsCustomer();
3808
3809 // If active (STOCK_CALCULATE_ON_BILL), we decrement the main product and its components at invoice validation
3810 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3811 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3812 $langs->load("agenda");
3813
3814 // Loop on each line
3815 $cpt = count($this->lines);
3816 for ($i = 0; $i < $cpt; $i++) {
3817 if ($this->lines[$i]->fk_product > 0) {
3818 $mouvP = new MouvementStock($this->db);
3819 $mouvP->origin = &$this; // deprecated
3820 $mouvP->setOrigin($this->element, $this->id);
3821
3822 // We decrease stock for product
3823 if ($this->type == self::TYPE_CREDIT_NOTE) {
3824 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3825 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3826 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num), '', '', $this->lines[$i]->batch);
3827 if ($result < 0) {
3828 $error++;
3829 $this->setErrorsFromObject($mouvP);
3830 }
3831 } else {
3832 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3833 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3834
3835 $is_batch_line = false;
3836 if ($batch_rule > 0) {
3837 $productStatic->fetch($this->lines[$i]->fk_product);
3838 if ($productStatic->hasbatch() && is_object($productbatch)) {
3839 $is_batch_line = true;
3840 $product_qty_remain = $this->lines[$i]->qty;
3841
3842 $sortfield = '';
3843 $sortorder = '';
3844 // find lot/serial by sellby (DLC) and eatby dates (DLUO) first
3846 $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3847 $sortorder = 'ASC,ASC,ASC,ASC';
3848 }
3849
3850 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 : null), $sortfield, $sortorder);
3851 if (!is_array($resBatchList)) {
3852 $error++;
3853 $this->error = $this->db->lasterror();
3854 }
3855
3856 if (!$error) {
3857 $batchList = $resBatchList;
3858 if (empty($batchList)) {
3859 $error++;
3860 $langs->load('errors');
3861 $warehouseStatic->fetch($idwarehouse);
3862 $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3863 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3864 }
3865
3866 foreach ($batchList as $batch) {
3867 if ($batch->qty <= 0) {
3868 continue; // try to decrement only batches have positive quantity first
3869 }
3870
3871 // enough quantity in this batch
3872 if ($batch->qty >= $product_qty_remain) {
3873 $product_batch_qty = $product_qty_remain;
3874 } else {
3875 // not enough (take all in batch)
3876 $product_batch_qty = $batch->qty;
3877 }
3878 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3879 if ($result < 0) {
3880 $error++;
3881 $this->setErrorsFromObject($mouvP);
3882 break;
3883 }
3884
3885 $product_qty_remain -= $product_batch_qty;
3886 // all product quantity was decremented
3887 if ($product_qty_remain <= 0) {
3888 break;
3889 }
3890 }
3891
3892 if (!$error && $product_qty_remain > 0) {
3893 if (getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER')) {
3894 $error++;
3895 $langs->load('errors');
3896 $warehouseStatic->fetch($idwarehouse);
3897 $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3898 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3899 } else {
3900 // take in the first batch
3901 $batch = $batchList[0];
3902 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3903 if ($result < 0) {
3904 $error++;
3905 $this->setErrorsFromObject($mouvP);
3906 }
3907 }
3908 }
3909 }
3910 }
3911 }
3912
3913 if (!$is_batch_line) { // If stock move not yet processed
3914 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3915 if ($result < 0) {
3916 $error++;
3917 $this->setErrorsFromObject($mouvP);
3918 }
3919 }
3920 }
3921 }
3922 }
3923 }
3924
3925 /*
3926 * Set situation_final to 0 if is a credit note and the invoice source is a invoice situation (case when invoice situation is at 100%)
3927 * So we can continue to create new invoice situation
3928 */
3929 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3930 $invoice_situation = new Facture($this->db);
3931 $result = $invoice_situation->fetch($this->fk_facture_source);
3932 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3933 $invoice_situation->situation_final = 0;
3934 // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3935 $result = $invoice_situation->setFinal($user, 1);
3936 }
3937 if ($result < 0) {
3938 $this->error = $invoice_situation->error;
3939 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3940 $error++;
3941 }
3942 }
3943
3944 // Trigger calls
3945 if (!$error && !$notrigger) {
3946 // Call trigger
3947 $result = $this->call_trigger('BILL_VALIDATE', $user);
3948 if ($result < 0) {
3949 $error++;
3950 }
3951 // End call triggers
3952 }
3953
3954 if (!$error) {
3955 // Rename directory in index entry if dir was a temporary ref
3956 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
3957 // Now we rename also files into index
3958 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'facture/".$this->db->escape($this->newref)."'";
3959 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".(int) $conf->entity;
3960 $resql = $this->db->query($sql);
3961 if (!$resql) {
3962 $error++;
3963 $this->error = $this->db->lasterror();
3964 }
3965 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'facture/".$this->db->escape($this->newref)."'";
3966 $sql .= " WHERE filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".(int) $conf->entity;
3967 $resql = $this->db->query($sql);
3968 if (!$resql) {
3969 $error++;
3970 $this->error = $this->db->lasterror();
3971 }
3972 }
3973 }
3974
3975 if (!$error && !$this->is_last_in_cycle()) {
3976 $resupdatenext = $this->updatePriceNextInvoice($langs);
3977 if (!$resupdatenext) {
3978 $error++;
3979 }
3980 }
3981
3982 // Set new ref and define current status
3983 if (!$error) {
3984 $this->ref = $num;
3985 $this->statut = self::STATUS_VALIDATED; // deprecated
3987 $this->date_validation = $now;
3988 $i = 0;
3989
3990 if (getDolGlobalInt('INVOICE_USE_SITUATION')) {
3991 $final = true;
3992 $nboflines = count($this->lines);
3993 while (($i < $nboflines) && $final) {
3994 $line = $this->lines[$i];
3995 '@phan-var-force FactureLigne $line';
3996 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3997 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3998 $current_progress = (float) $line->situation_percent;
3999 $full_progress = $previousprogress + $current_progress;
4000 $final = ($full_progress == 100);
4001 } else {
4002 $final = ($line->situation_percent == 100);
4003 }
4004 $i++;
4005 }
4006
4007 if (!$final) {
4008 if ($this->situation_final) {
4009 // If we must change situation_final
4010 $this->situation_final = 0;
4011 $this->setFinal($user, 1); // Trigger is disabled, already run by the validate
4012 }
4013 } else {
4014 if (!$this->situation_final) {
4015 // If we must change situation_final
4016 $this->situation_final = 1;
4017 $this->setFinal($user, 1); // Trigger is disabled, already run by the validate
4018 }
4019 }
4020 }
4021 }
4022 }
4023
4024 // All database actions are now complete
4025 // We rename the directory and files on disk if old dir was a temporary ref.
4026 if (!$error && preg_match('/^[\‍(]?PROV/i', $this->oldref)) {
4027 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
4028 $oldref = dol_sanitizeFileName($this->oldref);
4029 $newref = dol_sanitizeFileName($num);
4030 $dirsource = $conf->facture->dir_output.'/'.$oldref;
4031 $dirdest = $conf->facture->dir_output.'/'.$newref;
4032 if (!$error && file_exists($dirsource)) {
4033 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
4034
4035 if (@rename($dirsource, $dirdest)) {
4036 dol_syslog("Rename ok");
4037 // Rename also docs starting with $oldref with $newref
4038 $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
4039 foreach ($listoffiles as $fileentry) {
4040 $dirsource = $fileentry['name'];
4041 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
4042 $dirsource = $fileentry['path'].'/'.$dirsource;
4043 $dirdest = $fileentry['path'].'/'.$dirdest;
4044 @rename($dirsource, $dirdest);
4045 }
4046 }
4047 }
4048 }
4049
4050 if (!$error) {
4051 $this->db->commit();
4052 return 1;
4053 } else {
4054 $this->db->rollback();
4055 return -1;
4056 }
4057 }
4058
4065 public function updatePriceNextInvoice(&$langs)
4066 {
4067 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4068 $is_last = $next_invoice->is_last_in_cycle();
4069
4070 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4071 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4072 return false;
4073 }
4074
4075 foreach ($next_invoice->lines as $line) {
4076 '@phan-var-force FactureLigne $line';
4077 $result = $next_invoice->updateline(
4078 $line->id,
4079 $line->desc,
4080 $line->subprice,
4081 $line->qty,
4082 $line->remise_percent,
4083 $line->date_start,
4084 $line->date_end,
4085 $line->tva_tx,
4086 $line->localtax1_tx,
4087 $line->localtax2_tx,
4088 'HT',
4089 $line->info_bits,
4090 $line->product_type,
4091 $line->fk_parent_line,
4092 0,
4093 $line->fk_fournprice,
4094 $line->pa_ht,
4095 $line->label,
4096 $line->special_code,
4097 $line->array_options,
4098 $line->situation_percent,
4099 $line->fk_unit
4100 );
4101
4102 if ($result < 0) {
4103 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4104 return false;
4105 }
4106 }
4107
4108 break; // Only the next invoice and not each next invoice
4109 }
4110
4111 return true;
4112 }
4113
4121 public function setDraft($user, $idwarehouse = -1)
4122 {
4123 // phpcs:enable
4124 global $langs;
4125
4126 $error = 0;
4127
4128 if ($this->status == self::STATUS_DRAFT) {
4129 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
4130 return 0;
4131 }
4132
4133 dol_syslog(__METHOD__, LOG_DEBUG);
4134
4135 $this->db->begin();
4136
4137 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4138 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
4139 $sql .= " WHERE rowid = ".((int) $this->id);
4140
4141 $result = $this->db->query($sql);
4142 if ($result) {
4143 if (!$error) {
4144 $this->oldcopy = clone $this;
4145 }
4146
4147 // If we decrease stock on invoice validation, we increase back
4148 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
4149 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
4150 $langs->load("agenda");
4151
4152 $num = count($this->lines);
4153 for ($i = 0; $i < $num; $i++) {
4154 if ($this->lines[$i]->fk_product > 0) {
4155 $mouvP = new MouvementStock($this->db);
4156 $mouvP->origin = &$this;
4157 $mouvP->setOrigin($this->element, $this->id);
4158 // We decrease stock for product
4159 if ($this->type == self::TYPE_CREDIT_NOTE) {
4160 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
4161 } else {
4162 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
4163 }
4164 }
4165 }
4166 }
4167
4168 if ($error == 0) {
4169 $old_statut = $this->status;
4170 $this->statut = self::STATUS_DRAFT; // deprecated
4171 $this->status = self::STATUS_DRAFT;
4172
4173 // Call trigger
4174 $result = $this->call_trigger('BILL_UNVALIDATE', $user);
4175 if ($result < 0) {
4176 $error++;
4177 $this->statut = $old_statut; // deprecated
4178 $this->status = $old_statut;
4179 }
4180 // End call triggers
4181 } else {
4182 $this->db->rollback();
4183 return -1;
4184 }
4185
4186 if ($error == 0) {
4187 $this->db->commit();
4188 return 1;
4189 } else {
4190 $this->db->rollback();
4191 return -1;
4192 }
4193 } else {
4194 $this->error = $this->db->error();
4195 $this->db->rollback();
4196 return -1;
4197 }
4198 }
4199
4200
4241 public function addline(
4242 $desc,
4243 $pu_ht,
4244 $qty,
4245 $txtva,
4246 $txlocaltax1 = 0,
4247 $txlocaltax2 = 0,
4248 $fk_product = 0,
4249 $remise_percent = 0,
4250 $date_start = '',
4251 $date_end = '',
4252 $fk_code_ventilation = 0,
4253 $info_bits = 0,
4254 $fk_remise_except = 0,
4255 $price_base_type = 'HT',
4256 $pu_ttc = 0,
4257 $type = 0,
4258 $rang = -1,
4259 $special_code = 0,
4260 $origin = '',
4261 $origin_id = 0,
4262 $fk_parent_line = 0,
4263 $fk_fournprice = null,
4264 $pa_ht = 0,
4265 $label = '',
4266 $array_options = array(),
4267 $situation_percent = 100,
4268 $fk_prev_id = 0,
4269 $fk_unit = null,
4270 $pu_ht_devise = 0,
4271 $ref_ext = '',
4272 $noupdateafterinsertline = 0
4273 ) {
4274 // Deprecation warning
4275 if ($label) {
4276 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4277 //var_dump(getCallerInfoString());exit;
4278 }
4279
4280 global $mysoc, $langs;
4281
4282 dol_syslog(get_class($this)."::addline id=$this->id, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, fk_code_ventilation=$fk_code_ventilation, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, desc=".dol_trunc($desc, 25), LOG_DEBUG);
4283
4284 if ($this->status == self::STATUS_DRAFT) {
4285 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4286
4287 // Clean parameters
4288 if (empty($remise_percent)) {
4289 $remise_percent = 0;
4290 }
4291 if (empty($qty)) {
4292 $qty = 0;
4293 }
4294 if (empty($info_bits)) {
4295 $info_bits = 0;
4296 }
4297 if (empty($rang)) {
4298 $rang = 0;
4299 }
4300 if (empty($fk_code_ventilation)) {
4301 $fk_code_ventilation = 0;
4302 }
4303 if (empty($txtva)) {
4304 $txtva = 0;
4305 }
4306 if (empty($txlocaltax1)) {
4307 $txlocaltax1 = 0;
4308 }
4309 if (empty($txlocaltax2)) {
4310 $txlocaltax2 = 0;
4311 }
4312 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4313 $fk_parent_line = 0;
4314 }
4315 if (empty($fk_prev_id)) {
4316 $fk_prev_id = 'null';
4317 }
4318
4319 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
4320 // INVOICE_USE_SITUATION = 2 - Lines situation percent on new lines must be 0 (No cumulative). They will be added by changing the percent that is initialized to 0.
4321 if ($this->isSituationInvoice() && getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4322 $situation_percent = 0;
4323 } else {
4324 $situation_percent = 100;
4325 }
4326 }
4327
4328 if (empty($ref_ext)) {
4329 $ref_ext = '';
4330 }
4331
4332 $remise_percent = (float) price2num($remise_percent);
4333
4334 $qty = (float) price2num($qty);
4335 $pu_ht = (float) price2num($pu_ht);
4336 $pu_ht_devise = (float) price2num($pu_ht_devise);
4337 $pu_ttc = (float) price2num($pu_ttc);
4338 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4339 if (strpos((string) $txtva, '*') !== false) {
4340 $info_bits |= 1;
4341 }
4342 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4343 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4344 }
4345 $txlocaltax1 = (float) price2num($txlocaltax1);
4346 $txlocaltax2 = (float) price2num($txlocaltax2);
4347
4348 if ($price_base_type == 'HT') {
4349 $pu = $pu_ht;
4350 } else {
4351 $pu = $pu_ttc;
4352 }
4353
4354 // Check parameters
4355 if ($type < 0) {
4356 return -1;
4357 }
4358
4359 if ($date_start && $date_end && $date_start > $date_end) {
4360 $langs->load("errors");
4361 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4362 return -1;
4363 }
4364
4365 $this->db->begin();
4366
4367 $product_type = $type;
4368 if (!empty($fk_product) && $fk_product > 0) {
4369 $product = new Product($this->db);
4370 $result = $product->fetch($fk_product);
4371 $product_type = $product->type;
4372
4373 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4374 // get real stock
4375 $productChildrenNb = 0;
4376 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
4377 $productChildrenNb = $product->hasFatherOrChild(1);
4378 }
4379 if ($productChildrenNb > 0) {
4380 // compute real stock from each subcomponent
4381 $product_stock = null;
4382 $product->loadStockForVirtualProduct('warehouseopen', $qty);
4383 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4384 if ($product_stock === null) {
4385 $product_stock = $componentStockWarehouse->real;
4386 } else {
4387 $product_stock = min($product_stock, $componentStockWarehouse->real);
4388 }
4389 }
4390 if ($product_stock === null) {
4391 $product_stock = 0;
4392 }
4393 } else {
4394 $product_stock = $product->stock_reel;
4395 }
4396
4397 if ($product_stock < $qty) {
4398 $langs->load("errors");
4399 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4400 $this->db->rollback();
4401 return -3;
4402 }
4403 }
4404
4405 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
4406 $tmpproduct = new Product($this->db);
4407 $result = $tmpproduct->fetch($fk_product);
4408 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
4409 if ($newqty != $qty) {
4410 $qty = $newqty;
4411 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
4412 }
4413 }
4414 }
4415
4416 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4417
4418 // Clean vat code
4419 $reg = array();
4420 $vat_src_code = '';
4421 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4422 $vat_src_code = $reg[1];
4423 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4424 }
4425
4426 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
4427 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
4428 // and this is done at the line level, which has its own VAT rate
4429
4430 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
4431
4432 $total_ht = $tabprice[0];
4433 $total_tva = $tabprice[1];
4434 $total_ttc = $tabprice[2];
4435 $total_localtax1 = $tabprice[9];
4436 $total_localtax2 = $tabprice[10];
4437 $pu_ht = $tabprice[3];
4438
4439 // MultiCurrency
4440 $multicurrency_total_ht = $tabprice[16];
4441 $multicurrency_total_tva = $tabprice[17];
4442 $multicurrency_total_ttc = $tabprice[18];
4443 $pu_ht_devise = $tabprice[19];
4444
4445 // Rank to use
4446 $ranktouse = $rang;
4447 if (empty($ranktouse) || $ranktouse == -1) {
4448 $rangmax = $this->line_max($fk_parent_line);
4449 $ranktouse = $rangmax + 1;
4450 }
4451
4452 // Same gate as in updateline(): the -abs() forcing on credit note lines is relaxed only when
4453 // both FACTURE_ENABLE_NEGATIVE_LINES and INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN are enabled.
4454 $apply_abs_price_on_credit_note = false;
4455 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
4456 $apply_abs_price_on_credit_note = true;
4457 }
4458
4459 // Insert line
4460 $this->line = new FactureLigne($this->db);
4461
4462 $this->line->context = $this->context;
4463
4464 $this->line->fk_facture = $this->id;
4465 $this->line->label = $label; // deprecated
4466 $this->line->desc = $desc;
4467 $this->line->ref_ext = $ref_ext;
4468
4469 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : (float) $qty); // For credit note, quantity is always positive and unit price negative
4470 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht) : (float) $pu_ht); // For credit note, unit price always negative, always positive otherwise
4471 // Persist the original entry mode of the line so updateline() can preserve it later.
4472 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? ($apply_abs_price_on_credit_note ? -abs((float) $pu_ttc) : (float) $pu_ttc) : 0;
4473
4474 $this->line->vat_src_code = $vat_src_code;
4475 $this->line->tva_tx = $txtva;
4476 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4477 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4478 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4479 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4480
4481 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ht) : (float) $total_ht); // For credit note and if qty is negative, total is negative
4482 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc); // For credit note and if qty is negative, total is negative
4483 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva); // For credit note and if qty is negative, total is negative
4484 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_localtax1) : (float) $total_localtax1); // For credit note and if qty is negative, total is negative
4485 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_localtax2) : (float) $total_localtax2); // For credit note and if qty is negative, total is negative
4486
4487 $this->line->fk_product = $fk_product;
4488 $this->line->product_type = $product_type;
4489 $this->line->remise_percent = $remise_percent;
4490 $this->line->date_start = $date_start;
4491 $this->line->date_end = $date_end;
4492 $this->line->fk_code_ventilation = $fk_code_ventilation;
4493 $this->line->rang = $ranktouse;
4494 $this->line->info_bits = $info_bits;
4495 $this->line->fk_remise_except = $fk_remise_except;
4496
4497 $this->line->special_code = $special_code;
4498 $this->line->fk_parent_line = $fk_parent_line;
4499
4500 $this->line->origin = $origin;
4501 $this->line->origin_id = $origin_id;
4502
4503 $this->line->situation_percent = $situation_percent;
4504 $this->line->fk_prev_id = $fk_prev_id;
4505 $this->line->fk_unit = $fk_unit;
4506
4507 // infos margin
4508 $this->line->fk_fournprice = $fk_fournprice;
4509 $this->line->pa_ht = $pa_ht;
4510
4511 // Multicurrency
4512 $this->line->fk_multicurrency = $this->fk_multicurrency;
4513 $this->line->multicurrency_code = $this->multicurrency_code;
4514 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht_devise) : (float) $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
4515
4516 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ht) : (float) $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
4517 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
4518 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
4519
4520 if (is_array($array_options) && count($array_options) > 0) {
4521 $this->line->array_options = $array_options;
4522 }
4523
4524 $result = $this->line->insert();
4525 if ($result > 0) {
4526 // Update denormalized fields at the order level
4527 if (empty($noupdateafterinsertline)) {
4528 $result = $this->update_price(1, 'auto', 0, $mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
4529 }
4530
4531 if (!isset($this->context['createfromclone'])) {
4532 if (!empty($fk_parent_line)) {
4533 // Always reorder if child line
4534 $this->line_order(true, 'DESC');
4535 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4536 // Update all rank of all other lines starting from the same $ranktouse
4537 $linecount = count($this->lines);
4538 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4539 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
4540 }
4541 }
4542
4543 $this->lines[] = $this->line;
4544 } else {
4545 // Loop on all lines of parent object
4546 foreach ($this->lines as $tmpline) {
4547 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4548 $this->line->extraparams = $tmpline->extraparams;
4549 $this->line->setExtraParameters();
4550 }
4551 }
4552 }
4553
4554 if ($result > 0) {
4555 $this->db->commit();
4556 return $this->line->id;
4557 } else {
4558 $this->error = $this->db->lasterror();
4559 $this->db->rollback();
4560 return -1;
4561 }
4562 } else {
4563 $this->error = $this->line->error;
4564 $this->errors = $this->line->errors;
4565 $this->db->rollback();
4566 return -2;
4567 }
4568 } else {
4569 $this->errors[] = 'status of invoice must be Draft to allow use of ->addline()';
4570 dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4571 return -3;
4572 }
4573 }
4574
4606 public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = array(), $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0)
4607 {
4608 global $user;
4609
4610 if (!$this->isLineOfObject($rowid)) {
4611 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4612 return -1;
4613 }
4614
4615 // Deprecation warning
4616 if ($label) {
4617 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4618 }
4619
4620 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4621
4622 global $mysoc, $langs;
4623
4624 dol_syslog(get_class($this)."::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
4625
4626 if ($this->status == self::STATUS_DRAFT) {
4627 if (!$this->is_last_in_cycle() && empty($this->error)) {
4628 if (!$this->checkProgressLine($rowid, $situation_percent)) {
4629 if (!$this->error) {
4630 $this->error = $langs->trans('invoiceLineProgressError');
4631 }
4632 return -3;
4633 }
4634 }
4635
4636 if ($date_start && $date_end && $date_start > $date_end) {
4637 $langs->load("errors");
4638 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4639 return -1;
4640 }
4641
4642 $this->db->begin();
4643
4644 // Clean parameters
4645 if (empty($qty)) {
4646 $qty = 0;
4647 }
4648 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4649 $fk_parent_line = 0;
4650 }
4651 if (empty($special_code) || $special_code == 3) {
4652 $special_code = 0;
4653 }
4654 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '' || $situation_percent == null) {
4655 // INVOICE_USE_SITUATION = 2 - If there is no progress on a line, percent must not be 100% (No cumulative)
4656 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalInt('INVOICE_USE_SITUATION') == 2 && (int) $situation_percent < 100) {
4657 $situation_percent = 0;
4658 } else {
4659 $situation_percent = 100;
4660 }
4661 }
4662 if (empty($ref_ext)) {
4663 $ref_ext = '';
4664 }
4665
4666 $remise_percent = (float) price2num($remise_percent);
4667
4668 $qty = (float) price2num($qty);
4669 $pu = (float) price2num($pu);
4670 $pu_ht_devise = (float) price2num($pu_ht_devise);
4671 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4672
4673 if (strpos((string) $txtva, '*') !== false) {
4674 $info_bits |= 1;
4675 }
4676 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4677 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4678 }
4679 $txlocaltax1 = (float) price2num($txlocaltax1);
4680 $txlocaltax2 = (float) price2num($txlocaltax2);
4681
4682 // Check parameters
4683 if ($type < 0) {
4684 return -1;
4685 }
4686
4687 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
4688 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
4689 // and this is done at the line level, which has its own VAT rate
4690
4691 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4692
4693 // Clean vat code
4694 $reg = array();
4695 $vat_src_code = '';
4696 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4697 $vat_src_code = $reg[1];
4698 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4699 }
4700
4701 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
4702 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
4703 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
4704 $tmpline = new FactureLigne($this->db);
4705 if ($tmpline->fetch($rowid) > 0) {
4706 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
4707 if ($newqty != $qty) {
4708 $qty = $newqty;
4709 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
4710 }
4711 }
4712 }
4713
4714 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
4715
4716 $total_ht = $tabprice[0];
4717 $total_tva = $tabprice[1];
4718 $total_ttc = $tabprice[2];
4719 $total_localtax1 = $tabprice[9];
4720 $total_localtax2 = $tabprice[10];
4721 $pu_ht = $tabprice[3];
4722 $pu_tva = $tabprice[4];
4723 $pu_ttc = $tabprice[5];
4724
4725 // MultiCurrency
4726 $multicurrency_total_ht = $tabprice[16];
4727 $multicurrency_total_tva = $tabprice[17];
4728 $multicurrency_total_ttc = $tabprice[18];
4729 $pu_ht_devise = $tabprice[19];
4730
4731 // Old properties: $price, $remise (deprecated)
4732 $price = $pu;
4733 $remise = 0;
4734 if ($remise_percent > 0) {
4735 $remise = round(((float) $pu * (float) $remise_percent / 100), 2);
4736 $price = ((float) $pu - $remise);
4737 }
4738 $price = price2num($price);
4739
4740 // Fetch current line from the database and then clone the object and set it in $oldline property
4741 $line = new FactureLigne($this->db);
4742 $line->fetch($rowid);
4743 $line->fetch_optionals();
4744
4745 if (!empty($line->fk_product)) {
4746 $product = new Product($this->db);
4747 $result = $product->fetch($line->fk_product);
4748 $product_type = $product->type;
4749
4750 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4751 // get real stock
4752 $productChildrenNb = 0;
4753 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
4754 $productChildrenNb = $product->hasFatherOrChild(1);
4755 }
4756 if ($productChildrenNb > 0) {
4757 // compute real stock from each subcomponent
4758 $product_stock = null;
4759 $product->loadStockForVirtualProduct('warehouseopen', $qty);
4760 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4761 if ($product_stock === null) {
4762 $product_stock = $componentStockWarehouse->real;
4763 } else {
4764 $product_stock = min($product_stock, $componentStockWarehouse->real);
4765 }
4766 }
4767 if ($product_stock === null) {
4768 $product_stock = 0;
4769 }
4770 } else {
4771 $product_stock = $product->stock_reel;
4772 }
4773
4774 if ($product_stock < $qty) {
4775 $langs->load("errors");
4776 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', (string) $product->ref);
4777 $this->db->rollback();
4778 return -3;
4779 }
4780 }
4781 }
4782
4783 $staticline = clone $line;
4784
4785 $line->oldline = $staticline;
4786 $this->line = $line;
4787 $this->line->context = $this->context;
4788 $this->line->rang = $rang;
4789
4790 // Reorder if fk_parent_line change
4791 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4792 $rangmax = $this->line_max($fk_parent_line);
4793 $this->line->rang = $rangmax + 1;
4794 }
4795 $apply_abs_price_on_credit_note = false;
4796 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
4797 $apply_abs_price_on_credit_note = true;
4798 }
4799
4800
4801
4802 $this->line->id = $rowid;
4803 $this->line->rowid = $rowid;
4804 $this->line->label = $label;
4805 $this->line->desc = $desc;
4806 $this->line->ref_ext = $ref_ext;
4807 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
4808
4809 $this->line->vat_src_code = $vat_src_code;
4810 $this->line->tva_tx = $txtva;
4811 $this->line->localtax1_tx = $txlocaltax1;
4812 $this->line->localtax2_tx = $txlocaltax2;
4813 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4814 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4815
4816 $this->line->remise_percent = $remise_percent;
4817 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht) : (float) $pu_ht); // For credit note, unit price always negative, always positive otherwise
4818 // Persist the original entry mode of the line so a no-op edit can preserve it later.
4819 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? ($apply_abs_price_on_credit_note ? -abs((float) $pu_ttc) : (float) $pu_ttc) : 0;
4820 $this->line->date_start = $date_start;
4821 $this->line->date_end = $date_end;
4822 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ht) : (float) $total_ht); // For credit note and if qty is negative, total is negative
4823 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva);
4824 $this->line->total_localtax1 = (float) $total_localtax1;
4825 $this->line->total_localtax2 = (float) $total_localtax2;
4826 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc);
4827 $this->line->info_bits = $info_bits;
4828 $this->line->special_code = $special_code;
4829 $this->line->product_type = $type;
4830 $this->line->fk_parent_line = $fk_parent_line;
4831 $this->line->skip_update_total = $skip_update_total;
4832 $this->line->situation_percent = $situation_percent;
4833 $this->line->fk_unit = $fk_unit;
4834
4835 $this->line->fk_fournprice = $fk_fournprice;
4836 $this->line->pa_ht = $pa_ht;
4837
4838 // Multicurrency
4839 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht_devise) : (float) $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
4840 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ht) : (float) $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
4841 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4842 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4843
4844 if (is_array($array_options) && count($array_options) > 0) {
4845 // We replace values in this->line->array_options only for entries defined into $array_options
4846 foreach ($array_options as $key => $value) {
4847 $this->line->array_options[$key] = $array_options[$key];
4848 }
4849 }
4850
4851 $result = $this->line->update($user, $notrigger);
4852 if ($result > 0) {
4853 // Reorder if child line
4854 if (!empty($fk_parent_line)) {
4855 $this->line_order(true, 'DESC');
4856 }
4857
4858 // Update denormalized information at the invoice level
4859 $this->update_price(1, 'auto');
4860 $this->db->commit();
4861 return $result;
4862 } else {
4863 $this->error = $this->line->error;
4864 $this->db->rollback();
4865 return -1;
4866 }
4867 } else {
4868 $this->error = "Invoice statut makes operation forbidden";
4869 return -2;
4870 }
4871 }
4872
4880 public function checkProgressLine($idline, $situation_percent)
4881 {
4882 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4883 INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4884 WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4885
4886 $result = $this->db->query($sql);
4887 if (!$result) {
4888 $this->error = $this->db->error();
4889 return false;
4890 }
4891
4892 $obj = $this->db->fetch_object($result);
4893
4894 if ($obj === null) {
4895 return true;
4896 } else {
4897 return ($situation_percent < $obj->situation_percent);
4898 }
4899 }
4900
4901 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4910 public function update_percent($line, $percent, $update_price = true)
4911 {
4912 // phpcs:enable
4913 global $mysoc, $user;
4914
4915 // Progress should never be changed for discount lines
4916 if (($line->info_bits & 2) == 2) {
4917 return;
4918 }
4919
4920 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4921
4922 // Cap percentages to 100
4923 if ($percent > 100) {
4924 $percent = 100;
4925 }
4926 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4927 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4928 $current_progress = $percent - $previous_progress;
4929 $line->situation_percent = $current_progress;
4930 $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, array(), $current_progress);
4931 } else {
4932 $line->situation_percent = $percent;
4933 $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, array(), $percent);
4934 }
4935 $line->total_ht = (float) $tabprice[0];
4936 $line->total_tva = (float) $tabprice[1];
4937 $line->total_ttc = (float) $tabprice[2];
4938 $line->total_localtax1 = (float) $tabprice[9];
4939 $line->total_localtax2 = (float) $tabprice[10];
4940 $line->multicurrency_total_ht = (float) $tabprice[16];
4941 $line->multicurrency_total_tva = (float) $tabprice[17];
4942 $line->multicurrency_total_ttc = (float) $tabprice[18];
4943 $line->update($user);
4944
4945 // sometimes it is better to not update price for each line, ie when updating situation on all lines
4946 if ($update_price) {
4947 $this->update_price(1);
4948 }
4949 }
4950
4958 public function deleteLine($rowid, $id = 0)
4959 {
4960 global $user;
4961
4962 dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4963
4964 if ($this->status != self::STATUS_DRAFT) {
4965 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4966 return -1;
4967 }
4968
4969 $line = new FactureLigne($this->db);
4970
4971 $line->context = $this->context;
4972
4973 // Load line
4974 $result = $line->fetch($rowid);
4975 if (!($result > 0)) {
4976 dol_print_error($this->db, $line->error, $line->errors);
4977 return -1;
4978 }
4979
4980 if ($id <= 0) {
4981 $id = $this->id;
4982 }
4983 if ($id > 0 && (int) $line->fk_facture !== (int) $id) {
4984 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4985 return -1;
4986 }
4987
4988 $this->db->begin();
4989
4990 // Memorize previous line for triggers
4991 $staticline = clone $line;
4992 $line->oldline = $staticline;
4993
4994 if ($line->delete($user) > 0) {
4995 $result = $this->update_price(1);
4996
4997 if ($result > 0) {
4998 $this->db->commit();
4999 return 1;
5000 } else {
5001 $this->db->rollback();
5002 $this->error = $this->db->lasterror();
5003 return -1;
5004 }
5005 } else {
5006 $this->db->rollback();
5007 $this->error = $line->error;
5008 return -1;
5009 }
5010 }
5011
5012 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5023 public function set_remise($user, $remise, $notrigger = 0)
5024 {
5025 // phpcs:enable
5026 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
5027 // @phan-suppress-next-line PhanDeprecatedFunction
5028 return $this->setDiscount($user, $remise, $notrigger);
5029 }
5030
5039 public function setDiscount($user, $remise, $notrigger = 0)
5040 {
5041 // Clean parameters
5042 if (empty($remise)) {
5043 $remise = 0;
5044 }
5045
5046 if ($user->hasRight('facture', 'creer')) {
5047 $remise = (float) price2num($remise, 2);
5048
5049 $error = 0;
5050
5051 $this->db->begin();
5052
5053 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
5054 $sql .= " SET remise_percent = ".((float) $remise);
5055 $sql .= " WHERE rowid = ".((int) $this->id);
5056 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
5057
5058 dol_syslog(__METHOD__, LOG_DEBUG);
5059 $resql = $this->db->query($sql);
5060 if (!$resql) {
5061 $this->errors[] = $this->db->error();
5062 $error++;
5063 }
5064
5065 if (!$notrigger && empty($error)) {
5066 // Call trigger
5067 $result = $this->call_trigger('BILL_MODIFY', $user);
5068 if ($result < 0) {
5069 $error++;
5070 }
5071 // End call triggers
5072 }
5073
5074 if (!$error) {
5075 $this->remise_percent = $remise;
5076 $this->update_price(1);
5077
5078 $this->db->commit();
5079 return 1;
5080 } else {
5081 foreach ($this->errors as $errmsg) {
5082 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5083 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5084 }
5085 $this->db->rollback();
5086 return -1 * $error;
5087 }
5088 }
5089
5090 return 0;
5091 }
5092
5093
5104 public function setCategories($categories)
5105 {
5106 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5107 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5108 }
5109
5118 public function getNextNumRef($soc, $mode = 'next')
5119 {
5120 global $conf, $langs;
5121
5122 if ($this->module_source == 'takepos') {
5123 $langs->load('cashdesk');
5124
5125 $moduleName = 'takepos';
5126 $moduleSourceName = 'Takepos';
5127 $addonConstName = 'TAKEPOS_REF_ADDON';
5128
5129 // Clean parameters (if not defined or using deprecated value)
5130 if (!getDolGlobalString('TAKEPOS_REF_ADDON')) {
5131 $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
5132 }
5133
5134 $addon = getDolGlobalString('TAKEPOS_REF_ADDON');
5135 } else {
5136 $langs->load('bills');
5137
5138 $moduleName = 'facture';
5139 $moduleSourceName = 'Invoice';
5140 $addonConstName = 'FACTURE_ADDON';
5141
5142 // Clean parameters (if not defined or using deprecated value)
5143 if (!getDolGlobalString('FACTURE_ADDON')) {
5144 $conf->global->FACTURE_ADDON = 'mod_facture_mars';
5145 } elseif (getDolGlobalString('FACTURE_ADDON') == 'terre') { // terre is deprecated
5146 $conf->global->FACTURE_ADDON = 'mod_facture_mars';
5147 } elseif (getDolGlobalString('FACTURE_ADDON') == 'mercure') {
5148 $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
5149 }
5150
5151 $addon = getDolGlobalString('FACTURE_ADDON');
5152 }
5153
5154 if (!empty($addon)) {
5155 dol_syslog("Call getNextNumRef with ".$addonConstName." = " . getDolGlobalString('FACTURE_ADDON').", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
5156
5157 $mybool = false;
5158
5159 $file = $addon.'.php';
5160 $classname = $addon;
5161
5162
5163 // Include file with class
5164 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
5165 foreach ($dirmodels as $reldir) {
5166 $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
5167
5168 // Load file with numbering class (if found)
5169 if (is_file($dir.$file) && is_readable($dir.$file)) {
5170 $mybool = ((bool) include_once $dir.$file) || $mybool;
5171 }
5172 }
5173
5174 // For compatibility
5175 if (!$mybool) {
5176 $file = $addon.'/'.$addon.'.modules.php';
5177 $classname = 'mod_'.$moduleName.'_'.$addon;
5178 $classname = preg_replace('/\-.*$/', '', $classname);
5179 // Include file with class
5180 foreach ($conf->file->dol_document_root as $dirroot) {
5181 $dir = $dirroot.'/core/modules/'.$moduleName.'/';
5182
5183 // Load file with numbering class (if found)
5184 if (is_file($dir.$file) && is_readable($dir.$file)) {
5185 $mybool = (include_once $dir.$file) || $mybool;
5186 }
5187 }
5188 }
5189
5190 if (!$mybool) {
5191 dol_print_error(null, 'Failed to include file '.$file);
5192 return '';
5193 }
5194
5195 $obj = new $classname();
5196 '@phan-var-force ModeleNumRefFactures $obj';
5197
5198 $numref = $obj->getNextValue($soc, $this, $mode);
5199
5200
5205 if ($mode != 'last' && !$numref) {
5206 $this->error = $obj->error;
5207 return '';
5208 }
5209
5210 return $numref;
5211 } else {
5212 $langs->load('errors');
5213 print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5214 return '';
5215 }
5216 }
5217
5224 public function info($id)
5225 {
5226 $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5227 $sql .= ' date_closing as dateclosing,';
5228 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5229 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
5230 $sql .= ' WHERE c.rowid = '.((int) $id);
5231
5232 $result = $this->db->query($sql);
5233 if ($result) {
5234 if ($this->db->num_rows($result)) {
5235 $obj = $this->db->fetch_object($result);
5236
5237 $this->id = $obj->rowid;
5238 $this->user_creation_id = $obj->fk_user_author;
5239 $this->user_modification_id = $obj->fk_user_modif;
5240 $this->user_validation_id = $obj->fk_user_valid;
5241 $this->user_closing_id = $obj->fk_user_closing;
5242
5243 $this->date_creation = $this->db->jdate($obj->datec);
5244 $this->date_modification = $this->db->jdate($obj->datem);
5245 $this->date_validation = $this->db->jdate($obj->datev);
5246 $this->date_closing = $this->db->jdate($obj->dateclosing);
5247 }
5248 $this->db->free($result);
5249 } else {
5250 dol_print_error($this->db);
5251 }
5252 }
5253
5254
5255 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5269 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
5270 {
5271 // phpcs:enable
5272 global $user;
5273
5274 $ga = array();
5275
5276 $sql = "SELECT s.rowid, s.nom as name, s.client,";
5277 $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
5278 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
5279 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5280 $sql .= " AND f.fk_soc = s.rowid";
5281 if ($draft) {
5282 $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
5283 }
5284 if (is_object($excluser)) {
5285 $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
5286 }
5287 // If the internal user must only see his customers, force searching by him
5288 $search_sale = 0;
5289 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5290 $search_sale = $user->id;
5291 }
5292 // Search on sale representative
5293 if ($search_sale && $search_sale != '-1') {
5294 if ($search_sale == -2) {
5295 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5296 } elseif ($search_sale > 0) {
5297 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
5298 }
5299 }
5300 // Search on socid
5301 if ($socid) {
5302 $sql .= " AND f.fk_soc = ".((int) $socid);
5303 }
5304 $sql .= $this->db->order($sortfield, $sortorder);
5305 $sql .= $this->db->plimit($limit, $offset);
5306
5307 $result = $this->db->query($sql);
5308 if ($result) {
5309 $numc = $this->db->num_rows($result);
5310 if ($numc) {
5311 $i = 0;
5312 while ($i < $numc) {
5313 $obj = $this->db->fetch_object($result);
5314
5315 if ($shortlist == 1) {
5316 $ga[$obj->fid] = $obj->ref;
5317 } elseif ($shortlist == 2) {
5318 $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
5319 } else {
5320 $ga[$i]['id'] = $obj->fid;
5321 $ga[$i]['ref'] = $obj->ref;
5322 $ga[$i]['name'] = $obj->name;
5323 }
5324 $i++;
5325 }
5326 }
5327 return $ga;
5328 } else {
5329 dol_print_error($this->db);
5330 return -1;
5331 }
5332 }
5333
5334
5335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5344 public function list_replacable_invoices($socid = 0)
5345 {
5346 // phpcs:enable
5347 global $conf;
5348
5349 $return = array();
5350
5351 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5352 $sql .= " ff.rowid as rowidnext";
5353 //$sql .= ", SUM(pf.amount) as alreadypaid";
5354 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5355 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
5356 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
5357 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
5358 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5359 $sql .= " AND f.paye = 0"; // Not paid completely
5360 $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
5361 $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
5362 if ($socid > 0) {
5363 $sql .= " AND f.fk_soc = ".((int) $socid);
5364 }
5365 //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
5366 $sql .= " ORDER BY f.ref";
5367
5368 dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
5369 $resql = $this->db->query($sql);
5370 if ($resql) {
5371 while ($obj = $this->db->fetch_object($resql)) {
5372 $return[$obj->rowid] = array(
5373 'id' => $obj->rowid,
5374 'ref' => $obj->ref,
5375 'status' => $obj->status,
5376 'paid' => $obj->paid,
5377 'alreadypaid' => 0
5378 );
5379 }
5380 //print_r($return);
5381 return $return;
5382 } else {
5383 $this->error = $this->db->error();
5384 return -1;
5385 }
5386 }
5387
5388
5389 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5399 public function list_qualified_avoir_invoices($socid = 0)
5400 {
5401 // phpcs:enable
5402 global $conf;
5403
5404 $return = array();
5405
5406 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement, f.multicurrency_code";
5407 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5408 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
5409 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
5410 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5411 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5412 // $sql.= " WHERE f.fk_statut >= 1";
5413 // $sql.= " AND (f.paye = 1"; // Classee payee completement
5414 // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
5415 $sql .= " AND ff.type IS NULL"; // Return true if there isn't any replacement invoice
5416 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
5417
5418 if (getDolGlobalString('INVOICE_USE_SITUATION_CREDIT_NOTE')) {
5419 // Keep invoices that are not situation invoices or that are the last in series if it is a situation invoice
5420 $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
5421 $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID because of the group by later
5422 $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
5423 $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
5424 $sql .= " AND fs.type = ".self::TYPE_SITUATION;
5425 $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5426 if ($socid > 0) {
5427 $sql .= " AND fs.fk_soc = ".((int) $socid);
5428 }
5429 $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
5430 $sql .= ")";
5431 } else {
5432 $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
5433 }
5434
5435 if ($socid > 0) {
5436 $sql .= " AND f.fk_soc = ".((int) $socid);
5437 }
5438
5439 if (getDolGlobalInt('LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5440 $sql .= " ORDER BY CASE WHEN f.rowid = ".((int) GETPOST('fac_avoir'))." THEN 0 ELSE 1 END, f.ref";
5441 $sql .= " DESC";
5442 $sql .= $this->db->plimit(getDolGlobalInt('LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5443 } else {
5444 $sql .= " ORDER BY f.ref";
5445 }
5446
5447 dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
5448 $resql = $this->db->query($sql);
5449 if ($resql) {
5450 while ($obj = $this->db->fetch_object($resql)) {
5451 $qualified = 0;
5452 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5453 $qualified = 1;
5454 }
5455 if ($obj->fk_statut == self::STATUS_CLOSED) {
5456 $qualified = 1;
5457 }
5458 if ($qualified) {
5459 //$ref=$obj->ref;
5460 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5461 $return[$obj->rowid] = array('ref' => $obj->ref, 'status' => $obj->fk_statut, 'type' => $obj->type, 'paye' => $obj->paye, 'paymentornot' => $paymentornot, 'multicurrency_code' => $obj->multicurrency_code);
5462 }
5463 }
5464
5465 return $return;
5466 } else {
5467 $this->error = $this->db->error();
5468 return -1;
5469 }
5470 }
5471
5472
5473 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5480 public function load_board($user)
5481 {
5482 // phpcs:enable
5483 global $conf, $langs;
5484
5485 $sanitizedclause = " WHERE";
5486
5487 $now = dol_now();
5488 $warningdelay = getWarningDelay('invoice', 'client');
5489
5490 // The count, the total and the number of late invoices are computed by the database: reading every unpaid invoice to
5491 // count them in PHP took seconds on the home page of an instance with a lot of unpaid invoices. An invoice is late when
5492 // its due date is before now minus the warning delay, the rule of hasDelay() for a validated invoice (an invoice without
5493 // due date was counted as late by that rule, this is kept).
5494 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ht) as total,";
5495 $sql .= " SUM(CASE WHEN f.date_lim_reglement IS NULL OR f.date_lim_reglement < '".$this->db->idate($now - $warningdelay)."' THEN 1 ELSE 0 END) as nblate";
5496 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5497 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5498 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5499 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5500 $sanitizedclause = " AND";
5501 }
5502 $sql .= $sanitizedclause." f.paye=0";
5503 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5504 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
5505 if ($user->socid) {
5506 $sql .= " AND f.fk_soc = ".((int) $user->socid);
5507 }
5508
5509 $resql = $this->db->query($sql);
5510 if ($resql) {
5511 $langs->load("bills");
5512 $response = new WorkboardResponse();
5513 $response->warning_delay = $warningdelay / 60 / 60 / 24;
5514 $response->label = $langs->trans("CustomerBillsUnpaid");
5515 $response->labelShort = $langs->trans("Unpaid");
5516 $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5517 $response->img = img_object('', "bill");
5518
5519 $obj = $this->db->fetch_object($resql);
5520 if ($obj) {
5521 $response->nbtodo = (int) $obj->nb;
5522 $response->total = (float) $obj->total;
5523 $response->nbtodolate = (int) $obj->nblate;
5524 if ($response->nbtodolate > 0) {
5525 $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5526 }
5527 }
5528
5529 $this->db->free($resql);
5530 return $response;
5531 } else {
5532 dol_print_error($this->db);
5533 $this->error = $this->db->error();
5534 return -1;
5535 }
5536 }
5537
5538
5539 /* Management of a bill's contacts */
5540
5546 public function getIdBillingContact()
5547 {
5548 return $this->getIdContact('external', 'BILLING');
5549 }
5550
5556 public function getIdShippingContact()
5557 {
5558 return $this->getIdContact('external', 'SHIPPING');
5559 }
5560
5561
5570 public function initAsSpecimen($option = '')
5571 {
5572 global $conf, $langs, $user;
5573
5574 $now = dol_now();
5575 $arraynow = dol_getdate($now);
5576 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
5577
5578 // Load array of products prodids
5579 $num_prods = 0;
5580 $prodids = array();
5581 $sql = "SELECT rowid";
5582 $sql .= " FROM ".MAIN_DB_PREFIX."product";
5583 $sql .= " WHERE entity IN (".getEntity('product').")";
5584 $sql .= $this->db->plimit(100);
5585
5586 $resql = $this->db->query($sql);
5587 if ($resql) {
5588 $num_prods = $this->db->num_rows($resql);
5589 $i = 0;
5590 while ($i < $num_prods) {
5591 $i++;
5592 $row = $this->db->fetch_row($resql);
5593 $prodids[$i] = $row[0];
5594 }
5595 }
5596 //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
5597 if (empty($num_prods)) {
5598 $num_prods = 1;
5599 $prodids[$num_prods] = 1;
5600 }
5601
5602 // Initialize parameters
5603 $this->id = 0;
5604 $this->entity = $conf->entity;
5605 $this->ref = 'SPECIMEN';
5606 $this->specimen = 1;
5607 $this->socid = 1;
5608 $this->date = $nownotime;
5609 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5610 $this->cond_reglement_id = 1;
5611 $this->cond_reglement_code = 'RECEP';
5612 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
5613 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
5614 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
5615
5616 $this->note_public = 'This is a comment (public)';
5617 $this->note_private = 'This is a comment (private)';
5618
5619 $this->user_creation_id = $user->id;
5620
5621 $this->multicurrency_tx = 1;
5622 $this->multicurrency_code = $conf->currency;
5623
5624 $this->fk_incoterms = 0;
5625 $this->location_incoterms = '';
5626
5627 $this->pos_print_counter = 0; // Already printed 0 times
5628 $this->email_sent_counter = 0; // Already sent by email 0 times
5629
5630 $this->status = 0;
5631
5632 if (empty($option) || $option != 'nolines') {
5633 // Lines
5634 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
5635 $xnbp = 0;
5636 while ($xnbp < $nbp) {
5637 $line = new FactureLigne($this->db);
5638 $line->desc = $langs->trans("Description")." ".$xnbp;
5639 $line->qty = 1;
5640 $line->subprice = 100;
5641 $line->tva_tx = 19.6;
5642 $line->localtax1_tx = 0;
5643 $line->localtax2_tx = 0;
5644 $line->remise_percent = 0;
5645 if ($xnbp == 1 && $option != 'takepos' && $option != 'nonegativeup') { // Qty is negative (product line)
5646 $prodid = mt_rand(1, $num_prods);
5647 if (isset($prodids[$prodid])) {
5648 $line->fk_product = $prodids[$prodid];
5649 }
5650 $line->qty = -1;
5651 $line->total_ht = -100;
5652 $line->total_ttc = -119.6;
5653 $line->total_tva = -19.6;
5654 $line->multicurrency_total_ht = -200;
5655 $line->multicurrency_total_ttc = -239.2;
5656 $line->multicurrency_total_tva = -39.2;
5657 } elseif ($xnbp == 2 && $option != 'takepos' && $option != 'nonegativeup') { // UP is negative (free line)
5658 $line->subprice = -100;
5659 $line->total_ht = -100;
5660 $line->total_ttc = -119.6;
5661 $line->total_tva = -19.6;
5662 $line->remise_percent = 0;
5663 $line->multicurrency_total_ht = -200;
5664 $line->multicurrency_total_ttc = -239.2;
5665 $line->multicurrency_total_tva = -39.2;
5666 } elseif ($xnbp == 3) { // Discount is 50% (product line)
5667 $prodid = mt_rand(1, $num_prods);
5668 if (isset($prodids[$prodid])) {
5669 $line->fk_product = $prodids[$prodid];
5670 }
5671 $line->total_ht = 50;
5672 $line->total_ttc = 59.8;
5673 $line->total_tva = 9.8;
5674 $line->multicurrency_total_ht = 100;
5675 $line->multicurrency_total_ttc = 119.6;
5676 $line->multicurrency_total_tva = 19.6;
5677 $line->remise_percent = 50;
5678 } else { // (product line)
5679 $prodid = mt_rand(1, $num_prods);
5680 if (isset($prodids[$prodid])) {
5681 $line->fk_product = $prodids[$prodid];
5682 }
5683 $line->total_ht = 100;
5684 $line->total_ttc = 119.6;
5685 $line->total_tva = 19.6;
5686 $line->multicurrency_total_ht = 200;
5687 $line->multicurrency_total_ttc = 239.2;
5688 $line->multicurrency_total_tva = 39.2;
5689 $line->remise_percent = 0;
5690 }
5691
5692 $this->lines[$xnbp] = $line;
5693
5694
5695 $this->total_ht += $line->total_ht;
5696 $this->total_tva += $line->total_tva;
5697 $this->total_ttc += $line->total_ttc;
5698
5699 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5700 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5701 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5702
5703 $xnbp++;
5704 }
5705 $this->revenuestamp = 0;
5706
5707 // Add a line "offered"
5708 if ($option != 'takepos') {
5709 $line = new FactureLigne($this->db);
5710 $line->desc = $langs->trans("Description")." (offered line)";
5711 $line->qty = 1;
5712 $line->subprice = 100;
5713 $line->tva_tx = 19.6;
5714 $line->localtax1_tx = 0;
5715 $line->localtax2_tx = 0;
5716 $line->remise_percent = 100;
5717 $line->total_ht = 0;
5718 $line->total_ttc = 0; // 90 * 1.196
5719 $line->total_tva = 0;
5720 $line->multicurrency_total_ht = 0;
5721 $line->multicurrency_total_ttc = 0;
5722 $line->multicurrency_total_tva = 0;
5723 $prodid = mt_rand(1, $num_prods);
5724 if (isset($prodids[$prodid])) {
5725 $line->fk_product = $prodids[$prodid];
5726 }
5727
5728 $this->lines[$xnbp] = $line;
5729 $xnbp++;
5730 }
5731 }
5732
5733 return 1;
5734 }
5735
5741 public function loadStateBoard()
5742 {
5743 global $user;
5744
5745 $this->nb = array();
5746
5747 $sanitizedclause = "WHERE";
5748
5749 $sql = "SELECT count(f.rowid) as nb";
5750 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5751 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
5752 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5753 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5754 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5755 $sanitizedclause = "AND";
5756 }
5757 $sql .= " ".$sanitizedclause." f.entity IN (".getEntity('invoice').")";
5758
5759 $resql = $this->db->query($sql);
5760 if ($resql) {
5761 while ($obj = $this->db->fetch_object($resql)) {
5762 $this->nb["invoices"] = $obj->nb;
5763 }
5764 $this->db->free($resql);
5765 return 1;
5766 } else {
5767 dol_print_error($this->db);
5768 $this->error = $this->db->error();
5769 return -1;
5770 }
5771 }
5772
5778 public function getLinesArray()
5779 {
5780 return $this->fetch_lines();
5781 }
5782
5794 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5795 {
5796 $outputlangs->loadLangs(array("bills", "products"));
5797
5798 if (!dol_strlen($modele)) {
5799 $modele = 'sponge';
5800 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5801
5802 if (!empty($this->model_pdf)) {
5803 $modele = $this->model_pdf;
5804 } elseif (getDolGlobalString($thisTypeConfName)) {
5805 $modele = getDolGlobalString($thisTypeConfName);
5806 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
5807 $modele = getDolGlobalString('FACTURE_ADDON_PDF');
5808 }
5809 }
5810
5811 $modelpath = "core/modules/facture/doc/";
5812
5813 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5814 }
5815
5821 public function newCycle()
5822 {
5823 $sql = "SELECT max(situation_cycle_ref) as maxsituationref";
5824 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5825 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5826
5827 $resql = $this->db->query($sql);
5828 if ($resql) {
5829 if ($this->db->num_rows($resql) > 0) {
5830 $ref = 0;
5831 $obj = $this->db->fetch_object($resql);
5832 if ($obj) {
5833 $ref = (int) $obj->maxsituationref;
5834 }
5835 $ref++;
5836 } else {
5837 $ref = 1;
5838 }
5839 $this->db->free($resql);
5840 return $ref;
5841 } else {
5842 $this->error = $this->db->lasterror();
5843 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5844 return -1;
5845 }
5846 }
5847
5848 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5854 public function is_first()
5855 {
5856 // phpcs:enable
5857 return ($this->situation_counter == 1);
5858 }
5859
5860 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5866 public function get_prev_sits()
5867 {
5868 // phpcs:enable
5869 global $conf;
5870
5871 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5872 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5873 $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5874 $sql .= ' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int) $conf->entity));
5875 $resql = $this->db->query($sql);
5876 $res = array();
5877 if ($resql && $this->db->num_rows($resql) > 0) {
5878 while ($row = $this->db->fetch_object($resql)) {
5879 $id = $row->rowid;
5880 $situation = new Facture($this->db);
5881 $situation->fetch($id);
5882 $res[] = $situation;
5883 }
5884 } else {
5885 $this->error = $this->db->error();
5886 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5887 return -1;
5888 }
5889
5890 return $res;
5891 }
5892
5900 public function setFinal(User $user, $notrigger = 0)
5901 {
5902 $error = 0;
5903
5904 $this->db->begin();
5905
5906 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5907
5908 dol_syslog(__METHOD__, LOG_DEBUG);
5909 $resql = $this->db->query($sql);
5910 if (!$resql) {
5911 $this->errors[] = $this->db->error();
5912 $error++;
5913 }
5914
5915 if (!$notrigger && empty($error)) {
5916 // Call trigger
5917 $result = $this->call_trigger('BILL_MODIFY', $user);
5918 if ($result < 0) {
5919 $error++;
5920 }
5921 // End call triggers
5922 }
5923
5924 if (!$error) {
5925 $this->db->commit();
5926 return 1;
5927 } else {
5928 foreach ($this->errors as $errmsg) {
5929 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5930 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5931 }
5932 $this->db->rollback();
5933 return -1 * $error;
5934 }
5935 }
5936
5937 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5943 public function is_last_in_cycle()
5944 {
5945 // phpcs:enable
5946 global $conf;
5947
5948 if (!empty($this->situation_cycle_ref)) {
5949 // No point in testing anything if we're not inside a cycle
5950 $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5951 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5952 $sql .= ' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int) $conf->entity));
5953 $resql = $this->db->query($sql);
5954
5955 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5956 $last = $res['max(situation_counter)'];
5957 return ($last == $this->situation_counter);
5958 } else {
5959 $this->error = $this->db->lasterror();
5960 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5961 return false;
5962 }
5963 } else {
5964 return true;
5965 }
5966 }
5967
5976 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5977 {
5978 $tables = array(
5979 'facture'
5980 );
5981
5982 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5983 }
5984
5993 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5994 {
5995 $tables = array(
5996 'facturedet'
5997 );
5998
5999 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
6000 }
6001
6007 public function hasDelay()
6008 {
6009 global $conf;
6010
6011 $now = dol_now();
6012
6013 // Paid invoices have status STATUS_CLOSED
6014 if ($this->status != Facture::STATUS_VALIDATED) {
6015 return false;
6016 }
6017
6018 $hasDelay = $this->date_lim_reglement < ($now - getWarningDelay('invoice', 'client'));
6019 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6020 $totalpaid = $this->getSommePaiement(0);
6021 $totalpaid = (float) $totalpaid;
6022 $retainedWarrantyAmount = $this->getRetainedWarrantyAmount('MT');
6023 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
6024 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now - getWarningDelay('invoice', 'client'))) {
6025 $hasDelay = 1;
6026 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - getWarningDelay('invoice', 'client'))) {
6027 $hasDelay = 1;
6028 } else {
6029 $hasDelay = 0;
6030 }
6031 }
6032 }
6033
6034 return $hasDelay;
6035 }
6036
6042 public function isSituationInvoice()
6043 {
6044 return $this->situation_cycle_ref;
6045 }
6046
6051 public function displayRetainedWarranty()
6052 {
6053 // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
6054
6055 // note : we don't need to test INVOICE_USE_RETAINED_WARRANTY because if $this->retained_warranty is not empty it's because it was set when this conf was active
6056
6057 $displayWarranty = false;
6058 if (!empty($this->retained_warranty)) {
6059 $displayWarranty = true;
6060
6061 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
6062 // Check if this situation invoice is 100% for real
6063 $displayWarranty = false;
6064 if (!empty($this->situation_final)) {
6065 $displayWarranty = true;
6066 } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
6067 // $object->situation_final need validation to be done so this test is need for draft
6068 $displayWarranty = true;
6069
6070 foreach ($this->lines as $i => $line) {
6071 if ($line->product_type < 2 && $line->situation_percent < 100) {
6072 $displayWarranty = false;
6073 break;
6074 }
6075 }
6076 }
6077 }
6078 }
6079
6080 return $displayWarranty;
6081 }
6082
6089 public function getRetainedWarrantyAmount($rounding = 'MT')
6090 {
6091 if (empty($this->retained_warranty)) {
6092 return -1;
6093 }
6094
6095 $retainedWarrantyAmount = 0;
6096
6097 // Billed - retained warranty
6098 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
6099 $displayWarranty = true;
6100 // Check if this situation invoice is 100% for real
6101 if (!empty($this->lines)) {
6102 foreach ($this->lines as $i => $line) {
6103 if ($line->product_type < 2 && $line->situation_percent < 100) {
6104 $displayWarranty = false;
6105 break;
6106 }
6107 }
6108 }
6109
6110 if ($displayWarranty && !empty($this->situation_final)) {
6112 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6113
6114 // Sum the total including tax of all previous invoices, including the current one.
6115 $total2BillWT = 0;
6116 foreach ($TPreviousIncoice as &$fac) {
6117 $total2BillWT += $fac->total_ttc;
6118 }
6119 $total2BillWT += $this->total_ttc;
6120
6121 // Take the percent
6122 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6123 } else {
6124 return -1;
6125 }
6126 } else {
6127 // Because one day retained warranty could be used on standard invoices
6128 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6129 }
6130
6131 if (is_numeric($rounding) && $rounding < 0) {
6132 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
6133 }
6134
6135 if (is_numeric($rounding) && $rounding > 0) {
6136 return round($retainedWarrantyAmount, $rounding);
6137 }
6138
6139 return (float) price2num($retainedWarrantyAmount, $rounding);
6140 }
6141
6148 public function setRetainedWarranty($value)
6149 {
6150 dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
6151
6152 if ($this->status >= 0) {
6153 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6154 $sql .= " SET retained_warranty = ".((float) $value);
6155 $sql .= ' WHERE rowid='.((int) $this->id);
6156
6157 if ($this->db->query($sql)) {
6158 $this->retained_warranty = (float) $value;
6159 return 1;
6160 } else {
6161 dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
6162 $this->error = $this->db->error();
6163 return -1;
6164 }
6165 } else {
6166 dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
6167 $this->error = 'Status of the object is incompatible '.$this->status;
6168 return -2;
6169 }
6170 }
6171
6172
6180 public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '')
6181 {
6182 if (!$timestamp && $dateYmd) {
6183 $timestamp = $this->db->jdate($dateYmd);
6184 }
6185
6186
6187 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
6188 if ($this->status >= 0) {
6189 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6190 $sql .= " SET retained_warranty_date_limit = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
6191 $sql .= ' WHERE rowid = '.((int) $this->id);
6192
6193 if ($this->db->query($sql)) {
6194 $this->retained_warranty_date_limit = $timestamp;
6195 return 1;
6196 } else {
6197 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
6198 $this->error = $this->db->error();
6199 return -1;
6200 }
6201 } else {
6202 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6203 $this->error = 'Status of the object is incompatible '.$this->status;
6204 return -2;
6205 }
6206 }
6207
6208
6220 public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
6221 {
6222 global $conf, $langs, $user;
6223
6224 $error = 0;
6225 $this->output = '';
6226 $this->error = '';
6227 $nbMailSend = 0;
6228 $errorsMsg = array();
6229
6230 $langs->load("bills");
6231
6232 if (!isModEnabled('invoice')) { // Should not happen. If module disabled, cron job should not be visible.
6233 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Invoice"));
6234 return 0;
6235 }
6236 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
6237 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6238 return 0;
6239 }
6240 /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
6241 $langs->load("bills");
6242 $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Invoice"));
6243 return 0;
6244 }
6245 */
6246
6247 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
6248 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
6249 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
6250 $formmail = new FormMail($this->db);
6251
6252 $now = dol_now();
6253 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
6254
6255 $tmpinvoice = new Facture($this->db);
6256
6257 dol_syslog(__METHOD__." start", LOG_INFO);
6258
6259 // Label of the agenda event recorded for each reminder sent. It also allows to know that a reminder was already sent for an invoice.
6260 $labelreminderok = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
6261
6262 // Select all action comm reminder
6263 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
6264 if (!empty($paymentmode) && $paymentmode != 'all') {
6265 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
6266 }
6267 $sql .= " WHERE f.paye = 0"; // Only unpaid
6268 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
6269 if ($datetouse == 'invoicedate') {
6270 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
6271 } else {
6272 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
6273 }
6274 $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch processes only one company (no sharing)
6275 if (!empty($paymentmode) && $paymentmode != 'all') {
6276 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
6277 }
6278 // A credit note is not an amount that the customer has to pay, and an invoice without an amount to pay has nothing to remind
6279 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE;
6280 $sql .= " AND f.total_ttc > 0";
6281 // Do not send the same reminder twice if the batch is run again the same day (an event is recorded when a reminder is sent)
6282 $sql .= " AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX."actioncomm as a";
6283 $sql .= " WHERE a.elementtype = 'invoice' AND a.fk_element = f.rowid AND a.code = 'AC_EMAIL'";
6284 $sql .= " AND a.label = '".$this->db->escape($labelreminderok)."'";
6285 $sql .= " AND a.datep >= '".$this->db->idate(dol_get_first_hour($now))."')";
6286 if ($datetouse == 'invoicedate') {
6287 $sql .= $this->db->order("datef", "ASC");
6288 } else {
6289 $sql .= $this->db->order("date_lim_reglement", "ASC");
6290 }
6291
6292 $resql = $this->db->query($sql);
6293
6294 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
6295 if ($datetouse == 'invoicedate') {
6296 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedInvoicesWithDate", $stmpidate);
6297 } else {
6298 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
6299 }
6300 if (!empty($paymentmode) && $paymentmode != 'all') {
6301 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
6302 }
6303 $this->output .= '<br>';
6304
6305 if ($resql) {
6306 while ($obj = $this->db->fetch_object($resql)) {
6307 // Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
6308 $loopError = 0;
6309
6310 // Load event
6311 $res = $tmpinvoice->fetch($obj->id);
6312 if ($res > 0) {
6313 $tmpinvoice->fetch_thirdparty();
6314 // Load paid amounts so that __AMOUNT_REMAIN__ is the real remaining amount
6315 $tmpinvoice->getSommePaiement();
6316 $tmpinvoice->getSumCreditNotesUsed();
6317 $tmpinvoice->getSumDepositsUsed();
6318
6319 $outputlangs = new Translate('', $conf);
6320 if ($tmpinvoice->thirdparty->default_lang) {
6321 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6322 $outputlangs->loadLangs(array("main", "bills"));
6323 } else {
6324 $outputlangs = $langs;
6325 }
6326
6327 // Select email template according to language of recipient
6328 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
6329 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6330 $langs->load("errors");
6331 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
6332 return 0;
6333 }
6334
6335 // PREPARE EMAIL
6336 $errormesg = '';
6337
6338 // Make substitution in email content
6339 $tmpinvoice->totalpaid = $tmpinvoice->getSommePaiement();
6340 $tmpinvoice->totalcreditnotes = $tmpinvoice->getSumCreditNotesUsed();
6341 $tmpinvoice->totaldeposits = $tmpinvoice->getSumDepositsUsed();
6342 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $tmpinvoice);
6343
6344 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
6345
6346 // Topic
6347 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6348
6349 // Content
6350 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6351
6352 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
6353
6354 // Recipient
6355 $to = array();
6356 if ($forcerecipient) { // If a recipient was forced
6357 $to = array($forcerecipient);
6358 } else {
6359 $res = $tmpinvoice->fetch_thirdparty();
6360 $recipient = $tmpinvoice->thirdparty;
6361 if ($res > 0) {
6362 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
6363 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6364 foreach ($tmparraycontact as $data_email) {
6365 if (!empty($data_email['email'])) {
6366 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
6367 }
6368 }
6369 }
6370 if (empty($to) && !empty($recipient->email)) {
6371 $to[] = $recipient->email;
6372 }
6373 if (empty($to)) {
6374 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for invoice or customer.";
6375 $loopError++;
6376 }
6377 } else {
6378 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6379 $loopError++;
6380 }
6381 }
6382
6383 // Sender
6384 $email_from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
6385 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
6386 $email_from = (string) $arraymessage->email_from;
6387 }
6388 if (empty($email_from)) {
6389 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6390 $loopError++;
6391 }
6392
6393 if (!$loopError && !empty($to)) {
6394 $to = implode(',', $to);
6395 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
6396 $to = $to.','.$arraymessage->email_to;
6397 }
6398
6399 // Errors Recipient
6400 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
6401
6402 $trackid = 'inv'.$tmpinvoice->id;
6403 $sendcontext = 'standard';
6404
6405 $email_tocc = '';
6406 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
6407 $email_tocc = (string) $arraymessage->email_tocc;
6408 }
6409
6410 $email_tobcc = '';
6411 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
6412 $email_tobcc = (string) $arraymessage->email_tobcc;
6413 }
6414
6415 //join file is asked
6416 $joinFile = [];
6417 $joinFileName = [];
6418 $joinFileMime = [];
6419 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6420 $joinFile[] = DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc;
6421 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6422 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc);
6423 }
6424
6425 // Mail Creation
6426 $cMailFile = new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
6427
6428 $resultsendmail = $cMailFile->sendfile();
6429
6430 $this->db->begin();
6431
6432 // Sending Mail
6433 if ($resultsendmail) {
6434 $nbMailSend++;
6435
6436 // Add a line into event table
6437 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6438
6439 // Insert record of emails sent
6440 $actioncomm = new ActionComm($this->db);
6441
6442 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6443 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6444 $actioncomm->contact_id = 0;
6445
6446 $actioncomm->code = 'AC_EMAIL';
6447 $actioncomm->label = $labelreminderok;
6448 $actioncomm->note_private = $sendContent;
6449 $actioncomm->fk_project = $tmpinvoice->fk_project;
6450 $actioncomm->datep = dol_now();
6451 $actioncomm->datef = $actioncomm->datep;
6452 $actioncomm->percentage = -1; // Not applicable
6453 $actioncomm->authorid = $user->id; // User saving action
6454 $actioncomm->userownerid = $user->id; // Owner of action
6455 // Fields when action is an email (content should be added into note)
6456 $actioncomm->email_msgid = $cMailFile->msgid;
6457 $actioncomm->email_subject = $sendTopic;
6458 $actioncomm->email_from = $email_from;
6459 $actioncomm->email_sender = '';
6460 $actioncomm->email_to = $to;
6461 //$actioncomm->email_tocc = $sendtocc;
6462 //$actioncomm->email_tobcc = $sendtobcc;
6463 //$actioncomm->email_subject = $subject;
6464 $actioncomm->errors_to = $errors_to;
6465
6466 $actioncomm->elementtype = 'invoice';
6467 $actioncomm->elementid = $tmpinvoice->id;
6468
6469 //$actioncomm->extraparams = $extraparams;
6470
6471 $actioncomm->create($user);
6472 } else {
6473 $errormesg = $cMailFile->error.' : '.$to;
6474 $loopError++;
6475
6476 // Add a line into event table
6477 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6478
6479 // Insert record of emails sent
6480 $actioncomm = new ActionComm($this->db);
6481
6482 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6483 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6484 $actioncomm->contact_id = 0;
6485
6486 $actioncomm->code = 'AC_EMAIL';
6487 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
6488 $actioncomm->note_private = $errormesg;
6489 $actioncomm->fk_project = $tmpinvoice->fk_project;
6490 $actioncomm->datep = dol_now();
6491 $actioncomm->datef = $actioncomm->datep;
6492 $actioncomm->percentage = -1; // Not applicable
6493 $actioncomm->authorid = $user->id; // User saving action
6494 $actioncomm->userownerid = $user->id; // Owner of action
6495 // Fields when action is an email (content should be added into note)
6496 $actioncomm->email_msgid = $cMailFile->msgid;
6497 $actioncomm->email_subject = $sendTopic;
6498 $actioncomm->email_from = $email_from;
6499 $actioncomm->email_sender = '';
6500 $actioncomm->email_to = $to;
6501 //$actioncomm->email_tocc = $sendtocc;
6502 //$actioncomm->email_tobcc = $sendtobcc;
6503 //$actioncomm->email_subject = $subject;
6504 $actioncomm->errors_to = $errors_to;
6505
6506 $actioncomm->elementtype = 'invoice';
6507 $actioncomm->elementid = $tmpinvoice->id;
6508
6509 //$actioncomm->extraparams = $extraparams;
6510
6511 $actioncomm->create($user);
6512 }
6513
6514 $this->db->commit(); // We always commit
6515 }
6516
6517 if ($errormesg) {
6518 $errorsMsg[] = $errormesg;
6519 }
6520 } else {
6521 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
6522 $loopError++;
6523 }
6524
6525 $error += $loopError;
6526 }
6527 } else {
6528 $error++;
6529 }
6530
6531 if (!$error) {
6532 $this->output .= 'Nb of emails sent : '.$nbMailSend;
6533
6534 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
6535
6536 return 0;
6537 } else {
6538 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
6539
6540 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
6541
6542 return $error;
6543 }
6544 }
6545
6552 public function willBeLastOfSameType($allow_validated_drafts = false)
6553 {
6554 // get date of last validated invoices of same type
6555 $sql = "SELECT datef";
6556 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
6557 $sql .= " WHERE type = " . (int) $this->type ;
6558 $sql .= " AND date_valid IS NOT NULL";
6559 $sql .= " AND entity IN (".getEntity('invoice').")";
6560 $sql .= " ORDER BY datef DESC LIMIT 1";
6561
6562 $result = $this->db->query($sql);
6563 if ($result) {
6564 // compare with current validation date
6565 if ($this->db->num_rows($result)) {
6566 $obj = $this->db->fetch_object($result);
6567 $last_date = $this->db->jdate($obj->datef);
6568 $invoice_date = $this->date;
6569
6570 $is_last_of_same_type = $invoice_date >= $last_date;
6571 if ($allow_validated_drafts) {
6572 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
6573 }
6574
6575 return array($is_last_of_same_type, $last_date);
6576 } else {
6577 // element is first of type to be validated
6578 return array(true);
6579 }
6580 } else {
6581 dol_print_error($this->db);
6582 }
6583
6584 return array();
6585 }
6586
6594 public function getKanbanView($option = '', $arraydata = null)
6595 {
6596 global $langs;
6597
6598 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6599
6600 $picto = $this->picto;
6601 if ($this->type == self::TYPE_REPLACEMENT) {
6602 $picto .= 'r'; // Replacement invoice
6603 }
6604 if ($this->type == self::TYPE_CREDIT_NOTE) {
6605 $picto .= 'a'; // Credit note
6606 }
6607 if ($this->type == self::TYPE_DEPOSIT) {
6608 $picto .= 'd'; // Deposit invoice
6609 }
6610
6611 $return = '<div class="box-flex-item box-flex-grow-zero">';
6612 $return .= '<div class="info-box info-box-sm">';
6613 $return .= '<span class="info-box-icon bg-infobox-action">';
6614 $return .= img_picto('', $picto);
6615 $return .= '</span>';
6616 $return .= '<div class="info-box-content">';
6617 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
6618 if ($selected >= 0) {
6619 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6620 }
6621 if (!empty($arraydata['thirdparty'])) {
6622 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
6623 }
6624 if (property_exists($this, 'date')) {
6625 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
6626 }
6627 if (property_exists($this, 'total_ht')) {
6628 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
6629 $return .= ' '.$langs->trans("HT");
6630 $return .= '</span>';
6631 }
6632 if (method_exists($this, 'getLibStatut')) {
6633 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
6634 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
6635 }
6636 $return .= '</div>';
6637 $return .= '</div>';
6638 $return .= '</div>';
6639 return $return;
6640 }
6641}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:280
$object ref
Definition info.php:90
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Returns the IDs of the customer shipping contacts.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
createFromClone(User $user, $fromid=0, $forceentity=null)
Load an object from its id and create a new one in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines ...
update(User $user, $notrigger=0)
Update database.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Returns the IDs of the customer billing contacts.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clickable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
setInputReason($inputReasonId, $notrigger=0)
Update invoice input reason.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
getRetainedWarrantyAmount($rounding='MT')
Calculate the amount of the retained warranty (from the percentage).
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd='')
Change the retained_warranty_date_limit.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for invoices validated that are due.
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Invoice objects.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
isSituationInvoice()
Check if an invoice is a situation invoice.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
fetch_lines($only_type_product='', $loadalsotranslation=0)
Load all detailed lines into this->lines.
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tags the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a di...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as :
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
create(User $user, $notrigger=0, $forceduedate=0, $updatecurrencyrate=0)
Create invoice in database.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
addline( $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $fk_code_ventilation=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $situation_percent=100, $fk_prev_id=0, $fk_unit=null, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an invoice line into database (linked to product/service or not).
setUnpaid($user)
Tag the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a dir...
const STATUS_CLOSED
Classified paid.
setCategories($categories)
Sets object to given categories.
createFromContract($object, User $user, $lines=array())
Load an object from a contract and create a new invoice into database.
Class to manage invoice lines.
Class to manage invoice templates.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage "other" html components Only common components are here.
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
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_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:676
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:662
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:616
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:554
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:126
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:635
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:65
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
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...
setEntity($currentobject)
Set entity id to use when to create an object.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
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.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
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.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
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
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.