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-2026 Nick Fragoulis
24 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
25 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
26 * Copyright (C) 2025-2026 Lenin Rivas <lenin.rivas777@gmail.com>
27 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
28 * Copyright (C) 2026 Lionel Vessiller <lvessiller@open-dsi.fr>
29 * Copyright (C) 2026 José MARTINEZ <jose.martinez@pichinov.com>
30 * Copyright (C) 2026 Nick Fragoulis
31 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
32 *
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 3 of the License, or
36 * (at your option) any later version.
37 *
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
42 *
43 * You should have received a copy of the GNU General Public License
44 * along with this program. If not, see <https://www.gnu.org/licenses/>.
45 */
46
53require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
54require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/factureligne.class.php';
55require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
56require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
57require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
58require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
59require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
60
61if (isModEnabled('accounting')) {
62 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
63}
64if (isModEnabled('accounting')) {
65 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
66}
67
72{
73 use CommonSubtotal;
74
78 public $element = 'facture';
79
83 public $TRIGGER_PREFIX = 'BILL';
84
88 public $table_element = 'facture';
89
93 public $table_element_line = 'facturedet';
94
98 public $class_element_line = 'FactureLigne';
99
103 public $fk_element = 'fk_facture';
104
108 public $picto = 'bill';
109
114 public $restrictiononfksoc = 1;
115
119 protected $table_ref_field = 'ref';
120
124 public $ref;
125
130 public $fk_user_author;
131
136 public $fk_user_valid;
137
142 public $fk_user_modif;
143
147 public $datem;
148
152 public $delivery_date; // Date expected of shipment (date of start of shipment, not the reception that occurs some days after)
153
159 public $ref_client;
160
164 public $ref_customer;
165
169 public $resteapayer;
170
175 public $paye;
176
180 public $module_source;
184 public $pos_source;
185
189 public $increment;
190
194 public $pos_print_counter = 0;
195
199 public $email_sent_counter = 0;
200
204 public $fk_fac_rec_source;
205
209 public $fk_facture_source;
210
214 public $fk_bank;
215
219 public $lines = array();
220
224 public $line;
228 public $extraparams = array();
229
233 public $fac_rec;
234
235
239 public $situation_cycle_ref;
240
244 public $situation_counter;
245
249 public $situation_final;
250
254 public $tab_previous_situation_invoice = array();
255
259 public $tab_next_situation_invoice = array();
260
264 public $retained_warranty;
265
269 public $retained_warranty_date_limit;
270
274 public $retained_warranty_fk_cond_reglement;
275
279 public $availability_id;
280
284 public $date_closing;
285
289 public $source;
290
295 public $remise_percent;
296
300 public $online_payment_url;
301
305 public $ip;
306
307
333 // BEGIN MODULEBUILDER PROPERTIES
337 public $fields = array(
338 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 1),
339 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 5),
340 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
341 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 10, 'uieditable' => 1, 'alwayseditable' => 1),
342 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 12),
343 'type' => array('type' => 'smallint(6)', 'label' => 'Type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
344 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
345 //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
346 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 50),
347 'datef' => array('type' => 'date', 'label' => 'DateInvoice', 'enabled' => 1, 'visible' => 1, 'position' => 20),
348 'date_valid' => array('type' => 'date', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 22),
349 'date_lim_reglement' => array('type' => 'date', 'label' => 'DateDue', 'enabled' => 1, 'visible' => 1, 'position' => 25),
350 'payment_reference' => array('type' => 'varchar(25)', 'label' => 'PaymentReference', 'enabled' => 1, 'visible' => -1, 'position' => 26),
351 'date_closing' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 30),
352 'paye' => array('type' => 'smallint(6)', 'label' => 'InvoicePaidCompletely', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 80),
353 'close_code' => array('type' => 'varchar(16)', 'label' => 'EarlyClosingReason', 'enabled' => 1, 'visible' => -1, 'position' => 92),
354 'close_note' => array('type' => 'varchar(128)', 'label' => 'EarlyClosingComment', 'enabled' => 1, 'visible' => -1, 'position' => 93),
355 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 95, 'isameasure' => 1),
356 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => -1, 'position' => 100, 'isameasure' => 1),
357 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => -1, 'position' => 110, 'isameasure' => 1),
358 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => -1, 'position' => 120, 'isameasure' => 1),
359 'revenuestamp' => array('type' => 'double(24,8)', 'label' => 'RevenueStamp', 'enabled' => 1, 'visible' => -1, 'position' => 115, 'isameasure' => 1),
360 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
361 'fk_facture_source' => array('type' => 'integer', 'label' => 'SourceInvoice', 'enabled' => 1, 'visible' => -1, 'position' => 170),
362 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => 1, 'visible' => -1, 'position' => 175),
363 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 1, 'visible' => -1, 'position' => 180),
364 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'CurrencyCode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
365 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 190),
366 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 195),
367 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 205, 'uieditable' => 1, 'alwayseditable' => 1),
368 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 210, 'uieditable' => 1, 'alwayseditable' => 1),
369 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 215),
370 'fk_input_reason' => array('type' => 'integer', 'label' => 'Source', 'enabled' => 1, 'visible' => -1, 'position' => 220),
371 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
372 'situation_cycle_ref' => array('type' => 'smallint(6)', 'label' => 'Situation cycle ref', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 230),
373 'situation_counter' => array('type' => 'smallint(6)', 'label' => 'Situation counter', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 235),
374 'situation_final' => array('type' => 'smallint(6)', 'label' => 'Situation final', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 240),
375 'retained_warranty' => array('type' => 'double', 'label' => 'Retained warranty', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 245),
376 'retained_warranty_date_limit' => array('type' => 'date', 'label' => 'Retained warranty date limit', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 250),
377 'retained_warranty_fk_cond_reglement' => array('type' => 'integer', 'label' => 'Retained warranty fk cond reglement', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 255),
378 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 260),
379 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 265),
380 'date_pointoftax' => array('type' => 'date', 'label' => 'DatePointOfTax', 'enabled' => 'getDolGlobalString("INVOICE_POINTOFTAX_DATE")', 'visible' => -1, 'position' => 270),
381 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyID', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 275),
382 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 280),
383 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 285, 'isameasure' => 1),
384 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 290, 'isameasure' => 1),
385 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 291, 'isameasure' => 1),
386 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 292, 'isameasure' => 1),
387 'fk_fac_rec_source' => array('type' => 'integer', 'label' => 'RecurringInvoiceSource', 'enabled' => 1, 'visible' => -1, 'position' => 305),
388 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 310),
389 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'langfile' => 'cashdesk', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 315),
390 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'langfile' => 'cashdesk', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 320),
391 'pos_print_counter' => array('type' => 'integer', 'label' => 'PrintCount', 'langfile' => 'cashdesk', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => 0, 'position' => 325),
392 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 500),
393 'tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 502),
394 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 506),
395 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModification', 'enabled' => 1, 'visible' => -1, 'notnull' => -1, 'position' => 508),
396 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 510),
397 'fk_user_closing' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 512),
398 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
399 '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')),
400 );
401 // END MODULEBUILDER PROPERTIES
402
406 const TYPE_STANDARD = 0;
407
412
417
421 const TYPE_DEPOSIT = 3;
422
426 const TYPE_PROFORMA = 4;
427
431 const TYPE_SITUATION = 5;
432
436 const STATUS_DRAFT = 0;
437
442
459 const STATUS_CLOSED = 2;
460
467
468
474 public function __construct($db)
475 {
476 $this->db = $db;
477
478 $this->ismultientitymanaged = 1;
479 $this->isextrafieldmanaged = 1;
480
481 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
482 }
483
492 protected function persistFieldValue(User $user, $field)
493 {
494 if ($field == 'ref_client') {
495 return $this->set_ref_client((string) $this->ref_client);
496 }
497
498 return parent::persistFieldValue($user, $field);
499 }
500
512 public function create(User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
513 {
514 global $langs, $conf, $mysoc;
515 $error = 0;
516 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
517 // Clean parameters
518 if (empty($this->type)) {
519 $this->type = self::TYPE_STANDARD;
520 }
521
522 $this->ref_client = trim((string) $this->ref_client); // deprecated
523 $this->ref_customer = trim((string) $this->ref_customer);
524
525 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : '');
526 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private); // deprecated
527 $this->note_public = (isset($this->note_public) ? trim($this->note_public) : '');
528
529 if (!$this->cond_reglement_id) {
530 $this->cond_reglement_id = 0;
531 }
532 if (!$this->mode_reglement_id) {
533 $this->mode_reglement_id = 0;
534 }
535 $this->status = self::STATUS_DRAFT;
536 $this->statut = self::STATUS_DRAFT; // deprecated
537
538 if (!empty($this->multicurrency_code)) {
539 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate of multicurrency_code only if not using original rate)
540 if (empty($this->multicurrency_tx)) {
541 // If original rate is not set, we take a default value from date
542 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
543 } else {
544 // original rate multicurrency_tx and multicurrency_code are already known, so we keep them and we catch only the ID of the currency.
545 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
546 }
547 } else {
548 $this->fk_multicurrency = 0;
549 }
550 if (empty($this->fk_multicurrency)) {
551 $this->multicurrency_code = $conf->currency;
552 $this->fk_multicurrency = 0;
553 $this->multicurrency_tx = 1;
554 }
555 $this->entity = setEntity($this);
556
557 dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
558
559 // Check parameters
560 if (empty($this->date)) {
561 $this->error = "Try to create an invoice with an empty parameter (date)";
562 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
563 return -3;
564 }
565 $soc = new Societe($this->db);
566 $result = $soc->fetch($this->socid);
567 if ($result < 0) {
568 $this->error = "Failed to fetch company: ".$soc->error;
569 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
570 return -2;
571 }
572
573 // A replacement invoice can't replace an invoice already transferred into accounting (checked again on validation)
574 if ($this->type == self::TYPE_REPLACEMENT && $this->fk_facture_source > 0) {
575 $facreplaced = new Facture($this->db);
576 if ($facreplaced->fetch($this->fk_facture_source) > 0 && $facreplaced->getVentilExportCompta() > 0) {
577 $langs->load('bills');
578 $this->error = $langs->trans("ErrorInvoiceReplacedAlreadyInAccountancy", $facreplaced->ref);
579 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
580 return -5;
581 }
582 }
583
584 $now = dol_now();
585 $this->date_creation = $now;
586
587 $this->db->begin();
588
589 $originaldatewhen = null;
590 $nextdatewhen = null;
591 $previousdaynextdatewhen = null;
592
593 $_facrec = null;
594
595 // Erase some properties of the invoice to create with the one of the recurring invoice
596 if ($this->fac_rec > 0) {
597 $this->fk_fac_rec_source = $this->fac_rec;
598
599 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
600 $_facrec = new FactureRec($this->db);
601 $result = $_facrec->fetch($this->fac_rec);
602 $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
603
604 if (getDolGlobalString('MODEL_FAC_REC_AUTHOR')) {
605 // If option MODEL_FAC_REC_AUTHOR is set, we want the same author than the author of recurring invoice instead of current user
606 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
607 }
608
609 // Define some dates
610 $originaldatewhen = $_facrec->date_when;
611 $nextdatewhen = null;
612 $previousdaynextdatewhen = null;
613
614 if ($originaldatewhen) {
615 // date_when is read from database in the timezone of the server (jdate), so delays must be added in this timezone
616 if ($_facrec->rule_for_lines_dates == 'postpaid') { // Bugged feature, should use different variable nameas we store something different.
617 $previousdaynextdatewhen = dol_time_plus_duree($originaldatewhen, -1, 'd', 0, 'tzserver');
618 $originaldatewhen = dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency, 0, 'tzserver');
619 } else {
620 $nextdatewhen = dol_time_plus_duree($originaldatewhen, (int) $_facrec->frequency, $_facrec->unit_frequency, 0, 'tzserver');
621 $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd', 0, 'tzserver');
622 }
623 }
624
625 // Define thirdparty
626 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.
627 $this->socid = $_facrec->socid;
628 }
629
630 // Define the entity
631 $this->entity = $_facrec->entity; // Invoice created in same entity than template
632
633 // Fields coming from GUI.
634 // @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
635 // set by posted page with $object->xxx = ... and this section should be removed.
636 $this->fk_project = GETPOSTINT('projectid') > 0 ? GETPOSTINT('projectid') : $_facrec->fk_project;
637 $this->note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
638 $this->note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
639 $this->model_pdf = GETPOSTISSET('model') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
640 $this->cond_reglement_id = GETPOSTINT('cond_reglement_id') > 0 ? GETPOSTINT('cond_reglement_id') : $_facrec->cond_reglement_id;
641 $this->mode_reglement_id = GETPOSTINT('mode_reglement_id') > 0 ? GETPOSTINT('mode_reglement_id') : $_facrec->mode_reglement_id;
642 $this->fk_account = GETPOST('fk_account') > 0 ? GETPOSTINT('fk_account') : $_facrec->fk_account;
643
644 // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
645 $this->total_ht = $_facrec->total_ht;
646 $this->total_ttc = $_facrec->total_ttc;
647
648 // Fields always coming from template
649 $this->fk_incoterms = $_facrec->fk_incoterms;
650 $this->location_incoterms = $_facrec->location_incoterms;
651
652 // Clean parameters
653 if (!$this->type) {
654 $this->type = self::TYPE_STANDARD;
655 }
656 $this->ref_client = trim($this->ref_client);
657 $this->ref_customer = trim($this->ref_customer);
658 $this->note_public = trim($this->note_public);
659 $this->note_private = trim($this->note_private);
660 $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
661
662 // Use template extra fields as fallback only - form values (already set) take precedence
663 foreach ($_facrec->array_options as $key => $val) {
664 if (!isset($this->array_options[$key]) || $this->array_options[$key] === '') {
665 $this->array_options[$key] = $val;
666 }
667 }
668
669 if (!$this->mode_reglement_id) {
670 $this->mode_reglement_id = 0;
671 }
672 $this->status = self::STATUS_DRAFT;
673 $this->statut = self::STATUS_DRAFT; // deprecated
674
675 $this->linked_objects = $_facrec->linkedObjectsIds;
676 // We do not add link to template invoice or next invoice will be linked to all generated invoices
677 //$this->linked_objects['facturerec'][0] = $this->fac_rec;
678
679 // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
680 if ($_facrec->frequency > 0) {
681 dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
682 if (empty($_facrec->date_when)) {
683 $_facrec->date_when = $now;
684 }
685 $next_date = $_facrec->getNextDate(); // Calculate next date
686
687 $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
688 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
689
690 $result = $_facrec->setNextDate($next_date, 1);
691 }
692
693 // Define lang of customer
694 $outputlangs = $langs;
695 $newlang = '';
696
697 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
698 $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
699 }
700 // @phan-suppress-next-line PhanUndeclaredProperty
701 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
702 $newlang = $this->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
703 }
704 if (!empty($newlang)) {
705 $outputlangs = new Translate("", $conf);
706 $outputlangs->setDefaultLang($newlang);
707 }
708
709 // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
710 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
711 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm', 0, 'tzserver'), '%m');
712 $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
713 $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm', 0, 'tzserver'), '%m');
714 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm', 0, 'tzserver'), '%B');
715 $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
716 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm', 0, 'tzserver'), '%B');
717 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y', 0, 'tzserver'), '%Y');
718 $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
719 $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y', 0, 'tzserver'), '%Y');
720 // Only for template invoice
721 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ? dol_print_date($originaldatewhen, 'dayhour') : '');
722 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ? dol_print_date($nextdatewhen, 'dayhour') : '');
723 $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '');
724 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
725 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
726
727 //var_dump($substitutionarray);exit;
728
729 complete_substitutions_array($substitutionarray, $outputlangs);
730
731 $this->note_public = make_substitutions($this->note_public, $substitutionarray);
732 $this->note_private = make_substitutions($this->note_private, $substitutionarray);
733 }
734
735 // Define due date if not already defined
736 if (empty($forceduedate)) {
737 $duedate = $this->calculate_date_lim_reglement();
738 /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
739 dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
740 return -1;
741 }*/
742 $this->date_lim_reglement = $duedate;
743 } else {
744 $this->date_lim_reglement = $forceduedate;
745 }
746
747 // Insert into database
748 $socid = $this->socid;
749
750 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
751 $sql .= " ref";
752 $sql .= ", entity";
753 $sql .= ", ref_ext";
754 $sql .= ", type";
755 $sql .= ", subtype";
756 $sql .= ", fk_soc";
757 $sql .= ", datec";
758 $sql .= ", datef";
759 $sql .= ", date_pointoftax";
760 $sql .= ", note_private";
761 $sql .= ", note_public";
762 $sql .= ", ref_client";
763 $sql .= ", fk_account";
764 $sql .= ", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
765 $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
766 $sql .= ", fk_input_reason";
767 $sql .= ", situation_cycle_ref, situation_counter, situation_final";
768 $sql .= ", fk_incoterms, location_incoterms";
769 $sql .= ", fk_multicurrency";
770 $sql .= ", multicurrency_code";
771 $sql .= ", multicurrency_tx";
772 $sql .= ", retained_warranty";
773 $sql .= ", retained_warranty_date_limit";
774 $sql .= ", retained_warranty_fk_cond_reglement";
775 $sql .= ", ip";
776 $sql .= ")";
777 $sql .= " VALUES (";
778 $sql .= "'(PROV)'";
779 $sql .= ", ".(int) $this->entity;
780 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
781 $sql .= ", ".((int) $this->type);
782 $sql .= ", ".(isset($this->subtype) ? (int) $this->subtype : "null");
783 $sql .= ", ".((int) $socid);
784 $sql .= ", '".$this->db->idate($this->date_creation)."'";
785 // 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.
786 // So we hope that caller has set the gmt datein ->date to match this.
787 $sql .= ", '".$this->db->idate($this->date)."'";
788 $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
789 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
790 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
791 $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : ($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"));
792 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
793 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
794 $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape((string) $this->pos_source)."'" : "null");
795 $sql .= ", ".(int) $this->pos_print_counter;
796 $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape((string) $this->fk_fac_rec_source)."'" : "null");
797 $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape((string) $this->fk_facture_source)."'" : "null");
798 $sql .= ", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id : "null");
799 $sql .= ", ".($this->fk_project ? (int) $this->fk_project : "null");
800 $sql .= ", ".((int) $this->cond_reglement_id);
801 $sql .= ", ".((int) $this->mode_reglement_id);
802 $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
803 $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
804 $sql .= ", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id : "null");
805 $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape((string) $this->situation_cycle_ref)."'" : "null");
806 $sql .= ", ".($this->situation_counter ? "'".$this->db->escape((string) $this->situation_counter)."'" : "null");
807 $sql .= ", ".($this->situation_final ? (int) $this->situation_final : 0);
808 $sql .= ", ".(int) $this->fk_incoterms;
809 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
810 $sql .= ", ".(int) $this->fk_multicurrency;
811 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
812 $sql .= ", ".(float) $this->multicurrency_tx;
813 $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape((string) $this->retained_warranty));
814 $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
815 $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
816 $sql .= ", ".(!empty($this->ip) ? "'".$this->db->escape($this->ip)."'" : "null");
817 $sql .= ")";
818
819 $resql = $this->db->query($sql);
820 if ($resql) {
821 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
822
823 // Keep author on object so a later call to update() does not reset fk_user_author
824 if ($origin_user_author_id > 0) {
825 $this->user_creation_id = $origin_user_author_id;
826 $this->fk_user_author = $origin_user_author_id;
827 }
828
829 // Update ref with new one
830 $this->ref = '(PROV'.$this->id.')';
831 $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
832
833 $resql = $this->db->query($sql);
834 if (!$resql) {
835 $error++;
836 }
837
838 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
839 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
840 }
841
842 // Add object linked
843 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
844 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
845 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, ...))
846 foreach ($tmp_origin_id as $origin_id) {
847 $ret = $this->add_object_linked($origin, $origin_id);
848 if (!$ret) {
849 $this->error = $this->db->lasterror();
850 $error++;
851 }
852 }
853 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
854 $origin_id = $tmp_origin_id;
855 $ret = $this->add_object_linked($origin, $origin_id);
856 if (!$ret) {
857 $this->error = $this->db->lasterror();
858 $error++;
859 }
860 }
861 }
862 }
863
864 // Propagate contacts
865 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
866 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
867 $originidforcontact = $this->origin_id;
868 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
869 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
870 $exp = new Expedition($this->db);
871 $exp->fetch($this->origin_id);
872 $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
873 if (!empty($exp->linkedObjectsIds['commande']) && is_array($exp->linkedObjectsIds['commande'])) {
874 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
875 $originforcontact = 'commande';
876 if (is_object($value)) {
877 $originidforcontact = $value->id;
878 } else {
879 $originidforcontact = $value;
880 }
881 break; // We take first one
882 }
883 }
884 }
885
886 $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople";
887 $sqlcontact .= " FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
888 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
889
890 $resqlcontact = $this->db->query($sqlcontact);
891 if ($resqlcontact) {
892 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
893 $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
894 }
895 } else {
896 dol_print_error($this->db);
897 }
898 }
899
900 // Insert lines of invoices, if not coming from template invoice, into database
901 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
902 $fk_parent_line = 0;
903
904 dol_syslog("There is ".count($this->lines)." lines into ->lines that are InvoiceLines");
905 foreach ($this->lines as $i => $val) {
906 $newinvoiceline = $this->lines[$i];
907 '@phan-var-force FactureLigne $newinvoiceline';
908
909 $newinvoiceline->context = $this->context;
910
911 $newinvoiceline->fk_facture = $this->id;
912
913 $newinvoiceline->origin = $this->lines[$i]->element;
914 $newinvoiceline->origin_type = $this->lines[$i]->element;
915 $newinvoiceline->origin_id = $this->lines[$i]->id;
916
917 // Auto set date of service ?
918 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
919 $newinvoiceline->date_start = $originaldatewhen;
920 }
921 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
922 $newinvoiceline->date_end = $previousdaynextdatewhen;
923 }
924
925 if ($result >= 0) {
926 // Reset fk_parent_line for no child products and special product
927 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
928 $fk_parent_line = 0;
929 }
930
931 // Complete vat rate with code
932 $vatrate = $newinvoiceline->tva_tx;
933 if ($newinvoiceline->vat_src_code && ! preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
934 $vatrate .= ' ('.$newinvoiceline->vat_src_code.')';
935 }
936
937 $newinvoiceline->fk_parent_line = $fk_parent_line;
938
939 if ($this->type == Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
940 $discount = new DiscountAbsolute($this->db);
941 $discount->fetch($newinvoiceline->fk_remise_except);
942
943 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
944 $newinvoiceline->fk_remise_except = $discountId;
945 }
946
947 // Preserve the original entry mode of the line so the total is computed from the typed value (no rounding drift).
948 $line_price_base_type = $newinvoiceline->getPriceBaseType();
949 $result = $this->addline(
950 $newinvoiceline->desc,
951 (float) $newinvoiceline->subprice,
952 $newinvoiceline->qty,
953 $vatrate,
954 $newinvoiceline->localtax1_tx,
955 $newinvoiceline->localtax2_tx,
956 $newinvoiceline->fk_product,
957 $newinvoiceline->remise_percent,
958 $newinvoiceline->date_start,
959 $newinvoiceline->date_end,
960 $newinvoiceline->fk_code_ventilation,
961 $newinvoiceline->info_bits,
962 $newinvoiceline->fk_remise_except,
963 $line_price_base_type,
964 (float) $newinvoiceline->subprice_ttc,
965 $newinvoiceline->product_type,
966 $newinvoiceline->rang,
967 $newinvoiceline->special_code,
968 $newinvoiceline->element,
969 $newinvoiceline->id,
970 $fk_parent_line,
971 $newinvoiceline->fk_fournprice,
972 $newinvoiceline->pa_ht,
973 $newinvoiceline->label,
974 $newinvoiceline->array_options,
975 $newinvoiceline->situation_percent,
976 $newinvoiceline->fk_prev_id,
977 $newinvoiceline->fk_unit,
978 $newinvoiceline->multicurrency_subprice,
979 $newinvoiceline->ref_ext,
980 1
981 );
982
983 if ($result < 0) {
984 $this->setErrorsFromObject($newinvoiceline);
985 $error++;
986 break;
987 }
988
989 // Defined the new fk_parent_line
990 if ($result > 0 && $newinvoiceline->product_type == 9) {
991 $fk_parent_line = $result;
992 }
993 }
994 }
995 } elseif (!$error && empty($this->fac_rec)) { // If not coming from a template invoice and this->lines is an array of invoice line arrays
996 $fk_parent_line = 0;
997
998 dol_syslog("There is ".count($this->lines)." lines into ->lines as a simple array");
999
1000 // Loop on a copy: addline() appends the inserted lines to $this->lines and uses
1001 // count($this->lines) to shift ranks, so the input lines must not remain in it.
1002 $linestoadd = $this->lines;
1003 $this->lines = array();
1004 foreach ($linestoadd as $i => $val) {
1005 $line = $linestoadd[$i];
1006 '@phan-var-force FactureLigne $line';
1007
1008 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
1009 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
1010 if (!is_object($line)) {
1011 $line = (object) $line;
1012 }
1013
1014 if ($result >= 0) {
1015 // Reset fk_parent_line for no child products and special product
1016 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1017 $fk_parent_line = 0;
1018 }
1019
1020 // Complete vat rate with code
1021 $vatrate = $line->tva_tx;
1022 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
1023 $vatrate .= ' ('.$line->vat_src_code.')';
1024 }
1025
1026 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1027 $originid = $line->origin_id;
1028 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1029 } else { // old but bugged version (we store id of line and type of parent object)
1030 $originid = $line->id;
1031 $origintype = $this->element;
1032 }
1033
1034 // init ref_ext
1035 if (empty($line->ref_ext)) {
1036 $line->ref_ext = '';
1037 }
1038
1039 $result = $this->addline(
1040 $line->desc,
1041 $line->subprice,
1042 $line->qty,
1043 $vatrate,
1044 $line->localtax1_tx,
1045 $line->localtax2_tx,
1046 $line->fk_product,
1047 $line->remise_percent,
1048 $line->date_start,
1049 $line->date_end,
1050 $line->fk_code_ventilation,
1051 $line->info_bits,
1052 $line->fk_remise_except,
1053 'HT',
1054 0,
1055 $line->product_type,
1056 $line->rang,
1057 $line->special_code,
1058 $origintype,
1059 $originid,
1060 $fk_parent_line,
1061 $line->fk_fournprice,
1062 $line->pa_ht,
1063 $line->label,
1064 $line->array_options,
1065 $line->situation_percent,
1066 $line->fk_prev_id,
1067 $line->fk_unit,
1068 $line->multicurrency_subprice,
1069 $line->ref_ext,
1070 1
1071 );
1072 if ($result < 0) {
1073 $this->error = $this->db->lasterror();
1074 dol_print_error($this->db);
1075 $this->db->rollback();
1076 return -1;
1077 }
1078
1079 // Defined the new fk_parent_line
1080 if ($result > 0 && $line->product_type == 9) {
1081 $fk_parent_line = $result;
1082 }
1083 }
1084 }
1085 }
1086
1087 // Insert lines when coming from a template invoice
1088 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1089 dol_syslog("There is ".count($_facrec->lines)." lines from recurring invoice");
1090 $fk_parent_line = 0;
1091
1092 foreach ($_facrec->lines as $i => $val) {
1093 // Reset fk_parent_line for no child products and special product
1094 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1095 $fk_parent_line = 0;
1096 }
1097
1098 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
1099 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1100 if (empty($tva_tx)) {
1101 $tva_npr = 0;
1102 }
1103 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1104 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1105
1106 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1107 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1108
1109 // If buyprice not defined from template invoice, we try to guess the best value
1110 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1111 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1112 $producttmp = new ProductFournisseur($this->db);
1113 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1114
1115 // If margin module defined on costprice, we try the costprice
1116 // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
1117 // else we get the best supplier price
1118 if (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($producttmp->cost_price)) {
1119 $buyprice = $producttmp->cost_price;
1120 } elseif (isModEnabled('stock') && (getDolGlobalString('MARGIN_TYPE') == 'costprice' || getDolGlobalString('MARGIN_TYPE') == 'pmp') && !empty($producttmp->pmp)) {
1121 $buyprice = $producttmp->pmp;
1122 } else {
1123 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1124 if ($producttmp->product_fourn_price_id > 0) {
1125 $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
1126 }
1127 }
1128 }
1129 }
1130
1131 // Update price according to $updatecurrencyrate
1132 if ($updatecurrencyrate == 1) {
1133 // TODO
1134 } elseif ($updatecurrencyrate == 2) {
1135 // TODO
1136 }
1137
1138 $result_insert = $this->addline(
1139 $_facrec->lines[$i]->desc,
1140 $_facrec->lines[$i]->subprice,
1141 $_facrec->lines[$i]->qty,
1142 $tva_tx,
1143 $localtax1_tx,
1144 $localtax2_tx,
1145 $_facrec->lines[$i]->fk_product,
1146 $_facrec->lines[$i]->remise_percent,
1147 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
1148 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
1149 0,
1150 $tva_npr,
1151 0, // fk_remise_except
1152 'HT',
1153 0,
1154 $_facrec->lines[$i]->product_type,
1155 $_facrec->lines[$i]->rang,
1156 $_facrec->lines[$i]->special_code,
1157 '',
1158 0,
1159 $fk_parent_line,
1160 $fk_product_fournisseur_price,
1161 is_null($buyprice) ? '' : $buyprice, // do not use (float) here, it may be ''
1162 $_facrec->lines[$i]->label,
1163 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1164 100, // situation percent is undefined on recurring invoice lines
1165 0, // fk_prev_id
1166 $_facrec->lines[$i]->fk_unit,
1167 $_facrec->lines[$i]->multicurrency_subprice,
1168 $_facrec->lines[$i]->ref_ext,
1169 1
1170 );
1171
1172 foreach ($this->lines as $line) {
1173 if ($line->id == $result_insert) {
1174 $line->extraparams = $_facrec->lines[$i]->extraparams;
1175 $line->setExtraParameters();
1176 }
1177 }
1178
1179 // Defined the new fk_parent_line
1180 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1181 $fk_parent_line = $result_insert;
1182 }
1183
1184 if ($result_insert < 0) {
1185 $error++;
1186 $this->error = $this->db->error();
1187 break;
1188 }
1189 }
1190 }
1191
1192 if (!$error) {
1193 $result = $this->update_price(1, 'auto', 0, $mysoc);
1194 if ($result <= 0) {
1195 $this->error = $langs->trans('FailedToUpdatePrice');
1196 $this->db->rollback();
1197 return -3;
1198 }
1199 }
1200
1201 $action = 'create';
1202
1203 // Actions on extra fields
1204 if (!$error) {
1205 $result = $this->insertExtraFields();
1206 if ($result < 0) {
1207 $error++;
1208 }
1209 }
1210
1211 if (!$error && !$notrigger) {
1212 // Call trigger
1213 $result = $this->call_trigger('BILL_CREATE', $user);
1214 if ($result < 0) {
1215 $error++;
1216 }
1217 }
1218
1219 if (!$error) {
1220 $this->db->commit();
1221 return $this->id;
1222 } else {
1223 $this->db->rollback();
1224 return -4;
1225 }
1226 } else {
1227 $this->error = $this->db->error();
1228 $this->db->rollback();
1229 return -1;
1230 }
1231 }
1232
1233
1241 public function createFromCurrent(User $user, $invertdetail = 0)
1242 {
1243 // Source invoice load
1244 $facture = new Facture($this->db);
1245
1246 // Avoid updating the row ranks
1247 $facture->context['createfromclone'] = 1;
1248
1249 // Retrieve all extrafield
1250 // fetch optionals attributes and labels
1251 // (unless the caller already set array_options, e.g. from a create form, so we don't overwrite them)
1252 if (empty($this->array_options)) {
1253 $this->fetch_optionals();
1254 }
1255
1256 if (!empty($this->array_options)) {
1257 $facture->array_options = $this->array_options;
1258 }
1259
1260 foreach ($this->lines as &$line) {
1261 $line->fetch_optionals(); //fetch extrafields
1262 }
1263
1264 $facture->fk_facture_source = $this->fk_facture_source;
1265 $facture->type = $this->type;
1266 $facture->subtype = $this->subtype;
1267 $facture->socid = $this->socid;
1268 $facture->date = $this->date;
1269 $facture->date_pointoftax = $this->date_pointoftax;
1270 $facture->note_public = $this->note_public;
1271 $facture->note_private = $this->note_private;
1272 $facture->ref_client = $this->ref_client;
1273 $facture->ref_customer = $this->ref_customer;
1274 $facture->model_pdf = $this->model_pdf;
1275 $facture->fk_project = $this->fk_project;
1276 $facture->cond_reglement_id = $this->cond_reglement_id;
1277 $facture->mode_reglement_id = $this->mode_reglement_id;
1278
1279 $facture->origin = $this->origin;
1280 $facture->origin_id = $this->origin_id;
1281 $facture->fk_account = $this->fk_account;
1282
1283 $facture->lines = $this->lines; // Array of lines of invoice
1284 $facture->situation_counter = $this->situation_counter;
1285 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1286 $facture->situation_final = $this->situation_final;
1287
1288 $facture->retained_warranty = $this->retained_warranty;
1289 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1290 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1291
1292 $facture->fk_user_author = $user->id;
1293 $facture->user_creation_id = $user->id;
1294
1295
1296 // Loop on each line of new invoice
1297 foreach ($facture->lines as $i => $tmpline) {
1298 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1299 if ($invertdetail) {
1300 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1301 $facture->lines[$i]->subprice_ttc = -$facture->lines[$i]->subprice_ttc; // Keep the TTC entry mode with the inverted sign so the credit note has no rounding drift.
1302 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1303 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1304 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1305 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1306 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1307 $facture->lines[$i]->ref_ext = '';
1308 }
1309 }
1310
1311 dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1312
1313 $facid = $facture->create($user);
1314 if ($facid <= 0) {
1315 $this->error = $facture->error;
1316 $this->errors = $facture->errors;
1317 } elseif ($this->type == self::TYPE_SITUATION && getDolGlobalString('INVOICE_USE_SITUATION')) {
1318 $this->fetchObjectLinked(null, '', $this->id, 'facture');
1319
1320 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1321 foreach ($Tfk_object as $fk_object) {
1322 $facture->add_object_linked($typeObject, $fk_object);
1323 }
1324 }
1325
1326 $facture->add_object_linked('facture', $this->fk_facture_source);
1327 }
1328
1329 return $facid;
1330 }
1331
1332
1341 public function createFromClone(User $user, $fromid = 0, $forceentity = null)
1342 {
1343 global $hookmanager;
1344
1345 $error = 0;
1346
1347 $object = new Facture($this->db);
1348
1349 $this->db->begin();
1350
1351 $object->fetch($fromid);
1352 // fetch() clears $object->thirdparty, but the subsequent $object->create() path
1353 // reaches addLine() -> getLocalTaxesFromRate() -> get_localtax() and uses the
1354 // buyer thirdparty to decide whether IRPF/localtax2 applies. Without this fetch,
1355 // get_localtax() sees $thirdparty_buyer = null, returns 0 and the cloned lines
1356 // lose their localtax2_tx (see issue #29052).
1357 $object->fetch_thirdparty();
1358
1359 // Load source object
1360 $objFrom = clone $object;
1361
1362 // Change socid if needed
1363 if (!empty($this->socid) && $this->socid != $object->socid) {
1364 $objsoc = new Societe($this->db);
1365
1366 if ($objsoc->fetch($this->socid) > 0) {
1367 $object->socid = $objsoc->id;
1368 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1369 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1370 $object->fk_project = 0;
1371 $object->fk_delivery_address = 0;
1372 }
1373
1374 // TODO Change product price if multi-prices
1375 }
1376
1377 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1378
1379 $object->id = 0;
1380 $object->statut = self::STATUS_DRAFT;
1381 $object->status = self::STATUS_DRAFT;
1382
1383 // Clear fields
1384 $object->date = (empty($this->date) ? dol_now() : $this->date);
1385 $object->user_creation_id = $user->id;
1386 $object->user_validation_id = null;
1387 $object->user_modification_id = null;
1388 $object->fk_user_author = $user->id;
1389 $object->fk_user_valid = null;
1390 $object->fk_facture_source = 0;
1391 $object->fk_fac_rec_source = 0;
1392 $object->date_creation = '';
1393 $object->date_modification = '';
1394 $object->date_validation = '';
1395 $object->ref_client = '';
1396 $object->ref_customer = '';
1397 $object->close_code = '';
1398 $object->close_note = '';
1399 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1400 $object->note_private = '';
1401 $object->note_public = '';
1402 }
1403
1404 // Loop on each line of new invoice
1405 foreach ($object->lines as $i => $line) {
1406 '@phan-var-force FactureLigne $line';
1407 if (($line->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1408 unset($object->lines[$i]);
1409 continue;
1410 }
1411
1412 // Block to update dates of service (month by month only if previously filled and similar to start and end of month)
1413 // If it's a service with start and end dates
1414 if (getDolGlobalString('INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1415 // Get the dates
1416 $start = dol_getdate($line->date_start);
1417 $end = dol_getdate($line->date_end);
1418
1419 // Get the first and last day of the month
1420 $first = dol_get_first_day($start['year'], $start['mon']);
1421 $last = dol_get_last_day($end['year'], $end['mon']);
1422
1423 //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1424 //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1425 // If start date is first date of month and end date is last date of month
1426 if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1427 && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1428 $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1429 $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1430 $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1431 $object->lines[$i]->date_start = $newFirst;
1432 $object->lines[$i]->date_end = $newLast;
1433 }
1434 }
1435
1436 $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1437
1438 // Do not clone accountancy ventilation: a cloned invoice must reappear in "to dispatch" list
1439 $object->lines[$i]->fk_code_ventilation = 0;
1440 }
1441
1442 // Create clone
1443 $object->context['createfromclone'] = 'createfromclone';
1444 $object->context['createfromclone_fromid'] = $objFrom->id;
1445 $object->context['createfromclone_fromref'] = $objFrom->ref;
1446 $result = $object->create($user);
1447
1448 if ($result < 0) {
1449 $error++;
1450 $this->setErrorsFromObject($object);
1451 } else {
1452 // copy internal contacts
1453 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1454 $error++;
1455 $this->setErrorsFromObject($object);
1456 } elseif ($object->socid == $objFrom->socid) {
1457 // copy external contacts if same company
1458 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1459 $error++;
1460 $this->setErrorsFromObject($object);
1461 }
1462 }
1463 }
1464
1465 if (!$error) {
1466 // Hook of thirdparty module
1467 if (is_object($hookmanager)) {
1468 $parameters = array('objFrom' => $objFrom, 'clonedObj' => $object);
1469 $action = '';
1470 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1471 if ($reshook < 0) {
1472 $this->setErrorsFromObject($hookmanager);
1473 $error++;
1474 }
1475 }
1476 }
1477
1478 unset($object->context['createfromclone']);
1479 unset($object->context['createfromclone_fromid']);
1480 unset($object->context['createfromclone_fromref']);
1481
1482 // End
1483 if (!$error) {
1484 $this->db->commit();
1485 return $object->id;
1486 } else {
1487 $this->db->rollback();
1488 return -1;
1489 }
1490 }
1491
1499 public function createFromOrder($object, User $user)
1500 {
1501 global $hookmanager;
1502
1503 $error = 0;
1504
1505 // Closed order
1506 $this->date = dol_now();
1507 $this->source = 0;
1508
1509 // Avoid updating the row ranks
1510 $this->context['createfromclone'] = 1;
1511
1512 $num = count($object->lines);
1513 for ($i = 0; $i < $num; $i++) {
1514 $line = new FactureLigne($this->db);
1515 $src_line = $object->lines[$i];
1516 '@phan-var-force FactureLigne $src_line';
1517 $line->libelle = $src_line->libelle; // deprecated
1518 $line->label = $src_line->label;
1519 $line->desc = $src_line->desc;
1520 $line->subprice = $src_line->subprice;
1521 $line->subprice_ttc = $src_line->subprice_ttc; // Preserve the TTC entry mode so create() keeps the typed value (no rounding drift).
1522 $line->total_ht = $src_line->total_ht;
1523 $line->total_tva = $src_line->total_tva;
1524 $line->total_localtax1 = $src_line->total_localtax1;
1525 $line->total_localtax2 = $src_line->total_localtax2;
1526 $line->total_ttc = $src_line->total_ttc;
1527 $line->vat_src_code = $src_line->vat_src_code;
1528 $line->tva_tx = $src_line->tva_tx;
1529 $line->localtax1_tx = $src_line->localtax1_tx;
1530 $line->localtax2_tx = $src_line->localtax2_tx;
1531 $line->qty = $src_line->qty;
1532 $line->fk_remise_except = $src_line->fk_remise_except;
1533 $line->remise_percent = $src_line->remise_percent;
1534 $line->fk_product = $src_line->fk_product;
1535 $line->info_bits = $src_line->info_bits;
1536 $line->product_type = $src_line->product_type;
1537 $line->rang = $src_line->rang;
1538 $line->special_code = $src_line->special_code;
1539 $line->fk_parent_line = $src_line->fk_parent_line;
1540 $line->fk_unit = $src_line->fk_unit;
1541 $line->date_start = $src_line->date_start;
1542 $line->date_end = $src_line->date_end;
1543
1544 // Multicurrency
1545 $line->fk_multicurrency = $src_line->fk_multicurrency;
1546 $line->multicurrency_code = $src_line->multicurrency_code;
1547 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1548 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1549 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1550 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1551
1552 $line->fk_fournprice = $src_line->fk_fournprice;
1553 $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);
1554 $line->pa_ht = $marginInfos[0];
1555
1556 // get extrafields from original line
1557 $src_line->fetch_optionals();
1558 foreach ($src_line->array_options as $options_key => $value) {
1559 $line->array_options[$options_key] = $value;
1560 }
1561
1562 $this->lines[$i] = $line;
1563 }
1564
1565 $this->socid = $object->socid;
1566 $this->fk_project = $object->fk_project;
1567 $this->fk_account = $object->fk_account;
1568 $this->cond_reglement_id = $object->cond_reglement_id;
1569 $this->mode_reglement_id = $object->mode_reglement_id;
1570 $this->fk_incoterms = $object->fk_incoterms;
1571 $this->location_incoterms = $object->location_incoterms;
1572 $this->availability_id = $object->availability_id;
1573 $this->demand_reason_id = $object->demand_reason_id;
1574 $this->delivery_date = $object->delivery_date;
1575 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1576 $this->contact_id = $object->contact_id;
1577 $this->ref_client = $object->ref_client;
1578 $this->ref_customer = $object->ref_client;
1579
1580 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1581 $this->note_private = $object->note_private;
1582 $this->note_public = $object->note_public;
1583 }
1584
1585 $this->module_source = $object->module_source;
1586 $this->pos_source = $object->pos_source;
1587
1588 $this->origin = $object->element;
1589 $this->origin_type = $object->element;
1590 $this->origin_id = $object->id;
1591
1592 $this->fk_user_author = $user->id;
1593 $this->user_creation_id = $user->id;
1594
1595 // get extrafields from original line
1596 $object->fetch_optionals();
1597 foreach ($object->array_options as $options_key => $value) {
1598 $this->array_options[$options_key] = $value;
1599 }
1600
1601 // Possibility to add external linked objects with hooks
1602 $this->linked_objects[$this->origin] = $this->origin_id;
1603 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1604 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1605 }
1606
1607 $ret = $this->create($user);
1608
1609 if ($ret > 0) {
1610 // Actions hooked (by external module)
1611 $hookmanager->initHooks(array('invoicedao'));
1612
1613 $parameters = array('objFrom' => $object);
1614 $action = '';
1615 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1616 if ($reshook < 0) {
1617 $this->setErrorsFromObject($hookmanager);
1618 $error++;
1619 }
1620 } else {
1621 $error++;
1622 }
1623
1624 unset($this->context['createfromclone']);
1625
1626 if (!$error) {
1627 return 1;
1628 } else {
1629 return -1;
1630 }
1631 }
1632
1641 public function createFromContract($object, User $user, $lines = array())
1642 {
1643 global $hookmanager;
1644
1645 $error = 0;
1646
1647 // Closed order
1648 $this->date = dol_now();
1649 $this->source = 0;
1650
1651 $use_all_lines = empty($lines);
1652 $num = count($object->lines);
1653 for ($i = 0; $i < $num; $i++) {
1654 if (!$use_all_lines && !in_array($object->lines[$i]->id, $lines)) {
1655 continue;
1656 }
1657
1658 $line = new FactureLigne($this->db);
1659
1660 $line->libelle = $object->lines[$i]->libelle; // deprecated
1661 $line->label = $object->lines[$i]->label;
1662 $line->desc = $object->lines[$i]->desc;
1663 $line->subprice = $object->lines[$i]->subprice;
1664 $line->subprice_ttc = $object->lines[$i]->subprice_ttc; // Preserve the TTC entry mode so create() keeps the typed value (no rounding drift).
1665 $line->total_ht = $object->lines[$i]->total_ht;
1666 $line->total_tva = $object->lines[$i]->total_tva;
1667 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1668 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1669 $line->total_ttc = $object->lines[$i]->total_ttc;
1670 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1671 $line->tva_tx = $object->lines[$i]->tva_tx;
1672 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1673 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1674 $line->qty = $object->lines[$i]->qty;
1675 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1676 $line->remise_percent = $object->lines[$i]->remise_percent;
1677 $line->fk_product = $object->lines[$i]->fk_product;
1678 $line->info_bits = $object->lines[$i]->info_bits;
1679 $line->product_type = $object->lines[$i]->product_type;
1680 $line->rang = $object->lines[$i]->rang;
1681 $line->special_code = $object->lines[$i]->special_code;
1682 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1683 $line->fk_unit = $object->lines[$i]->fk_unit;
1684 $line->date_start = $object->lines[$i]->date_start;
1685 $line->date_end = $object->lines[$i]->date_end;
1686
1687 // Multicurrency
1688 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1689 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1690 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1691 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1692 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1693 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1694
1695 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1696 $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);
1697 $line->pa_ht = $marginInfos[0];
1698
1699 // get extrafields from original line
1700 $object->lines[$i]->fetch_optionals();
1701 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1702 $line->array_options[$options_key] = $value;
1703 }
1704
1705 $this->lines[$i] = $line;
1706 }
1707
1708 $this->socid = $object->socid;
1709 $this->fk_project = $object->fk_project;
1710 $this->fk_account = $object->fk_account;
1711 $this->cond_reglement_id = $object->cond_reglement_id;
1712 $this->mode_reglement_id = $object->mode_reglement_id;
1713 //$this->availability_id = $object->availability_id;
1714 $this->demand_reason_id = $object->demand_reason_id;
1715 //$this->delivery_date = $object->delivery_date;
1716 $this->contact_id = $object->contact_id;
1717 $this->ref_customer = $object->ref_customer;
1718 $this->ref_client = $object->ref_customer;
1719
1720 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1721 $this->note_private = $object->note_private;
1722 $this->note_public = $object->note_public;
1723 }
1724
1725 //$this->module_source = $object->module_source;
1726 //$this->pos_source = $object->pos_source;
1727
1728 $this->origin = $object->element;
1729 $this->origin_id = $object->id;
1730
1731 $this->fk_user_author = $user->id;
1732 $this->user_creation_id = $user->id;
1733
1734 // get extrafields from original line
1735 $object->fetch_optionals();
1736 foreach ($object->array_options as $options_key => $value) {
1737 $this->array_options[$options_key] = $value;
1738 }
1739
1740 // Possibility to add external linked objects with hooks
1741 $this->linked_objects[$this->origin] = $this->origin_id;
1742 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1743 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1744 }
1745
1746 $ret = $this->create($user);
1747
1748 if ($ret > 0) {
1749 // Actions hooked (by external module)
1750 $hookmanager->initHooks(array('invoicedao'));
1751
1752 $parameters = array('objFrom' => $object);
1753 $action = '';
1754 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1755 if ($reshook < 0) {
1756 $this->setErrorsFromObject($hookmanager);
1757 $error++;
1758 }
1759
1760 if (!$error) {
1761 return 1;
1762 } else {
1763 return -1;
1764 }
1765 } else {
1766 return -1;
1767 }
1768 }
1769
1782 public static function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1783 {
1784 global $conf, $langs, $hookmanager, $action;
1785
1786 if (! in_array($origin->element, array('propal', 'commande'))) {
1787 $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1788 return null;
1789 }
1790
1791 if (empty($date)) {
1792 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1793 return null;
1794 }
1795
1796 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1797
1798 if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1799 $origin->error = 'ErrorDateIsInFuture';
1800 return null;
1801 }
1802
1803 if ($payment_terms_id <= 0) {
1804 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1805 return null;
1806 }
1807
1808 $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1809
1810 if (empty($payment_conditions_deposit_percent)) {
1811 $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1812 return null;
1813 }
1814
1815 if (empty($origin->deposit_percent)) {
1816 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1817 return null;
1818 }
1819
1820 $deposit = new self($origin->db);
1821 $deposit->socid = $origin->socid;
1822 $deposit->type = self::TYPE_DEPOSIT;
1823 $deposit->fk_project = $origin->fk_project;
1824 $deposit->ref_client = $origin->ref_client;
1825 $deposit->ref_customer = $origin->ref_client;
1826 $deposit->date = $date;
1827 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1828 $deposit->cond_reglement_id = $payment_terms_id;
1829 $deposit->availability_id = $origin->availability_id;
1830 $deposit->demand_reason_id = $origin->demand_reason_id;
1831 $deposit->fk_account = $origin->fk_account;
1832 $deposit->fk_incoterms = $origin->fk_incoterms;
1833 $deposit->location_incoterms = $origin->location_incoterms;
1834 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1835 $deposit->multicurrency_code = $origin->multicurrency_code;
1836 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1837 $deposit->module_source = $origin->module_source;
1838 $deposit->pos_source = $origin->pos_source;
1839 $deposit->model_pdf = 'sponge';
1840
1841 $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1842
1843 if (getDolGlobalString($modelByTypeConfName)) {
1844 $deposit->model_pdf = getDolGlobalString($modelByTypeConfName);
1845 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
1846 $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF');
1847 }
1848
1849 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1850 $deposit->note_private = $origin->note_private;
1851 $deposit->note_public = $origin->note_public;
1852 }
1853
1854 $deposit->origin = $origin->element;
1855 $deposit->origin_type = $origin->element;
1856 $deposit->origin_id = $origin->id;
1857
1858 $origin->fetch_optionals();
1859
1860 foreach ($origin->array_options as $extrakey => $value) {
1861 $deposit->array_options[$extrakey] = $value;
1862 }
1863
1864 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1865
1866 foreach ($overrideFields as $key => $value) {
1867 $deposit->$key = $value;
1868 }
1869
1870 $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1871
1872 $origin->db->begin();
1873
1874 // Facture::create() also imports contact from origin
1875 $createReturn = $deposit->create($user, $notrigger);
1876
1877 if ($createReturn <= 0) {
1878 $origin->db->rollback();
1879 $origin->error = $deposit->error;
1880 $origin->errors = $deposit->errors;
1881 return null;
1882 }
1883
1884 $amount_ttc_diff = 0;
1885 $amountdeposit = array();
1886 $descriptions = array();
1887
1888 // Bucket lines by tva_tx + vat_src_code so addline below receives the rate in
1889 // the "tva (CODE)" format that Facture::addline knows how to parse. Bucketing
1890 // on tva_tx alone wipes out the dictionary Code on the generated deposit line
1891 // and on every downstream document derived from it (see issue #38035).
1892 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1893 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1894
1895 $TTotalByTva = array();
1896 foreach ($origin->lines as &$line) {
1897 if (!empty($line->special_code)) {
1898 continue;
1899 }
1900 $key = $line->tva_tx . ($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
1901 if (!array_key_exists($key, $TTotalByTva)) {
1902 $TTotalByTva[$key] = 0;
1903 $descriptions[$key] = '';
1904 }
1905 $TTotalByTva[$key] += $line->total_ttc;
1906 $descriptions[$key] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1907 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1908 $descriptions[$key] .= $langs->trans('Qty') . ' : ' . $line->qty;
1909 $descriptions[$key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1910 }
1911
1912 foreach ($TTotalByTva as $tva => &$total) {
1913 $tva_rate_only = preg_replace('/\s*\‍(.*\‍)/', '', (string) $tva);
1914 $coef = ($origin->total_ttc != 0 ? $total / $origin->total_ttc : 0); // Calc coef (0 if the total of the origin is 0, there is nothing to split)
1915 $am = $amount * $coef;
1916 $amount_ttc_diff += $am;
1917 if (!isset($amountdeposit[$tva])) {
1918 $amountdeposit[$tva] = 0;
1919 }
1920 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100); // Convert into HT for the addline
1921 }
1922 unset($line, $total); // Break the references, they must not alter $origin->lines or $TTotalByTva later
1923 } else {
1924 $totalamount = 0;
1925 $lines = $origin->lines;
1926 $numlines = count($lines);
1927 for ($i = 0; $i < $numlines; $i++) {
1928 if (empty($lines[$i]->qty)) {
1929 continue; // We discard qty=0, it is an option
1930 }
1931 if (!empty($lines[$i]->special_code)) {
1932 continue; // We discard special_code (frais port, ecotaxe, option, ...)
1933 }
1934
1935 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1936 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ? ' ('.$lines[$i]->vat_src_code.')' : '');
1937 if (!isset($amountdeposit[$tva_key])) {
1938 $amountdeposit[$tva_key] = 0;
1939 $descriptions[$tva_key] = '';
1940 }
1941 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (float) $origin->deposit_percent) / 100;
1942 $descriptions[$tva_key] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1943 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1944 $descriptions[$tva_key] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1945 $descriptions[$tva_key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1946 }
1947
1948 if ($totalamount == 0) {
1949 $amountdeposit[0] = 0;
1950 }
1951
1952 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1953 }
1954
1955 foreach ($amountdeposit as $tva => $amount) {
1956 if (empty($amount)) {
1957 continue;
1958 }
1959
1960 $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1961
1962 // Hidden conf
1963 if (getDolGlobalString('INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1964 $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1965 }
1966
1967 $addlineResult = $deposit->addline(
1968 $descline,
1969 $amount, // subprice
1970 1, // quantity
1971 $tva, // vat rate
1972 0, // localtax1_tx
1973 0, // localtax2_tx
1974 (!getDolGlobalString('INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1975 0, // remise_percent
1976 0, // date_start
1977 0, // date_end
1978 0,
1979 0, // info_bits
1980 0,
1981 'HT',
1982 0,
1983 0, // product_type
1984 1,
1985 0, // special_code
1986 $deposit->origin,
1987 0,
1988 0,
1989 0,
1990 0
1991 //,$langs->trans('Deposit') //Deprecated
1992 );
1993
1994 if ($addlineResult < 0) {
1995 $origin->db->rollback();
1996 $origin->error = $deposit->error;
1997 $origin->errors = $deposit->errors;
1998 return null;
1999 }
2000 }
2001
2002 $diff = $deposit->total_ttc - $amount_ttc_diff;
2003
2004 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && (float) price2num($diff, 'MT') != 0) {
2005 $deposit->fetch_lines();
2006 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
2007
2008 // Pass tva_tx in the "rate (CODE)" form so updateline preserves the vat_src_code
2009 // it received from addline; passing the bare rate would wipe the code.
2010 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ? ' ('.$deposit->lines[0]->vat_src_code.')' : '');
2011 $updatelineResult = $deposit->updateline(
2012 $deposit->lines[0]->id,
2013 $deposit->lines[0]->desc,
2014 $subprice_diff,
2015 $deposit->lines[0]->qty,
2016 $deposit->lines[0]->remise_percent,
2017 $deposit->lines[0]->date_start,
2018 $deposit->lines[0]->date_end,
2019 $tva_tx_with_code,
2020 0,
2021 0,
2022 'HT',
2023 $deposit->lines[0]->info_bits,
2024 $deposit->lines[0]->product_type,
2025 0,
2026 0,
2027 0,
2028 $deposit->lines[0]->pa_ht,
2029 $deposit->lines[0]->label,
2030 0,
2031 array(),
2032 100
2033 );
2034
2035 if ($updatelineResult < 0) {
2036 $origin->db->rollback();
2037 $origin->error = $deposit->error;
2038 $origin->errors = $deposit->errors;
2039 return null;
2040 }
2041 }
2042
2043 $hookmanager->initHooks(array('invoicedao'));
2044
2045 $parameters = array('objFrom' => $origin);
2046 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
2047 // modified by hook
2048 if ($reshook < 0) {
2049 $origin->db->rollback();
2050 $origin->error = $hookmanager->error;
2051 $origin->errors = $hookmanager->errors;
2052 return null;
2053 }
2054
2055 if (!empty($autoValidateDeposit)) {
2056 $validateReturn = $deposit->validate($user, '', 0, $notrigger);
2057
2058 if ($validateReturn < 0) {
2059 $origin->db->rollback();
2060 $origin->error = $deposit->error;
2061 $origin->errors = $deposit->errors;
2062 return null;
2063 }
2064 }
2065
2066 unset($deposit->context['createdepositfromorigin']);
2067
2068 $origin->db->commit();
2069
2070 return $deposit;
2071 }
2072
2080 public function getTooltipContentArray($params)
2081 {
2082 global $conf, $langs, $mysoc, $user;
2083
2084 $langs->load('bills');
2085
2086 $datas = [];
2087 $nofetch = !empty($params['nofetch']);
2088 $moretitle = $params['moretitle'] ?? '';
2089
2090 $picto = $this->picto;
2091 if ($this->type == self::TYPE_REPLACEMENT) {
2092 $picto .= 'r'; // Replacement invoice
2093 }
2094 if ($this->type == self::TYPE_CREDIT_NOTE) {
2095 $picto .= 'a'; // Credit note
2096 }
2097 if ($this->type == self::TYPE_DEPOSIT) {
2098 $picto .= 'd'; // Deposit invoice
2099 }
2100
2101 if ($user->hasRight("facture", "read")) {
2102 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
2103
2104 $datas['picto'] .= '&nbsp;'.$this->getLibType(1);
2105
2106 // Complete datas
2107 if (!empty($params['fromajaxtooltip']) && !isset($this->totalpaid)) {
2108 $this->totalpaid = $this->getSommePaiement(0);
2109 }
2110 if (!empty($params['fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2111 $this->totalcreditnotes = $this->getSumCreditNotesUsed(0);
2112 }
2113 if (!empty($params['fromajaxtooltip']) && !isset($this->totaldeposits)) {
2114 $this->totaldeposits = $this->getSumDepositsUsed(0);
2115 }
2116 if (isset($this->status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2117 $datas['picto'] .= ' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2118 }
2119 if ($moretitle) {
2120 $datas['picto'] .= ' - '.$moretitle;
2121 }
2122 if (!empty($this->ref)) {
2123 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2124 }
2125 if (!$nofetch) {
2126 $langs->load('companies');
2127 if (empty($this->thirdparty)) {
2128 $this->fetch_thirdparty();
2129 }
2130 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2131 }
2132 $datas['RefCustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.(empty($this->ref_customer) ? (empty($this->ref_client) ? '' : $this->ref_client) : $this->ref_customer);
2133 if (!$nofetch) {
2134 $langs->load('project');
2135 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2136 $res = $this->fetchProject();
2137 if ($res > 0 && $this->project instanceof Project) {
2138 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
2139 }
2140 }
2141 }
2142 if (!empty($this->date)) {
2143 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
2144 }
2145 if (!empty($this->total_ht)) {
2146 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2147 }
2148 if (!empty($this->total_tva)) {
2149 $datas['amountvat'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2150 }
2151 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2152 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2153 }
2154 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2155 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
2156 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2157 }
2158 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2159 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2160 }
2161 if (!empty($this->total_ttc)) {
2162 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2163 }
2164 }
2165
2166 return $datas;
2167 }
2168
2183 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
2184 {
2185 global $langs, $conf, $user;
2186
2187 if (!empty($conf->dol_no_mouse_hover)) {
2188 $notooltip = 1; // Force disable tooltips
2189 }
2190
2191 $result = '';
2192
2193 if ($option == 'withdraw') {
2194 $baseurl = DOL_URL_ROOT.'/compta/facture/prelevement.php';
2195 $query = ['facid' => $this->id];
2196 } else {
2197 $baseurl = DOL_URL_ROOT.'/compta/facture/card.php';
2198 $query = ['id' => $this->id];
2199 }
2200
2201 if (!$user->hasRight("facture", "read")) {
2202 $option = 'nolink';
2203 }
2204
2205 if ($option !== 'nolink') {
2206 // Add param to save lastsearch_values or not
2207 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2208 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2209 $add_save_lastsearch_values = 1;
2210 }
2211 if ($add_save_lastsearch_values) {
2212 $query = array_merge($query, ['save_lastsearch_values' => 1]);
2213 }
2214 }
2215 $url = dolBuildUrl($baseurl, $query);
2216
2217 if ($short) {
2218 return $url;
2219 }
2220
2221 $picto = $this->picto;
2222 if ($this->type == self::TYPE_REPLACEMENT) {
2223 $picto .= 'r'; // Replacement invoice
2224 }
2225 if ($this->type == self::TYPE_CREDIT_NOTE) {
2226 $picto .= 'a'; // Credit note
2227 }
2228 if ($this->type == self::TYPE_DEPOSIT) {
2229 $picto .= 'd'; // Deposit invoice
2230 }
2231
2232 $params = [
2233 'id' => $this->id,
2234 'objecttype' => $this->element,
2235 'moretitle' => $moretitle,
2236 'option' => $option,
2237 'nofetch' => 1,
2238 ];
2239 $classfortooltip = 'classfortooltip';
2240 $dataparams = '';
2241 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2242 $classfortooltip = 'classforajaxtooltip';
2243 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2244 $label = '';
2245 } else {
2246 $label = implode($this->getTooltipContentArray($params));
2247 }
2248
2249 $linkclose = ($target ? ' target="'.$target.'"' : '');
2250 if (empty($notooltip) && $user->hasRight("facture", "read")) {
2251 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2252 $label = $langs->trans("Invoice");
2253 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2254 }
2255 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2256 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2257 }
2258
2259 $linkstart = '<a href="'.$url.'"';
2260 $linkstart .= $linkclose.'>';
2261 $linkend = '</a>';
2262
2263 if ($option == 'nolink') {
2264 $linkstart = '';
2265 $linkend = '';
2266 }
2267
2268 $result .= $linkstart;
2269 if ($withpicto) {
2270 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2271 }
2272 if ($withpicto != 2) {
2273 $result .= ($max ? dol_trunc($this->ref, $max) : $this->ref);
2274 }
2275 $result .= $linkend;
2276
2277 if ($addlinktonotes) {
2278 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2279 if ($txttoshow) {
2280 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
2281 $result .= ' <span class="note inline-block">';
2282 $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dolPrintHTMLForAttribute($notetoshow).'">';
2283 $result .= img_picto('', 'note');
2284 $result .= '</a>';
2285 $result .= '</span>';
2286 }
2287 }
2288
2289 global $action, $hookmanager;
2290 $hookmanager->initHooks(array('invoicedao'));
2291 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value' => $save_lastsearch_value, 'target' => $target);
2292 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2293 if ($reshook > 0) {
2294 $result = $hookmanager->resPrint;
2295 } else {
2296 $result .= $hookmanager->resPrint;
2297 }
2298
2299 return $result;
2300 }
2301
2312 public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false)
2313 {
2314 global $conf, $extrafields;
2315
2316 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2317 return -1;
2318 }
2319
2320 $extraFieldsCheck = false;
2321 $doFetchInOneSqlRequest = getDolGlobalInt('MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2322
2323 if ($doFetchInOneSqlRequest) {
2324 // If $extrafields is not a known object, we initialize it
2325 if (!isset($extrafields) || !is_object($extrafields)) {
2326 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2327 $extrafields = new ExtraFields($this->db);
2328 }
2329
2330 // Load array of extrafields for elementype = $this->table_element
2331 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
2332 $extrafields->fetch_name_optionals_label($this->table_element);
2333 }
2334
2335 $extraFieldsCheck = (
2336 !empty($extrafields->attributes[$this->table_element]['label'])
2337 && is_array($extrafields->attributes[$this->table_element]['label'])
2338 && count($extrafields->attributes[$this->table_element]['label']) > 0
2339 );
2340 }
2341
2342
2343 // Original SQL query from fetch()
2344 $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2345 $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2346 $sql .= ', f.datef as df, f.date_pointoftax';
2347 $sql .= ', f.date_lim_reglement as dlr';
2348 $sql .= ', f.datec as datec';
2349 $sql .= ', f.date_valid as datev';
2350 $sql .= ', f.tms as datem';
2351 $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';
2352 $sql .= ", f.fk_input_reason";
2353 $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
2354 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2355 $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2356 $sql .= ', f.fk_account';
2357 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2358 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2359 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2360 $sql .= ', f.fk_incoterms, f.location_incoterms';
2361 $sql .= ', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2362 $sql .= ", i.libelle as label_incoterms";
2363 $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";
2364 $sql .= ", f.payment_reference, f.dispute_status";
2365
2366 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2367 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2368 $type = !empty($extrafields->attributes[$this->table_element]['type'][$key])
2369 ? $extrafields->attributes[$this->table_element]['type'][$key]
2370 : '';
2371
2372 if ($type !== 'separate') {
2373 if (in_array($type, array('point','multipts','linestrg','polygon'))) {
2374 $sql .= ", ST_AsWKT(ef.".$this->db->sanitize($key).") as ".$this->db->sanitize($key);
2375 } else {
2376 $sql .= ", ef.".$this->db->sanitize($key);
2377 }
2378 }
2379 }
2380 }
2381
2382 $sql .= ' FROM '.$this->db->prefix().'facture as f';
2383
2384 // Add extrafields table to the join if we have extrafields for this entity
2385 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2386 // Add LEFT JOIN for extrafields
2387 $sql .= ' LEFT JOIN '.$this->db->prefix().$this->table_element.'_extrafields as ef ON f.rowid = ef.fk_object';
2388 }
2389
2390 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2391 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_paiement as p ON f.fk_mode_reglement = p.id';
2392 $sql .= " LEFT JOIN ".$this->db->prefix()."c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2393 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_incoterms as i ON f.fk_incoterms = i.rowid';
2394
2395 if ($rowid) {
2396 $sql .= " WHERE f.rowid = ".((int) $rowid);
2397 } else {
2398 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
2399 if ($ref) {
2400 $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
2401 }
2402 if ($ref_ext) {
2403 $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
2404 }
2405 }
2406
2407 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2408 $resql = $this->db->query($sql);
2409 if ($resql) {
2410 if ($this->db->num_rows($resql)) {
2411 $obj = $this->db->fetch_object($resql);
2412
2413 $this->id = $obj->rowid;
2414 $this->entity = $obj->entity;
2415
2416 $this->ref = $obj->ref;
2417 $this->ref_client = $obj->ref_client;
2418 $this->ref_customer = $obj->ref_client;
2419 $this->ref_ext = $obj->ref_ext;
2420 $this->type = $obj->type;
2421 $this->subtype = $obj->subtype;
2422 $this->date = $this->db->jdate($obj->df);
2423 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2424 $this->date_creation = $this->db->jdate($obj->datec);
2425 $this->date_validation = $this->db->jdate($obj->datev);
2426 $this->date_modification = $this->db->jdate($obj->datem);
2427 $this->datem = $this->db->jdate($obj->datem);
2428 $this->total_ht = $obj->total_ht;
2429 $this->total_tva = $obj->total_tva;
2430 $this->total_localtax1 = $obj->localtax1;
2431 $this->total_localtax2 = $obj->localtax2;
2432 $this->total_ttc = $obj->total_ttc;
2433 $this->revenuestamp = $obj->revenuestamp;
2434 $this->paye = $obj->paye;
2435 $this->close_code = $obj->close_code;
2436 $this->close_note = $obj->close_note;
2437
2438 $this->socid = $obj->fk_soc;
2439 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2440
2441 $this->fk_project = $obj->fk_project;
2442 $this->project = null; // Clear if another value was already set by fetch_projet
2443
2444 $this->statut = $obj->status; // deprecated
2445 $this->status = $obj->status;
2446
2447 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2448 $this->mode_reglement_id = $obj->fk_mode_reglement;
2449 $this->mode_reglement_code = $obj->mode_reglement_code;
2450 $this->mode_reglement = $obj->mode_reglement_libelle;
2451 $this->cond_reglement_id = $obj->fk_cond_reglement;
2452 $this->cond_reglement_code = $obj->cond_reglement_code;
2453 $this->cond_reglement = $obj->cond_reglement_libelle;
2454 $this->cond_reglement_label = $obj->cond_reglement_libelle;
2455 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2456 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2457 $this->fk_facture_source = $obj->fk_facture_source;
2458 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2459 $this->note = $obj->note_private; // deprecated
2460 $this->note_private = $obj->note_private;
2461 $this->note_public = $obj->note_public;
2462 $this->user_creation_id = $obj->fk_user_author;
2463 $this->user_validation_id = $obj->fk_user_valid;
2464 $this->user_modification_id = $obj->fk_user_modif;
2465 $this->fk_user_author = $obj->fk_user_author;
2466 $this->fk_user_valid = $obj->fk_user_valid;
2467 $this->fk_user_modif = $obj->fk_user_modif;
2468 $this->model_pdf = $obj->model_pdf;
2469 $this->last_main_doc = $obj->last_main_doc;
2470 $this->demand_reason_id = $obj->fk_input_reason;
2471 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2472 $this->situation_counter = $obj->situation_counter;
2473 $this->situation_final = $obj->situation_final;
2474 $this->retained_warranty = $obj->retained_warranty;
2475 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2476 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2477
2478 $this->payment_reference = $obj->payment_reference;
2479 $this->dispute_status = $obj->dispute_status;
2480
2481 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2482
2483 //Incoterms
2484 $this->fk_incoterms = $obj->fk_incoterms;
2485 $this->location_incoterms = $obj->location_incoterms;
2486 $this->label_incoterms = $obj->label_incoterms;
2487
2488 $this->module_source = $obj->module_source;
2489 $this->pos_source = $obj->pos_source;
2490 $this->pos_print_counter = (int) $obj->pos_print_counter;
2491 $this->email_sent_counter = $obj->email_sent_counter;
2492
2493 // Multicurrency
2494 $this->fk_multicurrency = $obj->fk_multicurrency;
2495 $this->multicurrency_code = $obj->multicurrency_code;
2496 $this->multicurrency_tx = $obj->multicurrency_tx;
2497 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2498 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2499 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2500
2501 // Now process extrafields
2502 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2503 $this->array_options = array();
2504
2505 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2506 $type = !empty($extrafields->attributes[$this->table_element]['type'][$key])
2507 ? $extrafields->attributes[$this->table_element]['type'][$key]
2508 : '';
2509
2510 if ($type !== 'separate') {
2511 $rawval = $obj->$key;
2512
2513 // date/datetime
2514 if (in_array($type, array('date', 'datetime'))) {
2515 $this->array_options['options_' . $key] = $this->db->jdate($rawval);
2516 } elseif ($type == 'password') {
2517 if (!empty($rawval) && preg_match('/^dolcrypt:/', $rawval)) {
2518 $this->array_options['options_' . $key] = dolDecrypt($rawval);
2519 } else {
2520 $this->array_options['options_' . $key] = $rawval;
2521 }
2522 } else {
2523 $this->array_options['options_' . $key] = $rawval;
2524 }
2525 }
2526 }
2527
2528 // Champs "computed"
2529 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2530 if (!empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
2531 if (empty($conf->disable_compute)) {
2532 global $objectoffield;
2533 $objectoffield = $this;
2534 $this->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
2535 }
2536 }
2537 }
2538 }
2539
2540 if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2542 }
2543
2544 if (!$doFetchInOneSqlRequest) {
2545 // Retrieve all extrafield
2546 // fetch optionals attributes and labels
2547 $this->fetch_optionals();
2548 }
2549
2550 // Lines
2551 $this->lines = array();
2552
2553 $result = $this->fetch_lines();
2554 if ($result < 0) {
2555 $this->error = $this->db->error();
2556 return -3;
2557 }
2558
2559 $this->db->free($resql);
2560
2561 return 1;
2562 } else {
2563 $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2564
2565 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2566 return 0;
2567 }
2568 } else {
2569 $this->error = $this->db->lasterror();
2570 return -1;
2571 }
2572 }
2573
2574
2575 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2583 public function fetch_lines($only_type_product = '', $loadalsotranslation = 0)
2584 {
2585 global $conf, $extrafields;
2586
2587 // phpcs:enable
2588 $this->lines = array();
2589
2590 $extraFieldsCheck = false;
2591 $doFetchInOneSqlRequest = getDolGlobalInt('MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2592
2593 if ($doFetchInOneSqlRequest) {
2594 // If $extrafields is not a known object, we initialize it
2595 if (!isset($extrafields) || !is_object($extrafields)) {
2596 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2597 $extrafields = new ExtraFields($this->db);
2598 }
2599
2600 // Load array of extrafields for elementype = $this->table_element_line
2601 if (empty($extrafields->attributes[$this->table_element_line]['loaded'])) {
2602 $extrafields->fetch_name_optionals_label($this->table_element_line);
2603 }
2604
2605 $extraFieldsCheck = (
2606 !empty($extrafields->attributes[$this->table_element_line]['label'])
2607 && is_array($extrafields->attributes[$this->table_element_line]['label'])
2608 && count($extrafields->attributes[$this->table_element_line]['label']) > 0
2609 );
2610 }
2611
2612 $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,';
2613 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.subprice_ttc, l.ref_ext,';
2614 $sql .= ' l.situation_percent, l.fk_prev_id,';
2615 $sql .= ' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2616 $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2617 $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,';
2618 $sql .= ' l.fk_unit, l.extraparams,';
2619 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2620 $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';
2621
2622 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2623 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2624 $type = !empty($extrafields->attributes[$this->table_element_line]['type'][$key])
2625 ? $extrafields->attributes[$this->table_element_line]['type'][$key]
2626 : '';
2627
2628 if ($type !== 'separate') {
2629 if (in_array($type, array('point','multipts','linestrg','polygon'))) {
2630 $sql .= ", ST_AsWKT(ef.".$this->db->sanitize($key).") as ".$this->db->sanitize($key);
2631 } else {
2632 $sql .= ", ef.".$this->db->sanitize($key);
2633 }
2634 }
2635 }
2636 }
2637
2638 $sql .= ' FROM '.$this->db->prefix().'facturedet as l';
2639
2640 // Add extrafields table to the join if we have extrafields for this entity
2641 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2642 // Add LEFT JOIN for extrafields
2643 $sql .= ' LEFT JOIN '.$this->db->prefix().$this->table_element_line.'_extrafields as ef ON l.rowid = ef.fk_object';
2644 }
2645
2646 $sql .= ' LEFT JOIN '.$this->db->prefix().'product as p ON l.fk_product = p.rowid';
2647 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2648 if (is_int($only_type_product)) {
2649 $sql .= " AND p.fk_product_type = ".((int) $only_type_product);
2650 }
2651 $sql .= ' ORDER BY l.rang, l.rowid';
2652
2653 dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2654 $result = $this->db->query($sql);
2655 if ($result) {
2656 $num = $this->db->num_rows($result);
2657 $i = 0;
2658 while ($i < $num) {
2659 $objp = $this->db->fetch_object($result);
2660 $line = new FactureLigne($this->db);
2661
2662 $line->id = $objp->rowid;
2663 $line->rowid = $objp->rowid; // deprecated
2664 $line->fk_facture = $objp->fk_facture;
2665 $line->label = $objp->custom_label; // deprecated
2666 $line->desc = $objp->description; // Description line
2667 $line->description = $objp->description; // Description line
2668 $line->product_type = $objp->product_type; // Type of line
2669 $line->ref = $objp->product_ref; // Ref product
2670 $line->product_ref = $objp->product_ref; // Ref product
2671 $line->libelle = $objp->product_label; // deprecated
2672 $line->product_label = $objp->product_label; // Label product
2673 $line->product_barcode = $objp->product_barcode; // Barcode number product
2674 $line->product_desc = $objp->product_desc; // Description product
2675 $line->fk_product_type = $objp->fk_product_type; // Type of product
2676 $line->qty = $objp->qty;
2677 $line->subprice = $objp->subprice;
2678 $line->subprice_ttc = $objp->subprice_ttc;
2679 $line->ref_ext = $objp->ref_ext; // line external ref
2680
2681 $line->vat_src_code = $objp->vat_src_code;
2682 $line->tva_tx = $objp->tva_tx;
2683 $line->localtax1_tx = $objp->localtax1_tx;
2684 $line->localtax2_tx = $objp->localtax2_tx;
2685 $line->localtax1_type = $objp->localtax1_type;
2686 $line->localtax2_type = $objp->localtax2_type;
2687 $line->remise_percent = $objp->remise_percent;
2688 $line->fk_remise_except = $objp->fk_remise_except;
2689 $line->fk_product = $objp->fk_product;
2690 $line->date_start = $this->db->jdate($objp->date_start);
2691 $line->date_end = $this->db->jdate($objp->date_end);
2692 $line->info_bits = $objp->info_bits;
2693 $line->total_ht = $objp->total_ht;
2694 $line->total_tva = $objp->total_tva;
2695 $line->total_localtax1 = $objp->total_localtax1;
2696 $line->total_localtax2 = $objp->total_localtax2;
2697 $line->total_ttc = $objp->total_ttc;
2698
2699 $line->fk_fournprice = $objp->fk_fournprice;
2700 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2701 $line->pa_ht = $marginInfos[0];
2702 $line->marge_tx = (string) $marginInfos[1];
2703 $line->marque_tx = (string) $marginInfos[2];
2704 $line->rang = $objp->rang;
2705 $line->special_code = $objp->special_code;
2706 $line->fk_parent_line = $objp->fk_parent_line;
2707 $line->situation_percent = $objp->situation_percent;
2708 $line->fk_prev_id = $objp->fk_prev_id;
2709 $line->fk_unit = $objp->fk_unit;
2710
2711 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2712
2713 $line->batch = $objp->batch;
2714 $line->fk_warehouse = $objp->fk_warehouse;
2715
2716 // Accountancy
2717 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2718
2719 // Multicurrency
2720 $line->fk_multicurrency = $objp->fk_multicurrency;
2721 $line->multicurrency_code = $objp->multicurrency_code;
2722 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2723 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2724 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2725 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2726
2727 $line->array_options = array();
2728 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2729 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2730 $type = !empty($extrafields->attributes[$this->table_element_line]['type'][$key])
2731 ? $extrafields->attributes[$this->table_element_line]['type'][$key]
2732 : '';
2733
2734 if ($type !== 'separate') {
2735 $rawval = $objp->$key;
2736
2737 // date/datetime
2738 if (in_array($type, array('date', 'datetime'))) {
2739 $line->array_options['options_' . $key] = $this->db->jdate($rawval);
2740 } elseif ($type == 'password') {
2741 if (!empty($rawval) && preg_match('/^dolcrypt:/', $rawval)) {
2742 $line->array_options['options_' . $key] = dolDecrypt($rawval);
2743 } else {
2744 $line->array_options['options_' . $key] = $rawval;
2745 }
2746 } else {
2747 $line->array_options['options_' . $key] = $rawval;
2748 }
2749 }
2750 }
2751
2752 // Champs "computed"
2753 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2754 if (!empty($extrafields->attributes[$this->table_element_line]['computed'][$key])) {
2755 if (empty($conf->disable_compute)) {
2756 global $objectoffield;
2757 $objectoffield = $line;
2758 $line->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element_line]['computed'][$key], 1, 0, '2');
2759 }
2760 }
2761 }
2762 }
2763
2764 if (!$doFetchInOneSqlRequest) {
2765 // Retrieve all extrafield
2766 $line->fetch_optionals();
2767 }
2768
2769 // multilangs
2770 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2771 $tmpproduct = new Product($this->db);
2772 $tmpproduct->fetch($objp->fk_product);
2773 $tmpproduct->getMultiLangs();
2774
2775 $line->multilangs = $tmpproduct->multilangs;
2776 }
2777
2778 $this->lines[$i] = $line;
2779
2780 $i++;
2781 }
2782 $this->db->free($result);
2783 return 1;
2784 } else {
2785 $this->error = $this->db->error();
2786 return -3;
2787 }
2788 }
2789
2797 {
2798 $this->tab_previous_situation_invoice = array();
2799 $this->tab_next_situation_invoice = array();
2800
2801 $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2802 $sql .= " WHERE rowid <> ".((int) $this->id);
2803 $sql .= ' AND entity = '.((int) $this->entity);
2804 $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2805 $sql .= ' ORDER BY situation_counter ASC';
2806
2807 dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2808 $result = $this->db->query($sql);
2809 if ($result && $this->db->num_rows($result) > 0) {
2810 while ($objp = $this->db->fetch_object($result)) {
2811 $invoice = new Facture($this->db);
2812 if ($invoice->fetch($objp->rowid) > 0) {
2813 if ($objp->situation_counter < $this->situation_counter
2814 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2815 ) {
2816 $this->tab_previous_situation_invoice[] = $invoice;
2817 } else {
2818 $this->tab_next_situation_invoice[] = $invoice;
2819 }
2820 }
2821 }
2822 }
2823 }
2824
2832 public function update(User $user, $notrigger = 0)
2833 {
2834 $error = 0;
2835
2836 $this->oldcopy = dol_clone($this, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
2837
2838 // Clean parameters
2839 if (empty($this->type)) {
2840 $this->type = self::TYPE_STANDARD;
2841 }
2842 if (isset($this->subtype)) {
2843 $this->subtype = (int) $this->subtype;
2844 }
2845 if (isset($this->ref)) {
2846 $this->ref = trim($this->ref);
2847 }
2848 if (isset($this->ref_ext)) {
2849 $this->ref_ext = trim($this->ref_ext);
2850 }
2851 if (!empty($this->ref_customer)) {
2852 $this->ref_customer = trim($this->ref_customer);
2853 }
2854 if (isset($this->increment)) {
2855 $this->increment = trim($this->increment);
2856 }
2857 if (isset($this->close_code)) {
2858 $this->close_code = trim($this->close_code);
2859 }
2860 if (isset($this->close_note)) {
2861 $this->close_note = trim($this->close_note);
2862 }
2863 if (isset($this->note) || isset($this->note_private)) {
2864 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2865 }
2866 if (isset($this->note) || isset($this->note_private)) {
2867 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2868 }
2869 if (isset($this->note_public)) {
2870 $this->note_public = trim($this->note_public);
2871 }
2872 if (isset($this->model_pdf)) {
2873 $this->model_pdf = trim($this->model_pdf);
2874 }
2875 if (isset($this->import_key)) {
2876 $this->import_key = trim($this->import_key);
2877 }
2878 if (isset($this->retained_warranty)) {
2879 $this->retained_warranty = (float) $this->retained_warranty;
2880 }
2881 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2882 $this->user_creation_id = $this->fk_user_author;
2883 }
2884 if (!isset($this->user_modification_id) && !empty($user->id)) {
2885 $this->user_modification_id = $user->id;
2886 }
2887 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2888 $this->user_validation_id = $this->fk_user_valid;
2889 }
2890
2891 // The point of tax date of a validated invoice can't be changed
2892 if ($this->checkPointOfTaxNotChanged() < 0) {
2893 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
2894 return -1;
2895 }
2896
2897 // Update request
2898 // TODO Use the invoice->update() method.
2899 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2900 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2901 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2902 $sql .= " type=".(isset($this->type) ? ((int) $this->type) : "null").",";
2903 $sql .= " subtype=".(isset($this->subtype) ? (int) $this->subtype : "null").",";
2904 $sql .= " ref_client=".(!empty($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : (isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null")).",";
2905 $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2906 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
2907 $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2908 $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2909 $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2910 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2911 $sql .= " paye=".(isset($this->paye) ? ((int) $this->paye) : 0).",";
2912 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2913 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2914 $sql .= " total_tva=".((float) $this->total_tva).",";
2915 $sql .= " localtax1=".((float) $this->total_localtax1).",";
2916 $sql .= " localtax2=".((float) $this->total_localtax2).",";
2917 $sql .= " total_ht=".((float) $this->total_ht).",";
2918 $sql .= " total_ttc=".((float) $this->total_ttc).",";
2919 $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? (float) $this->revenuestamp : "null").",";
2920 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
2921 $sql .= " fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) : "null").",";
2922 $sql .= " fk_user_modif=".(!empty($user->id) ? ((int) $user->id) : "null").",";
2923 $sql .= " fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
2924 $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source : "null").",";
2925 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
2926 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
2927 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
2928 $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2929 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2930 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2931 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2932 $sql .= " import_key = ".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2933 $sql .= " module_source = ".(isset($this->module_source) ? "'".$this->db->escape($this->module_source)."'" : "null").",";
2934 $sql .= " pos_source = ".(isset($this->pos_source) ? "'".$this->db->escape($this->pos_source)."'" : "null").",";
2935 $sql .= " pos_print_counter = ".(int) $this->pos_print_counter.",";
2936 $sql .= " situation_cycle_ref = ".(empty($this->situation_cycle_ref) ? "null" : (int) $this->situation_cycle_ref).",";
2937 $sql .= " situation_counter = ".(empty($this->situation_counter) ? "null" : (int) $this->situation_counter).",";
2938 $sql .= " situation_final = ".(empty($this->situation_final) ? "0" : (int) $this->situation_final).",";
2939 $sql .= " retained_warranty = ".(empty($this->retained_warranty) ? "0" : (float) $this->retained_warranty).",";
2940 $sql .= " retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2941 $sql .= " retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement : "null");
2942 $sql .= " WHERE rowid = ".((int) $this->id);
2943
2944 $this->db->begin();
2945
2946 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2947 $resql = $this->db->query($sql);
2948 if (!$resql) {
2949 $error++;
2950 $this->errors[] = "Error ".$this->db->lasterror();
2951 }
2952
2953 if (!$error) {
2954 $result = $this->insertExtraFields();
2955 if ($result < 0) {
2956 $error++;
2957 }
2958 }
2959
2960 if (!$error && !$notrigger) {
2961 // Call trigger
2962 $result = $this->call_trigger('BILL_MODIFY', $user);
2963 if ($result < 0) {
2964 $error++;
2965 }
2966 // End call triggers
2967 }
2968
2969 // Commit or rollback
2970 if ($error) {
2971 foreach ($this->errors as $errmsg) {
2972 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2973 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2974 }
2975 $this->db->rollback();
2976 return -1 * $error;
2977 } else {
2978 $this->db->commit();
2979 return 1;
2980 }
2981 }
2982
2983
2984 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2991 public function insert_discount($idremise)
2992 {
2993 // phpcs:enable
2994 global $langs;
2995
2996 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2997 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2998
2999 $this->db->begin();
3000
3001 $remise = new DiscountAbsolute($this->db);
3002 $result = $remise->fetch($idremise);
3003
3004 if ($result > 0) {
3005 if ($this->socid > 0 && $remise->fk_soc != $this->socid) { // The discount must belong to the thirdparty of the invoice
3006 $this->error = $langs->trans("ErrorDiscountNotSameCompany");
3007 $this->db->rollback();
3008 return -6;
3009 }
3010 if ($remise->fk_facture) { // Protection against multiple submission
3011 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
3012 $this->db->rollback();
3013 return -5;
3014 }
3015
3016 $facligne = new FactureLigne($this->db);
3017 $facligne->fk_facture = $this->id;
3018 $facligne->fk_remise_except = $remise->id;
3019 $facligne->desc = $remise->description; // Description of the invoice line
3020 $facligne->vat_src_code = $remise->vat_src_code;
3021 $facligne->tva_tx = $remise->tva_tx;
3022 $facligne->localtax1_tx = $remise->localtax1_tx;
3023 $facligne->localtax1_type = (int) $remise->localtax1_type;
3024 $facligne->localtax2_tx = $remise->localtax2_tx;
3025 $facligne->localtax2_type = (int) $remise->localtax2_type;
3026 $facligne->subprice = -(float) $remise->total_ht;
3027 $facligne->fk_product = 0; // Predefined Product ID
3028 $facligne->qty = 1;
3029 $facligne->remise_percent = 0;
3030 $facligne->rang = -1;
3031 $facligne->info_bits = 2;
3032
3033 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
3034 $facligne->rang = 1;
3035 $linecount = count($this->lines);
3036 for ($ii = 1; $ii <= $linecount; $ii++) {
3037 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
3038 }
3039 }
3040
3041 // Get buy/cost price of invoice that is source of discount
3042 if ($remise->fk_facture_source > 0) {
3043 $srcinvoice = new Facture($this->db);
3044 $srcinvoice->fetch($remise->fk_facture_source);
3045 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
3046 $formmargin = new FormMargin($this->db);
3047 // A deposit or credit note is converted into one discount per VAT rate, and a discount can be split,
3048 // so keep only the cost of the source lines with the same VAT rate, prorated to the amount of the discount.
3049 $srclinesofvat = array();
3050 foreach ($srcinvoice->lines as $srcline) {
3051 if (price2num($srcline->tva_tx) == price2num($remise->tva_tx)) {
3052 $srclinesofvat[] = $srcline;
3053 }
3054 }
3055 if (count($srclinesofvat) > 0) {
3056 $srcinvoice->lines = $srclinesofvat;
3057 }
3058 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
3059 $facligne->pa_ht = $arraytmp['pa_total'];
3060 if ((float) $arraytmp['pv_total'] != 0 && price2num($arraytmp['pv_total'], 'MT') != price2num(abs((float) $remise->total_ht), 'MT')) {
3061 $facligne->pa_ht = (float) price2num($arraytmp['pa_total'] * abs((float) $remise->total_ht / (float) $arraytmp['pv_total']), 'MU');
3062 }
3063 }
3064
3065 $facligne->total_ht = -(float) $remise->total_ht;
3066 $facligne->total_tva = -(float) $remise->total_tva;
3067 $facligne->total_ttc = -(float) $remise->total_ttc;
3068 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
3069 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
3070
3071 // The discount line must carry the currency of the invoice, like any other line
3072 $facligne->fk_multicurrency = $this->fk_multicurrency;
3073 $facligne->multicurrency_code = $this->multicurrency_code;
3074 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
3075 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
3076 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
3077 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
3078
3079 $lineid = $facligne->insert();
3080 if ($lineid > 0) {
3081 $result = $this->update_price(1);
3082 if ($result > 0) {
3083 // Create link between discount and invoice line
3084 $result = $remise->link_to_invoice($lineid, 0);
3085 if ($result < 0) {
3086 $this->error = $remise->error;
3087 $this->db->rollback();
3088 return -4;
3089 }
3090
3091 $this->db->commit();
3092 return 1;
3093 } else {
3094 $this->error = $facligne->error;
3095 $this->db->rollback();
3096 return -1;
3097 }
3098 } else {
3099 $this->error = $facligne->error;
3100 $this->db->rollback();
3101 return -2;
3102 }
3103 } else {
3104 $this->db->rollback();
3105 return -3;
3106 }
3107 }
3108
3109 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3117 public function set_ref_client($ref_client, $notrigger = 0)
3118 {
3119 // phpcs:enable
3120 global $user;
3121
3122 $error = 0;
3123
3124 $this->db->begin();
3125
3126 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3127 if (empty($ref_client)) {
3128 $sql .= " SET ref_client = NULL";
3129 } else {
3130 $sql .= " SET ref_client = '".$this->db->escape($ref_client)."'";
3131 }
3132 $sql .= " WHERE rowid = ".((int) $this->id);
3133
3134 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
3135 $resql = $this->db->query($sql);
3136 if (!$resql) {
3137 $this->errors[] = $this->db->error();
3138 $error++;
3139 }
3140
3141 if (!$error) {
3142 $this->ref_client = $ref_client; //deprecated
3143 $this->ref_customer = $ref_client;
3144 }
3145
3146 if (!$notrigger && empty($error)) {
3147 // Call trigger
3148 $result = $this->call_trigger('BILL_MODIFY', $user);
3149 if ($result < 0) {
3150 $error++;
3151 }
3152 // End call triggers
3153 }
3154
3155 if (!$error) {
3156 $this->ref_client = $ref_client; //deprecated
3157 $this->ref_customer = $ref_client;
3158
3159 $this->db->commit();
3160 return 1;
3161 } else {
3162 foreach ($this->errors as $errmsg) {
3163 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3164 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3165 }
3166 $this->db->rollback();
3167 return -1 * $error;
3168 }
3169 }
3170
3171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3179 public function setInputReason($inputReasonId, $notrigger = 0)
3180 {
3181 // phpcs:enable
3182 global $user;
3183
3184 $error = 0;
3185
3186 dol_syslog(__METHOD__.' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3187 if ($this->status >= self::STATUS_DRAFT) {
3188 $this->oldcopy = dol_clone($this, 2);
3189 $this->demand_reason_id = $inputReasonId;
3190
3191 $this->db->begin();
3192
3193 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3194 $sql .= " SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId : 'null');
3195 $sql .= " WHERE rowid = ".((int) $this->id);
3196
3197 dol_syslog(__METHOD__, LOG_DEBUG);
3198 $res = $this->db->query($sql);
3199 if (!$res) {
3200 $error++;
3201 $this->error = $this->db->lasterror();
3202 $this->errors[] = $this->error;
3203 }
3204
3205 if (!$error) {
3206 if (!$notrigger) {
3207 // Call trigger
3208 $result = $this->call_trigger('BILL_MODIFY', $user);
3209 if ($result < 0) {
3210 $error++;
3211 }
3212 // End call triggers
3213 }
3214 }
3215
3216 if (!$error) {
3217 $this->db->commit();
3218 } else {
3219 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3220 $this->db->rollback();
3221 dol_syslog(__METHOD__.' Error : '.$this->errorsToString(), LOG_ERR);
3222 }
3223
3224 if (!$error) {
3225 return 1;
3226 } else {
3227 return -1;
3228 }
3229 }
3230
3231 return 0;
3232 }
3233
3242 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3243 {
3244 global $langs, $conf;
3245 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3246
3247 $rowid = $this->id;
3248
3249 dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
3250
3251 // Test to avoid invoice deletion (allowed if draft)
3252 $result = $this->is_erasable();
3253
3254 if ($result <= 0) {
3255 return 0;
3256 }
3257
3258 // Block deletion of validated credit notes that have consumed deposit credits (draft can still be deleted: credits consumed only on validate)
3259 if ($this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0 && $this->status != self::STATUS_DRAFT) {
3260 $srcInvoice = new Facture($this->db);
3261 if ($srcInvoice->fetch($this->fk_facture_source) > 0 && $srcInvoice->type == self::TYPE_DEPOSIT) {
3262 $langs->load('bills');
3263 $this->error = $langs->trans('CreditNoteOnDepositCantBeDeleted');
3264 return -1;
3265 }
3266 }
3267
3268 $error = 0;
3269
3270 $this->db->begin();
3271
3272 if (!$error && !$notrigger) {
3273 // Call trigger
3274 $result = $this->call_trigger('BILL_DELETE', $user);
3275 if ($result < 0) {
3276 $error++;
3277 }
3278 // End call triggers
3279 }
3280
3281 // Remove linked categories.
3282 if (!$error) {
3283 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_invoice";
3284 $sql .= " WHERE fk_invoice = ".((int) $this->id);
3285
3286 $result = $this->db->query($sql);
3287 if (!$result) {
3288 $error++;
3289 $this->errors[] = $this->db->lasterror();
3290 }
3291 }
3292
3293 // Removed extrafields
3294 if (!$error) {
3295 $result = $this->deleteExtraFields();
3296 if ($result < 0) {
3297 $error++;
3298 dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
3299 }
3300 }
3301
3302 if (!$error) {
3303 // Delete linked object
3304 $res = $this->deleteObjectLinked();
3305 if ($res < 0) {
3306 $error++;
3307 }
3308 }
3309
3310 if (!$error) {
3311 // If invoice was converted into a discount not yet consumed, we remove discount
3312 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
3313 $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
3314 $sql .= ' AND fk_facture_line IS NULL';
3315 $resql = $this->db->query($sql);
3316
3317 // If invoice has consumed discounts
3318 $this->fetch_lines();
3319 $list_rowid_det = array();
3320 foreach ($this->lines as $key => $invoiceline) {
3321 $list_rowid_det[] = $invoiceline->id;
3322 }
3323
3324 // Consumed discounts are freed
3325 if (count($list_rowid_det)) {
3326 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3327 $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
3328 $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
3329
3330 if (!$this->db->query($sql)) {
3331 $this->error = $this->db->error()." sql=".$sql;
3332 $this->errors[] = $this->error;
3333 $this->db->rollback();
3334 return -5;
3335 }
3336 }
3337
3338 // Remove other links to the deleted invoice
3339
3340 $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
3341 $sql .= ' SET fk_invoice = NULL';
3342 $sql .= ' WHERE fk_invoice = '.((int) $rowid);
3343
3344 if (!$this->db->query($sql)) {
3345 $this->error = $this->db->error()." sql=".$sql;
3346 $this->errors[] = $this->error;
3347 $this->db->rollback();
3348 return -5;
3349 }
3350
3351 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
3352 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
3353 $sql .= ' WHERE invoice_id = '.((int) $rowid);
3354
3355 if (!$this->db->query($sql)) {
3356 $this->error = $this->db->error()." sql=".$sql;
3357 $this->errors[] = $this->error;
3358 $this->db->rollback();
3359 return -5;
3360 }
3361
3362 // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
3363 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
3364 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3365 $langs->load("agenda");
3366
3367 $num = count($this->lines);
3368 for ($i = 0; $i < $num; $i++) {
3369 if ($this->lines[$i]->fk_product > 0) {
3370 $mouvP = new MouvementStock($this->db);
3371 $mouvP->origin = &$this;
3372 $mouvP->setOrigin($this->element, $this->id);
3373 // We decrease stock for product
3374 if ($this->type == self::TYPE_CREDIT_NOTE) {
3375 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv("InvoiceDeleteDolibarr", $this->ref));
3376 } else {
3377 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
3378 }
3379 }
3380 }
3381 }
3382
3383 // Invoice line extrafields
3384 $sql_main_table = MAIN_DB_PREFIX.'facturedet';
3385 $sql_ef_table = $sql_main_table."_extrafields";
3386 $sqlef = "DELETE FROM ".$sql_ef_table." WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table." WHERE fk_facture = ".((int) $rowid).")";
3387 // Delete invoice line
3388 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
3389
3390 if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact() >= 0) {
3391 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
3392
3393 $resql = $this->db->query($sql);
3394 if ($resql) {
3395 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
3396 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3397 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3398
3399 // On efface le repertoire de pdf provisoire
3400 $ref = dol_sanitizeFileName($this->ref);
3401 if ($conf->facture->dir_output && !empty($this->ref)) {
3402 $dir = $conf->facture->dir_output."/".$ref;
3403 $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
3404 if (file_exists($file)) { // We must delete all files before deleting directory
3405 $ret = dol_delete_preview($this);
3406
3407 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
3408 $langs->load("errors");
3409 $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
3410 $this->errors[] = $this->error;
3411 $this->db->rollback();
3412 return 0;
3413 }
3414 }
3415 if (file_exists($dir)) {
3416 if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
3417 $langs->load("errors");
3418 $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
3419 $this->errors[] = $this->error;
3420 $this->db->rollback();
3421 return 0;
3422 }
3423 }
3424 }
3425
3426 $this->db->commit();
3427 return 1;
3428 } else {
3429 $this->error = $this->db->lasterror()." sql=".$sql;
3430 $this->errors[] = $this->error;
3431 $this->db->rollback();
3432 return -6;
3433 }
3434 } else {
3435 $this->error = $this->db->lasterror()." sql=".$sql;
3436 $this->errors[] = $this->error;
3437 $this->db->rollback();
3438 return -4;
3439 }
3440 } else {
3441 $this->db->rollback();
3442 return -2;
3443 }
3444 }
3445
3446 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3458 public function set_paid($user, $close_code = '', $close_note = '')
3459 {
3460 // phpcs:enable
3461 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3462 return $this->setPaid($user, $close_code, $close_note);
3463 }
3464
3475 public function setPaid($user, $close_code = '', $close_note = '')
3476 {
3477 $error = 0;
3478
3479 if ($this->paye != 1 || $this->status != self::STATUS_CLOSED) {
3480 $this->db->begin();
3481
3482 $now = dol_now();
3483
3484 dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
3485
3486 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3487 $sql .= ' fk_statut = '.self::STATUS_CLOSED;
3488 if (!$close_code) {
3489 $sql .= ', paye = 1';
3490 }
3491 if ($close_code) {
3492 $sql .= ", close_code = '".$this->db->escape($close_code)."'";
3493 }
3494 if ($close_note) {
3495 $sql .= ", close_note = '".$this->db->escape($close_note)."'";
3496 }
3497 $sql .= ', fk_user_closing = '.((int) $user->id);
3498 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3499 $sql .= " WHERE rowid = ".((int) $this->id);
3500
3501 $resql = $this->db->query($sql);
3502 if ($resql) {
3503 // Call trigger
3504 $result = $this->call_trigger('BILL_PAYED', $user);
3505 if ($result < 0) {
3506 $error++;
3507 }
3508 // End call triggers
3509 } else {
3510 $error++;
3511 $this->error = $this->db->lasterror();
3512 }
3513
3514 if (!$error) {
3515 $this->paye = 1;
3516 $this->status = self::STATUS_CLOSED;
3517 $this->db->commit();
3518 return 1;
3519 } else {
3520 $this->db->rollback();
3521 return -1;
3522 }
3523 } else {
3524 return 0;
3525 }
3526 }
3527
3528
3529 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3540 public function set_unpaid($user)
3541 {
3542 // phpcs:enable
3543 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3544 return $this->setUnpaid($user);
3545 }
3546
3555 public function setUnpaid($user)
3556 {
3557 $error = 0;
3558
3559 $this->db->begin();
3560
3561 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3562 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
3563 $sql .= ' date_closing=null,';
3564 $sql .= ' fk_user_closing=null';
3565 $sql .= " WHERE rowid = ".((int) $this->id);
3566
3567 dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
3568 $resql = $this->db->query($sql);
3569 if ($resql) {
3570 // Call trigger
3571 $result = $this->call_trigger('BILL_UNPAYED', $user);
3572 if ($result < 0) {
3573 $error++;
3574 }
3575 // End call triggers
3576 } else {
3577 $error++;
3578 $this->error = $this->db->error();
3579 dol_print_error($this->db);
3580 }
3581
3582 if (!$error) {
3583 $this->db->commit();
3584 return 1;
3585 } else {
3586 $this->db->rollback();
3587 return -1;
3588 }
3589 }
3590
3591
3592 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3605 public function set_canceled($user, $close_code = '', $close_note = '')
3606 {
3607 // phpcs:enable
3608 dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3609 return $this->setCanceled($user, $close_code, $close_note);
3610 }
3611
3622 public function setCanceled($user, $close_code = '', $close_note = '')
3623 {
3624 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
3625
3626 $this->db->begin();
3627 $now = dol_now();
3628
3629 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3630 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
3631 if ($close_code) {
3632 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3633 }
3634 if ($close_note) {
3635 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3636 }
3637 $sql .= ', fk_user_closing = '.((int) $user->id);
3638 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3639 $sql .= " WHERE rowid = ".((int) $this->id);
3640
3641 $resql = $this->db->query($sql);
3642 if ($resql) {
3643 // Bound discounts are deducted from the invoice
3644 // as they have not been used since the invoice is abandoned.
3645 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3646 $sql .= ' SET fk_facture = NULL';
3647 $sql .= ' WHERE fk_facture = '.((int) $this->id);
3648
3649 $resql = $this->db->query($sql);
3650 if ($resql) {
3651 // Call trigger
3652 $result = $this->call_trigger('BILL_CANCEL', $user);
3653 if ($result < 0) {
3654 $this->db->rollback();
3655 return -1;
3656 }
3657 // End call triggers
3658
3659 $this->db->commit();
3660 return 1;
3661 } else {
3662 $this->error = $this->db->error()." sql=".$sql;
3663 $this->db->rollback();
3664 return -1;
3665 }
3666 } else {
3667 $this->error = $this->db->error()." sql=".$sql;
3668 $this->db->rollback();
3669 return -2;
3670 }
3671 }
3672
3685 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3686 {
3687 global $conf, $langs, $mysoc;
3688 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3689
3690 $productStatic = null;
3691 $warehouseStatic = null;
3692 $productbatch = null;
3693 if ($batch_rule > 0) {
3694 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3695 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3696 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3697 $productStatic = new Product($this->db);
3698 $warehouseStatic = new Entrepot($this->db);
3699 $productbatch = new Productbatch($this->db);
3700 }
3701
3702 $now = dol_now();
3703
3704 $error = 0;
3705 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3706
3707 // Force to have object complete for checks
3708 $this->fetch_thirdparty();
3709 $this->fetch_lines();
3710
3711 // Check parameters
3712 if ($this->status != self::STATUS_DRAFT) {
3713 dol_syslog(get_class($this)."::validate Current status is not draft. operation canceled.", LOG_WARNING);
3714 return 0;
3715 }
3716 if (count($this->lines) <= 0) {
3717 $langs->load("errors");
3718 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3719 return -1;
3720 }
3721 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'creer'))
3722 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'invoice_advance', 'validate'))) {
3723 $this->error = 'Permission denied';
3724 dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS=' . getDolGlobalString('MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3725 return -1;
3726 }
3727 if ((preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) && // empty should not happened, but when it occurs, the test save life
3728 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
3729 ) {
3730 $this->date = dol_now();
3731 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3732 }
3733 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
3734 $last_of_type = $this->willBeLastOfSameType(true);
3735 if (!$last_of_type[0]) {
3736 $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3737 return -1;
3738 }
3739 }
3740 // Point of tax date mandatory (not for a deposit invoice: nothing is supplied yet)
3741 if (getDolGlobalString('INVOICE_POINTOFTAX_DATE') && getDolGlobalString('INVOICE_POINTOFTAX_DATE_MANDATORY') && $this->type != self::TYPE_DEPOSIT && empty($this->date_pointoftax)) {
3742 $langs->loadLangs(array("errors", "bills"));
3743 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePointOfTax")).' ('.$langs->trans("ForbiddenBySetupRules").')';
3744 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3745 return -1;
3746 }
3747
3748 // Check for mandatory fields in thirdparty (defined into setup)
3749 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3750 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER');
3751 foreach ($array_to_check as $key) {
3752 $keymin = strtolower($key);
3753 if (!property_exists($this->thirdparty, $keymin)) {
3754 continue;
3755 }
3756 $vallabel = $this->thirdparty->$keymin;
3757
3758 $i = (int) preg_replace('/[^0-9]/', '', $key);
3759 if ($i > 0) {
3760 if ($this->thirdparty->isACompany()) {
3761 // Check for mandatory prof id (but only if country is other than ours)
3762 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3763 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3764 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
3765 $langs->load("errors");
3766 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3767 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3768 return -1;
3769 }
3770 }
3771 }
3772 } else {
3773 if ($key == 'EMAIL') {
3774 // Check for mandatory
3775 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
3776 $langs->load("errors");
3777 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3778 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3779 return -1;
3780 }
3781 }
3782 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3783 // Check for mandatory
3784 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3785 $langs->load("errors");
3786 $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3787 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3788 return -1;
3789 }
3790 }
3791 if ($key == 'TVA_INTRA') {
3792 // Check for mandatory vat number
3793 if (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') == 'eeconly') {
3794 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3795 $langs->load("errors");
3796 $this->error = $langs->trans('ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3797 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3798 return -1;
3799 }
3800 } elseif (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3801 $langs->load("errors");
3802 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3803 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3804 return -1;
3805 }
3806 }
3807 }
3808 }
3809 }
3810
3811 // Check for mandatory fields in $this
3812 $array_to_check = array('REF_CLIENT' => 'RefCustomer');
3813 foreach ($array_to_check as $key => $val) {
3814 $keymin = strtolower($key);
3815 $vallabel = $this->$keymin;
3816
3817 // Check for mandatory
3818 $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3819 if (!$vallabel && getDolGlobalString($keymandatory)) {
3820 $langs->load("errors");
3821 $error++;
3822 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3823 }
3824 }
3825
3826 // Cap check: credit note on deposit must not exceed available deposit credit
3827 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3828 $srcCheckInv = new Facture($this->db);
3829 if ($srcCheckInv->fetch($this->fk_facture_source) > 0 && $srcCheckInv->type == self::TYPE_DEPOSIT) {
3830 $sqlcap = 'SELECT COALESCE(SUM(amount_ttc),0) as avail FROM '.MAIN_DB_PREFIX.'societe_remise_except WHERE fk_facture_source='.((int) $this->fk_facture_source).' AND fk_facture IS NULL AND fk_facture_line IS NULL';
3831 $rescap = $this->db->query($sqlcap);
3832 if ($rescap) {
3833 $available_ttc = (float) $this->db->fetch_object($rescap)->avail;
3834 if (price2num(abs((float) $this->total_ttc), 'MT') > price2num($available_ttc, 'MT')) {
3835 $langs->load('bills');
3836 $this->error = $langs->trans('CreditNoteExceedsDepositCredit', price($available_ttc));
3837 return -1;
3838 }
3839 }
3840 }
3841 }
3842
3843 $this->db->begin();
3844
3845 // Check parameters
3846 if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3847 // Check that source invoice is known
3848 if ($this->fk_facture_source <= 0) {
3849 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3850 $this->db->rollback();
3851 return -10;
3852 }
3853
3854 // Load source invoice that has been replaced
3855 $facreplaced = new Facture($this->db);
3856 $result = $facreplaced->fetch($this->fk_facture_source);
3857 if ($result <= 0) {
3858 $this->error = $langs->trans("ErrorBadInvoice");
3859 $this->db->rollback();
3860 return -11;
3861 }
3862
3863 // Check that source invoice not already replaced by another one.
3864 $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3865 if ($idreplacement && $idreplacement != $this->id) {
3866 $facreplacement = new Facture($this->db);
3867 $facreplacement->fetch($idreplacement);
3868 $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3869 $this->db->rollback();
3870 return -12;
3871 }
3872
3873 // Check that source invoice is not already transferred into accounting: its entries would remain and the
3874 // replacement invoice would be transferred too.
3875 if ($facreplaced->getVentilExportCompta() > 0) {
3876 $this->error = $langs->trans("ErrorInvoiceReplacedAlreadyInAccountancy", $facreplaced->ref);
3877 $this->db->rollback();
3878 return -14;
3879 }
3880
3881 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3882 if ($result < 0) {
3883 $this->error = $facreplaced->error;
3884 $this->db->rollback();
3885 return -13;
3886 }
3887 }
3888
3889 // Define new ref
3890 if ($force_number) {
3891 $num = $force_number;
3892 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3893 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3894 $this->date = dol_now();
3895 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3896 }
3897 $num = $this->getNextNumRef($this->thirdparty);
3898 } else {
3899 $num = (string) $this->ref;
3900 }
3901
3902 if (!$num) {
3903 $error++;
3904 } else {
3905 $this->oldref = $this->ref;
3906 $this->newref = dol_sanitizeFileName($num);
3907 }
3908
3909 if (!$error) {
3910 $this->update_price(1);
3911
3912 // Validate
3913 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3914 $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)."'";
3915 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3916 $sql .= ", datef='".$this->db->idate($this->date)."'";
3917 $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3918 }
3919 $sql .= " WHERE rowid = ".((int) $this->id);
3920
3921 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3922 $resql = $this->db->query($sql);
3923 if (!$resql) {
3924 $this->error = $this->db->lasterror();
3925 $error++;
3926 }
3927 }
3928
3929 if (!$error) {
3930 // Define third party as a customer
3931 $result = $this->thirdparty->setAsCustomer();
3932
3933 // If active (STOCK_CALCULATE_ON_BILL), we decrement the main product and its components at invoice validation
3934 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3935 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3936 $langs->load("agenda");
3937
3938 // Loop on each line
3939 $cpt = count($this->lines);
3940 for ($i = 0; $i < $cpt; $i++) {
3941 if ($this->lines[$i]->fk_product > 0) {
3942 $mouvP = new MouvementStock($this->db);
3943 $mouvP->origin = &$this; // deprecated
3944 $mouvP->setOrigin($this->element, $this->id);
3945
3946 // We decrease stock for product
3947 if ($this->type == self::TYPE_CREDIT_NOTE) {
3948 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3949 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3950 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("InvoiceValidatedInDolibarr", $num), '', '', $this->lines[$i]->batch);
3951 if ($result < 0) {
3952 $error++;
3953 $this->setErrorsFromObject($mouvP);
3954 }
3955 } else {
3956 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3957 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3958
3959 $is_batch_line = false;
3960 if ($batch_rule > 0) {
3961 $productStatic->fetch($this->lines[$i]->fk_product);
3962 if ($productStatic->hasbatch() && is_object($productbatch)) {
3963 $is_batch_line = true;
3964 $product_qty_remain = $this->lines[$i]->qty;
3965
3966 $sortfield = '';
3967 $sortorder = '';
3968 // find lot/serial by sellby (DLC) and eatby dates (DLUO) first
3970 $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3971 $sortorder = 'ASC,ASC,ASC,ASC';
3972 }
3973
3974 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 : null), $sortfield, $sortorder);
3975 if (!is_array($resBatchList)) {
3976 $error++;
3977 $this->error = $this->db->lasterror();
3978 }
3979
3980 if (!$error) {
3981 $batchList = $resBatchList;
3982 if (empty($batchList)) {
3983 $error++;
3984 $langs->load('errors');
3985 $warehouseStatic->fetch($idwarehouse);
3986 $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3987 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3988 }
3989
3990 foreach ($batchList as $batch) {
3991 if ($batch->qty <= 0) {
3992 continue; // try to decrement only batches have positive quantity first
3993 }
3994
3995 // enough quantity in this batch
3996 if ($batch->qty >= $product_qty_remain) {
3997 $product_batch_qty = $product_qty_remain;
3998 } else {
3999 // not enough (take all in batch)
4000 $product_batch_qty = $batch->qty;
4001 }
4002 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
4003 if ($result < 0) {
4004 $error++;
4005 $this->setErrorsFromObject($mouvP);
4006 break;
4007 }
4008
4009 $product_qty_remain -= $product_batch_qty;
4010 // all product quantity was decremented
4011 if ($product_qty_remain <= 0) {
4012 break;
4013 }
4014 }
4015
4016 if (!$error && $product_qty_remain > 0) {
4017 if (getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER')) {
4018 $error++;
4019 $langs->load('errors');
4020 $warehouseStatic->fetch($idwarehouse);
4021 $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
4022 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
4023 } else {
4024 // take in the first batch
4025 $batch = $batchList[0];
4026 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
4027 if ($result < 0) {
4028 $error++;
4029 $this->setErrorsFromObject($mouvP);
4030 }
4031 }
4032 }
4033 }
4034 }
4035 }
4036
4037 if (!$is_batch_line) { // If stock move not yet processed
4038 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv("InvoiceValidatedInDolibarr", $num));
4039 if ($result < 0) {
4040 $error++;
4041 $this->setErrorsFromObject($mouvP);
4042 }
4043 }
4044 }
4045 }
4046 }
4047 }
4048
4049 /*
4050 * 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%)
4051 * So we can continue to create new invoice situation
4052 */
4053 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
4054 $invoice_situation = new Facture($this->db);
4055 $result = $invoice_situation->fetch($this->fk_facture_source);
4056 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
4057 $invoice_situation->situation_final = 0;
4058 // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
4059 $result = $invoice_situation->setFinal($user, 1);
4060 }
4061 if ($result < 0) {
4062 $this->error = $invoice_situation->error;
4063 $this->errors = array_merge($this->errors, $invoice_situation->errors);
4064 $error++;
4065 }
4066 }
4067
4068 // If credit note on a deposit invoice, consume unused deposit credit up to credit note TTC amount
4069 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
4070 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
4071 $depositInvoice = new Facture($this->db);
4072 if ($depositInvoice->fetch($this->fk_facture_source) > 0 && $depositInvoice->type == self::TYPE_DEPOSIT) {
4073 if ($this->consumeDepositCredits($user, $depositInvoice, abs((float) $this->total_ttc)) < 0) {
4074 $error++;
4075 }
4076 }
4077 }
4078
4079 // Trigger calls
4080 if (!$error && !$notrigger) {
4081 // Call trigger
4082 $result = $this->call_trigger('BILL_VALIDATE', $user);
4083 if ($result < 0) {
4084 $error++;
4085 }
4086 // End call triggers
4087 }
4088
4089 if (!$error) {
4090 // Rename directory in index entry if dir was a temporary ref
4091 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
4092 // Now we rename also files into index
4093 $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)."'";
4094 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".(int) $conf->entity;
4095 $resql = $this->db->query($sql);
4096 if (!$resql) {
4097 $error++;
4098 $this->error = $this->db->lasterror();
4099 }
4100 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'facture/".$this->db->escape($this->newref)."'";
4101 $sql .= " WHERE filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".(int) $conf->entity;
4102 $resql = $this->db->query($sql);
4103 if (!$resql) {
4104 $error++;
4105 $this->error = $this->db->lasterror();
4106 }
4107 }
4108 }
4109
4110 if (!$error && !$this->is_last_in_cycle()) {
4111 $resupdatenext = $this->updatePriceNextInvoice($langs);
4112 if (!$resupdatenext) {
4113 $error++;
4114 }
4115 }
4116
4117 // Set new ref and define current status
4118 if (!$error) {
4119 $this->ref = $num;
4120 $this->statut = self::STATUS_VALIDATED; // deprecated
4122 $this->date_validation = $now;
4123
4124 // Generate the structured payment reference, see core/lib/paymentref.lib.php.
4125 // Done here because the definitive ref and the validated status are both
4126 // needed to build it.
4127 if (getDolGlobalString('INVOICE_PAYMENT_REF_MODE')) {
4128 include_once DOL_DOCUMENT_ROOT.'/core/lib/paymentref.lib.php';
4129 dolPayRefGenerateForInvoice($this, $user, 1);
4130 }
4131
4132 $i = 0;
4133
4134 if (getDolGlobalInt('INVOICE_USE_SITUATION')) {
4135 $final = true;
4136 $nboflines = count($this->lines);
4137 while (($i < $nboflines) && $final) {
4138 $line = $this->lines[$i];
4139 '@phan-var-force FactureLigne $line';
4140 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
4141 $final = ($line->situation_percent == 100);
4142 } else {
4143 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
4144 $current_progress = (float) $line->situation_percent;
4145 $full_progress = $previousprogress + $current_progress;
4146 $final = ($full_progress == 100);
4147 }
4148 $i++;
4149 }
4150
4151 if (!$final) {
4152 if ($this->situation_final) {
4153 // If we must change situation_final
4154 $this->situation_final = 0;
4155 $this->setFinal($user, 1); // Trigger is disabled, already run by the validate
4156 }
4157 } else {
4158 if (!$this->situation_final) {
4159 // If we must change situation_final
4160 $this->situation_final = 1;
4161 $this->setFinal($user, 1); // Trigger is disabled, already run by the validate
4162 }
4163 }
4164 }
4165 }
4166 }
4167
4168 // All database actions are now complete
4169 // We rename the directory and files on disk if old dir was a temporary ref.
4170 if (!$error && preg_match('/^[\‍(]?PROV/i', $this->oldref)) {
4171 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
4172 $oldref = dol_sanitizeFileName($this->oldref);
4173 $newref = dol_sanitizeFileName($num);
4174 $dirsource = $conf->facture->dir_output.'/'.$oldref;
4175 $dirdest = $conf->facture->dir_output.'/'.$newref;
4176 if (!$error && file_exists($dirsource)) {
4177 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
4178
4179 if (@rename($dirsource, $dirdest)) {
4180 dol_syslog("Rename ok");
4181 // Rename also docs starting with $oldref with $newref
4182 $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
4183 foreach ($listoffiles as $fileentry) {
4184 $dirsource = $fileentry['name'];
4185 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
4186 $dirsource = $fileentry['path'].'/'.$dirsource;
4187 $dirdest = $fileentry['path'].'/'.$dirdest;
4188 @rename($dirsource, $dirdest);
4189 }
4190 }
4191 }
4192 }
4193
4194 if (!$error) {
4195 $this->db->commit();
4196 return 1;
4197 } else {
4198 $this->db->rollback();
4199 return -1;
4200 }
4201 }
4202
4216 public function consumeDepositCredits(User $user, Facture $depositInvoice, float $amount_ttc)
4217 {
4218 global $langs;
4219
4220 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
4221
4222 if ($amount_ttc <= 0) {
4223 return 1;
4224 }
4225
4226 $sql = 'SELECT rowid, amount_ttc, tva_tx, multicurrency_amount_ttc, description, fk_user, fk_soc, discount_type, vat_src_code';
4227 $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except';
4228 $sql .= ' WHERE fk_facture_source = '.((int) $depositInvoice->id);
4229 $sql .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL';
4230 $sql .= ' ORDER BY amount_ttc ASC';
4231
4232 $resql = $this->db->query($sql);
4233 if (!$resql) {
4234 $this->error = $this->db->lasterror();
4235 return -1;
4236 }
4237
4238 $remaining = $amount_ttc;
4239 while ($remaining > 0 && ($row = $this->db->fetch_object($resql))) {
4240 $row_ttc = (float) $row->amount_ttc;
4241 if ($row_ttc <= $remaining + 0.001) {
4242 // Whole row consumed: delete by rowid (fk_facture_source=0 bypasses series pre-check, noresetinvoice=true keeps deposit paid)
4243 $disc = new DiscountAbsolute($this->db);
4244 $disc->id = (int) $row->rowid;
4245 if ($disc->delete($user, true) < 0) {
4246 $this->error = $disc->error;
4247 $this->db->free($resql);
4248 return -1;
4249 }
4250 $remaining = (float) price2num($remaining - $row_ttc, 'MT');
4251 } else {
4252 // Partial: delete original, recreate the part to keep
4253 $keep_ttc = (float) price2num($row_ttc - $remaining, 'MT');
4254 $tva_tx = (float) $row->tva_tx;
4255 $mc_ratio = ($row_ttc > 0) ? ((float) $row->multicurrency_amount_ttc / $row_ttc) : 1;
4256
4257 $disc = new DiscountAbsolute($this->db);
4258 $disc->id = (int) $row->rowid;
4259 if ($disc->delete($user, true) < 0) {
4260 $this->error = $disc->error;
4261 $this->db->free($resql);
4262 return -1;
4263 }
4264
4265 $d = new DiscountAbsolute($this->db);
4266 $d->fk_facture_source = (int) $depositInvoice->id;
4267 $d->description = $row->description;
4268 $d->fk_user = (int) $row->fk_user;
4269 $d->fk_soc = (int) $row->fk_soc;
4270 $d->socid = (int) $row->fk_soc;
4271 $d->discount_type = (int) $row->discount_type;
4272 $d->tva_tx = $tva_tx;
4273 $d->vat_src_code = $row->vat_src_code;
4274 $d->amount_ttc = $keep_ttc;
4275 $d->amount_ht = (float) price2num($keep_ttc / (1 + $tva_tx / 100), 'MT');
4276 $d->amount_tva = (float) price2num($keep_ttc - $d->amount_ht);
4277 $d->multicurrency_amount_ttc = (float) price2num($keep_ttc * $mc_ratio);
4278 $d->multicurrency_amount_ht = (float) price2num($d->multicurrency_amount_ttc / (1 + $tva_tx / 100), 'MT');
4279 $d->multicurrency_amount_tva = (float) price2num($d->multicurrency_amount_ttc - $d->multicurrency_amount_ht);
4280
4281 if ($d->create($user) <= 0) {
4282 $this->error = $d->error;
4283 $this->db->free($resql);
4284 return -1;
4285 }
4286 $remaining = 0;
4287 }
4288 }
4289 $this->db->free($resql);
4290
4291 // Trace in agenda of both deposit and credit note (non-blocking)
4292 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
4293 $langs->load('bills');
4294 $label = $langs->trans('CreditNoteDepositCreditConsumed', (!empty($this->newref) ? $this->newref : $this->ref), price($amount_ttc));
4295 foreach (array($depositInvoice->id, $this->id) as $facid) {
4296 $actioncomm = new ActionComm($this->db);
4297 $actioncomm->type_code = 'AC_OTH_AUTO';
4298 $actioncomm->code = 'AC_OTH_AUTO';
4299 $actioncomm->label = $label;
4300 $actioncomm->socid = $this->socid;
4301 $actioncomm->datep = dol_now();
4302 $actioncomm->datef = $actioncomm->datep;
4303 $actioncomm->percentage = -1;
4304 $actioncomm->authorid = $user->id;
4305 $actioncomm->userownerid = $user->id;
4306 $actioncomm->elementtype = 'invoice';
4307 $actioncomm->elementid = $facid;
4308 $actioncomm->create($user);
4309 }
4310
4311 return 1;
4312 }
4313
4320 public function updatePriceNextInvoice(&$langs)
4321 {
4322 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4323 $is_last = $next_invoice->is_last_in_cycle();
4324
4325 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4326 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4327 return false;
4328 }
4329
4330 foreach ($next_invoice->lines as $line) {
4331 '@phan-var-force FactureLigne $line';
4332 $result = $next_invoice->updateline(
4333 $line->id,
4334 $line->desc,
4335 $line->subprice,
4336 $line->qty,
4337 $line->remise_percent,
4338 $line->date_start,
4339 $line->date_end,
4340 $line->tva_tx,
4341 $line->localtax1_tx,
4342 $line->localtax2_tx,
4343 'HT',
4344 $line->info_bits,
4345 $line->product_type,
4346 $line->fk_parent_line,
4347 0,
4348 $line->fk_fournprice,
4349 $line->pa_ht,
4350 $line->label,
4351 $line->special_code,
4352 $line->array_options,
4353 $line->situation_percent,
4354 $line->fk_unit
4355 );
4356
4357 if ($result < 0) {
4358 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4359 return false;
4360 }
4361 }
4362
4363 break; // Only the next invoice and not each next invoice
4364 }
4365
4366 return true;
4367 }
4368
4376 public function setDraft($user, $idwarehouse = -1)
4377 {
4378 // phpcs:enable
4379 global $langs;
4380
4381 $error = 0;
4382
4383 if ($this->status == self::STATUS_DRAFT) {
4384 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
4385 return 0;
4386 }
4387
4388 dol_syslog(__METHOD__, LOG_DEBUG);
4389
4390 // Block draft revert for credit notes on deposit invoices: credits have been consumed and cannot be recreated
4391 if ($this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
4392 $sourceInvoice = new Facture($this->db);
4393 if ($sourceInvoice->fetch($this->fk_facture_source) > 0 && $sourceInvoice->type == self::TYPE_DEPOSIT) {
4394 $langs->load('bills');
4395 $this->error = $langs->trans('CreditNoteOnDepositCantBeSetToDraft');
4396 return -1;
4397 }
4398 }
4399
4400 $this->db->begin();
4401
4402 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4403 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
4404 $sql .= " WHERE rowid = ".((int) $this->id);
4405
4406 $result = $this->db->query($sql);
4407 if ($result) {
4408 if (!$error) {
4409 $this->oldcopy = clone $this;
4410 }
4411
4412 // If we decrease stock on invoice validation, we increase back
4413 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
4414 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
4415 $langs->load("agenda");
4416
4417 $num = count($this->lines);
4418 for ($i = 0; $i < $num; $i++) {
4419 if ($this->lines[$i]->fk_product > 0) {
4420 $mouvP = new MouvementStock($this->db);
4421 $mouvP->origin = &$this;
4422 $mouvP->setOrigin($this->element, $this->id);
4423 // We decrease stock for product
4424 if ($this->type == self::TYPE_CREDIT_NOTE) {
4425 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv("InvoiceBackToDraftInDolibarr", $this->ref));
4426 } else {
4427 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
4428 }
4429 if ($result < 0) {
4430 $error++;
4431 $this->setErrorsFromObject($mouvP);
4432 dol_syslog(__METHOD__." stock movement failed for line ".$i.": ".$mouvP->error, LOG_ERR);
4433 break;
4434 }
4435 }
4436 }
4437 }
4438 if ($error == 0) {
4439 $old_statut = $this->status;
4440 $this->statut = self::STATUS_DRAFT; // deprecated
4441 $this->status = self::STATUS_DRAFT;
4442
4443 // Call trigger
4444 $result = $this->call_trigger('BILL_UNVALIDATE', $user);
4445 if ($result < 0) {
4446 $error++;
4447 $this->statut = $old_statut; // deprecated
4448 $this->status = $old_statut;
4449 }
4450 // End call triggers
4451 } else {
4452 $this->db->rollback();
4453 return -1;
4454 }
4455
4456 if ($error == 0) {
4457 $this->db->commit();
4458 return 1;
4459 } else {
4460 $this->db->rollback();
4461 return -1;
4462 }
4463 } else {
4464 $this->error = $this->db->error();
4465 $this->db->rollback();
4466 return -1;
4467 }
4468 }
4469
4470
4511 public function addline(
4512 $desc,
4513 $pu_ht,
4514 $qty,
4515 $txtva,
4516 $txlocaltax1 = 0,
4517 $txlocaltax2 = 0,
4518 $fk_product = 0,
4519 $remise_percent = 0,
4520 $date_start = '',
4521 $date_end = '',
4522 $fk_code_ventilation = 0,
4523 $info_bits = 0,
4524 $fk_remise_except = 0,
4525 $price_base_type = 'HT',
4526 $pu_ttc = 0,
4527 $type = 0,
4528 $rang = -1,
4529 $special_code = 0,
4530 $origin = '',
4531 $origin_id = 0,
4532 $fk_parent_line = 0,
4533 $fk_fournprice = null,
4534 $pa_ht = 0,
4535 $label = '',
4536 $array_options = array(),
4537 $situation_percent = 100,
4538 $fk_prev_id = 0,
4539 $fk_unit = null,
4540 $pu_ht_devise = 0,
4541 $ref_ext = '',
4542 $noupdateafterinsertline = 0
4543 ) {
4544 // Deprecation warning
4545 if ($label) {
4546 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4547 //var_dump(getCallerInfoString());exit;
4548 }
4549
4550 global $mysoc, $langs;
4551
4552 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);
4553
4554 if ($this->status == self::STATUS_DRAFT) {
4555 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4556
4557 // Clean parameters
4558 if (empty($remise_percent)) {
4559 $remise_percent = 0;
4560 }
4561 if (empty($qty)) {
4562 $qty = 0;
4563 }
4564 if (empty($info_bits)) {
4565 $info_bits = 0;
4566 }
4567 if (empty($rang)) {
4568 $rang = 0;
4569 }
4570 if (empty($fk_code_ventilation)) {
4571 $fk_code_ventilation = 0;
4572 }
4573 if (empty($txtva)) {
4574 $txtva = 0;
4575 }
4576 if (empty($txlocaltax1)) {
4577 $txlocaltax1 = 0;
4578 }
4579 if (empty($txlocaltax2)) {
4580 $txlocaltax2 = 0;
4581 }
4582 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4583 $fk_parent_line = 0;
4584 }
4585 if (empty($fk_prev_id)) {
4586 $fk_prev_id = 'null';
4587 }
4588
4589 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
4590 // 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.
4591 if ($this->isSituationInvoice() && getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4592 $situation_percent = 0;
4593 } else {
4594 $situation_percent = 100;
4595 }
4596 }
4597
4598 if (empty($ref_ext)) {
4599 $ref_ext = '';
4600 }
4601
4602 $remise_percent = (float) price2num($remise_percent);
4603
4604 $qty = (float) price2num($qty);
4605 $pu_ht = (float) price2num($pu_ht);
4606 $pu_ht_devise = (float) price2num($pu_ht_devise);
4607 $pu_ttc = (float) price2num($pu_ttc);
4608 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4609 if (strpos((string) $txtva, '*') !== false) {
4610 $info_bits |= 1;
4611 }
4612 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4613 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4614 }
4615 $txlocaltax1 = (float) price2num($txlocaltax1);
4616 $txlocaltax2 = (float) price2num($txlocaltax2);
4617
4618 if ($price_base_type == 'HT') {
4619 $pu = $pu_ht;
4620 } else {
4621 $pu = $pu_ttc;
4622 }
4623
4624 // Check parameters
4625 if ($type < 0) {
4626 return -1;
4627 }
4628
4629 if ($date_start && $date_end && $date_start > $date_end) {
4630 $langs->load("errors");
4631 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4632 return -1;
4633 }
4634
4635 $this->db->begin();
4636
4637 $product_type = $type;
4638 if (!empty($fk_product) && $fk_product > 0) {
4639 $product = new Product($this->db);
4640 $result = $product->fetch($fk_product);
4641 $product_type = $product->type;
4642
4643 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4644 // get real stock
4645 $productChildrenNb = 0;
4646 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
4647 $productChildrenNb = $product->hasFatherOrChild(1);
4648 }
4649 if ($productChildrenNb > 0) {
4650 // compute real stock from each subcomponent
4651 $product_stock = null;
4652 $product->loadStockForVirtualProduct('warehouseopen', $qty);
4653 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4654 if ($product_stock === null) {
4655 $product_stock = $componentStockWarehouse->real;
4656 } else {
4657 $product_stock = min($product_stock, $componentStockWarehouse->real);
4658 }
4659 }
4660 if ($product_stock === null) {
4661 $product_stock = 0;
4662 }
4663 } else {
4664 $product_stock = $product->stock_reel;
4665 }
4666
4667 if ($product_stock < $qty) {
4668 $langs->load("errors");
4669 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4670 $this->db->rollback();
4671 return -3;
4672 }
4673 }
4674
4675 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
4676 $tmpproduct = new Product($this->db);
4677 $result = $tmpproduct->fetch($fk_product);
4678 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
4679 if ($newqty != $qty) {
4680 $qty = $newqty;
4681 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
4682 }
4683 }
4684 }
4685
4686 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4687
4688 // Clean vat code
4689 $reg = array();
4690 $vat_src_code = '';
4691 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4692 $vat_src_code = $reg[1];
4693 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4694 }
4695
4696 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
4697 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
4698 // and this is done at the line level, which has its own VAT rate
4699
4700 $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, $this->multicurrency_code);
4701
4702 $total_ht = $tabprice[0];
4703 $total_tva = $tabprice[1];
4704 $total_ttc = $tabprice[2];
4705 $total_localtax1 = $tabprice[9];
4706 $total_localtax2 = $tabprice[10];
4707 $pu_ht = $tabprice[3];
4708
4709 // MultiCurrency
4710 $multicurrency_total_ht = $tabprice[16];
4711 $multicurrency_total_tva = $tabprice[17];
4712 $multicurrency_total_ttc = $tabprice[18];
4713 $pu_ht_devise = $tabprice[19];
4714
4715 // Rank to use
4716 $ranktouse = $rang;
4717 if (empty($ranktouse) || $ranktouse == -1) {
4718 $rangmax = $this->line_max($fk_parent_line);
4719 $ranktouse = $rangmax + 1;
4720 }
4721
4722 // Same gate as in updateline(): the -abs() forcing on credit note lines is relaxed only when
4723 // both FACTURE_ENABLE_NEGATIVE_LINES and INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN are enabled.
4724 $apply_abs_price_on_credit_note = false;
4725 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
4726 $apply_abs_price_on_credit_note = true;
4727 }
4728
4729 // Insert line
4730 $this->line = new FactureLigne($this->db);
4731
4732 $this->line->context = $this->context;
4733
4734 $this->line->fk_facture = $this->id;
4735 $this->line->label = $label; // deprecated
4736 $this->line->desc = $desc;
4737 $this->line->ref_ext = $ref_ext;
4738
4739 $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
4740 $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
4741 // Persist the original entry mode of the line so updateline() can preserve it later.
4742 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? ($apply_abs_price_on_credit_note ? -abs((float) $pu_ttc) : (float) $pu_ttc) : 0;
4743
4744 $this->line->vat_src_code = $vat_src_code;
4745 $this->line->tva_tx = $txtva;
4746 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4747 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4748 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4749 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4750
4751 $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
4752 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc); // For credit note and if qty is negative, total is negative
4753 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva); // For credit note and if qty is negative, total is negative
4754 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_localtax1) : (float) $total_localtax1); // For credit note and if qty is negative, total is negative
4755 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_localtax2) : (float) $total_localtax2); // For credit note and if qty is negative, total is negative
4756
4757 $this->line->fk_product = $fk_product;
4758 $this->line->product_type = $product_type;
4759 $this->line->remise_percent = $remise_percent;
4760 $this->line->date_start = $date_start;
4761 $this->line->date_end = $date_end;
4762 $this->line->fk_code_ventilation = $fk_code_ventilation;
4763 $this->line->rang = $ranktouse;
4764 $this->line->info_bits = $info_bits;
4765 $this->line->fk_remise_except = $fk_remise_except;
4766
4767 $this->line->special_code = $special_code;
4768 $this->line->fk_parent_line = $fk_parent_line;
4769
4770 $this->line->origin = $origin;
4771 $this->line->origin_id = $origin_id;
4772
4773 $this->line->situation_percent = $situation_percent;
4774 $this->line->fk_prev_id = $fk_prev_id;
4775 $this->line->fk_unit = $fk_unit;
4776
4777 // infos margin
4778 $this->line->fk_fournprice = $fk_fournprice;
4779 $this->line->pa_ht = $pa_ht;
4780
4781 // Multicurrency
4782 $this->line->fk_multicurrency = $this->fk_multicurrency;
4783 $this->line->multicurrency_code = $this->multicurrency_code;
4784 $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
4785
4786 $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
4787 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
4788 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
4789
4790 if (is_array($array_options) && count($array_options) > 0) {
4791 $this->line->array_options = $array_options;
4792 }
4793
4794 $result = $this->line->insert();
4795 if ($result > 0) {
4796 // Update denormalized fields at the order level
4797 if (empty($noupdateafterinsertline)) {
4798 $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.
4799 }
4800
4801 if (!isset($this->context['createfromclone'])) {
4802 if (!empty($fk_parent_line)) {
4803 // Always reorder if child line
4804 $this->line_order(true, 'DESC');
4805 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4806 // Update all rank of all other lines starting from the same $ranktouse
4807 $linecount = count($this->lines);
4808 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4809 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
4810 }
4811 }
4812
4813 $this->lines[] = $this->line;
4814 } else {
4815 // Loop on all lines of parent object
4816 foreach ($this->lines as $tmpline) {
4817 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4818 $this->line->extraparams = $tmpline->extraparams;
4819 $this->line->setExtraParameters();
4820 }
4821 }
4822 }
4823
4824 if ($result > 0) {
4825 $this->db->commit();
4826 return $this->line->id;
4827 } else {
4828 $this->error = $this->db->lasterror();
4829 $this->db->rollback();
4830 return -1;
4831 }
4832 } else {
4833 $this->error = $this->line->error;
4834 $this->errors = $this->line->errors;
4835 $this->db->rollback();
4836 return -2;
4837 }
4838 } else {
4839 $this->errors[] = 'status of invoice must be Draft to allow use of ->addline()';
4840 dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4841 return -3;
4842 }
4843 }
4844
4876 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)
4877 {
4878 global $user;
4879
4880 if (!$this->isLineOfObject($rowid)) {
4881 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4882 return -1;
4883 }
4884
4885 // Deprecation warning
4886 if ($label) {
4887 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4888 }
4889
4890 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4891
4892 global $mysoc, $langs;
4893
4894 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);
4895
4896 if ($this->status == self::STATUS_DRAFT) {
4897 if (!$this->is_last_in_cycle() && empty($this->error)) {
4898 if (!$this->checkProgressLine($rowid, $situation_percent)) {
4899 if (!$this->error) {
4900 $this->error = $langs->trans('invoiceLineProgressError');
4901 }
4902 return -3;
4903 }
4904 }
4905
4906 if ($date_start && $date_end && $date_start > $date_end) {
4907 $langs->load("errors");
4908 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4909 return -1;
4910 }
4911
4912 $this->db->begin();
4913
4914 // Clean parameters
4915 if (empty($qty)) {
4916 $qty = 0;
4917 }
4918 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4919 $fk_parent_line = 0;
4920 }
4921 if (empty($special_code) || $special_code == 3) {
4922 $special_code = 0;
4923 }
4924 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '' || $situation_percent == null) {
4925 // INVOICE_USE_SITUATION = 2 - If there is no progress on a line, percent must not be 100% (No cumulative)
4926 if ($this->isSituationInvoice() && getDolGlobalInt('INVOICE_USE_SITUATION') == 2 && (int) $situation_percent < 100) {
4927 $situation_percent = 0;
4928 } else {
4929 $situation_percent = 100;
4930 }
4931 }
4932 if (empty($ref_ext)) {
4933 $ref_ext = '';
4934 }
4935
4936 $remise_percent = (float) price2num($remise_percent);
4937
4938 $qty = (float) price2num($qty);
4939 $pu = (float) price2num($pu);
4940 $pu_ht_devise = (float) price2num($pu_ht_devise);
4941 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4942
4943 if (strpos((string) $txtva, '*') !== false) {
4944 $info_bits |= 1;
4945 }
4946 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4947 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4948 }
4949 $txlocaltax1 = (float) price2num($txlocaltax1);
4950 $txlocaltax2 = (float) price2num($txlocaltax2);
4951
4952 // Check parameters
4953 if ($type < 0) {
4954 return -1;
4955 }
4956
4957 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
4958 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
4959 // and this is done at the line level, which has its own VAT rate
4960
4961 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4962
4963 // Clean vat code
4964 $reg = array();
4965 $vat_src_code = '';
4966 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4967 $vat_src_code = $reg[1];
4968 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4969 }
4970
4971 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
4972 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
4973 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
4974 $tmpline = new FactureLigne($this->db);
4975 if ($tmpline->fetch($rowid) > 0) {
4976 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
4977 if ($newqty != $qty) {
4978 $qty = $newqty;
4979 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
4980 }
4981 }
4982 }
4983
4984 $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, $this->multicurrency_code);
4985
4986 $total_ht = $tabprice[0];
4987 $total_tva = $tabprice[1];
4988 $total_ttc = $tabprice[2];
4989 $total_localtax1 = $tabprice[9];
4990 $total_localtax2 = $tabprice[10];
4991 $pu_ht = $tabprice[3];
4992 $pu_tva = $tabprice[4];
4993 $pu_ttc = $tabprice[5];
4994
4995 // MultiCurrency
4996 $multicurrency_total_ht = $tabprice[16];
4997 $multicurrency_total_tva = $tabprice[17];
4998 $multicurrency_total_ttc = $tabprice[18];
4999 $pu_ht_devise = $tabprice[19];
5000
5001 // Old properties: $price, $remise (deprecated)
5002 $price = $pu;
5003 $remise = 0;
5004 if ($remise_percent > 0) {
5005 $remise = round(((float) $pu * (float) $remise_percent / 100), 2);
5006 $price = ((float) $pu - $remise);
5007 }
5008 $price = price2num($price);
5009
5010 // Fetch current line from the database and then clone the object and set it in $oldline property
5011 $line = new FactureLigne($this->db);
5012 $line->fetch($rowid);
5013 $line->fetch_optionals();
5014
5015 if (!empty($line->fk_product)) {
5016 $product = new Product($this->db);
5017 $result = $product->fetch($line->fk_product);
5018 $product_type = $product->type;
5019
5020 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
5021 // get real stock
5022 $productChildrenNb = 0;
5023 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
5024 $productChildrenNb = $product->hasFatherOrChild(1);
5025 }
5026 if ($productChildrenNb > 0) {
5027 // compute real stock from each subcomponent
5028 $product_stock = null;
5029 $product->loadStockForVirtualProduct('warehouseopen', $qty);
5030 foreach ($product->stock_warehouse as $componentStockWarehouse) {
5031 if ($product_stock === null) {
5032 $product_stock = $componentStockWarehouse->real;
5033 } else {
5034 $product_stock = min($product_stock, $componentStockWarehouse->real);
5035 }
5036 }
5037 if ($product_stock === null) {
5038 $product_stock = 0;
5039 }
5040 } else {
5041 $product_stock = $product->stock_reel;
5042 }
5043
5044 if ($product_stock < $qty) {
5045 $langs->load("errors");
5046 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', (string) $product->ref);
5047 $this->db->rollback();
5048 return -3;
5049 }
5050 }
5051 }
5052
5053 $staticline = clone $line;
5054
5055 $line->oldline = $staticline;
5056 $this->line = $line;
5057 $this->line->context = $this->context;
5058 $this->line->rang = $rang;
5059
5060 // Reorder if fk_parent_line change
5061 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
5062 $rangmax = $this->line_max($fk_parent_line);
5063 $this->line->rang = $rangmax + 1;
5064 }
5065 $apply_abs_price_on_credit_note = false;
5066 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
5067 $apply_abs_price_on_credit_note = true;
5068 }
5069
5070
5071
5072 $this->line->id = $rowid;
5073 $this->line->rowid = $rowid;
5074 $this->line->label = $label;
5075 $this->line->desc = $desc;
5076 $this->line->ref_ext = $ref_ext;
5077 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
5078
5079 $this->line->vat_src_code = $vat_src_code;
5080 $this->line->tva_tx = $txtva;
5081 $this->line->localtax1_tx = $txlocaltax1;
5082 $this->line->localtax2_tx = $txlocaltax2;
5083 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
5084 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
5085
5086 $this->line->remise_percent = $remise_percent;
5087 $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
5088 // Persist the original entry mode of the line so a no-op edit can preserve it later.
5089 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? ($apply_abs_price_on_credit_note ? -abs((float) $pu_ttc) : (float) $pu_ttc) : 0;
5090 $this->line->date_start = $date_start;
5091 $this->line->date_end = $date_end;
5092 $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
5093 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva);
5094 $this->line->total_localtax1 = (float) $total_localtax1;
5095 $this->line->total_localtax2 = (float) $total_localtax2;
5096 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc);
5097 $this->line->info_bits = $info_bits;
5098 $this->line->special_code = $special_code;
5099 $this->line->product_type = $type;
5100 $this->line->fk_parent_line = $fk_parent_line;
5101 $this->line->skip_update_total = $skip_update_total;
5102 $this->line->situation_percent = $situation_percent;
5103 $this->line->fk_unit = $fk_unit;
5104
5105 $this->line->fk_fournprice = $fk_fournprice;
5106 $this->line->pa_ht = $pa_ht;
5107
5108 // Multicurrency
5109 $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
5110 $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
5111 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
5112 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
5113
5114 if (is_array($array_options) && count($array_options) > 0) {
5115 // We replace values in this->line->array_options only for entries defined into $array_options
5116 foreach ($array_options as $key => $value) {
5117 $this->line->array_options[$key] = $array_options[$key];
5118 }
5119 }
5120
5121 $result = $this->line->update($user, $notrigger);
5122 if ($result > 0) {
5123 // Reorder if child line
5124 if (!empty($fk_parent_line)) {
5125 $this->line_order(true, 'DESC');
5126 }
5127
5128 // Update denormalized information at the invoice level
5129 $this->update_price(1, 'auto');
5130 $this->db->commit();
5131 return $result;
5132 } else {
5133 $this->error = $this->line->error;
5134 $this->db->rollback();
5135 return -1;
5136 }
5137 } else {
5138 $this->error = "Invoice statut makes operation forbidden";
5139 return -2;
5140 }
5141 }
5142
5150 public function checkProgressLine($idline, $situation_percent)
5151 {
5152 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
5153 INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
5154 WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
5155
5156 $result = $this->db->query($sql);
5157 if (!$result) {
5158 $this->error = $this->db->error();
5159 return false;
5160 }
5161
5162 $obj = $this->db->fetch_object($result);
5163
5164 if ($obj === null) {
5165 return true;
5166 } else {
5167 return ($situation_percent < $obj->situation_percent);
5168 }
5169 }
5170
5171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5180 public function update_percent($line, $percent, $update_price = true)
5181 {
5182 // phpcs:enable
5183 global $mysoc, $user;
5184
5185 // Progress should never be changed for discount lines
5186 if (($line->info_bits & 2) == 2) {
5187 return;
5188 }
5189
5190 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
5191
5192 // Cap percentages to 100
5193 if ($percent > 100) {
5194 $percent = 100;
5195 }
5196 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
5197 $line->situation_percent = $percent;
5198 $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);
5199 } else {
5200 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
5201 $current_progress = $percent - $previous_progress;
5202 $line->situation_percent = $current_progress;
5203 $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);
5204 }
5205 $line->total_ht = (float) $tabprice[0];
5206 $line->total_tva = (float) $tabprice[1];
5207 $line->total_ttc = (float) $tabprice[2];
5208 $line->total_localtax1 = (float) $tabprice[9];
5209 $line->total_localtax2 = (float) $tabprice[10];
5210 $line->multicurrency_total_ht = (float) $tabprice[16];
5211 $line->multicurrency_total_tva = (float) $tabprice[17];
5212 $line->multicurrency_total_ttc = (float) $tabprice[18];
5213 $line->update($user);
5214
5215 // sometimes it is better to not update price for each line, ie when updating situation on all lines
5216 if ($update_price) {
5217 $this->update_price(1);
5218 }
5219 }
5220
5228 public function deleteLine($rowid, $id = 0)
5229 {
5230 global $user;
5231
5232 dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
5233
5234 if ($this->status != self::STATUS_DRAFT) {
5235 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
5236 return -1;
5237 }
5238
5239 $line = new FactureLigne($this->db);
5240
5241 $line->context = $this->context;
5242
5243 // Load line
5244 $result = $line->fetch($rowid);
5245 if (!($result > 0)) {
5246 dol_print_error($this->db, $line->error, $line->errors);
5247 return -1;
5248 }
5249
5250 if ($id <= 0) {
5251 $id = $this->id;
5252 }
5253 if ($id > 0 && (int) $line->fk_facture !== (int) $id) {
5254 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
5255 return -1;
5256 }
5257
5258 $this->db->begin();
5259
5260 // Memorize previous line for triggers
5261 $staticline = clone $line;
5262 $line->oldline = $staticline;
5263
5264 if ($line->delete($user) > 0) {
5265 $result = $this->update_price(1);
5266
5267 if ($result > 0) {
5268 $this->db->commit();
5269 return 1;
5270 } else {
5271 $this->db->rollback();
5272 $this->error = $this->db->lasterror();
5273 return -1;
5274 }
5275 } else {
5276 $this->db->rollback();
5277 $this->error = $line->error;
5278 return -1;
5279 }
5280 }
5281
5282 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5293 public function set_remise($user, $remise, $notrigger = 0)
5294 {
5295 // phpcs:enable
5296 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
5297 // @phan-suppress-next-line PhanDeprecatedFunction
5298 return $this->setDiscount($user, $remise, $notrigger);
5299 }
5300
5309 public function setDiscount($user, $remise, $notrigger = 0)
5310 {
5311 // Clean parameters
5312 if (empty($remise)) {
5313 $remise = 0;
5314 }
5315
5316 if ($user->hasRight('facture', 'creer')) {
5317 $remise = (float) price2num($remise, 2);
5318
5319 $error = 0;
5320
5321 $this->db->begin();
5322
5323 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
5324 $sql .= " SET remise_percent = ".((float) $remise);
5325 $sql .= " WHERE rowid = ".((int) $this->id);
5326 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
5327
5328 dol_syslog(__METHOD__, LOG_DEBUG);
5329 $resql = $this->db->query($sql);
5330 if (!$resql) {
5331 $this->errors[] = $this->db->error();
5332 $error++;
5333 }
5334
5335 if (!$notrigger && empty($error)) {
5336 // Call trigger
5337 $result = $this->call_trigger('BILL_MODIFY', $user);
5338 if ($result < 0) {
5339 $error++;
5340 }
5341 // End call triggers
5342 }
5343
5344 if (!$error) {
5345 $this->remise_percent = $remise;
5346 $this->update_price(1);
5347
5348 $this->db->commit();
5349 return 1;
5350 } else {
5351 foreach ($this->errors as $errmsg) {
5352 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5353 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5354 }
5355 $this->db->rollback();
5356 return -1 * $error;
5357 }
5358 }
5359
5360 return 0;
5361 }
5362
5363
5374 public function setCategories($categories)
5375 {
5376 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5377 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5378 }
5379
5388 public function getNextNumRef($soc, $mode = 'next')
5389 {
5390 global $conf, $langs;
5391
5392 if ($this->module_source == 'takepos') {
5393 $langs->load('cashdesk');
5394
5395 $moduleName = 'takepos';
5396 $moduleSourceName = 'Takepos';
5397 $addonConstName = 'TAKEPOS_REF_ADDON';
5398
5399 // Clean parameters (if not defined or using deprecated value)
5400 if (!getDolGlobalString('TAKEPOS_REF_ADDON')) {
5401 $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
5402 }
5403
5404 $addon = getDolGlobalString('TAKEPOS_REF_ADDON');
5405 } else {
5406 $langs->load('bills');
5407
5408 $moduleName = 'facture';
5409 $moduleSourceName = 'Invoice';
5410 $addonConstName = 'FACTURE_ADDON';
5411
5412 // Clean parameters (if not defined or using deprecated value)
5413 if (!getDolGlobalString('FACTURE_ADDON')) {
5414 $conf->global->FACTURE_ADDON = 'mod_facture_mars';
5415 } elseif (getDolGlobalString('FACTURE_ADDON') == 'terre') { // terre is deprecated
5416 $conf->global->FACTURE_ADDON = 'mod_facture_mars';
5417 } elseif (getDolGlobalString('FACTURE_ADDON') == 'mercure') {
5418 $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
5419 }
5420
5421 $addon = getDolGlobalString('FACTURE_ADDON');
5422 }
5423
5424 if (!empty($addon)) {
5425 dol_syslog("Call getNextNumRef with ".$addonConstName." = " . getDolGlobalString('FACTURE_ADDON').", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
5426
5427 $mybool = false;
5428
5429 $file = $addon.'.php';
5430 $classname = $addon;
5431
5432
5433 // Include file with class
5434 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
5435 foreach ($dirmodels as $reldir) {
5436 $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
5437
5438 // Load file with numbering class (if found)
5439 if (is_file($dir.$file) && is_readable($dir.$file)) {
5440 $mybool = ((bool) include_once $dir.$file) || $mybool;
5441 }
5442 }
5443
5444 // For compatibility
5445 if (!$mybool) {
5446 $file = $addon.'/'.$addon.'.modules.php';
5447 $classname = 'mod_'.$moduleName.'_'.$addon;
5448 $classname = preg_replace('/\-.*$/', '', $classname);
5449 // Include file with class
5450 foreach ($conf->file->dol_document_root as $dirroot) {
5451 $dir = $dirroot.'/core/modules/'.$moduleName.'/';
5452
5453 // Load file with numbering class (if found)
5454 if (is_file($dir.$file) && is_readable($dir.$file)) {
5455 $mybool = (include_once $dir.$file) || $mybool;
5456 }
5457 }
5458 }
5459
5460 if (!$mybool) {
5461 dol_print_error(null, 'Failed to include file '.$file);
5462 return '';
5463 }
5464
5465 $obj = new $classname();
5466 '@phan-var-force ModeleNumRefFactures $obj';
5467
5468 $numref = $obj->getNextValue($soc, $this, $mode);
5469
5470
5475 if ($mode != 'last' && !$numref) {
5476 $this->error = $obj->error;
5477 return '';
5478 }
5479
5480 return $numref;
5481 } else {
5482 $langs->load('errors');
5483 print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5484 return '';
5485 }
5486 }
5487
5494 public function info($id)
5495 {
5496 $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5497 $sql .= ' date_closing as dateclosing,';
5498 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5499 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
5500 $sql .= ' WHERE c.rowid = '.((int) $id);
5501
5502 $result = $this->db->query($sql);
5503 if ($result) {
5504 if ($this->db->num_rows($result)) {
5505 $obj = $this->db->fetch_object($result);
5506
5507 $this->id = $obj->rowid;
5508 $this->user_creation_id = $obj->fk_user_author;
5509 $this->user_modification_id = $obj->fk_user_modif;
5510 $this->user_validation_id = $obj->fk_user_valid;
5511 $this->user_closing_id = $obj->fk_user_closing;
5512
5513 $this->date_creation = $this->db->jdate($obj->datec);
5514 $this->date_modification = $this->db->jdate($obj->datem);
5515 $this->date_validation = $this->db->jdate($obj->datev);
5516 $this->date_closing = $this->db->jdate($obj->dateclosing);
5517 }
5518 $this->db->free($result);
5519 } else {
5520 dol_print_error($this->db);
5521 }
5522 }
5523
5524
5525 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5539 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
5540 {
5541 // phpcs:enable
5542 global $user;
5543
5544 $ga = array();
5545
5546 $sql = "SELECT s.rowid, s.nom as name, s.client,";
5547 $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
5548 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
5549 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5550 $sql .= " AND f.fk_soc = s.rowid";
5551 if ($draft) {
5552 $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
5553 }
5554 if (is_object($excluser)) {
5555 $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
5556 }
5557 // If the internal user must only see his customers, force searching by him
5558 $search_sale = 0;
5559 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5560 $search_sale = $user->id;
5561 }
5562 // Search on sale representative
5563 if ($search_sale && $search_sale != '-1') {
5564 if ($search_sale == -2) {
5565 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5566 } elseif ($search_sale > 0) {
5567 $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).")";
5568 }
5569 }
5570 // Search on socid
5571 if ($socid) {
5572 $sql .= " AND f.fk_soc = ".((int) $socid);
5573 }
5574 $sql .= $this->db->order($sortfield, $sortorder);
5575 $sql .= $this->db->plimit($limit, $offset);
5576
5577 $result = $this->db->query($sql);
5578 if ($result) {
5579 $numc = $this->db->num_rows($result);
5580 if ($numc) {
5581 $i = 0;
5582 while ($i < $numc) {
5583 $obj = $this->db->fetch_object($result);
5584
5585 if ($shortlist == 1) {
5586 $ga[$obj->fid] = $obj->ref;
5587 } elseif ($shortlist == 2) {
5588 $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
5589 } else {
5590 $ga[$i]['id'] = $obj->fid;
5591 $ga[$i]['ref'] = $obj->ref;
5592 $ga[$i]['name'] = $obj->name;
5593 }
5594 $i++;
5595 }
5596 }
5597 return $ga;
5598 } else {
5599 dol_print_error($this->db);
5600 return -1;
5601 }
5602 }
5603
5604
5605 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5614 public function list_replacable_invoices($socid = 0)
5615 {
5616 // phpcs:enable
5617 global $conf;
5618
5619 $return = array();
5620
5621 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5622 $sql .= " ff.rowid as rowidnext";
5623 //$sql .= ", SUM(pf.amount) as alreadypaid";
5624 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5625 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
5626 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
5627 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
5628 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5629 $sql .= " AND f.paye = 0"; // Not paid completely
5630 $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
5631 $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
5632 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type = 'customer_invoice' AND ab.fk_doc = f.rowid)"; // Not already transferred into accounting
5633 if ($socid > 0) {
5634 $sql .= " AND f.fk_soc = ".((int) $socid);
5635 }
5636 //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
5637 $sql .= " ORDER BY f.ref";
5638
5639 dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
5640 $resql = $this->db->query($sql);
5641 if ($resql) {
5642 while ($obj = $this->db->fetch_object($resql)) {
5643 $return[$obj->rowid] = array(
5644 'id' => $obj->rowid,
5645 'ref' => $obj->ref,
5646 'status' => $obj->status,
5647 'paid' => $obj->paid,
5648 'alreadypaid' => 0
5649 );
5650 }
5651 //print_r($return);
5652 return $return;
5653 } else {
5654 $this->error = $this->db->error();
5655 return -1;
5656 }
5657 }
5658
5659
5660 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5670 public function list_qualified_avoir_invoices($socid = 0)
5671 {
5672 // phpcs:enable
5673 global $conf;
5674
5675 $return = array();
5676
5677 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement, f.multicurrency_code";
5678 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5679 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
5680 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
5681 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5682 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5683 // $sql.= " WHERE f.fk_statut >= 1";
5684 // $sql.= " AND (f.paye = 1"; // Classee payee completement
5685 // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
5686 $sql .= " AND ff.type IS NULL"; // Return true if there isn't any replacement invoice
5687 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
5688
5689 if (getDolGlobalString('INVOICE_USE_SITUATION_CREDIT_NOTE')) {
5690 // Keep invoices that are not situation invoices or that are the last in series if it is a situation invoice
5691 $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
5692 $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID because of the group by later
5693 $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
5694 $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
5695 $sql .= " AND fs.type = ".self::TYPE_SITUATION;
5696 $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5697 if ($socid > 0) {
5698 $sql .= " AND fs.fk_soc = ".((int) $socid);
5699 }
5700 $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
5701 $sql .= ")";
5702 } else {
5703 $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
5704 }
5705
5706 if ($socid > 0) {
5707 $sql .= " AND f.fk_soc = ".((int) $socid);
5708 }
5709
5710 if (getDolGlobalInt('LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5711 $sql .= " ORDER BY CASE WHEN f.rowid = ".((int) GETPOST('fac_avoir'))." THEN 0 ELSE 1 END, f.ref";
5712 $sql .= " DESC";
5713 $sql .= $this->db->plimit(getDolGlobalInt('LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5714 } else {
5715 $sql .= " ORDER BY f.ref";
5716 }
5717
5718 dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
5719 $resql = $this->db->query($sql);
5720 if ($resql) {
5721 while ($obj = $this->db->fetch_object($resql)) {
5722 $qualified = 0;
5723 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5724 $qualified = 1;
5725 }
5726 if ($obj->fk_statut == self::STATUS_CLOSED) {
5727 $qualified = 1;
5728 }
5729 if ($qualified) {
5730 //$ref=$obj->ref;
5731 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5732 $return[$obj->rowid] = array('ref' => $obj->ref, 'status' => $obj->fk_statut, 'type' => $obj->type, 'paye' => $obj->paye, 'paymentornot' => $paymentornot, 'multicurrency_code' => $obj->multicurrency_code);
5733 }
5734 }
5735
5736 return $return;
5737 } else {
5738 $this->error = $this->db->error();
5739 return -1;
5740 }
5741 }
5742
5743
5744 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5751 public function load_board($user)
5752 {
5753 // phpcs:enable
5754 global $conf, $langs;
5755
5756 $sanitizedclause = " WHERE";
5757
5758 $now = dol_now();
5759 $warningdelay = getWarningDelay('invoice', 'client');
5760
5761 // The count, the total and the number of late invoices are computed by the database: reading every unpaid invoice to
5762 // count them in PHP took seconds on the home page of an instance with a lot of unpaid invoices. An invoice is late when
5763 // its due date is before now minus the warning delay, the rule of hasDelay() for a validated invoice (an invoice without
5764 // due date was counted as late by that rule, this is kept).
5765 $sql = "SELECT COUNT(f.rowid) as nb, SUM(f.total_ht) as total,";
5766 $sql .= " SUM(CASE WHEN f.date_lim_reglement IS NULL OR f.date_lim_reglement < '".$this->db->idate($now - $warningdelay)."' THEN 1 ELSE 0 END) as nblate";
5767 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5768 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5769 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5770 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5771 $sanitizedclause = " AND";
5772 }
5773 $sql .= $sanitizedclause." f.paye=0";
5774 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5775 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
5776 if ($user->socid) {
5777 $sql .= " AND f.fk_soc = ".((int) $user->socid);
5778 }
5779
5780 $resql = $this->db->query($sql);
5781 if ($resql) {
5782 $langs->load("bills");
5783 $response = new WorkboardResponse();
5784 $response->warning_delay = $warningdelay / 60 / 60 / 24;
5785 $response->label = $langs->trans("CustomerBillsUnpaid");
5786 $response->labelShort = $langs->trans("Unpaid");
5787 $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5788 $response->img = img_object('', "bill");
5789
5790 $obj = $this->db->fetch_object($resql);
5791 if ($obj) {
5792 $response->nbtodo = (int) $obj->nb;
5793 $response->total = (float) $obj->total;
5794 $response->nbtodolate = (int) $obj->nblate;
5795 if ($response->nbtodolate > 0) {
5796 $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5797 }
5798 }
5799
5800 $this->db->free($resql);
5801 return $response;
5802 } else {
5803 dol_print_error($this->db);
5804 $this->error = $this->db->error();
5805 return -1;
5806 }
5807 }
5808
5809
5810 /* Management of a bill's contacts */
5811
5817 public function getIdBillingContact()
5818 {
5819 return $this->getIdContact('external', 'BILLING');
5820 }
5821
5827 public function getIdShippingContact()
5828 {
5829 return $this->getIdContact('external', 'SHIPPING');
5830 }
5831
5832
5841 public function initAsSpecimen($option = '')
5842 {
5843 global $conf, $langs, $user;
5844
5845 $now = dol_now();
5846 $arraynow = dol_getdate($now);
5847 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
5848
5849 // Load array of products prodids
5850 $num_prods = 0;
5851 $prodids = array();
5852 $sql = "SELECT rowid";
5853 $sql .= " FROM ".MAIN_DB_PREFIX."product";
5854 $sql .= " WHERE entity IN (".getEntity('product').")";
5855 $sql .= $this->db->plimit(100);
5856
5857 $resql = $this->db->query($sql);
5858 if ($resql) {
5859 $num_prods = $this->db->num_rows($resql);
5860 $i = 0;
5861 while ($i < $num_prods) {
5862 $i++;
5863 $row = $this->db->fetch_row($resql);
5864 $prodids[$i] = $row[0];
5865 }
5866 }
5867 //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
5868 if (empty($num_prods)) {
5869 $num_prods = 1;
5870 $prodids[$num_prods] = 1;
5871 }
5872
5873 // Initialize parameters
5874 $this->id = 0;
5875 $this->entity = $conf->entity;
5876 $this->ref = 'SPECIMEN';
5877 $this->specimen = 1;
5878 $this->socid = 1;
5879 $this->date = $nownotime;
5880 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5881 $this->cond_reglement_id = 1;
5882 $this->cond_reglement_code = 'RECEP';
5883 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
5884 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
5885 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
5886
5887 $this->note_public = 'This is a comment (public)';
5888 $this->note_private = 'This is a comment (private)';
5889
5890 $this->user_creation_id = $user->id;
5891
5892 $this->multicurrency_tx = 1;
5893 $this->multicurrency_code = $conf->currency;
5894
5895 $this->fk_incoterms = 0;
5896 $this->location_incoterms = '';
5897
5898 $this->pos_print_counter = 0; // Already printed 0 times
5899 $this->email_sent_counter = 0; // Already sent by email 0 times
5900
5901 $this->status = 0;
5902
5903 if (empty($option) || $option != 'nolines') {
5904 // Lines
5905 $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)
5906 $xnbp = 0;
5907 while ($xnbp < $nbp) {
5908 $line = new FactureLigne($this->db);
5909 $line->desc = $langs->trans("Description")." ".$xnbp;
5910 $line->qty = 1;
5911 $line->subprice = 100;
5912 $line->tva_tx = 19.6;
5913 $line->localtax1_tx = 0;
5914 $line->localtax2_tx = 0;
5915 $line->remise_percent = 0;
5916 if ($xnbp == 1 && $option != 'takepos' && $option != 'nonegativeup') { // Qty is negative (product line)
5917 $prodid = mt_rand(1, $num_prods);
5918 if (isset($prodids[$prodid])) {
5919 $line->fk_product = $prodids[$prodid];
5920 }
5921 $line->qty = -1;
5922 $line->total_ht = -100;
5923 $line->total_ttc = -119.6;
5924 $line->total_tva = -19.6;
5925 $line->multicurrency_total_ht = -200;
5926 $line->multicurrency_total_ttc = -239.2;
5927 $line->multicurrency_total_tva = -39.2;
5928 } elseif ($xnbp == 2 && $option != 'takepos' && $option != 'nonegativeup') { // UP is negative (free line)
5929 $line->subprice = -100;
5930 $line->total_ht = -100;
5931 $line->total_ttc = -119.6;
5932 $line->total_tva = -19.6;
5933 $line->remise_percent = 0;
5934 $line->multicurrency_total_ht = -200;
5935 $line->multicurrency_total_ttc = -239.2;
5936 $line->multicurrency_total_tva = -39.2;
5937 } elseif ($xnbp == 3) { // Discount is 50% (product line)
5938 $prodid = mt_rand(1, $num_prods);
5939 if (isset($prodids[$prodid])) {
5940 $line->fk_product = $prodids[$prodid];
5941 }
5942 $line->total_ht = 50;
5943 $line->total_ttc = 59.8;
5944 $line->total_tva = 9.8;
5945 $line->multicurrency_total_ht = 100;
5946 $line->multicurrency_total_ttc = 119.6;
5947 $line->multicurrency_total_tva = 19.6;
5948 $line->remise_percent = 50;
5949 } else { // (product line)
5950 $prodid = mt_rand(1, $num_prods);
5951 if (isset($prodids[$prodid])) {
5952 $line->fk_product = $prodids[$prodid];
5953 }
5954 $line->total_ht = 100;
5955 $line->total_ttc = 119.6;
5956 $line->total_tva = 19.6;
5957 $line->multicurrency_total_ht = 200;
5958 $line->multicurrency_total_ttc = 239.2;
5959 $line->multicurrency_total_tva = 39.2;
5960 $line->remise_percent = 0;
5961 }
5962
5963 $this->lines[$xnbp] = $line;
5964
5965
5966 $this->total_ht += $line->total_ht;
5967 $this->total_tva += $line->total_tva;
5968 $this->total_ttc += $line->total_ttc;
5969
5970 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5971 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5972 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5973
5974 $xnbp++;
5975 }
5976 $this->revenuestamp = 0;
5977
5978 // Add a line "offered"
5979 if ($option != 'takepos') {
5980 $line = new FactureLigne($this->db);
5981 $line->desc = $langs->trans("Description")." (offered line)";
5982 $line->qty = 1;
5983 $line->subprice = 100;
5984 $line->tva_tx = 19.6;
5985 $line->localtax1_tx = 0;
5986 $line->localtax2_tx = 0;
5987 $line->remise_percent = 100;
5988 $line->total_ht = 0;
5989 $line->total_ttc = 0; // 90 * 1.196
5990 $line->total_tva = 0;
5991 $line->multicurrency_total_ht = 0;
5992 $line->multicurrency_total_ttc = 0;
5993 $line->multicurrency_total_tva = 0;
5994 $prodid = mt_rand(1, $num_prods);
5995 if (isset($prodids[$prodid])) {
5996 $line->fk_product = $prodids[$prodid];
5997 }
5998
5999 $this->lines[$xnbp] = $line;
6000 $xnbp++;
6001 }
6002 }
6003
6004 return 1;
6005 }
6006
6012 public function loadStateBoard()
6013 {
6014 global $user;
6015
6016 $this->nb = array();
6017
6018 $sanitizedclause = "WHERE";
6019
6020 $sql = "SELECT count(f.rowid) as nb";
6021 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
6022 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
6023 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
6024 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
6025 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
6026 $sanitizedclause = "AND";
6027 }
6028 $sql .= " ".$sanitizedclause." f.entity IN (".getEntity('invoice').")";
6029
6030 $resql = $this->db->query($sql);
6031 if ($resql) {
6032 while ($obj = $this->db->fetch_object($resql)) {
6033 $this->nb["invoices"] = $obj->nb;
6034 }
6035 $this->db->free($resql);
6036 return 1;
6037 } else {
6038 dol_print_error($this->db);
6039 $this->error = $this->db->error();
6040 return -1;
6041 }
6042 }
6043
6050 {
6051 $context = parent::getObjectLinesDisplayContext();
6052 $context['inputalsopricewithtax'] = 1;
6053
6054 return $context;
6055 }
6056
6062 public function getLinesArray()
6063 {
6064 return $this->fetch_lines();
6065 }
6066
6078 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
6079 {
6080 $outputlangs->loadLangs(array("bills", "products"));
6081
6082 if (!dol_strlen($modele)) {
6083 $modele = 'sponge';
6084 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
6085
6086 if (!empty($this->model_pdf)) {
6087 $modele = $this->model_pdf;
6088 } elseif (getDolGlobalString($thisTypeConfName)) {
6089 $modele = getDolGlobalString($thisTypeConfName);
6090 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
6091 $modele = getDolGlobalString('FACTURE_ADDON_PDF');
6092 }
6093 }
6094
6095 $modelpath = "core/modules/facture/doc/";
6096
6097 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
6098 }
6099
6105 public function newCycle()
6106 {
6107 $sql = "SELECT max(situation_cycle_ref) as maxsituationref";
6108 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
6109 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
6110
6111 $resql = $this->db->query($sql);
6112 if ($resql) {
6113 if ($this->db->num_rows($resql) > 0) {
6114 $ref = 0;
6115 $obj = $this->db->fetch_object($resql);
6116 if ($obj) {
6117 $ref = (int) $obj->maxsituationref;
6118 }
6119 $ref++;
6120 } else {
6121 $ref = 1;
6122 }
6123 $this->db->free($resql);
6124 return $ref;
6125 } else {
6126 $this->error = $this->db->lasterror();
6127 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
6128 return -1;
6129 }
6130 }
6131
6132 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6138 public function is_first()
6139 {
6140 // phpcs:enable
6141 return ($this->situation_counter == 1);
6142 }
6143
6144 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6150 public function get_prev_sits()
6151 {
6152 // phpcs:enable
6153 global $conf;
6154
6155 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
6156 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
6157 $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
6158 $sql .= ' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int) $conf->entity));
6159 $resql = $this->db->query($sql);
6160 $res = array();
6161 if ($resql && $this->db->num_rows($resql) > 0) {
6162 while ($row = $this->db->fetch_object($resql)) {
6163 $id = $row->rowid;
6164 $situation = new Facture($this->db);
6165 $situation->fetch($id);
6166 $res[] = $situation;
6167 }
6168 } else {
6169 $this->error = $this->db->error();
6170 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
6171 return -1;
6172 }
6173
6174 return $res;
6175 }
6176
6184 public function setFinal(User $user, $notrigger = 0)
6185 {
6186 $error = 0;
6187
6188 $this->db->begin();
6189
6190 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
6191
6192 dol_syslog(__METHOD__, LOG_DEBUG);
6193 $resql = $this->db->query($sql);
6194 if (!$resql) {
6195 $this->errors[] = $this->db->error();
6196 $error++;
6197 }
6198
6199 if (!$notrigger && empty($error)) {
6200 // Call trigger
6201 $result = $this->call_trigger('BILL_MODIFY', $user);
6202 if ($result < 0) {
6203 $error++;
6204 }
6205 // End call triggers
6206 }
6207
6208 if (!$error) {
6209 $this->db->commit();
6210 return 1;
6211 } else {
6212 foreach ($this->errors as $errmsg) {
6213 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
6214 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
6215 }
6216 $this->db->rollback();
6217 return -1 * $error;
6218 }
6219 }
6220
6221 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6227 public function is_last_in_cycle()
6228 {
6229 // phpcs:enable
6230 global $conf;
6231
6232 if (!empty($this->situation_cycle_ref)) {
6233 // No point in testing anything if we're not inside a cycle
6234 $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
6235 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
6236 $sql .= ' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int) $conf->entity));
6237 $resql = $this->db->query($sql);
6238
6239 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
6240 $last = $res['max(situation_counter)'];
6241 return ($last == $this->situation_counter);
6242 } else {
6243 $this->error = $this->db->lasterror();
6244 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6245 return false;
6246 }
6247 } else {
6248 return true;
6249 }
6250 }
6251
6260 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
6261 {
6262 $tables = array(
6263 'facture'
6264 );
6265
6266 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
6267 }
6268
6277 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
6278 {
6279 $tables = array(
6280 'facturedet'
6281 );
6282
6283 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
6284 }
6285
6291 public function hasDelay()
6292 {
6293 global $conf;
6294
6295 $now = dol_now();
6296
6297 // Paid invoices have status STATUS_CLOSED
6298 if ($this->status != Facture::STATUS_VALIDATED) {
6299 return false;
6300 }
6301
6302 $hasDelay = $this->date_lim_reglement < ($now - getWarningDelay('invoice', 'client'));
6303 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6304 $totalpaid = $this->getSommePaiement(0);
6305 $totalpaid = (float) $totalpaid;
6306 $retainedWarrantyAmount = $this->getRetainedWarrantyAmount('MT');
6307 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
6308 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now - getWarningDelay('invoice', 'client'))) {
6309 $hasDelay = 1;
6310 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - getWarningDelay('invoice', 'client'))) {
6311 $hasDelay = 1;
6312 } else {
6313 $hasDelay = 0;
6314 }
6315 }
6316 }
6317
6318 return $hasDelay;
6319 }
6320
6326 public function isSituationInvoice()
6327 {
6328 return $this->situation_cycle_ref;
6329 }
6330
6335 public function displayRetainedWarranty()
6336 {
6337 // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
6338
6339 // 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
6340
6341 $displayWarranty = false;
6342 if (!empty($this->retained_warranty)) {
6343 $displayWarranty = true;
6344
6345 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
6346 // Check if this situation invoice is 100% for real
6347 $displayWarranty = false;
6348 if (!empty($this->situation_final)) {
6349 $displayWarranty = true;
6350 } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
6351 // $object->situation_final need validation to be done so this test is need for draft
6352 $displayWarranty = true;
6353
6354 foreach ($this->lines as $i => $line) {
6355 if ($line->product_type < 2 && $line->situation_percent < 100) {
6356 $displayWarranty = false;
6357 break;
6358 }
6359 }
6360 }
6361 }
6362 }
6363
6364 return $displayWarranty;
6365 }
6366
6373 public function getRetainedWarrantyAmount($rounding = 'MT')
6374 {
6375 if (empty($this->retained_warranty)) {
6376 return -1;
6377 }
6378
6379 $retainedWarrantyAmount = 0;
6380
6381 // Billed - retained warranty
6382 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
6383 $displayWarranty = true;
6384 // Check if this situation invoice is 100% for real
6385 if (!empty($this->lines)) {
6386 foreach ($this->lines as $i => $line) {
6387 if ($line->product_type < 2 && $line->situation_percent < 100) {
6388 $displayWarranty = false;
6389 break;
6390 }
6391 }
6392 }
6393
6394 if ($displayWarranty && !empty($this->situation_final)) {
6396 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6397
6398 // Sum the total including tax of all previous invoices, including the current one.
6399 $total2BillWT = 0;
6400 foreach ($TPreviousIncoice as &$fac) {
6401 $total2BillWT += $fac->total_ttc;
6402 }
6403 $total2BillWT += $this->total_ttc;
6404
6405 // Take the percent
6406 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6407 } else {
6408 return -1;
6409 }
6410 } else {
6411 // Because one day retained warranty could be used on standard invoices
6412 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6413 }
6414
6415 if (is_numeric($rounding) && $rounding < 0) {
6416 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
6417 }
6418
6419 if (is_numeric($rounding) && $rounding > 0) {
6420 return round($retainedWarrantyAmount, $rounding);
6421 }
6422
6423 return (float) price2num($retainedWarrantyAmount, $rounding);
6424 }
6425
6432 public function setRetainedWarranty($value)
6433 {
6434 dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
6435
6436 if ($this->status >= 0) {
6437 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6438 $sql .= " SET retained_warranty = ".((float) $value);
6439 $sql .= ' WHERE rowid='.((int) $this->id);
6440
6441 if ($this->db->query($sql)) {
6442 $this->retained_warranty = (float) $value;
6443 return 1;
6444 } else {
6445 dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
6446 $this->error = $this->db->error();
6447 return -1;
6448 }
6449 } else {
6450 dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
6451 $this->error = 'Status of the object is incompatible '.$this->status;
6452 return -2;
6453 }
6454 }
6455
6456
6464 public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '')
6465 {
6466 if (!$timestamp && $dateYmd) {
6467 $timestamp = $this->db->jdate($dateYmd);
6468 }
6469
6470
6471 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
6472 if ($this->status >= 0) {
6473 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6474 $sql .= " SET retained_warranty_date_limit = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
6475 $sql .= ' WHERE rowid = '.((int) $this->id);
6476
6477 if ($this->db->query($sql)) {
6478 $this->retained_warranty_date_limit = $timestamp;
6479 return 1;
6480 } else {
6481 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
6482 $this->error = $this->db->error();
6483 return -1;
6484 }
6485 } else {
6486 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6487 $this->error = 'Status of the object is incompatible '.$this->status;
6488 return -2;
6489 }
6490 }
6491
6492
6506 public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
6507 {
6508 global $conf, $langs, $user;
6509
6510 $error = 0;
6511 $this->output = '';
6512 $this->error = '';
6513 $nbMailSend = 0;
6514 $errorsMsg = array();
6515
6516 $langs->load("bills");
6517
6518 if (!isModEnabled('invoice')) { // Should not happen. If module disabled, cron job should not be visible.
6519 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Invoice"));
6520 return 0;
6521 }
6522 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
6523 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6524 return 0;
6525 }
6526
6527 // Build list of forced recipients (separator is ';' because cron splits parameters on ',')
6528 $arrayforcerecipient = array();
6529 foreach (explode(';', (string) $forcerecipient) as $tmpvalue) {
6530 $tmpvalue = trim($tmpvalue);
6531 if ($tmpvalue !== '') {
6532 if (!in_array($tmpvalue, array('thirdpartyemail', 'externalbillingcontacts', 'salesrepresentative')) && !isValidEmail($tmpvalue)) {
6533 $this->output .= 'Bad value "'.$tmpvalue.'" for parameter forcerecipient. Must be an email, "thirdpartyemail", "externalbillingcontacts" or "salesrepresentative"';
6534 return 0;
6535 }
6536 $arrayforcerecipient[] = $tmpvalue;
6537 }
6538 }
6539 $forcerecipient = implode(';', $arrayforcerecipient);
6540 if (empty($arrayforcerecipient)) {
6541 $arrayforcerecipient = array('thirdpartyemail');
6542 }
6543 /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
6544 $langs->load("bills");
6545 $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Invoice"));
6546 return 0;
6547 }
6548 */
6549
6550 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
6551 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
6552 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
6553 $formmail = new FormMail($this->db);
6554
6555 $now = dol_now();
6556 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
6557
6558 $tmpinvoice = new Facture($this->db);
6559
6560 dol_syslog(__METHOD__." start", LOG_INFO);
6561
6562 // Label of the agenda event recorded for each reminder sent. It also allows to know that a reminder was already sent for an invoice.
6563 $labelreminderok = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
6564
6565 // Select all action comm reminder
6566 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
6567 if (!empty($paymentmode) && $paymentmode != 'all') {
6568 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
6569 }
6570 $sql .= " WHERE f.paye = 0"; // Only unpaid
6571 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
6572 if ($datetouse == 'invoicedate') {
6573 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
6574 } else {
6575 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
6576 }
6577 $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch processes only one company (no sharing)
6578 if (!empty($paymentmode) && $paymentmode != 'all') {
6579 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
6580 }
6581 // A credit note is not an amount that the customer has to pay, and an invoice without an amount to pay has nothing to remind
6582 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE;
6583 $sql .= " AND f.total_ttc > 0";
6584 // Do not send the same reminder twice if the batch is run again the same day (an event is recorded when a reminder is sent)
6585 $sql .= " AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX."actioncomm as a";
6586 $sql .= " WHERE a.elementtype = 'invoice' AND a.fk_element = f.rowid AND a.code = 'AC_EMAIL'";
6587 $sql .= " AND a.label = '".$this->db->escape($labelreminderok)."'";
6588 $sql .= " AND a.datep >= '".$this->db->idate(dol_get_first_hour($now))."')";
6589 if ($datetouse == 'invoicedate') {
6590 $sql .= $this->db->order("datef", "ASC");
6591 } else {
6592 $sql .= $this->db->order("date_lim_reglement", "ASC");
6593 }
6594
6595 $resql = $this->db->query($sql);
6596
6597 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
6598 if ($datetouse == 'invoicedate') {
6599 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedInvoicesWithDate", $stmpidate);
6600 } else {
6601 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
6602 }
6603 if (!empty($paymentmode) && $paymentmode != 'all') {
6604 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
6605 }
6606 $this->output .= '<br>';
6607
6608 if ($resql) {
6609 while ($obj = $this->db->fetch_object($resql)) {
6610 // Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
6611 $loopError = 0;
6612
6613 // Load event
6614 $res = $tmpinvoice->fetch($obj->id);
6615 if ($res > 0) {
6616 $tmpinvoice->fetch_thirdparty();
6617 // Load paid amounts so that __AMOUNT_REMAIN__ is the real remaining amount
6618 $tmpinvoice->getSommePaiement();
6619 $tmpinvoice->getSumCreditNotesUsed();
6620 $tmpinvoice->getSumDepositsUsed();
6621
6622 $outputlangs = new Translate('', $conf);
6623 if ($tmpinvoice->thirdparty->default_lang) {
6624 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6625 $outputlangs->loadLangs(array("main", "bills"));
6626 } else {
6627 $outputlangs = $langs;
6628 }
6629
6630 // Select email template according to language of recipient
6631 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
6632 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6633 $langs->load("errors");
6634 if (is_numeric($template)) {
6635 // The cron was started with a template id and that id cannot be
6636 // resolved at all. This is almost certainly a global setup error
6637 // (template deleted or wrong id passed to the cron), and every
6638 // remaining invoice in this batch would fail the same way. Stop
6639 // here so the operator can fix the setup before retrying, instead
6640 // of flooding the cron output with one identical error per
6641 // invoice (per @eldy's review of PR #38547).
6642 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
6643 return 0;
6644 }
6645 // The cron was started with a template label and getEMailTemplate
6646 // also filters by the recipient's language (see html.formmail.class.php
6647 // line 1786). Only the invoices for thirdparties whose default_lang
6648 // has no matching template fail; the rest of the batch is fine.
6649 // Log the error and continue so a single missing translation does
6650 // not stop reminders for everyone else (see issue #34656).
6651 $errorsMsg[] = $langs->trans('ErrorFailedToFindEmailTemplate', $template).' (invoice '.$tmpinvoice->ref.')';
6652 continue;
6653 }
6654
6655 // PREPARE EMAIL
6656 $errormesg = '';
6657
6658 // Make substitution in email content
6659 $tmpinvoice->totalpaid = $tmpinvoice->getSommePaiement();
6660 $tmpinvoice->totalcreditnotes = $tmpinvoice->getSumCreditNotesUsed();
6661 $tmpinvoice->totaldeposits = $tmpinvoice->getSumDepositsUsed();
6662 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $tmpinvoice);
6663
6664 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
6665
6666 // Topic
6667 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6668
6669 // Content
6670 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6671
6672 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
6673
6674 // Recipient
6675 $to = array();
6676 $res = $tmpinvoice->fetch_thirdparty();
6677 $recipient = $tmpinvoice->thirdparty;
6678 if ($res > 0) {
6679 foreach ($arrayforcerecipient as $tmpforcerecipient) {
6680 if ($tmpforcerecipient == 'thirdpartyemail') {
6681 if (!empty($recipient->email)) {
6682 $to[] = $recipient->email;
6683 }
6684 } elseif ($tmpforcerecipient == 'externalbillingcontacts') {
6685 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
6686 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6687 foreach ($tmparraycontact as $data_email) {
6688 if (!empty($data_email['email'])) {
6689 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
6690 }
6691 }
6692 }
6693 } elseif ($tmpforcerecipient == 'salesrepresentative') {
6694 $tmparraysalesrep = $recipient->getSalesRepresentatives($user);
6695 if (is_array($tmparraysalesrep)) {
6696 foreach ($tmparraysalesrep as $salesrep) {
6697 if (!empty($salesrep['email']) && !empty($salesrep['status'])) {
6698 $to[] = $salesrep['email'];
6699 }
6700 }
6701 }
6702 } else { // A fixed email
6703 $to[] = $tmpforcerecipient;
6704 }
6705 }
6706 $to = array_values(array_unique(array_filter($to)));
6707 if (empty($to)) {
6708 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email found for recipients ".implode(";", $arrayforcerecipient).".";
6709 $loopError++;
6710 }
6711 } else {
6712 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6713 $loopError++;
6714 }
6715
6716 // Sender
6717 $email_from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
6718 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
6719 $email_from = (string) $arraymessage->email_from;
6720 }
6721 if (empty($email_from)) {
6722 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6723 $loopError++;
6724 }
6725
6726 if (!$loopError && !empty($to)) {
6727 $to = implode(',', $to);
6728 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
6729 $to = $to.','.$arraymessage->email_to;
6730 }
6731
6732 // Errors Recipient
6733 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
6734
6735 $trackid = 'inv'.$tmpinvoice->id;
6736 $sendcontext = 'standard';
6737
6738 $email_tocc = '';
6739 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
6740 $email_tocc = (string) $arraymessage->email_tocc;
6741 }
6742
6743 $email_tobcc = '';
6744 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
6745 $email_tobcc = (string) $arraymessage->email_tobcc;
6746 }
6747
6748 //join file is asked
6749 $joinFile = [];
6750 $joinFileName = [];
6751 $joinFileMime = [];
6752 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6753 $joinFile[] = DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc;
6754 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6755 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc);
6756 }
6757
6758 // Mail Creation
6759 $cMailFile = new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
6760
6761 $resultsendmail = $cMailFile->sendfile();
6762
6763 $this->db->begin();
6764
6765 // Sending Mail
6766 if ($resultsendmail) {
6767 $nbMailSend++;
6768
6769 // Add a line into event table
6770 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6771
6772 // Insert record of emails sent
6773 $actioncomm = new ActionComm($this->db);
6774
6775 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6776 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6777 $actioncomm->contact_id = 0;
6778
6779 $actioncomm->code = 'AC_EMAIL';
6780 $actioncomm->label = $labelreminderok;
6781 $actioncomm->note_private = $sendContent;
6782 $actioncomm->fk_project = $tmpinvoice->fk_project;
6783 $actioncomm->datep = dol_now();
6784 $actioncomm->datef = $actioncomm->datep;
6785 $actioncomm->percentage = -1; // Not applicable
6786 $actioncomm->authorid = $user->id; // User saving action
6787 $actioncomm->userownerid = $user->id; // Owner of action
6788 // Fields when action is an email (content should be added into note)
6789 $actioncomm->email_msgid = $cMailFile->msgid;
6790 $actioncomm->email_subject = $sendTopic;
6791 $actioncomm->email_from = $email_from;
6792 $actioncomm->email_sender = '';
6793 $actioncomm->email_to = $to;
6794 //$actioncomm->email_tocc = $sendtocc;
6795 //$actioncomm->email_tobcc = $sendtobcc;
6796 //$actioncomm->email_subject = $subject;
6797 $actioncomm->errors_to = $errors_to;
6798
6799 $actioncomm->elementtype = 'invoice';
6800 $actioncomm->elementid = $tmpinvoice->id;
6801
6802 //$actioncomm->extraparams = $extraparams;
6803
6804 $actioncomm->create($user);
6805 } else {
6806 $errormesg = $cMailFile->error.' : '.$to;
6807 $loopError++;
6808
6809 // Add a line into event table
6810 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6811
6812 // Insert record of emails sent
6813 $actioncomm = new ActionComm($this->db);
6814
6815 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6816 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6817 $actioncomm->contact_id = 0;
6818
6819 $actioncomm->code = 'AC_EMAIL';
6820 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
6821 $actioncomm->note_private = $errormesg;
6822 $actioncomm->fk_project = $tmpinvoice->fk_project;
6823 $actioncomm->datep = dol_now();
6824 $actioncomm->datef = $actioncomm->datep;
6825 $actioncomm->percentage = -1; // Not applicable
6826 $actioncomm->authorid = $user->id; // User saving action
6827 $actioncomm->userownerid = $user->id; // Owner of action
6828 // Fields when action is an email (content should be added into note)
6829 $actioncomm->email_msgid = $cMailFile->msgid;
6830 $actioncomm->email_subject = $sendTopic;
6831 $actioncomm->email_from = $email_from;
6832 $actioncomm->email_sender = '';
6833 $actioncomm->email_to = $to;
6834 //$actioncomm->email_tocc = $sendtocc;
6835 //$actioncomm->email_tobcc = $sendtobcc;
6836 //$actioncomm->email_subject = $subject;
6837 $actioncomm->errors_to = $errors_to;
6838
6839 $actioncomm->elementtype = 'invoice';
6840 $actioncomm->elementid = $tmpinvoice->id;
6841
6842 //$actioncomm->extraparams = $extraparams;
6843
6844 $actioncomm->create($user);
6845 }
6846
6847 $this->db->commit(); // We always commit
6848 }
6849
6850 if ($errormesg) {
6851 $errorsMsg[] = $errormesg;
6852 }
6853 } else {
6854 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
6855 $loopError++;
6856 }
6857
6858 $error += $loopError;
6859 }
6860 } else {
6861 $error++;
6862 }
6863
6864 if (!$error) {
6865 $this->output .= 'Nb of emails sent : '.$nbMailSend;
6866
6867 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
6868
6869 return 0;
6870 } else {
6871 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
6872
6873 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
6874
6875 return $error;
6876 }
6877 }
6878
6885 public function willBeLastOfSameType($allow_validated_drafts = false)
6886 {
6887 // get date of last validated invoices of same type
6888 $sql = "SELECT datef";
6889 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
6890 $sql .= " WHERE type = " . (int) $this->type ;
6891 $sql .= " AND date_valid IS NOT NULL";
6892 $sql .= " AND entity IN (".getEntity('invoice').")";
6893 $sql .= " ORDER BY datef DESC LIMIT 1";
6894
6895 $result = $this->db->query($sql);
6896 if ($result) {
6897 // compare with current validation date
6898 if ($this->db->num_rows($result)) {
6899 $obj = $this->db->fetch_object($result);
6900 $last_date = $this->db->jdate($obj->datef);
6901 $invoice_date = $this->date;
6902
6903 $is_last_of_same_type = $invoice_date >= $last_date;
6904 if ($allow_validated_drafts) {
6905 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
6906 }
6907
6908 return array($is_last_of_same_type, $last_date);
6909 } else {
6910 // element is first of type to be validated
6911 return array(true);
6912 }
6913 } else {
6914 dol_print_error($this->db);
6915 }
6916
6917 return array();
6918 }
6919
6927 public function getKanbanView($option = '', $arraydata = null)
6928 {
6929 global $langs;
6930
6931 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6932
6933 $picto = $this->picto;
6934 if ($this->type == self::TYPE_REPLACEMENT) {
6935 $picto .= 'r'; // Replacement invoice
6936 }
6937 if ($this->type == self::TYPE_CREDIT_NOTE) {
6938 $picto .= 'a'; // Credit note
6939 }
6940 if ($this->type == self::TYPE_DEPOSIT) {
6941 $picto .= 'd'; // Deposit invoice
6942 }
6943
6944 $return = '<div class="box-flex-item box-flex-grow-zero">';
6945 $return .= '<div class="info-box info-box-sm">';
6946 $return .= '<span class="info-box-icon bg-infobox-action">';
6947 $return .= img_picto('', $picto);
6948 $return .= '</span>';
6949 $return .= '<div class="info-box-content">';
6950 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
6951 if ($selected >= 0) {
6952 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6953 }
6954 if (!empty($arraydata['thirdparty'])) {
6955 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
6956 }
6957 if (property_exists($this, 'date')) {
6958 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
6959 }
6960 if (property_exists($this, 'total_ht')) {
6961 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
6962 $return .= ' '.$langs->trans("HT");
6963 $return .= '</span>';
6964 }
6965 if (method_exists($this, 'getLibStatut')) {
6966 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
6967 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
6968 }
6969 $return .= '</div>';
6970 $return .= '</div>';
6971 $return .= '</div>';
6972 return $return;
6973 }
6974}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
checkPointOfTaxNotChanged()
Check that the point of tax date of a validated invoice is not changed by an update.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage standard extra fields.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Returns the IDs of the customer shipping contacts.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
createFromClone(User $user, $fromid=0, $forceentity=null)
Load an object from its id and create a new one in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
__construct($db)
Constructor.
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.
const STATUS_DRAFT
Draft status.
persistFieldValue(User $user, $field)
Save into database the current value of one field, called by updateFieldFromUi().
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.
consumeDepositCredits(User $user, Facture $depositInvoice, float $amount_ttc)
Consume unused deposit credit rows (llx_societe_remise_except) up to $amount_ttc.
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.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card before printObjectLines() and formAdd...
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 projects.
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:686
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:672
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:626
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:564
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
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:66
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
dolPayRefGenerateForInvoice($object, $user, $store=1)
Generate and optionally store the payment reference of an invoice.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.