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