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