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