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