dolibarr  16.0.5
facture.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
5  * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
6  * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
7  * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
9  * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
10  * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
11  * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
12  * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
13  * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
14  * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15  * Copyright (C) 2013 Cedric Gross <c.gross@kreiz-it.fr>
16  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
17  * Copyright (C) 2016-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  $facture->fk_account = $this->fk_account;
1168 
1169  $facture->lines = $this->lines; // Array of lines of invoice
1170  $facture->situation_counter = $this->situation_counter;
1171  $facture->situation_cycle_ref = $this->situation_cycle_ref;
1172  $facture->situation_final = $this->situation_final;
1173 
1174  $facture->retained_warranty = $this->retained_warranty;
1175  $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1176  $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1177 
1178  $facture->fk_user_author = $user->id;
1179 
1180 
1181  // Loop on each line of new invoice
1182  foreach ($facture->lines as $i => $tmpline) {
1183  $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1184  if ($invertdetail) {
1185  $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1186  $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1187  $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1188  $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1189  $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1190  $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1191  $facture->lines[$i]->ref_ext = '';
1192  }
1193  }
1194 
1195  dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1196 
1197  $facid = $facture->create($user);
1198  if ($facid <= 0) {
1199  $this->error = $facture->error;
1200  $this->errors = $facture->errors;
1201  } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1202  $this->fetchObjectLinked('', '', $this->id, 'facture');
1203 
1204  foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1205  foreach ($Tfk_object as $fk_object) {
1206  $facture->add_object_linked($typeObject, $fk_object);
1207  }
1208  }
1209 
1210  $facture->add_object_linked('facture', $this->fk_facture_source);
1211  }
1212 
1213  return $facid;
1214  }
1215 
1216 
1224  public function createFromClone(User $user, $fromid = 0)
1225  {
1226  global $conf, $hookmanager;
1227 
1228  $error = 0;
1229 
1230  $object = new Facture($this->db);
1231 
1232  $this->db->begin();
1233 
1234  $object->fetch($fromid);
1235 
1236  // Load source object
1237  $objFrom = clone $object;
1238 
1239  // Change socid if needed
1240  if (!empty($this->socid) && $this->socid != $object->socid) {
1241  $objsoc = new Societe($this->db);
1242 
1243  if ($objsoc->fetch($this->socid) > 0) {
1244  $object->socid = $objsoc->id;
1245  $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1246  $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1247  $object->fk_project = '';
1248  $object->fk_delivery_address = '';
1249  }
1250 
1251  // TODO Change product price if multi-prices
1252  }
1253 
1254  $object->id = 0;
1255  $object->statut = self::STATUS_DRAFT;
1256  $object->status = self::STATUS_DRAFT;
1257 
1258  // Clear fields
1259  $object->date = (empty($this->date) ? dol_now() : $this->date);
1260  $object->user_author = $user->id; // deprecated
1261  $object->user_valid = null; // deprecated
1262  $object->fk_user_author = $user->id;
1263  $object->fk_user_valid = null;
1264  $object->fk_facture_source = 0;
1265  $object->date_creation = '';
1266  $object->date_modification = '';
1267  $object->date_validation = '';
1268  $object->ref_client = '';
1269  $object->close_code = '';
1270  $object->close_note = '';
1271  if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
1272  $object->note_private = '';
1273  $object->note_public = '';
1274  }
1275 
1276  // Loop on each line of new invoice
1277  foreach ($object->lines as $i => $line) {
1278  if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1279  unset($object->lines[$i]);
1280  continue;
1281  }
1282 
1283  // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month)
1284  // If it's a service with start and end dates
1285  if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1286  // Get the dates
1287  $start = dol_getdate($line->date_start);
1288  $end = dol_getdate($line->date_end);
1289 
1290  // Get the first and last day of the month
1291  $first = dol_get_first_day($start['year'], $start['mon']);
1292  $last = dol_get_last_day($end['year'], $end['mon']);
1293 
1294  //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1295  //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1296  // If start date is first date of month and end date is last date of month
1297  if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1298  && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1299  $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1300  $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1301  $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1302  $object->lines[$i]->date_start = $newFirst;
1303  $object->lines[$i]->date_end = $newLast;
1304  }
1305  }
1306 
1307  $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1308  }
1309 
1310  // Create clone
1311  $object->context['createfromclone'] = 'createfromclone';
1312  $result = $object->create($user);
1313  if ($result < 0) {
1314  $error++;
1315  $this->error = $object->error;
1316  $this->errors = $object->errors;
1317  } else {
1318  // copy internal contacts
1319  if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1320  $error++;
1321  $this->error = $object->error;
1322  $this->errors = $object->errors;
1323  } elseif ($object->socid == $objFrom->socid) {
1324  // copy external contacts if same company
1325  if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1326  $error++;
1327  $this->error = $object->error;
1328  $this->errors = $object->errors;
1329  }
1330  }
1331  }
1332 
1333  if (!$error) {
1334  // Hook of thirdparty module
1335  if (is_object($hookmanager)) {
1336  $parameters = array('objFrom'=>$objFrom);
1337  $action = '';
1338  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1339  if ($reshook < 0) {
1340  $this->errors += $hookmanager->errors;
1341  $this->error = $hookmanager->error;
1342  $error++;
1343  }
1344  }
1345  }
1346 
1347  unset($object->context['createfromclone']);
1348 
1349  // End
1350  if (!$error) {
1351  $this->db->commit();
1352  return $object->id;
1353  } else {
1354  $this->db->rollback();
1355  return -1;
1356  }
1357  }
1358 
1366  public function createFromOrder($object, User $user)
1367  {
1368  global $conf, $hookmanager;
1369 
1370  $error = 0;
1371 
1372  // Closed order
1373  $this->date = dol_now();
1374  $this->source = 0;
1375 
1376  $num = count($object->lines);
1377  for ($i = 0; $i < $num; $i++) {
1378  $line = new FactureLigne($this->db);
1379 
1380  $line->libelle = $object->lines[$i]->libelle; // deprecated
1381  $line->label = $object->lines[$i]->label;
1382  $line->desc = $object->lines[$i]->desc;
1383  $line->subprice = $object->lines[$i]->subprice;
1384  $line->total_ht = $object->lines[$i]->total_ht;
1385  $line->total_tva = $object->lines[$i]->total_tva;
1386  $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1387  $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1388  $line->total_ttc = $object->lines[$i]->total_ttc;
1389  $line->vat_src_code = $object->lines[$i]->vat_src_code;
1390  $line->tva_tx = $object->lines[$i]->tva_tx;
1391  $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1392  $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1393  $line->qty = $object->lines[$i]->qty;
1394  $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1395  $line->remise_percent = $object->lines[$i]->remise_percent;
1396  $line->fk_product = $object->lines[$i]->fk_product;
1397  $line->info_bits = $object->lines[$i]->info_bits;
1398  $line->product_type = $object->lines[$i]->product_type;
1399  $line->rang = $object->lines[$i]->rang;
1400  $line->special_code = $object->lines[$i]->special_code;
1401  $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1402  $line->fk_unit = $object->lines[$i]->fk_unit;
1403  $line->date_start = $object->lines[$i]->date_start;
1404  $line->date_end = $object->lines[$i]->date_end;
1405 
1406  // Multicurrency
1407  $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1408  $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1409  $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1410  $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1411  $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1412  $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1413 
1414  $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1415  $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);
1416  $line->pa_ht = $marginInfos[0];
1417 
1418  // get extrafields from original line
1419  $object->lines[$i]->fetch_optionals();
1420  foreach ($object->lines[$i]->array_options as $options_key => $value) {
1421  $line->array_options[$options_key] = $value;
1422  }
1423 
1424  $this->lines[$i] = $line;
1425  }
1426 
1427  $this->socid = $object->socid;
1428  $this->fk_project = $object->fk_project;
1429  $this->fk_account = $object->fk_account;
1430  $this->cond_reglement_id = $object->cond_reglement_id;
1431  $this->mode_reglement_id = $object->mode_reglement_id;
1432  $this->availability_id = $object->availability_id;
1433  $this->demand_reason_id = $object->demand_reason_id;
1434  $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1435  $this->date_livraison = $object->delivery_date; // deprecated
1436  $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1437  $this->contact_id = $object->contact_id;
1438  $this->ref_client = $object->ref_client;
1439 
1440  if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1441  $this->note_private = $object->note_private;
1442  $this->note_public = $object->note_public;
1443  }
1444 
1445  $this->module_source = $object->module_source;
1446  $this->pos_source = $object->pos_source;
1447 
1448  $this->origin = $object->element;
1449  $this->origin_id = $object->id;
1450 
1451  $this->fk_user_author = $user->id;
1452 
1453  // get extrafields from original line
1454  $object->fetch_optionals();
1455  foreach ($object->array_options as $options_key => $value) {
1456  $this->array_options[$options_key] = $value;
1457  }
1458 
1459  // Possibility to add external linked objects with hooks
1460  $this->linked_objects[$this->origin] = $this->origin_id;
1461  if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1462  $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1463  }
1464 
1465  $ret = $this->create($user);
1466 
1467  if ($ret > 0) {
1468  // Actions hooked (by external module)
1469  $hookmanager->initHooks(array('invoicedao'));
1470 
1471  $parameters = array('objFrom'=>$object);
1472  $action = '';
1473  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1474  if ($reshook < 0) {
1475  $this->errors += $hookmanager->errors;
1476  $this->error = $hookmanager->error;
1477  $error++;
1478  }
1479 
1480  if (!$error) {
1481  return 1;
1482  } else {
1483  return -1;
1484  }
1485  } else {
1486  return -1;
1487  }
1488  }
1489 
1502  static public function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1503  {
1504  global $conf, $langs, $hookmanager, $action;
1505 
1506  if (! in_array($origin->element, array('propal', 'commande'))) {
1507  $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1508  return null;
1509  }
1510 
1511  if (empty($date)) {
1512  $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1513  return null;
1514  }
1515 
1516  require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1517 
1518  if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1519  $origin->error = 'ErrorDateIsInFuture';
1520  return null;
1521  }
1522 
1523  if ($payment_terms_id <= 0) {
1524  $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1525  return null;
1526  }
1527 
1528  $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1529 
1530  if (empty($payment_conditions_deposit_percent)) {
1531  $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1532  return null;
1533  }
1534 
1535  if (empty($origin->deposit_percent)) {
1536  $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1537  return null;
1538  }
1539 
1540  $deposit = new self($origin->db);
1541  $deposit->socid = $origin->socid;
1542  $deposit->type = self::TYPE_DEPOSIT;
1543  $deposit->fk_project = $origin->fk_project;
1544  $deposit->ref_client = $origin->ref_client;
1545  $deposit->date = $date;
1546  $deposit->mode_reglement_id = $origin->mode_reglement_id;
1547  $deposit->cond_reglement_id = $payment_terms_id;
1548  $deposit->availability_id = $origin->availability_id;
1549  $deposit->demand_reason_id = $origin->demand_reason_id;
1550  $deposit->fk_account = $origin->fk_account;
1551  $deposit->fk_incoterms = $origin->fk_incoterms;
1552  $deposit->location_incoterms = $origin->location_incoterms;
1553  $deposit->fk_multicurrency = $origin->fk_multicurrency;
1554  $deposit->multicurrency_code = $origin->multicurrency_code;
1555  $deposit->multicurrency_tx = $origin->multicurrency_tx;
1556  $deposit->module_source = $origin->module_source;
1557  $deposit->pos_source = $origin->pos_source;
1558  $deposit->model_pdf = 'crabe';
1559 
1560  $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1561 
1562  if (!empty($conf->global->$modelByTypeConfName)) {
1563  $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1564  } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1565  $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1566  }
1567 
1568  if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1569  $deposit->note_private = $origin->note_private;
1570  $deposit->note_public = $origin->note_public;
1571  }
1572 
1573  $deposit->origin = $origin->element;
1574  $deposit->origin_id = $origin->id;
1575 
1576  $origin->fetch_optionals();
1577 
1578  foreach ($origin->array_options as $extrakey => $value) {
1579  $deposit->array_options[$extrakey] = $value;
1580  }
1581 
1582  $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1583 
1584  foreach ($overrideFields as $key => $value) {
1585  $deposit->$key = $value;
1586  }
1587 
1588  $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1589 
1590  $origin->db->begin();
1591 
1592  // Facture::create() also imports contact from origin
1593  $createReturn = $deposit->create($user, $notrigger);
1594 
1595  if ($createReturn <= 0) {
1596  $origin->db->rollback();
1597  $origin->error = $deposit->error;
1598  $origin->errors = $deposit->errors;
1599  return null;
1600  }
1601 
1602  $amount_ttc_diff = 0;
1603  $amountdeposit = array();
1604  $descriptions = array();
1605 
1606  if (! empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1607  $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1608 
1609  $TTotalByTva = array();
1610  foreach ($origin->lines as &$line) {
1611  if (!empty($line->special_code)) {
1612  continue;
1613  }
1614  $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1615  $descriptions[$line->tva_tx] .= '<li>' . (! empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1616  $descriptions[$line->tva_tx] .= (! empty($line->product_label) ? $line->product_label . ' - ' : '');
1617  $descriptions[$line->tva_tx] .= $langs->trans('Qty') . ' : ' . $line->qty;
1618  $descriptions[$line->tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1619  }
1620 
1621  foreach ($TTotalByTva as $tva => &$total) {
1622  $coef = $total / $origin->total_ttc; // Calc coef
1623  $am = $amount * $coef;
1624  $amount_ttc_diff += $am;
1625  $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
1626  }
1627  } else {
1628  $totalamount = 0;
1629  $lines = $origin->lines;
1630  $numlines = count($lines);
1631  for ($i = 0; $i < $numlines; $i++) {
1632  if (empty($lines[$i]->qty)) {
1633  continue; // We discard qty=0, it is an option
1634  }
1635  if (!empty($lines[$i]->special_code)) {
1636  continue; // We discard special_code (frais port, ecotaxe, option, ...)
1637  }
1638 
1639  $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1640  $tva_tx = $lines[$i]->tva_tx;
1641  $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1642  $descriptions[$tva_tx] .= '<li>' . (! empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1643  $descriptions[$tva_tx] .= (! empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1644  $descriptions[$tva_tx] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1645  $descriptions[$tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1646  }
1647 
1648  if ($totalamount == 0) {
1649  $amountdeposit[0] = 0;
1650  }
1651 
1652  $amount_ttc_diff = $amountdeposit[0];
1653  }
1654 
1655  foreach ($amountdeposit as $tva => $amount) {
1656  if (empty($amount)) {
1657  continue;
1658  }
1659 
1660  $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1661 
1662  // Hidden conf
1663  if (! empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && ! empty($descriptions[$tva])) {
1664  $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1665  }
1666 
1667  $addlineResult = $deposit->addline(
1668  $descline,
1669  $amount, // subprice
1670  1, // quantity
1671  $tva, // vat rate
1672  0, // localtax1_tx
1673  0, // localtax2_tx
1674  (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1675  0, // remise_percent
1676  0, // date_start
1677  0, // date_end
1678  0,
1679  0, // info_bits
1680  0,
1681  'HT',
1682  0,
1683  0, // product_type
1684  1,
1685  0, // special_code
1686  $deposit->origin,
1687  0,
1688  0,
1689  0,
1690  0
1691  //,$langs->trans('Deposit') //Deprecated
1692  );
1693 
1694  if ($addlineResult < 0) {
1695  $origin->db->rollback();
1696  $origin->error = $deposit->error;
1697  $origin->errors = $deposit->errors;
1698  return null;
1699  }
1700  }
1701 
1702  $diff = $deposit->total_ttc - $amount_ttc_diff;
1703 
1704  if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1705  $deposit->fetch_lines();
1706  $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1707 
1708  $updatelineResult = $deposit->updateline(
1709  $deposit->lines[0]->id,
1710  $deposit->lines[0]->desc,
1711  $subprice_diff,
1712  $deposit->lines[0]->qty,
1713  $deposit->lines[0]->remise_percent,
1714  $deposit->lines[0]->date_start,
1715  $deposit->lines[0]->date_end,
1716  $deposit->lines[0]->tva_tx,
1717  0,
1718  0,
1719  'HT',
1720  $deposit->lines[0]->info_bits,
1721  $deposit->lines[0]->product_type,
1722  0,
1723  0,
1724  0,
1725  $deposit->lines[0]->pa_ht,
1726  $deposit->lines[0]->label,
1727  0,
1728  array(),
1729  100
1730  );
1731 
1732  if ($updatelineResult < 0) {
1733  $origin->db->rollback();
1734  $origin->error = $deposit->error;
1735  $origin->errors = $deposit->errors;
1736  return null;
1737  }
1738  }
1739 
1740 
1741  if (! is_object($hookmanager)) {
1742  require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1743  $hookmanager = new HookManager($origin->db);
1744  }
1745 
1746  $hookmanager->initHooks(array('invoicedao'));
1747 
1748  $parameters = array('objFrom' => $origin);
1749  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
1750  // modified by hook
1751  if ($reshook < 0) {
1752  $origin->db->rollback();
1753  $origin->error = $hookmanager->error;
1754  $origin->errors = $hookmanager->errors;
1755  return null;
1756  }
1757 
1758  if (! empty($autoValidateDeposit)) {
1759  $validateReturn = $deposit->validate($user, '', 0, $notrigger);
1760 
1761  if ($validateReturn < 0) {
1762  $origin->db->rollback();
1763  $origin->error = $deposit->error;
1764  $origin->errors = $deposit->errors;
1765  return null;
1766  }
1767  }
1768 
1769  unset($deposit->context['createdepositfromorigin']);
1770 
1771  $origin->db->commit();
1772 
1773  return $deposit;
1774  }
1775 
1790  public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
1791  {
1792  global $langs, $conf, $user, $mysoc;
1793 
1794  if (!empty($conf->dol_no_mouse_hover)) {
1795  $notooltip = 1; // Force disable tooltips
1796  }
1797 
1798  $result = '';
1799 
1800  if ($option == 'withdraw') {
1801  $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1802  } else {
1803  $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
1804  }
1805 
1806  if (!$user->rights->facture->lire) {
1807  $option = 'nolink';
1808  }
1809 
1810  if ($option !== 'nolink') {
1811  // Add param to save lastsearch_values or not
1812  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1813  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1814  $add_save_lastsearch_values = 1;
1815  }
1816  if ($add_save_lastsearch_values) {
1817  $url .= '&save_lastsearch_values=1';
1818  }
1819  }
1820 
1821  if ($short) {
1822  return $url;
1823  }
1824 
1825  $picto = $this->picto;
1826  if ($this->type == self::TYPE_REPLACEMENT) {
1827  $picto .= 'r'; // Replacement invoice
1828  }
1829  if ($this->type == self::TYPE_CREDIT_NOTE) {
1830  $picto .= 'a'; // Credit note
1831  }
1832  if ($this->type == self::TYPE_DEPOSIT) {
1833  $picto .= 'd'; // Deposit invoice
1834  }
1835  $label = '';
1836 
1837  if ($user->rights->facture->lire) {
1838  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
1839  if ($this->type == self::TYPE_REPLACEMENT) {
1840  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("ReplacementInvoice").'</u>';
1841  }
1842  if ($this->type == self::TYPE_CREDIT_NOTE) {
1843  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
1844  }
1845  if ($this->type == self::TYPE_DEPOSIT) {
1846  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
1847  }
1848  if ($this->type == self::TYPE_SITUATION) {
1849  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceSituation").'</u>';
1850  }
1851  if (isset($this->statut) && isset($this->alreadypaid)) {
1852  $label .= ' '.$this->getLibStatut(5, $this->alreadypaid);
1853  }
1854  if (!empty($this->ref)) {
1855  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1856  }
1857  if (!empty($this->ref_client)) {
1858  $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
1859  }
1860  if (!empty($this->date)) {
1861  $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1862  }
1863  if (!empty($this->total_ht)) {
1864  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1865  }
1866  if (!empty($this->total_tva)) {
1867  $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1868  }
1869  if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) { // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
1870  $label .= '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1871  }
1872  if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1873  $label .= '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1874  }
1875  if (!empty($this->total_ttc)) {
1876  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1877  }
1878  if ($moretitle) {
1879  $label .= ' - '.$moretitle;
1880  }
1881  }
1882 
1883  $linkclose = ($target ? ' target="'.$target.'"' : '');
1884  if (empty($notooltip) && $user->rights->facture->lire) {
1885  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1886  $label = $langs->trans("Invoice");
1887  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1888  }
1889  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1890  $linkclose .= ' class="classfortooltip"';
1891  }
1892 
1893  $linkstart = '<a href="'.$url.'"';
1894  $linkstart .= $linkclose.'>';
1895  $linkend = '</a>';
1896 
1897  if ($option == 'nolink') {
1898  $linkstart = '';
1899  $linkend = '';
1900  }
1901 
1902  $result .= $linkstart;
1903  if ($withpicto) {
1904  $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1905  }
1906  if ($withpicto != 2) {
1907  $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref);
1908  }
1909  $result .= $linkend;
1910 
1911  if ($addlinktonotes) {
1912  $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1913  if ($txttoshow) {
1914  //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1915  $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
1916  $result .= ' <span class="note inline-block">';
1917  $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
1918  $result .= img_picto('', 'note');
1919  $result .= '</a>';
1920  //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1921  //$result.='</a>';
1922  $result .= '</span>';
1923  }
1924  }
1925 
1926  global $action, $hookmanager;
1927  $hookmanager->initHooks(array('invoicedao'));
1928  $parameters = array('id'=>$this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value'=> $save_lastsearch_value, 'target' => $target);
1929  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1930  if ($reshook > 0) {
1931  $result = $hookmanager->resPrint;
1932  } else {
1933  $result .= $hookmanager->resPrint;
1934  }
1935 
1936  return $result;
1937  }
1938 
1949  public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false)
1950  {
1951  if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1952  return -1;
1953  }
1954 
1955  $sql = 'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc';
1956  $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1957  $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
1958  $sql .= ', f.datef as df, f.date_pointoftax';
1959  $sql .= ', f.date_lim_reglement as dlr';
1960  $sql .= ', f.datec as datec';
1961  $sql .= ', f.date_valid as datev';
1962  $sql .= ', f.tms as datem';
1963  $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';
1964  $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
1965  $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1966  $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1967  $sql .= ', f.fk_account';
1968  $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1969  $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1970  $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1971  $sql .= ', f.fk_incoterms, f.location_incoterms';
1972  $sql .= ', f.module_source, f.pos_source';
1973  $sql .= ", i.libelle as label_incoterms";
1974  $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";
1975  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
1976  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1977  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
1978  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
1979 
1980  if ($rowid) {
1981  $sql .= " WHERE f.rowid=".((int) $rowid);
1982  } else {
1983  $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
1984  if ($ref) {
1985  $sql .= " AND f.ref='".$this->db->escape($ref)."'";
1986  }
1987  if ($ref_ext) {
1988  $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
1989  }
1990  if ($notused) {
1991  $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated
1992  }
1993  }
1994 
1995  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1996  $resql = $this->db->query($sql);
1997  if ($resql) {
1998  if ($this->db->num_rows($resql)) {
1999  $obj = $this->db->fetch_object($resql);
2000 
2001  $this->id = $obj->rowid;
2002  $this->entity = $obj->entity;
2003 
2004  $this->ref = $obj->ref;
2005  $this->ref_client = $obj->ref_client;
2006  $this->ref_customer = $obj->ref_client;
2007  $this->ref_ext = $obj->ref_ext;
2008  $this->type = $obj->type;
2009  $this->date = $this->db->jdate($obj->df);
2010  $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2011  $this->date_creation = $this->db->jdate($obj->datec);
2012  $this->date_validation = $this->db->jdate($obj->datev);
2013  $this->date_modification = $this->db->jdate($obj->datem);
2014  $this->datem = $this->db->jdate($obj->datem);
2015  $this->remise_percent = $obj->remise_percent;
2016  $this->remise_absolue = $obj->remise_absolue;
2017  $this->total_ht = $obj->total_ht;
2018  $this->total_tva = $obj->total_tva;
2019  $this->total_localtax1 = $obj->localtax1;
2020  $this->total_localtax2 = $obj->localtax2;
2021  $this->total_ttc = $obj->total_ttc;
2022  $this->revenuestamp = $obj->revenuestamp;
2023  $this->paye = $obj->paye;
2024  $this->close_code = $obj->close_code;
2025  $this->close_note = $obj->close_note;
2026 
2027  $this->socid = $obj->fk_soc;
2028  $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2029 
2030  $this->fk_project = $obj->fk_project;
2031  $this->project = null; // Clear if another value was already set by fetch_projet
2032 
2033  $this->statut = $obj->fk_statut;
2034  $this->status = $obj->fk_statut;
2035 
2036  $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2037  $this->mode_reglement_id = $obj->fk_mode_reglement;
2038  $this->mode_reglement_code = $obj->mode_reglement_code;
2039  $this->mode_reglement = $obj->mode_reglement_libelle;
2040  $this->cond_reglement_id = $obj->fk_cond_reglement;
2041  $this->cond_reglement_code = $obj->cond_reglement_code;
2042  $this->cond_reglement = $obj->cond_reglement_libelle;
2043  $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2044  $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2045  $this->fk_facture_source = $obj->fk_facture_source;
2046  $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2047  $this->note = $obj->note_private; // deprecated
2048  $this->note_private = $obj->note_private;
2049  $this->note_public = $obj->note_public;
2050  $this->user_author = $obj->fk_user_author; // deprecated
2051  $this->user_valid = $obj->fk_user_valid; // deprecated
2052  $this->user_modification = $obj->fk_user_modif; // deprecated
2053  $this->fk_user_author = $obj->fk_user_author;
2054  $this->fk_user_valid = $obj->fk_user_valid;
2055  $this->fk_user_modif = $obj->fk_user_modif;
2056  $this->model_pdf = $obj->model_pdf;
2057  $this->modelpdf = $obj->model_pdf; // deprecated
2058  $this->last_main_doc = $obj->last_main_doc;
2059  $this->situation_cycle_ref = $obj->situation_cycle_ref;
2060  $this->situation_counter = $obj->situation_counter;
2061  $this->situation_final = $obj->situation_final;
2062  $this->retained_warranty = $obj->retained_warranty;
2063  $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2064  $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2065 
2066  $this->extraparams = (array) json_decode($obj->extraparams, true);
2067 
2068  //Incoterms
2069  $this->fk_incoterms = $obj->fk_incoterms;
2070  $this->location_incoterms = $obj->location_incoterms;
2071  $this->label_incoterms = $obj->label_incoterms;
2072 
2073  $this->module_source = $obj->module_source;
2074  $this->pos_source = $obj->pos_source;
2075 
2076  // Multicurrency
2077  $this->fk_multicurrency = $obj->fk_multicurrency;
2078  $this->multicurrency_code = $obj->multicurrency_code;
2079  $this->multicurrency_tx = $obj->multicurrency_tx;
2080  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2081  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2082  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2083 
2084  if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2086  }
2087 
2088  if ($this->status == self::STATUS_DRAFT) {
2089  $this->brouillon = 1;
2090  }
2091 
2092  // Retrieve all extrafield
2093  // fetch optionals attributes and labels
2094  $this->fetch_optionals();
2095 
2096  // Lines
2097  $this->lines = array();
2098 
2099  $result = $this->fetch_lines();
2100  if ($result < 0) {
2101  $this->error = $this->db->error();
2102  return -3;
2103  }
2104 
2105  $this->db->free($resql);
2106 
2107  return 1;
2108  } else {
2109  $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2110 
2111  dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2112  return 0;
2113  }
2114  } else {
2115  $this->error = $this->db->lasterror();
2116  return -1;
2117  }
2118  }
2119 
2120 
2121  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2130  public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2131  {
2132  // phpcs:enable
2133  global $langs, $conf;
2134 
2135  $this->lines = array();
2136 
2137  $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,';
2138  $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,';
2139  $sql .= ' l.situation_percent, l.fk_prev_id,';
2140  $sql .= ' l.rang, l.special_code,';
2141  $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2142  $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,';
2143  $sql .= ' l.fk_unit,';
2144  $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2145  $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2146  $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
2147  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2148  $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2149  $sql .= ' ORDER BY l.rang, l.rowid';
2150 
2151  dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2152  $result = $this->db->query($sql);
2153  if ($result) {
2154  $num = $this->db->num_rows($result);
2155  $i = 0;
2156  while ($i < $num) {
2157  $objp = $this->db->fetch_object($result);
2158  $line = new FactureLigne($this->db);
2159 
2160  $line->id = $objp->rowid;
2161  $line->rowid = $objp->rowid; // deprecated
2162  $line->fk_facture = $objp->fk_facture;
2163  $line->label = $objp->custom_label; // deprecated
2164  $line->desc = $objp->description; // Description line
2165  $line->description = $objp->description; // Description line
2166  $line->product_type = $objp->product_type; // Type of line
2167  $line->ref = $objp->product_ref; // Ref product
2168  $line->product_ref = $objp->product_ref; // Ref product
2169  $line->libelle = $objp->product_label; // deprecated
2170  $line->product_label = $objp->product_label; // Label product
2171  $line->product_desc = $objp->product_desc; // Description product
2172  $line->fk_product_type = $objp->fk_product_type; // Type of product
2173  $line->qty = $objp->qty;
2174  $line->subprice = $objp->subprice;
2175  $line->ref_ext = $objp->ref_ext; // line external ref
2176 
2177  $line->vat_src_code = $objp->vat_src_code;
2178  $line->tva_tx = $objp->tva_tx;
2179  $line->localtax1_tx = $objp->localtax1_tx;
2180  $line->localtax2_tx = $objp->localtax2_tx;
2181  $line->localtax1_type = $objp->localtax1_type;
2182  $line->localtax2_type = $objp->localtax2_type;
2183  $line->remise_percent = $objp->remise_percent;
2184  $line->fk_remise_except = $objp->fk_remise_except;
2185  $line->fk_product = $objp->fk_product;
2186  $line->date_start = $this->db->jdate($objp->date_start);
2187  $line->date_end = $this->db->jdate($objp->date_end);
2188  $line->date_start = $this->db->jdate($objp->date_start);
2189  $line->date_end = $this->db->jdate($objp->date_end);
2190  $line->info_bits = $objp->info_bits;
2191  $line->total_ht = $objp->total_ht;
2192  $line->total_tva = $objp->total_tva;
2193  $line->total_localtax1 = $objp->total_localtax1;
2194  $line->total_localtax2 = $objp->total_localtax2;
2195  $line->total_ttc = $objp->total_ttc;
2196  $line->code_ventilation = $objp->fk_code_ventilation;
2197  $line->fk_fournprice = $objp->fk_fournprice;
2198  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2199  $line->pa_ht = $marginInfos[0];
2200  $line->marge_tx = $marginInfos[1];
2201  $line->marque_tx = $marginInfos[2];
2202  $line->rang = $objp->rang;
2203  $line->special_code = $objp->special_code;
2204  $line->fk_parent_line = $objp->fk_parent_line;
2205  $line->situation_percent = $objp->situation_percent;
2206  $line->fk_prev_id = $objp->fk_prev_id;
2207  $line->fk_unit = $objp->fk_unit;
2208 
2209  // Accountancy
2210  $line->fk_accounting_account = $objp->fk_code_ventilation;
2211 
2212  // Multicurrency
2213  $line->fk_multicurrency = $objp->fk_multicurrency;
2214  $line->multicurrency_code = $objp->multicurrency_code;
2215  $line->multicurrency_subprice = $objp->multicurrency_subprice;
2216  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2217  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2218  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2219 
2220  $line->fetch_optionals();
2221 
2222  // multilangs
2223  if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2224  $tmpproduct = new Product($this->db);
2225  $tmpproduct->fetch($objp->fk_product);
2226  $tmpproduct->getMultiLangs();
2227 
2228  $line->multilangs = $tmpproduct->multilangs;
2229  }
2230 
2231  $this->lines[$i] = $line;
2232 
2233  $i++;
2234  }
2235  $this->db->free($result);
2236  return 1;
2237  } else {
2238  $this->error = $this->db->error();
2239  return -3;
2240  }
2241  }
2242 
2250  {
2251  global $conf;
2252 
2253  $this->tab_previous_situation_invoice = array();
2254  $this->tab_next_situation_invoice = array();
2255 
2256  $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2257  $sql .= " WHERE rowid <> ".((int) $this->id);
2258  $sql .= ' AND entity = '.((int) $this->entity);
2259  $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2260  $sql .= ' ORDER BY situation_counter ASC';
2261 
2262  dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2263  $result = $this->db->query($sql);
2264  if ($result && $this->db->num_rows($result) > 0) {
2265  while ($objp = $this->db->fetch_object($result)) {
2266  $invoice = new Facture($this->db);
2267  if ($invoice->fetch($objp->rowid) > 0) {
2268  if ($objp->situation_counter < $this->situation_counter
2269  || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2270  ) {
2271  $this->tab_previous_situation_invoice[] = $invoice;
2272  } else {
2273  $this->tab_next_situation_invoice[] = $invoice;
2274  }
2275  }
2276  }
2277  }
2278  }
2279 
2287  public function update(User $user, $notrigger = 0)
2288  {
2289  global $conf;
2290 
2291  $error = 0;
2292 
2293  // Clean parameters
2294  if (empty($this->type)) {
2295  $this->type = self::TYPE_STANDARD;
2296  }
2297  if (isset($this->ref)) {
2298  $this->ref = trim($this->ref);
2299  }
2300  if (isset($this->ref_ext)) {
2301  $this->ref_ext = trim($this->ref_ext);
2302  }
2303  if (isset($this->ref_client)) {
2304  $this->ref_client = trim($this->ref_client);
2305  }
2306  if (isset($this->increment)) {
2307  $this->increment = trim($this->increment);
2308  }
2309  if (isset($this->close_code)) {
2310  $this->close_code = trim($this->close_code);
2311  }
2312  if (isset($this->close_note)) {
2313  $this->close_note = trim($this->close_note);
2314  }
2315  if (isset($this->note) || isset($this->note_private)) {
2316  $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2317  }
2318  if (isset($this->note) || isset($this->note_private)) {
2319  $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2320  }
2321  if (isset($this->note_public)) {
2322  $this->note_public = trim($this->note_public);
2323  }
2324  if (isset($this->model_pdf)) {
2325  $this->model_pdf = trim($this->model_pdf);
2326  }
2327  if (isset($this->import_key)) {
2328  $this->import_key = trim($this->import_key);
2329  }
2330  if (isset($this->retained_warranty)) {
2331  $this->retained_warranty = floatval($this->retained_warranty);
2332  }
2333 
2334 
2335  // Check parameters
2336  // Put here code to add control on parameters values
2337 
2338  // Update request
2339  $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2340  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2341  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2342  $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
2343  $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
2344  $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2345  $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
2346  $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2347  $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2348  $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2349  $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2350  $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
2351  $sql .= " remise_percent=".(isset($this->remise_percent) ? $this->db->escape($this->remise_percent) : "null").",";
2352  $sql .= " remise_absolue=".(isset($this->remise_absolue) ? $this->db->escape($this->remise_absolue) : "null").",";
2353  $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2354  $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2355  $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
2356  $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
2357  $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
2358  $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
2359  $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
2360  $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? $this->db->escape($this->revenuestamp) : "null").",";
2361  $sql .= " fk_statut=".(isset($this->statut) ? $this->db->escape($this->statut) : "null").",";
2362  $sql .= " fk_user_author=".(isset($this->user_author) ? $this->db->escape($this->user_author) : "null").",";
2363  $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->db->escape($this->fk_user_valid) : "null").",";
2364  $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->db->escape($this->fk_facture_source) : "null").",";
2365  $sql .= " fk_projet=".(isset($this->fk_project) ? $this->db->escape($this->fk_project) : "null").",";
2366  $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->db->escape($this->cond_reglement_id) : "null").",";
2367  $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->db->escape($this->mode_reglement_id) : "null").",";
2368  $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2369  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2370  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2371  $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2372  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2373  $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : $this->db->escape($this->situation_cycle_ref)).",";
2374  $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : $this->db->escape($this->situation_counter)).",";
2375  $sql .= " situation_final=".(empty($this->situation_final) ? "0" : $this->db->escape($this->situation_final)).",";
2376  $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty)).",";
2377  $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2378  $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) : "null");
2379  $sql .= " WHERE rowid=".((int) $this->id);
2380 
2381  $this->db->begin();
2382 
2383  dol_syslog(get_class($this)."::update", LOG_DEBUG);
2384  $resql = $this->db->query($sql);
2385  if (!$resql) {
2386  $error++;
2387  $this->errors[] = "Error ".$this->db->lasterror();
2388  }
2389 
2390  if (!$error) {
2391  $result = $this->insertExtraFields();
2392  if ($result < 0) {
2393  $error++;
2394  }
2395  }
2396 
2397  if (!$error && !$notrigger) {
2398  // Call trigger
2399  $result = $this->call_trigger('BILL_MODIFY', $user);
2400  if ($result < 0) {
2401  $error++;
2402  }
2403  // End call triggers
2404  }
2405 
2406  // Commit or rollback
2407  if ($error) {
2408  foreach ($this->errors as $errmsg) {
2409  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2410  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2411  }
2412  $this->db->rollback();
2413  return -1 * $error;
2414  } else {
2415  $this->db->commit();
2416  return 1;
2417  }
2418  }
2419 
2420 
2421  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2428  public function insert_discount($idremise)
2429  {
2430  // phpcs:enable
2431  global $conf, $langs;
2432 
2433  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2434  include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2435 
2436  $this->db->begin();
2437 
2438  $remise = new DiscountAbsolute($this->db);
2439  $result = $remise->fetch($idremise);
2440 
2441  if ($result > 0) {
2442  if ($remise->fk_facture) { // Protection against multiple submission
2443  $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2444  $this->db->rollback();
2445  return -5;
2446  }
2447 
2448  $facligne = new FactureLigne($this->db);
2449  $facligne->fk_facture = $this->id;
2450  $facligne->fk_remise_except = $remise->id;
2451  $facligne->desc = $remise->description; // Description ligne
2452  $facligne->vat_src_code = $remise->vat_src_code;
2453  $facligne->tva_tx = $remise->tva_tx;
2454  $facligne->subprice = -$remise->amount_ht;
2455  $facligne->fk_product = 0; // Id produit predefini
2456  $facligne->qty = 1;
2457  $facligne->remise_percent = 0;
2458  $facligne->rang = -1;
2459  $facligne->info_bits = 2;
2460 
2461  if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2462  $facligne->rang = 1;
2463  $linecount = count($this->lines);
2464  for ($ii = 1; $ii <= $linecount; $ii++) {
2465  $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii+1);
2466  }
2467  }
2468 
2469  // Get buy/cost price of invoice that is source of discount
2470  if ($remise->fk_facture_source > 0) {
2471  $srcinvoice = new Facture($this->db);
2472  $srcinvoice->fetch($remise->fk_facture_source);
2473  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2474  $formmargin = new FormMargin($this->db);
2475  $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2476  $facligne->pa_ht = $arraytmp['pa_total'];
2477  }
2478 
2479  $facligne->total_ht = -$remise->amount_ht;
2480  $facligne->total_tva = -$remise->amount_tva;
2481  $facligne->total_ttc = -$remise->amount_ttc;
2482 
2483  $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2484  $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2485  $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2486  $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2487 
2488  $lineid = $facligne->insert();
2489  if ($lineid > 0) {
2490  $result = $this->update_price(1);
2491  if ($result > 0) {
2492  // Create link between discount and invoice line
2493  $result = $remise->link_to_invoice($lineid, 0);
2494  if ($result < 0) {
2495  $this->error = $remise->error;
2496  $this->db->rollback();
2497  return -4;
2498  }
2499 
2500  $this->db->commit();
2501  return 1;
2502  } else {
2503  $this->error = $facligne->error;
2504  $this->db->rollback();
2505  return -1;
2506  }
2507  } else {
2508  $this->error = $facligne->error;
2509  $this->db->rollback();
2510  return -2;
2511  }
2512  } else {
2513  $this->db->rollback();
2514  return -3;
2515  }
2516  }
2517 
2518  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2526  public function set_ref_client($ref_client, $notrigger = 0)
2527  {
2528  // phpcs:enable
2529  global $user;
2530 
2531  $error = 0;
2532 
2533  $this->db->begin();
2534 
2535  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2536  if (empty($ref_client)) {
2537  $sql .= ' SET ref_client = NULL';
2538  } else {
2539  $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
2540  }
2541  $sql .= " WHERE rowid = ".((int) $this->id);
2542 
2543  dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2544  $resql = $this->db->query($sql);
2545  if (!$resql) {
2546  $this->errors[] = $this->db->error();
2547  $error++;
2548  }
2549 
2550  if (!$error) {
2551  $this->ref_client = $ref_client;
2552  }
2553 
2554  if (!$notrigger && empty($error)) {
2555  // Call trigger
2556  $result = $this->call_trigger('BILL_MODIFY', $user);
2557  if ($result < 0) {
2558  $error++;
2559  }
2560  // End call triggers
2561  }
2562 
2563  if (!$error) {
2564  $this->ref_client = $ref_client;
2565 
2566  $this->db->commit();
2567  return 1;
2568  } else {
2569  foreach ($this->errors as $errmsg) {
2570  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2571  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2572  }
2573  $this->db->rollback();
2574  return -1 * $error;
2575  }
2576  }
2577 
2586  public function delete($user, $notrigger = 0, $idwarehouse = -1)
2587  {
2588  global $langs, $conf;
2589  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2590 
2591  $rowid = $this->id;
2592 
2593  dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
2594 
2595  // Test to avoid invoice deletion (allowed if draft)
2596  $result = $this->is_erasable();
2597 
2598  if ($result <= 0) {
2599  return 0;
2600  }
2601 
2602  $error = 0;
2603 
2604  $this->db->begin();
2605 
2606  if (!$error && !$notrigger) {
2607  // Call trigger
2608  $result = $this->call_trigger('BILL_DELETE', $user);
2609  if ($result < 0) {
2610  $error++;
2611  }
2612  // End call triggers
2613  }
2614 
2615  // Removed extrafields
2616  if (!$error) {
2617  $result = $this->deleteExtraFields();
2618  if ($result < 0) {
2619  $error++;
2620  dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
2621  }
2622  }
2623 
2624  if (!$error) {
2625  // Delete linked object
2626  $res = $this->deleteObjectLinked();
2627  if ($res < 0) {
2628  $error++;
2629  }
2630  }
2631 
2632  if (!$error) {
2633  // If invoice was converted into a discount not yet consumed, we remove discount
2634  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
2635  $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
2636  $sql .= ' AND fk_facture_line IS NULL';
2637  $resql = $this->db->query($sql);
2638 
2639  // If invoice has consumed discounts
2640  $this->fetch_lines();
2641  $list_rowid_det = array();
2642  foreach ($this->lines as $key => $invoiceline) {
2643  $list_rowid_det[] = $invoiceline->id;
2644  }
2645 
2646  // Consumed discounts are freed
2647  if (count($list_rowid_det)) {
2648  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2649  $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
2650  $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(join(',', $list_rowid_det)).')';
2651 
2652  if (!$this->db->query($sql)) {
2653  $this->error = $this->db->error()." sql=".$sql;
2654  $this->errors[] = $this->error;
2655  $this->db->rollback();
2656  return -5;
2657  }
2658  }
2659 
2660  // Remove other links to the deleted invoice
2661 
2662  $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
2663  $sql .= ' SET fk_invoice = NULL';
2664  $sql .= ' WHERE fk_invoice = '.((int) $rowid);
2665 
2666  if (!$this->db->query($sql)) {
2667  $this->error = $this->db->error()." sql=".$sql;
2668  $this->errors[] = $this->error;
2669  $this->db->rollback();
2670  return -5;
2671  }
2672 
2673  $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time';
2674  $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
2675  $sql .= ' WHERE invoice_id = '.((int) $rowid);
2676 
2677  if (!$this->db->query($sql)) {
2678  $this->error = $this->db->error()." sql=".$sql;
2679  $this->errors[] = $this->error;
2680  $this->db->rollback();
2681  return -5;
2682  }
2683 
2684  // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
2685  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2686  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2687  $langs->load("agenda");
2688 
2689  $num = count($this->lines);
2690  for ($i = 0; $i < $num; $i++) {
2691  if ($this->lines[$i]->fk_product > 0) {
2692  $mouvP = new MouvementStock($this->db);
2693  $mouvP->origin = &$this;
2694  $mouvP->setOrigin($this->element, $this->id);
2695  // We decrease stock for product
2696  if ($this->type == self::TYPE_CREDIT_NOTE) {
2697  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
2698  } else {
2699  $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
2700  }
2701  }
2702  }
2703  }
2704 
2705  // Invoice line extrafileds
2706  $main = MAIN_DB_PREFIX.'facturedet';
2707  $ef = $main."_extrafields";
2708  $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
2709  // Delete invoice line
2710  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
2711 
2712  if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact()) {
2713  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
2714 
2715  $resql = $this->db->query($sql);
2716  if ($resql) {
2717  // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2718  $this->deleteEcmFiles();
2719 
2720  // On efface le repertoire de pdf provisoire
2721  $ref = dol_sanitizeFileName($this->ref);
2722  if ($conf->facture->dir_output && !empty($this->ref)) {
2723  $dir = $conf->facture->dir_output."/".$ref;
2724  $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
2725  if (file_exists($file)) { // We must delete all files before deleting directory
2726  $ret = dol_delete_preview($this);
2727 
2728  if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2729  $langs->load("errors");
2730  $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
2731  $this->errors[] = $this->error;
2732  $this->db->rollback();
2733  return 0;
2734  }
2735  }
2736  if (file_exists($dir)) {
2737  if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
2738  $langs->load("errors");
2739  $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
2740  $this->errors[] = $this->error;
2741  $this->db->rollback();
2742  return 0;
2743  }
2744  }
2745  }
2746 
2747  $this->db->commit();
2748  return 1;
2749  } else {
2750  $this->error = $this->db->lasterror()." sql=".$sql;
2751  $this->errors[] = $this->error;
2752  $this->db->rollback();
2753  return -6;
2754  }
2755  } else {
2756  $this->error = $this->db->lasterror()." sql=".$sql;
2757  $this->errors[] = $this->error;
2758  $this->db->rollback();
2759  return -4;
2760  }
2761  } else {
2762  $this->db->rollback();
2763  return -2;
2764  }
2765  }
2766 
2767  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2779  public function set_paid($user, $close_code = '', $close_note = '')
2780  {
2781  // phpcs:enable
2782  dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2783  return $this->setPaid($user, $close_code, $close_note);
2784  }
2785 
2795  public function setPaid($user, $close_code = '', $close_note = '')
2796  {
2797  $error = 0;
2798 
2799  if ($this->paye != 1) {
2800  $this->db->begin();
2801 
2802  $now = dol_now();
2803 
2804  dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
2805 
2806  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2807  $sql .= ' fk_statut='.self::STATUS_CLOSED;
2808  if (!$close_code) {
2809  $sql .= ', paye=1';
2810  }
2811  if ($close_code) {
2812  $sql .= ", close_code='".$this->db->escape($close_code)."'";
2813  }
2814  if ($close_note) {
2815  $sql .= ", close_note='".$this->db->escape($close_note)."'";
2816  }
2817  $sql .= ', fk_user_closing = '.((int) $user->id);
2818  $sql .= ", date_closing = '".$this->db->idate($now)."'";
2819  $sql .= " WHERE rowid = ".((int) $this->id);
2820 
2821  $resql = $this->db->query($sql);
2822  if ($resql) {
2823  // Call trigger
2824  $result = $this->call_trigger('BILL_PAYED', $user);
2825  if ($result < 0) {
2826  $error++;
2827  }
2828  // End call triggers
2829  } else {
2830  $error++;
2831  $this->error = $this->db->lasterror();
2832  }
2833 
2834  if (!$error) {
2835  $this->db->commit();
2836  return 1;
2837  } else {
2838  $this->db->rollback();
2839  return -1;
2840  }
2841  } else {
2842  return 0;
2843  }
2844  }
2845 
2846 
2847  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2858  public function set_unpaid($user)
2859  {
2860  // phpcs:enable
2861  dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2862  return $this->setUnpaid($user);
2863  }
2864 
2873  public function setUnpaid($user)
2874  {
2875  $error = 0;
2876 
2877  $this->db->begin();
2878 
2879  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2880  $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
2881  $sql .= ' date_closing=null,';
2882  $sql .= ' fk_user_closing=null';
2883  $sql .= " WHERE rowid = ".((int) $this->id);
2884 
2885  dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
2886  $resql = $this->db->query($sql);
2887  if ($resql) {
2888  // Call trigger
2889  $result = $this->call_trigger('BILL_UNPAYED', $user);
2890  if ($result < 0) {
2891  $error++;
2892  }
2893  // End call triggers
2894  } else {
2895  $error++;
2896  $this->error = $this->db->error();
2897  dol_print_error($this->db);
2898  }
2899 
2900  if (!$error) {
2901  $this->db->commit();
2902  return 1;
2903  } else {
2904  $this->db->rollback();
2905  return -1;
2906  }
2907  }
2908 
2909 
2910  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2923  public function set_canceled($user, $close_code = '', $close_note = '')
2924  {
2925  // phpcs:enable
2926  dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2927  return $this->setCanceled($user, $close_code, $close_note);
2928  }
2929 
2940  public function setCanceled($user, $close_code = '', $close_note = '')
2941  {
2942  dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
2943 
2944  $this->db->begin();
2945 
2946  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2947  $sql .= ' fk_statut='.self::STATUS_ABANDONED;
2948  if ($close_code) {
2949  $sql .= ", close_code='".$this->db->escape($close_code)."'";
2950  }
2951  if ($close_note) {
2952  $sql .= ", close_note='".$this->db->escape($close_note)."'";
2953  }
2954  $sql .= " WHERE rowid = ".((int) $this->id);
2955 
2956  $resql = $this->db->query($sql);
2957  if ($resql) {
2958  // Bound discounts are deducted from the invoice
2959  // as they have not been used since the invoice is abandoned.
2960  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2961  $sql .= ' SET fk_facture = NULL';
2962  $sql .= ' WHERE fk_facture = '.((int) $this->id);
2963 
2964  $resql = $this->db->query($sql);
2965  if ($resql) {
2966  // Call trigger
2967  $result = $this->call_trigger('BILL_CANCEL', $user);
2968  if ($result < 0) {
2969  $this->db->rollback();
2970  return -1;
2971  }
2972  // End call triggers
2973 
2974  $this->db->commit();
2975  return 1;
2976  } else {
2977  $this->error = $this->db->error()." sql=".$sql;
2978  $this->db->rollback();
2979  return -1;
2980  }
2981  } else {
2982  $this->error = $this->db->error()." sql=".$sql;
2983  $this->db->rollback();
2984  return -2;
2985  }
2986  }
2987 
2999  public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3000  {
3001  global $conf, $langs, $mysoc;
3002  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3003 
3004  $productStatic = null;
3005  $warehouseStatic = null;
3006  if ($batch_rule > 0) {
3007  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3008  require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3009  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3010  $productStatic = new Product($this->db);
3011  $warehouseStatic = new Entrepot($this->db);
3012  $productbatch = new ProductBatch($this->db);
3013  }
3014 
3015  $now = dol_now();
3016 
3017  $error = 0;
3018  dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3019 
3020  // Force to have object complete for checks
3021  $this->fetch_thirdparty();
3022  $this->fetch_lines();
3023 
3024  // Check parameters
3025  if ($this->statut != self::STATUS_DRAFT) {
3026  dol_syslog(get_class($this)."::validate status is not draft. operation canceled.", LOG_WARNING);
3027  return 0;
3028  }
3029  if (count($this->lines) <= 0) {
3030  $langs->load("errors");
3031  $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3032  return -1;
3033  }
3034  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3035  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3036  $this->error = 'Permission denied';
3037  dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3038  return -1;
3039  }
3040  if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3041  $last_of_type = $this->willBeLastOfSameType(true);
3042  if (!$last_of_type[0]) {
3043  $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3044  return -1;
3045  }
3046  }
3047 
3048  // Check for mandatory fields in thirdparty (defined into setup)
3049  if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3050  $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_CUSTOMER');
3051  foreach ($array_to_check as $key) {
3052  $keymin = strtolower($key);
3053  if (!property_exists($this->thirdparty, $keymin)) {
3054  continue;
3055  }
3056  $vallabel = $this->thirdparty->$keymin;
3057 
3058  $i = (int) preg_replace('/[^0-9]/', '', $key);
3059  if ($i > 0) {
3060  if ($this->thirdparty->isACompany()) {
3061  // Check for mandatory prof id (but only if country is other than ours)
3062  if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3063  $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3064  if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3065  $langs->load("errors");
3066  $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3067  dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3068  return -1;
3069  }
3070  }
3071  }
3072  } else {
3073  if ($key == 'EMAIL') {
3074  // Check for mandatory
3075  if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3076  $langs->load("errors");
3077  $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3078  dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3079  return -1;
3080  }
3081  }
3082  if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3083  // Check for mandatory
3084  if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3085  $langs->load("errors");
3086  $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3087  dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3088  return -1;
3089  }
3090  }
3091  }
3092  }
3093  }
3094 
3095  // Check for mandatory fields in $this
3096  $array_to_check = array('REF_CLIENT'=>'RefCustomer');
3097  foreach ($array_to_check as $key => $val) {
3098  $keymin = strtolower($key);
3099  $vallabel = $this->$keymin;
3100 
3101  // Check for mandatory
3102  $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3103  if (!$vallabel && !empty($conf->global->$keymandatory)) {
3104  $langs->load("errors");
3105  $error++;
3106  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null, 'errors');
3107  }
3108  }
3109 
3110  $this->db->begin();
3111 
3112  // Check parameters
3113  if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3114  // Check that source invoice is known
3115  if ($this->fk_facture_source <= 0) {
3116  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3117  $this->db->rollback();
3118  return -10;
3119  }
3120 
3121  // Load source invoice that has been replaced
3122  $facreplaced = new Facture($this->db);
3123  $result = $facreplaced->fetch($this->fk_facture_source);
3124  if ($result <= 0) {
3125  $this->error = $langs->trans("ErrorBadInvoice");
3126  $this->db->rollback();
3127  return -11;
3128  }
3129 
3130  // Check that source invoice not already replaced by another one.
3131  $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3132  if ($idreplacement && $idreplacement != $this->id) {
3133  $facreplacement = new Facture($this->db);
3134  $facreplacement->fetch($idreplacement);
3135  $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3136  $this->db->rollback();
3137  return -12;
3138  }
3139 
3140  $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3141  if ($result < 0) {
3142  $this->error = $facreplaced->error;
3143  $this->db->rollback();
3144  return -13;
3145  }
3146  }
3147 
3148  // Define new ref
3149  if ($force_number) {
3150  $num = $force_number;
3151  } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3152  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
3153  $this->date = dol_now();
3154  $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3155  }
3156  $num = $this->getNextNumRef($this->thirdparty);
3157  } else {
3158  $num = $this->ref;
3159  }
3160 
3161  $this->newref = dol_sanitizeFileName($num);
3162 
3163  if ($num) {
3164  $this->update_price(1);
3165 
3166  // Validate
3167  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3168  $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)."'";
3169  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
3170  $sql .= ", datef='".$this->db->idate($this->date)."'";
3171  $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3172  }
3173  $sql .= " WHERE rowid = ".((int) $this->id);
3174 
3175  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3176  $resql = $this->db->query($sql);
3177  if (!$resql) {
3178  dol_print_error($this->db);
3179  $error++;
3180  }
3181 
3182  // We check if the invoice was provisional
3183  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref))) {
3184  // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
3185  }
3186 
3187  if (!$error) {
3188  // Define third party as a customer
3189  $result = $this->thirdparty->set_as_client();
3190 
3191  // If active we decrement the main product and its components at invoice validation
3192  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3193  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3194  $langs->load("agenda");
3195 
3196  // Loop on each line
3197  $cpt = count($this->lines);
3198  for ($i = 0; $i < $cpt; $i++) {
3199  if ($this->lines[$i]->fk_product > 0) {
3200  $mouvP = new MouvementStock($this->db);
3201  $mouvP->origin = &$this;
3202  $mouvP->setOrigin($this->element, $this->id);
3203  // We decrease stock for product
3204  if ($this->type == self::TYPE_CREDIT_NOTE) {
3205  $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num));
3206  if ($result < 0) {
3207  $error++;
3208  $this->error = $mouvP->error;
3209  }
3210  } else {
3211  $is_batch_line = false;
3212  if ($batch_rule > 0) {
3213  $productStatic->fetch($this->lines[$i]->fk_product);
3214  if ($productStatic->hasbatch()) {
3215  $is_batch_line = true;
3216  $product_qty_remain = $this->lines[$i]->qty;
3217 
3218  $sortfield = null;
3219  $sortorder = null;
3220  // find all batch order by sellby (DLC) and eatby dates (DLUO) first
3222  $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3223  $sortorder = 'ASC,ASC,ASC,ASC';
3224  }
3225 
3226  $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder);
3227  if (!is_array($resBatchList)) {
3228  $error++;
3229  $this->error = $this->db->lasterror();
3230  }
3231 
3232  if (!$error) {
3233  $batchList = $resBatchList;
3234  if (empty($batchList)) {
3235  $error++;
3236  $langs->load('errors');
3237  $warehouseStatic->fetch($idwarehouse);
3238  $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3239  dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3240  }
3241 
3242  foreach ($batchList as $batch) {
3243  if ($batch->qty <= 0) {
3244  continue; // try to decrement only batches have positive quantity first
3245  }
3246 
3247  // enough quantity in this batch
3248  if ($batch->qty >= $product_qty_remain) {
3249  $product_batch_qty = $product_qty_remain;
3250  } else {
3251  // not enough (take all in batch)
3252  $product_batch_qty = $batch->qty;
3253  }
3254  $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3255  if ($result < 0) {
3256  $error++;
3257  $this->error = $mouvP->error;
3258  break;
3259  }
3260 
3261  $product_qty_remain -= $product_batch_qty;
3262  // all product quantity was decremented
3263  if ($product_qty_remain <= 0) {
3264  break;
3265  }
3266  }
3267 
3268  if (!$error && $product_qty_remain > 0) {
3269  if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3270  // take in the first batch
3271  $batch = $batchList[0];
3272  $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3273  if ($result < 0) {
3274  $error++;
3275  $this->error = $mouvP->error;
3276  }
3277  } else {
3278  $error++;
3279  $langs->load('errors');
3280  $warehouseStatic->fetch($idwarehouse);
3281  $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3282  dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3283  }
3284  }
3285  }
3286  }
3287  }
3288 
3289  if (!$is_batch_line) {
3290  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3291  if ($result < 0) {
3292  $error++;
3293  $this->error = $mouvP->error;
3294  }
3295  }
3296  }
3297  }
3298  }
3299  }
3300  }
3301 
3302  /*
3303  * 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%)
3304  * So we can continue to create new invoice situation
3305  */
3306  if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3307  $invoice_situation = new Facture($this->db);
3308  $result = $invoice_situation->fetch($this->fk_facture_source);
3309  if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3310  $invoice_situation->situation_final = 0;
3311  // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3312  $result = $invoice_situation->setFinal($user, 1);
3313  }
3314  if ($result < 0) {
3315  $this->error = $invoice_situation->error;
3316  $this->errors = $invoice_situation->errors;
3317  $error++;
3318  }
3319  }
3320 
3321  // Trigger calls
3322  if (!$error && !$notrigger) {
3323  // Call trigger
3324  $result = $this->call_trigger('BILL_VALIDATE', $user);
3325  if ($result < 0) {
3326  $error++;
3327  }
3328  // End call triggers
3329  }
3330 
3331  if (!$error) {
3332  $this->oldref = $this->ref;
3333 
3334  // Rename directory if dir was a temporary ref
3335  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
3336  // Now we rename also files into index
3337  $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)."'";
3338  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3339  $resql = $this->db->query($sql);
3340  if (!$resql) {
3341  $error++;
3342  $this->error = $this->db->lasterror();
3343  }
3344 
3345  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
3346  $oldref = dol_sanitizeFileName($this->ref);
3347  $newref = dol_sanitizeFileName($num);
3348  $dirsource = $conf->facture->dir_output.'/'.$oldref;
3349  $dirdest = $conf->facture->dir_output.'/'.$newref;
3350  if (!$error && file_exists($dirsource)) {
3351  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
3352 
3353  if (@rename($dirsource, $dirdest)) {
3354  dol_syslog("Rename ok");
3355  // Rename docs starting with $oldref with $newref
3356  $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
3357  foreach ($listoffiles as $fileentry) {
3358  $dirsource = $fileentry['name'];
3359  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
3360  $dirsource = $fileentry['path'].'/'.$dirsource;
3361  $dirdest = $fileentry['path'].'/'.$dirdest;
3362  @rename($dirsource, $dirdest);
3363  }
3364  }
3365  }
3366  }
3367  }
3368 
3369  if (!$error && !$this->is_last_in_cycle()) {
3370  if (!$this->updatePriceNextInvoice($langs)) {
3371  $error++;
3372  }
3373  }
3374 
3375  // Set new ref and define current status
3376  if (!$error) {
3377  $this->ref = $num;
3378  $this->ref = $num;
3379  $this->statut = self::STATUS_VALIDATED;
3380  $this->status = self::STATUS_VALIDATED;
3381  $this->brouillon = 0;
3382  $this->date_validation = $now;
3383  $i = 0;
3384 
3385  if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3386  $final = true;
3387  $nboflines = count($this->lines);
3388  while (($i < $nboflines) && $final) {
3389  $final = ($this->lines[$i]->situation_percent == 100);
3390  $i++;
3391  }
3392 
3393  if (empty($final)) {
3394  $this->situation_final = 0;
3395  } else {
3396  $this->situation_final = 1;
3397  }
3398 
3399  $this->setFinal($user);
3400  }
3401  }
3402  } else {
3403  $error++;
3404  }
3405 
3406  if (!$error) {
3407  $this->db->commit();
3408  return 1;
3409  } else {
3410  $this->db->rollback();
3411  return -1;
3412  }
3413  }
3414 
3421  public function updatePriceNextInvoice(&$langs)
3422  {
3423  foreach ($this->tab_next_situation_invoice as $next_invoice) {
3424  $is_last = $next_invoice->is_last_in_cycle();
3425 
3426  if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3427  $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3428  return false;
3429  }
3430 
3431  $next_invoice->brouillon = 1;
3432 
3433  foreach ($next_invoice->lines as $line) {
3434  $result = $next_invoice->updateline(
3435  $line->id,
3436  $line->desc,
3437  $line->subprice,
3438  $line->qty,
3439  $line->remise_percent,
3440  $line->date_start,
3441  $line->date_end,
3442  $line->tva_tx,
3443  $line->localtax1_tx,
3444  $line->localtax2_tx,
3445  'HT',
3446  $line->info_bits,
3447  $line->product_type,
3448  $line->fk_parent_line,
3449  0,
3450  $line->fk_fournprice,
3451  $line->pa_ht,
3452  $line->label,
3453  $line->special_code,
3454  $line->array_options,
3455  $line->situation_percent,
3456  $line->fk_unit
3457  );
3458 
3459  if ($result < 0) {
3460  $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3461  return false;
3462  }
3463  }
3464 
3465  break; // Only the next invoice and not each next invoice
3466  }
3467 
3468  return true;
3469  }
3470 
3478  public function setDraft($user, $idwarehouse = -1)
3479  {
3480  // phpcs:enable
3481  global $conf, $langs;
3482 
3483  $error = 0;
3484 
3485  if ($this->statut == self::STATUS_DRAFT) {
3486  dol_syslog(__METHOD__." already draft status", LOG_WARNING);
3487  return 0;
3488  }
3489 
3490  dol_syslog(__METHOD__, LOG_DEBUG);
3491 
3492  $this->db->begin();
3493 
3494  $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3495  $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
3496  $sql .= " WHERE rowid = ".((int) $this->id);
3497 
3498  $result = $this->db->query($sql);
3499  if ($result) {
3500  if (!$error) {
3501  $this->oldcopy = clone $this;
3502  }
3503 
3504  // If we decrease stock on invoice validation, we increase back
3505  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3506  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3507  $langs->load("agenda");
3508 
3509  $num = count($this->lines);
3510  for ($i = 0; $i < $num; $i++) {
3511  if ($this->lines[$i]->fk_product > 0) {
3512  $mouvP = new MouvementStock($this->db);
3513  $mouvP->origin = &$this;
3514  $mouvP->setOrigin($this->element, $this->id);
3515  // We decrease stock for product
3516  if ($this->type == self::TYPE_CREDIT_NOTE) {
3517  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
3518  } else {
3519  $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
3520  }
3521  }
3522  }
3523  }
3524 
3525  if ($error == 0) {
3526  $old_statut = $this->statut;
3527  $this->brouillon = 1;
3528  $this->statut = self::STATUS_DRAFT;
3529  $this->status = self::STATUS_DRAFT;
3530 
3531  // Call trigger
3532  $result = $this->call_trigger('BILL_UNVALIDATE', $user);
3533  if ($result < 0) {
3534  $error++;
3535  $this->statut = $old_statut;
3536  $this->status = $old_statut;
3537  $this->brouillon = 0;
3538  }
3539  // End call triggers
3540  } else {
3541  $this->db->rollback();
3542  return -1;
3543  }
3544 
3545  if ($error == 0) {
3546  $this->db->commit();
3547  return 1;
3548  } else {
3549  $this->db->rollback();
3550  return -1;
3551  }
3552  } else {
3553  $this->error = $this->db->error();
3554  $this->db->rollback();
3555  return -1;
3556  }
3557  }
3558 
3559 
3601  public function addline(
3602  $desc,
3603  $pu_ht,
3604  $qty,
3605  $txtva,
3606  $txlocaltax1 = 0,
3607  $txlocaltax2 = 0,
3608  $fk_product = 0,
3609  $remise_percent = 0,
3610  $date_start = '',
3611  $date_end = '',
3612  $ventil = 0,
3613  $info_bits = 0,
3614  $fk_remise_except = '',
3615  $price_base_type = 'HT',
3616  $pu_ttc = 0,
3617  $type = 0,
3618  $rang = -1,
3619  $special_code = 0,
3620  $origin = '',
3621  $origin_id = 0,
3622  $fk_parent_line = 0,
3623  $fk_fournprice = null,
3624  $pa_ht = 0,
3625  $label = '',
3626  $array_options = 0,
3627  $situation_percent = 100,
3628  $fk_prev_id = 0,
3629  $fk_unit = null,
3630  $pu_ht_devise = 0,
3631  $ref_ext = '',
3632  $noupdateafterinsertline = 0
3633  ) {
3634  // Deprecation warning
3635  if ($label) {
3636  dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3637  //var_dump(debug_backtrace(false));exit;
3638  }
3639 
3640  global $mysoc, $conf, $langs;
3641 
3642  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);
3643 
3644  if ($this->statut == self::STATUS_DRAFT) {
3645  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3646 
3647  // Clean parameters
3648  if (empty($remise_percent)) {
3649  $remise_percent = 0;
3650  }
3651  if (empty($qty)) {
3652  $qty = 0;
3653  }
3654  if (empty($info_bits)) {
3655  $info_bits = 0;
3656  }
3657  if (empty($rang)) {
3658  $rang = 0;
3659  }
3660  if (empty($ventil)) {
3661  $ventil = 0;
3662  }
3663  if (empty($txtva)) {
3664  $txtva = 0;
3665  }
3666  if (empty($txlocaltax1)) {
3667  $txlocaltax1 = 0;
3668  }
3669  if (empty($txlocaltax2)) {
3670  $txlocaltax2 = 0;
3671  }
3672  if (empty($fk_parent_line) || $fk_parent_line < 0) {
3673  $fk_parent_line = 0;
3674  }
3675  if (empty($fk_prev_id)) {
3676  $fk_prev_id = 'null';
3677  }
3678  if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
3679  $situation_percent = 100;
3680  }
3681  if (empty($ref_ext)) {
3682  $ref_ext = '';
3683  }
3684 
3685  $remise_percent = price2num($remise_percent);
3686  $qty = price2num($qty);
3687  $pu_ht = price2num($pu_ht);
3688  $pu_ht_devise = price2num($pu_ht_devise);
3689  $pu_ttc = price2num($pu_ttc);
3690  $pa_ht = price2num($pa_ht);
3691  if (!preg_match('/\((.*)\)/', $txtva)) {
3692  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3693  }
3694  $txlocaltax1 = price2num($txlocaltax1);
3695  $txlocaltax2 = price2num($txlocaltax2);
3696 
3697  if ($price_base_type == 'HT') {
3698  $pu = $pu_ht;
3699  } else {
3700  $pu = $pu_ttc;
3701  }
3702 
3703  // Check parameters
3704  if ($type < 0) {
3705  return -1;
3706  }
3707 
3708  if ($date_start && $date_end && $date_start > $date_end) {
3709  $langs->load("errors");
3710  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3711  return -1;
3712  }
3713 
3714  $this->db->begin();
3715 
3716  $product_type = $type;
3717  if (!empty($fk_product) && $fk_product > 0) {
3718  $product = new Product($this->db);
3719  $result = $product->fetch($fk_product);
3720  $product_type = $product->type;
3721 
3722  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3723  $langs->load("errors");
3724  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3725  $this->db->rollback();
3726  return -3;
3727  }
3728  }
3729 
3730  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3731 
3732  // Clean vat code
3733  $reg = array();
3734  $vat_src_code = '';
3735  if (preg_match('/\((.*)\)/', $txtva, $reg)) {
3736  $vat_src_code = $reg[1];
3737  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
3738  }
3739 
3740  // Calcul du total TTC et de la TVA pour la ligne a partir de
3741  // qty, pu, remise_percent et txtva
3742  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3743  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3744 
3745  $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);
3746 
3747  $total_ht = $tabprice[0];
3748  $total_tva = $tabprice[1];
3749  $total_ttc = $tabprice[2];
3750  $total_localtax1 = $tabprice[9];
3751  $total_localtax2 = $tabprice[10];
3752  $pu_ht = $tabprice[3];
3753 
3754  // MultiCurrency
3755  $multicurrency_total_ht = $tabprice[16];
3756  $multicurrency_total_tva = $tabprice[17];
3757  $multicurrency_total_ttc = $tabprice[18];
3758  $pu_ht_devise = $tabprice[19];
3759 
3760  // Rank to use
3761  $ranktouse = $rang;
3762  if ($ranktouse == -1) {
3763  $rangmax = $this->line_max($fk_parent_line);
3764  $ranktouse = $rangmax + 1;
3765  }
3766 
3767  // Insert line
3768  $this->line = new FactureLigne($this->db);
3769 
3770  $this->line->context = $this->context;
3771 
3772  $this->line->fk_facture = $this->id;
3773  $this->line->label = $label; // deprecated
3774  $this->line->desc = $desc;
3775  $this->line->ref_ext = $ref_ext;
3776 
3777  $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
3778  $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
3779 
3780  $this->line->vat_src_code = $vat_src_code;
3781  $this->line->tva_tx = $txtva;
3782  $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3783  $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3784  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3785  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3786 
3787  $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
3788  $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
3789  $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
3790  $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
3791  $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
3792 
3793  $this->line->fk_product = $fk_product;
3794  $this->line->product_type = $product_type;
3795  $this->line->remise_percent = $remise_percent;
3796  $this->line->date_start = $date_start;
3797  $this->line->date_end = $date_end;
3798  $this->line->ventil = $ventil;
3799  $this->line->rang = $ranktouse;
3800  $this->line->info_bits = $info_bits;
3801  $this->line->fk_remise_except = $fk_remise_except;
3802 
3803  $this->line->special_code = $special_code;
3804  $this->line->fk_parent_line = $fk_parent_line;
3805  $this->line->origin = $origin;
3806  $this->line->origin_id = $origin_id;
3807  $this->line->situation_percent = $situation_percent;
3808  $this->line->fk_prev_id = $fk_prev_id;
3809  $this->line->fk_unit = $fk_unit;
3810 
3811  // infos marge
3812  $this->line->fk_fournprice = $fk_fournprice;
3813  $this->line->pa_ht = $pa_ht;
3814 
3815  // Multicurrency
3816  $this->line->fk_multicurrency = $this->fk_multicurrency;
3817  $this->line->multicurrency_code = $this->multicurrency_code;
3818  $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
3819 
3820  $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
3821  $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
3822  $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
3823 
3824  if (is_array($array_options) && count($array_options) > 0) {
3825  $this->line->array_options = $array_options;
3826  }
3827 
3828  $result = $this->line->insert();
3829  if ($result > 0) {
3830  // Reorder if child line
3831  if (!empty($fk_parent_line)) {
3832  $this->line_order(true, 'DESC');
3833  } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
3834  $linecount = count($this->lines);
3835  for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3836  $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
3837  }
3838  }
3839 
3840  // Mise a jour informations denormalisees au niveau de la facture meme
3841  if (empty($noupdateafterinsertline)) {
3842  $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.
3843  }
3844 
3845  if ($result > 0) {
3846  $this->db->commit();
3847  return $this->line->id;
3848  } else {
3849  $this->error = $this->db->lasterror();
3850  $this->db->rollback();
3851  return -1;
3852  }
3853  } else {
3854  $this->error = $this->line->error;
3855  $this->errors = $this->line->errors;
3856  $this->db->rollback();
3857  return -2;
3858  }
3859  } else {
3860  dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3861  return -3;
3862  }
3863  }
3864 
3896  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)
3897  {
3898  global $conf, $user;
3899  // Deprecation warning
3900  if ($label) {
3901  dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3902  }
3903 
3904  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3905 
3906  global $mysoc, $langs;
3907 
3908  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);
3909 
3910  if ($this->statut == self::STATUS_DRAFT) {
3911  if (!$this->is_last_in_cycle() && empty($this->error)) {
3912  if (!$this->checkProgressLine($rowid, $situation_percent)) {
3913  if (!$this->error) {
3914  $this->error = $langs->trans('invoiceLineProgressError');
3915  }
3916  return -3;
3917  }
3918  }
3919 
3920  if ($date_start && $date_end && $date_start > $date_end) {
3921  $langs->load("errors");
3922  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3923  return -1;
3924  }
3925 
3926  $this->db->begin();
3927 
3928  // Clean parameters
3929  if (empty($qty)) {
3930  $qty = 0;
3931  }
3932  if (empty($fk_parent_line) || $fk_parent_line < 0) {
3933  $fk_parent_line = 0;
3934  }
3935  if (empty($special_code) || $special_code == 3) {
3936  $special_code = 0;
3937  }
3938  if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
3939  $situation_percent = 100;
3940  }
3941  if (empty($ref_ext)) {
3942  $ref_ext = '';
3943  }
3944 
3945  $remise_percent = price2num($remise_percent);
3946  $qty = price2num($qty);
3947  $pu = price2num($pu);
3948  $pu_ht_devise = price2num($pu_ht_devise);
3949  $pa_ht = price2num($pa_ht);
3950  if (!preg_match('/\((.*)\)/', $txtva)) {
3951  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3952  }
3953  $txlocaltax1 = price2num($txlocaltax1);
3954  $txlocaltax2 = price2num($txlocaltax2);
3955 
3956  // Check parameters
3957  if ($type < 0) {
3958  return -1;
3959  }
3960 
3961  // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
3962  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3963  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3964 
3965  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3966 
3967  // Clean vat code
3968  $reg = array();
3969  $vat_src_code = '';
3970  if (preg_match('/\((.*)\)/', $txtva, $reg)) {
3971  $vat_src_code = $reg[1];
3972  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
3973  }
3974 
3975  $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);
3976 
3977  $total_ht = $tabprice[0];
3978  $total_tva = $tabprice[1];
3979  $total_ttc = $tabprice[2];
3980  $total_localtax1 = $tabprice[9];
3981  $total_localtax2 = $tabprice[10];
3982  $pu_ht = $tabprice[3];
3983  $pu_tva = $tabprice[4];
3984  $pu_ttc = $tabprice[5];
3985 
3986  // MultiCurrency
3987  $multicurrency_total_ht = $tabprice[16];
3988  $multicurrency_total_tva = $tabprice[17];
3989  $multicurrency_total_ttc = $tabprice[18];
3990  $pu_ht_devise = $tabprice[19];
3991 
3992  // Old properties: $price, $remise (deprecated)
3993  $price = $pu;
3994  $remise = 0;
3995  if ($remise_percent > 0) {
3996  $remise = round(($pu * $remise_percent / 100), 2);
3997  $price = ($pu - $remise);
3998  }
3999  $price = price2num($price);
4000 
4001  //Fetch current line from the database and then clone the object and set it in $oldline property
4002  $line = new FactureLigne($this->db);
4003  $line->fetch($rowid);
4004  $line->fetch_optionals();
4005 
4006  if (!empty($line->fk_product)) {
4007  $product = new Product($this->db);
4008  $result = $product->fetch($line->fk_product);
4009  $product_type = $product->type;
4010 
4011  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
4012  $langs->load("errors");
4013  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4014  $this->db->rollback();
4015  return -3;
4016  }
4017  }
4018 
4019  $staticline = clone $line;
4020 
4021  $line->oldline = $staticline;
4022  $this->line = $line;
4023  $this->line->context = $this->context;
4024  $this->line->rang = $rang;
4025 
4026  // Reorder if fk_parent_line change
4027  if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4028  $rangmax = $this->line_max($fk_parent_line);
4029  $this->line->rang = $rangmax + 1;
4030  }
4031 
4032  $this->line->id = $rowid;
4033  $this->line->rowid = $rowid;
4034  $this->line->label = $label;
4035  $this->line->desc = $desc;
4036  $this->line->ref_ext = $ref_ext;
4037  $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
4038 
4039  $this->line->vat_src_code = $vat_src_code;
4040  $this->line->tva_tx = $txtva;
4041  $this->line->localtax1_tx = $txlocaltax1;
4042  $this->line->localtax2_tx = $txlocaltax2;
4043  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
4044  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
4045 
4046  $this->line->remise_percent = $remise_percent;
4047  $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
4048  $this->line->date_start = $date_start;
4049  $this->line->date_end = $date_end;
4050  $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
4051  $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4052  $this->line->total_localtax1 = $total_localtax1;
4053  $this->line->total_localtax2 = $total_localtax2;
4054  $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4055  $this->line->info_bits = $info_bits;
4056  $this->line->special_code = $special_code;
4057  $this->line->product_type = $type;
4058  $this->line->fk_parent_line = $fk_parent_line;
4059  $this->line->skip_update_total = $skip_update_total;
4060  $this->line->situation_percent = $situation_percent;
4061  $this->line->fk_unit = $fk_unit;
4062 
4063  $this->line->fk_fournprice = $fk_fournprice;
4064  $this->line->pa_ht = $pa_ht;
4065 
4066  // Multicurrency
4067  $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
4068  $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
4069  $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4070  $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4071 
4072  if (is_array($array_options) && count($array_options) > 0) {
4073  // We replace values in this->line->array_options only for entries defined into $array_options
4074  foreach ($array_options as $key => $value) {
4075  $this->line->array_options[$key] = $array_options[$key];
4076  }
4077  }
4078 
4079  $result = $this->line->update($user, $notrigger);
4080  if ($result > 0) {
4081  // Reorder if child line
4082  if (!empty($fk_parent_line)) {
4083  $this->line_order(true, 'DESC');
4084  }
4085 
4086  // Mise a jour info denormalisees au niveau facture
4087  $this->update_price(1, 'auto');
4088  $this->db->commit();
4089  return $result;
4090  } else {
4091  $this->error = $this->line->error;
4092  $this->db->rollback();
4093  return -1;
4094  }
4095  } else {
4096  $this->error = "Invoice statut makes operation forbidden";
4097  return -2;
4098  }
4099  }
4100 
4108  public function checkProgressLine($idline, $situation_percent)
4109  {
4110  $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4111  INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4112  WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4113 
4114  $result = $this->db->query($sql);
4115  if (!$result) {
4116  $this->error = $this->db->error();
4117  return false;
4118  }
4119 
4120  $obj = $this->db->fetch_object($result);
4121 
4122  if ($obj === null) {
4123  return true;
4124  } else {
4125  return $situation_percent < $obj->situation_percent;
4126  }
4127  }
4128 
4129  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4138  public function update_percent($line, $percent, $update_price = true)
4139  {
4140  // phpcs:enable
4141  global $mysoc, $user;
4142 
4143  // Progress should never be changed for discount lines
4144  if (($line->info_bits & 2) == 2) {
4145  return;
4146  }
4147 
4148  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4149 
4150  // Cap percentages to 100
4151  if ($percent > 100) {
4152  $percent = 100;
4153  }
4154  $line->situation_percent = $percent;
4155  $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);
4156  $line->total_ht = $tabprice[0];
4157  $line->total_tva = $tabprice[1];
4158  $line->total_ttc = $tabprice[2];
4159  $line->total_localtax1 = $tabprice[9];
4160  $line->total_localtax2 = $tabprice[10];
4161  $line->multicurrency_total_ht = $tabprice[16];
4162  $line->multicurrency_total_tva = $tabprice[17];
4163  $line->multicurrency_total_ttc = $tabprice[18];
4164  $line->update($user);
4165 
4166  // sometimes it is better to not update price for each line, ie when updating situation on all lines
4167  if ($update_price) {
4168  $this->update_price(1);
4169  }
4170  }
4171 
4178  public function deleteline($rowid)
4179  {
4180  global $user;
4181 
4182  dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4183 
4184  if ($this->statut != self::STATUS_DRAFT) {
4185  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4186  return -1;
4187  }
4188 
4189  $this->db->begin();
4190 
4191  // Free discount linked to invoice line
4192  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
4193  $sql .= ' SET fk_facture_line = NULL';
4194  $sql .= ' WHERE fk_facture_line = '.((int) $rowid);
4195 
4196  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
4197  $result = $this->db->query($sql);
4198  if (!$result) {
4199  $this->error = $this->db->error();
4200  $this->db->rollback();
4201  return -1;
4202  }
4203 
4204  $line = new FactureLigne($this->db);
4205 
4206  $line->context = $this->context;
4207 
4208  // For triggers
4209  $result = $line->fetch($rowid);
4210  if (!($result > 0)) {
4211  dol_print_error($this->db, $line->error, $line->errors);
4212  }
4213 
4214  if ($line->delete($user) > 0) {
4215  $result = $this->update_price(1);
4216 
4217  if ($result > 0) {
4218  $this->db->commit();
4219  return 1;
4220  } else {
4221  $this->db->rollback();
4222  $this->error = $this->db->lasterror();
4223  return -1;
4224  }
4225  } else {
4226  $this->db->rollback();
4227  $this->error = $line->error;
4228  return -1;
4229  }
4230  }
4231 
4232  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4243  public function set_remise($user, $remise, $notrigger = 0)
4244  {
4245  // phpcs:enable
4246  dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4247  return $this->setDiscount($user, $remise, $notrigger);
4248  }
4249 
4258  public function setDiscount($user, $remise, $notrigger = 0)
4259  {
4260  // Clean parameters
4261  if (empty($remise)) {
4262  $remise = 0;
4263  }
4264 
4265  if ($user->rights->facture->creer) {
4266  $remise = price2num($remise, 2);
4267 
4268  $error = 0;
4269 
4270  $this->db->begin();
4271 
4272  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4273  $sql .= ' SET remise_percent = '.((float) $remise);
4274  $sql .= " WHERE rowid = ".((int) $this->id);
4275  $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4276 
4277  dol_syslog(__METHOD__, LOG_DEBUG);
4278  $resql = $this->db->query($sql);
4279  if (!$resql) {
4280  $this->errors[] = $this->db->error();
4281  $error++;
4282  }
4283 
4284  if (!$notrigger && empty($error)) {
4285  // Call trigger
4286  $result = $this->call_trigger('BILL_MODIFY', $user);
4287  if ($result < 0) {
4288  $error++;
4289  }
4290  // End call triggers
4291  }
4292 
4293  if (!$error) {
4294  $this->remise_percent = $remise;
4295  $this->update_price(1);
4296 
4297  $this->db->commit();
4298  return 1;
4299  } else {
4300  foreach ($this->errors as $errmsg) {
4301  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4302  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4303  }
4304  $this->db->rollback();
4305  return -1 * $error;
4306  }
4307  }
4308  }
4309 
4310 
4311  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4320  public function set_remise_absolue($user, $remise, $notrigger = 0)
4321  {
4322  // phpcs:enable
4323  if (empty($remise)) {
4324  $remise = 0;
4325  }
4326 
4327  if ($user->rights->facture->creer) {
4328  $error = 0;
4329 
4330  $this->db->begin();
4331 
4332  $remise = price2num($remise);
4333 
4334  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4335  $sql .= ' SET remise_absolue = '.((float) $remise);
4336  $sql .= " WHERE rowid = ".((int) $this->id);
4337  $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4338 
4339  dol_syslog(__METHOD__, LOG_DEBUG);
4340  $resql = $this->db->query($sql);
4341  if (!$resql) {
4342  $this->errors[] = $this->db->error();
4343  $error++;
4344  }
4345 
4346  if (!$error) {
4347  $this->oldcopy = clone $this;
4348  $this->remise_absolue = $remise;
4349  $this->update_price(1);
4350  }
4351 
4352  if (!$notrigger && empty($error)) {
4353  // Call trigger
4354  $result = $this->call_trigger('BILL_MODIFY', $user);
4355  if ($result < 0) {
4356  $error++;
4357  }
4358  // End call triggers
4359  }
4360 
4361  if (!$error) {
4362  $this->db->commit();
4363  return 1;
4364  } else {
4365  foreach ($this->errors as $errmsg) {
4366  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4367  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4368  }
4369  $this->db->rollback();
4370  return -1 * $error;
4371  }
4372  }
4373  }
4374 
4383  public function getNextNumRef($soc, $mode = 'next')
4384  {
4385  global $conf, $langs;
4386 
4387  if ($this->module_source == 'takepos') {
4388  $langs->load('cashdesk');
4389 
4390  $moduleName = 'takepos';
4391  $moduleSourceName = 'Takepos';
4392  $addonConstName = 'TAKEPOS_REF_ADDON';
4393 
4394  // Clean parameters (if not defined or using deprecated value)
4395  if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4396  $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
4397  }
4398 
4399  $addon = $conf->global->TAKEPOS_REF_ADDON;
4400  } else {
4401  $langs->load('bills');
4402 
4403  $moduleName = 'facture';
4404  $moduleSourceName = 'Invoice';
4405  $addonConstName = 'FACTURE_ADDON';
4406 
4407  // Clean parameters (if not defined or using deprecated value)
4408  if (empty($conf->global->FACTURE_ADDON)) {
4409  $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4410  } elseif ($conf->global->FACTURE_ADDON == 'terre') {
4411  $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4412  } elseif ($conf->global->FACTURE_ADDON == 'mercure') {
4413  $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
4414  }
4415 
4416  $addon = $conf->global->FACTURE_ADDON;
4417  }
4418 
4419  if (!empty($addon)) {
4420  dol_syslog("Call getNextNumRef with ".$addonConstName." = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
4421 
4422  $mybool = false;
4423 
4424  $file = $addon.'.php';
4425  $classname = $addon;
4426 
4427 
4428  // Include file with class
4429  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
4430  foreach ($dirmodels as $reldir) {
4431  $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
4432 
4433  // Load file with numbering class (if found)
4434  if (is_file($dir.$file) && is_readable($dir.$file)) {
4435  $mybool |= include_once $dir.$file;
4436  }
4437  }
4438 
4439  // For compatibility
4440  if (!$mybool) {
4441  $file = $addon.'/'.$addon.'.modules.php';
4442  $classname = 'mod_'.$moduleName.'_'.$addon;
4443  $classname = preg_replace('/\-.*$/', '', $classname);
4444  // Include file with class
4445  foreach ($conf->file->dol_document_root as $dirroot) {
4446  $dir = $dirroot.'/core/modules/'.$moduleName.'/';
4447 
4448  // Load file with numbering class (if found)
4449  if (is_file($dir.$file) && is_readable($dir.$file)) {
4450  $mybool |= include_once $dir.$file;
4451  }
4452  }
4453  }
4454 
4455  if (!$mybool) {
4456  dol_print_error('', 'Failed to include file '.$file);
4457  return '';
4458  }
4459 
4460  $obj = new $classname();
4461 
4462  $numref = $obj->getNextValue($soc, $this, $mode);
4463 
4464 
4469  if ($mode != 'last' && !$numref) {
4470  $this->error = $obj->error;
4471  return '';
4472  }
4473 
4474  return $numref;
4475  } else {
4476  $langs->load('errors');
4477  print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4478  return '';
4479  }
4480  }
4481 
4488  public function info($id)
4489  {
4490  $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4491  $sql .= ' date_closing as dateclosing,';
4492  $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
4493  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
4494  $sql .= ' WHERE c.rowid = '.((int) $id);
4495 
4496  $result = $this->db->query($sql);
4497  if ($result) {
4498  if ($this->db->num_rows($result)) {
4499  $obj = $this->db->fetch_object($result);
4500  $this->id = $obj->rowid;
4501  if ($obj->fk_user_author) {
4502  $cuser = new User($this->db);
4503  $cuser->fetch($obj->fk_user_author);
4504  $this->user_creation = $cuser;
4505  }
4506  if ($obj->fk_user_valid) {
4507  $vuser = new User($this->db);
4508  $vuser->fetch($obj->fk_user_valid);
4509  $this->user_validation = $vuser;
4510  }
4511  if ($obj->fk_user_closing) {
4512  $cluser = new User($this->db);
4513  $cluser->fetch($obj->fk_user_closing);
4514  $this->user_closing = $cluser;
4515  }
4516 
4517  $this->date_creation = $this->db->jdate($obj->datec);
4518  $this->date_modification = $this->db->jdate($obj->datem);
4519  $this->date_validation = $this->db->jdate($obj->datev);
4520  $this->date_closing = $this->db->jdate($obj->dateclosing);
4521  }
4522  $this->db->free($result);
4523  } else {
4524  dol_print_error($this->db);
4525  }
4526  }
4527 
4528 
4529  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4543  public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
4544  {
4545  // phpcs:enable
4546  global $conf, $user;
4547 
4548  $ga = array();
4549 
4550  $sql = "SELECT s.rowid, s.nom as name, s.client,";
4551  $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
4552  if (empty($user->rights->societe->client->voir) && !$socid) {
4553  $sql .= ", sc.fk_soc, sc.fk_user";
4554  }
4555  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
4556  if (empty($user->rights->societe->client->voir) && !$socid) {
4557  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
4558  }
4559  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4560  $sql .= " AND f.fk_soc = s.rowid";
4561  if (empty($user->rights->societe->client->voir) && !$socid) { //restriction
4562  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4563  }
4564  if ($socid) {
4565  $sql .= " AND s.rowid = ".((int) $socid);
4566  }
4567  if ($draft) {
4568  $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
4569  }
4570  if (is_object($excluser)) {
4571  $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
4572  }
4573  $sql .= $this->db->order($sortfield, $sortorder);
4574  $sql .= $this->db->plimit($limit, $offset);
4575 
4576  $result = $this->db->query($sql);
4577  if ($result) {
4578  $numc = $this->db->num_rows($result);
4579  if ($numc) {
4580  $i = 0;
4581  while ($i < $numc) {
4582  $obj = $this->db->fetch_object($result);
4583 
4584  if ($shortlist == 1) {
4585  $ga[$obj->fid] = $obj->ref;
4586  } elseif ($shortlist == 2) {
4587  $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
4588  } else {
4589  $ga[$i]['id'] = $obj->fid;
4590  $ga[$i]['ref'] = $obj->ref;
4591  $ga[$i]['name'] = $obj->name;
4592  }
4593  $i++;
4594  }
4595  }
4596  return $ga;
4597  } else {
4598  dol_print_error($this->db);
4599  return -1;
4600  }
4601  }
4602 
4603 
4604  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4613  public function list_replacable_invoices($socid = 0)
4614  {
4615  // phpcs:enable
4616  global $conf;
4617 
4618  $return = array();
4619 
4620  $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4621  $sql .= " ff.rowid as rowidnext";
4622  //$sql .= ", SUM(pf.amount) as alreadypaid";
4623  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4624  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4625  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
4626  $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
4627  $sql .= " AND f.entity IN (".getEntity('invoice').")";
4628  $sql .= " AND f.paye = 0"; // Not paid completely
4629  $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
4630  $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
4631  if ($socid > 0) {
4632  $sql .= " AND f.fk_soc = ".((int) $socid);
4633  }
4634  //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
4635  $sql .= " ORDER BY f.ref";
4636 
4637  dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
4638  $resql = $this->db->query($sql);
4639  if ($resql) {
4640  while ($obj = $this->db->fetch_object($resql)) {
4641  $return[$obj->rowid] = array(
4642  'id' => $obj->rowid,
4643  'ref' => $obj->ref,
4644  'status' => $obj->status,
4645  'paid' => $obj->paid,
4646  'alreadypaid' => 0
4647  );
4648  }
4649  //print_r($return);
4650  return $return;
4651  } else {
4652  $this->error = $this->db->error();
4653  return -1;
4654  }
4655  }
4656 
4657 
4658  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4667  public function list_qualified_avoir_invoices($socid = 0)
4668  {
4669  // phpcs:enable
4670  global $conf;
4671 
4672  $return = array();
4673 
4674 
4675  $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4676  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4677  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4678  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
4679  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4680  $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4681  // $sql.= " WHERE f.fk_statut >= 1";
4682  // $sql.= " AND (f.paye = 1"; // Classee payee completement
4683  // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
4684  $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
4685  $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
4686 
4687  if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4688  // Keep invoices that are not situation invoices or that are the last in serie if it is a situation invoice
4689  $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
4690  $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID becasue of the group by later
4691  $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
4692  $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
4693  $sql .= " AND fs.type = ".self::TYPE_SITUATION;
4694  $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4695  if ($socid > 0) {
4696  $sql .= " AND fs.fk_soc = ".((int) $socid);
4697  }
4698  $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
4699  $sql .= ")";
4700  } else {
4701  $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
4702  }
4703 
4704  if ($socid > 0) {
4705  $sql .= " AND f.fk_soc = ".((int) $socid);
4706  }
4707  $sql .= " ORDER BY f.ref";
4708 
4709  dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
4710  $resql = $this->db->query($sql);
4711  if ($resql) {
4712  while ($obj = $this->db->fetch_object($resql)) {
4713  $qualified = 0;
4714  if ($obj->fk_statut == self::STATUS_VALIDATED) {
4715  $qualified = 1;
4716  }
4717  if ($obj->fk_statut == self::STATUS_CLOSED) {
4718  $qualified = 1;
4719  }
4720  if ($qualified) {
4721  //$ref=$obj->ref;
4722  $paymentornot = ($obj->fk_paiement ? 1 : 0);
4723  $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
4724  }
4725  }
4726 
4727  return $return;
4728  } else {
4729  $this->error = $this->db->error();
4730  return -1;
4731  }
4732  }
4733 
4734 
4735  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4742  public function load_board($user)
4743  {
4744  // phpcs:enable
4745  global $conf, $langs;
4746 
4747  $clause = " WHERE";
4748 
4749  $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4750  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4751  if (empty($user->rights->societe->client->voir) && !$user->socid) {
4752  $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4753  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4754  $clause = " AND";
4755  }
4756  $sql .= $clause." f.paye=0";
4757  $sql .= " AND f.entity IN (".getEntity('invoice').")";
4758  $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
4759  if ($user->socid) {
4760  $sql .= " AND f.fk_soc = ".((int) $user->socid);
4761  }
4762 
4763  $resql = $this->db->query($sql);
4764  if ($resql) {
4765  $langs->load("bills");
4766  $now = dol_now();
4767 
4768  $response = new WorkboardResponse();
4769  $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4770  $response->label = $langs->trans("CustomerBillsUnpaid");
4771  $response->labelShort = $langs->trans("Unpaid");
4772  $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4773  $response->img = img_object('', "bill");
4774 
4775  $generic_facture = new Facture($this->db);
4776 
4777  while ($obj = $this->db->fetch_object($resql)) {
4778  $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4779  $generic_facture->statut = $obj->fk_statut;
4780 
4781  $response->nbtodo++;
4782  $response->total += $obj->total_ht;
4783 
4784  if ($generic_facture->hasDelay()) {
4785  $response->nbtodolate++;
4786  $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4787  }
4788  }
4789 
4790  $this->db->free($resql);
4791  return $response;
4792  } else {
4793  dol_print_error($this->db);
4794  $this->error = $this->db->error();
4795  return -1;
4796  }
4797  }
4798 
4799 
4800  /* gestion des contacts d'une facture */
4801 
4807  public function getIdBillingContact()
4808  {
4809  return $this->getIdContact('external', 'BILLING');
4810  }
4811 
4817  public function getIdShippingContact()
4818  {
4819  return $this->getIdContact('external', 'SHIPPING');
4820  }
4821 
4822 
4831  public function initAsSpecimen($option = '')
4832  {
4833  global $conf, $langs, $user;
4834 
4835  $now = dol_now();
4836  $arraynow = dol_getdate($now);
4837  $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
4838 
4839  // Load array of products prodids
4840  $num_prods = 0;
4841  $prodids = array();
4842  $sql = "SELECT rowid";
4843  $sql .= " FROM ".MAIN_DB_PREFIX."product";
4844  $sql .= " WHERE entity IN (".getEntity('product').")";
4845  $sql .= $this->db->plimit(100);
4846 
4847  $resql = $this->db->query($sql);
4848  if ($resql) {
4849  $num_prods = $this->db->num_rows($resql);
4850  $i = 0;
4851  while ($i < $num_prods) {
4852  $i++;
4853  $row = $this->db->fetch_row($resql);
4854  $prodids[$i] = $row[0];
4855  }
4856  }
4857  //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
4858  if (empty($num_prods)) {
4859  $num_prods = 1;
4860  }
4861 
4862  // Initialize parameters
4863  $this->id = 0;
4864  $this->entity = 1;
4865  $this->ref = 'SPECIMEN';
4866  $this->specimen = 1;
4867  $this->socid = 1;
4868  $this->date = $nownotime;
4869  $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4870  $this->cond_reglement_id = 1;
4871  $this->cond_reglement_code = 'RECEP';
4872  $this->date_lim_reglement = $this->calculate_date_lim_reglement();
4873  $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
4874  $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
4875 
4876  $this->note_public = 'This is a comment (public)';
4877  $this->note_private = 'This is a comment (private)';
4878  $this->note = 'This is a comment (private)';
4879 
4880  $this->fk_user_author = $user->id;
4881 
4882  $this->multicurrency_tx = 1;
4883  $this->multicurrency_code = $conf->currency;
4884 
4885  $this->fk_incoterms = 0;
4886  $this->location_incoterms = '';
4887 
4888  if (empty($option) || $option != 'nolines') {
4889  // Lines
4890  $nbp = 5;
4891  $xnbp = 0;
4892  while ($xnbp < $nbp) {
4893  $line = new FactureLigne($this->db);
4894  $line->desc = $langs->trans("Description")." ".$xnbp;
4895  $line->qty = 1;
4896  $line->subprice = 100;
4897  $line->tva_tx = 19.6;
4898  $line->localtax1_tx = 0;
4899  $line->localtax2_tx = 0;
4900  $line->remise_percent = 0;
4901  if ($xnbp == 1) { // Qty is negative (product line)
4902  $prodid = mt_rand(1, $num_prods);
4903  $line->fk_product = $prodids[$prodid];
4904  $line->qty = -1;
4905  $line->total_ht = -100;
4906  $line->total_ttc = -119.6;
4907  $line->total_tva = -19.6;
4908  $line->multicurrency_total_ht = -200;
4909  $line->multicurrency_total_ttc = -239.2;
4910  $line->multicurrency_total_tva = -39.2;
4911  } elseif ($xnbp == 2) { // UP is negative (free line)
4912  $line->subprice = -100;
4913  $line->total_ht = -100;
4914  $line->total_ttc = -119.6;
4915  $line->total_tva = -19.6;
4916  $line->remise_percent = 0;
4917  $line->multicurrency_total_ht = -200;
4918  $line->multicurrency_total_ttc = -239.2;
4919  $line->multicurrency_total_tva = -39.2;
4920  } elseif ($xnbp == 3) { // Discount is 50% (product line)
4921  $prodid = mt_rand(1, $num_prods);
4922  $line->fk_product = $prodids[$prodid];
4923  $line->total_ht = 50;
4924  $line->total_ttc = 59.8;
4925  $line->total_tva = 9.8;
4926  $line->multicurrency_total_ht = 100;
4927  $line->multicurrency_total_ttc = 119.6;
4928  $line->multicurrency_total_tva = 19.6;
4929  $line->remise_percent = 50;
4930  } else // (product line)
4931  {
4932  $prodid = mt_rand(1, $num_prods);
4933  $line->fk_product = $prodids[$prodid];
4934  $line->total_ht = 100;
4935  $line->total_ttc = 119.6;
4936  $line->total_tva = 19.6;
4937  $line->multicurrency_total_ht = 200;
4938  $line->multicurrency_total_ttc = 239.2;
4939  $line->multicurrency_total_tva = 39.2;
4940  $line->remise_percent = 0;
4941  }
4942 
4943  $this->lines[$xnbp] = $line;
4944 
4945 
4946  $this->total_ht += $line->total_ht;
4947  $this->total_tva += $line->total_tva;
4948  $this->total_ttc += $line->total_ttc;
4949 
4950  $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4951  $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4952  $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4953 
4954  $xnbp++;
4955  }
4956  $this->revenuestamp = 0;
4957 
4958  // Add a line "offered"
4959  $line = new FactureLigne($this->db);
4960  $line->desc = $langs->trans("Description")." (offered line)";
4961  $line->qty = 1;
4962  $line->subprice = 100;
4963  $line->tva_tx = 19.6;
4964  $line->localtax1_tx = 0;
4965  $line->localtax2_tx = 0;
4966  $line->remise_percent = 100;
4967  $line->total_ht = 0;
4968  $line->total_ttc = 0; // 90 * 1.196
4969  $line->total_tva = 0;
4970  $line->multicurrency_total_ht = 0;
4971  $line->multicurrency_total_ttc = 0;
4972  $line->multicurrency_total_tva = 0;
4973  $prodid = mt_rand(1, $num_prods);
4974  $line->fk_product = $prodids[$prodid];
4975 
4976  $this->lines[$xnbp] = $line;
4977  $xnbp++;
4978  }
4979  }
4980 
4981  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4987  public function load_state_board()
4988  {
4989  // phpcs:enable
4990  global $conf, $user;
4991 
4992  $this->nb = array();
4993 
4994  $clause = "WHERE";
4995 
4996  $sql = "SELECT count(f.rowid) as nb";
4997  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4998  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
4999  if (empty($user->rights->societe->client->voir) && !$user->socid) {
5000  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5001  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5002  $clause = "AND";
5003  }
5004  $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
5005 
5006  $resql = $this->db->query($sql);
5007  if ($resql) {
5008  while ($obj = $this->db->fetch_object($resql)) {
5009  $this->nb["invoices"] = $obj->nb;
5010  }
5011  $this->db->free($resql);
5012  return 1;
5013  } else {
5014  dol_print_error($this->db);
5015  $this->error = $this->db->error();
5016  return -1;
5017  }
5018  }
5019 
5025  public function getLinesArray()
5026  {
5027  return $this->fetch_lines();
5028  }
5029 
5041  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5042  {
5043  global $conf, $langs;
5044 
5045  $outputlangs->loadLangs(array("bills", "products"));
5046 
5047  if (!dol_strlen($modele)) {
5048  $modele = 'crabe';
5049  $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5050 
5051  if (!empty($this->model_pdf)) {
5052  $modele = $this->model_pdf;
5053  } elseif (!empty($this->modelpdf)) { // deprecated
5054  $modele = $this->modelpdf;
5055  } elseif (!empty($conf->global->$thisTypeConfName)) {
5056  $modele = $conf->global->$thisTypeConfName;
5057  } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5058  $modele = $conf->global->FACTURE_ADDON_PDF;
5059  }
5060  }
5061 
5062  $modelpath = "core/modules/facture/doc/";
5063 
5064  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5065  }
5066 
5072  public function newCycle()
5073  {
5074  $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f';
5075  $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5076  $resql = $this->db->query($sql);
5077  if ($resql) {
5078  if ($this->db->num_rows($resql) > 0) {
5079  $res = $this->db->fetch_array($resql);
5080  $ref = $res['max(situation_cycle_ref)'];
5081  $ref++;
5082  } else {
5083  $ref = 1;
5084  }
5085  $this->db->free($resql);
5086  return $ref;
5087  } else {
5088  $this->error = $this->db->lasterror();
5089  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5090  return -1;
5091  }
5092  }
5093 
5094  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5100  public function is_first()
5101  {
5102  // phpcs:enable
5103  return ($this->situation_counter == 1);
5104  }
5105 
5106  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5112  public function get_prev_sits()
5113  {
5114  // phpcs:enable
5115  global $conf;
5116 
5117  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5118  $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5119  $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5120  $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5121  $resql = $this->db->query($sql);
5122  $res = array();
5123  if ($resql && $this->db->num_rows($resql) > 0) {
5124  while ($row = $this->db->fetch_object($resql)) {
5125  $id = $row->rowid;
5126  $situation = new Facture($this->db);
5127  $situation->fetch($id);
5128  $res[] = $situation;
5129  }
5130  } else {
5131  $this->error = $this->db->error();
5132  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5133  return -1;
5134  }
5135 
5136  return $res;
5137  }
5138 
5146  public function setFinal(User $user, $notrigger = 0)
5147  {
5148  $error = 0;
5149 
5150  $this->db->begin();
5151 
5152  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5153 
5154  dol_syslog(__METHOD__, LOG_DEBUG);
5155  $resql = $this->db->query($sql);
5156  if (!$resql) {
5157  $this->errors[] = $this->db->error();
5158  $error++;
5159  }
5160 
5161  if (!$notrigger && empty($error)) {
5162  // Call trigger
5163  $result = $this->call_trigger('BILL_MODIFY', $user);
5164  if ($result < 0) {
5165  $error++;
5166  }
5167  // End call triggers
5168  }
5169 
5170  if (!$error) {
5171  $this->db->commit();
5172  return 1;
5173  } else {
5174  foreach ($this->errors as $errmsg) {
5175  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5176  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5177  }
5178  $this->db->rollback();
5179  return -1 * $error;
5180  }
5181  }
5182 
5183  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5189  public function is_last_in_cycle()
5190  {
5191  // phpcs:enable
5192  global $conf;
5193 
5194  if (!empty($this->situation_cycle_ref)) {
5195  // No point in testing anything if we're not inside a cycle
5196  $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5197  $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5198  $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5199  $resql = $this->db->query($sql);
5200 
5201  if ($resql && $this->db->num_rows($resql) > 0) {
5202  $res = $this->db->fetch_array($resql);
5203  $last = $res['max(situation_counter)'];
5204  return ($last == $this->situation_counter);
5205  } else {
5206  $this->error = $this->db->lasterror();
5207  dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5208  return false;
5209  }
5210  } else {
5211  return true;
5212  }
5213  }
5214 
5223  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
5224  {
5225  $tables = array(
5226  'facture'
5227  );
5228 
5229  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
5230  }
5231 
5240  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5241  {
5242  $tables = array(
5243  'facturedet'
5244  );
5245 
5246  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
5247  }
5248 
5254  public function hasDelay()
5255  {
5256  global $conf;
5257 
5258  $now = dol_now();
5259 
5260  // Paid invoices have status STATUS_CLOSED
5261  if ($this->statut != Facture::STATUS_VALIDATED) {
5262  return false;
5263  }
5264 
5265  $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5266  if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5267  $totalpaid = $this->getSommePaiement();
5268  $totalpaid = floatval($totalpaid);
5269  $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
5270  if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5271  if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5272  $hasDelay = 1;
5273  } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5274  $hasDelay = 1;
5275  } else {
5276  $hasDelay = 0;
5277  }
5278  }
5279  }
5280 
5281  return $hasDelay;
5282  }
5283 
5288  public function displayRetainedWarranty()
5289  {
5290  global $conf;
5291 
5292  // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
5293 
5294  // 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
5295 
5296  $displayWarranty = false;
5297  if (!empty($this->retained_warranty)) {
5298  $displayWarranty = true;
5299 
5300  if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
5301  // Check if this situation invoice is 100% for real
5302  $displayWarranty = false;
5303  if (!empty($this->situation_final)) {
5304  $displayWarranty = true;
5305  } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
5306  // $object->situation_final need validation to be done so this test is need for draft
5307  $displayWarranty = true;
5308 
5309  foreach ($this->lines as $i => $line) {
5310  if ($line->product_type < 2 && $line->situation_percent < 100) {
5311  $displayWarranty = false;
5312  break;
5313  }
5314  }
5315  }
5316  }
5317  }
5318 
5319  return $displayWarranty;
5320  }
5321 
5326  public function getRetainedWarrantyAmount($rounding = -1)
5327  {
5328  global $conf;
5329  if (empty($this->retained_warranty)) {
5330  return -1;
5331  }
5332 
5333  $retainedWarrantyAmount = 0;
5334 
5335  // Billed - retained warranty
5336  if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
5337  $displayWarranty = true;
5338  // Check if this situation invoice is 100% for real
5339  if (!empty($this->lines)) {
5340  foreach ($this->lines as $i => $line) {
5341  if ($line->product_type < 2 && $line->situation_percent < 100) {
5342  $displayWarranty = false;
5343  break;
5344  }
5345  }
5346  }
5347 
5348  if ($displayWarranty && !empty($this->situation_final)) {
5350  $TPreviousIncoice = $this->tab_previous_situation_invoice;
5351 
5352  $total2BillWT = 0;
5353  foreach ($TPreviousIncoice as &$fac) {
5354  $total2BillWT += $fac->total_ttc;
5355  }
5356  $total2BillWT += $this->total_ttc;
5357 
5358  $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5359  } else {
5360  return -1;
5361  }
5362  } else {
5363  // Because one day retained warranty could be used on standard invoices
5364  $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5365  }
5366 
5367  if ($rounding < 0) {
5368  $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5369  }
5370 
5371  if ($rounding > 0) {
5372  return round($retainedWarrantyAmount, $rounding);
5373  }
5374 
5375  return $retainedWarrantyAmount;
5376  }
5377 
5384  public function setRetainedWarranty($value)
5385  {
5386  dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
5387 
5388  if ($this->statut >= 0) {
5389  $fieldname = 'retained_warranty';
5390  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5391  $sql .= " SET ".$fieldname." = ".((float) $value);
5392  $sql .= ' WHERE rowid='.((int) $this->id);
5393 
5394  if ($this->db->query($sql)) {
5395  $this->retained_warranty = floatval($value);
5396  return 1;
5397  } else {
5398  dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
5399  $this->error = $this->db->error();
5400  return -1;
5401  }
5402  } else {
5403  dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
5404  $this->error = 'Status of the object is incompatible '.$this->statut;
5405  return -2;
5406  }
5407  }
5408 
5409 
5417  public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false)
5418  {
5419  if (!$timestamp && $dateYmd) {
5420  $timestamp = $this->db->jdate($dateYmd);
5421  }
5422 
5423 
5424  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
5425  if ($this->statut >= 0) {
5426  $fieldname = 'retained_warranty_date_limit';
5427  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5428  $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
5429  $sql .= ' WHERE rowid = '.((int) $this->id);
5430 
5431  if ($this->db->query($sql)) {
5432  $this->retained_warranty_date_limit = $timestamp;
5433  return 1;
5434  } else {
5435  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
5436  $this->error = $this->db->error();
5437  return -1;
5438  }
5439  } else {
5440  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5441  $this->error = 'Status of the object is incompatible '.$this->statut;
5442  return -2;
5443  }
5444  }
5445 
5446 
5456  public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '')
5457  {
5458  global $conf, $langs, $user;
5459 
5460  $error = 0;
5461  $this->output = '';
5462  $this->error = '';
5463  $nbMailSend = 0;
5464  $errorsMsg = array();
5465 
5466  $langs->load("bills");
5467 
5468  if (!isModEnabled('facture')) { // Should not happen. If module disabled, cron job should not be visible.
5469  $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5470  return 0;
5471  }
5472  /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
5473  $langs->load("bills");
5474  $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5475  return 0;
5476  }
5477  */
5478 
5479  require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5480  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
5481  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
5482  $formmail = new FormMail($this->db);
5483 
5484  $now = dol_now();
5485  $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
5486 
5487  $tmpinvoice = new Facture($this->db);
5488 
5489  dol_syslog(__METHOD__, LOG_DEBUG);
5490 
5491  // Select all action comm reminder
5492  $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
5493  if (!empty($paymentmode) && $paymentmode != 'all') {
5494  $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
5495  }
5496  $sql .= " WHERE f.paye = 0";
5497  $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
5498  $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
5499  $sql .= " AND f.entity IN (".getEntity('facture').")";
5500  if (!empty($paymentmode) && $paymentmode != 'all') {
5501  $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
5502  }
5503  // TODO Add filter to check there is no payment started
5504  $sql .= $this->db->order("date_lim_reglement", "ASC");
5505 
5506  $resql = $this->db->query($sql);
5507 
5508  $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
5509  $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
5510  if (!empty($paymentmode) && $paymentmode != 'all') {
5511  $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
5512  }
5513  $this->output .= '<br>';
5514 
5515  if ($resql) {
5516  while ($obj = $this->db->fetch_object($resql)) {
5517  if (!$error) {
5518  // Load event
5519  $res = $tmpinvoice->fetch($obj->id);
5520  if ($res > 0) {
5521  $tmpinvoice->fetch_thirdparty();
5522 
5523  $outputlangs = new Translate('', $conf);
5524  if ($tmpinvoice->thirdparty->default_lang) {
5525  $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5526  $outputlangs->loadLangs(array("main", "bills"));
5527  } else {
5528  $outputlangs = $langs;
5529  }
5530 
5531  // Select email template
5532  $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
5533  if (is_numeric($arraymessage) && $arraymessage <= 0) {
5534  $langs->load("errors");
5535  $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
5536  return 0;
5537  }
5538 
5539  // PREPARE EMAIL
5540  $errormesg = '';
5541 
5542  // Make substitution in email content
5543  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, '', $tmpinvoice);
5544 
5545  complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
5546 
5547  // Topic
5548  $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5549 
5550  // Content
5551  $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5552 
5553  $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
5554 
5555  // Recipient
5556  $to = '';
5557  $res = $tmpinvoice->fetch_thirdparty();
5558  $recipient = $tmpinvoice->thirdparty;
5559  if ($res > 0) {
5560  if (!empty($recipient->email)) {
5561  $to = $recipient->email;
5562  } else {
5563  $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for user.";
5564  $error++;
5565  }
5566  } else {
5567  $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5568  $error++;
5569  }
5570 
5571  // Sender
5572  $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
5573  if (empty($from)) {
5574  $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5575  $error++;
5576  }
5577 
5578  if (!$error && $to) {
5579  $this->db->begin();
5580 
5581  // Errors Recipient
5582  $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5583 
5584  $trackid = 'inv'.$tmpinvoice->id;
5585  $sendcontext = 'standard';
5586 
5587  //join file is asked
5588  $joinFile = [];
5589  $joinFileName = [];
5590  $joinFileMime = [];
5591  if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5592  $joinFile[] = DOL_DATA_ROOT.$tmpinvoice->last_main_doc;
5593  $joinFileName[] = basename($tmpinvoice->last_main_doc);
5594  $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.$tmpinvoice->last_main_doc);
5595  }
5596 
5597  // Mail Creation
5598  $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, '', "", 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
5599 
5600  // Sending Mail
5601  if ($cMailFile->sendfile()) {
5602  $nbMailSend++;
5603 
5604  // Add a line into event table
5605  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5606 
5607  // Insert record of emails sent
5608  $actioncomm = new ActionComm($this->db);
5609 
5610  $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5611  $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5612  $actioncomm->contact_id = 0;
5613 
5614  $actioncomm->code = 'AC_EMAIL';
5615  $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK';
5616  $actioncomm->note_private = $sendContent;
5617  $actioncomm->fk_project = $tmpinvoice->fk_project;
5618  $actioncomm->datep = dol_now();
5619  $actioncomm->datef = $actioncomm->datep;
5620  $actioncomm->percentage = -1; // Not applicable
5621  $actioncomm->authorid = $user->id; // User saving action
5622  $actioncomm->userownerid = $user->id; // Owner of action
5623  // Fields when action is an email (content should be added into note)
5624  $actioncomm->email_msgid = $cMailFile->msgid;
5625  $actioncomm->email_from = $from;
5626  $actioncomm->email_sender = '';
5627  $actioncomm->email_to = $to;
5628  //$actioncomm->email_tocc = $sendtocc;
5629  //$actioncomm->email_tobcc = $sendtobcc;
5630  //$actioncomm->email_subject = $subject;
5631  $actioncomm->errors_to = $errors_to;
5632 
5633  //$actioncomm->extraparams = $extraparams;
5634 
5635  $actioncomm->create($user);
5636  } else {
5637  $errormesg = $cMailFile->error.' : '.$to;
5638  $error++;
5639 
5640  // Add a line into event table
5641  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5642 
5643  // Insert record of emails sent
5644  $actioncomm = new ActionComm($this->db);
5645 
5646  $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5647  $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5648  $actioncomm->contact_id = 0;
5649 
5650  $actioncomm->code = 'AC_EMAIL';
5651  $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
5652  $actioncomm->note_private = $errormesg;
5653  $actioncomm->fk_project = $tmpinvoice->fk_project;
5654  $actioncomm->datep = dol_now();
5655  $actioncomm->datef = $actioncomm->datep;
5656  $actioncomm->percentage = -1; // Not applicable
5657  $actioncomm->authorid = $user->id; // User saving action
5658  $actioncomm->userownerid = $user->id; // Owner of action
5659  // Fields when action is an email (content should be added into note)
5660  $actioncomm->email_msgid = $cMailFile->msgid;
5661  $actioncomm->email_from = $from;
5662  $actioncomm->email_sender = '';
5663  $actioncomm->email_to = $to;
5664  //$actioncomm->email_tocc = $sendtocc;
5665  //$actioncomm->email_tobcc = $sendtobcc;
5666  //$actioncomm->email_subject = $subject;
5667  $actioncomm->errors_to = $errors_to;
5668 
5669  //$actioncomm->extraparams = $extraparams;
5670 
5671  $actioncomm->create($user);
5672  }
5673 
5674  $this->db->commit(); // We always commit
5675  }
5676 
5677  if ($errormesg) {
5678  $errorsMsg[] = $errormesg;
5679  }
5680  } else {
5681  $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
5682  $error++;
5683  }
5684  }
5685  }
5686  } else {
5687  $error++;
5688  }
5689 
5690  if (!$error) {
5691  $this->output .= 'Nb of emails sent : '.$nbMailSend;
5692  return 0;
5693  } else {
5694  $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
5695  return $error;
5696  }
5697  }
5698 
5705  public function willBeLastOfSameType($allow_validated_drafts = false)
5706  {
5707  // get date of last validated invoices of same type
5708  $sql = "SELECT datef";
5709  $sql .= " FROM ".MAIN_DB_PREFIX."facture";
5710  $sql .= " WHERE type = " . (int) $this->type ;
5711  $sql .= " AND date_valid IS NOT NULL";
5712  $sql .= " ORDER BY datef DESC LIMIT 1";
5713 
5714  $result = $this->db->query($sql);
5715  if ($result) {
5716  // compare with current validation date
5717  if ($this->db->num_rows($result)) {
5718  $obj = $this->db->fetch_object($result);
5719  $last_date = $this->db->jdate($obj->datef);
5720  $invoice_date = $this->date;
5721 
5722  $is_last_of_same_type = $invoice_date >= $last_date;
5723  if ($allow_validated_drafts) {
5724  $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
5725  }
5726 
5727  return array($is_last_of_same_type, $last_date);
5728  } else {
5729  // element is first of type to be validated
5730  return array(true);
5731  }
5732  } else {
5733  dol_print_error($this->db);
5734  }
5735  }
5736 }
5737 
5743 {
5747  public $element = 'facturedet';
5748 
5752  public $table_element = 'facturedet';
5753 
5754  public $oldline;
5755 
5758  public $fk_facture;
5761 
5763  public $desc;
5764  public $ref_ext; // External reference of the line
5765 
5766  public $localtax1_type; // Local tax 1 type
5767  public $localtax2_type; // Local tax 2 type
5768  public $fk_remise_except; // Link to line into llx_remise_except
5769  public $rang = 0;
5770 
5771  public $fk_fournprice;
5772  public $pa_ht;
5773  public $marge_tx;
5774  public $marque_tx;
5775 
5776  public $remise_percent;
5777 
5778  public $special_code; // Liste d'options non cumulabels:
5779  // 1: frais de port
5780  // 2: ecotaxe
5781  // 3: ??
5782 
5783  public $origin;
5784  public $origin_id;
5785 
5786  public $fk_code_ventilation = 0;
5787 
5788  public $date_start;
5789  public $date_end;
5790 
5791  public $skip_update_total; // Skip update price total for special lines
5792 
5796  public $situation_percent;
5797 
5801  public $fk_prev_id;
5802 
5803  // Multicurrency
5804  public $fk_multicurrency;
5805  public $multicurrency_code;
5806  public $multicurrency_subprice;
5807  public $multicurrency_total_ht;
5808  public $multicurrency_total_tva;
5809  public $multicurrency_total_ttc;
5810 
5817  public function fetch($rowid)
5818  {
5819  $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,';
5820  $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5821  $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,';
5822  $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5823  $sql .= ' fd.fk_code_ventilation,';
5824  $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5825  $sql .= ' fd.situation_percent, fd.fk_prev_id,';
5826  $sql .= ' fd.multicurrency_subprice,';
5827  $sql .= ' fd.multicurrency_total_ht,';
5828  $sql .= ' fd.multicurrency_total_tva,';
5829  $sql .= ' fd.multicurrency_total_ttc,';
5830  $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5831  $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
5832  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
5833  $sql .= ' WHERE fd.rowid = '.((int) $rowid);
5834 
5835  $result = $this->db->query($sql);
5836  if ($result) {
5837  $objp = $this->db->fetch_object($result);
5838 
5839  $this->rowid = $objp->rowid;
5840  $this->id = $objp->rowid;
5841  $this->fk_facture = $objp->fk_facture;
5842  $this->fk_parent_line = $objp->fk_parent_line;
5843  $this->label = $objp->custom_label;
5844  $this->desc = $objp->description;
5845  $this->qty = $objp->qty;
5846  $this->subprice = $objp->subprice;
5847  $this->ref_ext = $objp->ref_ext;
5848  $this->vat_src_code = $objp->vat_src_code;
5849  $this->tva_tx = $objp->tva_tx;
5850  $this->localtax1_tx = $objp->localtax1_tx;
5851  $this->localtax2_tx = $objp->localtax2_tx;
5852  $this->remise_percent = $objp->remise_percent;
5853  $this->fk_remise_except = $objp->fk_remise_except;
5854  $this->fk_product = $objp->fk_product;
5855  $this->product_type = $objp->product_type;
5856  $this->date_start = $this->db->jdate($objp->date_start);
5857  $this->date_end = $this->db->jdate($objp->date_end);
5858  $this->info_bits = $objp->info_bits;
5859  $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5860  $this->special_code = $objp->special_code;
5861  $this->total_ht = $objp->total_ht;
5862  $this->total_tva = $objp->total_tva;
5863  $this->total_localtax1 = $objp->total_localtax1;
5864  $this->total_localtax2 = $objp->total_localtax2;
5865  $this->total_ttc = $objp->total_ttc;
5866  $this->fk_code_ventilation = $objp->fk_code_ventilation;
5867  $this->rang = $objp->rang;
5868  $this->fk_fournprice = $objp->fk_fournprice;
5869  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5870  $this->pa_ht = $marginInfos[0];
5871  $this->marge_tx = $marginInfos[1];
5872  $this->marque_tx = $marginInfos[2];
5873 
5874  $this->ref = $objp->product_ref; // deprecated
5875 
5876  $this->product_ref = $objp->product_ref;
5877  $this->product_label = $objp->product_label;
5878  $this->product_desc = $objp->product_desc;
5879 
5880  $this->fk_unit = $objp->fk_unit;
5881  $this->fk_user_modif = $objp->fk_user_modif;
5882  $this->fk_user_author = $objp->fk_user_author;
5883 
5884  $this->situation_percent = $objp->situation_percent;
5885  $this->fk_prev_id = $objp->fk_prev_id;
5886 
5887  $this->multicurrency_subprice = $objp->multicurrency_subprice;
5888  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5889  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5890  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5891 
5892  $this->db->free($result);
5893 
5894  return 1;
5895  } else {
5896  $this->error = $this->db->lasterror();
5897  return -1;
5898  }
5899  }
5900 
5908  public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5909  {
5910  global $langs, $user, $conf;
5911 
5912  $error = 0;
5913 
5914  $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'.
5915 
5916  dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
5917 
5918  // Clean parameters
5919  $this->desc = trim($this->desc);
5920  if (empty($this->tva_tx)) {
5921  $this->tva_tx = 0;
5922  }
5923  if (empty($this->localtax1_tx)) {
5924  $this->localtax1_tx = 0;
5925  }
5926  if (empty($this->localtax2_tx)) {
5927  $this->localtax2_tx = 0;
5928  }
5929  if (empty($this->localtax1_type)) {
5930  $this->localtax1_type = 0;
5931  }
5932  if (empty($this->localtax2_type)) {
5933  $this->localtax2_type = 0;
5934  }
5935  if (empty($this->total_localtax1)) {
5936  $this->total_localtax1 = 0;
5937  }
5938  if (empty($this->total_localtax2)) {
5939  $this->total_localtax2 = 0;
5940  }
5941  if (empty($this->rang)) {
5942  $this->rang = 0;
5943  }
5944  if (empty($this->remise_percent)) {
5945  $this->remise_percent = 0;
5946  }
5947  if (empty($this->info_bits)) {
5948  $this->info_bits = 0;
5949  }
5950  if (empty($this->subprice)) {
5951  $this->subprice = 0;
5952  }
5953  if (empty($this->ref_ext)) {
5954  $this->ref_ext = '';
5955  }
5956  if (empty($this->special_code)) {
5957  $this->special_code = 0;
5958  }
5959  if (empty($this->fk_parent_line)) {
5960  $this->fk_parent_line = 0;
5961  }
5962  if (empty($this->fk_prev_id)) {
5963  $this->fk_prev_id = 0;
5964  }
5965  if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
5966  $this->situation_percent = 100;
5967  }
5968 
5969  if (empty($this->pa_ht)) {
5970  $this->pa_ht = 0;
5971  }
5972  if (empty($this->multicurrency_subprice)) {
5973  $this->multicurrency_subprice = 0;
5974  }
5975  if (empty($this->multicurrency_total_ht)) {
5976  $this->multicurrency_total_ht = 0;
5977  }
5978  if (empty($this->multicurrency_total_tva)) {
5979  $this->multicurrency_total_tva = 0;
5980  }
5981  if (empty($this->multicurrency_total_ttc)) {
5982  $this->multicurrency_total_ttc = 0;
5983  }
5984 
5985  // if buy price not defined, define buyprice as configured in margin admin
5986  if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
5987  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
5988  return $result;
5989  } else {
5990  $this->pa_ht = $result;
5991  }
5992  }
5993 
5994  // Check parameters
5995  if ($this->product_type < 0) {
5996  $this->error = 'ErrorProductTypeMustBe0orMore';
5997  return -1;
5998  }
5999  if (!empty($this->fk_product) && $this->fk_product > 0) {
6000  // Check product exists
6001  $result = Product::isExistingObject('product', $this->fk_product);
6002  if ($result <= 0) {
6003  $this->error = 'ErrorProductIdDoesNotExists';
6004  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6005  return -1;
6006  }
6007  }
6008 
6009  $this->db->begin();
6010 
6011  // Update line in database
6012  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
6013  $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
6014  $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6015  $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6016  $sql .= ' date_start, date_end, fk_code_ventilation, ';
6017  $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6018  $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6019  $sql .= ' situation_percent, fk_prev_id,';
6020  $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
6021  $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6022  $sql .= ')';
6023  $sql .= " VALUES (".$this->fk_facture.",";
6024  $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
6025  $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
6026  $sql .= " '".$this->db->escape($this->desc)."',";
6027  $sql .= " ".price2num($this->qty).",";
6028  $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
6029  $sql .= " ".price2num($this->tva_tx).",";
6030  $sql .= " ".price2num($this->localtax1_tx).",";
6031  $sql .= " ".price2num($this->localtax2_tx).",";
6032  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
6033  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
6034  $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
6035  $sql .= " ".((int) $this->product_type).",";
6036  $sql .= " ".price2num($this->remise_percent).",";
6037  $sql .= " ".price2num($this->subprice).",";
6038  $sql .= " '".$this->db->escape($this->ref_ext)."',";
6039  $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
6040  $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
6041  $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
6042  $sql .= ' '.((int) $this->fk_code_ventilation).',';
6043  $sql .= ' '.((int) $this->rang).',';
6044  $sql .= ' '.((int) $this->special_code).',';
6045  $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
6046  $sql .= ' '.price2num($this->pa_ht).',';
6047  $sql .= " '".$this->db->escape($this->info_bits)."',";
6048  $sql .= " ".price2num($this->total_ht).",";
6049  $sql .= " ".price2num($this->total_tva).",";
6050  $sql .= " ".price2num($this->total_ttc).",";
6051  $sql .= " ".price2num($this->total_localtax1).",";
6052  $sql .= " ".price2num($this->total_localtax2);
6053  $sql .= ", ".((float) $this->situation_percent);
6054  $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
6055  $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6056  $sql .= ", ".((int) $user->id);
6057  $sql .= ", ".((int) $user->id);
6058  $sql .= ", ".(int) $this->fk_multicurrency;
6059  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
6060  $sql .= ", ".price2num($this->multicurrency_subprice);
6061  $sql .= ", ".price2num($this->multicurrency_total_ht);
6062  $sql .= ", ".price2num($this->multicurrency_total_tva);
6063  $sql .= ", ".price2num($this->multicurrency_total_ttc);
6064  $sql .= ')';
6065 
6066  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
6067  $resql = $this->db->query($sql);
6068  if ($resql) {
6069  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
6070  $this->rowid = $this->id; // For backward compatibility
6071 
6072  if (!$error) {
6073  $result = $this->insertExtraFields();
6074  if ($result < 0) {
6075  $error++;
6076  }
6077  }
6078 
6079  // If fk_remise_except is defined, the discount is linked to the invoice
6080  // which flags it as "consumed".
6081  if ($this->fk_remise_except) {
6082  $discount = new DiscountAbsolute($this->db);
6083  $result = $discount->fetch($this->fk_remise_except);
6084  if ($result >= 0) {
6085  // Check if discount was found
6086  if ($result > 0) {
6087  // Check if discount not already affected to another invoice
6088  if ($discount->fk_facture_line > 0) {
6089  if (empty($noerrorifdiscountalreadylinked)) {
6090  $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
6091  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6092  $this->db->rollback();
6093  return -3;
6094  }
6095  } else {
6096  $result = $discount->link_to_invoice($this->rowid, 0);
6097  if ($result < 0) {
6098  $this->error = $discount->error;
6099  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6100  $this->db->rollback();
6101  return -3;
6102  }
6103  }
6104  } else {
6105  $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
6106  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6107  $this->db->rollback();
6108  return -3;
6109  }
6110  } else {
6111  $this->error = $discount->error;
6112  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6113  $this->db->rollback();
6114  return -3;
6115  }
6116  }
6117 
6118  if (!$notrigger) {
6119  // Call trigger
6120  $result = $this->call_trigger('LINEBILL_INSERT', $user);
6121  if ($result < 0) {
6122  $this->db->rollback();
6123  return -2;
6124  }
6125  // End call triggers
6126  }
6127 
6128  $this->db->commit();
6129  return $this->id;
6130  } else {
6131  $this->error = $this->db->lasterror();
6132  $this->db->rollback();
6133  return -2;
6134  }
6135  }
6136 
6144  public function update($user = '', $notrigger = 0)
6145  {
6146  global $user, $conf;
6147 
6148  $error = 0;
6149 
6150  $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'.
6151 
6152  // Clean parameters
6153  $this->desc = trim($this->desc);
6154  if (empty($this->ref_ext)) {
6155  $this->ref_ext = '';
6156  }
6157  if (empty($this->tva_tx)) {
6158  $this->tva_tx = 0;
6159  }
6160  if (empty($this->localtax1_tx)) {
6161  $this->localtax1_tx = 0;
6162  }
6163  if (empty($this->localtax2_tx)) {
6164  $this->localtax2_tx = 0;
6165  }
6166  if (empty($this->localtax1_type)) {
6167  $this->localtax1_type = 0;
6168  }
6169  if (empty($this->localtax2_type)) {
6170  $this->localtax2_type = 0;
6171  }
6172  if (empty($this->total_localtax1)) {
6173  $this->total_localtax1 = 0;
6174  }
6175  if (empty($this->total_localtax2)) {
6176  $this->total_localtax2 = 0;
6177  }
6178  if (empty($this->remise_percent)) {
6179  $this->remise_percent = 0;
6180  }
6181  if (empty($this->info_bits)) {
6182  $this->info_bits = 0;
6183  }
6184  if (empty($this->special_code)) {
6185  $this->special_code = 0;
6186  }
6187  if (empty($this->product_type)) {
6188  $this->product_type = 0;
6189  }
6190  if (empty($this->fk_parent_line)) {
6191  $this->fk_parent_line = 0;
6192  }
6193  if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
6194  $this->situation_percent = 100;
6195  }
6196  if (empty($this->pa_ht)) {
6197  $this->pa_ht = 0;
6198  }
6199 
6200  if (empty($this->multicurrency_subprice)) {
6201  $this->multicurrency_subprice = 0;
6202  }
6203  if (empty($this->multicurrency_total_ht)) {
6204  $this->multicurrency_total_ht = 0;
6205  }
6206  if (empty($this->multicurrency_total_tva)) {
6207  $this->multicurrency_total_tva = 0;
6208  }
6209  if (empty($this->multicurrency_total_ttc)) {
6210  $this->multicurrency_total_ttc = 0;
6211  }
6212 
6213  // Check parameters
6214  if ($this->product_type < 0) {
6215  return -1;
6216  }
6217 
6218  // if buy price not provided, define buyprice as configured in margin admin
6219  if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6220  // We call defineBuyPrice only if data was not provided (if input was '0', we will not go here and value will remaine '0')
6221  $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6222  if ($result < 0) {
6223  return $result;
6224  } else {
6225  $this->pa_ht = $result;
6226  }
6227  }
6228 
6229  $this->db->begin();
6230 
6231  // Update line in database
6232  $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6233  $sql .= " description='".$this->db->escape($this->desc)."'";
6234  $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
6235  $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
6236  $sql .= ", subprice=".price2num($this->subprice);
6237  $sql .= ", remise_percent=".price2num($this->remise_percent);
6238  if ($this->fk_remise_except) {
6239  $sql .= ", fk_remise_except=".$this->fk_remise_except;
6240  } else {
6241  $sql .= ", fk_remise_except=null";
6242  }
6243  $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
6244  $sql .= ", tva_tx=".price2num($this->tva_tx);
6245  $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
6246  $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
6247  $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
6248  $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
6249  $sql .= ", qty=".price2num($this->qty);
6250  $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
6251  $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
6252  $sql .= ", product_type=".$this->product_type;
6253  $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
6254  $sql .= ", special_code='".$this->db->escape($this->special_code)."'";
6255  if (empty($this->skip_update_total)) {
6256  $sql .= ", total_ht=".price2num($this->total_ht);
6257  $sql .= ", total_tva=".price2num($this->total_tva);
6258  $sql .= ", total_ttc=".price2num($this->total_ttc);
6259  $sql .= ", total_localtax1=".price2num($this->total_localtax1);
6260  $sql .= ", total_localtax2=".price2num($this->total_localtax2);
6261  }
6262  $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
6263  $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)
6264  $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
6265  if (!empty($this->rang)) {
6266  $sql .= ", rang=".((int) $this->rang);
6267  }
6268  $sql .= ", situation_percent = ".((float) $this->situation_percent);
6269  $sql .= ", fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6270  $sql .= ", fk_user_modif = ".((int) $user->id);
6271 
6272  // Multicurrency
6273  $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6274  $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6275  $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6276  $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6277 
6278  $sql .= " WHERE rowid = ".((int) $this->rowid);
6279 
6280  dol_syslog(get_class($this)."::update", LOG_DEBUG);
6281  $resql = $this->db->query($sql);
6282  if ($resql) {
6283  if (!$error) {
6284  $this->id = $this->rowid;
6285  $result = $this->insertExtraFields();
6286  if ($result < 0) {
6287  $error++;
6288  }
6289  }
6290 
6291  if (!$error && !$notrigger) {
6292  // Call trigger
6293  $result = $this->call_trigger('LINEBILL_MODIFY', $user);
6294  if ($result < 0) {
6295  $this->db->rollback();
6296  return -2;
6297  }
6298  // End call triggers
6299  }
6300  $this->db->commit();
6301  return 1;
6302  } else {
6303  $this->error = $this->db->error();
6304  $this->db->rollback();
6305  return -2;
6306  }
6307  }
6308 
6316  public function delete($tmpuser = null, $notrigger = false)
6317  {
6318  global $user;
6319 
6320  $this->db->begin();
6321 
6322  // Call trigger
6323  if (empty($notrigger)) {
6324  $result = $this->call_trigger('LINEBILL_DELETE', $user);
6325  if ($result < 0) {
6326  $this->db->rollback();
6327  return -1;
6328  }
6329  }
6330  // End call triggers
6331 
6332  // extrafields
6333  $result = $this->deleteExtraFields();
6334  if ($result < 0) {
6335  $this->db->rollback();
6336  return -1;
6337  }
6338 
6339  $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->rowid);
6340 
6341  if ($this->db->query($sql)) {
6342  $this->db->commit();
6343  return 1;
6344  } else {
6345  $this->error = $this->db->error()." sql=".$sql;
6346  $this->db->rollback();
6347  return -1;
6348  }
6349  }
6350 
6351  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6358  public function update_total()
6359  {
6360  // phpcs:enable
6361  $this->db->begin();
6362  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6363 
6364  // Clean parameters
6365  if (empty($this->total_localtax1)) {
6366  $this->total_localtax1 = 0;
6367  }
6368  if (empty($this->total_localtax2)) {
6369  $this->total_localtax2 = 0;
6370  }
6371 
6372  // Update line in database
6373  $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6374  $sql .= " total_ht=".price2num($this->total_ht)."";
6375  $sql .= ",total_tva=".price2num($this->total_tva)."";
6376  $sql .= ",total_localtax1=".price2num($this->total_localtax1)."";
6377  $sql .= ",total_localtax2=".price2num($this->total_localtax2)."";
6378  $sql .= ",total_ttc=".price2num($this->total_ttc)."";
6379  $sql .= " WHERE rowid = ".((int) $this->rowid);
6380 
6381  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6382 
6383  $resql = $this->db->query($sql);
6384  if ($resql) {
6385  $this->db->commit();
6386  return 1;
6387  } else {
6388  $this->error = $this->db->error();
6389  $this->db->rollback();
6390  return -2;
6391  }
6392  }
6393 
6394  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6403  public function get_prev_progress($invoiceid, $include_credit_note = true)
6404  {
6405  // phpcs:enable
6406  global $invoicecache;
6407  if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
6408  return 0;
6409  } else {
6410  // If invoice is not a situation invoice, this->fk_prev_id is used for something else
6411  if (!isset($invoicecache[$invoiceid])) {
6412  $invoicecache[$invoiceid] = new Facture($this->db);
6413  $invoicecache[$invoiceid]->fetch($invoiceid);
6414  }
6415  if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
6416  return 0;
6417  }
6418 
6419  $sql = "SELECT situation_percent FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6420  $resql = $this->db->query($sql);
6421  if ($resql && $this->db->num_rows($resql) > 0) {
6422  $res = $this->db->fetch_array($resql);
6423 
6424  $returnPercent = floatval($res['situation_percent']);
6425 
6426  if ($include_credit_note) {
6427  $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
6428  $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
6429  $sql .= " WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6430  $sql .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
6431  $sql .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6432 
6433  $res = $this->db->query($sql);
6434  if ($res) {
6435  while ($obj = $this->db->fetch_object($res)) {
6436  $returnPercent = $returnPercent + floatval($obj->situation_percent);
6437  }
6438  } else {
6439  dol_print_error($this->db);
6440  }
6441  }
6442 
6443  return $returnPercent;
6444  } else {
6445  $this->error = $this->db->error();
6446  dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6447  $this->db->rollback();
6448  return -1;
6449  }
6450  }
6451  }
6452 }
Facture\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: facture.class.php:412
make_substitutions
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
Definition: functions.lib.php:7839
CommonInvoice\getSommePaiement
getSommePaiement($multicurrency=0)
Return amount of payments already done.
Definition: commoninvoice.class.php:137
dol_getdate
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
Definition: functions.lib.php:2713
Facture\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: facture.class.php:5041
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
getLocalTaxesFromRate
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
Definition: functions.lib.php:6097
FactureLigne\$fk_facture
$fk_facture
From llx_facturedet Id facture.
Definition: facture.class.php:5758
db
$conf db
API class for accounts.
Definition: inc.php:41
dol_get_last_hour
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
Facture\deleteline
deleteline($rowid)
Delete line in database.
Definition: facture.class.php:4178
dol_escape_htmltag
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.
Definition: functions.lib.php:1468
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:3805
CommonObject\getIdContact
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
Definition: commonobject.class.php:1643
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
Expedition
Class to manage shipments.
Definition: expedition.class.php:52
ActionComm
Class to manage agenda events (actions)
Definition: actioncomm.class.php:38
Facture\$fk_facture_source
$fk_facture_source
id of source invoice if replacement invoice or credit note
Definition: facture.class.php:205
Facture\insert_discount
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
Definition: facture.class.php:2428
Facture\setUnpaid
setUnpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
Definition: facture.class.php:2873
Facture\load_state_board
load_state_board()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: facture.class.php:4987
dol_delete_dir_recursive
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:1383
Facture\getIdShippingContact
getIdShippingContact()
Retourne id des contacts clients de livraison.
Definition: facture.class.php:4817
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
Facture\set_remise
set_remise($user, $remise, $notrigger=0)
Set percent discount.
Definition: facture.class.php:4243
ProductFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.product.class.php:41
Facture\createFromClone
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
Definition: facture.class.php:1224
Facture\set_ref_client
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
Definition: facture.class.php:2526
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
CommonObject\updateRangOfLine
updateRangOfLine($rowid, $rang)
Update position of line (rang)
Definition: commonobject.class.php:3219
CommonObject\fetchObjectLinked
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).
Definition: commonobject.class.php:3916
Facture\is_first
is_first()
Checks if the invoice is the first of a cycle.
Definition: facture.class.php:5100
Facture\STATUS_VALIDATED
const STATUS_VALIDATED
Validated (need to be paid)
Definition: facture.class.php:417
Facture\setCanceled
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
Definition: facture.class.php:2940
Facture\fetch
fetch($rowid, $ref='', $ref_ext='', $notused='', $fetch_situation=false)
Get object from database.
Definition: facture.class.php:1949
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
Facture\updateline
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.
Definition: facture.class.php:3896
Facture\set_unpaid
set_unpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
Definition: facture.class.php:2858
Translate
Class to manage translations.
Definition: translate.class.php:30
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
FactureRec
Class to manage invoice templates.
Definition: facture-rec.class.php:40
MultiCurrency\getIdFromCode
static getIdFromCode($dbs, $code)
Get id of currency from code.
Definition: multicurrency.class.php:501
Facture\addline
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).
Definition: facture.class.php:3601
CommonObject\deleteObjectLinked
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
Definition: commonobject.class.php:4228
ref
$object ref
Definition: info.php:77
dol_mimetype
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
Definition: functions.lib.php:9741
Facture\$pos_source
$pos_source
key of pos source ('0', '1', ...)
Definition: facture.class.php:201
CMailFile
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Definition: CMailFile.class.php:38
CommonObject\commonReplaceProduct
static commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
Definition: commonobject.class.php:8376
Facture\__construct
__construct(DoliDB $db)
Constructor.
Definition: facture.class.php:451
Facture\info
info($id)
Load miscellaneous information for tab "Info".
Definition: facture.class.php:4488
rowid
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
Definition: email_expire_services_to_representatives.php:79
Facture\validate
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.
Definition: facture.class.php:2999
Facture\$table_ref_field
$table_ref_field
{}
Definition: facture.class.php:102
Facture\getRetainedWarrantyAmount
getRetainedWarrantyAmount($rounding=-1)
Definition: facture.class.php:5326
dol_dir_list
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
FormMargin
Classe permettant la generation de composants html autre Only common components are here.
Definition: html.formmargin.class.php:29
FactureLigne\insert
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
Definition: facture.class.php:5908
Facture
Class to manage invoices.
Definition: facture.class.php:60
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
Facture\getNomUrl
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)
Definition: facture.class.php:1790
Facture\replaceProduct
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
Definition: facture.class.php:5240
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
Facture\newCycle
newCycle()
Gets the smallest reference available for a new cycle.
Definition: facture.class.php:5072
FactureLigne\fetch
fetch($rowid)
Load invoice line from database.
Definition: facture.class.php:5817
Facture\willBeLastOfSameType
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
Definition: facture.class.php:5705
Facture\TYPE_DEPOSIT
const TYPE_DEPOSIT
Deposit invoice.
Definition: facture.class.php:397
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
Facture\checkProgressLine
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
Definition: facture.class.php:4108
WorkboardResponse
Definition: workboardresponse.class.php:25
CommonObject\fetch_thirdparty
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
Definition: commonobject.class.php:1736
dol_concatdesc
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...
Definition: functions.lib.php:7248
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
Facture\getNextNumRef
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
Definition: facture.class.php:4383
FactureLigne\get_prev_progress
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
Definition: facture.class.php:6403
Facture\hasDelay
hasDelay()
Is the customer invoice delayed?
Definition: facture.class.php:5254
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
Facture\TYPE_REPLACEMENT
const TYPE_REPLACEMENT
Replacement invoice.
Definition: facture.class.php:387
calcul_price_total
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
dol_delete_file
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:1231
Facture\get_prev_sits
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
Definition: facture.class.php:5112
FactureLigne
Class to manage invoice lines.
Definition: facture.class.php:5742
CommonObject\update_price
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).
Definition: commonobject.class.php:3525
Facture\createDepositFromOrigin
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.
Definition: facture.class.php:1502
Facture\getLinesArray
getLinesArray()
Create an array of invoice lines.
Definition: facture.class.php:5025
Facture\set_paid
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
Definition: facture.class.php:2779
Facture\liste_array
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.
Definition: facture.class.php:4543
Facture\create
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
Definition: facture.class.php:466
Facture\load_board
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: facture.class.php:4742
Facture\setFinal
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
Definition: facture.class.php:5146
Facture\TYPE_PROFORMA
const TYPE_PROFORMA
Proforma invoice (should not be used.
Definition: facture.class.php:402
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:148
FactureLigne\update_total
update_total()
Update DB line fields total_xxx Used by migration.
Definition: facture.class.php:6358
MouvementStock
Class to manage stock movements.
Definition: mouvementstock.class.php:31
Facture\$paye
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
Definition: facture.class.php:196
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6156
Facture\createFromCurrent
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
Definition: facture.class.php:1130
Facture\update
update(User $user, $notrigger=0)
Update database.
Definition: facture.class.php:2287
CommonObject\isExistingObject
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check an object id/ref exists If you don't need/want to instantiate object and just need to know if o...
Definition: commonobject.class.php:617
Facture\update_percent
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
Definition: facture.class.php:4138
Facture\STATUS_CLOSED
const STATUS_CLOSED
Classified paid.
Definition: facture.class.php:426
CommonObject\delete_linked_contact
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Definition: commonobject.class.php:1319
Facture\setRetainedWarrantyDateLimit
setRetainedWarrantyDateLimit($timestamp, $dateYmd=false)
Change the retained_warranty_date_limit.
Definition: facture.class.php:5417
getDictionaryValue
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
Definition: functions.lib.php:10138
dol_get_first_hour
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
Facture\set_remise_absolue
set_remise_absolue($user, $remise, $notrigger=0)
Set absolute discount.
Definition: facture.class.php:4320
getCommonSubstitutionArray
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
Definition: functions.lib.php:7275
Facture\getIdBillingContact
getIdBillingContact()
Retourne id des contacts clients de facturation.
Definition: facture.class.php:4807
Facture\setDiscount
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
Definition: facture.class.php:4258
CommonObject\defineBuyPrice
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
Definition: commonobject.class.php:8405
CommonObject\deleteEcmFiles
deleteEcmFiles($mode=0)
Delete related files of object in database.
Definition: commonobject.class.php:9966
CommonObject\add_contact
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Definition: commonobject.class.php:1108
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8347
Facture\$module_source
$module_source
key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos',...
Definition: facture.class.php:199
Facture\set_canceled
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
Definition: facture.class.php:2923
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
DiscountAbsolute
Class to manage absolute discounts.
Definition: discount.class.php:29
Facture\fetchPreviousNextSituationInvoice
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
Definition: facture.class.php:2249
Facture\setRetainedWarranty
setRetainedWarranty($value)
Change the retained warranty.
Definition: facture.class.php:5384
MultiCurrency\getIdAndTxFromCode
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Definition: multicurrency.class.php:526
Facture\is_last_in_cycle
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
Definition: facture.class.php:5189
CommonObject\line_max
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
Definition: commonobject.class.php:3373
Facture\$fk_fac_rec_source
$fk_fac_rec_source
id of template invoice when generated from a template invoice
Definition: facture.class.php:203
dol_get_first_day
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
CommonObject\fetch_optionals
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
Definition: commonobject.class.php:6007
dol_get_last_day
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
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
Facture\replaceThirdparty
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: facture.class.php:5223
Facture\setPaid
setPaid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
Definition: facture.class.php:2795
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:105
Facture\setDraft
setDraft($user, $idwarehouse=-1)
Set draft status.
Definition: facture.class.php:3478
Facture\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: facture.class.php:392
dol_time_plus_duree
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
User
Class to manage Dolibarr users.
Definition: user.class.php:44
FactureLigne\update
update($user='', $notrigger=0)
Update line into database.
Definition: facture.class.php:6144
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:386
CommonInvoice
Superclass for invoices classes.
Definition: commoninvoice.class.php:32
Facture\TYPE_STANDARD
const TYPE_STANDARD
Standard invoice.
Definition: facture.class.php:382
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6116
Product
Class to manage products or services.
Definition: product.class.php:46
getMarginInfos
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
Definition: margins.lib.php:117
dol_delete_preview
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1435
CommonObject\add_object_linked
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
Definition: commonobject.class.php:3818
dol_get_next_month
dol_get_next_month($month, $year)
Return next month.
Definition: date.lib.php:489
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
CommonInvoiceLine
Parent class of all other business classes for details of elements (invoices, contracts,...
Definition: commoninvoice.class.php:1031
Facture\list_qualified_avoir_invoices
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
Definition: facture.class.php:4667
Facture\initAsSpecimen
initAsSpecimen($option='')
Initialise an instance with random values.
Definition: facture.class.php:4831
FactureLigne\$fk_parent_line
$fk_parent_line
Id parent line.
Definition: facture.class.php:5760
Entrepot
Class to manage warehouses.
Definition: entrepot.class.php:35
CommonInvoice\is_erasable
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
Definition: commoninvoice.class.php:424
Facture\list_replacable_invoices
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
Definition: facture.class.php:4613
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
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
Facture\sendEmailsRemindersOnInvoiceDueDate
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='')
Send reminders by emails for ivoices that are due CAN BE A CRON TASK.
Definition: facture.class.php:5456
Facture\STATUS_ABANDONED
const STATUS_ABANDONED
Classified abandoned and no payment done.
Definition: facture.class.php:435
Facture\fetch_lines
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
Definition: facture.class.php:2130
price
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.
Definition: functions.lib.php:5541
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
FormMail
Classe permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new For...
Definition: html.formmail.class.php:38
CommonInvoice\calculate_date_lim_reglement
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
Definition: commoninvoice.class.php:624
dol_mktime
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...
Definition: functions.lib.php:2757
CommonObject\line_order
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
Definition: commonobject.class.php:3055
Facture\TYPE_SITUATION
const TYPE_SITUATION
Situation invoice.
Definition: facture.class.php:407
type
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
Facture\displayRetainedWarranty
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
Definition: facture.class.php:5288
Productbatch\BATCH_RULE_SELLBY_EATBY_DATES_FIRST
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Definition: productbatch.class.php:36
HookManager
Class to manage hooks.
Definition: hookmanager.class.php:30
complete_substitutions_array
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
Definition: functions.lib.php:7961
FactureLigne\$desc
$desc
Description ligne.
Definition: facture.class.php:5763
float
div float
Buy price without taxes.
Definition: style.css.php:809
if
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Definition: journals_list.php:25
Facture\createFromOrder
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
Definition: facture.class.php:1366
Facture\updatePriceNextInvoice
updatePriceNextInvoice(&$langs)
Update price of next invoice.
Definition: facture.class.php:3421