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