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