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