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