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