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