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