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