dolibarr  13.0.2
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 Ferran Marcet <fmarcet@2byte.es>
18  * Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr>
19  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 3 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program. If not, see <https://www.gnu.org/licenses/>.
33  */
34 
41 include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
46 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
47 
48 if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
49 if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
50 
54 class Facture extends CommonInvoice
55 {
59  public $element = 'facture';
60 
64  public $table_element = 'facture';
65 
69  public $table_element_line = 'facturedet';
70 
74  public $fk_element = 'fk_facture';
75 
79  public $picto = 'bill';
80 
85  public $ismultientitymanaged = 1;
86 
91  public $restrictiononfksoc = 1;
92 
96  protected $table_ref_field = 'ref';
97 
101  public $socid;
102 
103  public $author;
104 
108  public $fk_user_author;
109 
113  public $fk_user_valid;
114 
115  public $date; // Date invoice
116  public $datem;
117 
122  public $date_livraison; // deprecated; Use delivery_date instead.
123 
124  public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
125 
129  public $ref_client;
130 
135  public $ref_int; // deprecated
136 
137  //Check constants for types
138  public $type = self::TYPE_STANDARD;
139 
140  //var $amount;
141  public $remise_absolue;
142  public $remise_percent;
143  public $total_ht = 0;
144  public $total_tva = 0;
145  public $total_localtax1 = 0;
146  public $total_localtax2 = 0;
147  public $total_ttc = 0;
148  public $revenuestamp;
149 
152  public $close_code;
154  public $close_note;
155 
159  public $paye;
160 
164  public $pos_source;
169  public $linked_objects = array();
170  public $date_lim_reglement;
171  public $cond_reglement_code; // Code in llx_c_paiement
172  public $mode_reglement_code; // Code in llx_c_paiement
173 
177  public $fk_bank;
178 
182  public $lines = array();
183 
184  public $line;
185  public $extraparams = array();
186 
187  public $fac_rec;
188 
189  public $date_pointoftax;
190 
191  // Multicurrency
195  public $fk_multicurrency;
196 
197  public $multicurrency_code;
198  public $multicurrency_tx;
199  public $multicurrency_total_ht;
200  public $multicurrency_total_tva;
201  public $multicurrency_total_ttc;
202 
206  public $situation_cycle_ref;
207 
211  public $situation_counter;
212 
216  public $situation_final;
217 
221  public $tab_previous_situation_invoice = array();
222 
226  public $tab_next_situation_invoice = array();
227 
228  public $oldcopy;
229 
233  public $retained_warranty;
234 
238  public $retained_warranty_date_limit;
239 
243  public $retained_warranty_fk_cond_reglement;
244 
245 
270  // BEGIN MODULEBUILDER PROPERTIES
274  public $fields = array(
275  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
276  'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15),
277  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
278  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>25),
279  'ref_int' =>array('type'=>'varchar(255)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>0, 'position'=>30), // deprecated
280  'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
281  'ref_client' =>array('type'=>'varchar(255)', 'label'=>'Ref client', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
282  //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
283  'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>50),
284  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
285  'datef' =>array('type'=>'date', 'label'=>'DateInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
286  'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
287  'date_closing' =>array('type'=>'datetime', 'label'=>'Date closing', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
288  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>75),
289  'paye' =>array('type'=>'smallint(6)', 'label'=>'InvoicePaidCompletely', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>80),
290  //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85),
291  'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
292  'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
293  //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
294  'close_code' =>array('type'=>'varchar(16)', 'label'=>'EarlyClosingReason', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
295  'close_note' =>array('type'=>'varchar(128)', 'label'=>'EarlyClosingComment', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
296  'tva' =>array('type'=>'double(24,8)', 'label'=>'TotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>115, 'isameasure'=>1),
297  'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LT1', 'enabled'=>1, 'visible'=>-1, 'position'=>120, 'isameasure'=>1),
298  'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LT2', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1),
299  'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1),
300  'total' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1),
301  'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1),
302  'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
303  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>155),
304  'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
305  'fk_user_closing' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
306  'fk_facture_source' =>array('type'=>'integer', 'label'=>'SourceInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
307  'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
308  'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
309  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'CurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
310  'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>190),
311  'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
312  'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateDue', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
313  'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>205),
314  'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>210),
315  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>215),
316  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
317  'situation_cycle_ref' =>array('type'=>'smallint(6)', 'label'=>'Situation cycle ref', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>230),
318  'situation_counter' =>array('type'=>'smallint(6)', 'label'=>'Situation counter', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>235),
319  'situation_final' =>array('type'=>'smallint(6)', 'label'=>'Situation final', 'enabled'=>'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1', 'visible'=>-1, 'position'=>240),
320  'retained_warranty' =>array('type'=>'double', 'label'=>'Retained warranty', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>245),
321  'retained_warranty_date_limit' =>array('type'=>'date', 'label'=>'Retained warranty date limit', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>250),
322  '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),
323  'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>260),
324  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>265),
325  'date_pointoftax' =>array('type'=>'date', 'label'=>'DatePointOfTax', 'enabled'=>'$conf->global->INVOICE_POINTOFTAX_DATE', 'visible'=>-1, 'position'=>270),
326  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>275),
327  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>280),
328  'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
329  'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
330  'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>295, 'isameasure'=>1),
331  'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>300, 'isameasure'=>1),
332  'fk_fac_rec_source' =>array('type'=>'integer', 'label'=>'RecurringInvoiceSource', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
333  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>310),
334  'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>315),
335  'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>320),
336  'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Paid', 3=>'Abandonned')),
337  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
338  );
339  // END MODULEBUILDER PROPERTIES
340 
344  const TYPE_STANDARD = 0;
345 
349  const TYPE_REPLACEMENT = 1;
350 
354  const TYPE_CREDIT_NOTE = 2;
355 
359  const TYPE_DEPOSIT = 3;
360 
364  const TYPE_PROFORMA = 4;
365 
369  const TYPE_SITUATION = 5;
370 
374  const STATUS_DRAFT = 0;
375 
379  const STATUS_VALIDATED = 1;
380 
388  const STATUS_CLOSED = 2;
389 
397  const STATUS_ABANDONED = 3;
398 
399  const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandonned remain - escompte
400  const CLOSECODE_BADDEBT = 'badcustomer'; // Abandonned - bad
401  const CLOSECODE_ABANDONED = 'abandon'; // Abandonned - other
402  const CLOSECODE_REPLACED = 'replaced'; // Closed after doing a replacement invoice
403 
404 
410  public function __construct($db)
411  {
412  $this->db = $db;
413  }
414 
425  public function create(User $user, $notrigger = 0, $forceduedate = 0)
426  {
427  global $langs, $conf, $mysoc, $hookmanager;
428  $error = 0;
429 
430  // Clean parameters
431  if (empty($this->type)) $this->type = self::TYPE_STANDARD;
432  $this->ref_client = trim($this->ref_client);
433  $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
434  $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
435  $this->note_public = trim($this->note_public);
436  if (!$this->cond_reglement_id) $this->cond_reglement_id = 0;
437  if (!$this->mode_reglement_id) $this->mode_reglement_id = 0;
438  $this->brouillon = 1;
439 
440  // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
441  if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
442  else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
443  if (empty($this->fk_multicurrency))
444  {
445  $this->multicurrency_code = $conf->currency;
446  $this->fk_multicurrency = 0;
447  $this->multicurrency_tx = 1;
448  }
449 
450  dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
451 
452  // Check parameters
453  if (empty($this->date))
454  {
455  $this->error = "Try to create an invoice with an empty parameter (date)";
456  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
457  return -3;
458  }
459  $soc = new Societe($this->db);
460  $result = $soc->fetch($this->socid);
461  if ($result < 0)
462  {
463  $this->error = "Failed to fetch company: ".$soc->error;
464  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
465  return -2;
466  }
467 
468  $now = dol_now();
469 
470  $this->db->begin();
471 
472  $originaldatewhen = null;
473  $nextdatewhen = null;
474  $previousdaynextdatewhen = null;
475 
476  // Create invoice from a template recurring invoice
477  if ($this->fac_rec > 0)
478  {
479  $this->fk_fac_rec_source = $this->fac_rec;
480 
481  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
482  $_facrec = new FactureRec($this->db);
483  $result = $_facrec->fetch($this->fac_rec);
484  $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
485 
486  // Define some dates
487  $originaldatewhen = $_facrec->date_when;
488  $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
489  $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
490 
491  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.
492  {
493  $this->socid = $_facrec->socid;
494  }
495  $this->entity = $_facrec->entity; // Invoice created in same entity than template
496 
497  // 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
498  $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_project;
499  $this->note_public = GETPOST('note_public', 'none') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
500  $this->note_private = GETPOST('note_private', 'none') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
501  $this->modelpdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->modelpdf;
502  $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id;
503  $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id;
504  $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
505 
506  // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
507  $this->total_ht = $_facrec->total_ht;
508  $this->total_ttc = $_facrec->total_ttc;
509 
510  // Fields always coming from template
511  $this->remise_absolue = $_facrec->remise_absolue;
512  $this->remise_percent = $_facrec->remise_percent;
513  $this->fk_incoterms = $_facrec->fk_incoterms;
514  $this->location_incoterms = $_facrec->location_incoterms;
515 
516  // Clean parameters
517  if (!$this->type) $this->type = self::TYPE_STANDARD;
518  $this->ref_client = trim($this->ref_client);
519  $this->note_public = trim($this->note_public);
520  $this->note_private = trim($this->note_private);
521  $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
522 
523  $this->array_options = $_facrec->array_options;
524 
525  //if (! $this->remise) $this->remise = 0;
526  if (!$this->mode_reglement_id) $this->mode_reglement_id = 0;
527  $this->brouillon = 1;
528 
529  $this->linked_objects = $_facrec->linkedObjectsIds;
530  // We do not add link to template invoice or next invoice will be linked to all generated invoices
531  //$this->linked_objects['facturerec'][0] = $this->fac_rec;
532 
533  $forceduedate = $this->calculate_date_lim_reglement();
534 
535  // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
536  if ($_facrec->frequency > 0)
537  {
538  dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
539  if (empty($_facrec->date_when)) $_facrec->date_when = $now;
540  $next_date = $_facrec->getNextDate(); // Calculate next date
541  $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
542  //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
543  $result = $_facrec->setNextDate($next_date, 1);
544  }
545 
546  // Define lang of customer
547  $outputlangs = $langs;
548  $newlang = '';
549 
550  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
551  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang = $this->default_lang; // for thirdparty
552  if (!empty($newlang))
553  {
554  $outputlangs = new Translate("", $conf);
555  $outputlangs->setDefaultLang($newlang);
556  }
557 
558  // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
559  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
560  $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
561  $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
562  $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
563  $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
564  $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
565  $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
566  $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
567  $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
568  $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
569  // Only for template invoice
570  $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour');
571  $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($nextdatewhen, 'dayhour');
572  $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($previousdaynextdatewhen, 'dayhour');
573  $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
574  $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
575 
576  //var_dump($substitutionarray);exit;
577 
578  complete_substitutions_array($substitutionarray, $outputlangs);
579 
580  $this->note_public = make_substitutions($this->note_public, $substitutionarray);
581  $this->note_private = make_substitutions($this->note_private, $substitutionarray);
582  }
583 
584  // Define due date if not already defined
585  if (empty($forceduedate)) {
586  $duedate = $this->calculate_date_lim_reglement();
587  /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
588  dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
589  return -1;
590  }*/
591  $this->date_lim_reglement = $duedate;
592  } else {
593  $this->date_lim_reglement = $forceduedate;
594  }
595 
596  // Insert into database
597  $socid = $this->socid;
598 
599  $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
600  $sql .= " ref";
601  $sql .= ", entity";
602  $sql .= ", ref_ext";
603  $sql .= ", type";
604  $sql .= ", fk_soc";
605  $sql .= ", datec";
606  $sql .= ", remise_absolue";
607  $sql .= ", remise_percent";
608  $sql .= ", datef";
609  $sql .= ", date_pointoftax";
610  $sql .= ", note_private";
611  $sql .= ", note_public";
612  $sql .= ", ref_client, ref_int";
613  $sql .= ", fk_account";
614  $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
615  $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
616  $sql .= ", situation_cycle_ref, situation_counter, situation_final";
617  $sql .= ", fk_incoterms, location_incoterms";
618  $sql .= ", fk_multicurrency";
619  $sql .= ", multicurrency_code";
620  $sql .= ", multicurrency_tx";
621  $sql .= ", retained_warranty";
622  $sql .= ", retained_warranty_date_limit";
623  $sql .= ", retained_warranty_fk_cond_reglement";
624  $sql .= ")";
625  $sql .= " VALUES (";
626  $sql .= "'(PROV)'";
627  $sql .= ", ".setEntity($this);
628  $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
629  $sql .= ", '".$this->db->escape($this->type)."'";
630  $sql .= ", ".((int) $socid);
631  $sql .= ", '".$this->db->idate($now)."'";
632  $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL');
633  $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL');
634  $sql .= ", '".$this->db->idate($this->date)."'";
635  $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
636  $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
637  $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
638  $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
639  $sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
640  $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
641  $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
642  $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
643  $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
644  $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
645  $sql .= ", ".($user->id > 0 ? (int) $user->id : "null");
646  $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
647  $sql .= ", ".$this->cond_reglement_id;
648  $sql .= ", ".$this->mode_reglement_id;
649  $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
650  $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
651  $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
652  $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
653  $sql .= ", ".($this->situation_final ? $this->situation_final : 0);
654  $sql .= ", ".(int) $this->fk_incoterms;
655  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
656  $sql .= ", ".(int) $this->fk_multicurrency;
657  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
658  $sql .= ", ".(double) $this->multicurrency_tx;
659  $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty));
660  $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
661  $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
662  $sql .= ")";
663 
664  $resql = $this->db->query($sql);
665  if ($resql)
666  {
667  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
668 
669  // Update ref with new one
670  $this->ref = '(PROV'.$this->id.')';
671  $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
672 
673  $resql = $this->db->query($sql);
674  if (!$resql) $error++;
675 
676  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
677  {
678  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
679  }
680 
681  // Add object linked
682  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects))
683  {
684  foreach ($this->linked_objects as $origin => $tmp_origin_id)
685  {
686  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, ...))
687  {
688  foreach ($tmp_origin_id as $origin_id)
689  {
690  $ret = $this->add_object_linked($origin, $origin_id);
691  if (!$ret)
692  {
693  $this->error = $this->db->lasterror();
694  $error++;
695  }
696  }
697  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
698  {
699  $origin_id = $tmp_origin_id;
700  $ret = $this->add_object_linked($origin, $origin_id);
701  if (!$ret)
702  {
703  $this->error = $this->db->lasterror();
704  $error++;
705  }
706  }
707  }
708  }
709 
710  // Propagate contacts
711  if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) // Get contact from origin object
712  {
713  $originforcontact = $this->origin;
714  $originidforcontact = $this->origin_id;
715  if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
716  {
717  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
718  $exp = new Expedition($this->db);
719  $exp->fetch($this->origin_id);
720  $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
721  if (count($exp->linkedObjectsIds['commande']) > 0)
722  {
723  foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
724  {
725  $originforcontact = 'commande';
726  if (is_object($value)) $originidforcontact = $value->id;
727  else $originidforcontact = $value;
728  break; // We take first one
729  }
730  }
731  }
732 
733  $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";
734  $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
735 
736  $resqlcontact = $this->db->query($sqlcontact);
737  if ($resqlcontact)
738  {
739  while ($objcontact = $this->db->fetch_object($resqlcontact))
740  {
741  //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
742  $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
743  }
744  } else dol_print_error($resqlcontact);
745  }
746 
747  /*
748  * Insert lines of invoices, if not from template invoice, into database
749  */
750  if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode)
751  {
752  $fk_parent_line = 0;
753 
754  dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
755  foreach ($this->lines as $i => $val)
756  {
757  $newinvoiceline = $this->lines[$i];
758  $newinvoiceline->fk_facture = $this->id;
759 
760  $newinvoiceline->origin = $this->lines[$i]->element;
761  $newinvoiceline->origin_id = $this->lines[$i]->id;
762 
763  // Auto set date of service ?
764  if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only
765  {
766  $newinvoiceline->date_start = $originaldatewhen;
767  }
768  if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) // $previousdaynextdatewhen is defined when generating from recurring invoice only
769  {
770  $newinvoiceline->date_end = $previousdaynextdatewhen;
771  }
772 
773  if ($result >= 0)
774  {
775  // Reset fk_parent_line for no child products and special product
776  if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
777  $fk_parent_line = 0;
778  }
779 
780  $newinvoiceline->fk_parent_line = $fk_parent_line;
781 
782  if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
783  $discount = new DiscountAbsolute($this->db);
784  $discount->fetch($newinvoiceline->fk_remise_except);
785 
786  $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
787  $newinvoiceline->fk_remise_except = $discountId;
788  }
789 
790  $result = $newinvoiceline->insert();
791 
792  // Defined the new fk_parent_line
793  if ($result > 0 && $newinvoiceline->product_type == 9) {
794  $fk_parent_line = $result;
795  }
796  }
797  if ($result < 0)
798  {
799  $this->error = $newinvoiceline->error;
800  $this->errors = $newinvoiceline->errors;
801  $error++;
802  break;
803  }
804  }
805  } elseif (!$error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays
806  {
807  $fk_parent_line = 0;
808 
809  dol_syslog("There is ".count($this->lines)." lines that are array lines");
810 
811  foreach ($this->lines as $i => $val)
812  {
813  $line = $this->lines[$i];
814 
815  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
816  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
817  if (!is_object($line)) $line = (object) $line;
818 
819  if ($result >= 0)
820  {
821  // Reset fk_parent_line for no child products and special product
822  if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
823  $fk_parent_line = 0;
824  }
825 
826  // Complete vat rate with code
827  $vatrate = $line->tva_tx;
828  if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')';
829 
830  if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
831  $originid = $line->origin_id;
832  $origintype = $line->origin;
833  } else {
834  $originid = $line->id;
835  $origintype = $this->element;
836  }
837 
838  // init ref_ext
839  if (empty($line->ref_ext)) {
840  $line->ref_ext = '';
841  }
842 
843  $result = $this->addline(
844  $line->desc,
845  $line->subprice,
846  $line->qty,
847  $vatrate,
848  $line->localtax1_tx,
849  $line->localtax2_tx,
850  $line->fk_product,
851  $line->remise_percent,
852  $line->date_start,
853  $line->date_end,
854  $line->fk_code_ventilation,
855  $line->info_bits,
856  $line->fk_remise_except,
857  'HT',
858  0,
859  $line->product_type,
860  $line->rang,
861  $line->special_code,
862  $origintype,
863  $originid,
864  $fk_parent_line,
865  $line->fk_fournprice,
866  $line->pa_ht,
867  $line->label,
868  $line->array_options,
869  $line->situation_percent,
870  $line->fk_prev_id,
871  $line->fk_unit,
872  $line->multicurrency_subprice,
873  $line->ref_ext
874  );
875  if ($result < 0)
876  {
877  $this->error = $this->db->lasterror();
878  dol_print_error($this->db);
879  $this->db->rollback();
880  return -1;
881  }
882 
883  // Defined the new fk_parent_line
884  if ($result > 0 && $line->product_type == 9) {
885  $fk_parent_line = $result;
886  }
887  }
888  }
889  }
890 
891  /*
892  * Insert lines of template invoices
893  */
894  if (!$error && $this->fac_rec > 0)
895  {
896  foreach ($_facrec->lines as $i => $val)
897  {
898  if ($_facrec->lines[$i]->fk_product)
899  {
900  $prod = new Product($this->db);
901  $res = $prod->fetch($_facrec->lines[$i]->fk_product);
902  }
903 
904  // For line from template invoice, we use data from template invoice
905  /*
906  $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
907  $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
908  if (empty($tva_tx)) $tva_npr=0;
909  $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
910  $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
911  */
912  $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
913  $tva_npr = $_facrec->lines[$i]->info_bits;
914  if (empty($tva_tx)) $tva_npr = 0;
915  $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
916  $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
917 
918  $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
919  $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
920 
921  // If buyprice not defined from template invoice, we try to guess the best value
922  if (!$buyprice && $_facrec->lines[$i]->fk_product > 0)
923  {
924  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
925  $producttmp = new ProductFournisseur($this->db);
926  $producttmp->fetch($_facrec->lines[$i]->fk_product);
927 
928  // If margin module defined on costprice, we try the costprice
929  // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
930  // else we get the best supplier price
931  if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price;
932  elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp;
933  else {
934  if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0)
935  {
936  if ($producttmp->product_fourn_price_id > 0)
937  {
938  $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
939  }
940  }
941  }
942  }
943 
944  $result_insert = $this->addline(
945  $_facrec->lines[$i]->desc,
946  $_facrec->lines[$i]->subprice,
947  $_facrec->lines[$i]->qty,
948  $tva_tx,
949  $localtax1_tx,
950  $localtax2_tx,
951  $_facrec->lines[$i]->fk_product,
952  $_facrec->lines[$i]->remise_percent,
953  ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
954  ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
955  0,
956  $tva_npr,
957  '',
958  'HT',
959  0,
960  $_facrec->lines[$i]->product_type,
961  $_facrec->lines[$i]->rang,
962  $_facrec->lines[$i]->special_code,
963  '',
964  0,
965  0,
966  $fk_product_fournisseur_price,
967  $buyprice,
968  $_facrec->lines[$i]->label,
969  empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options,
970  $_facrec->lines[$i]->situation_percent,
971  '',
972  $_facrec->lines[$i]->fk_unit,
973  $_facrec->lines[$i]->multicurrency_subprice
974  );
975 
976  if ($result_insert < 0)
977  {
978  $error++;
979  $this->error = $this->db->error();
980  break;
981  }
982  }
983  }
984 
985  if (!$error)
986  {
987  $result = $this->update_price(1);
988 
989  if ($result > 0)
990  {
991  $action = 'create';
992 
993  // Actions on extra fields
994  if (!$error)
995  {
996  $result = $this->insertExtraFields();
997  if ($result < 0) $error++;
998  }
999 
1000  if (!$error && !$notrigger)
1001  {
1002  // Call trigger
1003  $result = $this->call_trigger('BILL_CREATE', $user);
1004  if ($result < 0) $error++;
1005  // End call triggers
1006  }
1007 
1008  if (!$error)
1009  {
1010  $this->db->commit();
1011  return $this->id;
1012  } else {
1013  $this->db->rollback();
1014  return -4;
1015  }
1016  } else {
1017  $this->error = $langs->trans('FailedToUpdatePrice');
1018  $this->db->rollback();
1019  return -3;
1020  }
1021  } else {
1022  dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
1023  $this->db->rollback();
1024  return -2;
1025  }
1026  } else {
1027  $this->error = $this->db->error();
1028  $this->db->rollback();
1029  return -1;
1030  }
1031  }
1032 
1033 
1041  public function createFromCurrent(User $user, $invertdetail = 0)
1042  {
1043  global $conf;
1044 
1045  // Charge facture source
1046  $facture = new Facture($this->db);
1047 
1048  // Retrieve all extrafield
1049  // fetch optionals attributes and labels
1050  $this->fetch_optionals();
1051 
1052  if (!empty($this->array_options)) {
1053  $facture->array_options = $this->array_options;
1054  }
1055 
1056  foreach ($this->lines as &$line) {
1057  $line->fetch_optionals(); //fetch extrafields
1058  }
1059 
1060  $facture->fk_facture_source = $this->fk_facture_source;
1061  $facture->type = $this->type;
1062  $facture->socid = $this->socid;
1063  $facture->date = $this->date;
1064  $facture->date_pointoftax = $this->date_pointoftax;
1065  $facture->note_public = $this->note_public;
1066  $facture->note_private = $this->note_private;
1067  $facture->ref_client = $this->ref_client;
1068  $facture->modelpdf = $this->modelpdf; // deprecated
1069  $facture->model_pdf = $this->modelpdf;
1070  $facture->fk_project = $this->fk_project;
1071  $facture->cond_reglement_id = $this->cond_reglement_id;
1072  $facture->mode_reglement_id = $this->mode_reglement_id;
1073  $facture->remise_absolue = $this->remise_absolue;
1074  $facture->remise_percent = $this->remise_percent;
1075 
1076  $facture->origin = $this->origin;
1077  $facture->origin_id = $this->origin_id;
1078 
1079  $facture->lines = $this->lines; // Array of lines of invoice
1080  $facture->situation_counter = $this->situation_counter;
1081  $facture->situation_cycle_ref = $this->situation_cycle_ref;
1082  $facture->situation_final = $this->situation_final;
1083 
1084  $facture->retained_warranty = $this->retained_warranty;
1085  $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1086  $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1087 
1088  $facture->fk_user_author = $user->id;
1089 
1090 
1091  // Loop on each line of new invoice
1092  foreach ($facture->lines as $i => $tmpline)
1093  {
1094  $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1095  if ($invertdetail)
1096  {
1097  $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1098  $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1099  $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1100  $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1101  $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1102  $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1103  $facture->lines[$i]->ref_ext = '';
1104  }
1105  }
1106 
1107  dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1108 
1109  $facid = $facture->create($user);
1110  if ($facid <= 0)
1111  {
1112  $this->error = $facture->error;
1113  $this->errors = $facture->errors;
1114  } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
1115  {
1116  $this->fetchObjectLinked('', '', $this->id, 'facture');
1117 
1118  foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object)
1119  {
1120  foreach ($Tfk_object as $fk_object)
1121  {
1122  $facture->add_object_linked($typeObject, $fk_object);
1123  }
1124  }
1125 
1126  $facture->add_object_linked('facture', $this->fk_facture_source);
1127  }
1128 
1129  return $facid;
1130  }
1131 
1132 
1140  public function createFromClone(User $user, $fromid = 0)
1141  {
1142  global $conf, $hookmanager;
1143 
1144  $error = 0;
1145 
1146  $object = new Facture($this->db);
1147 
1148  $this->db->begin();
1149 
1150  $object->fetch($fromid);
1151 
1152  // Change socid if needed
1153  if (!empty($this->socid) && $this->socid != $object->socid)
1154  {
1155  $objsoc = new Societe($this->db);
1156 
1157  if ($objsoc->fetch($this->socid) > 0)
1158  {
1159  $object->socid = $objsoc->id;
1160  $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1161  $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1162  $object->fk_project = '';
1163  $object->fk_delivery_address = '';
1164  }
1165 
1166  // TODO Change product price if multi-prices
1167  }
1168 
1169  $object->id = 0;
1170  $object->statut = self::STATUS_DRAFT;
1171  $object->status = self::STATUS_DRAFT;
1172 
1173  // Clear fields
1174  $object->date = (empty($this->date) ? dol_now() : $this->date);
1175  $object->user_author = $user->id; // deprecated
1176  $object->user_valid = null; // deprecated
1177  $object->fk_user_author = $user->id;
1178  $object->fk_user_valid = null;
1179  $object->fk_facture_source = 0;
1180  $object->date_creation = '';
1181  $object->date_modification = '';
1182  $object->date_validation = '';
1183  $object->ref_client = '';
1184  $object->close_code = '';
1185  $object->close_note = '';
1186  if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
1187  $object->note_private = '';
1188  $object->note_public = '';
1189  }
1190 
1191  // Loop on each line of new invoice
1192  foreach ($object->lines as $i => $line)
1193  {
1194  if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts
1195  {
1196  unset($object->lines[$i]);
1197  continue;
1198  }
1199 
1200  // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month)
1201  // If it's a service with start and end dates
1202  if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1203  // Get the dates
1204  $start = dol_getdate($line->date_start);
1205  $end = dol_getdate($line->date_end);
1206 
1207  // Get the first and last day of the month
1208  $first = dol_get_first_day($start['year'], $start['mon']);
1209  $last = dol_get_last_day($end['year'], $end['mon']);
1210 
1211  //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1212  //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1213  // If start date is first date of month and end date is last date of month
1214  if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1215  && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1216  $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1217  $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1218  $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1219  $object->lines[$i]->date_start = $newFirst;
1220  $object->lines[$i]->date_end = $newLast;
1221  }
1222  }
1223 
1224  $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1225  }
1226 
1227  // Create clone
1228  $object->context['createfromclone'] = 'createfromclone';
1229  $result = $object->create($user);
1230  if ($result < 0) $error++;
1231  else {
1232  // copy internal contacts
1233  if ($object->copy_linked_contact($this, 'internal') < 0)
1234  $error++;
1235 
1236  // copy external contacts if same company
1237  elseif ($this->socid == $object->socid)
1238  {
1239  if ($object->copy_linked_contact($this, 'external') < 0)
1240  $error++;
1241  }
1242  }
1243 
1244  if (!$error)
1245  {
1246  // Hook of thirdparty module
1247  if (is_object($hookmanager))
1248  {
1249  $parameters = array('objFrom'=>$this);
1250  $action = '';
1251  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1252  if ($reshook < 0) $error++;
1253  }
1254  }
1255 
1256  unset($object->context['createfromclone']);
1257 
1258  // End
1259  if (!$error)
1260  {
1261  $this->db->commit();
1262  return $object->id;
1263  } else {
1264  $this->db->rollback();
1265  return -1;
1266  }
1267  }
1268 
1276  public function createFromOrder($object, User $user)
1277  {
1278  global $conf, $hookmanager;
1279 
1280  $error = 0;
1281 
1282  // Closed order
1283  $this->date = dol_now();
1284  $this->source = 0;
1285 
1286  $num = count($object->lines);
1287  for ($i = 0; $i < $num; $i++)
1288  {
1289  $line = new FactureLigne($this->db);
1290 
1291  $line->libelle = $object->lines[$i]->libelle; // deprecated
1292  $line->label = $object->lines[$i]->label;
1293  $line->desc = $object->lines[$i]->desc;
1294  $line->subprice = $object->lines[$i]->subprice;
1295  $line->total_ht = $object->lines[$i]->total_ht;
1296  $line->total_tva = $object->lines[$i]->total_tva;
1297  $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1298  $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1299  $line->total_ttc = $object->lines[$i]->total_ttc;
1300  $line->vat_src_code = $object->lines[$i]->vat_src_code;
1301  $line->tva_tx = $object->lines[$i]->tva_tx;
1302  $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1303  $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1304  $line->qty = $object->lines[$i]->qty;
1305  $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1306  $line->remise_percent = $object->lines[$i]->remise_percent;
1307  $line->fk_product = $object->lines[$i]->fk_product;
1308  $line->info_bits = $object->lines[$i]->info_bits;
1309  $line->product_type = $object->lines[$i]->product_type;
1310  $line->rang = $object->lines[$i]->rang;
1311  $line->special_code = $object->lines[$i]->special_code;
1312  $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1313  $line->fk_unit = $object->lines[$i]->fk_unit;
1314  $line->date_start = $object->lines[$i]->date_start;
1315  $line->date_end = $object->lines[$i]->date_end;
1316 
1317  // Multicurrency
1318  $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1319  $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1320  $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1321  $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1322  $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1323  $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1324 
1325  $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1326  $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);
1327  $line->pa_ht = $marginInfos[0];
1328 
1329  // get extrafields from original line
1330  $object->lines[$i]->fetch_optionals();
1331  foreach ($object->lines[$i]->array_options as $options_key => $value) {
1332  $line->array_options[$options_key] = $value;
1333  }
1334 
1335  $this->lines[$i] = $line;
1336  }
1337 
1338  $this->socid = $object->socid;
1339  $this->fk_project = $object->fk_project;
1340  $this->fk_account = $object->fk_account;
1341  $this->cond_reglement_id = $object->cond_reglement_id;
1342  $this->mode_reglement_id = $object->mode_reglement_id;
1343  $this->availability_id = $object->availability_id;
1344  $this->demand_reason_id = $object->demand_reason_id;
1345  $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1346  $this->date_livraison = $object->delivery_date; // deprecated
1347  $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1348  $this->contact_id = $object->contact_id;
1349  $this->ref_client = $object->ref_client;
1350 
1351  if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN))
1352  {
1353  $this->note_private = $object->note_private;
1354  $this->note_public = $object->note_public;
1355  }
1356 
1357  $this->module_source = $object->module_source;
1358  $this->pos_source = $object->pos_source;
1359 
1360  $this->origin = $object->element;
1361  $this->origin_id = $object->id;
1362 
1363  $this->fk_user_author = $user->id;
1364 
1365  // get extrafields from original line
1366  $object->fetch_optionals();
1367  foreach ($object->array_options as $options_key => $value)
1368  $this->array_options[$options_key] = $value;
1369 
1370  // Possibility to add external linked objects with hooks
1371  $this->linked_objects[$this->origin] = $this->origin_id;
1372  if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects))
1373  {
1374  $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1375  }
1376 
1377  $ret = $this->create($user);
1378 
1379  if ($ret > 0) {
1380  // Actions hooked (by external module)
1381  $hookmanager->initHooks(array('invoicedao'));
1382 
1383  $parameters = array('objFrom'=>$object);
1384  $action = '';
1385  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1386  if ($reshook < 0) $error++;
1387 
1388  if (!$error)
1389  {
1390  return 1;
1391  } else return -1;
1392  } else return -1;
1393  }
1394 
1409  public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
1410  {
1411  global $langs, $conf, $user, $mysoc;
1412 
1413  if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
1414 
1415  $result = '';
1416 
1417  if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1418  else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
1419 
1420  if (!$user->rights->facture->lire)
1421  $option = 'nolink';
1422 
1423  if ($option !== 'nolink')
1424  {
1425  // Add param to save lastsearch_values or not
1426  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1427  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1428  if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1429  }
1430 
1431  if ($short) return $url;
1432 
1433  $picto = $this->picto;
1434  if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice
1435  if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note
1436  if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice
1437  $label = '';
1438 
1439  if ($user->rights->facture->lire) {
1440  $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
1441  if ($this->type == self::TYPE_REPLACEMENT) $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("ReplacementInvoice").'</u>';
1442  if ($this->type == self::TYPE_CREDIT_NOTE) $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
1443  if ($this->type == self::TYPE_DEPOSIT) $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
1444  if ($this->type == self::TYPE_SITUATION) $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceSituation").'</u>';
1445  if (isset($this->statut) && isset($this->alreadypaid)) {
1446  $label .= ' '.$this->getLibStatut(5, $this->alreadypaid);
1447  }
1448  if (!empty($this->ref))
1449  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1450  if (!empty($this->ref_client))
1451  $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
1452  if (!empty($this->date))
1453  $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1454  if (!empty($this->total_ht))
1455  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1456  if (!empty($this->total_tva))
1457  $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1458  if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
1459  $label .= '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1460  if (!empty($this->total_localtax2) && $this->total_localtax2 != 0)
1461  $label .= '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1462  if (!empty($this->total_ttc))
1463  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1464  if ($moretitle) $label .= ' - '.$moretitle;
1465  }
1466 
1467  $linkclose = ($target ? ' target="'.$target.'"' : '');
1468  if (empty($notooltip) && $user->rights->facture->lire)
1469  {
1470  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1471  {
1472  $label = $langs->trans("Invoice");
1473  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1474  }
1475  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1476  $linkclose .= ' class="classfortooltip"';
1477  }
1478 
1479  $linkstart = '<a href="'.$url.'"';
1480  $linkstart .= $linkclose.'>';
1481  $linkend = '</a>';
1482 
1483  if ($option == 'nolink') {
1484  $linkstart = '';
1485  $linkend = '';
1486  }
1487 
1488  $result .= $linkstart;
1489  if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1490  if ($withpicto != 2) $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref);
1491  $result .= $linkend;
1492 
1493  if ($addlinktonotes)
1494  {
1495  $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1496  if ($txttoshow)
1497  {
1498  //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1499  $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
1500  $result .= ' <span class="note inline-block">';
1501  $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
1502  $result .= img_picto('', 'note');
1503  $result .= '</a>';
1504  //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1505  //$result.='</a>';
1506  $result .= '</span>';
1507  }
1508  }
1509 
1510  return $result;
1511  }
1512 
1523  public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false)
1524  {
1525  global $conf;
1526 
1527  if (empty($rowid) && empty($ref) && empty($ref_ext)) return -1;
1528 
1529  $sql = 'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc';
1530  $sql .= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp';
1531  $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
1532  $sql .= ', f.datef as df, f.date_pointoftax';
1533  $sql .= ', f.date_lim_reglement as dlr';
1534  $sql .= ', f.datec as datec';
1535  $sql .= ', f.date_valid as datev';
1536  $sql .= ', f.tms as datem';
1537  $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.model_pdf, f.last_main_doc';
1538  $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
1539  $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1540  $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1541  $sql .= ', f.fk_account';
1542  $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1543  $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1544  $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1545  $sql .= ', f.fk_incoterms, f.location_incoterms';
1546  $sql .= ', f.module_source, f.pos_source';
1547  $sql .= ", i.libelle as label_incoterms";
1548  $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";
1549  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
1550  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1551  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
1552  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
1553 
1554  if ($rowid) $sql .= " WHERE f.rowid=".$rowid;
1555  else {
1556  $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Dont't use entity if you use rowid
1557  if ($ref) $sql .= " AND f.ref='".$this->db->escape($ref)."'";
1558  if ($ref_ext) $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
1559  if ($notused) $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated
1560  }
1561 
1562  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1563  $result = $this->db->query($sql);
1564  if ($result)
1565  {
1566  if ($this->db->num_rows($result))
1567  {
1568  $obj = $this->db->fetch_object($result);
1569 
1570  $this->id = $obj->rowid;
1571  $this->entity = $obj->entity;
1572 
1573  $this->ref = $obj->ref;
1574  $this->ref_client = $obj->ref_client;
1575  $this->ref_ext = $obj->ref_ext;
1576  $this->type = $obj->type;
1577  $this->date = $this->db->jdate($obj->df);
1578  $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
1579  $this->date_creation = $this->db->jdate($obj->datec);
1580  $this->date_validation = $this->db->jdate($obj->datev);
1581  $this->date_modification = $this->db->jdate($obj->datem);
1582  $this->datem = $this->db->jdate($obj->datem);
1583  $this->remise_percent = $obj->remise_percent;
1584  $this->remise_absolue = $obj->remise_absolue;
1585  $this->total_ht = $obj->total;
1586  $this->total_tva = $obj->tva;
1587  $this->total_localtax1 = $obj->localtax1;
1588  $this->total_localtax2 = $obj->localtax2;
1589  $this->total_ttc = $obj->total_ttc;
1590  $this->revenuestamp = $obj->revenuestamp;
1591  $this->paye = $obj->paye;
1592  $this->close_code = $obj->close_code;
1593  $this->close_note = $obj->close_note;
1594 
1595  $this->socid = $obj->fk_soc;
1596  $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
1597 
1598  $this->fk_project = $obj->fk_project;
1599  $this->project = null; // Clear if another value was already set by fetch_projet
1600 
1601  $this->statut = $obj->fk_statut;
1602  $this->status = $obj->fk_statut;
1603 
1604  $this->date_lim_reglement = $this->db->jdate($obj->dlr);
1605  $this->mode_reglement_id = $obj->fk_mode_reglement;
1606  $this->mode_reglement_code = $obj->mode_reglement_code;
1607  $this->mode_reglement = $obj->mode_reglement_libelle;
1608  $this->cond_reglement_id = $obj->fk_cond_reglement;
1609  $this->cond_reglement_code = $obj->cond_reglement_code;
1610  $this->cond_reglement = $obj->cond_reglement_libelle;
1611  $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1612  $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1613  $this->fk_facture_source = $obj->fk_facture_source;
1614  $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
1615  $this->note = $obj->note_private; // deprecated
1616  $this->note_private = $obj->note_private;
1617  $this->note_public = $obj->note_public;
1618  $this->user_author = $obj->fk_user_author; // deprecated
1619  $this->user_valid = $obj->fk_user_valid; // deprecated
1620  $this->fk_user_author = $obj->fk_user_author;
1621  $this->fk_user_valid = $obj->fk_user_valid;
1622  $this->model_pdf = $obj->model_pdf;
1623  $this->modelpdf = $obj->model_pdf; // deprecated
1624  $this->last_main_doc = $obj->last_main_doc;
1625  $this->situation_cycle_ref = $obj->situation_cycle_ref;
1626  $this->situation_counter = $obj->situation_counter;
1627  $this->situation_final = $obj->situation_final;
1628  $this->retained_warranty = $obj->retained_warranty;
1629  $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
1630  $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
1631 
1632  $this->extraparams = (array) json_decode($obj->extraparams, true);
1633 
1634  //Incoterms
1635  $this->fk_incoterms = $obj->fk_incoterms;
1636  $this->location_incoterms = $obj->location_incoterms;
1637  $this->label_incoterms = $obj->label_incoterms;
1638 
1639  $this->module_source = $obj->module_source;
1640  $this->pos_source = $obj->pos_source;
1641 
1642  // Multicurrency
1643  $this->fk_multicurrency = $obj->fk_multicurrency;
1644  $this->multicurrency_code = $obj->multicurrency_code;
1645  $this->multicurrency_tx = $obj->multicurrency_tx;
1646  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1647  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1648  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1649 
1650  if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation)
1651  {
1653  }
1654 
1655  if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
1656 
1657  // Retrieve all extrafield
1658  // fetch optionals attributes and labels
1659  $this->fetch_optionals();
1660 
1661  // Lines
1662  $this->lines = array();
1663 
1664  $result = $this->fetch_lines();
1665  if ($result < 0)
1666  {
1667  $this->error = $this->db->error();
1668  return -3;
1669  }
1670  return 1;
1671  } else {
1672  $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
1673  dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
1674  return 0;
1675  }
1676  } else {
1677  $this->error = $this->db->error();
1678  return -1;
1679  }
1680  }
1681 
1682 
1683  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1692  public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
1693  {
1694  global $langs, $conf;
1695  // phpcs:enable
1696  $this->lines = array();
1697 
1698  $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,';
1699  $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,';
1700  $sql .= ' l.situation_percent, l.fk_prev_id,';
1701  $sql .= ' l.rang, l.special_code,';
1702  $sql .= ' l.date_start as date_start, l.date_end as date_end,';
1703  $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,';
1704  $sql .= ' l.fk_unit,';
1705  $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1706  $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
1707  $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
1708  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
1709  $sql .= ' WHERE l.fk_facture = '.$this->id;
1710  $sql .= ' ORDER BY l.rang, l.rowid';
1711 
1712  dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
1713  $result = $this->db->query($sql);
1714  if ($result)
1715  {
1716  $num = $this->db->num_rows($result);
1717  $i = 0;
1718  while ($i < $num)
1719  {
1720  $objp = $this->db->fetch_object($result);
1721  $line = new FactureLigne($this->db);
1722 
1723  $line->id = $objp->rowid;
1724  $line->rowid = $objp->rowid; // deprecated
1725  $line->fk_facture = $objp->fk_facture;
1726  $line->label = $objp->custom_label; // deprecated
1727  $line->desc = $objp->description; // Description line
1728  $line->description = $objp->description; // Description line
1729  $line->product_type = $objp->product_type; // Type of line
1730  $line->ref = $objp->product_ref; // Ref product
1731  $line->product_ref = $objp->product_ref; // Ref product
1732  $line->libelle = $objp->product_label; // deprecated
1733  $line->product_label = $objp->product_label; // Label product
1734  $line->product_desc = $objp->product_desc; // Description product
1735  $line->fk_product_type = $objp->fk_product_type; // Type of product
1736  $line->qty = $objp->qty;
1737  $line->subprice = $objp->subprice;
1738  $line->ref_ext = $objp->ref_ext; // line external ref
1739 
1740  $line->vat_src_code = $objp->vat_src_code;
1741  $line->tva_tx = $objp->tva_tx;
1742  $line->localtax1_tx = $objp->localtax1_tx;
1743  $line->localtax2_tx = $objp->localtax2_tx;
1744  $line->localtax1_type = $objp->localtax1_type;
1745  $line->localtax2_type = $objp->localtax2_type;
1746  $line->remise_percent = $objp->remise_percent;
1747  $line->fk_remise_except = $objp->fk_remise_except;
1748  $line->fk_product = $objp->fk_product;
1749  $line->date_start = $this->db->jdate($objp->date_start);
1750  $line->date_end = $this->db->jdate($objp->date_end);
1751  $line->date_start = $this->db->jdate($objp->date_start);
1752  $line->date_end = $this->db->jdate($objp->date_end);
1753  $line->info_bits = $objp->info_bits;
1754  $line->total_ht = $objp->total_ht;
1755  $line->total_tva = $objp->total_tva;
1756  $line->total_localtax1 = $objp->total_localtax1;
1757  $line->total_localtax2 = $objp->total_localtax2;
1758  $line->total_ttc = $objp->total_ttc;
1759  $line->code_ventilation = $objp->fk_code_ventilation;
1760  $line->fk_fournprice = $objp->fk_fournprice;
1761  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1762  $line->pa_ht = $marginInfos[0];
1763  $line->marge_tx = $marginInfos[1];
1764  $line->marque_tx = $marginInfos[2];
1765  $line->rang = $objp->rang;
1766  $line->special_code = $objp->special_code;
1767  $line->fk_parent_line = $objp->fk_parent_line;
1768  $line->situation_percent = $objp->situation_percent;
1769  $line->fk_prev_id = $objp->fk_prev_id;
1770  $line->fk_unit = $objp->fk_unit;
1771 
1772  // Accountancy
1773  $line->fk_accounting_account = $objp->fk_code_ventilation;
1774 
1775  // Multicurrency
1776  $line->fk_multicurrency = $objp->fk_multicurrency;
1777  $line->multicurrency_code = $objp->multicurrency_code;
1778  $line->multicurrency_subprice = $objp->multicurrency_subprice;
1779  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
1780  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
1781  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
1782 
1783  $line->fetch_optionals();
1784 
1785  // multilangs
1786  if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
1787  $line = new Product($this->db);
1788  $line->fetch($objp->fk_product);
1789  $line->getMultiLangs();
1790  }
1791 
1792  $this->lines[$i] = $line;
1793 
1794  $i++;
1795  }
1796  $this->db->free($result);
1797  return 1;
1798  } else {
1799  $this->error = $this->db->error();
1800  return -3;
1801  }
1802  }
1803 
1811  {
1812  global $conf;
1813 
1814  $this->tab_previous_situation_invoice = array();
1815  $this->tab_next_situation_invoice = array();
1816 
1817  $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
1818  $sql .= ' WHERE rowid <> '.$this->id;
1819  $sql .= ' AND entity = '.$this->entity;
1820  $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
1821  $sql .= ' ORDER BY situation_counter ASC';
1822 
1823  dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
1824  $result = $this->db->query($sql);
1825  if ($result && $this->db->num_rows($result) > 0)
1826  {
1827  while ($objp = $this->db->fetch_object($result))
1828  {
1829  $invoice = new Facture($this->db);
1830  if ($invoice->fetch($objp->rowid) > 0)
1831  {
1832  if ($objp->situation_counter < $this->situation_counter
1833  || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
1834  )
1835  {
1836  $this->tab_previous_situation_invoice[] = $invoice;
1837  } else {
1838  $this->tab_next_situation_invoice[] = $invoice;
1839  }
1840  }
1841  }
1842  }
1843  }
1844 
1852  public function update(User $user, $notrigger = 0)
1853  {
1854  global $conf;
1855 
1856  $error = 0;
1857 
1858  // Clean parameters
1859  if (empty($this->type)) $this->type = self::TYPE_STANDARD;
1860  if (isset($this->ref)) $this->ref = trim($this->ref);
1861  if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext);
1862  if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client);
1863  if (isset($this->increment)) $this->increment = trim($this->increment);
1864  if (isset($this->close_code)) $this->close_code = trim($this->close_code);
1865  if (isset($this->close_note)) $this->close_note = trim($this->close_note);
1866  if (isset($this->note) || isset($this->note_private)) $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
1867  if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1868  if (isset($this->note_public)) $this->note_public = trim($this->note_public);
1869  if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
1870  if (isset($this->import_key)) $this->import_key = trim($this->import_key);
1871  if (isset($this->retained_warranty)) $this->retained_warranty = floatval($this->retained_warranty);
1872 
1873 
1874  // Check parameters
1875  // Put here code to add control on parameters values
1876 
1877  // Update request
1878  $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
1879  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1880  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1881  $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
1882  $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
1883  $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
1884  $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
1885  $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1886  $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1887  $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
1888  $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1889  $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
1890  $sql .= " remise_percent=".(isset($this->remise_percent) ? $this->db->escape($this->remise_percent) : "null").",";
1891  $sql .= " remise_absolue=".(isset($this->remise_absolue) ? $this->db->escape($this->remise_absolue) : "null").",";
1892  $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
1893  $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
1894  $sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
1895  $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
1896  $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
1897  $sql .= " total=".(isset($this->total_ht) ? $this->total_ht : "null").",";
1898  $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
1899  $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? $this->db->escape($this->revenuestamp) : "null").",";
1900  $sql .= " fk_statut=".(isset($this->statut) ? $this->db->escape($this->statut) : "null").",";
1901  $sql .= " fk_user_author=".(isset($this->user_author) ? $this->db->escape($this->user_author) : "null").",";
1902  $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->db->escape($this->fk_user_valid) : "null").",";
1903  $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->db->escape($this->fk_facture_source) : "null").",";
1904  $sql .= " fk_projet=".(isset($this->fk_project) ? $this->db->escape($this->fk_project) : "null").",";
1905  $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->db->escape($this->cond_reglement_id) : "null").",";
1906  $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->db->escape($this->mode_reglement_id) : "null").",";
1907  $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
1908  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1909  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1910  $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1911  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
1912  $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : $this->db->escape($this->situation_cycle_ref)).",";
1913  $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : $this->db->escape($this->situation_counter)).",";
1914  $sql .= " situation_final=".(empty($this->situation_final) ? "0" : $this->db->escape($this->situation_final)).",";
1915  $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty)).",";
1916  $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
1917  $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) : "null");
1918  $sql .= " WHERE rowid=".$this->id;
1919 
1920  $this->db->begin();
1921 
1922  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1923  $resql = $this->db->query($sql);
1924  if (!$resql) {
1925  $error++; $this->errors[] = "Error ".$this->db->lasterror();
1926  }
1927 
1928  if (!$error)
1929  {
1930  $result = $this->insertExtraFields();
1931  if ($result < 0)
1932  {
1933  $error++;
1934  }
1935  }
1936 
1937  if (!$error && !$notrigger)
1938  {
1939  // Call trigger
1940  $result = $this->call_trigger('BILL_MODIFY', $user);
1941  if ($result < 0) $error++;
1942  // End call triggers
1943  }
1944 
1945  // Commit or rollback
1946  if ($error)
1947  {
1948  foreach ($this->errors as $errmsg)
1949  {
1950  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1951  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1952  }
1953  $this->db->rollback();
1954  return -1 * $error;
1955  } else {
1956  $this->db->commit();
1957  return 1;
1958  }
1959  }
1960 
1961 
1962  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1969  public function insert_discount($idremise)
1970  {
1971  // phpcs:enable
1972  global $langs;
1973 
1974  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1975  include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1976 
1977  $this->db->begin();
1978 
1979  $remise = new DiscountAbsolute($this->db);
1980  $result = $remise->fetch($idremise);
1981 
1982  if ($result > 0)
1983  {
1984  if ($remise->fk_facture) // Protection against multiple submission
1985  {
1986  $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
1987  $this->db->rollback();
1988  return -5;
1989  }
1990 
1991  $facligne = new FactureLigne($this->db);
1992  $facligne->fk_facture = $this->id;
1993  $facligne->fk_remise_except = $remise->id;
1994  $facligne->desc = $remise->description; // Description ligne
1995  $facligne->vat_src_code = $remise->vat_src_code;
1996  $facligne->tva_tx = $remise->tva_tx;
1997  $facligne->subprice = -$remise->amount_ht;
1998  $facligne->fk_product = 0; // Id produit predefini
1999  $facligne->qty = 1;
2000  $facligne->remise_percent = 0;
2001  $facligne->rang = -1;
2002  $facligne->info_bits = 2;
2003 
2004  // Get buy/cost price of invoice that is source of discount
2005  if ($remise->fk_facture_source > 0)
2006  {
2007  $srcinvoice = new Facture($this->db);
2008  $srcinvoice->fetch($remise->fk_facture_source);
2009  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2010  $formmargin = new FormMargin($this->db);
2011  $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2012  $facligne->pa_ht = $arraytmp['pa_total'];
2013  }
2014 
2015  $facligne->total_ht = -$remise->amount_ht;
2016  $facligne->total_tva = -$remise->amount_tva;
2017  $facligne->total_ttc = -$remise->amount_ttc;
2018 
2019  $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2020  $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2021  $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2022  $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2023 
2024  $lineid = $facligne->insert();
2025  if ($lineid > 0)
2026  {
2027  $result = $this->update_price(1);
2028  if ($result > 0)
2029  {
2030  // Create link between discount and invoice line
2031  $result = $remise->link_to_invoice($lineid, 0);
2032  if ($result < 0)
2033  {
2034  $this->error = $remise->error;
2035  $this->db->rollback();
2036  return -4;
2037  }
2038 
2039  $this->db->commit();
2040  return 1;
2041  } else {
2042  $this->error = $facligne->error;
2043  $this->db->rollback();
2044  return -1;
2045  }
2046  } else {
2047  $this->error = $facligne->error;
2048  $this->db->rollback();
2049  return -2;
2050  }
2051  } else {
2052  $this->db->rollback();
2053  return -3;
2054  }
2055  }
2056 
2057  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2065  public function set_ref_client($ref_client, $notrigger = 0)
2066  {
2067  // phpcs:enable
2068  global $user;
2069 
2070  $error = 0;
2071 
2072  $this->db->begin();
2073 
2074  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2075  if (empty($ref_client))
2076  $sql .= ' SET ref_client = NULL';
2077  else $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
2078  $sql .= ' WHERE rowid = '.$this->id;
2079 
2080  dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2081  $resql = $this->db->query($sql);
2082  if (!$resql)
2083  {
2084  $this->errors[] = $this->db->error();
2085  $error++;
2086  }
2087 
2088  if (!$error)
2089  {
2090  $this->ref_client = $ref_client;
2091  }
2092 
2093  if (!$notrigger && empty($error))
2094  {
2095  // Call trigger
2096  $result = $this->call_trigger('BILL_MODIFY', $user);
2097  if ($result < 0) $error++;
2098  // End call triggers
2099  }
2100 
2101  if (!$error)
2102  {
2103  $this->ref_client = $ref_client;
2104 
2105  $this->db->commit();
2106  return 1;
2107  } else {
2108  foreach ($this->errors as $errmsg)
2109  {
2110  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2111  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2112  }
2113  $this->db->rollback();
2114  return -1 * $error;
2115  }
2116  }
2117 
2126  public function delete($user, $notrigger = 0, $idwarehouse = -1)
2127  {
2128  global $langs, $conf;
2129  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2130 
2131  $rowid = $this->id;
2132 
2133  dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
2134 
2135  // Test to avoid invoice deletion (allowed if draft)
2136  $result = $this->is_erasable();
2137 
2138  if ($result <= 0) return 0;
2139 
2140  $error = 0;
2141 
2142  $this->db->begin();
2143 
2144  if (!$error && !$notrigger)
2145  {
2146  // Call trigger
2147  $result = $this->call_trigger('BILL_DELETE', $user);
2148  if ($result < 0) $error++;
2149  // End call triggers
2150  }
2151 
2152  // Removed extrafields
2153  if (!$error) {
2154  $result = $this->deleteExtraFields();
2155  if ($result < 0)
2156  {
2157  $error++;
2158  dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
2159  }
2160  }
2161 
2162  if (!$error)
2163  {
2164  // Delete linked object
2165  $res = $this->deleteObjectLinked();
2166  if ($res < 0) $error++;
2167  }
2168 
2169  if (!$error)
2170  {
2171  // If invoice was converted into a discount not yet consumed, we remove discount
2172  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
2173  $sql .= ' WHERE fk_facture_source = '.$rowid;
2174  $sql .= ' AND fk_facture_line IS NULL';
2175  $resql = $this->db->query($sql);
2176 
2177  // If invoice has consumned discounts
2178  $this->fetch_lines();
2179  $list_rowid_det = array();
2180  foreach ($this->lines as $key => $invoiceline)
2181  {
2182  $list_rowid_det[] = $invoiceline->id;
2183  }
2184 
2185  // Consumned discounts are freed
2186  if (count($list_rowid_det))
2187  {
2188  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2189  $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
2190  $sql .= ' WHERE fk_facture_line IN ('.join(',', $list_rowid_det).')';
2191 
2192  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2193  if (!$this->db->query($sql))
2194  {
2195  $this->error = $this->db->error()." sql=".$sql;
2196  $this->errors[] = $this->error;
2197  $this->db->rollback();
2198  return -5;
2199  }
2200  }
2201 
2202  // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
2203  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1)
2204  {
2205  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2206  $langs->load("agenda");
2207 
2208  $num = count($this->lines);
2209  for ($i = 0; $i < $num; $i++)
2210  {
2211  if ($this->lines[$i]->fk_product > 0)
2212  {
2213  $mouvP = new MouvementStock($this->db);
2214  $mouvP->origin = &$this;
2215  // We decrease stock for product
2216  if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
2217  else $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
2218  }
2219  }
2220  }
2221 
2222  // Invoice line extrafileds
2223  $main = MAIN_DB_PREFIX.'facturedet';
2224  $ef = $main."_extrafields";
2225  $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)";
2226  // Delete invoice line
2227  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.$rowid;
2228 
2229  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2230 
2231  if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact())
2232  {
2233  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.$rowid;
2234 
2235  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2236 
2237  $resql = $this->db->query($sql);
2238  if ($resql)
2239  {
2240  // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2241  $this->deleteEcmFiles();
2242 
2243  // On efface le repertoire de pdf provisoire
2244  $ref = dol_sanitizeFileName($this->ref);
2245  if ($conf->facture->dir_output && !empty($this->ref))
2246  {
2247  $dir = $conf->facture->dir_output."/".$ref;
2248  $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
2249  if (file_exists($file)) // We must delete all files before deleting directory
2250  {
2251  $ret = dol_delete_preview($this);
2252 
2253  if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
2254  {
2255  $langs->load("errors");
2256  $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
2257  $this->errors[] = $this->error;
2258  $this->db->rollback();
2259  return 0;
2260  }
2261  }
2262  if (file_exists($dir))
2263  {
2264  if (!dol_delete_dir_recursive($dir)) // For remove dir and meta
2265  {
2266  $langs->load("errors");
2267  $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
2268  $this->errors[] = $this->error;
2269  $this->db->rollback();
2270  return 0;
2271  }
2272  }
2273  }
2274 
2275  $this->db->commit();
2276  return 1;
2277  } else {
2278  $this->error = $this->db->lasterror()." sql=".$sql;
2279  $this->errors[] = $this->error;
2280  $this->db->rollback();
2281  return -6;
2282  }
2283  } else {
2284  $this->error = $this->db->lasterror()." sql=".$sql;
2285  $this->errors[] = $this->error;
2286  $this->db->rollback();
2287  return -4;
2288  }
2289  } else {
2290  $this->db->rollback();
2291  return -2;
2292  }
2293  }
2294 
2295  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2305  public function set_paid($user, $close_code = '', $close_note = '')
2306  {
2307  // phpcs:enable
2308  $error = 0;
2309 
2310  if ($this->paye != 1)
2311  {
2312  $this->db->begin();
2313 
2314  $now = dol_now();
2315 
2316  dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG);
2317 
2318  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2319  $sql .= ' fk_statut='.self::STATUS_CLOSED;
2320  if (!$close_code) $sql .= ', paye=1';
2321  if ($close_code) $sql .= ", close_code='".$this->db->escape($close_code)."'";
2322  if ($close_note) $sql .= ", close_note='".$this->db->escape($close_note)."'";
2323  $sql .= ', fk_user_closing = '.$user->id;
2324  $sql .= ", date_closing = '".$this->db->idate($now)."'";
2325  $sql .= ' WHERE rowid = '.$this->id;
2326 
2327  $resql = $this->db->query($sql);
2328  if ($resql)
2329  {
2330  // Call trigger
2331  $result = $this->call_trigger('BILL_PAYED', $user);
2332  if ($result < 0) $error++;
2333  // End call triggers
2334  } else {
2335  $error++;
2336  $this->error = $this->db->lasterror();
2337  }
2338 
2339  if (!$error)
2340  {
2341  $this->db->commit();
2342  return 1;
2343  } else {
2344  $this->db->rollback();
2345  return -1;
2346  }
2347  } else {
2348  return 0;
2349  }
2350  }
2351 
2352 
2353  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2362  public function set_unpaid($user)
2363  {
2364  // phpcs:enable
2365  $error = 0;
2366 
2367  $this->db->begin();
2368 
2369  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2370  $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
2371  $sql .= ' date_closing=null,';
2372  $sql .= ' fk_user_closing=null';
2373  $sql .= ' WHERE rowid = '.$this->id;
2374 
2375  dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
2376  $resql = $this->db->query($sql);
2377  if ($resql)
2378  {
2379  // Call trigger
2380  $result = $this->call_trigger('BILL_UNPAYED', $user);
2381  if ($result < 0) $error++;
2382  // End call triggers
2383  } else {
2384  $error++;
2385  $this->error = $this->db->error();
2386  dol_print_error($this->db);
2387  }
2388 
2389  if (!$error)
2390  {
2391  $this->db->commit();
2392  return 1;
2393  } else {
2394  $this->db->rollback();
2395  return -1;
2396  }
2397  }
2398 
2399 
2400  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2411  public function set_canceled($user, $close_code = '', $close_note = '')
2412  {
2413  // phpcs:enable
2414 
2415  dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG);
2416 
2417  $this->db->begin();
2418 
2419  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2420  $sql .= ' fk_statut='.self::STATUS_ABANDONED;
2421  if ($close_code) $sql .= ", close_code='".$this->db->escape($close_code)."'";
2422  if ($close_note) $sql .= ", close_note='".$this->db->escape($close_note)."'";
2423  $sql .= ' WHERE rowid = '.$this->id;
2424 
2425  $resql = $this->db->query($sql);
2426  if ($resql)
2427  {
2428  // On desaffecte de la facture les remises liees
2429  // car elles n'ont pas ete utilisees vu que la facture est abandonnee.
2430  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2431  $sql .= ' SET fk_facture = NULL';
2432  $sql .= ' WHERE fk_facture = '.$this->id;
2433 
2434  $resql = $this->db->query($sql);
2435  if ($resql)
2436  {
2437  // Call trigger
2438  $result = $this->call_trigger('BILL_CANCEL', $user);
2439  if ($result < 0)
2440  {
2441  $this->db->rollback();
2442  return -1;
2443  }
2444  // End call triggers
2445 
2446  $this->db->commit();
2447  return 1;
2448  } else {
2449  $this->error = $this->db->error()." sql=".$sql;
2450  $this->db->rollback();
2451  return -1;
2452  }
2453  } else {
2454  $this->error = $this->db->error()." sql=".$sql;
2455  $this->db->rollback();
2456  return -2;
2457  }
2458  }
2459 
2471  public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
2472  {
2473  global $conf, $langs;
2474  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2475 
2476  $productStatic = null;
2477  $warehouseStatic = null;
2478  if ($batch_rule > 0) {
2479  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2480  require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
2481  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2482  $productStatic = new Product($this->db);
2483  $warehouseStatic = new Entrepot($this->db);
2484  }
2485 
2486  $now = dol_now();
2487 
2488  $error = 0;
2489  dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
2490 
2491  // Force to have object complete for checks
2492  $this->fetch_thirdparty();
2493  $this->fetch_lines();
2494 
2495  // Check parameters
2496  if (!$this->brouillon)
2497  {
2498  dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
2499  return 0;
2500  }
2501  if (count($this->lines) <= 0)
2502  {
2503  $langs->load("errors");
2504  $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
2505  return -1;
2506  }
2507  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
2508  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate)))
2509  {
2510  $this->error = 'Permission denied';
2511  dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
2512  return -1;
2513  }
2514 
2515  $this->db->begin();
2516 
2517  // Check parameters
2518  if ($this->type == self::TYPE_REPLACEMENT) // if this is a replacement invoice
2519  {
2520  // Check that source invoice is known
2521  if ($this->fk_facture_source <= 0)
2522  {
2523  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
2524  $this->db->rollback();
2525  return -10;
2526  }
2527 
2528  // Load source invoice that has been replaced
2529  $facreplaced = new Facture($this->db);
2530  $result = $facreplaced->fetch($this->fk_facture_source);
2531  if ($result <= 0)
2532  {
2533  $this->error = $langs->trans("ErrorBadInvoice");
2534  $this->db->rollback();
2535  return -11;
2536  }
2537 
2538  // Check that source invoice not already replaced by another one.
2539  $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
2540  if ($idreplacement && $idreplacement != $this->id)
2541  {
2542  $facreplacement = new Facture($this->db);
2543  $facreplacement->fetch($idreplacement);
2544  $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
2545  $this->db->rollback();
2546  return -12;
2547  }
2548 
2549  $result = $facreplaced->set_canceled($user, self::CLOSECODE_REPLACED, '');
2550  if ($result < 0)
2551  {
2552  $this->error = $facreplaced->error;
2553  $this->db->rollback();
2554  return -13;
2555  }
2556  }
2557 
2558  // Define new ref
2559  if ($force_number)
2560  {
2561  $num = $force_number;
2562  } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
2563  {
2564  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
2565  {
2566  $this->date = dol_now();
2567  $this->date_lim_reglement = $this->calculate_date_lim_reglement();
2568  }
2569  $num = $this->getNextNumRef($this->thirdparty);
2570  } else {
2571  $num = $this->ref;
2572  }
2573  $this->newref = dol_sanitizeFileName($num);
2574 
2575  if ($num)
2576  {
2577  $this->update_price(1);
2578 
2579  // Validate
2580  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2581  $sql .= " SET ref='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? $user->id : "null").", date_valid = '".$this->db->idate($now)."'";
2582  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
2583  {
2584  $sql .= ", datef='".$this->db->idate($this->date)."'";
2585  $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
2586  }
2587  $sql .= ' WHERE rowid = '.$this->id;
2588 
2589  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
2590  $resql = $this->db->query($sql);
2591  if (!$resql)
2592  {
2593  dol_print_error($this->db);
2594  $error++;
2595  }
2596 
2597  // On verifie si la facture etait une provisoire
2598  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref)))
2599  {
2600  // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
2601  }
2602 
2603  if (!$error)
2604  {
2605  // Define third party as a customer
2606  $result = $this->thirdparty->set_as_client();
2607 
2608  // Si active on decremente le produit principal et ses composants a la validation de facture
2609  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0)
2610  {
2611  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2612  $langs->load("agenda");
2613 
2614  // Loop on each line
2615  $cpt = count($this->lines);
2616  for ($i = 0; $i < $cpt; $i++)
2617  {
2618  if ($this->lines[$i]->fk_product > 0)
2619  {
2620  $mouvP = new MouvementStock($this->db);
2621  $mouvP->origin = &$this;
2622  // We decrease stock for product
2623  if ($this->type == self::TYPE_CREDIT_NOTE) {
2624  $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num));
2625  if ($result < 0) {
2626  $error++;
2627  $this->error = $mouvP->error;
2628  }
2629  } else {
2630  $is_batch_line = false;
2631  if ($batch_rule > 0) {
2632  $productStatic->fetch($this->lines[$i]->fk_product);
2633  if ($productStatic->hasbatch()) {
2634  $is_batch_line = true;
2635  $product_qty_remain = $this->lines[$i]->qty;
2636 
2637  $sortfield = null;
2638  $sortorder = null;
2639  // find all batch order by sellby (DLC) and eatby dates (DLUO) first
2641  $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
2642  $sortorder = 'ASC,ASC,ASC,ASC';
2643  }
2644 
2645  $resBatchList = Productbatch::findAllForProduct($this->db, $productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder);
2646  if (!is_array($resBatchList)) {
2647  $error++;
2648  $this->error = $this->db->lasterror();
2649  }
2650 
2651  if (!$error) {
2652  $batchList = $resBatchList;
2653  if (empty($batchList)) {
2654  $error++;
2655  $langs->load('errors');
2656  $warehouseStatic->fetch($idwarehouse);
2657  $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
2658  dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
2659  }
2660 
2661  foreach ($batchList as $batch) {
2662  if ($batch->qty <= 0) continue; // try to decrement only batches have positive quantity first
2663 
2664  // enough quantity in this batch
2665  if ($batch->qty >= $product_qty_remain) {
2666  $product_batch_qty = $product_qty_remain;
2667  } // not enough (take all in batch)
2668  else {
2669  $product_batch_qty = $batch->qty;
2670  }
2671  $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
2672  if ($result < 0) {
2673  $error++;
2674  $this->error = $mouvP->error;
2675  break;
2676  }
2677 
2678  $product_qty_remain -= $product_batch_qty;
2679  // all product quantity was decremented
2680  if ($product_qty_remain <= 0) break;
2681  }
2682 
2683  if (!$error && $product_qty_remain > 0) {
2684  if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
2685  // take in the first batch
2686  $batch = $batchList[0];
2687  $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
2688  if ($result < 0) {
2689  $error++;
2690  $this->error = $mouvP->error;
2691  }
2692  } else {
2693  $error++;
2694  $langs->load('errors');
2695  $warehouseStatic->fetch($idwarehouse);
2696  $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
2697  dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
2698  }
2699  }
2700  }
2701  }
2702  }
2703 
2704  if (!$is_batch_line) {
2705  $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
2706  if ($result < 0) {
2707  $error++;
2708  $this->error = $mouvP->error;
2709  }
2710  }
2711  }
2712  }
2713  }
2714  }
2715  }
2716 
2717  // Trigger calls
2718  if (!$error && !$notrigger)
2719  {
2720  // Call trigger
2721  $result = $this->call_trigger('BILL_VALIDATE', $user);
2722  if ($result < 0) $error++;
2723  // End call triggers
2724  }
2725 
2726  if (!$error)
2727  {
2728  $this->oldref = $this->ref;
2729 
2730  // Rename directory if dir was a temporary ref
2731  if (preg_match('/^[\(]?PROV/i', $this->ref))
2732  {
2733  // Now we rename also files into index
2734  $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)."'";
2735  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
2736  $resql = $this->db->query($sql);
2737  if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
2738 
2739  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
2740  $oldref = dol_sanitizeFileName($this->ref);
2741  $newref = dol_sanitizeFileName($num);
2742  $dirsource = $conf->facture->dir_output.'/'.$oldref;
2743  $dirdest = $conf->facture->dir_output.'/'.$newref;
2744  if (!$error && file_exists($dirsource))
2745  {
2746  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
2747 
2748  if (@rename($dirsource, $dirdest))
2749  {
2750  dol_syslog("Rename ok");
2751  // Rename docs starting with $oldref with $newref
2752  $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
2753  foreach ($listoffiles as $fileentry)
2754  {
2755  $dirsource = $fileentry['name'];
2756  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
2757  $dirsource = $fileentry['path'].'/'.$dirsource;
2758  $dirdest = $fileentry['path'].'/'.$dirdest;
2759  @rename($dirsource, $dirdest);
2760  }
2761  }
2762  }
2763  }
2764  }
2765 
2766  if (!$error && !$this->is_last_in_cycle())
2767  {
2768  if (!$this->updatePriceNextInvoice($langs))
2769  {
2770  $error++;
2771  }
2772  }
2773 
2774  // Set new ref and define current status
2775  if (!$error)
2776  {
2777  $this->ref = $num;
2778  $this->ref = $num;
2779  $this->statut = self::STATUS_VALIDATED;
2780  $this->brouillon = 0;
2781  $this->date_validation = $now;
2782  $i = 0;
2783 
2784  if (!empty($conf->global->INVOICE_USE_SITUATION))
2785  {
2786  $final = true;
2787  $nboflines = count($this->lines);
2788  while (($i < $nboflines) && $final) {
2789  $final = ($this->lines[$i]->situation_percent == 100);
2790  $i++;
2791  }
2792 
2793  if (empty($final)) $this->situation_final = 0;
2794  else $this->situation_final = 1;
2795 
2796  $this->setFinal($user);
2797  }
2798  }
2799  } else {
2800  $error++;
2801  }
2802 
2803  if (!$error)
2804  {
2805  $this->db->commit();
2806  return 1;
2807  } else {
2808  $this->db->rollback();
2809  return -1;
2810  }
2811  }
2812 
2819  public function updatePriceNextInvoice(&$langs)
2820  {
2821  foreach ($this->tab_next_situation_invoice as $next_invoice)
2822  {
2823  $is_last = $next_invoice->is_last_in_cycle();
2824 
2825  if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1)
2826  {
2827  $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
2828  return false;
2829  }
2830 
2831  $next_invoice->brouillon = 1;
2832  foreach ($next_invoice->lines as $line)
2833  {
2834  $result = $next_invoice->updateline(
2835  $line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent,
2836  $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type,
2837  $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent,
2838  $line->fk_unit
2839  );
2840 
2841  if ($result < 0)
2842  {
2843  $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
2844  return false;
2845  }
2846  }
2847 
2848  break; // Only the next invoice and not each next invoice
2849  }
2850 
2851  return true;
2852  }
2853 
2861  public function setDraft($user, $idwarehouse = -1)
2862  {
2863  // phpcs:enable
2864  global $conf, $langs;
2865 
2866  $error = 0;
2867 
2868  if ($this->statut == self::STATUS_DRAFT)
2869  {
2870  dol_syslog(__METHOD__." already draft status", LOG_WARNING);
2871  return 0;
2872  }
2873 
2874  dol_syslog(__METHOD__, LOG_DEBUG);
2875 
2876  $this->db->begin();
2877 
2878  $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
2879  $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2880  $sql .= " WHERE rowid = ".$this->id;
2881 
2882  $result = $this->db->query($sql);
2883  if ($result)
2884  {
2885  if (!$error)
2886  {
2887  $this->oldcopy = clone $this;
2888  }
2889 
2890  // If we decrease stock on invoice validation, we increase back
2891  if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL))
2892  {
2893  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2894  $langs->load("agenda");
2895 
2896  $num = count($this->lines);
2897  for ($i = 0; $i < $num; $i++)
2898  {
2899  if ($this->lines[$i]->fk_product > 0)
2900  {
2901  $mouvP = new MouvementStock($this->db);
2902  $mouvP->origin = &$this;
2903  // We decrease stock for product
2904  if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
2905  else $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
2906  }
2907  }
2908  }
2909 
2910  if ($error == 0)
2911  {
2912  $old_statut = $this->statut;
2913  $this->brouillon = 1;
2914  $this->statut = self::STATUS_DRAFT;
2915 
2916  // Call trigger
2917  $result = $this->call_trigger('BILL_UNVALIDATE', $user);
2918  if ($result < 0)
2919  {
2920  $error++;
2921  $this->statut = $old_statut;
2922  $this->brouillon = 0;
2923  }
2924  // End call triggers
2925  } else {
2926  $this->db->rollback();
2927  return -1;
2928  }
2929 
2930  if ($error == 0)
2931  {
2932  $this->db->commit();
2933  return 1;
2934  } else {
2935  $this->db->rollback();
2936  return -1;
2937  }
2938  } else {
2939  $this->error = $this->db->error();
2940  $this->db->rollback();
2941  return -1;
2942  }
2943  }
2944 
2945 
2985  public function addline(
2986  $desc,
2987  $pu_ht,
2988  $qty,
2989  $txtva,
2990  $txlocaltax1 = 0,
2991  $txlocaltax2 = 0,
2992  $fk_product = 0,
2993  $remise_percent = 0,
2994  $date_start = '',
2995  $date_end = '',
2996  $ventil = 0,
2997  $info_bits = 0,
2998  $fk_remise_except = '',
2999  $price_base_type = 'HT',
3000  $pu_ttc = 0,
3001  $type = self::TYPE_STANDARD,
3002  $rang = -1,
3003  $special_code = 0,
3004  $origin = '',
3005  $origin_id = 0,
3006  $fk_parent_line = 0,
3007  $fk_fournprice = null,
3008  $pa_ht = 0,
3009  $label = '',
3010  $array_options = 0,
3011  $situation_percent = 100,
3012  $fk_prev_id = 0,
3013  $fk_unit = null,
3014  $pu_ht_devise = 0,
3015  $ref_ext = ''
3016  ) {
3017  // Deprecation warning
3018  if ($label) {
3019  dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3020  //var_dump(debug_backtrace(false));exit;
3021  }
3022 
3023  global $mysoc, $conf, $langs;
3024 
3025  dol_syslog(get_class($this)."::addline id=$this->id,desc=$desc,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", LOG_DEBUG);
3026 
3027  if ($this->statut == self::STATUS_DRAFT)
3028  {
3029  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3030 
3031  // Clean parameters
3032  if (empty($remise_percent)) $remise_percent = 0;
3033  if (empty($qty)) $qty = 0;
3034  if (empty($info_bits)) $info_bits = 0;
3035  if (empty($rang)) $rang = 0;
3036  if (empty($ventil)) $ventil = 0;
3037  if (empty($txtva)) $txtva = 0;
3038  if (empty($txlocaltax1)) $txlocaltax1 = 0;
3039  if (empty($txlocaltax2)) $txlocaltax2 = 0;
3040  if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0;
3041  if (empty($fk_prev_id)) $fk_prev_id = 'null';
3042  if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
3043  if (empty($ref_ext)) $ref_ext = '';
3044 
3045  $remise_percent = price2num($remise_percent);
3046  $qty = price2num($qty);
3047  $pu_ht = price2num($pu_ht);
3048  $pu_ht_devise = price2num($pu_ht_devise);
3049  $pu_ttc = price2num($pu_ttc);
3050  $pa_ht = price2num($pa_ht);
3051  if (!preg_match('/\((.*)\)/', $txtva)) {
3052  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3053  }
3054  $txlocaltax1 = price2num($txlocaltax1);
3055  $txlocaltax2 = price2num($txlocaltax2);
3056 
3057  if ($price_base_type == 'HT')
3058  {
3059  $pu = $pu_ht;
3060  } else {
3061  $pu = $pu_ttc;
3062  }
3063 
3064  // Check parameters
3065  if ($type < 0) return -1;
3066 
3067  if ($date_start && $date_end && $date_start > $date_end) {
3068  $langs->load("errors");
3069  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3070  return -1;
3071  }
3072 
3073  $this->db->begin();
3074 
3075  $product_type = $type;
3076  if (!empty($fk_product))
3077  {
3078  $product = new Product($this->db);
3079  $result = $product->fetch($fk_product);
3080  $product_type = $product->type;
3081 
3082  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3083  $langs->load("errors");
3084  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3085  $this->db->rollback();
3086  return -3;
3087  }
3088  }
3089 
3090  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3091 
3092  // Clean vat code
3093  $reg = array();
3094  $vat_src_code = '';
3095  if (preg_match('/\((.*)\)/', $txtva, $reg))
3096  {
3097  $vat_src_code = $reg[1];
3098  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
3099  }
3100 
3101  // Calcul du total TTC et de la TVA pour la ligne a partir de
3102  // qty, pu, remise_percent et txtva
3103  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3104  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3105 
3106  $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);
3107 
3108  $total_ht = $tabprice[0];
3109  $total_tva = $tabprice[1];
3110  $total_ttc = $tabprice[2];
3111  $total_localtax1 = $tabprice[9];
3112  $total_localtax2 = $tabprice[10];
3113  $pu_ht = $tabprice[3];
3114 
3115  // MultiCurrency
3116  $multicurrency_total_ht = $tabprice[16];
3117  $multicurrency_total_tva = $tabprice[17];
3118  $multicurrency_total_ttc = $tabprice[18];
3119  $pu_ht_devise = $tabprice[19];
3120 
3121  // Rank to use
3122  $ranktouse = $rang;
3123  if ($ranktouse == -1)
3124  {
3125  $rangmax = $this->line_max($fk_parent_line);
3126  $ranktouse = $rangmax + 1;
3127  }
3128 
3129  // Insert line
3130  $this->line = new FactureLigne($this->db);
3131 
3132  $this->line->context = $this->context;
3133 
3134  $this->line->fk_facture = $this->id;
3135  $this->line->label = $label; // deprecated
3136  $this->line->desc = $desc;
3137  $this->line->ref_ext = $ref_ext;
3138 
3139  $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
3140  $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
3141 
3142  $this->line->vat_src_code = $vat_src_code;
3143  $this->line->tva_tx = $txtva;
3144  $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3145  $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3146  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3147  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3148 
3149  $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
3150  $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
3151  $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
3152  $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
3153  $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
3154 
3155  $this->line->fk_product = $fk_product;
3156  $this->line->product_type = $product_type;
3157  $this->line->remise_percent = $remise_percent;
3158  $this->line->date_start = $date_start;
3159  $this->line->date_end = $date_end;
3160  $this->line->ventil = $ventil;
3161  $this->line->rang = $ranktouse;
3162  $this->line->info_bits = $info_bits;
3163  $this->line->fk_remise_except = $fk_remise_except;
3164 
3165  $this->line->special_code = $special_code;
3166  $this->line->fk_parent_line = $fk_parent_line;
3167  $this->line->origin = $origin;
3168  $this->line->origin_id = $origin_id;
3169  $this->line->situation_percent = $situation_percent;
3170  $this->line->fk_prev_id = $fk_prev_id;
3171  $this->line->fk_unit = $fk_unit;
3172 
3173  // infos marge
3174  $this->line->fk_fournprice = $fk_fournprice;
3175  $this->line->pa_ht = $pa_ht;
3176 
3177  // Multicurrency
3178  $this->line->fk_multicurrency = $this->fk_multicurrency;
3179  $this->line->multicurrency_code = $this->multicurrency_code;
3180  $this->line->multicurrency_subprice = $pu_ht_devise;
3181  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
3182  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
3183  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
3184 
3185  if (is_array($array_options) && count($array_options) > 0) {
3186  $this->line->array_options = $array_options;
3187  }
3188 
3189  $result = $this->line->insert();
3190  if ($result > 0)
3191  {
3192  // Reorder if child line
3193  if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
3194 
3195  // Mise a jour informations denormalisees au niveau de la facture meme
3196  $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.
3197 
3198  if ($result > 0)
3199  {
3200  $this->db->commit();
3201  return $this->line->id;
3202  } else {
3203  $this->error = $this->db->lasterror();
3204  $this->db->rollback();
3205  return -1;
3206  }
3207  } else {
3208  $this->error = $this->line->error;
3209  $this->errors = $this->line->errors;
3210  $this->db->rollback();
3211  return -2;
3212  }
3213  } else {
3214  dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3215  return -3;
3216  }
3217  }
3218 
3249  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 = '')
3250  {
3251  global $conf, $user;
3252  // Deprecation warning
3253  if ($label) {
3254  dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3255  }
3256 
3257  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3258 
3259  global $mysoc, $langs;
3260 
3261  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);
3262 
3263  if ($this->brouillon)
3264  {
3265  if (!$this->is_last_in_cycle() && empty($this->error))
3266  {
3267  if (!$this->checkProgressLine($rowid, $situation_percent))
3268  {
3269  if (!$this->error) $this->error = $langs->trans('invoiceLineProgressError');
3270  return -3;
3271  }
3272  }
3273 
3274  if ($date_start && $date_end && $date_start > $date_end) {
3275  $langs->load("errors");
3276  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3277  return -1;
3278  }
3279 
3280  $this->db->begin();
3281 
3282  // Clean parameters
3283  if (empty($qty)) $qty = 0;
3284  if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0;
3285  if (empty($special_code) || $special_code == 3) $special_code = 0;
3286  if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
3287  if (empty($ref_ext)) $ref_ext = '';
3288 
3289  $remise_percent = price2num($remise_percent);
3290  $qty = price2num($qty);
3291  $pu = price2num($pu);
3292  $pu_ht_devise = price2num($pu_ht_devise);
3293  $pa_ht = price2num($pa_ht);
3294  if (!preg_match('/\((.*)\)/', $txtva)) {
3295  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3296  }
3297  $txlocaltax1 = price2num($txlocaltax1);
3298  $txlocaltax2 = price2num($txlocaltax2);
3299 
3300  // Check parameters
3301  if ($type < 0) return -1;
3302 
3303  // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
3304  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3305  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3306 
3307  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3308 
3309  // Clean vat code
3310  $reg = array();
3311  $vat_src_code = '';
3312  if (preg_match('/\((.*)\)/', $txtva, $reg))
3313  {
3314  $vat_src_code = $reg[1];
3315  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
3316  }
3317 
3318  $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);
3319 
3320  $total_ht = $tabprice[0];
3321  $total_tva = $tabprice[1];
3322  $total_ttc = $tabprice[2];
3323  $total_localtax1 = $tabprice[9];
3324  $total_localtax2 = $tabprice[10];
3325  $pu_ht = $tabprice[3];
3326  $pu_tva = $tabprice[4];
3327  $pu_ttc = $tabprice[5];
3328 
3329  // MultiCurrency
3330  $multicurrency_total_ht = $tabprice[16];
3331  $multicurrency_total_tva = $tabprice[17];
3332  $multicurrency_total_ttc = $tabprice[18];
3333  $pu_ht_devise = $tabprice[19];
3334 
3335  // Old properties: $price, $remise (deprecated)
3336  $price = $pu;
3337  $remise = 0;
3338  if ($remise_percent > 0)
3339  {
3340  $remise = round(($pu * $remise_percent / 100), 2);
3341  $price = ($pu - $remise);
3342  }
3343  $price = price2num($price);
3344 
3345  //Fetch current line from the database and then clone the object and set it in $oldline property
3346  $line = new FactureLigne($this->db);
3347  $line->fetch($rowid);
3348  $line->fetch_optionals();
3349 
3350  if (!empty($line->fk_product))
3351  {
3352  $product = new Product($this->db);
3353  $result = $product->fetch($line->fk_product);
3354  $product_type = $product->type;
3355 
3356  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3357  $langs->load("errors");
3358  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3359  $this->db->rollback();
3360  return -3;
3361  }
3362  }
3363 
3364  $staticline = clone $line;
3365 
3366  $line->oldline = $staticline;
3367  $this->line = $line;
3368  $this->line->context = $this->context;
3369 
3370  // Reorder if fk_parent_line change
3371  if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
3372  {
3373  $rangmax = $this->line_max($fk_parent_line);
3374  $this->line->rang = $rangmax + 1;
3375  }
3376 
3377  $this->line->id = $rowid;
3378  $this->line->rowid = $rowid;
3379  $this->line->label = $label;
3380  $this->line->desc = $desc;
3381  $this->line->ref_ext = $ref_ext;
3382  $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
3383 
3384  $this->line->vat_src_code = $vat_src_code;
3385  $this->line->tva_tx = $txtva;
3386  $this->line->localtax1_tx = $txlocaltax1;
3387  $this->line->localtax2_tx = $txlocaltax2;
3388  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3389  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3390 
3391  $this->line->remise_percent = $remise_percent;
3392  $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
3393  $this->line->date_start = $date_start;
3394  $this->line->date_end = $date_end;
3395  $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
3396  $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
3397  $this->line->total_localtax1 = $total_localtax1;
3398  $this->line->total_localtax2 = $total_localtax2;
3399  $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
3400  $this->line->info_bits = $info_bits;
3401  $this->line->special_code = $special_code;
3402  $this->line->product_type = $type;
3403  $this->line->fk_parent_line = $fk_parent_line;
3404  $this->line->skip_update_total = $skip_update_total;
3405  $this->line->situation_percent = $situation_percent;
3406  $this->line->fk_unit = $fk_unit;
3407 
3408  $this->line->fk_fournprice = $fk_fournprice;
3409  $this->line->pa_ht = $pa_ht;
3410 
3411  // Multicurrency
3412  $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
3413  $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
3414  $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
3415  $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3416 
3417  if (is_array($array_options) && count($array_options) > 0) {
3418  // We replace values in this->line->array_options only for entries defined into $array_options
3419  foreach ($array_options as $key => $value) {
3420  $this->line->array_options[$key] = $array_options[$key];
3421  }
3422  }
3423 
3424  $result = $this->line->update($user, $notrigger);
3425  if ($result > 0)
3426  {
3427  // Reorder if child line
3428  if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
3429 
3430  // Mise a jour info denormalisees au niveau facture
3431  $this->update_price(1);
3432  $this->db->commit();
3433  return $result;
3434  } else {
3435  $this->error = $this->line->error;
3436  $this->db->rollback();
3437  return -1;
3438  }
3439  } else {
3440  $this->error = "Invoice statut makes operation forbidden";
3441  return -2;
3442  }
3443  }
3444 
3452  public function checkProgressLine($idline, $situation_percent)
3453  {
3454  $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
3455  INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
3456  WHERE fd.fk_prev_id = '.$idline.'
3457  AND f.fk_statut <> 0';
3458 
3459  $result = $this->db->query($sql);
3460  if (!$result)
3461  {
3462  $this->error = $this->db->error();
3463  return false;
3464  }
3465 
3466  $obj = $this->db->fetch_object($result);
3467 
3468  if ($obj === null) return true;
3469  else return $situation_percent < $obj->situation_percent;
3470  }
3471 
3472  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3480  public function update_percent($line, $percent)
3481  {
3482  // phpcs:enable
3483  global $mysoc, $user;
3484 
3485  // Progress should never be changed for discount lines
3486  if (($line->info_bits & 2) == 2)
3487  {
3488  return;
3489  }
3490 
3491  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3492 
3493  // Cap percentages to 100
3494  if ($percent > 100) $percent = 100;
3495  $line->situation_percent = $percent;
3496  $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);
3497  $line->total_ht = $tabprice[0];
3498  $line->total_tva = $tabprice[1];
3499  $line->total_ttc = $tabprice[2];
3500  $line->total_localtax1 = $tabprice[9];
3501  $line->total_localtax2 = $tabprice[10];
3502  $line->multicurrency_total_ht = $tabprice[16];
3503  $line->multicurrency_total_tva = $tabprice[17];
3504  $line->multicurrency_total_ttc = $tabprice[18];
3505  $line->update($user);
3506  $this->update_price(1);
3507  }
3508 
3515  public function deleteline($rowid)
3516  {
3517  global $user;
3518 
3519  dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG);
3520 
3521  if (!$this->brouillon)
3522  {
3523  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
3524  return -1;
3525  }
3526 
3527  $this->db->begin();
3528 
3529  // Libere remise liee a ligne de facture
3530  $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3531  $sql .= ' SET fk_facture_line = NULL';
3532  $sql .= ' WHERE fk_facture_line = '.$rowid;
3533 
3534  dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
3535  $result = $this->db->query($sql);
3536  if (!$result)
3537  {
3538  $this->error = $this->db->error();
3539  $this->db->rollback();
3540  return -1;
3541  }
3542 
3543  $line = new FactureLigne($this->db);
3544 
3545  $line->context = $this->context;
3546 
3547  // For triggers
3548  $result = $line->fetch($rowid);
3549  if (!($result > 0)) dol_print_error($this->db, $line->error, $line->errors);
3550 
3551  if ($line->delete($user) > 0)
3552  {
3553  $result = $this->update_price(1);
3554 
3555  if ($result > 0)
3556  {
3557  $this->db->commit();
3558  return 1;
3559  } else {
3560  $this->db->rollback();
3561  $this->error = $this->db->lasterror();
3562  return -1;
3563  }
3564  } else {
3565  $this->db->rollback();
3566  $this->error = $line->error;
3567  return -1;
3568  }
3569  }
3570 
3571  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3580  public function set_remise($user, $remise, $notrigger = 0)
3581  {
3582  // phpcs:enable
3583  // Clean parameters
3584  if (empty($remise)) $remise = 0;
3585 
3586  if ($user->rights->facture->creer)
3587  {
3588  $remise = price2num($remise);
3589 
3590  $error = 0;
3591 
3592  $this->db->begin();
3593 
3594  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3595  $sql .= ' SET remise_percent = '.$remise;
3596  $sql .= ' WHERE rowid = '.$this->id;
3597  $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
3598 
3599  dol_syslog(__METHOD__, LOG_DEBUG);
3600  $resql = $this->db->query($sql);
3601  if (!$resql)
3602  {
3603  $this->errors[] = $this->db->error();
3604  $error++;
3605  }
3606 
3607  if (!$notrigger && empty($error))
3608  {
3609  // Call trigger
3610  $result = $this->call_trigger('BILL_MODIFY', $user);
3611  if ($result < 0) $error++;
3612  // End call triggers
3613  }
3614 
3615  if (!$error)
3616  {
3617  $this->remise_percent = $remise;
3618  $this->update_price(1);
3619 
3620  $this->db->commit();
3621  return 1;
3622  } else {
3623  foreach ($this->errors as $errmsg)
3624  {
3625  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3626  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3627  }
3628  $this->db->rollback();
3629  return -1 * $error;
3630  }
3631  }
3632  }
3633 
3634 
3635  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3644  public function set_remise_absolue($user, $remise, $notrigger = 0)
3645  {
3646  // phpcs:enable
3647  if (empty($remise)) $remise = 0;
3648 
3649  if ($user->rights->facture->creer)
3650  {
3651  $error = 0;
3652 
3653  $this->db->begin();
3654 
3655  $remise = price2num($remise);
3656 
3657  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3658  $sql .= ' SET remise_absolue = '.$remise;
3659  $sql .= ' WHERE rowid = '.$this->id;
3660  $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
3661 
3662  dol_syslog(__METHOD__, LOG_DEBUG);
3663  $resql = $this->db->query($sql);
3664  if (!$resql)
3665  {
3666  $this->errors[] = $this->db->error();
3667  $error++;
3668  }
3669 
3670  if (!$error)
3671  {
3672  $this->oldcopy = clone $this;
3673  $this->remise_absolue = $remise;
3674  $this->update_price(1);
3675  }
3676 
3677  if (!$notrigger && empty($error))
3678  {
3679  // Call trigger
3680  $result = $this->call_trigger('BILL_MODIFY', $user);
3681  if ($result < 0) $error++;
3682  // End call triggers
3683  }
3684 
3685  if (!$error)
3686  {
3687  $this->db->commit();
3688  return 1;
3689  } else {
3690  foreach ($this->errors as $errmsg)
3691  {
3692  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3693  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3694  }
3695  $this->db->rollback();
3696  return -1 * $error;
3697  }
3698  }
3699  }
3700 
3709  public function getNextNumRef($soc, $mode = 'next')
3710  {
3711  global $conf, $langs;
3712 
3713  if ($this->module_source == 'takepos') {
3714  $langs->load('cashdesk@cashdesk');
3715 
3716  $moduleName = 'takepos';
3717  $moduleSourceName = 'Takepos';
3718  $addonConstName = 'TAKEPOS_REF_ADDON';
3719 
3720  // Clean parameters (if not defined or using deprecated value)
3721  if (empty($conf->global->TAKEPOS_REF_ADDON)) $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
3722 
3723  $addon = $conf->global->TAKEPOS_REF_ADDON;
3724  } else {
3725  $langs->load('bills');
3726 
3727  $moduleName = 'facture';
3728  $moduleSourceName = 'Invoice';
3729  $addonConstName = 'FACTURE_ADDON';
3730 
3731  // Clean parameters (if not defined or using deprecated value)
3732  if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON = 'mod_facture_terre';
3733  elseif ($conf->global->FACTURE_ADDON == 'terre') $conf->global->FACTURE_ADDON = 'mod_facture_terre';
3734  elseif ($conf->global->FACTURE_ADDON == 'mercure') $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
3735 
3736  $addon = $conf->global->FACTURE_ADDON;
3737  }
3738 
3739  if (!empty($addon)) {
3740  dol_syslog("Call getNextNumRef with ".$addonConstName." = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->nom.", type=".$soc->typent_code, LOG_DEBUG);
3741 
3742  $mybool = false;
3743 
3744 
3745  $file = $addon.'.php';
3746  $classname = $addon;
3747 
3748 
3749  // Include file with class
3750  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3751  foreach ($dirmodels as $reldir) {
3752  $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
3753 
3754  // Load file with numbering class (if found)
3755  if (is_file($dir.$file) && is_readable($dir.$file)) {
3756  $mybool |= include_once $dir.$file;
3757  }
3758  }
3759 
3760  // For compatibility
3761  if (!$mybool) {
3762  $file = $addon.'/'.$addon.'.modules.php';
3763  $classname = 'mod_'.$moduleName.'_'.$addon;
3764  $classname = preg_replace('/\-.*$/', '', $classname);
3765  // Include file with class
3766  foreach ($conf->file->dol_document_root as $dirroot) {
3767  $dir = $dirroot.'/core/modules/'.$moduleName.'/';
3768 
3769  // Load file with numbering class (if found)
3770  if (is_file($dir.$file) && is_readable($dir.$file)) {
3771  $mybool |= include_once $dir.$file;
3772  }
3773  }
3774  }
3775 
3776  if (!$mybool) {
3777  dol_print_error('', 'Failed to include file '.$file);
3778  return '';
3779  }
3780 
3781  $obj = new $classname();
3782  $numref = $obj->getNextValue($soc, $this, $mode);
3783 
3788  if ($mode != 'last' && !$numref) {
3789  $this->error = $obj->error;
3790  return '';
3791  }
3792 
3793  return $numref;
3794  } else {
3795  $langs->load('errors');
3796  print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
3797  return '';
3798  }
3799  }
3800 
3807  public function info($id)
3808  {
3809  $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
3810  $sql .= ' date_closing as dateclosing,';
3811  $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
3812  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
3813  $sql .= ' WHERE c.rowid = '.$id;
3814 
3815  $result = $this->db->query($sql);
3816  if ($result)
3817  {
3818  if ($this->db->num_rows($result))
3819  {
3820  $obj = $this->db->fetch_object($result);
3821  $this->id = $obj->rowid;
3822  if ($obj->fk_user_author)
3823  {
3824  $cuser = new User($this->db);
3825  $cuser->fetch($obj->fk_user_author);
3826  $this->user_creation = $cuser;
3827  }
3828  if ($obj->fk_user_valid)
3829  {
3830  $vuser = new User($this->db);
3831  $vuser->fetch($obj->fk_user_valid);
3832  $this->user_validation = $vuser;
3833  }
3834  if ($obj->fk_user_closing)
3835  {
3836  $cluser = new User($this->db);
3837  $cluser->fetch($obj->fk_user_closing);
3838  $this->user_closing = $cluser;
3839  }
3840 
3841  $this->date_creation = $this->db->jdate($obj->datec);
3842  $this->date_modification = $this->db->jdate($obj->datem);
3843  $this->date_validation = $this->db->jdate($obj->datev);
3844  $this->date_closing = $this->db->jdate($obj->dateclosing);
3845  }
3846  $this->db->free($result);
3847  } else {
3848  dol_print_error($this->db);
3849  }
3850  }
3851 
3852 
3853  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3867  public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
3868  {
3869  // phpcs:enable
3870  global $conf, $user;
3871 
3872  $ga = array();
3873 
3874  $sql = "SELECT s.rowid, s.nom as name, s.client,";
3875  $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
3876  if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
3877  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
3878  if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3879  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
3880  $sql .= " AND f.fk_soc = s.rowid";
3881  if (!$user->rights->societe->client->voir && !$socid) //restriction
3882  {
3883  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
3884  }
3885  if ($socid) $sql .= " AND s.rowid = ".$socid;
3886  if ($draft) $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
3887  if (is_object($excluser)) $sql .= " AND f.fk_user_author <> ".$excluser->id;
3888  $sql .= $this->db->order($sortfield, $sortorder);
3889  $sql .= $this->db->plimit($limit, $offset);
3890 
3891  $result = $this->db->query($sql);
3892  if ($result)
3893  {
3894  $numc = $this->db->num_rows($result);
3895  if ($numc)
3896  {
3897  $i = 0;
3898  while ($i < $numc)
3899  {
3900  $obj = $this->db->fetch_object($result);
3901 
3902  if ($shortlist == 1)
3903  {
3904  $ga[$obj->fid] = $obj->ref;
3905  } elseif ($shortlist == 2)
3906  {
3907  $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
3908  } else {
3909  $ga[$i]['id'] = $obj->fid;
3910  $ga[$i]['ref'] = $obj->ref;
3911  $ga[$i]['name'] = $obj->name;
3912  }
3913  $i++;
3914  }
3915  }
3916  return $ga;
3917  } else {
3918  dol_print_error($this->db);
3919  return -1;
3920  }
3921  }
3922 
3923 
3924  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3933  public function list_replacable_invoices($socid = 0)
3934  {
3935  // phpcs:enable
3936  global $conf;
3937 
3938  $return = array();
3939 
3940  $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut,";
3941  $sql .= " ff.rowid as rowidnext";
3942  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
3943  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
3944  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
3945  $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
3946  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3947  $sql .= " AND f.paye = 0"; // Pas classee payee completement
3948  $sql .= " AND pf.fk_paiement IS NULL"; // Aucun paiement deja fait
3949  $sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement
3950  if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
3951  $sql .= " ORDER BY f.ref";
3952 
3953  dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
3954  $resql = $this->db->query($sql);
3955  if ($resql)
3956  {
3957  while ($obj = $this->db->fetch_object($resql))
3958  {
3959  $return[$obj->rowid] = array('id' => $obj->rowid,
3960  'ref' => $obj->ref,
3961  'status' => $obj->fk_statut);
3962  }
3963  //print_r($return);
3964  return $return;
3965  } else {
3966  $this->error = $this->db->error();
3967  return -1;
3968  }
3969  }
3970 
3971 
3972  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3981  public function list_qualified_avoir_invoices($socid = 0)
3982  {
3983  // phpcs:enable
3984  global $conf;
3985 
3986  $return = array();
3987 
3988 
3989  $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
3990  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
3991  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
3992  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
3993  $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
3994  $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
3995  // $sql.= " WHERE f.fk_statut >= 1";
3996  // $sql.= " AND (f.paye = 1"; // Classee payee completement
3997  // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
3998  $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
3999  $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
4000 
4001  if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4002  // Select the last situation invoice
4003  $sqlSit = 'SELECT MAX(fs.rowid)';
4004  $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs";
4005  $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")";
4006  $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION;
4007  $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4008  $sqlSit .= " GROUP BY fs.situation_cycle_ref";
4009  $sqlSit .= " ORDER BY fs.situation_counter";
4010  $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir
4011  } else {
4012  $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir
4013  }
4014 
4015  if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
4016  $sql .= " ORDER BY f.ref";
4017 
4018  dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
4019  $resql = $this->db->query($sql);
4020  if ($resql)
4021  {
4022  while ($obj = $this->db->fetch_object($resql))
4023  {
4024  $qualified = 0;
4025  if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified = 1;
4026  if ($obj->fk_statut == self::STATUS_CLOSED) $qualified = 1;
4027  if ($qualified)
4028  {
4029  //$ref=$obj->ref;
4030  $paymentornot = ($obj->fk_paiement ? 1 : 0);
4031  $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
4032  }
4033  }
4034 
4035  return $return;
4036  } else {
4037  $this->error = $this->db->error();
4038  return -1;
4039  }
4040  }
4041 
4042 
4043  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4050  public function load_board($user)
4051  {
4052  // phpcs:enable
4053  global $conf, $langs;
4054 
4055  $clause = " WHERE";
4056 
4057  $sql = "SELECT f.rowid, f.date_lim_reglement as datefin,f.fk_statut, f.total";
4058  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4059  if (!$user->rights->societe->client->voir && !$user->socid)
4060  {
4061  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4062  $sql .= " WHERE sc.fk_user = ".$user->id;
4063  $clause = " AND";
4064  }
4065  $sql .= $clause." f.paye=0";
4066  $sql .= " AND f.entity IN (".getEntity('invoice').")";
4067  $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
4068  if ($user->socid) $sql .= " AND f.fk_soc = ".$user->socid;
4069 
4070  $resql = $this->db->query($sql);
4071  if ($resql)
4072  {
4073  $langs->load("bills");
4074  $now = dol_now();
4075 
4076  $response = new WorkboardResponse();
4077  $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4078  $response->label = $langs->trans("CustomerBillsUnpaid");
4079  $response->labelShort = $langs->trans("Unpaid");
4080  $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4081  $response->img = img_object('', "bill");
4082 
4083  $generic_facture = new Facture($this->db);
4084 
4085  while ($obj = $this->db->fetch_object($resql))
4086  {
4087  $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4088  $generic_facture->statut = $obj->fk_statut;
4089 
4090  $response->nbtodo++;
4091  $response->total += $obj->total;
4092 
4093  if ($generic_facture->hasDelay()) {
4094  $response->nbtodolate++;
4095  $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4096  }
4097  }
4098 
4099  return $response;
4100  } else {
4101  dol_print_error($this->db);
4102  $this->error = $this->db->error();
4103  return -1;
4104  }
4105  }
4106 
4107 
4108  /* gestion des contacts d'une facture */
4109 
4115  public function getIdBillingContact()
4116  {
4117  return $this->getIdContact('external', 'BILLING');
4118  }
4119 
4125  public function getIdShippingContact()
4126  {
4127  return $this->getIdContact('external', 'SHIPPING');
4128  }
4129 
4130 
4139  public function initAsSpecimen($option = '')
4140  {
4141  global $conf, $langs, $user;
4142 
4143  $now = dol_now();
4144  $arraynow = dol_getdate($now);
4145  $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
4146 
4147  // Load array of products prodids
4148  $num_prods = 0;
4149  $prodids = array();
4150  $sql = "SELECT rowid";
4151  $sql .= " FROM ".MAIN_DB_PREFIX."product";
4152  $sql .= " WHERE entity IN (".getEntity('product').")";
4153  $sql .= $this->db->plimit(100);
4154 
4155  $resql = $this->db->query($sql);
4156  if ($resql)
4157  {
4158  $num_prods = $this->db->num_rows($resql);
4159  $i = 0;
4160  while ($i < $num_prods)
4161  {
4162  $i++;
4163  $row = $this->db->fetch_row($resql);
4164  $prodids[$i] = $row[0];
4165  }
4166  }
4167  //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
4168  if (empty($num_prods)) {
4169  $num_prods = 1;
4170  }
4171 
4172  // Initialize parameters
4173  $this->id = 0;
4174  $this->entity = 1;
4175  $this->ref = 'SPECIMEN';
4176  $this->specimen = 1;
4177  $this->socid = 1;
4178  $this->date = $nownotime;
4179  $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4180  $this->cond_reglement_id = 1;
4181  $this->cond_reglement_code = 'RECEP';
4182  $this->date_lim_reglement = $this->calculate_date_lim_reglement();
4183  $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
4184  $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
4185 
4186  $this->note_public = 'This is a comment (public)';
4187  $this->note_private = 'This is a comment (private)';
4188  $this->note = 'This is a comment (private)';
4189 
4190  $this->fk_user_author = $user->id;
4191 
4192  $this->multicurrency_tx = 1;
4193  $this->multicurrency_code = $conf->currency;
4194 
4195  $this->fk_incoterms = 0;
4196  $this->location_incoterms = '';
4197 
4198  if (empty($option) || $option != 'nolines')
4199  {
4200  // Lines
4201  $nbp = 5;
4202  $xnbp = 0;
4203  while ($xnbp < $nbp)
4204  {
4205  $line = new FactureLigne($this->db);
4206  $line->desc = $langs->trans("Description")." ".$xnbp;
4207  $line->qty = 1;
4208  $line->subprice = 100;
4209  $line->tva_tx = 19.6;
4210  $line->localtax1_tx = 0;
4211  $line->localtax2_tx = 0;
4212  $line->remise_percent = 0;
4213  if ($xnbp == 1) // Qty is negative (product line)
4214  {
4215  $prodid = mt_rand(1, $num_prods);
4216  $line->fk_product = $prodids[$prodid];
4217  $line->qty = -1;
4218  $line->total_ht = -100;
4219  $line->total_ttc = -119.6;
4220  $line->total_tva = -19.6;
4221  $line->multicurrency_total_ht = -200;
4222  $line->multicurrency_total_ttc = -239.2;
4223  $line->multicurrency_total_tva = -39.2;
4224  } elseif ($xnbp == 2) // UP is negative (free line)
4225  {
4226  $line->subprice = -100;
4227  $line->total_ht = -100;
4228  $line->total_ttc = -119.6;
4229  $line->total_tva = -19.6;
4230  $line->remise_percent = 0;
4231  $line->multicurrency_total_ht = -200;
4232  $line->multicurrency_total_ttc = -239.2;
4233  $line->multicurrency_total_tva = -39.2;
4234  } elseif ($xnbp == 3) // Discount is 50% (product line)
4235  {
4236  $prodid = mt_rand(1, $num_prods);
4237  $line->fk_product = $prodids[$prodid];
4238  $line->total_ht = 50;
4239  $line->total_ttc = 59.8;
4240  $line->total_tva = 9.8;
4241  $line->multicurrency_total_ht = 100;
4242  $line->multicurrency_total_ttc = 119.6;
4243  $line->multicurrency_total_tva = 19.6;
4244  $line->remise_percent = 50;
4245  } else // (product line)
4246  {
4247  $prodid = mt_rand(1, $num_prods);
4248  $line->fk_product = $prodids[$prodid];
4249  $line->total_ht = 100;
4250  $line->total_ttc = 119.6;
4251  $line->total_tva = 19.6;
4252  $line->multicurrency_total_ht = 200;
4253  $line->multicurrency_total_ttc = 239.2;
4254  $line->multicurrency_total_tva = 39.2;
4255  $line->remise_percent = 0;
4256  }
4257 
4258  $this->lines[$xnbp] = $line;
4259 
4260 
4261  $this->total_ht += $line->total_ht;
4262  $this->total_tva += $line->total_tva;
4263  $this->total_ttc += $line->total_ttc;
4264 
4265  $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4266  $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4267  $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4268 
4269  $xnbp++;
4270  }
4271  $this->revenuestamp = 0;
4272 
4273  // Add a line "offered"
4274  $line = new FactureLigne($this->db);
4275  $line->desc = $langs->trans("Description")." (offered line)";
4276  $line->qty = 1;
4277  $line->subprice = 100;
4278  $line->tva_tx = 19.6;
4279  $line->localtax1_tx = 0;
4280  $line->localtax2_tx = 0;
4281  $line->remise_percent = 100;
4282  $line->total_ht = 0;
4283  $line->total_ttc = 0; // 90 * 1.196
4284  $line->total_tva = 0;
4285  $line->multicurrency_total_ht = 0;
4286  $line->multicurrency_total_ttc = 0;
4287  $line->multicurrency_total_tva = 0;
4288  $prodid = mt_rand(1, $num_prods);
4289  $line->fk_product = $prodids[$prodid];
4290 
4291  $this->lines[$xnbp] = $line;
4292  $xnbp++;
4293  }
4294  }
4295 
4296  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4302  public function load_state_board()
4303  {
4304  // phpcs:enable
4305  global $conf, $user;
4306 
4307  $this->nb = array();
4308 
4309  $clause = "WHERE";
4310 
4311  $sql = "SELECT count(f.rowid) as nb";
4312  $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4313  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
4314  if (!$user->rights->societe->client->voir && !$user->socid)
4315  {
4316  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4317  $sql .= " WHERE sc.fk_user = ".$user->id;
4318  $clause = "AND";
4319  }
4320  $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
4321 
4322  $resql = $this->db->query($sql);
4323  if ($resql)
4324  {
4325  while ($obj = $this->db->fetch_object($resql))
4326  {
4327  $this->nb["invoices"] = $obj->nb;
4328  }
4329  $this->db->free($resql);
4330  return 1;
4331  } else {
4332  dol_print_error($this->db);
4333  $this->error = $this->db->error();
4334  return -1;
4335  }
4336  }
4337 
4343  public function getLinesArray()
4344  {
4345  return $this->fetch_lines();
4346  }
4347 
4359  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4360  {
4361  global $conf, $langs;
4362 
4363  $outputlangs->loadLangs(array("bills", "products"));
4364 
4365  if (!dol_strlen($modele))
4366  {
4367  $modele = 'crabe';
4368  $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
4369 
4370  if (!empty($this->model_pdf)) {
4371  $modele = $this->model_pdf;
4372  } elseif (!empty($this->modelpdf)) { // deprecated
4373  $modele = $this->modelpdf;
4374  } elseif (!empty($conf->global->$thisTypeConfName)) {
4375  $modele = $conf->global->$thisTypeConfName;
4376  } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
4377  $modele = $conf->global->FACTURE_ADDON_PDF;
4378  }
4379  }
4380 
4381  $modelpath = "core/modules/facture/doc/";
4382 
4383  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4384  }
4385 
4391  public function newCycle()
4392  {
4393  $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f';
4394  $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
4395  $resql = $this->db->query($sql);
4396  if ($resql) {
4397  if ($resql->num_rows > 0)
4398  {
4399  $res = $this->db->fetch_array($resql);
4400  $ref = $res['max(situation_cycle_ref)'];
4401  $ref++;
4402  } else {
4403  $ref = 1;
4404  }
4405  $this->db->free($resql);
4406  return $ref;
4407  } else {
4408  $this->error = $this->db->lasterror();
4409  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
4410  return -1;
4411  }
4412  }
4413 
4414  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4420  public function is_first()
4421  {
4422  // phpcs:enable
4423  return ($this->situation_counter == 1);
4424  }
4425 
4426  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4432  public function get_prev_sits()
4433  {
4434  // phpcs:enable
4435  global $conf;
4436 
4437  $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
4438  $sql .= ' WHERE situation_cycle_ref = '.$this->situation_cycle_ref;
4439  $sql .= ' AND situation_counter < '.$this->situation_counter;
4440  $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
4441  $resql = $this->db->query($sql);
4442  $res = array();
4443  if ($resql && $resql->num_rows > 0) {
4444  while ($row = $this->db->fetch_object($resql)) {
4445  $id = $row->rowid;
4446  $situation = new Facture($this->db);
4447  $situation->fetch($id);
4448  $res[] = $situation;
4449  }
4450  } else {
4451  $this->error = $this->db->error();
4452  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
4453  return -1;
4454  }
4455 
4456  return $res;
4457  }
4458 
4466  public function setFinal(User $user, $notrigger = 0)
4467  {
4468  $error = 0;
4469 
4470  $this->db->begin();
4471 
4472  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.$this->situation_final.' where rowid = '.$this->id;
4473 
4474  dol_syslog(__METHOD__, LOG_DEBUG);
4475  $resql = $this->db->query($sql);
4476  if (!$resql)
4477  {
4478  $this->errors[] = $this->db->error();
4479  $error++;
4480  }
4481 
4482  if (!$notrigger && empty($error))
4483  {
4484  // Call trigger
4485  $result = $this->call_trigger('BILL_MODIFY', $user);
4486  if ($result < 0) $error++;
4487  // End call triggers
4488  }
4489 
4490  if (!$error)
4491  {
4492  $this->db->commit();
4493  return 1;
4494  } else {
4495  foreach ($this->errors as $errmsg)
4496  {
4497  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4498  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4499  }
4500  $this->db->rollback();
4501  return -1 * $error;
4502  }
4503  }
4504 
4505  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4511  public function is_last_in_cycle()
4512  {
4513  // phpcs:enable
4514  global $conf;
4515 
4516  if (!empty($this->situation_cycle_ref)) {
4517  // No point in testing anything if we're not inside a cycle
4518  $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
4519  $sql .= ' WHERE situation_cycle_ref = '.$this->situation_cycle_ref;
4520  $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
4521  $resql = $this->db->query($sql);
4522 
4523  if ($resql && $resql->num_rows > 0) {
4524  $res = $this->db->fetch_array($resql);
4525  $last = $res['max(situation_counter)'];
4526  return ($last == $this->situation_counter);
4527  } else {
4528  $this->error = $this->db->lasterror();
4529  dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
4530  return false;
4531  }
4532  } else {
4533  return true;
4534  }
4535  }
4536 
4545  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
4546  {
4547  $tables = array(
4548  'facture'
4549  );
4550 
4551  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
4552  }
4553 
4559  public function hasDelay()
4560  {
4561  global $conf;
4562 
4563  $now = dol_now();
4564 
4565  // Paid invoices have status STATUS_CLOSED
4566  if ($this->statut != Facture::STATUS_VALIDATED) return false;
4567 
4568  $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
4569  if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit))
4570  {
4571  $totalpaye = $this->getSommePaiement();
4572  $totalpaye = floatval($totalpaye);
4573  $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
4574  if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0)
4575  {
4576  if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay))
4577  {
4578  $hasDelay = 1;
4579  } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay))
4580  {
4581  $hasDelay = 1;
4582  } else {
4583  $hasDelay = 0;
4584  }
4585  }
4586  }
4587 
4588  return $hasDelay;
4589  }
4590 
4595  public function displayRetainedWarranty()
4596  {
4597  global $conf;
4598 
4599  // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
4600 
4601  // note : we dont 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
4602 
4603  $displayWarranty = false;
4604  if (!empty($this->retained_warranty)) {
4605  $displayWarranty = true;
4606 
4607  if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
4608  // Check if this situation invoice is 100% for real
4609  $displayWarranty = false;
4610  if (!empty($this->situation_final)) {
4611  $displayWarranty = true;
4612  } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
4613  // $object->situation_final need validation to be done so this test is need for draft
4614  $displayWarranty = true;
4615 
4616  foreach ($this->lines as $i => $line) {
4617  if ($line->product_type < 2 && $line->situation_percent < 100) {
4618  $displayWarranty = false;
4619  break;
4620  }
4621  }
4622  }
4623  }
4624  }
4625 
4626  return $displayWarranty;
4627  }
4628 
4633  public function getRetainedWarrantyAmount($rounding = -1)
4634  {
4635  global $conf;
4636  if (empty($this->retained_warranty)) {
4637  return -1;
4638  }
4639 
4640  $retainedWarrantyAmount = 0;
4641 
4642  // Billed - retained warranty
4643  if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION))
4644  {
4645  $displayWarranty = true;
4646  // Check if this situation invoice is 100% for real
4647  if (!empty($this->lines)) {
4648  foreach ($this->lines as $i => $line) {
4649  if ($line->product_type < 2 && $line->situation_percent < 100) {
4650  $displayWarranty = false;
4651  break;
4652  }
4653  }
4654  }
4655 
4656  if ($displayWarranty && !empty($this->situation_final))
4657  {
4659  $TPreviousIncoice = $this->tab_previous_situation_invoice;
4660 
4661  $total2BillWT = 0;
4662  foreach ($TPreviousIncoice as &$fac) {
4663  $total2BillWT += $fac->total_ttc;
4664  }
4665  $total2BillWT += $this->total_ttc;
4666 
4667  $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
4668  } else {
4669  return -1;
4670  }
4671  } else {
4672  // Because one day retained warranty could be used on standard invoices
4673  $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
4674  }
4675 
4676  if ($rounding < 0) {
4677  $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
4678  }
4679 
4680  if ($rounding > 0) {
4681  return round($retainedWarrantyAmount, $rounding);
4682  }
4683 
4684  return $retainedWarrantyAmount;
4685  }
4686 
4693  public function setRetainedWarranty($value)
4694  {
4695  dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
4696  if ($this->statut >= 0)
4697  {
4698  $fieldname = 'retained_warranty';
4699  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
4700  $sql .= ' SET '.$fieldname.' = '.floatval($value);
4701  $sql .= ' WHERE rowid='.$this->id;
4702 
4703  if ($this->db->query($sql))
4704  {
4705  $this->retained_warranty = floatval($value);
4706  return 1;
4707  } else {
4708  dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
4709  $this->error = $this->db->error();
4710  return -1;
4711  }
4712  } else {
4713  dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
4714  $this->error = 'Status of the object is incompatible '.$this->statut;
4715  return -2;
4716  }
4717  }
4718 
4719 
4727  public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false)
4728  {
4729  if (!$timestamp && $dateYmd) {
4730  $timestamp = $this->db->jdate($dateYmd);
4731  }
4732 
4733 
4734  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
4735  if ($this->statut >= 0)
4736  {
4737  $fieldname = 'retained_warranty_date_limit';
4738  $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
4739  $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null');
4740  $sql .= ' WHERE rowid='.$this->id;
4741 
4742  if ($this->db->query($sql))
4743  {
4744  $this->retained_warranty_date_limit = $timestamp;
4745  return 1;
4746  } else {
4747  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
4748  $this->error = $this->db->error();
4749  return -1;
4750  }
4751  } else {
4752  dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
4753  $this->error = 'Status of the object is incompatible '.$this->statut;
4754  return -2;
4755  }
4756  }
4757 }
4758 
4764 {
4768  public $element = 'facturedet';
4769 
4773  public $table_element = 'facturedet';
4774 
4775  public $oldline;
4776 
4779  public $fk_facture;
4782 
4784  public $desc;
4785  public $ref_ext; // External reference of the line
4786 
4787  public $localtax1_type; // Local tax 1 type
4788  public $localtax2_type; // Local tax 2 type
4789  public $fk_remise_except; // Link to line into llx_remise_except
4790  public $rang = 0;
4791 
4792  public $fk_fournprice;
4793  public $pa_ht;
4794  public $marge_tx;
4795  public $marque_tx;
4796 
4797  public $remise_percent;
4798 
4799  public $special_code; // Liste d'options non cumulabels:
4800  // 1: frais de port
4801  // 2: ecotaxe
4802  // 3: ??
4803 
4804  public $origin;
4805  public $origin_id;
4806 
4807  public $fk_code_ventilation = 0;
4808 
4809  public $date_start;
4810  public $date_end;
4811 
4812  public $skip_update_total; // Skip update price total for special lines
4813 
4817  public $situation_percent;
4818 
4822  public $fk_prev_id;
4823 
4824  // Multicurrency
4825  public $fk_multicurrency;
4826  public $multicurrency_code;
4827  public $multicurrency_subprice;
4828  public $multicurrency_total_ht;
4829  public $multicurrency_total_tva;
4830  public $multicurrency_total_ttc;
4831 
4838  public function fetch($rowid)
4839  {
4840  $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,';
4841  $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
4842  $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,';
4843  $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
4844  $sql .= ' fd.fk_code_ventilation,';
4845  $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
4846  $sql .= ' fd.situation_percent, fd.fk_prev_id,';
4847  $sql .= ' fd.multicurrency_subprice,';
4848  $sql .= ' fd.multicurrency_total_ht,';
4849  $sql .= ' fd.multicurrency_total_tva,';
4850  $sql .= ' fd.multicurrency_total_ttc,';
4851  $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
4852  $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
4853  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
4854  $sql .= ' WHERE fd.rowid = '.$rowid;
4855 
4856  $result = $this->db->query($sql);
4857  if ($result)
4858  {
4859  $objp = $this->db->fetch_object($result);
4860 
4861  $this->rowid = $objp->rowid;
4862  $this->id = $objp->rowid;
4863  $this->fk_facture = $objp->fk_facture;
4864  $this->fk_parent_line = $objp->fk_parent_line;
4865  $this->label = $objp->custom_label;
4866  $this->desc = $objp->description;
4867  $this->qty = $objp->qty;
4868  $this->subprice = $objp->subprice;
4869  $this->ref_ext = $objp->ref_ext;
4870  $this->vat_src_code = $objp->vat_src_code;
4871  $this->tva_tx = $objp->tva_tx;
4872  $this->localtax1_tx = $objp->localtax1_tx;
4873  $this->localtax2_tx = $objp->localtax2_tx;
4874  $this->remise_percent = $objp->remise_percent;
4875  $this->fk_remise_except = $objp->fk_remise_except;
4876  $this->fk_product = $objp->fk_product;
4877  $this->product_type = $objp->product_type;
4878  $this->date_start = $this->db->jdate($objp->date_start);
4879  $this->date_end = $this->db->jdate($objp->date_end);
4880  $this->info_bits = $objp->info_bits;
4881  $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
4882  $this->special_code = $objp->special_code;
4883  $this->total_ht = $objp->total_ht;
4884  $this->total_tva = $objp->total_tva;
4885  $this->total_localtax1 = $objp->total_localtax1;
4886  $this->total_localtax2 = $objp->total_localtax2;
4887  $this->total_ttc = $objp->total_ttc;
4888  $this->fk_code_ventilation = $objp->fk_code_ventilation;
4889  $this->rang = $objp->rang;
4890  $this->fk_fournprice = $objp->fk_fournprice;
4891  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
4892  $this->pa_ht = $marginInfos[0];
4893  $this->marge_tx = $marginInfos[1];
4894  $this->marque_tx = $marginInfos[2];
4895 
4896  $this->ref = $objp->product_ref; // deprecated
4897 
4898  $this->product_ref = $objp->product_ref;
4899  $this->product_label = $objp->product_label;
4900  $this->product_desc = $objp->product_desc;
4901 
4902  $this->fk_unit = $objp->fk_unit;
4903  $this->fk_user_modif = $objp->fk_user_modif;
4904  $this->fk_user_author = $objp->fk_user_author;
4905 
4906  $this->situation_percent = $objp->situation_percent;
4907  $this->fk_prev_id = $objp->fk_prev_id;
4908 
4909  $this->multicurrency_subprice = $objp->multicurrency_subprice;
4910  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
4911  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
4912  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
4913 
4914  $this->db->free($result);
4915 
4916  return 1;
4917  } else {
4918  $this->error = $this->db->lasterror();
4919  return -1;
4920  }
4921  }
4922 
4930  public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
4931  {
4932  global $langs, $user, $conf;
4933 
4934  $error = 0;
4935 
4936  $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'.
4937 
4938  dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
4939 
4940  // Clean parameters
4941  $this->desc = trim($this->desc);
4942  if (empty($this->tva_tx)) $this->tva_tx = 0;
4943  if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
4944  if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
4945  if (empty($this->localtax1_type)) $this->localtax1_type = 0;
4946  if (empty($this->localtax2_type)) $this->localtax2_type = 0;
4947  if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
4948  if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
4949  if (empty($this->rang)) $this->rang = 0;
4950  if (empty($this->remise_percent)) $this->remise_percent = 0;
4951  if (empty($this->info_bits)) $this->info_bits = 0;
4952  if (empty($this->subprice)) $this->subprice = 0;
4953  if (empty($this->ref_ext)) $this->ref_ext = '';
4954  if (empty($this->special_code)) $this->special_code = 0;
4955  if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
4956  if (empty($this->fk_prev_id)) $this->fk_prev_id = 0;
4957  if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
4958 
4959  if (empty($this->pa_ht)) $this->pa_ht = 0;
4960  if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0;
4961  if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0;
4962  if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0;
4963  if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0;
4964 
4965  // if buy price not defined, define buyprice as configured in margin admin
4966  if ($this->pa_ht == 0 && $pa_ht_isemptystring)
4967  {
4968  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
4969  {
4970  return $result;
4971  } else {
4972  $this->pa_ht = $result;
4973  }
4974  }
4975 
4976  // Check parameters
4977  if ($this->product_type < 0)
4978  {
4979  $this->error = 'ErrorProductTypeMustBe0orMore';
4980  return -1;
4981  }
4982  if (!empty($this->fk_product))
4983  {
4984  // Check product exists
4985  $result = Product::isExistingObject('product', $this->fk_product);
4986  if ($result <= 0)
4987  {
4988  $this->error = 'ErrorProductIdDoesNotExists';
4989  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
4990  return -1;
4991  }
4992  }
4993 
4994  $this->db->begin();
4995 
4996  // Insertion dans base de la ligne
4997  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
4998  $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
4999  $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
5000  $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
5001  $sql .= ' date_start, date_end, fk_code_ventilation, ';
5002  $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
5003  $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
5004  $sql .= ' situation_percent, fk_prev_id,';
5005  $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
5006  $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
5007  $sql .= ')';
5008  $sql .= " VALUES (".$this->fk_facture.",";
5009  $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
5010  $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
5011  $sql .= " '".$this->db->escape($this->desc)."',";
5012  $sql .= " ".price2num($this->qty).",";
5013  $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
5014  $sql .= " ".price2num($this->tva_tx).",";
5015  $sql .= " ".price2num($this->localtax1_tx).",";
5016  $sql .= " ".price2num($this->localtax2_tx).",";
5017  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
5018  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
5019  $sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").',';
5020  $sql .= " ".((int) $this->product_type).",";
5021  $sql .= " ".price2num($this->remise_percent).",";
5022  $sql .= " ".price2num($this->subprice).",";
5023  $sql .= " '".$this->db->escape($this->ref_ext)."',";
5024  $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
5025  $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
5026  $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
5027  $sql .= ' '.$this->fk_code_ventilation.',';
5028  $sql .= ' '.$this->rang.',';
5029  $sql .= ' '.$this->special_code.',';
5030  $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
5031  $sql .= ' '.price2num($this->pa_ht).',';
5032  $sql .= " '".$this->db->escape($this->info_bits)."',";
5033  $sql .= " ".price2num($this->total_ht).",";
5034  $sql .= " ".price2num($this->total_tva).",";
5035  $sql .= " ".price2num($this->total_ttc).",";
5036  $sql .= " ".price2num($this->total_localtax1).",";
5037  $sql .= " ".price2num($this->total_localtax2);
5038  $sql .= ", ".$this->situation_percent;
5039  $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
5040  $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
5041  $sql .= ", ".$user->id;
5042  $sql .= ", ".$user->id;
5043  $sql .= ", ".(int) $this->fk_multicurrency;
5044  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
5045  $sql .= ", ".price2num($this->multicurrency_subprice);
5046  $sql .= ", ".price2num($this->multicurrency_total_ht);
5047  $sql .= ", ".price2num($this->multicurrency_total_tva);
5048  $sql .= ", ".price2num($this->multicurrency_total_ttc);
5049  $sql .= ')';
5050 
5051  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
5052  $resql = $this->db->query($sql);
5053  if ($resql)
5054  {
5055  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
5056  $this->rowid = $this->id; // For backward compatibility
5057 
5058  if (!$error)
5059  {
5060  $result = $this->insertExtraFields();
5061  if ($result < 0)
5062  {
5063  $error++;
5064  }
5065  }
5066 
5067  // Si fk_remise_except defini, on lie la remise a la facture
5068  // ce qui la flague comme "consommee".
5069  if ($this->fk_remise_except)
5070  {
5071  $discount = new DiscountAbsolute($this->db);
5072  $result = $discount->fetch($this->fk_remise_except);
5073  if ($result >= 0)
5074  {
5075  // Check if discount was found
5076  if ($result > 0)
5077  {
5078  // Check if discount not already affected to another invoice
5079  if ($discount->fk_facture_line > 0)
5080  {
5081  if (empty($noerrorifdiscountalreadylinked))
5082  {
5083  $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
5084  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
5085  $this->db->rollback();
5086  return -3;
5087  }
5088  } else {
5089  $result = $discount->link_to_invoice($this->rowid, 0);
5090  if ($result < 0)
5091  {
5092  $this->error = $discount->error;
5093  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
5094  $this->db->rollback();
5095  return -3;
5096  }
5097  }
5098  } else {
5099  $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
5100  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
5101  $this->db->rollback();
5102  return -3;
5103  }
5104  } else {
5105  $this->error = $discount->error;
5106  dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
5107  $this->db->rollback();
5108  return -3;
5109  }
5110  }
5111 
5112  if (!$notrigger)
5113  {
5114  // Call trigger
5115  $result = $this->call_trigger('LINEBILL_INSERT', $user);
5116  if ($result < 0)
5117  {
5118  $this->db->rollback();
5119  return -2;
5120  }
5121  // End call triggers
5122  }
5123 
5124  $this->db->commit();
5125  return $this->id;
5126  } else {
5127  $this->error = $this->db->lasterror();
5128  $this->db->rollback();
5129  return -2;
5130  }
5131  }
5132 
5140  public function update($user = '', $notrigger = 0)
5141  {
5142  global $user, $conf;
5143 
5144  $error = 0;
5145 
5146  $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'.
5147 
5148  // Clean parameters
5149  $this->desc = trim($this->desc);
5150  if (empty($this->ref_ext)) $this->ref_ext = '';
5151  if (empty($this->tva_tx)) $this->tva_tx = 0;
5152  if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
5153  if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
5154  if (empty($this->localtax1_type)) $this->localtax1_type = 0;
5155  if (empty($this->localtax2_type)) $this->localtax2_type = 0;
5156  if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
5157  if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
5158  if (empty($this->remise_percent)) $this->remise_percent = 0;
5159  if (empty($this->info_bits)) $this->info_bits = 0;
5160  if (empty($this->special_code)) $this->special_code = 0;
5161  if (empty($this->product_type)) $this->product_type = 0;
5162  if (empty($this->fk_parent_line)) $this->fk_parent_line = 0;
5163  if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
5164  if (empty($this->pa_ht)) $this->pa_ht = 0;
5165 
5166  if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0;
5167  if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0;
5168  if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0;
5169  if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0;
5170 
5171  // Check parameters
5172  if ($this->product_type < 0) return -1;
5173 
5174  // if buy price not defined, define buyprice as configured in margin admin
5175  if ($this->pa_ht == 0 && $pa_ht_isemptystring)
5176  {
5177  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
5178  {
5179  return $result;
5180  } else {
5181  $this->pa_ht = $result;
5182  }
5183  }
5184 
5185  $this->db->begin();
5186 
5187  // Update line in database
5188  $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
5189  $sql .= " description='".$this->db->escape($this->desc)."'";
5190  $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
5191  $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
5192  $sql .= ", subprice=".price2num($this->subprice)."";
5193  $sql .= ", remise_percent=".price2num($this->remise_percent)."";
5194  if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except;
5195  else $sql .= ", fk_remise_except=null";
5196  $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
5197  $sql .= ", tva_tx=".price2num($this->tva_tx)."";
5198  $sql .= ", localtax1_tx=".price2num($this->localtax1_tx)."";
5199  $sql .= ", localtax2_tx=".price2num($this->localtax2_tx)."";
5200  $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
5201  $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
5202  $sql .= ", qty=".price2num($this->qty);
5203  $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
5204  $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
5205  $sql .= ", product_type=".$this->product_type;
5206  $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
5207  $sql .= ", special_code='".$this->db->escape($this->special_code)."'";
5208  if (empty($this->skip_update_total))
5209  {
5210  $sql .= ", total_ht=".price2num($this->total_ht);
5211  $sql .= ", total_tva=".price2num($this->total_tva);
5212  $sql .= ", total_ttc=".price2num($this->total_ttc);
5213  $sql .= ", total_localtax1=".price2num($this->total_localtax1);
5214  $sql .= ", total_localtax2=".price2num($this->total_localtax2);
5215  }
5216  $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
5217  $sql .= ", buy_price_ht='".price2num($this->pa_ht)."'";
5218  $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
5219  if (!empty($this->rang)) $sql .= ", rang=".$this->rang;
5220  $sql .= ", situation_percent=".$this->situation_percent;
5221  $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
5222  $sql .= ", fk_user_modif =".$user->id;
5223 
5224  // Multicurrency
5225  $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
5226  $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
5227  $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
5228  $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
5229 
5230  $sql .= " WHERE rowid = ".$this->rowid;
5231 
5232  dol_syslog(get_class($this)."::update", LOG_DEBUG);
5233  $resql = $this->db->query($sql);
5234  if ($resql)
5235  {
5236  if (!$error)
5237  {
5238  $this->id = $this->rowid;
5239  $result = $this->insertExtraFields();
5240  if ($result < 0)
5241  {
5242  $error++;
5243  }
5244  }
5245 
5246  if (!$error && !$notrigger)
5247  {
5248  // Call trigger
5249  $result = $this->call_trigger('LINEBILL_UPDATE', $user);
5250  if ($result < 0)
5251  {
5252  $this->db->rollback();
5253  return -2;
5254  }
5255  // End call triggers
5256  }
5257  $this->db->commit();
5258  return 1;
5259  } else {
5260  $this->error = $this->db->error();
5261  $this->db->rollback();
5262  return -2;
5263  }
5264  }
5265 
5272  public function delete()
5273  {
5274  global $user;
5275 
5276  $this->db->begin();
5277 
5278  // Call trigger
5279  $result = $this->call_trigger('LINEBILL_DELETE', $user);
5280  if ($result < 0)
5281  {
5282  $this->db->rollback();
5283  return -1;
5284  }
5285  // End call triggers
5286 
5287  // extrafields
5288  $result = $this->deleteExtraFields();
5289  if ($result < 0)
5290  {
5291  $this->db->rollback();
5292  return -1;
5293  }
5294 
5295  $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid;
5296  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
5297  if ($this->db->query($sql))
5298  {
5299  $this->db->commit();
5300  return 1;
5301  } else {
5302  $this->error = $this->db->error()." sql=".$sql;
5303  $this->db->rollback();
5304  return -1;
5305  }
5306  }
5307 
5308  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5315  public function update_total()
5316  {
5317  // phpcs:enable
5318  $this->db->begin();
5319  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
5320 
5321  // Clean parameters
5322  if (empty($this->total_localtax1)) $this->total_localtax1 = 0;
5323  if (empty($this->total_localtax2)) $this->total_localtax2 = 0;
5324 
5325  // Mise a jour ligne en base
5326  $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
5327  $sql .= " total_ht=".price2num($this->total_ht)."";
5328  $sql .= ",total_tva=".price2num($this->total_tva)."";
5329  $sql .= ",total_localtax1=".price2num($this->total_localtax1)."";
5330  $sql .= ",total_localtax2=".price2num($this->total_localtax2)."";
5331  $sql .= ",total_ttc=".price2num($this->total_ttc)."";
5332  $sql .= " WHERE rowid = ".$this->rowid;
5333 
5334  dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
5335 
5336  $resql = $this->db->query($sql);
5337  if ($resql)
5338  {
5339  $this->db->commit();
5340  return 1;
5341  } else {
5342  $this->error = $this->db->error();
5343  $this->db->rollback();
5344  return -2;
5345  }
5346  }
5347 
5348  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5357  public function get_prev_progress($invoiceid, $include_credit_note = true)
5358  {
5359  // phpcs:enable
5360  global $invoicecache;
5361  if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
5362  return 0;
5363  } else {
5364  // If invoice is not a situation invoice, this->fk_prev_id is used for something else
5365  if (!isset($invoicecache[$invoiceid])) {
5366  $invoicecache[$invoiceid] = new Facture($this->db);
5367  $invoicecache[$invoiceid]->fetch($invoiceid);
5368  }
5369  if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) return 0;
5370 
5371  $sql = 'SELECT situation_percent FROM '.MAIN_DB_PREFIX.'facturedet WHERE rowid='.$this->fk_prev_id;
5372  $resql = $this->db->query($sql);
5373  if ($resql && $resql->num_rows > 0) {
5374  $res = $this->db->fetch_array($resql);
5375 
5376  $returnPercent = floatval($res['situation_percent']);
5377 
5378  if ($include_credit_note) {
5379  $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
5380  $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
5381  $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id;
5382  $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed
5383  $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE;
5384 
5385  $res = $this->db->query($sql);
5386  if ($res) {
5387  while ($obj = $this->db->fetch_object($res)) {
5388  $returnPercent = $returnPercent + floatval($obj->situation_percent);
5389  }
5390  } else {
5391  dol_print_error($this->db);
5392  }
5393  }
5394 
5395  return $returnPercent;
5396  } else {
5397  $this->error = $this->db->error();
5398  dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5399  $this->db->rollback();
5400  return -1;
5401  }
5402  }
5403  }
5404 }
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date...
load_board($user)
Load indicators for dashboard (this-&gt;nbtodo and this-&gt;nbtodolate)
Class to manage stock movements.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
const TYPE_STANDARD
Standard invoice.
getRetainedWarrantyAmount($rounding=-1)
static isExistingObject($element, $id, $ref= '', $ref_ext= '')
Check an object id/ref exists If you don&#39;t need/want to instantiate object and just need to know if o...
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
if(!empty($arrayfields['u.datec']['checked'])) print_liste_field_titre("DateCreationShort"u if(!empty($arrayfields['u.tms']['checked'])) print_liste_field_titre("DateModificationShort"u if(!empty($arrayfields['u.statut']['checked'])) print_liste_field_titre("Status"u statut
Definition: list.php:632
update_percent($line, $percent)
Update invoice line with percentage.
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
static getIdAndTxFromCode($db, $code, $date_document= '')
Get id and rate of currency from code.
deleteline($rowid)
Delete line in database.
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
validate($user, $force_number= '', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines...
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -&gt; yes (1) I...
fetch($rowid)
Load invoice line from database.
setRetainedWarranty($value)
Change the retained warranty.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
getLinesArray()
Create an array of invoice lines.
</td >< tdcolspan="3">< spanclass="opacitymedium"></span ></td ></tr >< trclass="liste_total"> CREANCES DETTES< tdcolspan="3"class="right"></td >< tdcolspan="3"class="right"></td ></tr > CREANCES DETTES RECETTES DEPENSES trips CREANCES DETTES Y m expensereport p date_valid Y m expensereport pe datep $db idate($date_start)."' AND $column < p rowid
$close_note
Commentaire si mis a paye sans paiement complet.
Class to manage products or services.
dol_now($mode= 'auto')
Return date for now.
line_order($renum=false, $rowidorder= 'ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
setRetainedWarrantyDateLimit($timestamp, $dateYmd=false)
Change the retained_warranty_date_limit.
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1335
Class to manage invoice templates.
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
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= '')
Update a detail line.
delete_linked_contact($source= '', $code= '')
Delete all links between an object $this and all its contacts.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller= '', $localtaxes_array= '', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code= '')
Calculate totals (net, vat, ...) of a line.
Definition: price.lib.php:86
Class to manage Dolibarr users.
Definition: user.class.php:44
const TYPE_REPLACEMENT
Replacement invoice.
Class to manage Dolibarr database access.
add_contact($fk_socpeople, $type_contact, $source= 'external', $notrigger=0)
Add a link between element $this-&gt;element and a contact.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:481
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this-&gt;lines.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
set_unpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
fetch($rowid, $ref= '', $ref_ext= '', $notused= '', $fetch_situation=false)
Get object from database.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this-&gt;socid or $this-&gt;fk_soc, into this-&gt;thirdparty.
const TYPE_PROFORMA
Proforma invoice (should not be used.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Parent class of all other business classes for details of elements (invoices, contracts, proposals, orders, ...)
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
load_state_board()
Load indicators for dashboard (this-&gt;nbtodo and this-&gt;nbtodolate)
const TYPE_SITUATION
Situation invoice.
$conf db
API class for accounts.
Definition: inc.php:54
$desc
Description ligne.
price($amount, $form=0, $outlangs= '', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code= '')
Function to format a value into an amount for visual output Function used into PDF and HTML pages...
const TYPE_CREDIT_NOTE
Credit note invoice.
getNextNumRef($soc, $mode= 'next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
$table_ref_field
{}
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
Class to manage third parties objects (customers, suppliers, prospects...)
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
getSommePaiement($multicurrency=0)
Return amount of payments already done.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
Classe permettant la generation de composants html autre Only common components are here...
deleteEcmFiles($mode=0)
Delete related files of object in database.
dol_get_next_month($month, $year)
Return next month.
Definition: date.lib.php:418
$pos_source
key of pos source (&#39;0&#39;, &#39;1&#39;, ...)
Class to manage shipments.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static getIdFromCode($db, $code)
Get id of currency from code.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
const STATUS_DRAFT
Draft status.
set_remise_absolue($user, $remise, $notrigger=0)
Set absolute discount.
update(User $user, $notrigger=0)
Update database.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1286
dol_getdate($timestamp, $fast=false, $forcetimezone= '')
Return an array with locale date info.
fetchObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $clause= 'OR', $alsosametype=1, $orderby= 'sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only). ...
$module_source
key of module source when invoice generated from a dedicated module (&#39;cashdesk&#39;, &#39;takepos&#39;, ...)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1144
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
set_paid($user, $close_code= '', $close_note= '')
Tag the invoice as paid completely (if close_code is filled) =&gt; this-&gt;fk_statut=2, this-&gt;paye=1 or partialy (if close_code filled) + appel trigger BILL_PAYED =&gt; this-&gt;fk_statut=2, this-&gt;paye stay 0.
deleteExtraFields()
Delete all extra fields values for the current object.
Class to manage translations.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
const STATUS_CLOSED
Classified paid.
getNomUrl($withpicto=0, $option= '', $max=0, $short=0, $moretitle= '', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target= '')
Return clicable link of object (with eventually picto)
set_canceled($user, $close_code= '', $close_note= '')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
$fk_fac_rec_source
id of template invoice when generated from a template invoice
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
deleteObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $rowid= '')
Delete all links between an object $this.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
Superclass for invoices classes.
const STATUS_ABANDONED
Classified abandoned and no payment done.
print $_SERVER["PHP_SELF"]
Edit parameters.
getIdBillingContact()
Retourne id des contacts clients de facturation.
const TYPE_DEPOSIT
Deposit invoice.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:498
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
hasDelay()
Is the customer invoice delayed?
call_trigger($triggerName, $user)
Call trigger based on this instance.
setDraft($user, $idwarehouse=-1)
Set draft status.
getIdShippingContact()
Retourne id des contacts clients de livraison.
$close_code
Fermeture apres paiement partiel: discount_vat, badcustomer, abandon Fermeture alors que aucun paieme...
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Class to manage absolute discounts.
info($id)
Load miscellaneous information for tab &quot;Info&quot;.
$fk_facture_source
id of source invoice if replacement invoice or credit note
$fk_parent_line
Id parent line.
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) ...
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=&gt;newva...
Class to manage invoices.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
initAsSpecimen($option= '')
Initialise an instance with random values.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
is_first()
Checks if the invoice is the first of a cycle.
add_object_linked($origin=null, $origin_id=null)
Add objects linked in llx_element_element.
static findAllForProduct($db, $fk_product, $fk_warehouse=0, $qty_min=null, $sortfield=null, $sortorder=null)
Return all batch for a product and a warehouse.
liste_array($shortlist=0, $draft=0, $excluser= '', $socid=0, $limit=0, $offset=0, $sortfield= 'f.datef, f.rowid', $sortorder= 'DESC')
Return list of invoices (eventually filtered on a user) into an array.
update_price($exclspec=0, $roundingadjust= 'none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines)...
dol_time_plus_duree($time, $duration_value, $duration_unit)
Add a delay to a date.
Definition: date.lib.php:114
$fk_facture
From llx_facturedet Id facture.
update_total()
Update DB line fields total_xxx Used by migration.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
__construct($db)
Constructor.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:105
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=self::TYPE_STANDARD, $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= '')
Add an invoice line into database (linked to product/service or not).
Class to manage predefined suppliers products.
if(!empty($search_group)) natural_search(array("g.nom"g note
Definition: list.php:122
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
Class to manage invoice lines.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the &quot;subst...
Class to manage warehouses.
update($user= '', $notrigger=0)
Update line into database.
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed...
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...