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