dolibarr  17.0.4
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) 2022 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 
120  public $fk_user_author;
121 
125  public $fk_user_valid;
126 
130  public $fk_user_modif;
131 
132 
133  public $date; // Date invoice
134  public $datem;
135 
141  public $date_livraison;
142 
146  public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
147 
153  public $ref_client;
154 
158  public $ref_customer;
159 
160  //Check constants for types
161  public $type = self::TYPE_STANDARD;
162 
163  // Warning: Do not set default value into property defintion. it must stay null.
164  // For example to avoid to have substition done when object is generic and not yet defined.
165  public $remise_absolue;
166  public $remise_percent;
167  public $total_ht;
168  public $total_tva;
169  public $total_localtax1;
170  public $total_localtax2;
171  public $total_ttc;
172  public $revenuestamp;
173 
174  public $resteapayer;
175 
181  public $close_code;
182 
187  public $close_note;
188 
192  public $paye;
193 
197  public $pos_source;
202  public $linked_objects = array();
203 
204  public $date_lim_reglement;
205  public $cond_reglement_code; // Code in llx_c_paiement
206  public $mode_reglement_code; // Code in llx_c_paiement
207 
211  public $fk_bank;
212 
216  public $lines = array();
217 
218  public $line;
219  public $extraparams = array();
220 
221  public $fac_rec;
222 
223  public $date_pointoftax;
224 
225  // Multicurrency
229  public $fk_multicurrency;
230 
231  public $multicurrency_code;
232  public $multicurrency_tx;
233  public $multicurrency_total_ht;
234  public $multicurrency_total_tva;
235  public $multicurrency_total_ttc;
236 
240  public $situation_cycle_ref;
241 
245  public $situation_counter;
246 
250  public $situation_final;
251 
255  public $tab_previous_situation_invoice = array();
256 
260  public $tab_next_situation_invoice = array();
261 
262  public $oldcopy;
263 
267  public $retained_warranty;
268 
272  public $retained_warranty_date_limit;
273 
277  public $retained_warranty_fk_cond_reglement;
278 
279 
304  // BEGIN MODULEBUILDER PROPERTIES
308  public $fields = array(
309  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>1),
310  'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>5),
311  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
312  'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>10),
313  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>12),
314  'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
315  //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
316  'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>50),
317  'datef' =>array('type'=>'date', 'label'=>'DateInvoice', 'enabled'=>1, 'visible'=>1, 'position'=>20),
318  'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>22),
319  'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateDue', 'enabled'=>1, 'visible'=>1, 'position'=>25),
320  'date_closing' =>array('type'=>'datetime', 'label'=>'Date closing', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
321  'paye' =>array('type'=>'smallint(6)', 'label'=>'InvoicePaidCompletely', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>80),
322  //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85),
323  'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
324  'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>91),
325  //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
326  'close_code' =>array('type'=>'varchar(16)', 'label'=>'EarlyClosingReason', 'enabled'=>1, 'visible'=>-1, 'position'=>92),
327  'close_note' =>array('type'=>'varchar(128)', 'label'=>'EarlyClosingComment', 'enabled'=>1, 'visible'=>-1, 'position'=>93),
328  'total_ht' =>array('type'=>'double(24,8)', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>1, 'position'=>95, 'isameasure'=>1),
329  'total_tva' =>array('type'=>'double(24,8)', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>100, 'isameasure'=>1),
330  'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LT1', 'enabled'=>1, 'visible'=>-1, 'position'=>110, 'isameasure'=>1),
331  'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LT2', 'enabled'=>1, 'visible'=>-1, 'position'=>120, 'isameasure'=>1),
332  'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>115, 'isameasure'=>1),
333  'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>1, 'position'=>130, 'isameasure'=>1),
334  'fk_facture_source' =>array('type'=>'integer', 'label'=>'SourceInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
335  'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
336  'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
337  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'CurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
338  'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>190),
339  'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
340  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>205),
341  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>210),
342  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>215),
343  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
344  'situation_cycle_ref' =>array('type'=>'smallint(6)', 'label'=>'Situation cycle ref', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>230),
345  'situation_counter' =>array('type'=>'smallint(6)', 'label'=>'Situation counter', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>235),
346  'situation_final' =>array('type'=>'smallint(6)', 'label'=>'Situation final', 'enabled'=>'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1', 'visible'=>-1, 'position'=>240),
347  'retained_warranty' =>array('type'=>'double', 'label'=>'Retained warranty', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>245),
348  'retained_warranty_date_limit' =>array('type'=>'date', 'label'=>'Retained warranty date limit', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>250),
349  '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),
350  'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>260),
351  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>265),
352  'date_pointoftax' =>array('type'=>'date', 'label'=>'DatePointOfTax', 'enabled'=>'$conf->global->INVOICE_POINTOFTAX_DATE', 'visible'=>-1, 'position'=>270),
353  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>275),
354  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Currency', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>280),
355  'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'CurrencyRate', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
356  'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
357  'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>291, 'isameasure'=>1),
358  'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>292, 'isameasure'=>1),
359  'fk_fac_rec_source' =>array('type'=>'integer', 'label'=>'RecurringInvoiceSource', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
360  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>310),
361  'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>315),
362  'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>320),
363  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
364  'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>502),
365  'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>506),
366  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'notnull'=>-1, 'position'=>508),
367  'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>510),
368  'fk_user_closing' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
369  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
370  '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')),
371  );
372  // END MODULEBUILDER PROPERTIES
373 
377  const TYPE_STANDARD = 0;
378 
382  const TYPE_REPLACEMENT = 1;
383 
387  const TYPE_CREDIT_NOTE = 2;
388 
392  const TYPE_DEPOSIT = 3;
393 
397  const TYPE_PROFORMA = 4;
398 
402  const TYPE_SITUATION = 5;
403 
407  const STATUS_DRAFT = 0;
408 
412  const STATUS_VALIDATED = 1;
413 
421  const STATUS_CLOSED = 2;
422 
430  const STATUS_ABANDONED = 3;
431 
432  const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandonned remain - escompte
433  const CLOSECODE_BADDEBT = 'badcustomer'; // Abandonned remain - bad customer
434  const CLOSECODE_BANKCHARGE = 'bankcharge'; // Abandonned remain - bank charge
435  const CLOSECODE_OTHER = 'other'; // Abandonned remain - other
436 
437  const CLOSECODE_ABANDONED = 'abandon'; // Abandonned - other
438  const CLOSECODE_REPLACED = 'replaced'; // Closed after doing a replacement invoice
439 
440 
446  public function __construct(DoliDB $db)
447  {
448  $this->db = $db;
449  }
450 
461  public function create(User $user, $notrigger = 0, $forceduedate = 0)
462  {
463  global $langs, $conf, $mysoc, $hookmanager;
464  $error = 0;
465 
466  // Clean parameters
467  if (empty($this->type)) {
468  $this->type = self::TYPE_STANDARD;
469  }
470  $this->ref_client = trim($this->ref_client);
471  $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
472  $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
473  $this->note_public = trim($this->note_public);
474  if (!$this->cond_reglement_id) {
475  $this->cond_reglement_id = 0;
476  }
477  if (!$this->mode_reglement_id) {
478  $this->mode_reglement_id = 0;
479  }
480  $this->brouillon = 1;
481  $this->status = self::STATUS_DRAFT;
482  $this->statut = self::STATUS_DRAFT;
483 
484  if (!empty($this->multicurrency_code)) {
485  // Multicurrency (test on $this->multicurrency_tx because we should take the default rate of multicurrency_code only if not using original rate)
486  if (empty($this->multicurrency_tx)) {
487  // If original rate is not set, we take a default value from date
488  list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
489  } else {
490  // original rate multicurrency_tx and multicurrency_code are set, we use them
491  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
492  }
493  } else {
494  $this->fk_multicurrency = 0;
495  }
496  if (empty($this->fk_multicurrency)) {
497  $this->multicurrency_code = $conf->currency;
498  $this->fk_multicurrency = 0;
499  $this->multicurrency_tx = 1;
500  }
501 
502  dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
503 
504  // Check parameters
505  if (empty($this->date)) {
506  $this->error = "Try to create an invoice with an empty parameter (date)";
507  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
508  return -3;
509  }
510  $soc = new Societe($this->db);
511  $result = $soc->fetch($this->socid);
512  if ($result < 0) {
513  $this->error = "Failed to fetch company: ".$soc->error;
514  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
515  return -2;
516  }
517 
518  $now = dol_now();
519  $this->date_creation = $now;
520 
521  $this->db->begin();
522 
523  $originaldatewhen = null;
524  $nextdatewhen = null;
525  $previousdaynextdatewhen = null;
526 
527  // Create invoice from a template recurring invoice
528  if ($this->fac_rec > 0) {
529  $this->fk_fac_rec_source = $this->fac_rec;
530 
531  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
532  $_facrec = new FactureRec($this->db);
533  $result = $_facrec->fetch($this->fac_rec);
534  $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
535 
536  // Define some dates
537  $originaldatewhen = $_facrec->date_when;
538  $nextdatewhen = null; $previousdaynextdatewhen = null;
539  if ($originaldatewhen) {
540  $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
541  $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
542  }
543 
544  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.
545  $this->socid = $_facrec->socid;
546  }
547  $this->entity = $_facrec->entity; // Invoice created in same entity than template
548 
549  // 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
550  $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_project;
551  $this->note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
552  $this->note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
553  $this->model_pdf = GETPOSTISSET('model') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
554  $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id;
555  $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id;
556  $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
557 
558  // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
559  $this->total_ht = $_facrec->total_ht;
560  $this->total_ttc = $_facrec->total_ttc;
561 
562  // Fields always coming from template
563  $this->remise_absolue = $_facrec->remise_absolue;
564  $this->remise_percent = $_facrec->remise_percent;
565  $this->fk_incoterms = $_facrec->fk_incoterms;
566  $this->location_incoterms = $_facrec->location_incoterms;
567 
568  // Clean parameters
569  if (!$this->type) {
570  $this->type = self::TYPE_STANDARD;
571  }
572  $this->ref_client = trim($this->ref_client);
573  $this->ref_customer = trim($this->ref_customer);
574  $this->note_public = trim($this->note_public);
575  $this->note_private = trim($this->note_private);
576  $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
577 
578  $this->array_options = $_facrec->array_options;
579 
580  if (!$this->mode_reglement_id) {
581  $this->mode_reglement_id = 0;
582  }
583  $this->brouillon = 1;
584  $this->status = self::STATUS_DRAFT;
585  $this->statut = self::STATUS_DRAFT;
586 
587  $this->linked_objects = $_facrec->linkedObjectsIds;
588  // We do not add link to template invoice or next invoice will be linked to all generated invoices
589  //$this->linked_objects['facturerec'][0] = $this->fac_rec;
590 
591  // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
592  if ($_facrec->frequency > 0) {
593  dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
594  if (empty($_facrec->date_when)) {
595  $_facrec->date_when = $now;
596  }
597  $next_date = $_facrec->getNextDate(); // Calculate next date
598  $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
599  //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
600  $result = $_facrec->setNextDate($next_date, 1);
601  }
602 
603  // Define lang of customer
604  $outputlangs = $langs;
605  $newlang = '';
606 
607  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
608  $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
609  }
610  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
611  $newlang = $this->default_lang; // for thirdparty
612  }
613  if (!empty($newlang)) {
614  $outputlangs = new Translate("", $conf);
615  $outputlangs->setDefaultLang($newlang);
616  }
617 
618  // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
619  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
620  $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
621  $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
622  $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
623  $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
624  $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
625  $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
626  $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
627  $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
628  $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
629  // Only for template invoice
630  $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ? dol_print_date($originaldatewhen, 'dayhour') : '');
631  $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ? dol_print_date($nextdatewhen, 'dayhour') : '');
632  $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '');
633  $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
634  $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
635 
636  //var_dump($substitutionarray);exit;
637 
638  complete_substitutions_array($substitutionarray, $outputlangs);
639 
640  $this->note_public = make_substitutions($this->note_public, $substitutionarray);
641  $this->note_private = make_substitutions($this->note_private, $substitutionarray);
642  }
643 
644  // Define due date if not already defined
645  if (empty($forceduedate)) {
646  $duedate = $this->calculate_date_lim_reglement();
647  /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
648  dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
649  return -1;
650  }*/
651  $this->date_lim_reglement = $duedate;
652  } else {
653  $this->date_lim_reglement = $forceduedate;
654  }
655 
656  // Insert into database
657  $socid = $this->socid;
658 
659  $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
660  $sql .= " ref";
661  $sql .= ", entity";
662  $sql .= ", ref_ext";
663  $sql .= ", type";
664  $sql .= ", fk_soc";
665  $sql .= ", datec";
666  $sql .= ", remise_absolue";
667  $sql .= ", remise_percent";
668  $sql .= ", datef";
669  $sql .= ", date_pointoftax";
670  $sql .= ", note_private";
671  $sql .= ", note_public";
672  $sql .= ", ref_client";
673  $sql .= ", fk_account";
674  $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
675  $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
676  $sql .= ", situation_cycle_ref, situation_counter, situation_final";
677  $sql .= ", fk_incoterms, location_incoterms";
678  $sql .= ", fk_multicurrency";
679  $sql .= ", multicurrency_code";
680  $sql .= ", multicurrency_tx";
681  $sql .= ", retained_warranty";
682  $sql .= ", retained_warranty_date_limit";
683  $sql .= ", retained_warranty_fk_cond_reglement";
684  $sql .= ")";
685  $sql .= " VALUES (";
686  $sql .= "'(PROV)'";
687  $sql .= ", ".setEntity($this);
688  $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
689  $sql .= ", '".$this->db->escape($this->type)."'";
690  $sql .= ", ".((int) $socid);
691  $sql .= ", '".$this->db->idate($this->date_creation)."'";
692  $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL');
693  $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL');
694  $sql .= ", '".$this->db->idate($this->date)."'";
695  $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
696  $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
697  $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
698  $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : ($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"));
699  $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
700  $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
701  $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
702  $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
703  $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
704  $sql .= ", ".($user->id > 0 ? (int) $user->id : "null");
705  $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
706  $sql .= ", ".((int) $this->cond_reglement_id);
707  $sql .= ", ".((int) $this->mode_reglement_id);
708  $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
709  $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
710  $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
711  $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
712  $sql .= ", ".($this->situation_final ? $this->situation_final : 0);
713  $sql .= ", ".(int) $this->fk_incoterms;
714  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
715  $sql .= ", ".(int) $this->fk_multicurrency;
716  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
717  $sql .= ", ".(double) $this->multicurrency_tx;
718  $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty));
719  $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
720  $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
721  $sql .= ")";
722 
723  $resql = $this->db->query($sql);
724  if ($resql) {
725  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
726 
727  // Update ref with new one
728  $this->ref = '(PROV'.$this->id.')';
729  $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
730 
731  $resql = $this->db->query($sql);
732  if (!$resql) {
733  $error++;
734  }
735 
736  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
737  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
738  }
739 
740  // Add object linked
741  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
742  foreach ($this->linked_objects as $origin => $tmp_origin_id) {
743  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, ...))
744  foreach ($tmp_origin_id as $origin_id) {
745  $ret = $this->add_object_linked($origin, $origin_id);
746  if (!$ret) {
747  $this->error = $this->db->lasterror();
748  $error++;
749  }
750  }
751  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
752  {
753  $origin_id = $tmp_origin_id;
754  $ret = $this->add_object_linked($origin, $origin_id);
755  if (!$ret) {
756  $this->error = $this->db->lasterror();
757  $error++;
758  }
759  }
760  }
761  }
762 
763  // Propagate contacts
764  if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
765  $originforcontact = $this->origin;
766  $originidforcontact = $this->origin_id;
767  if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
768  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
769  $exp = new Expedition($this->db);
770  $exp->fetch($this->origin_id);
771  $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
772  if (count($exp->linkedObjectsIds['commande']) > 0) {
773  foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
774  $originforcontact = 'commande';
775  if (is_object($value)) {
776  $originidforcontact = $value->id;
777  } else {
778  $originidforcontact = $value;
779  }
780  break; // We take first one
781  }
782  }
783  }
784 
785  $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";
786  $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
787 
788  $resqlcontact = $this->db->query($sqlcontact);
789  if ($resqlcontact) {
790  while ($objcontact = $this->db->fetch_object($resqlcontact)) {
791  //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
792  $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
793  }
794  } else {
795  dol_print_error($resqlcontact);
796  }
797  }
798 
799  /*
800  * Insert lines of invoices, if not from template invoice, into database
801  */
802  if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
803  $fk_parent_line = 0;
804 
805  dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
806  foreach ($this->lines as $i => $val) {
807  $newinvoiceline = $this->lines[$i];
808 
809  $newinvoiceline->context = $this->context;
810 
811  $newinvoiceline->fk_facture = $this->id;
812 
813  $newinvoiceline->origin = $this->lines[$i]->element;
814  $newinvoiceline->origin_id = $this->lines[$i]->id;
815 
816  // Auto set date of service ?
817  if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
818  $newinvoiceline->date_start = $originaldatewhen;
819  }
820  if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
821  $newinvoiceline->date_end = $previousdaynextdatewhen;
822  }
823 
824  if ($result >= 0) {
825  // Reset fk_parent_line for no child products and special product
826  if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
827  $fk_parent_line = 0;
828  }
829 
830  // Complete vat rate with code
831  $vatrate = $newinvoiceline->tva_tx;
832  if ($newinvoiceline->vat_src_code && ! preg_match('/\‍(.*\‍)/', $vatrate)) $vatrate.=' ('.$newinvoiceline->vat_src_code.')';
833 
834  $newinvoiceline->fk_parent_line = $fk_parent_line;
835 
836  if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
837  $discount = new DiscountAbsolute($this->db);
838  $discount->fetch($newinvoiceline->fk_remise_except);
839 
840  $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
841  $newinvoiceline->fk_remise_except = $discountId;
842  }
843 
844  $result = $this->addline(
845  $newinvoiceline->desc,
846  $newinvoiceline->subprice,
847  $newinvoiceline->qty,
848  $vatrate,
849  $newinvoiceline->localtax1_tx,
850  $newinvoiceline->localtax2_tx,
851  $newinvoiceline->fk_product,
852  $newinvoiceline->remise_percent,
853  $newinvoiceline->date_start,
854  $newinvoiceline->date_end,
855  $newinvoiceline->fk_code_ventilation,
856  $newinvoiceline->info_bits,
857  $newinvoiceline->fk_remise_except,
858  'HT',
859  0,
860  $newinvoiceline->product_type,
861  $newinvoiceline->rang,
862  $newinvoiceline->special_code,
863  $newinvoiceline->element,
864  $newinvoiceline->id,
865  $fk_parent_line,
866  $newinvoiceline->fk_fournprice,
867  $newinvoiceline->pa_ht,
868  $newinvoiceline->label,
869  $newinvoiceline->array_options,
870  $newinvoiceline->situation_percent,
871  $newinvoiceline->fk_prev_id,
872  $newinvoiceline->fk_unit,
873  $newinvoiceline->multicurrency_subprice,
874  $newinvoiceline->ref_ext,
875  1
876  );
877 
878  // Defined the new fk_parent_line
879  if ($result > 0 && $newinvoiceline->product_type == 9) {
880  $fk_parent_line = $result;
881  }
882  }
883  if ($result < 0) {
884  $this->error = $newinvoiceline->error;
885  $this->errors = $newinvoiceline->errors;
886  $error++;
887  break;
888  }
889  }
890  } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
891  $fk_parent_line = 0;
892 
893  dol_syslog("There is ".count($this->lines)." lines that are array lines");
894 
895  foreach ($this->lines as $i => $val) {
896  $line = $this->lines[$i];
897 
898  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
899  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
900  if (!is_object($line)) {
901  $line = (object) $line;
902  }
903 
904  if ($result >= 0) {
905  // Reset fk_parent_line for no child products and special product
906  if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
907  $fk_parent_line = 0;
908  }
909 
910  // Complete vat rate with code
911  $vatrate = $line->tva_tx;
912  if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', $vatrate)) {
913  $vatrate .= ' ('.$line->vat_src_code.')';
914  }
915 
916  if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
917  $originid = $line->origin_id;
918  $origintype = $line->origin;
919  } else {
920  $originid = $line->id;
921  $origintype = $this->element;
922  }
923 
924  // init ref_ext
925  if (empty($line->ref_ext)) {
926  $line->ref_ext = '';
927  }
928 
929  $result = $this->addline(
930  $line->desc,
931  $line->subprice,
932  $line->qty,
933  $vatrate,
934  $line->localtax1_tx,
935  $line->localtax2_tx,
936  $line->fk_product,
937  $line->remise_percent,
938  $line->date_start,
939  $line->date_end,
940  $line->fk_code_ventilation,
941  $line->info_bits,
942  $line->fk_remise_except,
943  'HT',
944  0,
945  $line->product_type,
946  $line->rang,
947  $line->special_code,
948  $origintype,
949  $originid,
950  $fk_parent_line,
951  $line->fk_fournprice,
952  $line->pa_ht,
953  $line->label,
954  $line->array_options,
955  $line->situation_percent,
956  $line->fk_prev_id,
957  $line->fk_unit,
958  $line->multicurrency_subprice,
959  $line->ref_ext,
960  1
961  );
962  if ($result < 0) {
963  $this->error = $this->db->lasterror();
964  dol_print_error($this->db);
965  $this->db->rollback();
966  return -1;
967  }
968 
969  // Defined the new fk_parent_line
970  if ($result > 0 && $line->product_type == 9) {
971  $fk_parent_line = $result;
972  }
973  }
974  }
975  }
976 
977  /*
978  * Insert lines of template invoices
979  */
980  if (!$error && $this->fac_rec > 0) {
981  foreach ($_facrec->lines as $i => $val) {
982  if ($_facrec->lines[$i]->fk_product) {
983  $prod = new Product($this->db);
984  $res = $prod->fetch($_facrec->lines[$i]->fk_product);
985  }
986 
987  // For line from template invoice, we use data from template invoice
988  /*
989  $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
990  $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
991  if (empty($tva_tx)) $tva_npr=0;
992  $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
993  $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
994  */
995  $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
996  $tva_npr = $_facrec->lines[$i]->info_bits;
997  if (empty($tva_tx)) {
998  $tva_npr = 0;
999  }
1000  $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1001  $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1002 
1003  $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1004  $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1005 
1006  // If buyprice not defined from template invoice, we try to guess the best value
1007  if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1008  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1009  $producttmp = new ProductFournisseur($this->db);
1010  $producttmp->fetch($_facrec->lines[$i]->fk_product);
1011 
1012  // If margin module defined on costprice, we try the costprice
1013  // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
1014  // else we get the best supplier price
1015  if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) {
1016  $buyprice = $producttmp->cost_price;
1017  } elseif (isModEnabled('stock') && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) {
1018  $buyprice = $producttmp->pmp;
1019  } else {
1020  if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1021  if ($producttmp->product_fourn_price_id > 0) {
1022  $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
1023  }
1024  }
1025  }
1026  }
1027 
1028  $result_insert = $this->addline(
1029  $_facrec->lines[$i]->desc,
1030  $_facrec->lines[$i]->subprice,
1031  $_facrec->lines[$i]->qty,
1032  $tva_tx,
1033  $localtax1_tx,
1034  $localtax2_tx,
1035  $_facrec->lines[$i]->fk_product,
1036  $_facrec->lines[$i]->remise_percent,
1037  ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
1038  ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
1039  0,
1040  $tva_npr,
1041  '',
1042  'HT',
1043  0,
1044  $_facrec->lines[$i]->product_type,
1045  $_facrec->lines[$i]->rang,
1046  $_facrec->lines[$i]->special_code,
1047  '',
1048  0,
1049  0,
1050  $fk_product_fournisseur_price,
1051  $buyprice,
1052  $_facrec->lines[$i]->label,
1053  empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options,
1054  100, // situation percent is undefined on recurring invoice lines
1055  '',
1056  $_facrec->lines[$i]->fk_unit,
1057  $_facrec->lines[$i]->multicurrency_subprice,
1058  $_facrec->lines[$i]->ref_ext,
1059  1
1060  );
1061 
1062  if ($result_insert < 0) {
1063  $error++;
1064  $this->error = $this->db->error();
1065  break;
1066  }
1067  }
1068  }
1069 
1070  if (!$error) {
1071  $result = $this->update_price(1, 'auto', 0, $mysoc);
1072  if ($result > 0) {
1073  $action = 'create';
1074 
1075  // Actions on extra fields
1076  if (!$error) {
1077  $result = $this->insertExtraFields();
1078  if ($result < 0) {
1079  $error++;
1080  }
1081  }
1082 
1083  if (!$error && !$notrigger) {
1084  // Call trigger
1085  $result = $this->call_trigger('BILL_CREATE', $user);
1086  if ($result < 0) {
1087  $error++;
1088  }
1089  // End call triggers
1090  }
1091 
1092  if (!$error) {
1093  $this->db->commit();
1094  return $this->id;
1095  } else {
1096  $this->db->rollback();
1097  return -4;
1098  }
1099  } else {
1100  $this->error = $langs->trans('FailedToUpdatePrice');
1101  $this->db->rollback();
1102  return -3;
1103  }
1104  } else {
1105  dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
1106  $this->db->rollback();
1107  return -2;
1108  }
1109  } else {
1110  $this->error = $this->db->error();
1111  $this->db->rollback();
1112  return -1;
1113  }
1114  }
1115 
1116 
1124  public function createFromCurrent(User $user, $invertdetail = 0)
1125  {
1126  global $conf;
1127 
1128  // Source invoice load
1129  $facture = new Facture($this->db);
1130 
1131  // Retrieve all extrafield
1132  // fetch optionals attributes and labels
1133  $this->fetch_optionals();
1134 
1135  if (!empty($this->array_options)) {
1136  $facture->array_options = $this->array_options;
1137  }
1138 
1139  foreach ($this->lines as &$line) {
1140  $line->fetch_optionals(); //fetch extrafields
1141  }
1142 
1143  $facture->fk_facture_source = $this->fk_facture_source;
1144  $facture->type = $this->type;
1145  $facture->socid = $this->socid;
1146  $facture->date = $this->date;
1147  $facture->date_pointoftax = $this->date_pointoftax;
1148  $facture->note_public = $this->note_public;
1149  $facture->note_private = $this->note_private;
1150  $facture->ref_client = $this->ref_client;
1151  $facture->modelpdf = $this->model_pdf; // deprecated
1152  $facture->model_pdf = $this->model_pdf;
1153  $facture->fk_project = $this->fk_project;
1154  $facture->cond_reglement_id = $this->cond_reglement_id;
1155  $facture->mode_reglement_id = $this->mode_reglement_id;
1156  $facture->remise_absolue = $this->remise_absolue;
1157  $facture->remise_percent = $this->remise_percent;
1158 
1159  $facture->origin = $this->origin;
1160  $facture->origin_id = $this->origin_id;
1161  $facture->fk_account = $this->fk_account;
1162 
1163  $facture->lines = $this->lines; // Array of lines of invoice
1164  $facture->situation_counter = $this->situation_counter;
1165  $facture->situation_cycle_ref = $this->situation_cycle_ref;
1166  $facture->situation_final = $this->situation_final;
1167 
1168  $facture->retained_warranty = $this->retained_warranty;
1169  $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1170  $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1171 
1172  $facture->fk_user_author = $user->id;
1173 
1174 
1175  // Loop on each line of new invoice
1176  foreach ($facture->lines as $i => $tmpline) {
1177  $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1178  if ($invertdetail) {
1179  $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1180  $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1181  $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1182  $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1183  $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1184  $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1185  $facture->lines[$i]->ref_ext = '';
1186  }
1187  }
1188 
1189  dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1190 
1191  $facid = $facture->create($user);
1192  if ($facid <= 0) {
1193  $this->error = $facture->error;
1194  $this->errors = $facture->errors;
1195  } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1196  $this->fetchObjectLinked('', '', $this->id, 'facture');
1197 
1198  foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1199  foreach ($Tfk_object as $fk_object) {
1200  $facture->add_object_linked($typeObject, $fk_object);
1201  }
1202  }
1203 
1204  $facture->add_object_linked('facture', $this->fk_facture_source);
1205  }
1206 
1207  return $facid;
1208  }
1209 
1210 
1218  public function createFromClone(User $user, $fromid = 0)
1219  {
1220  global $conf, $hookmanager;
1221 
1222  $error = 0;
1223 
1224  $object = new Facture($this->db);
1225 
1226  $this->db->begin();
1227 
1228  $object->fetch($fromid);
1229 
1230  // Load source object
1231  $objFrom = clone $object;
1232 
1233  // Change socid if needed
1234  if (!empty($this->socid) && $this->socid != $object->socid) {
1235  $objsoc = new Societe($this->db);
1236 
1237  if ($objsoc->fetch($this->socid) > 0) {
1238  $object->socid = $objsoc->id;
1239  $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1240  $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1241  $object->fk_project = '';
1242  $object->fk_delivery_address = '';
1243  }
1244 
1245  // TODO Change product price if multi-prices
1246  }
1247 
1248  $object->id = 0;
1249  $object->statut = self::STATUS_DRAFT;
1250  $object->status = self::STATUS_DRAFT;
1251 
1252  // Clear fields
1253  $object->date = (empty($this->date) ? dol_now() : $this->date);
1254  $object->user_author = $user->id; // deprecated
1255  $object->user_valid = null; // deprecated
1256  $object->fk_user_author = $user->id;
1257  $object->fk_user_valid = null;
1258  $object->fk_facture_source = 0;
1259  $object->date_creation = '';
1260  $object->date_modification = '';
1261  $object->date_validation = '';
1262  $object->ref_client = '';
1263  $object->close_code = '';
1264  $object->close_note = '';
1265  if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1266  $object->note_private = '';
1267  $object->note_public = '';
1268  }
1269 
1270  // Loop on each line of new invoice
1271  foreach ($object->lines as $i => $line) {
1272  if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1273  unset($object->lines[$i]);
1274  continue;
1275  }
1276 
1277  // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month)
1278  // If it's a service with start and end dates
1279  if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1280  // Get the dates
1281  $start = dol_getdate($line->date_start);
1282  $end = dol_getdate($line->date_end);
1283 
1284  // Get the first and last day of the month
1285  $first = dol_get_first_day($start['year'], $start['mon']);
1286  $last = dol_get_last_day($end['year'], $end['mon']);
1287 
1288  //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1289  //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1290  // If start date is first date of month and end date is last date of month
1291  if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1292  && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1293  $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1294  $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1295  $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1296  $object->lines[$i]->date_start = $newFirst;
1297  $object->lines[$i]->date_end = $newLast;
1298  }
1299  }
1300 
1301  $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1302  }
1303 
1304  // Create clone
1305  $object->context['createfromclone'] = 'createfromclone';
1306  $result = $object->create($user);
1307  if ($result < 0) {
1308  $error++;
1309  $this->error = $object->error;
1310  $this->errors = $object->errors;
1311  } else {
1312  // copy internal contacts
1313  if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1314  $error++;
1315  $this->error = $object->error;
1316  $this->errors = $object->errors;
1317  } elseif ($object->socid == $objFrom->socid) {
1318  // copy external contacts if same company
1319  if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1320  $error++;
1321  $this->error = $object->error;
1322  $this->errors = $object->errors;
1323  }
1324  }
1325  }
1326 
1327  if (!$error) {
1328  // Hook of thirdparty module
1329  if (is_object($hookmanager)) {
1330  $parameters = array('objFrom'=>$objFrom);
1331  $action = '';
1332  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1333  if ($reshook < 0) {
1334  $this->errors += $hookmanager->errors;
1335  $this->error = $hookmanager->error;
1336  $error++;
1337  }
1338  }
1339  }
1340 
1341  unset($object->context['createfromclone']);
1342 
1343  // End
1344  if (!$error) {
1345  $this->db->commit();
1346  return $object->id;
1347  } else {
1348  $this->db->rollback();
1349  return -1;
1350  }
1351  }
1352 
1360  public function createFromOrder($object, User $user)
1361  {
1362  global $conf, $hookmanager;
1363 
1364  $error = 0;
1365 
1366  // Closed order
1367  $this->date = dol_now();
1368  $this->source = 0;
1369 
1370  $num = count($object->lines);
1371  for ($i = 0; $i < $num; $i++) {
1372  $line = new FactureLigne($this->db);
1373 
1374  $line->libelle = $object->lines[$i]->libelle; // deprecated
1375  $line->label = $object->lines[$i]->label;
1376  $line->desc = $object->lines[$i]->desc;
1377  $line->subprice = $object->lines[$i]->subprice;
1378  $line->total_ht = $object->lines[$i]->total_ht;
1379  $line->total_tva = $object->lines[$i]->total_tva;
1380  $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1381  $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1382  $line->total_ttc = $object->lines[$i]->total_ttc;
1383  $line->vat_src_code = $object->lines[$i]->vat_src_code;
1384  $line->tva_tx = $object->lines[$i]->tva_tx;
1385  $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1386  $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1387  $line->qty = $object->lines[$i]->qty;
1388  $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1389  $line->remise_percent = $object->lines[$i]->remise_percent;
1390  $line->fk_product = $object->lines[$i]->fk_product;
1391  $line->info_bits = $object->lines[$i]->info_bits;
1392  $line->product_type = $object->lines[$i]->product_type;
1393  $line->rang = $object->lines[$i]->rang;
1394  $line->special_code = $object->lines[$i]->special_code;
1395  $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1396  $line->fk_unit = $object->lines[$i]->fk_unit;
1397  $line->date_start = $object->lines[$i]->date_start;
1398  $line->date_end = $object->lines[$i]->date_end;
1399 
1400  // Multicurrency
1401  $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1402  $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1403  $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1404  $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1405  $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1406  $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1407 
1408  $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1409  $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);
1410  $line->pa_ht = $marginInfos[0];
1411 
1412  // get extrafields from original line
1413  $object->lines[$i]->fetch_optionals();
1414  foreach ($object->lines[$i]->array_options as $options_key => $value) {
1415  $line->array_options[$options_key] = $value;
1416  }
1417 
1418  $this->lines[$i] = $line;
1419  }
1420 
1421  $this->socid = $object->socid;
1422  $this->fk_project = $object->fk_project;
1423  $this->fk_account = $object->fk_account;
1424  $this->cond_reglement_id = $object->cond_reglement_id;
1425  $this->mode_reglement_id = $object->mode_reglement_id;
1426  $this->availability_id = $object->availability_id;
1427  $this->demand_reason_id = $object->demand_reason_id;
1428  $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1429  $this->date_livraison = $object->delivery_date; // deprecated
1430  $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1431  $this->contact_id = $object->contact_id;
1432  $this->ref_client = $object->ref_client;
1433 
1434  if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1435  $this->note_private = $object->note_private;
1436  $this->note_public = $object->note_public;
1437  }
1438 
1439  $this->module_source = $object->module_source;
1440  $this->pos_source = $object->pos_source;
1441 
1442  $this->origin = $object->element;
1443  $this->origin_id = $object->id;
1444 
1445  $this->fk_user_author = $user->id;
1446 
1447  // get extrafields from original line
1448  $object->fetch_optionals();
1449  foreach ($object->array_options as $options_key => $value) {
1450  $this->array_options[$options_key] = $value;
1451  }
1452 
1453  // Possibility to add external linked objects with hooks
1454  $this->linked_objects[$this->origin] = $this->origin_id;
1455  if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1456  $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1457  }
1458 
1459  $ret = $this->create($user);
1460 
1461  if ($ret > 0) {
1462  // Actions hooked (by external module)
1463  $hookmanager->initHooks(array('invoicedao'));
1464 
1465  $parameters = array('objFrom'=>$object);
1466  $action = '';
1467  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1468  if ($reshook < 0) {
1469  $this->errors += $hookmanager->errors;
1470  $this->error = $hookmanager->error;
1471  $error++;
1472  }
1473 
1474  if (!$error) {
1475  return 1;
1476  } else {
1477  return -1;
1478  }
1479  } else {
1480  return -1;
1481  }
1482  }
1483 
1496  static public function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1497  {
1498  global $conf, $langs, $hookmanager, $action;
1499 
1500  if (! in_array($origin->element, array('propal', 'commande'))) {
1501  $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1502  return null;
1503  }
1504 
1505  if (empty($date)) {
1506  $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1507  return null;
1508  }
1509 
1510  require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1511 
1512  if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1513  $origin->error = 'ErrorDateIsInFuture';
1514  return null;
1515  }
1516 
1517  if ($payment_terms_id <= 0) {
1518  $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1519  return null;
1520  }
1521 
1522  $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1523 
1524  if (empty($payment_conditions_deposit_percent)) {
1525  $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1526  return null;
1527  }
1528 
1529  if (empty($origin->deposit_percent)) {
1530  $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1531  return null;
1532  }
1533 
1534  $deposit = new self($origin->db);
1535  $deposit->socid = $origin->socid;
1536  $deposit->type = self::TYPE_DEPOSIT;
1537  $deposit->fk_project = $origin->fk_project;
1538  $deposit->ref_client = $origin->ref_client;
1539  $deposit->date = $date;
1540  $deposit->mode_reglement_id = $origin->mode_reglement_id;
1541  $deposit->cond_reglement_id = $payment_terms_id;
1542  $deposit->availability_id = $origin->availability_id;
1543  $deposit->demand_reason_id = $origin->demand_reason_id;
1544  $deposit->fk_account = $origin->fk_account;
1545  $deposit->fk_incoterms = $origin->fk_incoterms;
1546  $deposit->location_incoterms = $origin->location_incoterms;
1547  $deposit->fk_multicurrency = $origin->fk_multicurrency;
1548  $deposit->multicurrency_code = $origin->multicurrency_code;
1549  $deposit->multicurrency_tx = $origin->multicurrency_tx;
1550  $deposit->module_source = $origin->module_source;
1551  $deposit->pos_source = $origin->pos_source;
1552  $deposit->model_pdf = 'crabe';
1553 
1554  $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1555 
1556  if (!empty($conf->global->$modelByTypeConfName)) {
1557  $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1558  } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1559  $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1560  }
1561 
1562  if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1563  $deposit->note_private = $origin->note_private;
1564  $deposit->note_public = $origin->note_public;
1565  }
1566 
1567  $deposit->origin = $origin->element;
1568  $deposit->origin_id = $origin->id;
1569 
1570  $origin->fetch_optionals();
1571 
1572  foreach ($origin->array_options as $extrakey => $value) {
1573  $deposit->array_options[$extrakey] = $value;
1574  }
1575 
1576  $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1577 
1578  foreach ($overrideFields as $key => $value) {
1579  $deposit->$key = $value;
1580  }
1581 
1582  $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1583 
1584  $origin->db->begin();
1585 
1586  // Facture::create() also imports contact from origin
1587  $createReturn = $deposit->create($user, $notrigger);
1588 
1589  if ($createReturn <= 0) {
1590  $origin->db->rollback();
1591  $origin->error = $deposit->error;
1592  $origin->errors = $deposit->errors;
1593  return null;
1594  }
1595 
1596  $amount_ttc_diff = 0;
1597  $amountdeposit = array();
1598  $descriptions = array();
1599 
1600  if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1601  $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1602 
1603  $TTotalByTva = array();
1604  foreach ($origin->lines as &$line) {
1605  if (!empty($line->special_code)) {
1606  continue;
1607  }
1608  $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1609  $descriptions[$line->tva_tx] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1610  $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1611  $descriptions[$line->tva_tx] .= $langs->trans('Qty') . ' : ' . $line->qty;
1612  $descriptions[$line->tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1613  }
1614 
1615  foreach ($TTotalByTva as $tva => &$total) {
1616  $coef = $total / $origin->total_ttc; // Calc coef
1617  $am = $amount * $coef;
1618  $amount_ttc_diff += $am;
1619  $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
1620  }
1621  } else {
1622  $totalamount = 0;
1623  $lines = $origin->lines;
1624  $numlines = count($lines);
1625  for ($i = 0; $i < $numlines; $i++) {
1626  if (empty($lines[$i]->qty)) {
1627  continue; // We discard qty=0, it is an option
1628  }
1629  if (!empty($lines[$i]->special_code)) {
1630  continue; // We discard special_code (frais port, ecotaxe, option, ...)
1631  }
1632 
1633  $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1634  $tva_tx = $lines[$i]->tva_tx;
1635  $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1636  $descriptions[$tva_tx] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1637  $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1638  $descriptions[$tva_tx] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1639  $descriptions[$tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1640  }
1641 
1642  if ($totalamount == 0) {
1643  $amountdeposit[0] = 0;
1644  }
1645 
1646  $amount_ttc_diff = $amountdeposit[0];
1647  }
1648 
1649  foreach ($amountdeposit as $tva => $amount) {
1650  if (empty($amount)) {
1651  continue;
1652  }
1653 
1654  $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1655 
1656  // Hidden conf
1657  if (!empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && !empty($descriptions[$tva])) {
1658  $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1659  }
1660 
1661  $addlineResult = $deposit->addline(
1662  $descline,
1663  $amount, // subprice
1664  1, // quantity
1665  $tva, // vat rate
1666  0, // localtax1_tx
1667  0, // localtax2_tx
1668  (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1669  0, // remise_percent
1670  0, // date_start
1671  0, // date_end
1672  0,
1673  0, // info_bits
1674  0,
1675  'HT',
1676  0,
1677  0, // product_type
1678  1,
1679  0, // special_code
1680  $deposit->origin,
1681  0,
1682  0,
1683  0,
1684  0
1685  //,$langs->trans('Deposit') //Deprecated
1686  );
1687 
1688  if ($addlineResult < 0) {
1689  $origin->db->rollback();
1690  $origin->error = $deposit->error;
1691  $origin->errors = $deposit->errors;
1692  return null;
1693  }
1694  }
1695 
1696  $diff = $deposit->total_ttc - $amount_ttc_diff;
1697 
1698  if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1699  $deposit->fetch_lines();
1700  $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1701 
1702  $updatelineResult = $deposit->updateline(
1703  $deposit->lines[0]->id,
1704  $deposit->lines[0]->desc,
1705  $subprice_diff,
1706  $deposit->lines[0]->qty,
1707  $deposit->lines[0]->remise_percent,
1708  $deposit->lines[0]->date_start,
1709  $deposit->lines[0]->date_end,
1710  $deposit->lines[0]->tva_tx,
1711  0,
1712  0,
1713  'HT',
1714  $deposit->lines[0]->info_bits,
1715  $deposit->lines[0]->product_type,
1716  0,
1717  0,
1718  0,
1719  $deposit->lines[0]->pa_ht,
1720  $deposit->lines[0]->label,
1721  0,
1722  array(),
1723  100
1724  );
1725 
1726  if ($updatelineResult < 0) {
1727  $origin->db->rollback();
1728  $origin->error = $deposit->error;
1729  $origin->errors = $deposit->errors;
1730  return null;
1731  }
1732  }
1733 
1734 
1735  if (! is_object($hookmanager)) {
1736  require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1737  $hookmanager = new HookManager($origin->db);
1738  }
1739 
1740  $hookmanager->initHooks(array('invoicedao'));
1741 
1742  $parameters = array('objFrom' => $origin);
1743  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
1744  // modified by hook
1745  if ($reshook < 0) {
1746  $origin->db->rollback();
1747  $origin->error = $hookmanager->error;
1748  $origin->errors = $hookmanager->errors;
1749  return null;
1750  }
1751 
1752  if (!empty($autoValidateDeposit)) {
1753  $validateReturn = $deposit->validate($user, '', 0, $notrigger);
1754 
1755  if ($validateReturn < 0) {
1756  $origin->db->rollback();
1757  $origin->error = $deposit->error;
1758  $origin->errors = $deposit->errors;
1759  return null;
1760  }
1761  }
1762 
1763  unset($deposit->context['createdepositfromorigin']);
1764 
1765  $origin->db->commit();
1766 
1767  return $deposit;
1768  }
1769 
1784  public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
1785  {
1786  global $langs, $conf, $user, $mysoc;
1787 
1788  if (!empty($conf->dol_no_mouse_hover)) {
1789  $notooltip = 1; // Force disable tooltips
1790  }
1791 
1792  $result = '';
1793 
1794  if ($option == 'withdraw') {
1795  $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1796  } else {
1797  $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
1798  }
1799 
1800  if (!$user->hasRight("facture", "read")) {
1801  $option = 'nolink';
1802  }
1803 
1804  if ($option !== 'nolink') {
1805  // Add param to save lastsearch_values or not
1806  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1807  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1808  $add_save_lastsearch_values = 1;
1809  }
1810  if ($add_save_lastsearch_values) {
1811  $url .= '&save_lastsearch_values=1';
1812  }
1813  }
1814 
1815  if ($short) {
1816  return $url;
1817  }
1818 
1819  $picto = $this->picto;
1820  if ($this->type == self::TYPE_REPLACEMENT) {
1821  $picto .= 'r'; // Replacement invoice
1822  }
1823  if ($this->type == self::TYPE_CREDIT_NOTE) {
1824  $picto .= 'a'; // Credit note
1825  }
1826  if ($this->type == self::TYPE_DEPOSIT) {
1827  $picto .= 'd'; // Deposit invoice
1828  }
1829  $label = '';
1830 
1831  if ($user->hasRight("facture", "read")) {
1832  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
1833  if (isset($this->statut) && isset($this->alreadypaid)) {
1834  $label .= ' '.$this->getLibStatut(5, $this->alreadypaid);
1835  }
1836  $label .= ' &nbsp; '.$this->getLibType(1);
1837  if (!empty($this->ref)) {
1838  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1839  }
1840  if (!empty($this->ref_client)) {
1841  $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
1842  }
1843  if (!empty($this->date)) {
1844  $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1845  }
1846  if (!empty($this->total_ht)) {
1847  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1848  }
1849  if (!empty($this->total_tva)) {
1850  $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1851  }
1852  if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) { // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
1853  $label .= '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1854  }
1855  if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1856  $label .= '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1857  }
1858  if (!empty($this->total_ttc)) {
1859  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1860  }
1861  if ($moretitle) {
1862  $label .= ' - '.$moretitle;
1863  }
1864  }
1865 
1866  $linkclose = ($target ? ' target="'.$target.'"' : '');
1867  if (empty($notooltip) && $user->hasRight("facture", "read")) {
1868  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1869  $label = $langs->trans("Invoice");
1870  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1871  }
1872  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1873  $linkclose .= ' class="classfortooltip"';
1874  }
1875 
1876  $linkstart = '<a href="'.$url.'"';
1877  $linkstart .= $linkclose.'>';
1878  $linkend = '</a>';
1879 
1880  if ($option == 'nolink') {
1881  $linkstart = '';
1882  $linkend = '';
1883  }
1884 
1885  $result .= $linkstart;
1886  if ($withpicto) {
1887  $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1888  }
1889  if ($withpicto != 2) {
1890  $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref);
1891  }
1892  $result .= $linkend;
1893 
1894  if ($addlinktonotes) {
1895  $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1896  if ($txttoshow) {
1897  //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1898  $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
1899  $result .= ' <span class="note inline-block">';
1900  $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
1901  $result .= img_picto('', 'note');
1902  $result .= '</a>';
1903  //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1904  //$result.='</a>';
1905  $result .= '</span>';
1906  }
1907  }
1908 
1909  global $action, $hookmanager;
1910  $hookmanager->initHooks(array('invoicedao'));
1911  $parameters = array('id'=>$this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value'=> $save_lastsearch_value, 'target' => $target);
1912  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1913  if ($reshook > 0) {
1914  $result = $hookmanager->resPrint;
1915  } else {
1916  $result .= $hookmanager->resPrint;
1917  }
1918 
1919  return $result;
1920  }
1921 
1932  public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false)
1933  {
1934  if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1935  return -1;
1936  }
1937 
1938  $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.fk_soc';
1939  $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1940  $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
1941  $sql .= ', f.datef as df, f.date_pointoftax';
1942  $sql .= ', f.date_lim_reglement as dlr';
1943  $sql .= ', f.datec as datec';
1944  $sql .= ', f.date_valid as datev';
1945  $sql .= ', f.tms as datem';
1946  $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';
1947  $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
1948  $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1949  $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1950  $sql .= ', f.fk_account';
1951  $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1952  $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1953  $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1954  $sql .= ', f.fk_incoterms, f.location_incoterms';
1955  $sql .= ', f.module_source, f.pos_source';
1956  $sql .= ", i.libelle as label_incoterms";
1957  $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";
1958  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
1959  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1960  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
1961  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
1962 
1963  if ($rowid) {
1964  $sql .= " WHERE f.rowid = ".((int) $rowid);
1965  } else {
1966  $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
1967  if ($ref) {
1968  $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
1969  }
1970  if ($ref_ext) {
1971  $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
1972  }
1973  }
1974 
1975  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1976  $resql = $this->db->query($sql);
1977  if ($resql) {
1978  if ($this->db->num_rows($resql)) {
1979  $obj = $this->db->fetch_object($resql);
1980 
1981  $this->id = $obj->rowid;
1982  $this->entity = $obj->entity;
1983 
1984  $this->ref = $obj->ref;
1985  $this->ref_client = $obj->ref_client;
1986  $this->ref_customer = $obj->ref_client;
1987  $this->ref_ext = $obj->ref_ext;
1988  $this->type = $obj->type;
1989  $this->date = $this->db->jdate($obj->df);
1990  $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
1991  $this->date_creation = $this->db->jdate($obj->datec);
1992  $this->date_validation = $this->db->jdate($obj->datev);
1993  $this->date_modification = $this->db->jdate($obj->datem);
1994  $this->datem = $this->db->jdate($obj->datem);
1995  $this->remise_percent = $obj->remise_percent;
1996  $this->remise_absolue = $obj->remise_absolue;
1997  $this->total_ht = $obj->total_ht;
1998  $this->total_tva = $obj->total_tva;
1999  $this->total_localtax1 = $obj->localtax1;
2000  $this->total_localtax2 = $obj->localtax2;
2001  $this->total_ttc = $obj->total_ttc;
2002  $this->revenuestamp = $obj->revenuestamp;
2003  $this->paye = $obj->paye;
2004  $this->close_code = $obj->close_code;
2005  $this->close_note = $obj->close_note;
2006 
2007  $this->socid = $obj->fk_soc;
2008  $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2009 
2010  $this->fk_project = $obj->fk_project;
2011  $this->project = null; // Clear if another value was already set by fetch_projet
2012 
2013  $this->statut = $obj->fk_statut;
2014  $this->status = $obj->fk_statut;
2015 
2016  $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2017  $this->mode_reglement_id = $obj->fk_mode_reglement;
2018  $this->mode_reglement_code = $obj->mode_reglement_code;
2019  $this->mode_reglement = $obj->mode_reglement_libelle;
2020  $this->cond_reglement_id = $obj->fk_cond_reglement;
2021  $this->cond_reglement_code = $obj->cond_reglement_code;
2022  $this->cond_reglement = $obj->cond_reglement_libelle;
2023  $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2024  $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2025  $this->fk_facture_source = $obj->fk_facture_source;
2026  $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2027  $this->note = $obj->note_private; // deprecated
2028  $this->note_private = $obj->note_private;
2029  $this->note_public = $obj->note_public;
2030  $this->user_author = $obj->fk_user_author; // deprecated
2031  $this->user_valid = $obj->fk_user_valid; // deprecated
2032  $this->user_modification = $obj->fk_user_modif; // deprecated
2033  $this->fk_user_author = $obj->fk_user_author;
2034  $this->fk_user_valid = $obj->fk_user_valid;
2035  $this->fk_user_modif = $obj->fk_user_modif;
2036  $this->model_pdf = $obj->model_pdf;
2037  $this->modelpdf = $obj->model_pdf; // deprecated
2038  $this->last_main_doc = $obj->last_main_doc;
2039  $this->situation_cycle_ref = $obj->situation_cycle_ref;
2040  $this->situation_counter = $obj->situation_counter;
2041  $this->situation_final = $obj->situation_final;
2042  $this->retained_warranty = $obj->retained_warranty;
2043  $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2044  $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2045 
2046  $this->extraparams = (array) json_decode($obj->extraparams, true);
2047 
2048  //Incoterms
2049  $this->fk_incoterms = $obj->fk_incoterms;
2050  $this->location_incoterms = $obj->location_incoterms;
2051  $this->label_incoterms = $obj->label_incoterms;
2052 
2053  $this->module_source = $obj->module_source;
2054  $this->pos_source = $obj->pos_source;
2055 
2056  // Multicurrency
2057  $this->fk_multicurrency = $obj->fk_multicurrency;
2058  $this->multicurrency_code = $obj->multicurrency_code;
2059  $this->multicurrency_tx = $obj->multicurrency_tx;
2060  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2061  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2062  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2063 
2064  if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2066  }
2067 
2068  if ($this->status == self::STATUS_DRAFT) {
2069  $this->brouillon = 1;
2070  }
2071 
2072  // Retrieve all extrafield
2073  // fetch optionals attributes and labels
2074  $this->fetch_optionals();
2075 
2076  // Lines
2077  $this->lines = array();
2078 
2079  $result = $this->fetch_lines();
2080  if ($result < 0) {
2081  $this->error = $this->db->error();
2082  return -3;
2083  }
2084 
2085  $this->db->free($resql);
2086 
2087  return 1;
2088  } else {
2089  $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2090 
2091  dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2092  return 0;
2093  }
2094  } else {
2095  $this->error = $this->db->lasterror();
2096  return -1;
2097  }
2098  }
2099 
2100 
2101  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2110  public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2111  {
2112  // phpcs:enable
2113  global $langs, $conf;
2114 
2115  $this->lines = array();
2116 
2117  $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,';
2118  $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,';
2119  $sql .= ' l.situation_percent, l.fk_prev_id,';
2120  $sql .= ' l.rang, l.special_code,';
2121  $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2122  $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,';
2123  $sql .= ' l.fk_unit,';
2124  $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2125  $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2126  $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
2127  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2128  $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2129  $sql .= ' ORDER BY l.rang, l.rowid';
2130 
2131  dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2132  $result = $this->db->query($sql);
2133  if ($result) {
2134  $num = $this->db->num_rows($result);
2135  $i = 0;
2136  while ($i < $num) {
2137  $objp = $this->db->fetch_object($result);
2138  $line = new FactureLigne($this->db);
2139 
2140  $line->id = $objp->rowid;
2141  $line->rowid = $objp->rowid; // deprecated
2142  $line->fk_facture = $objp->fk_facture;
2143  $line->label = $objp->custom_label; // deprecated
2144  $line->desc = $objp->description; // Description line
2145  $line->description = $objp->description; // Description line
2146  $line->product_type = $objp->product_type; // Type of line
2147  $line->ref = $objp->product_ref; // Ref product
2148  $line->product_ref = $objp->product_ref; // Ref product
2149  $line->libelle = $objp->product_label; // deprecated
2150  $line->product_label = $objp->product_label; // Label product
2151  $line->product_desc = $objp->product_desc; // Description product
2152  $line->fk_product_type = $objp->fk_product_type; // Type of product
2153  $line->qty = $objp->qty;
2154  $line->subprice = $objp->subprice;
2155  $line->ref_ext = $objp->ref_ext; // line external ref
2156 
2157  $line->vat_src_code = $objp->vat_src_code;
2158  $line->tva_tx = $objp->tva_tx;
2159  $line->localtax1_tx = $objp->localtax1_tx;
2160  $line->localtax2_tx = $objp->localtax2_tx;
2161  $line->localtax1_type = $objp->localtax1_type;
2162  $line->localtax2_type = $objp->localtax2_type;
2163  $line->remise_percent = $objp->remise_percent;
2164  $line->fk_remise_except = $objp->fk_remise_except;
2165  $line->fk_product = $objp->fk_product;
2166  $line->date_start = $this->db->jdate($objp->date_start);
2167  $line->date_end = $this->db->jdate($objp->date_end);
2168  $line->date_start = $this->db->jdate($objp->date_start);
2169  $line->date_end = $this->db->jdate($objp->date_end);
2170  $line->info_bits = $objp->info_bits;
2171  $line->total_ht = $objp->total_ht;
2172  $line->total_tva = $objp->total_tva;
2173  $line->total_localtax1 = $objp->total_localtax1;
2174  $line->total_localtax2 = $objp->total_localtax2;
2175  $line->total_ttc = $objp->total_ttc;
2176  $line->code_ventilation = $objp->fk_code_ventilation;
2177  $line->fk_fournprice = $objp->fk_fournprice;
2178  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2179  $line->pa_ht = $marginInfos[0];
2180  $line->marge_tx = $marginInfos[1];
2181  $line->marque_tx = $marginInfos[2];
2182  $line->rang = $objp->rang;
2183  $line->special_code = $objp->special_code;
2184  $line->fk_parent_line = $objp->fk_parent_line;
2185  $line->situation_percent = $objp->situation_percent;
2186  $line->fk_prev_id = $objp->fk_prev_id;
2187  $line->fk_unit = $objp->fk_unit;
2188 
2189  // Accountancy
2190  $line->fk_accounting_account = $objp->fk_code_ventilation;
2191 
2192  // Multicurrency
2193  $line->fk_multicurrency = $objp->fk_multicurrency;
2194  $line->multicurrency_code = $objp->multicurrency_code;
2195  $line->multicurrency_subprice = $objp->multicurrency_subprice;
2196  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2197  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2198  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2199 
2200  $line->fetch_optionals();
2201 
2202  // multilangs
2203  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2204  $tmpproduct = new Product($this->db);
2205  $tmpproduct->fetch($objp->fk_product);
2206  $tmpproduct->getMultiLangs();
2207 
2208  $line->multilangs = $tmpproduct->multilangs;
2209  }
2210 
2211  $this->lines[$i] = $line;
2212 
2213  $i++;
2214  }
2215  $this->db->free($result);
2216  return 1;
2217  } else {
2218  $this->error = $this->db->error();
2219  return -3;
2220  }
2221  }
2222 
2230  {
2231  global $conf;
2232 
2233  $this->tab_previous_situation_invoice = array();
2234  $this->tab_next_situation_invoice = array();
2235 
2236  $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2237  $sql .= " WHERE rowid <> ".((int) $this->id);
2238  $sql .= ' AND entity = '.((int) $this->entity);
2239  $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2240  $sql .= ' ORDER BY situation_counter ASC';
2241 
2242  dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2243  $result = $this->db->query($sql);
2244  if ($result && $this->db->num_rows($result) > 0) {
2245  while ($objp = $this->db->fetch_object($result)) {
2246  $invoice = new Facture($this->db);
2247  if ($invoice->fetch($objp->rowid) > 0) {
2248  if ($objp->situation_counter < $this->situation_counter
2249  || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2250  ) {
2251  $this->tab_previous_situation_invoice[] = $invoice;
2252  } else {
2253  $this->tab_next_situation_invoice[] = $invoice;
2254  }
2255  }
2256  }
2257  }
2258  }
2259 
2267  public function update(User $user, $notrigger = 0)
2268  {
2269  global $conf;
2270 
2271  $error = 0;
2272 
2273  // Clean parameters
2274  if (empty($this->type)) {
2275  $this->type = self::TYPE_STANDARD;
2276  }
2277  if (isset($this->ref)) {
2278  $this->ref = trim($this->ref);
2279  }
2280  if (isset($this->ref_ext)) {
2281  $this->ref_ext = trim($this->ref_ext);
2282  }
2283  if (isset($this->ref_client)) {
2284  $this->ref_client = trim($this->ref_client);
2285  }
2286  if (isset($this->increment)) {
2287  $this->increment = trim($this->increment);
2288  }
2289  if (isset($this->close_code)) {
2290  $this->close_code = trim($this->close_code);
2291  }
2292  if (isset($this->close_note)) {
2293  $this->close_note = trim($this->close_note);
2294  }
2295  if (isset($this->note) || isset($this->note_private)) {
2296  $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2297  }
2298  if (isset($this->note) || isset($this->note_private)) {
2299  $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2300  }
2301  if (isset($this->note_public)) {
2302  $this->note_public = trim($this->note_public);
2303  }
2304  if (isset($this->model_pdf)) {
2305  $this->model_pdf = trim($this->model_pdf);
2306  }
2307  if (isset($this->import_key)) {
2308  $this->import_key = trim($this->import_key);
2309  }
2310  if (isset($this->retained_warranty)) {
2311  $this->retained_warranty = floatval($this->retained_warranty);
2312  }
2313 
2314 
2315  // Check parameters
2316  // Put here code to add control on parameters values
2317 
2318  // Update request
2319  $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2320  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2321  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2322  $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
2323  $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
2324  $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2325  $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
2326  $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2327  $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2328  $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2329  $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2330  $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
2331  $sql .= " remise_percent=".(isset($this->remise_percent) ? $this->db->escape($this->remise_percent) : "null").",";
2332  $sql .= " remise_absolue=".(isset($this->remise_absolue) ? $this->db->escape($this->remise_absolue) : "null").",";
2333  $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2334  $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2335  $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
2336  $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
2337  $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
2338  $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
2339  $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
2340  $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? $this->db->escape($this->revenuestamp) : "null").",";
2341  $sql .= " fk_statut=".(isset($this->statut) ? $this->db->escape($this->statut) : "null").",";
2342  $sql .= " fk_user_author=".(isset($this->user_author) ? $this->db->escape($this->user_author) : "null").",";
2343  $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->db->escape($this->fk_user_valid) : "null").",";
2344  $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->db->escape($this->fk_facture_source) : "null").",";
2345  $sql .= " fk_projet=".(isset($this->fk_project) ? $this->db->escape($this->fk_project) : "null").",";
2346  $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->db->escape($this->cond_reglement_id) : "null").",";
2347  $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->db->escape($this->mode_reglement_id) : "null").",";
2348  $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2349  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2350  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2351  $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2352  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2353  $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : $this->db->escape($this->situation_cycle_ref)).",";
2354  $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : $this->db->escape($this->situation_counter)).",";
2355  $sql .= " situation_final=".(empty($this->situation_final) ? "0" : $this->db->escape($this->situation_final)).",";
2356  $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty)).",";
2357  $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2358  $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) : "null");
2359  $sql .= " WHERE rowid=".((int) $this->id);
2360 
2361  $this->db->begin();
2362 
2363  dol_syslog(get_class($this)."::update", LOG_DEBUG);
2364  $resql = $this->db->query($sql);
2365  if (!$resql) {
2366  $error++;
2367  $this->errors[] = "Error ".$this->db->lasterror();
2368  }
2369 
2370  if (!$error) {
2371  $result = $this->insertExtraFields();
2372  if ($result < 0) {
2373  $error++;
2374  }
2375  }
2376 
2377  if (!$error && !$notrigger) {
2378  // Call trigger
2379  $result = $this->call_trigger('BILL_MODIFY', $user);
2380  if ($result < 0) {
2381  $error++;
2382  }
2383  // End call triggers
2384  }
2385 
2386  // Commit or rollback
2387  if ($error) {
2388  foreach ($this->errors as $errmsg) {
2389  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2390  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2391  }
2392  $this->db->rollback();
2393  return -1 * $error;
2394  } else {
2395  $this->db->commit();
2396  return 1;
2397  }
2398  }
2399 
2400 
2401  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2408  public function insert_discount($idremise)
2409  {
2410  // phpcs:enable
2411  global $conf, $langs;
2412 
2413  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2414  include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2415 
2416  $this->db->begin();
2417 
2418  $remise = new DiscountAbsolute($this->db);
2419  $result = $remise->fetch($idremise);
2420 
2421  if ($result > 0) {
2422  if ($remise->fk_facture) { // Protection against multiple submission
2423  $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2424  $this->db->rollback();
2425  return -5;
2426  }
2427 
2428  $facligne = new FactureLigne($this->db);
2429  $facligne->fk_facture = $this->id;
2430  $facligne->fk_remise_except = $remise->id;
2431  $facligne->desc = $remise->description; // Description ligne
2432  $facligne->vat_src_code = $remise->vat_src_code;
2433  $facligne->tva_tx = $remise->tva_tx;
2434  $facligne->subprice = -$remise->amount_ht;
2435  $facligne->fk_product = 0; // Id produit predefini
2436  $facligne->qty = 1;
2437  $facligne->remise_percent = 0;
2438  $facligne->rang = -1;
2439  $facligne->info_bits = 2;
2440 
2441  if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2442  $facligne->rang = 1;
2443  $linecount = count($this->lines);
2444  for ($ii = 1; $ii <= $linecount; $ii++) {
2445  $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii+1);
2446  }
2447  }
2448 
2449  // Get buy/cost price of invoice that is source of discount
2450  if ($remise->fk_facture_source > 0) {
2451  $srcinvoice = new Facture($this->db);
2452  $srcinvoice->fetch($remise->fk_facture_source);
2453  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2454  $formmargin = new FormMargin($this->db);
2455  $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2456  $facligne->pa_ht = $arraytmp['pa_total'];
2457  }
2458 
2459  $facligne->total_ht = -$remise->amount_ht;
2460  $facligne->total_tva = -$remise->amount_tva;
2461  $facligne->total_ttc = -$remise->amount_ttc;
2462 
2463  $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2464  $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2465  $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2466  $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2467 
2468  $lineid = $facligne->insert();
2469  if ($lineid > 0) {
2470  $result = $this->update_price(1);
2471  if ($result > 0) {
2472  // Create link between discount and invoice line
2473  $result = $remise->link_to_invoice($lineid, 0);
2474  if ($result < 0) {
2475  $this->error = $remise->error;
2476  $this->db->rollback();
2477  return -4;
2478  }
2479 
2480  $this->db->commit();
2481  return 1;
2482  } else {
2483  $this->error = $facligne->error;
2484  $this->db->rollback();
2485  return -1;
2486  }
2487  } else {
2488  $this->error = $facligne->error;
2489  $this->db->rollback();
2490  return -2;
2491  }
2492  } else {
2493  $this->db->rollback();
2494  return -3;
2495  }
2496  }
2497 
2498  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2506  public function set_ref_client($ref_client, $notrigger = 0)
2507  {
2508  // phpcs:enable
2509  global $user;
2510 
2511  $error = 0;
2512 
2513  $this->db->begin();
2514 
2515  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2516  if (empty($ref_client)) {
2517  $sql .= ' SET ref_client = NULL';
2518  } else {
2519  $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
2520  }
2521  $sql .= " WHERE rowid = ".((int) $this->id);
2522 
2523  dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2524  $resql = $this->db->query($sql);
2525  if (!$resql) {
2526  $this->errors[] = $this->db->error();
2527  $error++;
2528  }
2529 
2530  if (!$error) {
2531  $this->ref_client = $ref_client;
2532  }
2533 
2534  if (!$notrigger && empty($error)) {
2535  // Call trigger
2536  $result = $this->call_trigger('BILL_MODIFY', $user);
2537  if ($result < 0) {
2538  $error++;
2539  }
2540  // End call triggers
2541  }
2542 
2543  if (!$error) {
2544  $this->ref_client = $ref_client;
2545 
2546  $this->db->commit();
2547  return 1;
2548  } else {
2549  foreach ($this->errors as $errmsg) {
2550  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2551  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2552  }
2553  $this->db->rollback();
2554  return -1 * $error;
2555  }
2556  }
2557 
2566  public function delete($user, $notrigger = 0, $idwarehouse = -1)
2567  {
2568  global $langs, $conf;
2569  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2570 
2571  $rowid = $this->id;
2572 
2573  dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
2574 
2575  // Test to avoid invoice deletion (allowed if draft)
2576  $result = $this->is_erasable();
2577 
2578  if ($result <= 0) {
2579  return 0;
2580  }
2581 
2582  $error = 0;
2583 
2584  $this->db->begin();
2585 
2586  if (!$error && !$notrigger) {
2587  // Call trigger
2588  $result = $this->call_trigger('BILL_DELETE', $user);
2589  if ($result < 0) {
2590  $error++;
2591  }
2592  // End call triggers
2593  }
2594 
2595  // Removed extrafields
2596  if (!$error) {
2597  $result = $this->deleteExtraFields();
2598  if ($result < 0) {
2599  $error++;
2600  dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
2601  }
2602  }
2603 
2604  if (!$error) {
2605  // Delete linked object
2606  $res = $this->deleteObjectLinked();
2607  if ($res < 0) {
2608  $error++;
2609  }
2610  }
2611 
2612  if (!$error) {
2613  // If invoice was converted into a discount not yet consumed, we remove discount
2614  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
2615  $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
2616  $sql .= ' AND fk_facture_line IS NULL';
2617  $resql = $this->db->query($sql);
2618 
2619  // If invoice has consumed discounts
2620  $this->fetch_lines();
2621  $list_rowid_det = array();
2622  foreach ($this->lines as $key => $invoiceline) {
2623  $list_rowid_det[] = $invoiceline->id;
2624  }
2625 
2626  // Consumed discounts are freed
2627  if (count($list_rowid_det)) {
2628  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2629  $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
2630  $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(join(',', $list_rowid_det)).')';
2631 
2632  if (!$this->db->query($sql)) {
2633  $this->error = $this->db->error()." sql=".$sql;
2634  $this->errors[] = $this->error;
2635  $this->db->rollback();
2636  return -5;
2637  }
2638  }
2639 
2640  // Remove other links to the deleted invoice
2641 
2642  $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
2643  $sql .= ' SET fk_invoice = NULL';
2644  $sql .= ' WHERE fk_invoice = '.((int) $rowid);
2645 
2646  if (!$this->db->query($sql)) {
2647  $this->error = $this->db->error()." sql=".$sql;
2648  $this->errors[] = $this->error;
2649  $this->db->rollback();
2650  return -5;
2651  }
2652 
2653  $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time';
2654  $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
2655  $sql .= ' WHERE invoice_id = '.((int) $rowid);
2656 
2657  if (!$this->db->query($sql)) {
2658  $this->error = $this->db->error()." sql=".$sql;
2659  $this->errors[] = $this->error;
2660  $this->db->rollback();
2661  return -5;
2662  }
2663 
2664  // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
2665  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2666  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2667  $langs->load("agenda");
2668 
2669  $num = count($this->lines);
2670  for ($i = 0; $i < $num; $i++) {
2671  if ($this->lines[$i]->fk_product > 0) {
2672  $mouvP = new MouvementStock($this->db);
2673  $mouvP->origin = &$this;
2674  $mouvP->setOrigin($this->element, $this->id);
2675  // We decrease stock for product
2676  if ($this->type == self::TYPE_CREDIT_NOTE) {
2677  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
2678  } else {
2679  $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
2680  }
2681  }
2682  }
2683  }
2684 
2685  // Invoice line extrafileds
2686  $main = MAIN_DB_PREFIX.'facturedet';
2687  $ef = $main."_extrafields";
2688  $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
2689  // Delete invoice line
2690  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
2691 
2692  if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact()) {
2693  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
2694 
2695  $resql = $this->db->query($sql);
2696  if ($resql) {
2697  // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2698  $this->deleteEcmFiles();
2699 
2700  // On efface le repertoire de pdf provisoire
2701  $ref = dol_sanitizeFileName($this->ref);
2702  if ($conf->facture->dir_output && !empty($this->ref)) {
2703  $dir = $conf->facture->dir_output."/".$ref;
2704  $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
2705  if (file_exists($file)) { // We must delete all files before deleting directory
2706  $ret = dol_delete_preview($this);
2707 
2708  if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2709  $langs->load("errors");
2710  $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
2711  $this->errors[] = $this->error;
2712  $this->db->rollback();
2713  return 0;
2714  }
2715  }
2716  if (file_exists($dir)) {
2717  if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
2718  $langs->load("errors");
2719  $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
2720  $this->errors[] = $this->error;
2721  $this->db->rollback();
2722  return 0;
2723  }
2724  }
2725  }
2726 
2727  $this->db->commit();
2728  return 1;
2729  } else {
2730  $this->error = $this->db->lasterror()." sql=".$sql;
2731  $this->errors[] = $this->error;
2732  $this->db->rollback();
2733  return -6;
2734  }
2735  } else {
2736  $this->error = $this->db->lasterror()." sql=".$sql;
2737  $this->errors[] = $this->error;
2738  $this->db->rollback();
2739  return -4;
2740  }
2741  } else {
2742  $this->db->rollback();
2743  return -2;
2744  }
2745  }
2746 
2747  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2759  public function set_paid($user, $close_code = '', $close_note = '')
2760  {
2761  // phpcs:enable
2762  dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2763  return $this->setPaid($user, $close_code, $close_note);
2764  }
2765 
2775  public function setPaid($user, $close_code = '', $close_note = '')
2776  {
2777  $error = 0;
2778 
2779  if ($this->paye != 1) {
2780  $this->db->begin();
2781 
2782  $now = dol_now();
2783 
2784  dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
2785 
2786  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2787  $sql .= ' fk_statut='.self::STATUS_CLOSED;
2788  if (!$close_code) {
2789  $sql .= ', paye=1';
2790  }
2791  if ($close_code) {
2792  $sql .= ", close_code='".$this->db->escape($close_code)."'";
2793  }
2794  if ($close_note) {
2795  $sql .= ", close_note='".$this->db->escape($close_note)."'";
2796  }
2797  $sql .= ', fk_user_closing = '.((int) $user->id);
2798  $sql .= ", date_closing = '".$this->db->idate($now)."'";
2799  $sql .= " WHERE rowid = ".((int) $this->id);
2800 
2801  $resql = $this->db->query($sql);
2802  if ($resql) {
2803  // Call trigger
2804  $result = $this->call_trigger('BILL_PAYED', $user);
2805  if ($result < 0) {
2806  $error++;
2807  }
2808  // End call triggers
2809  } else {
2810  $error++;
2811  $this->error = $this->db->lasterror();
2812  }
2813 
2814  if (!$error) {
2815  $this->db->commit();
2816  return 1;
2817  } else {
2818  $this->db->rollback();
2819  return -1;
2820  }
2821  } else {
2822  return 0;
2823  }
2824  }
2825 
2826 
2827  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2838  public function set_unpaid($user)
2839  {
2840  // phpcs:enable
2841  dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2842  return $this->setUnpaid($user);
2843  }
2844 
2853  public function setUnpaid($user)
2854  {
2855  $error = 0;
2856 
2857  $this->db->begin();
2858 
2859  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2860  $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
2861  $sql .= ' date_closing=null,';
2862  $sql .= ' fk_user_closing=null';
2863  $sql .= " WHERE rowid = ".((int) $this->id);
2864 
2865  dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
2866  $resql = $this->db->query($sql);
2867  if ($resql) {
2868  // Call trigger
2869  $result = $this->call_trigger('BILL_UNPAYED', $user);
2870  if ($result < 0) {
2871  $error++;
2872  }
2873  // End call triggers
2874  } else {
2875  $error++;
2876  $this->error = $this->db->error();
2877  dol_print_error($this->db);
2878  }
2879 
2880  if (!$error) {
2881  $this->db->commit();
2882  return 1;
2883  } else {
2884  $this->db->rollback();
2885  return -1;
2886  }
2887  }
2888 
2889 
2890  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2903  public function set_canceled($user, $close_code = '', $close_note = '')
2904  {
2905  // phpcs:enable
2906  dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2907  return $this->setCanceled($user, $close_code, $close_note);
2908  }
2909 
2920  public function setCanceled($user, $close_code = '', $close_note = '')
2921  {
2922  dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
2923 
2924  $this->db->begin();
2925 
2926  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2927  $sql .= ' fk_statut='.self::STATUS_ABANDONED;
2928  if ($close_code) {
2929  $sql .= ", close_code='".$this->db->escape($close_code)."'";
2930  }
2931  if ($close_note) {
2932  $sql .= ", close_note='".$this->db->escape($close_note)."'";
2933  }
2934  $sql .= " WHERE rowid = ".((int) $this->id);
2935 
2936  $resql = $this->db->query($sql);
2937  if ($resql) {
2938  // Bound discounts are deducted from the invoice
2939  // as they have not been used since the invoice is abandoned.
2940  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2941  $sql .= ' SET fk_facture = NULL';
2942  $sql .= ' WHERE fk_facture = '.((int) $this->id);
2943 
2944  $resql = $this->db->query($sql);
2945  if ($resql) {
2946  // Call trigger
2947  $result = $this->call_trigger('BILL_CANCEL', $user);
2948  if ($result < 0) {
2949  $this->db->rollback();
2950  return -1;
2951  }
2952  // End call triggers
2953 
2954  $this->db->commit();
2955  return 1;
2956  } else {
2957  $this->error = $this->db->error()." sql=".$sql;
2958  $this->db->rollback();
2959  return -1;
2960  }
2961  } else {
2962  $this->error = $this->db->error()." sql=".$sql;
2963  $this->db->rollback();
2964  return -2;
2965  }
2966  }
2967 
2979  public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
2980  {
2981  global $conf, $langs, $mysoc;
2982  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2983 
2984  $productStatic = null;
2985  $warehouseStatic = null;
2986  if ($batch_rule > 0) {
2987  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2988  require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
2989  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2990  $productStatic = new Product($this->db);
2991  $warehouseStatic = new Entrepot($this->db);
2992  $productbatch = new ProductBatch($this->db);
2993  }
2994 
2995  $now = dol_now();
2996 
2997  $error = 0;
2998  dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
2999 
3000  // Force to have object complete for checks
3001  $this->fetch_thirdparty();
3002  $this->fetch_lines();
3003 
3004  // Check parameters
3005  if ($this->statut != self::STATUS_DRAFT) {
3006  dol_syslog(get_class($this)."::validate status is not draft. operation canceled.", LOG_WARNING);
3007  return 0;
3008  }
3009  if (count($this->lines) <= 0) {
3010  $langs->load("errors");
3011  $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3012  return -1;
3013  }
3014  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3015  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3016  $this->error = 'Permission denied';
3017  dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3018  return -1;
3019  }
3020  if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3021  $last_of_type = $this->willBeLastOfSameType(true);
3022  if (!$last_of_type[0]) {
3023  $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3024  return -1;
3025  }
3026  }
3027 
3028  // Check for mandatory fields in thirdparty (defined into setup)
3029  if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3030  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_CUSTOMER');
3031  foreach ($array_to_check as $key) {
3032  $keymin = strtolower($key);
3033  if (!property_exists($this->thirdparty, $keymin)) {
3034  continue;
3035  }
3036  $vallabel = $this->thirdparty->$keymin;
3037 
3038  $i = (int) preg_replace('/[^0-9]/', '', $key);
3039  if ($i > 0) {
3040  if ($this->thirdparty->isACompany()) {
3041  // Check for mandatory prof id (but only if country is other than ours)
3042  if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3043  $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3044  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3045  $langs->load("errors");
3046  $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3047  dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3048  return -1;
3049  }
3050  }
3051  }
3052  } else {
3053  if ($key == 'EMAIL') {
3054  // Check for mandatory
3055  if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3056  $langs->load("errors");
3057  $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3058  dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3059  return -1;
3060  }
3061  }
3062  if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3063  // Check for mandatory
3064  if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3065  $langs->load("errors");
3066  $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3067  dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3068  return -1;
3069  }
3070  }
3071  }
3072  }
3073  }
3074 
3075  // Check for mandatory fields in $this
3076  $array_to_check = array('REF_CLIENT'=>'RefCustomer');
3077  foreach ($array_to_check as $key => $val) {
3078  $keymin = strtolower($key);
3079  $vallabel = $this->$keymin;
3080 
3081  // Check for mandatory
3082  $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3083  if (!$vallabel && !empty($conf->global->$keymandatory)) {
3084  $langs->load("errors");
3085  $error++;
3086  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null, 'errors');
3087  }
3088  }
3089 
3090  $this->db->begin();
3091 
3092  // Check parameters
3093  if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3094  // Check that source invoice is known
3095  if ($this->fk_facture_source <= 0) {
3096  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3097  $this->db->rollback();
3098  return -10;
3099  }
3100 
3101  // Load source invoice that has been replaced
3102  $facreplaced = new Facture($this->db);
3103  $result = $facreplaced->fetch($this->fk_facture_source);
3104  if ($result <= 0) {
3105  $this->error = $langs->trans("ErrorBadInvoice");
3106  $this->db->rollback();
3107  return -11;
3108  }
3109 
3110  // Check that source invoice not already replaced by another one.
3111  $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3112  if ($idreplacement && $idreplacement != $this->id) {
3113  $facreplacement = new Facture($this->db);
3114  $facreplacement->fetch($idreplacement);
3115  $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3116  $this->db->rollback();
3117  return -12;
3118  }
3119 
3120  $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3121  if ($result < 0) {
3122  $this->error = $facreplaced->error;
3123  $this->db->rollback();
3124  return -13;
3125  }
3126  }
3127 
3128  // Define new ref
3129  if ($force_number) {
3130  $num = $force_number;
3131  } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3132  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
3133  $this->date = dol_now();
3134  $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3135  }
3136  $num = $this->getNextNumRef($this->thirdparty);
3137  } else {
3138  $num = $this->ref;
3139  }
3140 
3141  $this->newref = dol_sanitizeFileName($num);
3142 
3143  if ($num) {
3144  $this->update_price(1);
3145 
3146  // Validate
3147  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3148  $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)."'";
3149  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
3150  $sql .= ", datef='".$this->db->idate($this->date)."'";
3151  $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3152  }
3153  $sql .= " WHERE rowid = ".((int) $this->id);
3154 
3155  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3156  $resql = $this->db->query($sql);
3157  if (!$resql) {
3158  dol_print_error($this->db);
3159  $error++;
3160  }
3161 
3162  // We check if the invoice was provisional
3163  if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref))) {
3164  // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
3165  }
3166 
3167  if (!$error) {
3168  // Define third party as a customer
3169  $result = $this->thirdparty->set_as_client();
3170 
3171  // If active we decrement the main product and its components at invoice validation
3172  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3173  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3174  $langs->load("agenda");
3175 
3176  // Loop on each line
3177  $cpt = count($this->lines);
3178  for ($i = 0; $i < $cpt; $i++) {
3179  if ($this->lines[$i]->fk_product > 0) {
3180  $mouvP = new MouvementStock($this->db);
3181  $mouvP->origin = &$this;
3182  $mouvP->setOrigin($this->element, $this->id);
3183  // We decrease stock for product
3184  if ($this->type == self::TYPE_CREDIT_NOTE) {
3185  $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num));
3186  if ($result < 0) {
3187  $error++;
3188  $this->error = $mouvP->error;
3189  }
3190  } else {
3191  $is_batch_line = false;
3192  if ($batch_rule > 0) {
3193  $productStatic->fetch($this->lines[$i]->fk_product);
3194  if ($productStatic->hasbatch()) {
3195  $is_batch_line = true;
3196  $product_qty_remain = $this->lines[$i]->qty;
3197 
3198  $sortfield = null;
3199  $sortorder = null;
3200  // find all batch order by sellby (DLC) and eatby dates (DLUO) first
3202  $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3203  $sortorder = 'ASC,ASC,ASC,ASC';
3204  }
3205 
3206  $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder);
3207  if (!is_array($resBatchList)) {
3208  $error++;
3209  $this->error = $this->db->lasterror();
3210  }
3211 
3212  if (!$error) {
3213  $batchList = $resBatchList;
3214  if (empty($batchList)) {
3215  $error++;
3216  $langs->load('errors');
3217  $warehouseStatic->fetch($idwarehouse);
3218  $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3219  dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3220  }
3221 
3222  foreach ($batchList as $batch) {
3223  if ($batch->qty <= 0) {
3224  continue; // try to decrement only batches have positive quantity first
3225  }
3226 
3227  // enough quantity in this batch
3228  if ($batch->qty >= $product_qty_remain) {
3229  $product_batch_qty = $product_qty_remain;
3230  } else {
3231  // not enough (take all in batch)
3232  $product_batch_qty = $batch->qty;
3233  }
3234  $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3235  if ($result < 0) {
3236  $error++;
3237  $this->error = $mouvP->error;
3238  break;
3239  }
3240 
3241  $product_qty_remain -= $product_batch_qty;
3242  // all product quantity was decremented
3243  if ($product_qty_remain <= 0) {
3244  break;
3245  }
3246  }
3247 
3248  if (!$error && $product_qty_remain > 0) {
3249  if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3250  // take in the first batch
3251  $batch = $batchList[0];
3252  $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3253  if ($result < 0) {
3254  $error++;
3255  $this->error = $mouvP->error;
3256  }
3257  } else {
3258  $error++;
3259  $langs->load('errors');
3260  $warehouseStatic->fetch($idwarehouse);
3261  $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3262  dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3263  }
3264  }
3265  }
3266  }
3267  }
3268 
3269  if (!$is_batch_line) {
3270  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3271  if ($result < 0) {
3272  $error++;
3273  $this->error = $mouvP->error;
3274  }
3275  }
3276  }
3277  }
3278  }
3279  }
3280  }
3281 
3282  /*
3283  * 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%)
3284  * So we can continue to create new invoice situation
3285  */
3286  if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3287  $invoice_situation = new Facture($this->db);
3288  $result = $invoice_situation->fetch($this->fk_facture_source);
3289  if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3290  $invoice_situation->situation_final = 0;
3291  // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3292  $result = $invoice_situation->setFinal($user, 1);
3293  }
3294  if ($result < 0) {
3295  $this->error = $invoice_situation->error;
3296  $this->errors = $invoice_situation->errors;
3297  $error++;
3298  }
3299  }
3300 
3301  // Trigger calls
3302  if (!$error && !$notrigger) {
3303  // Call trigger
3304  $result = $this->call_trigger('BILL_VALIDATE', $user);
3305  if ($result < 0) {
3306  $error++;
3307  }
3308  // End call triggers
3309  }
3310 
3311  if (!$error) {
3312  $this->oldref = $this->ref;
3313 
3314  // Rename directory if dir was a temporary ref
3315  if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
3316  // Now we rename also files into index
3317  $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)."'";
3318  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3319  $resql = $this->db->query($sql);
3320  if (!$resql) {
3321  $error++;
3322  $this->error = $this->db->lasterror();
3323  }
3324 
3325  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
3326  $oldref = dol_sanitizeFileName($this->ref);
3327  $newref = dol_sanitizeFileName($num);
3328  $dirsource = $conf->facture->dir_output.'/'.$oldref;
3329  $dirdest = $conf->facture->dir_output.'/'.$newref;
3330  if (!$error && file_exists($dirsource)) {
3331  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
3332 
3333  if (@rename($dirsource, $dirdest)) {
3334  dol_syslog("Rename ok");
3335  // Rename docs starting with $oldref with $newref
3336  $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
3337  foreach ($listoffiles as $fileentry) {
3338  $dirsource = $fileentry['name'];
3339  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
3340  $dirsource = $fileentry['path'].'/'.$dirsource;
3341  $dirdest = $fileentry['path'].'/'.$dirdest;
3342  @rename($dirsource, $dirdest);
3343  }
3344  }
3345  }
3346  }
3347  }
3348 
3349  if (!$error && !$this->is_last_in_cycle()) {
3350  if (!$this->updatePriceNextInvoice($langs)) {
3351  $error++;
3352  }
3353  }
3354 
3355  // Set new ref and define current status
3356  if (!$error) {
3357  $this->ref = $num;
3358  $this->ref = $num;
3359  $this->statut = self::STATUS_VALIDATED;
3360  $this->status = self::STATUS_VALIDATED;
3361  $this->brouillon = 0;
3362  $this->date_validation = $now;
3363  $i = 0;
3364 
3365  if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3366  $final = true;
3367  $nboflines = count($this->lines);
3368  while (($i < $nboflines) && $final) {
3369  $final = ($this->lines[$i]->situation_percent == 100);
3370  $i++;
3371  }
3372 
3373  if (empty($final)) {
3374  $this->situation_final = 0;
3375  } else {
3376  $this->situation_final = 1;
3377  }
3378 
3379  $this->setFinal($user);
3380  }
3381  }
3382  } else {
3383  $error++;
3384  }
3385 
3386  if (!$error) {
3387  $this->db->commit();
3388  return 1;
3389  } else {
3390  $this->db->rollback();
3391  return -1;
3392  }
3393  }
3394 
3401  public function updatePriceNextInvoice(&$langs)
3402  {
3403  foreach ($this->tab_next_situation_invoice as $next_invoice) {
3404  $is_last = $next_invoice->is_last_in_cycle();
3405 
3406  if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3407  $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3408  return false;
3409  }
3410 
3411  $next_invoice->brouillon = 1;
3412 
3413  foreach ($next_invoice->lines as $line) {
3414  $result = $next_invoice->updateline(
3415  $line->id,
3416  $line->desc,
3417  $line->subprice,
3418  $line->qty,
3419  $line->remise_percent,
3420  $line->date_start,
3421  $line->date_end,
3422  $line->tva_tx,
3423  $line->localtax1_tx,
3424  $line->localtax2_tx,
3425  'HT',
3426  $line->info_bits,
3427  $line->product_type,
3428  $line->fk_parent_line,
3429  0,
3430  $line->fk_fournprice,
3431  $line->pa_ht,
3432  $line->label,
3433  $line->special_code,
3434  $line->array_options,
3435  $line->situation_percent,
3436  $line->fk_unit
3437  );
3438 
3439  if ($result < 0) {
3440  $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3441  return false;
3442  }
3443  }
3444 
3445  break; // Only the next invoice and not each next invoice
3446  }
3447 
3448  return true;
3449  }
3450 
3458  public function setDraft($user, $idwarehouse = -1)
3459  {
3460  // phpcs:enable
3461  global $conf, $langs;
3462 
3463  $error = 0;
3464 
3465  if ($this->statut == self::STATUS_DRAFT) {
3466  dol_syslog(__METHOD__." already draft status", LOG_WARNING);
3467  return 0;
3468  }
3469 
3470  dol_syslog(__METHOD__, LOG_DEBUG);
3471 
3472  $this->db->begin();
3473 
3474  $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3475  $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
3476  $sql .= " WHERE rowid = ".((int) $this->id);
3477 
3478  $result = $this->db->query($sql);
3479  if ($result) {
3480  if (!$error) {
3481  $this->oldcopy = clone $this;
3482  }
3483 
3484  // If we decrease stock on invoice validation, we increase back
3485  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3486  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3487  $langs->load("agenda");
3488 
3489  $num = count($this->lines);
3490  for ($i = 0; $i < $num; $i++) {
3491  if ($this->lines[$i]->fk_product > 0) {
3492  $mouvP = new MouvementStock($this->db);
3493  $mouvP->origin = &$this;
3494  $mouvP->setOrigin($this->element, $this->id);
3495  // We decrease stock for product
3496  if ($this->type == self::TYPE_CREDIT_NOTE) {
3497  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
3498  } else {
3499  $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
3500  }
3501  }
3502  }
3503  }
3504 
3505  if ($error == 0) {
3506  $old_statut = $this->statut;
3507  $this->brouillon = 1;
3508  $this->statut = self::STATUS_DRAFT;
3509  $this->status = self::STATUS_DRAFT;
3510 
3511  // Call trigger
3512  $result = $this->call_trigger('BILL_UNVALIDATE', $user);
3513  if ($result < 0) {
3514  $error++;
3515  $this->statut = $old_statut;
3516  $this->status = $old_statut;
3517  $this->brouillon = 0;
3518  }
3519  // End call triggers
3520  } else {
3521  $this->db->rollback();
3522  return -1;
3523  }
3524 
3525  if ($error == 0) {
3526  $this->db->commit();
3527  return 1;
3528  } else {
3529  $this->db->rollback();
3530  return -1;
3531  }
3532  } else {
3533  $this->error = $this->db->error();
3534  $this->db->rollback();
3535  return -1;
3536  }
3537  }
3538 
3539 
3581  public function addline(
3582  $desc,
3583  $pu_ht,
3584  $qty,
3585  $txtva,
3586  $txlocaltax1 = 0,
3587  $txlocaltax2 = 0,
3588  $fk_product = 0,
3589  $remise_percent = 0,
3590  $date_start = '',
3591  $date_end = '',
3592  $ventil = 0,
3593  $info_bits = 0,
3594  $fk_remise_except = '',
3595  $price_base_type = 'HT',
3596  $pu_ttc = 0,
3597  $type = 0,
3598  $rang = -1,
3599  $special_code = 0,
3600  $origin = '',
3601  $origin_id = 0,
3602  $fk_parent_line = 0,
3603  $fk_fournprice = null,
3604  $pa_ht = 0,
3605  $label = '',
3606  $array_options = 0,
3607  $situation_percent = 100,
3608  $fk_prev_id = 0,
3609  $fk_unit = null,
3610  $pu_ht_devise = 0,
3611  $ref_ext = '',
3612  $noupdateafterinsertline = 0
3613  ) {
3614  // Deprecation warning
3615  if ($label) {
3616  dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3617  //var_dump(debug_backtrace(false));exit;
3618  }
3619 
3620  global $mysoc, $conf, $langs;
3621 
3622  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);
3623 
3624  if ($this->statut == self::STATUS_DRAFT) {
3625  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3626 
3627  // Clean parameters
3628  if (empty($remise_percent)) {
3629  $remise_percent = 0;
3630  }
3631  if (empty($qty)) {
3632  $qty = 0;
3633  }
3634  if (empty($info_bits)) {
3635  $info_bits = 0;
3636  }
3637  if (empty($rang)) {
3638  $rang = 0;
3639  }
3640  if (empty($ventil)) {
3641  $ventil = 0;
3642  }
3643  if (empty($txtva)) {
3644  $txtva = 0;
3645  }
3646  if (empty($txlocaltax1)) {
3647  $txlocaltax1 = 0;
3648  }
3649  if (empty($txlocaltax2)) {
3650  $txlocaltax2 = 0;
3651  }
3652  if (empty($fk_parent_line) || $fk_parent_line < 0) {
3653  $fk_parent_line = 0;
3654  }
3655  if (empty($fk_prev_id)) {
3656  $fk_prev_id = 'null';
3657  }
3658  if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
3659  $situation_percent = 100;
3660  }
3661  if (empty($ref_ext)) {
3662  $ref_ext = '';
3663  }
3664 
3665  $remise_percent = price2num($remise_percent);
3666  $qty = price2num($qty);
3667  $pu_ht = price2num($pu_ht);
3668  $pu_ht_devise = price2num($pu_ht_devise);
3669  $pu_ttc = price2num($pu_ttc);
3670  $pa_ht = price2num($pa_ht);
3671  if (!preg_match('/\‍((.*)\‍)/', $txtva)) {
3672  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3673  }
3674  $txlocaltax1 = price2num($txlocaltax1);
3675  $txlocaltax2 = price2num($txlocaltax2);
3676 
3677  if ($price_base_type == 'HT') {
3678  $pu = $pu_ht;
3679  } else {
3680  $pu = $pu_ttc;
3681  }
3682 
3683  // Check parameters
3684  if ($type < 0) {
3685  return -1;
3686  }
3687 
3688  if ($date_start && $date_end && $date_start > $date_end) {
3689  $langs->load("errors");
3690  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3691  return -1;
3692  }
3693 
3694  $this->db->begin();
3695 
3696  $product_type = $type;
3697  if (!empty($fk_product) && $fk_product > 0) {
3698  $product = new Product($this->db);
3699  $result = $product->fetch($fk_product);
3700  $product_type = $product->type;
3701 
3702  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3703  $langs->load("errors");
3704  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3705  $this->db->rollback();
3706  return -3;
3707  }
3708  }
3709 
3710  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3711 
3712  // Clean vat code
3713  $reg = array();
3714  $vat_src_code = '';
3715  if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3716  $vat_src_code = $reg[1];
3717  $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3718  }
3719 
3720  // Calcul du total TTC et de la TVA pour la ligne a partir de
3721  // qty, pu, remise_percent et txtva
3722  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3723  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3724 
3725  $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);
3726 
3727  $total_ht = $tabprice[0];
3728  $total_tva = $tabprice[1];
3729  $total_ttc = $tabprice[2];
3730  $total_localtax1 = $tabprice[9];
3731  $total_localtax2 = $tabprice[10];
3732  $pu_ht = $tabprice[3];
3733 
3734  // MultiCurrency
3735  $multicurrency_total_ht = $tabprice[16];
3736  $multicurrency_total_tva = $tabprice[17];
3737  $multicurrency_total_ttc = $tabprice[18];
3738  $pu_ht_devise = $tabprice[19];
3739 
3740  // Rank to use
3741  $ranktouse = $rang;
3742  if ($ranktouse == -1) {
3743  $rangmax = $this->line_max($fk_parent_line);
3744  $ranktouse = $rangmax + 1;
3745  }
3746 
3747  // Insert line
3748  $this->line = new FactureLigne($this->db);
3749 
3750  $this->line->context = $this->context;
3751 
3752  $this->line->fk_facture = $this->id;
3753  $this->line->label = $label; // deprecated
3754  $this->line->desc = $desc;
3755  $this->line->ref_ext = $ref_ext;
3756 
3757  $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
3758  $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
3759 
3760  $this->line->vat_src_code = $vat_src_code;
3761  $this->line->tva_tx = $txtva;
3762  $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3763  $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3764  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3765  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3766 
3767  $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
3768  $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
3769  $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
3770  $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
3771  $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
3772 
3773  $this->line->fk_product = $fk_product;
3774  $this->line->product_type = $product_type;
3775  $this->line->remise_percent = $remise_percent;
3776  $this->line->date_start = $date_start;
3777  $this->line->date_end = $date_end;
3778  $this->line->ventil = $ventil;
3779  $this->line->rang = $ranktouse;
3780  $this->line->info_bits = $info_bits;
3781  $this->line->fk_remise_except = $fk_remise_except;
3782 
3783  $this->line->special_code = $special_code;
3784  $this->line->fk_parent_line = $fk_parent_line;
3785  $this->line->origin = $origin;
3786  $this->line->origin_id = $origin_id;
3787  $this->line->situation_percent = $situation_percent;
3788  $this->line->fk_prev_id = $fk_prev_id;
3789  $this->line->fk_unit = $fk_unit;
3790 
3791  // infos marge
3792  $this->line->fk_fournprice = $fk_fournprice;
3793  $this->line->pa_ht = $pa_ht;
3794 
3795  // Multicurrency
3796  $this->line->fk_multicurrency = $this->fk_multicurrency;
3797  $this->line->multicurrency_code = $this->multicurrency_code;
3798  $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
3799 
3800  $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
3801  $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
3802  $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
3803 
3804  if (is_array($array_options) && count($array_options) > 0) {
3805  $this->line->array_options = $array_options;
3806  }
3807 
3808  $result = $this->line->insert();
3809  if ($result > 0) {
3810  // Reorder if child line
3811  if (!empty($fk_parent_line)) {
3812  $this->line_order(true, 'DESC');
3813  } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
3814  $linecount = count($this->lines);
3815  for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3816  $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
3817  }
3818  }
3819 
3820  // Mise a jour informations denormalisees au niveau de la facture meme
3821  if (empty($noupdateafterinsertline)) {
3822  $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.
3823  }
3824 
3825  if ($result > 0) {
3826  $this->db->commit();
3827  return $this->line->id;
3828  } else {
3829  $this->error = $this->db->lasterror();
3830  $this->db->rollback();
3831  return -1;
3832  }
3833  } else {
3834  $this->error = $this->line->error;
3835  $this->errors = $this->line->errors;
3836  $this->db->rollback();
3837  return -2;
3838  }
3839  } else {
3840  $this->errors[]='status of invoice must be Draft to allow use of ->addline()';
3841  dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3842  return -3;
3843  }
3844  }
3845 
3877  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)
3878  {
3879  global $conf, $user;
3880  // Deprecation warning
3881  if ($label) {
3882  dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3883  }
3884 
3885  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3886 
3887  global $mysoc, $langs;
3888 
3889  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);
3890 
3891  if ($this->statut == self::STATUS_DRAFT) {
3892  if (!$this->is_last_in_cycle() && empty($this->error)) {
3893  if (!$this->checkProgressLine($rowid, $situation_percent)) {
3894  if (!$this->error) {
3895  $this->error = $langs->trans('invoiceLineProgressError');
3896  }
3897  return -3;
3898  }
3899  }
3900 
3901  if ($date_start && $date_end && $date_start > $date_end) {
3902  $langs->load("errors");
3903  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3904  return -1;
3905  }
3906 
3907  $this->db->begin();
3908 
3909  // Clean parameters
3910  if (empty($qty)) {
3911  $qty = 0;
3912  }
3913  if (empty($fk_parent_line) || $fk_parent_line < 0) {
3914  $fk_parent_line = 0;
3915  }
3916  if (empty($special_code) || $special_code == 3) {
3917  $special_code = 0;
3918  }
3919  if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
3920  $situation_percent = 100;
3921  }
3922  if (empty($ref_ext)) {
3923  $ref_ext = '';
3924  }
3925 
3926  $remise_percent = price2num($remise_percent);
3927  $qty = price2num($qty);
3928  $pu = price2num($pu);
3929  $pu_ht_devise = price2num($pu_ht_devise);
3930  $pa_ht = price2num($pa_ht);
3931  if (!preg_match('/\‍((.*)\‍)/', $txtva)) {
3932  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3933  }
3934  $txlocaltax1 = price2num($txlocaltax1);
3935  $txlocaltax2 = price2num($txlocaltax2);
3936 
3937  // Check parameters
3938  if ($type < 0) {
3939  return -1;
3940  }
3941 
3942  // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
3943  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3944  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3945 
3946  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3947 
3948  // Clean vat code
3949  $reg = array();
3950  $vat_src_code = '';
3951  if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3952  $vat_src_code = $reg[1];
3953  $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3954  }
3955 
3956  $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);
3957 
3958  $total_ht = $tabprice[0];
3959  $total_tva = $tabprice[1];
3960  $total_ttc = $tabprice[2];
3961  $total_localtax1 = $tabprice[9];
3962  $total_localtax2 = $tabprice[10];
3963  $pu_ht = $tabprice[3];
3964  $pu_tva = $tabprice[4];
3965  $pu_ttc = $tabprice[5];
3966 
3967  // MultiCurrency
3968  $multicurrency_total_ht = $tabprice[16];
3969  $multicurrency_total_tva = $tabprice[17];
3970  $multicurrency_total_ttc = $tabprice[18];
3971  $pu_ht_devise = $tabprice[19];
3972 
3973  // Old properties: $price, $remise (deprecated)
3974  $price = $pu;
3975  $remise = 0;
3976  if ($remise_percent > 0) {
3977  $remise = round(($pu * $remise_percent / 100), 2);
3978  $price = ($pu - $remise);
3979  }
3980  $price = price2num($price);
3981 
3982  //Fetch current line from the database and then clone the object and set it in $oldline property
3983  $line = new FactureLigne($this->db);
3984  $line->fetch($rowid);
3985  $line->fetch_optionals();
3986 
3987  if (!empty($line->fk_product)) {
3988  $product = new Product($this->db);
3989  $result = $product->fetch($line->fk_product);
3990  $product_type = $product->type;
3991 
3992  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3993  $langs->load("errors");
3994  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3995  $this->db->rollback();
3996  return -3;
3997  }
3998  }
3999 
4000  $staticline = clone $line;
4001 
4002  $line->oldline = $staticline;
4003  $this->line = $line;
4004  $this->line->context = $this->context;
4005  $this->line->rang = $rang;
4006 
4007  // Reorder if fk_parent_line change
4008  if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4009  $rangmax = $this->line_max($fk_parent_line);
4010  $this->line->rang = $rangmax + 1;
4011  }
4012 
4013  $this->line->id = $rowid;
4014  $this->line->rowid = $rowid;
4015  $this->line->label = $label;
4016  $this->line->desc = $desc;
4017  $this->line->ref_ext = $ref_ext;
4018  $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
4019 
4020  $this->line->vat_src_code = $vat_src_code;
4021  $this->line->tva_tx = $txtva;
4022  $this->line->localtax1_tx = $txlocaltax1;
4023  $this->line->localtax2_tx = $txlocaltax2;
4024  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
4025  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
4026 
4027  $this->line->remise_percent = $remise_percent;
4028  $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
4029  $this->line->date_start = $date_start;
4030  $this->line->date_end = $date_end;
4031  $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
4032  $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4033  $this->line->total_localtax1 = $total_localtax1;
4034  $this->line->total_localtax2 = $total_localtax2;
4035  $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4036  $this->line->info_bits = $info_bits;
4037  $this->line->special_code = $special_code;
4038  $this->line->product_type = $type;
4039  $this->line->fk_parent_line = $fk_parent_line;
4040  $this->line->skip_update_total = $skip_update_total;
4041  $this->line->situation_percent = $situation_percent;
4042  $this->line->fk_unit = $fk_unit;
4043 
4044  $this->line->fk_fournprice = $fk_fournprice;
4045  $this->line->pa_ht = $pa_ht;
4046 
4047  // Multicurrency
4048  $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
4049  $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
4050  $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4051  $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4052 
4053  if (is_array($array_options) && count($array_options) > 0) {
4054  // We replace values in this->line->array_options only for entries defined into $array_options
4055  foreach ($array_options as $key => $value) {
4056  $this->line->array_options[$key] = $array_options[$key];
4057  }
4058  }
4059 
4060  $result = $this->line->update($user, $notrigger);
4061  if ($result > 0) {
4062  // Reorder if child line
4063  if (!empty($fk_parent_line)) {
4064  $this->line_order(true, 'DESC');
4065  }
4066 
4067  // Mise a jour info denormalisees au niveau facture
4068  $this->update_price(1, 'auto');
4069  $this->db->commit();
4070  return $result;
4071  } else {
4072  $this->error = $this->line->error;
4073  $this->db->rollback();
4074  return -1;
4075  }
4076  } else {
4077  $this->error = "Invoice statut makes operation forbidden";
4078  return -2;
4079  }
4080  }
4081 
4089  public function checkProgressLine($idline, $situation_percent)
4090  {
4091  $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4092  INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4093  WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4094 
4095  $result = $this->db->query($sql);
4096  if (!$result) {
4097  $this->error = $this->db->error();
4098  return false;
4099  }
4100 
4101  $obj = $this->db->fetch_object($result);
4102 
4103  if ($obj === null) {
4104  return true;
4105  } else {
4106  return $situation_percent < $obj->situation_percent;
4107  }
4108  }
4109 
4110  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4119  public function update_percent($line, $percent, $update_price = true)
4120  {
4121  // phpcs:enable
4122  global $mysoc, $user;
4123 
4124  // Progress should never be changed for discount lines
4125  if (($line->info_bits & 2) == 2) {
4126  return;
4127  }
4128 
4129  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4130 
4131  // Cap percentages to 100
4132  if ($percent > 100) {
4133  $percent = 100;
4134  }
4135  $line->situation_percent = $percent;
4136  $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);
4137  $line->total_ht = $tabprice[0];
4138  $line->total_tva = $tabprice[1];
4139  $line->total_ttc = $tabprice[2];
4140  $line->total_localtax1 = $tabprice[9];
4141  $line->total_localtax2 = $tabprice[10];
4142  $line->multicurrency_total_ht = $tabprice[16];
4143  $line->multicurrency_total_tva = $tabprice[17];
4144  $line->multicurrency_total_ttc = $tabprice[18];
4145  $line->update($user);
4146 
4147  // sometimes it is better to not update price for each line, ie when updating situation on all lines
4148  if ($update_price) {
4149  $this->update_price(1);
4150  }
4151  }
4152 
4159  public function deleteline($rowid)
4160  {
4161  global $user;
4162 
4163  dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4164 
4165  if ($this->statut != self::STATUS_DRAFT) {
4166  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4167  return -1;
4168  }
4169 
4170  $this->db->begin();
4171 
4172  // Free discount linked to invoice line
4173  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
4174  $sql .= ' SET fk_facture_line = NULL';
4175  $sql .= ' WHERE fk_facture_line = '.((int) $rowid);
4176 
4177  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
4178  $result = $this->db->query($sql);
4179  if (!$result) {
4180  $this->error = $this->db->error();
4181  $this->db->rollback();
4182  return -1;
4183  }
4184 
4185  $line = new FactureLigne($this->db);
4186 
4187  $line->context = $this->context;
4188 
4189  // For triggers
4190  $result = $line->fetch($rowid);
4191  if (!($result > 0)) {
4192  dol_print_error($this->db, $line->error, $line->errors);
4193  }
4194 
4195  if ($line->delete($user) > 0) {
4196  $result = $this->update_price(1);
4197 
4198  if ($result > 0) {
4199  $this->db->commit();
4200  return 1;
4201  } else {
4202  $this->db->rollback();
4203  $this->error = $this->db->lasterror();
4204  return -1;
4205  }
4206  } else {
4207  $this->db->rollback();
4208  $this->error = $line->error;
4209  return -1;
4210  }
4211  }
4212 
4213  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4224  public function set_remise($user, $remise, $notrigger = 0)
4225  {
4226  // phpcs:enable
4227  dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4228  return $this->setDiscount($user, $remise, $notrigger);
4229  }
4230 
4239  public function setDiscount($user, $remise, $notrigger = 0)
4240  {
4241  // Clean parameters
4242  if (empty($remise)) {
4243  $remise = 0;
4244  }
4245 
4246  if ($user->rights->facture->creer) {
4247  $remise = price2num($remise, 2);
4248 
4249  $error = 0;
4250 
4251  $this->db->begin();
4252 
4253  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4254  $sql .= ' SET remise_percent = '.((float) $remise);
4255  $sql .= " WHERE rowid = ".((int) $this->id);
4256  $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4257 
4258  dol_syslog(__METHOD__, LOG_DEBUG);
4259  $resql = $this->db->query($sql);
4260  if (!$resql) {
4261  $this->errors[] = $this->db->error();
4262  $error++;
4263  }
4264 
4265  if (!$notrigger && empty($error)) {
4266  // Call trigger
4267  $result = $this->call_trigger('BILL_MODIFY', $user);
4268  if ($result < 0) {
4269  $error++;
4270  }
4271  // End call triggers
4272  }
4273 
4274  if (!$error) {
4275  $this->remise_percent = $remise;
4276  $this->update_price(1);
4277 
4278  $this->db->commit();
4279  return 1;
4280  } else {
4281  foreach ($this->errors as $errmsg) {
4282  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4283  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4284  }
4285  $this->db->rollback();
4286  return -1 * $error;
4287  }
4288  }
4289  }
4290 
4291 
4292  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4301  public function set_remise_absolue($user, $remise, $notrigger = 0)
4302  {
4303  // phpcs:enable
4304  if (empty($remise)) {
4305  $remise = 0;
4306  }
4307 
4308  if ($user->rights->facture->creer) {
4309  $error = 0;
4310 
4311  $this->db->begin();
4312 
4313  $remise = price2num($remise);
4314 
4315  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4316  $sql .= ' SET remise_absolue = '.((float) $remise);
4317  $sql .= " WHERE rowid = ".((int) $this->id);
4318  $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4319 
4320  dol_syslog(__METHOD__, LOG_DEBUG);
4321  $resql = $this->db->query($sql);
4322  if (!$resql) {
4323  $this->errors[] = $this->db->error();
4324  $error++;
4325  }
4326 
4327  if (!$error) {
4328  $this->oldcopy = clone $this;
4329  $this->remise_absolue = $remise;
4330  $this->update_price(1);
4331  }
4332 
4333  if (!$notrigger && empty($error)) {
4334  // Call trigger
4335  $result = $this->call_trigger('BILL_MODIFY', $user);
4336  if ($result < 0) {
4337  $error++;
4338  }
4339  // End call triggers
4340  }
4341 
4342  if (!$error) {
4343  $this->db->commit();
4344  return 1;
4345  } else {
4346  foreach ($this->errors as $errmsg) {
4347  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4348  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4349  }
4350  $this->db->rollback();
4351  return -1 * $error;
4352  }
4353  }
4354  }
4355 
4364  public function getNextNumRef($soc, $mode = 'next')
4365  {
4366  global $conf, $langs;
4367 
4368  if ($this->module_source == 'takepos') {
4369  $langs->load('cashdesk');
4370 
4371  $moduleName = 'takepos';
4372  $moduleSourceName = 'Takepos';
4373  $addonConstName = 'TAKEPOS_REF_ADDON';
4374 
4375  // Clean parameters (if not defined or using deprecated value)
4376  if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4377  $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
4378  }
4379 
4380  $addon = $conf->global->TAKEPOS_REF_ADDON;
4381  } else {
4382  $langs->load('bills');
4383 
4384  $moduleName = 'facture';
4385  $moduleSourceName = 'Invoice';
4386  $addonConstName = 'FACTURE_ADDON';
4387 
4388  // Clean parameters (if not defined or using deprecated value)
4389  if (empty($conf->global->FACTURE_ADDON)) {
4390  $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4391  } elseif ($conf->global->FACTURE_ADDON == 'terre') {
4392  $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4393  } elseif ($conf->global->FACTURE_ADDON == 'mercure') {
4394  $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
4395  }
4396 
4397  $addon = $conf->global->FACTURE_ADDON;
4398  }
4399 
4400  if (!empty($addon)) {
4401  dol_syslog("Call getNextNumRef with ".$addonConstName." = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
4402 
4403  $mybool = false;
4404 
4405  $file = $addon.'.php';
4406  $classname = $addon;
4407 
4408 
4409  // Include file with class
4410  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
4411  foreach ($dirmodels as $reldir) {
4412  $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
4413 
4414  // Load file with numbering class (if found)
4415  if (is_file($dir.$file) && is_readable($dir.$file)) {
4416  $mybool |= include_once $dir.$file;
4417  }
4418  }
4419 
4420  // For compatibility
4421  if (!$mybool) {
4422  $file = $addon.'/'.$addon.'.modules.php';
4423  $classname = 'mod_'.$moduleName.'_'.$addon;
4424  $classname = preg_replace('/\-.*$/', '', $classname);
4425  // Include file with class
4426  foreach ($conf->file->dol_document_root as $dirroot) {
4427  $dir = $dirroot.'/core/modules/'.$moduleName.'/';
4428 
4429  // Load file with numbering class (if found)
4430  if (is_file($dir.$file) && is_readable($dir.$file)) {
4431  $mybool |= include_once $dir.$file;
4432  }
4433  }
4434  }
4435 
4436  if (!$mybool) {
4437  dol_print_error('', 'Failed to include file '.$file);
4438  return '';
4439  }
4440 
4441  $obj = new $classname();
4442 
4443  $numref = $obj->getNextValue($soc, $this, $mode);
4444 
4445 
4450  if ($mode != 'last' && !$numref) {
4451  $this->error = $obj->error;
4452  return '';
4453  }
4454 
4455  return $numref;
4456  } else {
4457  $langs->load('errors');
4458  print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4459  return '';
4460  }
4461  }
4462 
4469  public function info($id)
4470  {
4471  $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4472  $sql .= ' date_closing as dateclosing,';
4473  $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
4474  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
4475  $sql .= ' WHERE c.rowid = '.((int) $id);
4476 
4477  $result = $this->db->query($sql);
4478  if ($result) {
4479  if ($this->db->num_rows($result)) {
4480  $obj = $this->db->fetch_object($result);
4481  $this->id = $obj->rowid;
4482  if ($obj->fk_user_author) {
4483  $cuser = new User($this->db);
4484  $cuser->fetch($obj->fk_user_author);
4485  $this->user_creation = $cuser;
4486  }
4487  if ($obj->fk_user_valid) {
4488  $vuser = new User($this->db);
4489  $vuser->fetch($obj->fk_user_valid);
4490  $this->user_validation = $vuser;
4491  }
4492  if ($obj->fk_user_closing) {
4493  $cluser = new User($this->db);
4494  $cluser->fetch($obj->fk_user_closing);
4495  $this->user_closing = $cluser;
4496  }
4497 
4498  $this->date_creation = $this->db->jdate($obj->datec);
4499  $this->date_modification = $this->db->jdate($obj->datem);
4500  $this->date_validation = $this->db->jdate($obj->datev);
4501  $this->date_closing = $this->db->jdate($obj->dateclosing);
4502  }
4503  $this->db->free($result);
4504  } else {
4505  dol_print_error($this->db);
4506  }
4507  }
4508 
4509 
4510  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4524  public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
4525  {
4526  // phpcs:enable
4527  global $conf, $user;
4528 
4529  $ga = array();
4530 
4531  $sql = "SELECT s.rowid, s.nom as name, s.client,";
4532  $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
4533  if (empty($user->rights->societe->client->voir) && !$socid) {
4534  $sql .= ", sc.fk_soc, sc.fk_user";
4535  }
4536  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
4537  if (empty($user->rights->societe->client->voir) && !$socid) {
4538  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
4539  }
4540  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4541  $sql .= " AND f.fk_soc = s.rowid";
4542  if (empty($user->rights->societe->client->voir) && !$socid) { //restriction
4543  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4544  }
4545  if ($socid) {
4546  $sql .= " AND s.rowid = ".((int) $socid);
4547  }
4548  if ($draft) {
4549  $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
4550  }
4551  if (is_object($excluser)) {
4552  $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
4553  }
4554  $sql .= $this->db->order($sortfield, $sortorder);
4555  $sql .= $this->db->plimit($limit, $offset);
4556 
4557  $result = $this->db->query($sql);
4558  if ($result) {
4559  $numc = $this->db->num_rows($result);
4560  if ($numc) {
4561  $i = 0;
4562  while ($i < $numc) {
4563  $obj = $this->db->fetch_object($result);
4564 
4565  if ($shortlist == 1) {
4566  $ga[$obj->fid] = $obj->ref;
4567  } elseif ($shortlist == 2) {
4568  $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
4569  } else {
4570  $ga[$i]['id'] = $obj->fid;
4571  $ga[$i]['ref'] = $obj->ref;
4572  $ga[$i]['name'] = $obj->name;
4573  }
4574  $i++;
4575  }
4576  }
4577  return $ga;
4578  } else {
4579  dol_print_error($this->db);
4580  return -1;
4581  }
4582  }
4583 
4584 
4585  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4594  public function list_replacable_invoices($socid = 0)
4595  {
4596  // phpcs:enable
4597  global $conf;
4598 
4599  $return = array();
4600 
4601  $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4602  $sql .= " ff.rowid as rowidnext";
4603  //$sql .= ", SUM(pf.amount) as alreadypaid";
4604  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4605  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4606  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
4607  $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
4608  $sql .= " AND f.entity IN (".getEntity('invoice').")";
4609  $sql .= " AND f.paye = 0"; // Not paid completely
4610  $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
4611  $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
4612  if ($socid > 0) {
4613  $sql .= " AND f.fk_soc = ".((int) $socid);
4614  }
4615  //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
4616  $sql .= " ORDER BY f.ref";
4617 
4618  dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
4619  $resql = $this->db->query($sql);
4620  if ($resql) {
4621  while ($obj = $this->db->fetch_object($resql)) {
4622  $return[$obj->rowid] = array(
4623  'id' => $obj->rowid,
4624  'ref' => $obj->ref,
4625  'status' => $obj->status,
4626  'paid' => $obj->paid,
4627  'alreadypaid' => 0
4628  );
4629  }
4630  //print_r($return);
4631  return $return;
4632  } else {
4633  $this->error = $this->db->error();
4634  return -1;
4635  }
4636  }
4637 
4638 
4639  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4648  public function list_qualified_avoir_invoices($socid = 0)
4649  {
4650  // phpcs:enable
4651  global $conf;
4652 
4653  $return = array();
4654 
4655 
4656  $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4657  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4658  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4659  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
4660  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4661  $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4662  // $sql.= " WHERE f.fk_statut >= 1";
4663  // $sql.= " AND (f.paye = 1"; // Classee payee completement
4664  // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
4665  $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
4666  $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
4667 
4668  if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4669  // Keep invoices that are not situation invoices or that are the last in serie if it is a situation invoice
4670  $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
4671  $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID becasue of the group by later
4672  $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
4673  $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
4674  $sql .= " AND fs.type = ".self::TYPE_SITUATION;
4675  $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4676  if ($socid > 0) {
4677  $sql .= " AND fs.fk_soc = ".((int) $socid);
4678  }
4679  $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
4680  $sql .= ")";
4681  } else {
4682  $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
4683  }
4684 
4685  if ($socid > 0) {
4686  $sql .= " AND f.fk_soc = ".((int) $socid);
4687  }
4688  $sql .= " ORDER BY f.ref";
4689 
4690  dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
4691  $resql = $this->db->query($sql);
4692  if ($resql) {
4693  while ($obj = $this->db->fetch_object($resql)) {
4694  $qualified = 0;
4695  if ($obj->fk_statut == self::STATUS_VALIDATED) {
4696  $qualified = 1;
4697  }
4698  if ($obj->fk_statut == self::STATUS_CLOSED) {
4699  $qualified = 1;
4700  }
4701  if ($qualified) {
4702  //$ref=$obj->ref;
4703  $paymentornot = ($obj->fk_paiement ? 1 : 0);
4704  $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
4705  }
4706  }
4707 
4708  return $return;
4709  } else {
4710  $this->error = $this->db->error();
4711  return -1;
4712  }
4713  }
4714 
4715 
4716  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4723  public function load_board($user)
4724  {
4725  // phpcs:enable
4726  global $conf, $langs;
4727 
4728  $clause = " WHERE";
4729 
4730  $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4731  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4732  if (empty($user->rights->societe->client->voir) && !$user->socid) {
4733  $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4734  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4735  $clause = " AND";
4736  }
4737  $sql .= $clause." f.paye=0";
4738  $sql .= " AND f.entity IN (".getEntity('invoice').")";
4739  $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
4740  if ($user->socid) {
4741  $sql .= " AND f.fk_soc = ".((int) $user->socid);
4742  }
4743 
4744  $resql = $this->db->query($sql);
4745  if ($resql) {
4746  $langs->load("bills");
4747  $now = dol_now();
4748 
4749  $response = new WorkboardResponse();
4750  $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4751  $response->label = $langs->trans("CustomerBillsUnpaid");
4752  $response->labelShort = $langs->trans("Unpaid");
4753  $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4754  $response->img = img_object('', "bill");
4755 
4756  $generic_facture = new Facture($this->db);
4757 
4758  while ($obj = $this->db->fetch_object($resql)) {
4759  $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4760  $generic_facture->statut = $obj->fk_statut;
4761 
4762  $response->nbtodo++;
4763  $response->total += $obj->total_ht;
4764 
4765  if ($generic_facture->hasDelay()) {
4766  $response->nbtodolate++;
4767  $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4768  }
4769  }
4770 
4771  $this->db->free($resql);
4772  return $response;
4773  } else {
4774  dol_print_error($this->db);
4775  $this->error = $this->db->error();
4776  return -1;
4777  }
4778  }
4779 
4780 
4781  /* gestion des contacts d'une facture */
4782 
4788  public function getIdBillingContact()
4789  {
4790  return $this->getIdContact('external', 'BILLING');
4791  }
4792 
4798  public function getIdShippingContact()
4799  {
4800  return $this->getIdContact('external', 'SHIPPING');
4801  }
4802 
4803 
4812  public function initAsSpecimen($option = '')
4813  {
4814  global $conf, $langs, $user;
4815 
4816  $now = dol_now();
4817  $arraynow = dol_getdate($now);
4818  $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
4819 
4820  // Load array of products prodids
4821  $num_prods = 0;
4822  $prodids = array();
4823  $sql = "SELECT rowid";
4824  $sql .= " FROM ".MAIN_DB_PREFIX."product";
4825  $sql .= " WHERE entity IN (".getEntity('product').")";
4826  $sql .= $this->db->plimit(100);
4827 
4828  $resql = $this->db->query($sql);
4829  if ($resql) {
4830  $num_prods = $this->db->num_rows($resql);
4831  $i = 0;
4832  while ($i < $num_prods) {
4833  $i++;
4834  $row = $this->db->fetch_row($resql);
4835  $prodids[$i] = $row[0];
4836  }
4837  }
4838  //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
4839  if (empty($num_prods)) {
4840  $num_prods = 1;
4841  }
4842 
4843  // Initialize parameters
4844  $this->id = 0;
4845  $this->entity = 1;
4846  $this->ref = 'SPECIMEN';
4847  $this->specimen = 1;
4848  $this->socid = 1;
4849  $this->date = $nownotime;
4850  $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4851  $this->cond_reglement_id = 1;
4852  $this->cond_reglement_code = 'RECEP';
4853  $this->date_lim_reglement = $this->calculate_date_lim_reglement();
4854  $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
4855  $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
4856 
4857  $this->note_public = 'This is a comment (public)';
4858  $this->note_private = 'This is a comment (private)';
4859  $this->note = 'This is a comment (private)';
4860 
4861  $this->fk_user_author = $user->id;
4862 
4863  $this->multicurrency_tx = 1;
4864  $this->multicurrency_code = $conf->currency;
4865 
4866  $this->fk_incoterms = 0;
4867  $this->location_incoterms = '';
4868 
4869  if (empty($option) || $option != 'nolines') {
4870  // Lines
4871  $nbp = 5;
4872  $xnbp = 0;
4873  while ($xnbp < $nbp) {
4874  $line = new FactureLigne($this->db);
4875  $line->desc = $langs->trans("Description")." ".$xnbp;
4876  $line->qty = 1;
4877  $line->subprice = 100;
4878  $line->tva_tx = 19.6;
4879  $line->localtax1_tx = 0;
4880  $line->localtax2_tx = 0;
4881  $line->remise_percent = 0;
4882  if ($xnbp == 1) { // Qty is negative (product line)
4883  $prodid = mt_rand(1, $num_prods);
4884  $line->fk_product = $prodids[$prodid];
4885  $line->qty = -1;
4886  $line->total_ht = -100;
4887  $line->total_ttc = -119.6;
4888  $line->total_tva = -19.6;
4889  $line->multicurrency_total_ht = -200;
4890  $line->multicurrency_total_ttc = -239.2;
4891  $line->multicurrency_total_tva = -39.2;
4892  } elseif ($xnbp == 2) { // UP is negative (free line)
4893  $line->subprice = -100;
4894  $line->total_ht = -100;
4895  $line->total_ttc = -119.6;
4896  $line->total_tva = -19.6;
4897  $line->remise_percent = 0;
4898  $line->multicurrency_total_ht = -200;
4899  $line->multicurrency_total_ttc = -239.2;
4900  $line->multicurrency_total_tva = -39.2;
4901  } elseif ($xnbp == 3) { // Discount is 50% (product line)
4902  $prodid = mt_rand(1, $num_prods);
4903  $line->fk_product = $prodids[$prodid];
4904  $line->total_ht = 50;
4905  $line->total_ttc = 59.8;
4906  $line->total_tva = 9.8;
4907  $line->multicurrency_total_ht = 100;
4908  $line->multicurrency_total_ttc = 119.6;
4909  $line->multicurrency_total_tva = 19.6;
4910  $line->remise_percent = 50;
4911  } else // (product line)
4912  {
4913  $prodid = mt_rand(1, $num_prods);
4914  $line->fk_product = $prodids[$prodid];
4915  $line->total_ht = 100;
4916  $line->total_ttc = 119.6;
4917  $line->total_tva = 19.6;
4918  $line->multicurrency_total_ht = 200;
4919  $line->multicurrency_total_ttc = 239.2;
4920  $line->multicurrency_total_tva = 39.2;
4921  $line->remise_percent = 0;
4922  }
4923 
4924  $this->lines[$xnbp] = $line;
4925 
4926 
4927  $this->total_ht += $line->total_ht;
4928  $this->total_tva += $line->total_tva;
4929  $this->total_ttc += $line->total_ttc;
4930 
4931  $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4932  $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4933  $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4934 
4935  $xnbp++;
4936  }
4937  $this->revenuestamp = 0;
4938 
4939  // Add a line "offered"
4940  $line = new FactureLigne($this->db);
4941  $line->desc = $langs->trans("Description")." (offered line)";
4942  $line->qty = 1;
4943  $line->subprice = 100;
4944  $line->tva_tx = 19.6;
4945  $line->localtax1_tx = 0;
4946  $line->localtax2_tx = 0;
4947  $line->remise_percent = 100;
4948  $line->total_ht = 0;
4949  $line->total_ttc = 0; // 90 * 1.196
4950  $line->total_tva = 0;
4951  $line->multicurrency_total_ht = 0;
4952  $line->multicurrency_total_ttc = 0;
4953  $line->multicurrency_total_tva = 0;
4954  $prodid = mt_rand(1, $num_prods);
4955  $line->fk_product = $prodids[$prodid];
4956 
4957  $this->lines[$xnbp] = $line;
4958  $xnbp++;
4959  }
4960  }
4961 
4962  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4968  public function load_state_board()
4969  {
4970  // phpcs:enable
4971  global $conf, $user;
4972 
4973  $this->nb = array();
4974 
4975  $clause = "WHERE";
4976 
4977  $sql = "SELECT count(f.rowid) as nb";
4978  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4979  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
4980  if (empty($user->rights->societe->client->voir) && !$user->socid) {
4981  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4982  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4983  $clause = "AND";
4984  }
4985  $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
4986 
4987  $resql = $this->db->query($sql);
4988  if ($resql) {
4989  while ($obj = $this->db->fetch_object($resql)) {
4990  $this->nb["invoices"] = $obj->nb;
4991  }
4992  $this->db->free($resql);
4993  return 1;
4994  } else {
4995  dol_print_error($this->db);
4996  $this->error = $this->db->error();
4997  return -1;
4998  }
4999  }
5000 
5006  public function getLinesArray()
5007  {
5008  return $this->fetch_lines();
5009  }
5010 
5022  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5023  {
5024  global $conf, $langs;
5025 
5026  $outputlangs->loadLangs(array("bills", "products"));
5027 
5028  if (!dol_strlen($modele)) {
5029  $modele = 'crabe';
5030  $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5031 
5032  if (!empty($this->model_pdf)) {
5033  $modele = $this->model_pdf;
5034  } elseif (!empty($this->modelpdf)) { // deprecated
5035  $modele = $this->modelpdf;
5036  } elseif (!empty($conf->global->$thisTypeConfName)) {
5037  $modele = $conf->global->$thisTypeConfName;
5038  } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5039  $modele = $conf->global->FACTURE_ADDON_PDF;
5040  }
5041  }
5042 
5043  $modelpath = "core/modules/facture/doc/";
5044 
5045  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5046  }
5047 
5053  public function newCycle()
5054  {
5055  $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f';
5056  $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5057  $resql = $this->db->query($sql);
5058  if ($resql) {
5059  if ($this->db->num_rows($resql) > 0) {
5060  $res = $this->db->fetch_array($resql);
5061  $ref = $res['max(situation_cycle_ref)'];
5062  $ref++;
5063  } else {
5064  $ref = 1;
5065  }
5066  $this->db->free($resql);
5067  return $ref;
5068  } else {
5069  $this->error = $this->db->lasterror();
5070  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5071  return -1;
5072  }
5073  }
5074 
5075  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5081  public function is_first()
5082  {
5083  // phpcs:enable
5084  return ($this->situation_counter == 1);
5085  }
5086 
5087  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5093  public function get_prev_sits()
5094  {
5095  // phpcs:enable
5096  global $conf;
5097 
5098  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5099  $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5100  $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5101  $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5102  $resql = $this->db->query($sql);
5103  $res = array();
5104  if ($resql && $this->db->num_rows($resql) > 0) {
5105  while ($row = $this->db->fetch_object($resql)) {
5106  $id = $row->rowid;
5107  $situation = new Facture($this->db);
5108  $situation->fetch($id);
5109  $res[] = $situation;
5110  }
5111  } else {
5112  $this->error = $this->db->error();
5113  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5114  return -1;
5115  }
5116 
5117  return $res;
5118  }
5119 
5127  public function setFinal(User $user, $notrigger = 0)
5128  {
5129  $error = 0;
5130 
5131  $this->db->begin();
5132 
5133  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5134 
5135  dol_syslog(__METHOD__, LOG_DEBUG);
5136  $resql = $this->db->query($sql);
5137  if (!$resql) {
5138  $this->errors[] = $this->db->error();
5139  $error++;
5140  }
5141 
5142  if (!$notrigger && empty($error)) {
5143  // Call trigger
5144  $result = $this->call_trigger('BILL_MODIFY', $user);
5145  if ($result < 0) {
5146  $error++;
5147  }
5148  // End call triggers
5149  }
5150 
5151  if (!$error) {
5152  $this->db->commit();
5153  return 1;
5154  } else {
5155  foreach ($this->errors as $errmsg) {
5156  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5157  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5158  }
5159  $this->db->rollback();
5160  return -1 * $error;
5161  }
5162  }
5163 
5164  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5170  public function is_last_in_cycle()
5171  {
5172  // phpcs:enable
5173  global $conf;
5174 
5175  if (!empty($this->situation_cycle_ref)) {
5176  // No point in testing anything if we're not inside a cycle
5177  $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5178  $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5179  $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5180  $resql = $this->db->query($sql);
5181 
5182  if ($resql && $this->db->num_rows($resql) > 0) {
5183  $res = $this->db->fetch_array($resql);
5184  $last = $res['max(situation_counter)'];
5185  return ($last == $this->situation_counter);
5186  } else {
5187  $this->error = $this->db->lasterror();
5188  dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5189  return false;
5190  }
5191  } else {
5192  return true;
5193  }
5194  }
5195 
5204  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
5205  {
5206  $tables = array(
5207  'facture'
5208  );
5209 
5210  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
5211  }
5212 
5221  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5222  {
5223  $tables = array(
5224  'facturedet'
5225  );
5226 
5227  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
5228  }
5229 
5235  public function hasDelay()
5236  {
5237  global $conf;
5238 
5239  $now = dol_now();
5240 
5241  // Paid invoices have status STATUS_CLOSED
5242  if ($this->statut != Facture::STATUS_VALIDATED) {
5243  return false;
5244  }
5245 
5246  $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5247  if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5248  $totalpaid = $this->getSommePaiement();
5249  $totalpaid = floatval($totalpaid);
5250  $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
5251  if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5252  if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5253  $hasDelay = 1;
5254  } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5255  $hasDelay = 1;
5256  } else {
5257  $hasDelay = 0;
5258  }
5259  }
5260  }
5261 
5262  return $hasDelay;
5263  }
5264 
5269  public function displayRetainedWarranty()
5270  {
5271  global $conf;
5272 
5273  // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
5274 
5275  // 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
5276 
5277  $displayWarranty = false;
5278  if (!empty($this->retained_warranty)) {
5279  $displayWarranty = true;
5280 
5281  if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
5282  // Check if this situation invoice is 100% for real
5283  $displayWarranty = false;
5284  if (!empty($this->situation_final)) {
5285  $displayWarranty = true;
5286  } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
5287  // $object->situation_final need validation to be done so this test is need for draft
5288  $displayWarranty = true;
5289 
5290  foreach ($this->lines as $i => $line) {
5291  if ($line->product_type < 2 && $line->situation_percent < 100) {
5292  $displayWarranty = false;
5293  break;
5294  }
5295  }
5296  }
5297  }
5298  }
5299 
5300  return $displayWarranty;
5301  }
5302 
5307  public function getRetainedWarrantyAmount($rounding = -1)
5308  {
5309  global $conf;
5310  if (empty($this->retained_warranty)) {
5311  return -1;
5312  }
5313 
5314  $retainedWarrantyAmount = 0;
5315 
5316  // Billed - retained warranty
5317  if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
5318  $displayWarranty = true;
5319  // Check if this situation invoice is 100% for real
5320  if (!empty($this->lines)) {
5321  foreach ($this->lines as $i => $line) {
5322  if ($line->product_type < 2 && $line->situation_percent < 100) {
5323  $displayWarranty = false;
5324  break;
5325  }
5326  }
5327  }
5328 
5329  if ($displayWarranty && !empty($this->situation_final)) {
5331  $TPreviousIncoice = $this->tab_previous_situation_invoice;
5332 
5333  $total2BillWT = 0;
5334  foreach ($TPreviousIncoice as &$fac) {
5335  $total2BillWT += $fac->total_ttc;
5336  }
5337  $total2BillWT += $this->total_ttc;
5338 
5339  $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5340  } else {
5341  return -1;
5342  }
5343  } else {
5344  // Because one day retained warranty could be used on standard invoices
5345  $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5346  }
5347 
5348  if ($rounding < 0) {
5349  $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5350  }
5351 
5352  if ($rounding > 0) {
5353  return round($retainedWarrantyAmount, $rounding);
5354  }
5355 
5356  return $retainedWarrantyAmount;
5357  }
5358 
5365  public function setRetainedWarranty($value)
5366  {
5367  dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
5368 
5369  if ($this->statut >= 0) {
5370  $fieldname = 'retained_warranty';
5371  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5372  $sql .= " SET ".$fieldname." = ".((float) $value);
5373  $sql .= ' WHERE rowid='.((int) $this->id);
5374 
5375  if ($this->db->query($sql)) {
5376  $this->retained_warranty = floatval($value);
5377  return 1;
5378  } else {
5379  dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
5380  $this->error = $this->db->error();
5381  return -1;
5382  }
5383  } else {
5384  dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
5385  $this->error = 'Status of the object is incompatible '.$this->statut;
5386  return -2;
5387  }
5388  }
5389 
5390 
5398  public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false)
5399  {
5400  if (!$timestamp && $dateYmd) {
5401  $timestamp = $this->db->jdate($dateYmd);
5402  }
5403 
5404 
5405  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
5406  if ($this->statut >= 0) {
5407  $fieldname = 'retained_warranty_date_limit';
5408  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5409  $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
5410  $sql .= ' WHERE rowid = '.((int) $this->id);
5411 
5412  if ($this->db->query($sql)) {
5413  $this->retained_warranty_date_limit = $timestamp;
5414  return 1;
5415  } else {
5416  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
5417  $this->error = $this->db->error();
5418  return -1;
5419  }
5420  } else {
5421  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5422  $this->error = 'Status of the object is incompatible '.$this->statut;
5423  return -2;
5424  }
5425  }
5426 
5427 
5438  public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $forcerecipient = '')
5439  {
5440  global $conf, $langs, $user;
5441 
5442  $error = 0;
5443  $this->output = '';
5444  $this->error = '';
5445  $nbMailSend = 0;
5446  $errorsMsg = array();
5447 
5448  $langs->load("bills");
5449 
5450  if (!isModEnabled('facture')) { // Should not happen. If module disabled, cron job should not be visible.
5451  $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5452  return 0;
5453  }
5454  /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
5455  $langs->load("bills");
5456  $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5457  return 0;
5458  }
5459  */
5460 
5461  require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5462  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
5463  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
5464  $formmail = new FormMail($this->db);
5465 
5466  $now = dol_now();
5467  $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
5468 
5469  $tmpinvoice = new Facture($this->db);
5470 
5471  dol_syslog(__METHOD__, LOG_DEBUG);
5472 
5473  // Select all action comm reminder
5474  $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
5475  if (!empty($paymentmode) && $paymentmode != 'all') {
5476  $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
5477  }
5478  $sql .= " WHERE f.paye = 0";
5479  $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
5480  $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
5481  $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch process only one company (no sharing)
5482  if (!empty($paymentmode) && $paymentmode != 'all') {
5483  $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
5484  }
5485  // TODO Add a filter to check there is no payment started yet
5486  $sql .= $this->db->order("date_lim_reglement", "ASC");
5487 
5488  $resql = $this->db->query($sql);
5489 
5490  $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
5491  $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
5492  if (!empty($paymentmode) && $paymentmode != 'all') {
5493  $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
5494  }
5495  $this->output .= '<br>';
5496 
5497  if ($resql) {
5498  while ($obj = $this->db->fetch_object($resql)) {
5499  if (!$error) {
5500  // Load event
5501  $res = $tmpinvoice->fetch($obj->id);
5502  if ($res > 0) {
5503  $tmpinvoice->fetch_thirdparty();
5504 
5505  $outputlangs = new Translate('', $conf);
5506  if ($tmpinvoice->thirdparty->default_lang) {
5507  $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5508  $outputlangs->loadLangs(array("main", "bills"));
5509  } else {
5510  $outputlangs = $langs;
5511  }
5512 
5513  // Select email template
5514  $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
5515  if (is_numeric($arraymessage) && $arraymessage <= 0) {
5516  $langs->load("errors");
5517  $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
5518  return 0;
5519  }
5520 
5521  // PREPARE EMAIL
5522  $errormesg = '';
5523 
5524  // Make substitution in email content
5525  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, '', $tmpinvoice);
5526 
5527  complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
5528 
5529  // Topic
5530  $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5531 
5532  // Content
5533  $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5534 
5535  $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
5536 
5537  // Recipient
5538  $to = array();
5539  if ($forcerecipient) { // If a recipient was forced
5540  $to = array($forcerecipient);
5541  } else {
5542  $res = $tmpinvoice->fetch_thirdparty();
5543  $recipient = $tmpinvoice->thirdparty;
5544  if ($res > 0) {
5545  $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
5546  if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5547  foreach ($tmparraycontact as $data_email) {
5548  if (!empty($data_email['email'])) {
5549  $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
5550  }
5551  }
5552  }
5553  if (empty($to) && !empty($recipient->email)) {
5554  $to[] = $recipient->email;
5555  }
5556  if (empty($to)) {
5557  $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for invoice or customer.";
5558  $error++;
5559  }
5560  } else {
5561  $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5562  $error++;
5563  }
5564  }
5565 
5566  // Sender
5567  $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
5568  if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
5569  $from = $arraymessage->email_from;
5570  }
5571  if (empty($from)) {
5572  $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5573  $error++;
5574  }
5575 
5576  if (!$error && !empty($to)) {
5577  $this->db->begin();
5578 
5579  $to = implode(',', $to);
5580  if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
5581  $to = $to.','.$arraymessage->email_to;
5582  }
5583 
5584  // Errors Recipient
5585  $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5586 
5587  $trackid = 'inv'.$tmpinvoice->id;
5588  $sendcontext = 'standard';
5589 
5590  $email_tocc = '';
5591  if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
5592  $email_tocc = $arraymessage->email_tocc;
5593  }
5594 
5595  $email_tobcc = '';
5596  if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
5597  $email_tobcc = $arraymessage->email_tobcc;
5598  }
5599 
5600  //join file is asked
5601  $joinFile = [];
5602  $joinFileName = [];
5603  $joinFileMime = [];
5604  if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5605  $joinFile[] = DOL_DATA_ROOT.$tmpinvoice->last_main_doc;
5606  $joinFileName[] = basename($tmpinvoice->last_main_doc);
5607  $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.$tmpinvoice->last_main_doc);
5608  }
5609 
5610  // Mail Creation
5611  $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
5612 
5613  // Sending Mail
5614  if ($cMailFile->sendfile()) {
5615  $nbMailSend++;
5616 
5617  // Add a line into event table
5618  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5619 
5620  // Insert record of emails sent
5621  $actioncomm = new ActionComm($this->db);
5622 
5623  $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5624  $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5625  $actioncomm->contact_id = 0;
5626 
5627  $actioncomm->code = 'AC_EMAIL';
5628  $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK';
5629  $actioncomm->note_private = $sendContent;
5630  $actioncomm->fk_project = $tmpinvoice->fk_project;
5631  $actioncomm->datep = dol_now();
5632  $actioncomm->datef = $actioncomm->datep;
5633  $actioncomm->percentage = -1; // Not applicable
5634  $actioncomm->authorid = $user->id; // User saving action
5635  $actioncomm->userownerid = $user->id; // Owner of action
5636  // Fields when action is an email (content should be added into note)
5637  $actioncomm->email_msgid = $cMailFile->msgid;
5638  $actioncomm->email_from = $from;
5639  $actioncomm->email_sender = '';
5640  $actioncomm->email_to = $to;
5641  //$actioncomm->email_tocc = $sendtocc;
5642  //$actioncomm->email_tobcc = $sendtobcc;
5643  //$actioncomm->email_subject = $subject;
5644  $actioncomm->errors_to = $errors_to;
5645 
5646  $actioncomm->elementtype = 'invoice';
5647  $actioncomm->fk_element = $tmpinvoice->id;
5648 
5649  //$actioncomm->extraparams = $extraparams;
5650 
5651  $actioncomm->create($user);
5652  } else {
5653  $errormesg = $cMailFile->error.' : '.$to;
5654  $error++;
5655 
5656  // Add a line into event table
5657  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5658 
5659  // Insert record of emails sent
5660  $actioncomm = new ActionComm($this->db);
5661 
5662  $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5663  $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5664  $actioncomm->contact_id = 0;
5665 
5666  $actioncomm->code = 'AC_EMAIL';
5667  $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
5668  $actioncomm->note_private = $errormesg;
5669  $actioncomm->fk_project = $tmpinvoice->fk_project;
5670  $actioncomm->datep = dol_now();
5671  $actioncomm->datef = $actioncomm->datep;
5672  $actioncomm->percentage = -1; // Not applicable
5673  $actioncomm->authorid = $user->id; // User saving action
5674  $actioncomm->userownerid = $user->id; // Owner of action
5675  // Fields when action is an email (content should be added into note)
5676  $actioncomm->email_msgid = $cMailFile->msgid;
5677  $actioncomm->email_from = $from;
5678  $actioncomm->email_sender = '';
5679  $actioncomm->email_to = $to;
5680  //$actioncomm->email_tocc = $sendtocc;
5681  //$actioncomm->email_tobcc = $sendtobcc;
5682  //$actioncomm->email_subject = $subject;
5683  $actioncomm->errors_to = $errors_to;
5684 
5685  //$actioncomm->extraparams = $extraparams;
5686 
5687  $actioncomm->create($user);
5688  }
5689 
5690  $this->db->commit(); // We always commit
5691  }
5692 
5693  if ($errormesg) {
5694  $errorsMsg[] = $errormesg;
5695  }
5696  } else {
5697  $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
5698  $error++;
5699  }
5700  }
5701  }
5702  } else {
5703  $error++;
5704  }
5705 
5706  if (!$error) {
5707  $this->output .= 'Nb of emails sent : '.$nbMailSend;
5708  return 0;
5709  } else {
5710  $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
5711  return $error;
5712  }
5713  }
5714 
5721  public function willBeLastOfSameType($allow_validated_drafts = false)
5722  {
5723  // get date of last validated invoices of same type
5724  $sql = "SELECT datef";
5725  $sql .= " FROM ".MAIN_DB_PREFIX."facture";
5726  $sql .= " WHERE type = " . (int) $this->type ;
5727  $sql .= " AND date_valid IS NOT NULL";
5728  $sql .= " AND entity IN (".getEntity('invoice').")";
5729  $sql .= " ORDER BY datef DESC LIMIT 1";
5730 
5731  $result = $this->db->query($sql);
5732  if ($result) {
5733  // compare with current validation date
5734  if ($this->db->num_rows($result)) {
5735  $obj = $this->db->fetch_object($result);
5736  $last_date = $this->db->jdate($obj->datef);
5737  $invoice_date = $this->date;
5738 
5739  $is_last_of_same_type = $invoice_date >= $last_date;
5740  if ($allow_validated_drafts) {
5741  $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
5742  }
5743 
5744  return array($is_last_of_same_type, $last_date);
5745  } else {
5746  // element is first of type to be validated
5747  return array(true);
5748  }
5749  } else {
5750  dol_print_error($this->db);
5751  }
5752  }
5753 }
5754 
5760 {
5764  public $element = 'facturedet';
5765 
5769  public $table_element = 'facturedet';
5770 
5771  public $oldline;
5772 
5775  public $fk_facture;
5778 
5780  public $desc;
5781  public $ref_ext; // External reference of the line
5782 
5783  public $localtax1_type; // Local tax 1 type
5784  public $localtax2_type; // Local tax 2 type
5785  public $fk_remise_except; // Link to line into llx_remise_except
5786  public $rang = 0;
5787 
5788  public $fk_fournprice;
5789  public $pa_ht;
5790  public $marge_tx;
5791  public $marque_tx;
5792 
5793  public $remise_percent;
5794 
5795  public $special_code; // Liste d'options non cumulabels:
5796  // 1: frais de port
5797  // 2: ecotaxe
5798  // 3: ??
5799 
5800  public $origin;
5801  public $origin_id;
5802 
5803  public $fk_code_ventilation = 0;
5804 
5805  public $date_start;
5806  public $date_end;
5807 
5808  public $skip_update_total; // Skip update price total for special lines
5809 
5813  public $situation_percent;
5814 
5818  public $fk_prev_id;
5819 
5820  // Multicurrency
5821  public $fk_multicurrency;
5822  public $multicurrency_code;
5823  public $multicurrency_subprice;
5824  public $multicurrency_total_ht;
5825  public $multicurrency_total_tva;
5826  public $multicurrency_total_ttc;
5827 
5834  public function fetch($rowid)
5835  {
5836  $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,';
5837  $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5838  $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,';
5839  $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5840  $sql .= ' fd.fk_code_ventilation,';
5841  $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5842  $sql .= ' fd.situation_percent, fd.fk_prev_id,';
5843  $sql .= ' fd.multicurrency_subprice,';
5844  $sql .= ' fd.multicurrency_total_ht,';
5845  $sql .= ' fd.multicurrency_total_tva,';
5846  $sql .= ' fd.multicurrency_total_ttc,';
5847  $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5848  $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
5849  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
5850  $sql .= ' WHERE fd.rowid = '.((int) $rowid);
5851 
5852  $result = $this->db->query($sql);
5853  if ($result) {
5854  $objp = $this->db->fetch_object($result);
5855 
5856  if (!$objp) {
5857  $this->error = 'InvoiceLine with id '. $rowid .' not found sql='.$sql;
5858  return 0;
5859  }
5860 
5861  $this->rowid = $objp->rowid;
5862  $this->id = $objp->rowid;
5863  $this->fk_facture = $objp->fk_facture;
5864  $this->fk_parent_line = $objp->fk_parent_line;
5865  $this->label = $objp->custom_label;
5866  $this->desc = $objp->description;
5867  $this->qty = $objp->qty;
5868  $this->subprice = $objp->subprice;
5869  $this->ref_ext = $objp->ref_ext;
5870  $this->vat_src_code = $objp->vat_src_code;
5871  $this->tva_tx = $objp->tva_tx;
5872  $this->localtax1_tx = $objp->localtax1_tx;
5873  $this->localtax2_tx = $objp->localtax2_tx;
5874  $this->remise_percent = $objp->remise_percent;
5875  $this->fk_remise_except = $objp->fk_remise_except;
5876  $this->fk_product = $objp->fk_product;
5877  $this->product_type = $objp->product_type;
5878  $this->date_start = $this->db->jdate($objp->date_start);
5879  $this->date_end = $this->db->jdate($objp->date_end);
5880  $this->info_bits = $objp->info_bits;
5881  $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5882  $this->special_code = $objp->special_code;
5883  $this->total_ht = $objp->total_ht;
5884  $this->total_tva = $objp->total_tva;
5885  $this->total_localtax1 = $objp->total_localtax1;
5886  $this->total_localtax2 = $objp->total_localtax2;
5887  $this->total_ttc = $objp->total_ttc;
5888  $this->fk_code_ventilation = $objp->fk_code_ventilation;
5889  $this->rang = $objp->rang;
5890  $this->fk_fournprice = $objp->fk_fournprice;
5891  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5892  $this->pa_ht = $marginInfos[0];
5893  $this->marge_tx = $marginInfos[1];
5894  $this->marque_tx = $marginInfos[2];
5895 
5896  $this->ref = $objp->product_ref; // deprecated
5897 
5898  $this->product_ref = $objp->product_ref;
5899  $this->product_label = $objp->product_label;
5900  $this->product_desc = $objp->product_desc;
5901 
5902  $this->fk_unit = $objp->fk_unit;
5903  $this->fk_user_modif = $objp->fk_user_modif;
5904  $this->fk_user_author = $objp->fk_user_author;
5905 
5906  $this->situation_percent = $objp->situation_percent;
5907  $this->fk_prev_id = $objp->fk_prev_id;
5908 
5909  $this->multicurrency_subprice = $objp->multicurrency_subprice;
5910  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5911  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5912  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5913 
5914  $this->db->free($result);
5915 
5916  return 1;
5917  } else {
5918  $this->error = $this->db->lasterror();
5919  return -1;
5920  }
5921  }
5922 
5930  public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5931  {
5932  global $langs, $user, $conf;
5933 
5934  $error = 0;
5935 
5936  $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'.
5937 
5938  dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
5939 
5940  // Clean parameters
5941  $this->desc = trim($this->desc);
5942  if (empty($this->tva_tx)) {
5943  $this->tva_tx = 0;
5944  }
5945  if (empty($this->localtax1_tx)) {
5946  $this->localtax1_tx = 0;
5947  }
5948  if (empty($this->localtax2_tx)) {
5949  $this->localtax2_tx = 0;
5950  }
5951  if (empty($this->localtax1_type)) {
5952  $this->localtax1_type = 0;
5953  }
5954  if (empty($this->localtax2_type)) {
5955  $this->localtax2_type = 0;
5956  }
5957  if (empty($this->total_localtax1)) {
5958  $this->total_localtax1 = 0;
5959  }
5960  if (empty($this->total_localtax2)) {
5961  $this->total_localtax2 = 0;
5962  }
5963  if (empty($this->rang)) {
5964  $this->rang = 0;
5965  }
5966  if (empty($this->remise_percent)) {
5967  $this->remise_percent = 0;
5968  }
5969  if (empty($this->info_bits)) {
5970  $this->info_bits = 0;
5971  }
5972  if (empty($this->subprice)) {
5973  $this->subprice = 0;
5974  }
5975  if (empty($this->ref_ext)) {
5976  $this->ref_ext = '';
5977  }
5978  if (empty($this->special_code)) {
5979  $this->special_code = 0;
5980  }
5981  if (empty($this->fk_parent_line)) {
5982  $this->fk_parent_line = 0;
5983  }
5984  if (empty($this->fk_prev_id)) {
5985  $this->fk_prev_id = 0;
5986  }
5987  if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
5988  $this->situation_percent = 100;
5989  }
5990 
5991  if (empty($this->pa_ht)) {
5992  $this->pa_ht = 0;
5993  }
5994  if (empty($this->multicurrency_subprice)) {
5995  $this->multicurrency_subprice = 0;
5996  }
5997  if (empty($this->multicurrency_total_ht)) {
5998  $this->multicurrency_total_ht = 0;
5999  }
6000  if (empty($this->multicurrency_total_tva)) {
6001  $this->multicurrency_total_tva = 0;
6002  }
6003  if (empty($this->multicurrency_total_ttc)) {
6004  $this->multicurrency_total_ttc = 0;
6005  }
6006 
6007  // if buy price not defined, define buyprice as configured in margin admin
6008  if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6009  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
6010  return $result;
6011  } else {
6012  $this->pa_ht = $result;
6013  }
6014  }
6015 
6016  // Check parameters
6017  if ($this->product_type < 0) {
6018  $this->error = 'ErrorProductTypeMustBe0orMore';
6019  return -1;
6020  }
6021  if (!empty($this->fk_product) && $this->fk_product > 0) {
6022  // Check product exists
6023  $result = Product::isExistingObject('product', $this->fk_product);
6024  if ($result <= 0) {
6025  $this->error = 'ErrorProductIdDoesNotExists';
6026  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6027  return -1;
6028  }
6029  }
6030 
6031  $this->db->begin();
6032 
6033  // Update line in database
6034  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
6035  $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
6036  $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6037  $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6038  $sql .= ' date_start, date_end, fk_code_ventilation, ';
6039  $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6040  $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6041  $sql .= ' situation_percent, fk_prev_id,';
6042  $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
6043  $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6044  $sql .= ')';
6045  $sql .= " VALUES (".$this->fk_facture.",";
6046  $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
6047  $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
6048  $sql .= " '".$this->db->escape($this->desc)."',";
6049  $sql .= " ".price2num($this->qty).",";
6050  $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
6051  $sql .= " ".price2num($this->tva_tx).",";
6052  $sql .= " ".price2num($this->localtax1_tx).",";
6053  $sql .= " ".price2num($this->localtax2_tx).",";
6054  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
6055  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
6056  $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
6057  $sql .= " ".((int) $this->product_type).",";
6058  $sql .= " ".price2num($this->remise_percent).",";
6059  $sql .= " ".price2num($this->subprice).",";
6060  $sql .= " '".$this->db->escape($this->ref_ext)."',";
6061  $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
6062  $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
6063  $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
6064  $sql .= ' '.((int) $this->fk_code_ventilation).',';
6065  $sql .= ' '.((int) $this->rang).',';
6066  $sql .= ' '.((int) $this->special_code).',';
6067  $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
6068  $sql .= ' '.price2num($this->pa_ht).',';
6069  $sql .= " '".$this->db->escape($this->info_bits)."',";
6070  $sql .= " ".price2num($this->total_ht).",";
6071  $sql .= " ".price2num($this->total_tva).",";
6072  $sql .= " ".price2num($this->total_ttc).",";
6073  $sql .= " ".price2num($this->total_localtax1).",";
6074  $sql .= " ".price2num($this->total_localtax2);
6075  $sql .= ", ".((float) $this->situation_percent);
6076  $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
6077  $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6078  $sql .= ", ".((int) $user->id);
6079  $sql .= ", ".((int) $user->id);
6080  $sql .= ", ".(int) $this->fk_multicurrency;
6081  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
6082  $sql .= ", ".price2num($this->multicurrency_subprice);
6083  $sql .= ", ".price2num($this->multicurrency_total_ht);
6084  $sql .= ", ".price2num($this->multicurrency_total_tva);
6085  $sql .= ", ".price2num($this->multicurrency_total_ttc);
6086  $sql .= ')';
6087 
6088  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
6089  $resql = $this->db->query($sql);
6090  if ($resql) {
6091  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
6092  $this->rowid = $this->id; // For backward compatibility
6093 
6094  if (!$error) {
6095  $result = $this->insertExtraFields();
6096  if ($result < 0) {
6097  $error++;
6098  }
6099  }
6100 
6101  // If fk_remise_except is defined, the discount is linked to the invoice
6102  // which flags it as "consumed".
6103  if ($this->fk_remise_except) {
6104  $discount = new DiscountAbsolute($this->db);
6105  $result = $discount->fetch($this->fk_remise_except);
6106  if ($result >= 0) {
6107  // Check if discount was found
6108  if ($result > 0) {
6109  // Check if discount not already affected to another invoice
6110  if ($discount->fk_facture_line > 0) {
6111  if (empty($noerrorifdiscountalreadylinked)) {
6112  $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
6113  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6114  $this->db->rollback();
6115  return -3;
6116  }
6117  } else {
6118  $result = $discount->link_to_invoice($this->rowid, 0);
6119  if ($result < 0) {
6120  $this->error = $discount->error;
6121  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6122  $this->db->rollback();
6123  return -3;
6124  }
6125  }
6126  } else {
6127  $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
6128  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6129  $this->db->rollback();
6130  return -3;
6131  }
6132  } else {
6133  $this->error = $discount->error;
6134  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6135  $this->db->rollback();
6136  return -3;
6137  }
6138  }
6139 
6140  if (!$notrigger) {
6141  // Call trigger
6142  $result = $this->call_trigger('LINEBILL_INSERT', $user);
6143  if ($result < 0) {
6144  $this->db->rollback();
6145  return -2;
6146  }
6147  // End call triggers
6148  }
6149 
6150  $this->db->commit();
6151  return $this->id;
6152  } else {
6153  $this->error = $this->db->lasterror();
6154  $this->db->rollback();
6155  return -2;
6156  }
6157  }
6158 
6166  public function update($user = '', $notrigger = 0)
6167  {
6168  global $user, $conf;
6169 
6170  $error = 0;
6171 
6172  $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'.
6173 
6174  // Clean parameters
6175  $this->desc = trim($this->desc);
6176  if (empty($this->ref_ext)) {
6177  $this->ref_ext = '';
6178  }
6179  if (empty($this->tva_tx)) {
6180  $this->tva_tx = 0;
6181  }
6182  if (empty($this->localtax1_tx)) {
6183  $this->localtax1_tx = 0;
6184  }
6185  if (empty($this->localtax2_tx)) {
6186  $this->localtax2_tx = 0;
6187  }
6188  if (empty($this->localtax1_type)) {
6189  $this->localtax1_type = 0;
6190  }
6191  if (empty($this->localtax2_type)) {
6192  $this->localtax2_type = 0;
6193  }
6194  if (empty($this->total_localtax1)) {
6195  $this->total_localtax1 = 0;
6196  }
6197  if (empty($this->total_localtax2)) {
6198  $this->total_localtax2 = 0;
6199  }
6200  if (empty($this->remise_percent)) {
6201  $this->remise_percent = 0;
6202  }
6203  if (empty($this->info_bits)) {
6204  $this->info_bits = 0;
6205  }
6206  if (empty($this->special_code)) {
6207  $this->special_code = 0;
6208  }
6209  if (empty($this->product_type)) {
6210  $this->product_type = 0;
6211  }
6212  if (empty($this->fk_parent_line)) {
6213  $this->fk_parent_line = 0;
6214  }
6215  if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
6216  $this->situation_percent = 100;
6217  }
6218  if (empty($this->pa_ht)) {
6219  $this->pa_ht = 0;
6220  }
6221 
6222  if (empty($this->multicurrency_subprice)) {
6223  $this->multicurrency_subprice = 0;
6224  }
6225  if (empty($this->multicurrency_total_ht)) {
6226  $this->multicurrency_total_ht = 0;
6227  }
6228  if (empty($this->multicurrency_total_tva)) {
6229  $this->multicurrency_total_tva = 0;
6230  }
6231  if (empty($this->multicurrency_total_ttc)) {
6232  $this->multicurrency_total_ttc = 0;
6233  }
6234 
6235  // Check parameters
6236  if ($this->product_type < 0) {
6237  return -1;
6238  }
6239 
6240  // if buy price not provided, define buyprice as configured in margin admin
6241  if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6242  // We call defineBuyPrice only if data was not provided (if input was '0', we will not go here and value will remaine '0')
6243  $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6244  if ($result < 0) {
6245  return $result;
6246  } else {
6247  $this->pa_ht = $result;
6248  }
6249  }
6250 
6251  $this->db->begin();
6252 
6253  // Update line in database
6254  $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6255  $sql .= " description='".$this->db->escape($this->desc)."'";
6256  $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
6257  $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
6258  $sql .= ", subprice=".price2num($this->subprice);
6259  $sql .= ", remise_percent=".price2num($this->remise_percent);
6260  if ($this->fk_remise_except) {
6261  $sql .= ", fk_remise_except=".$this->fk_remise_except;
6262  } else {
6263  $sql .= ", fk_remise_except=null";
6264  }
6265  $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
6266  $sql .= ", tva_tx=".price2num($this->tva_tx);
6267  $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
6268  $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
6269  $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
6270  $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
6271  $sql .= ", qty=".price2num($this->qty);
6272  $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
6273  $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
6274  $sql .= ", product_type=".$this->product_type;
6275  $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
6276  $sql .= ", special_code='".$this->db->escape($this->special_code)."'";
6277  if (empty($this->skip_update_total)) {
6278  $sql .= ", total_ht=".price2num($this->total_ht);
6279  $sql .= ", total_tva=".price2num($this->total_tva);
6280  $sql .= ", total_ttc=".price2num($this->total_ttc);
6281  $sql .= ", total_localtax1=".price2num($this->total_localtax1);
6282  $sql .= ", total_localtax2=".price2num($this->total_localtax2);
6283  }
6284  $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
6285  $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)
6286  $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
6287  if (!empty($this->rang)) {
6288  $sql .= ", rang=".((int) $this->rang);
6289  }
6290  $sql .= ", situation_percent = ".((float) $this->situation_percent);
6291  $sql .= ", fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6292  $sql .= ", fk_user_modif = ".((int) $user->id);
6293 
6294  // Multicurrency
6295  $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6296  $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6297  $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6298  $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6299 
6300  $sql .= " WHERE rowid = ".((int) $this->rowid);
6301 
6302  dol_syslog(get_class($this)."::update", LOG_DEBUG);
6303  $resql = $this->db->query($sql);
6304  if ($resql) {
6305  if (!$error) {
6306  $this->id = $this->rowid;
6307  $result = $this->insertExtraFields();
6308  if ($result < 0) {
6309  $error++;
6310  }
6311  }
6312 
6313  if (!$error && !$notrigger) {
6314  // Call trigger
6315  $result = $this->call_trigger('LINEBILL_MODIFY', $user);
6316  if ($result < 0) {
6317  $this->db->rollback();
6318  return -2;
6319  }
6320  // End call triggers
6321  }
6322  $this->db->commit();
6323  return 1;
6324  } else {
6325  $this->error = $this->db->error();
6326  $this->db->rollback();
6327  return -2;
6328  }
6329  }
6330 
6338  public function delete($tmpuser = null, $notrigger = false)
6339  {
6340  global $user;
6341 
6342  $this->db->begin();
6343 
6344  // Call trigger
6345  if (empty($notrigger)) {
6346  $result = $this->call_trigger('LINEBILL_DELETE', $user);
6347  if ($result < 0) {
6348  $this->db->rollback();
6349  return -1;
6350  }
6351  }
6352  // End call triggers
6353 
6354  // extrafields
6355  $result = $this->deleteExtraFields();
6356  if ($result < 0) {
6357  $this->db->rollback();
6358  return -1;
6359  }
6360 
6361  $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->rowid);
6362 
6363  if ($this->db->query($sql)) {
6364  $this->db->commit();
6365  return 1;
6366  } else {
6367  $this->error = $this->db->error()." sql=".$sql;
6368  $this->db->rollback();
6369  return -1;
6370  }
6371  }
6372 
6373  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6380  public function update_total()
6381  {
6382  // phpcs:enable
6383  $this->db->begin();
6384  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6385 
6386  // Clean parameters
6387  if (empty($this->total_localtax1)) {
6388  $this->total_localtax1 = 0;
6389  }
6390  if (empty($this->total_localtax2)) {
6391  $this->total_localtax2 = 0;
6392  }
6393 
6394  // Update line in database
6395  $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6396  $sql .= " total_ht=".price2num($this->total_ht)."";
6397  $sql .= ",total_tva=".price2num($this->total_tva)."";
6398  $sql .= ",total_localtax1=".price2num($this->total_localtax1)."";
6399  $sql .= ",total_localtax2=".price2num($this->total_localtax2)."";
6400  $sql .= ",total_ttc=".price2num($this->total_ttc)."";
6401  $sql .= " WHERE rowid = ".((int) $this->rowid);
6402 
6403  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6404 
6405  $resql = $this->db->query($sql);
6406  if ($resql) {
6407  $this->db->commit();
6408  return 1;
6409  } else {
6410  $this->error = $this->db->error();
6411  $this->db->rollback();
6412  return -2;
6413  }
6414  }
6415 
6416  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6425  public function get_prev_progress($invoiceid, $include_credit_note = true)
6426  {
6427  // phpcs:enable
6428  global $invoicecache;
6429 
6430  if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
6431  return 0;
6432  } else {
6433  // If invoice is not a situation invoice, this->fk_prev_id is used for something else
6434  if (!isset($invoicecache[$invoiceid])) {
6435  $invoicecache[$invoiceid] = new Facture($this->db);
6436  $invoicecache[$invoiceid]->fetch($invoiceid);
6437  }
6438  if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
6439  return 0;
6440  }
6441 
6442  $sql = "SELECT situation_percent FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6443  $resql = $this->db->query($sql);
6444  if ($resql && $this->db->num_rows($resql) > 0) {
6445  $res = $this->db->fetch_array($resql);
6446 
6447  $returnPercent = floatval($res['situation_percent']);
6448 
6449  if ($include_credit_note) {
6450  $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
6451  $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
6452  $sql .= " WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6453  $sql .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
6454  $sql .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6455 
6456  $res = $this->db->query($sql);
6457  if ($res) {
6458  while ($obj = $this->db->fetch_object($res)) {
6459  $returnPercent = $returnPercent + floatval($obj->situation_percent);
6460  }
6461  } else {
6462  dol_print_error($this->db);
6463  }
6464  }
6465 
6466  return $returnPercent;
6467  } else {
6468  $this->error = $this->db->error();
6469  dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6470  $this->db->rollback();
6471  return -1;
6472  }
6473  }
6474  }
6475 }
$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.
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 commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product 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 commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage shipments.
Class to manage invoices.
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
setDraft($user, $idwarehouse=-1)
Set draft status.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $forcerecipient='')
Send reminders by emails for invoices that are due CAN BE A CRON TASK.
$fk_facture_source
id of source invoice if replacement invoice or credit note
getIdShippingContact()
Retourne id des contacts clients de livraison.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
deleteline($rowid)
Delete line in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
fetch($rowid, $ref='', $ref_ext='', $notused='', $fetch_situation=false)
Get object from database.
$table_ref_field
{}
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
load_state_board()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines.
update(User $user, $notrigger=0)
Update database.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
$fk_fac_rec_source
id of template invoice when generated from a template invoice
getIdBillingContact()
Retourne id des contacts clients de facturation.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
setRetainedWarrantyDateLimit($timestamp, $dateYmd=false)
Change the retained_warranty_date_limit.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clicable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
updatePriceNextInvoice(&$langs)
Update price of next invoice.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
$pos_source
key of pos source ('0', '1', ...)
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
set_remise_absolue($user, $remise, $notrigger=0)
Set absolute discount.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
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)
Update a detail line.
newCycle()
Gets the smallest reference available for a new cycle.
liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
addline( $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id=0, $fk_unit=null, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an invoice line into database (linked to product/service or not).
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
initAsSpecimen($option='')
Initialise an instance with random values.
getRetainedWarrantyAmount($rounding=-1)
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
$module_source
key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos',...
setUnpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
const STATUS_CLOSED
Classified paid.
Class to manage invoice lines.
$desc
Description ligne.
$fk_parent_line
Id parent line.
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
fetch($rowid)
Load invoice line from database.
update($user='', $notrigger=0)
Update line into database.
$fk_facture
From llx_facturedet Id facture.
update_total()
Update DB line fields total_xxx Used by migration.
Class to manage invoice templates.
Classe permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new For...
Classe permettant la generation de composants html autre Only common components are here.
Class to manage hooks.
Class to manage stock movements.
static getIdFromCode($dbs, $code)
Get id of currency from code.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Definition: user.class.php:47
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition: date.lib.php:635
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition: date.lib.php:621
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:575
dol_get_next_month($month, $year)
Return next month.
Definition: date.lib.php:513
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:594
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1402
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
Definition: files.lib.php:1251
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:61
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1454
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
div float
Buy price without taxes.
Definition: style.css.php:913
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition: price.lib.php:86
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
$conf db
API class for accounts.
Definition: inc.php:41