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 if ($_facrec->lines[$i]->fk_product) {
980 $prod = new Product($this->db);
981 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
982 }
983
984 // Reset fk_parent_line for no child products and special product
985 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
986 $fk_parent_line = 0;
987 }
988
989 // For line from template invoice, we use data from template invoice
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->close_code = '';
1270 $object->close_note = '';
1271 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1272 $object->note_private = '';
1273 $object->note_public = '';
1274 }
1275
1276 // Loop on each line of new invoice
1277 foreach ($object->lines as $i => $line) {
1278 if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1279 unset($object->lines[$i]);
1280 continue;
1281 }
1282
1283 // Block to update dates of service (month by month only if previously filled and similar to start and end of month)
1284 // If it's a service with start and end dates
1285 if (getDolGlobalString('INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1286 // Get the dates
1287 $start = dol_getdate($line->date_start);
1288 $end = dol_getdate($line->date_end);
1289
1290 // Get the first and last day of the month
1291 $first = dol_get_first_day($start['year'], $start['mon']);
1292 $last = dol_get_last_day($end['year'], $end['mon']);
1293
1294 //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1295 //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1296 // If start date is first date of month and end date is last date of month
1297 if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1298 && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1299 $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1300 $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1301 $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1302 $object->lines[$i]->date_start = $newFirst;
1303 $object->lines[$i]->date_end = $newLast;
1304 }
1305 }
1306
1307 $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1308 }
1309
1310 // Create clone
1311 $object->context['createfromclone'] = 'createfromclone';
1312 $result = $object->create($user);
1313 if ($result < 0) {
1314 $error++;
1315 $this->error = $object->error;
1316 $this->errors = $object->errors;
1317 } else {
1318 // copy internal contacts
1319 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1320 $error++;
1321 $this->error = $object->error;
1322 $this->errors = $object->errors;
1323 } elseif ($object->socid == $objFrom->socid) {
1324 // copy external contacts if same company
1325 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1326 $error++;
1327 $this->error = $object->error;
1328 $this->errors = $object->errors;
1329 }
1330 }
1331 }
1332
1333 if (!$error) {
1334 // Hook of thirdparty module
1335 if (is_object($hookmanager)) {
1336 $parameters = array('objFrom' => $objFrom);
1337 $action = '';
1338 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1339 if ($reshook < 0) {
1340 $this->setErrorsFromObject($hookmanager);
1341 $error++;
1342 }
1343 }
1344 }
1345
1346 unset($object->context['createfromclone']);
1347
1348 // End
1349 if (!$error) {
1350 $this->db->commit();
1351 return $object->id;
1352 } else {
1353 $this->db->rollback();
1354 return -1;
1355 }
1356 }
1357
1365 public function createFromOrder($object, User $user)
1366 {
1367 global $conf, $hookmanager;
1368
1369 $error = 0;
1370
1371 // Closed order
1372 $this->date = dol_now();
1373 $this->source = 0;
1374
1375 $num = count($object->lines);
1376 for ($i = 0; $i < $num; $i++) {
1377 $line = new FactureLigne($this->db);
1378
1379 $line->libelle = $object->lines[$i]->libelle; // deprecated
1380 $line->label = $object->lines[$i]->label;
1381 $line->desc = $object->lines[$i]->desc;
1382 $line->subprice = $object->lines[$i]->subprice;
1383 $line->total_ht = $object->lines[$i]->total_ht;
1384 $line->total_tva = $object->lines[$i]->total_tva;
1385 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1386 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1387 $line->total_ttc = $object->lines[$i]->total_ttc;
1388 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1389 $line->tva_tx = $object->lines[$i]->tva_tx;
1390 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1391 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1392 $line->qty = $object->lines[$i]->qty;
1393 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1394 $line->remise_percent = $object->lines[$i]->remise_percent;
1395 $line->fk_product = $object->lines[$i]->fk_product;
1396 $line->info_bits = $object->lines[$i]->info_bits;
1397 $line->product_type = $object->lines[$i]->product_type;
1398 $line->rang = $object->lines[$i]->rang;
1399 $line->special_code = $object->lines[$i]->special_code;
1400 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1401 $line->fk_unit = $object->lines[$i]->fk_unit;
1402 $line->date_start = $object->lines[$i]->date_start;
1403 $line->date_end = $object->lines[$i]->date_end;
1404
1405 // Multicurrency
1406 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1407 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1408 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1409 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1410 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1411 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1412
1413 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1414 $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);
1415 $line->pa_ht = $marginInfos[0];
1416
1417 // get extrafields from original line
1418 $object->lines[$i]->fetch_optionals();
1419 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1420 $line->array_options[$options_key] = $value;
1421 }
1422
1423 $this->lines[$i] = $line;
1424 }
1425
1426 $this->socid = $object->socid;
1427 $this->fk_project = $object->fk_project;
1428 $this->fk_account = $object->fk_account;
1429 $this->cond_reglement_id = $object->cond_reglement_id;
1430 $this->mode_reglement_id = $object->mode_reglement_id;
1431 $this->availability_id = $object->availability_id;
1432 $this->demand_reason_id = $object->demand_reason_id;
1433 $this->delivery_date = $object->delivery_date;
1434 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1435 $this->contact_id = $object->contact_id;
1436 $this->ref_client = $object->ref_client;
1437
1438 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1439 $this->note_private = $object->note_private;
1440 $this->note_public = $object->note_public;
1441 }
1442
1443 $this->module_source = $object->module_source;
1444 $this->pos_source = $object->pos_source;
1445
1446 $this->origin = $object->element;
1447 $this->origin_id = $object->id;
1448
1449 $this->fk_user_author = $user->id;
1450
1451 // get extrafields from original line
1452 $object->fetch_optionals();
1453 foreach ($object->array_options as $options_key => $value) {
1454 $this->array_options[$options_key] = $value;
1455 }
1456
1457 // Possibility to add external linked objects with hooks
1458 $this->linked_objects[$this->origin] = $this->origin_id;
1459 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1460 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1461 }
1462
1463 $ret = $this->create($user);
1464
1465 if ($ret > 0) {
1466 // Actions hooked (by external module)
1467 $hookmanager->initHooks(array('invoicedao'));
1468
1469 $parameters = array('objFrom' => $object);
1470 $action = '';
1471 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1472 if ($reshook < 0) {
1473 $this->setErrorsFromObject($hookmanager);
1474 $error++;
1475 }
1476
1477 if (!$error) {
1478 return 1;
1479 } else {
1480 return -1;
1481 }
1482 } else {
1483 return -1;
1484 }
1485 }
1486
1495 public function createFromContract($object, User $user, $lines = array())
1496 {
1497 global $conf, $hookmanager;
1498
1499 $error = 0;
1500
1501 // Closed order
1502 $this->date = dol_now();
1503 $this->source = 0;
1504
1505 $use_all_lines = empty($lines);
1506 $num = count($object->lines);
1507 for ($i = 0; $i < $num; $i++) {
1508 if (!$use_all_lines && !in_array($object->lines[$i]->id, $lines)) {
1509 continue;
1510 }
1511
1512 $line = new FactureLigne($this->db);
1513
1514 $line->libelle = $object->lines[$i]->libelle; // deprecated
1515 $line->label = $object->lines[$i]->label;
1516 $line->desc = $object->lines[$i]->desc;
1517 $line->subprice = $object->lines[$i]->subprice;
1518 $line->total_ht = $object->lines[$i]->total_ht;
1519 $line->total_tva = $object->lines[$i]->total_tva;
1520 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1521 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1522 $line->total_ttc = $object->lines[$i]->total_ttc;
1523 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1524 $line->tva_tx = $object->lines[$i]->tva_tx;
1525 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1526 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1527 $line->qty = $object->lines[$i]->qty;
1528 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1529 $line->remise_percent = $object->lines[$i]->remise_percent;
1530 $line->fk_product = $object->lines[$i]->fk_product;
1531 $line->info_bits = $object->lines[$i]->info_bits;
1532 $line->product_type = $object->lines[$i]->product_type;
1533 $line->rang = $object->lines[$i]->rang;
1534 $line->special_code = $object->lines[$i]->special_code;
1535 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1536 $line->fk_unit = $object->lines[$i]->fk_unit;
1537 $line->date_start = $object->lines[$i]->date_start;
1538 $line->date_end = $object->lines[$i]->date_end;
1539
1540 // Multicurrency
1541 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1542 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1543 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1544 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1545 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1546 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1547
1548 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1549 $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);
1550 $line->pa_ht = $marginInfos[0];
1551
1552 // get extrafields from original line
1553 $object->lines[$i]->fetch_optionals();
1554 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1555 $line->array_options[$options_key] = $value;
1556 }
1557
1558 $this->lines[$i] = $line;
1559 }
1560
1561 $this->socid = $object->socid;
1562 $this->fk_project = $object->fk_project;
1563 $this->fk_account = $object->fk_account;
1564 $this->cond_reglement_id = $object->cond_reglement_id;
1565 $this->mode_reglement_id = $object->mode_reglement_id;
1566 $this->availability_id = $object->availability_id;
1567 $this->demand_reason_id = $object->demand_reason_id;
1568 $this->delivery_date = $object->delivery_date;
1569 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1570 $this->contact_id = $object->contact_id;
1571 $this->ref_client = $object->ref_client;
1572
1573 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1574 $this->note_private = $object->note_private;
1575 $this->note_public = $object->note_public;
1576 }
1577
1578 $this->module_source = $object->module_source;
1579 $this->pos_source = $object->pos_source;
1580
1581 $this->origin = $object->element;
1582 $this->origin_id = $object->id;
1583
1584 $this->fk_user_author = $user->id;
1585
1586 // get extrafields from original line
1587 $object->fetch_optionals();
1588 foreach ($object->array_options as $options_key => $value) {
1589 $this->array_options[$options_key] = $value;
1590 }
1591
1592 // Possibility to add external linked objects with hooks
1593 $this->linked_objects[$this->origin] = $this->origin_id;
1594 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1595 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1596 }
1597
1598 $ret = $this->create($user);
1599
1600 if ($ret > 0) {
1601 // Actions hooked (by external module)
1602 $hookmanager->initHooks(array('invoicedao'));
1603
1604 $parameters = array('objFrom' => $object);
1605 $action = '';
1606 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1607 if ($reshook < 0) {
1608 $this->setErrorsFromObject($hookmanager);
1609 $error++;
1610 }
1611
1612 if (!$error) {
1613 return 1;
1614 } else {
1615 return -1;
1616 }
1617 } else {
1618 return -1;
1619 }
1620 }
1621
1634 public static function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1635 {
1636 global $conf, $langs, $hookmanager, $action;
1637
1638 if (! in_array($origin->element, array('propal', 'commande'))) {
1639 $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1640 return null;
1641 }
1642
1643 if (empty($date)) {
1644 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1645 return null;
1646 }
1647
1648 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1649
1650 if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1651 $origin->error = 'ErrorDateIsInFuture';
1652 return null;
1653 }
1654
1655 if ($payment_terms_id <= 0) {
1656 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1657 return null;
1658 }
1659
1660 $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1661
1662 if (empty($payment_conditions_deposit_percent)) {
1663 $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1664 return null;
1665 }
1666
1667 if (empty($origin->deposit_percent)) {
1668 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1669 return null;
1670 }
1671
1672 $deposit = new self($origin->db);
1673 $deposit->socid = $origin->socid;
1674 $deposit->type = self::TYPE_DEPOSIT;
1675 $deposit->fk_project = $origin->fk_project;
1676 $deposit->ref_client = $origin->ref_client;
1677 $deposit->date = $date;
1678 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1679 $deposit->cond_reglement_id = $payment_terms_id;
1680 $deposit->availability_id = $origin->availability_id;
1681 $deposit->demand_reason_id = $origin->demand_reason_id;
1682 $deposit->fk_account = $origin->fk_account;
1683 $deposit->fk_incoterms = $origin->fk_incoterms;
1684 $deposit->location_incoterms = $origin->location_incoterms;
1685 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1686 $deposit->multicurrency_code = $origin->multicurrency_code;
1687 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1688 $deposit->module_source = $origin->module_source;
1689 $deposit->pos_source = $origin->pos_source;
1690 $deposit->model_pdf = 'crabe';
1691
1692 $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1693
1694 if (getDolGlobalString($modelByTypeConfName)) {
1695 $deposit->model_pdf = getDolGlobalString($modelByTypeConfName);
1696 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
1697 $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF');
1698 }
1699
1700 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1701 $deposit->note_private = $origin->note_private;
1702 $deposit->note_public = $origin->note_public;
1703 }
1704
1705 $deposit->origin = $origin->element;
1706 $deposit->origin_id = $origin->id;
1707
1708 $origin->fetch_optionals();
1709
1710 foreach ($origin->array_options as $extrakey => $value) {
1711 $deposit->array_options[$extrakey] = $value;
1712 }
1713
1714 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1715
1716 foreach ($overrideFields as $key => $value) {
1717 $deposit->$key = $value;
1718 }
1719
1720 $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1721
1722 $origin->db->begin();
1723
1724 // Facture::create() also imports contact from origin
1725 $createReturn = $deposit->create($user, $notrigger);
1726
1727 if ($createReturn <= 0) {
1728 $origin->db->rollback();
1729 $origin->error = $deposit->error;
1730 $origin->errors = $deposit->errors;
1731 return null;
1732 }
1733
1734 $amount_ttc_diff = 0;
1735 $amountdeposit = array();
1736 $descriptions = array();
1737
1738 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1739 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1740
1741 $TTotalByTva = array();
1742 foreach ($origin->lines as &$line) {
1743 if (!empty($line->special_code)) {
1744 continue;
1745 }
1746 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1747 $descriptions[$line->tva_tx] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1748 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1749 $descriptions[$line->tva_tx] .= $langs->trans('Qty') . ' : ' . $line->qty;
1750 $descriptions[$line->tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1751 }
1752
1753 foreach ($TTotalByTva as $tva => &$total) {
1754 $coef = $total / $origin->total_ttc; // Calc coef
1755 $am = $amount * $coef;
1756 $amount_ttc_diff += $am;
1757 $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
1758 }
1759 } else {
1760 $totalamount = 0;
1761 $lines = $origin->lines;
1762 $numlines = count($lines);
1763 for ($i = 0; $i < $numlines; $i++) {
1764 if (empty($lines[$i]->qty)) {
1765 continue; // We discard qty=0, it is an option
1766 }
1767 if (!empty($lines[$i]->special_code)) {
1768 continue; // We discard special_code (frais port, ecotaxe, option, ...)
1769 }
1770
1771 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1772 $tva_tx = $lines[$i]->tva_tx;
1773 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1774 $descriptions[$tva_tx] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1775 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1776 $descriptions[$tva_tx] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1777 $descriptions[$tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1778 }
1779
1780 if ($totalamount == 0) {
1781 $amountdeposit[0] = 0;
1782 }
1783
1784 $amount_ttc_diff = $amountdeposit[0];
1785 }
1786
1787 foreach ($amountdeposit as $tva => $amount) {
1788 if (empty($amount)) {
1789 continue;
1790 }
1791
1792 $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1793
1794 // Hidden conf
1795 if (getDolGlobalString('INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1796 $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1797 }
1798
1799 $addlineResult = $deposit->addline(
1800 $descline,
1801 $amount, // subprice
1802 1, // quantity
1803 $tva, // vat rate
1804 0, // localtax1_tx
1805 0, // localtax2_tx
1806 (!getDolGlobalString('INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1807 0, // remise_percent
1808 0, // date_start
1809 0, // date_end
1810 0,
1811 0, // info_bits
1812 0,
1813 'HT',
1814 0,
1815 0, // product_type
1816 1,
1817 0, // special_code
1818 $deposit->origin,
1819 0,
1820 0,
1821 0,
1822 0
1823 //,$langs->trans('Deposit') //Deprecated
1824 );
1825
1826 if ($addlineResult < 0) {
1827 $origin->db->rollback();
1828 $origin->error = $deposit->error;
1829 $origin->errors = $deposit->errors;
1830 return null;
1831 }
1832 }
1833
1834 $diff = $deposit->total_ttc - $amount_ttc_diff;
1835
1836 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1837 $deposit->fetch_lines();
1838 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1839
1840 $updatelineResult = $deposit->updateline(
1841 $deposit->lines[0]->id,
1842 $deposit->lines[0]->desc,
1843 $subprice_diff,
1844 $deposit->lines[0]->qty,
1845 $deposit->lines[0]->remise_percent,
1846 $deposit->lines[0]->date_start,
1847 $deposit->lines[0]->date_end,
1848 $deposit->lines[0]->tva_tx,
1849 0,
1850 0,
1851 'HT',
1852 $deposit->lines[0]->info_bits,
1853 $deposit->lines[0]->product_type,
1854 0,
1855 0,
1856 0,
1857 $deposit->lines[0]->pa_ht,
1858 $deposit->lines[0]->label,
1859 0,
1860 array(),
1861 100
1862 );
1863
1864 if ($updatelineResult < 0) {
1865 $origin->db->rollback();
1866 $origin->error = $deposit->error;
1867 $origin->errors = $deposit->errors;
1868 return null;
1869 }
1870 }
1871
1872 $hookmanager->initHooks(array('invoicedao'));
1873
1874 $parameters = array('objFrom' => $origin);
1875 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
1876 // modified by hook
1877 if ($reshook < 0) {
1878 $origin->db->rollback();
1879 $origin->error = $hookmanager->error;
1880 $origin->errors = $hookmanager->errors;
1881 return null;
1882 }
1883
1884 if (!empty($autoValidateDeposit)) {
1885 $validateReturn = $deposit->validate($user, '', 0, $notrigger);
1886
1887 if ($validateReturn < 0) {
1888 $origin->db->rollback();
1889 $origin->error = $deposit->error;
1890 $origin->errors = $deposit->errors;
1891 return null;
1892 }
1893 }
1894
1895 unset($deposit->context['createdepositfromorigin']);
1896
1897 $origin->db->commit();
1898
1899 return $deposit;
1900 }
1901
1909 public function getTooltipContentArray($params)
1910 {
1911 global $conf, $langs, $mysoc, $user;
1912
1913 $langs->load('bills');
1914
1915 $datas = [];
1916 $moretitle = $params['moretitle'] ?? '';
1917
1918 $picto = $this->picto;
1919 if ($this->type == self::TYPE_REPLACEMENT) {
1920 $picto .= 'r'; // Replacement invoice
1921 }
1922 if ($this->type == self::TYPE_CREDIT_NOTE) {
1923 $picto .= 'a'; // Credit note
1924 }
1925 if ($this->type == self::TYPE_DEPOSIT) {
1926 $picto .= 'd'; // Deposit invoice
1927 }
1928
1929 if ($user->hasRight("facture", "read")) {
1930 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
1931
1932 $datas['picto'] .= '&nbsp;'.$this->getLibType(1);
1933
1934 // Complete datas
1935 if (!empty($params['fromajaxtooltip']) && !isset($this->totalpaid)) {
1936 // Load the totalpaid field
1937 $this->totalpaid = $this->getSommePaiement(0);
1938 }
1939 if (isset($this->status) && isset($this->totalpaid)) {
1940 $datas['picto'] .= ' '.$this->getLibStatut(5, $this->totalpaid);
1941 }
1942 if ($moretitle) {
1943 $datas['picto'] .= ' - '.$moretitle;
1944 }
1945 if (!empty($this->ref)) {
1946 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1947 }
1948 if (!empty($this->ref_customer)) {
1949 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
1950 }
1951 if (!empty($this->date)) {
1952 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1953 }
1954 if (!empty($this->total_ht)) {
1955 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1956 }
1957 if (!empty($this->total_tva)) {
1958 $datas['amountvat'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1959 }
1960 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
1961 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
1962 }
1963 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1964 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
1965 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1966 }
1967 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1968 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1969 }
1970 if (!empty($this->total_ttc)) {
1971 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1972 }
1973 }
1974
1975 return $datas;
1976 }
1977
1992 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
1993 {
1994 global $langs, $conf, $user;
1995
1996 if (!empty($conf->dol_no_mouse_hover)) {
1997 $notooltip = 1; // Force disable tooltips
1998 }
1999
2000 $result = '';
2001
2002 if ($option == 'withdraw') {
2003 $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
2004 } else {
2005 $url = DOL_URL_ROOT.'/compta/facture/card.php?id='.$this->id;
2006 }
2007
2008 if (!$user->hasRight("facture", "read")) {
2009 $option = 'nolink';
2010 }
2011
2012 if ($option !== 'nolink') {
2013 // Add param to save lastsearch_values or not
2014 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2015 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2016 $add_save_lastsearch_values = 1;
2017 }
2018 if ($add_save_lastsearch_values) {
2019 $url .= '&save_lastsearch_values=1';
2020 }
2021 }
2022
2023 if ($short) {
2024 return $url;
2025 }
2026
2027 $picto = $this->picto;
2028 if ($this->type == self::TYPE_REPLACEMENT) {
2029 $picto .= 'r'; // Replacement invoice
2030 }
2031 if ($this->type == self::TYPE_CREDIT_NOTE) {
2032 $picto .= 'a'; // Credit note
2033 }
2034 if ($this->type == self::TYPE_DEPOSIT) {
2035 $picto .= 'd'; // Deposit invoice
2036 }
2037
2038 $params = [
2039 'id' => $this->id,
2040 'objecttype' => $this->element,
2041 'moretitle' => $moretitle,
2042 'option' => $option,
2043 ];
2044 $classfortooltip = 'classfortooltip';
2045 $dataparams = '';
2046 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2047 $classfortooltip = 'classforajaxtooltip';
2048 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2049 $label = '';
2050 } else {
2051 $label = implode($this->getTooltipContentArray($params));
2052 }
2053
2054 $linkclose = ($target ? ' target="'.$target.'"' : '');
2055 if (empty($notooltip) && $user->hasRight("facture", "read")) {
2056 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2057 $label = $langs->trans("Invoice");
2058 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2059 }
2060 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2061 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2062 }
2063
2064 $linkstart = '<a href="'.$url.'"';
2065 $linkstart .= $linkclose.'>';
2066 $linkend = '</a>';
2067
2068 if ($option == 'nolink') {
2069 $linkstart = '';
2070 $linkend = '';
2071 }
2072
2073 $result .= $linkstart;
2074 if ($withpicto) {
2075 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2076 }
2077 if ($withpicto != 2) {
2078 $result .= ($max ? dol_trunc($this->ref, $max) : $this->ref);
2079 }
2080 $result .= $linkend;
2081
2082 if ($addlinktonotes) {
2083 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2084 if ($txttoshow) {
2085 //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
2086 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
2087 $result .= ' <span class="note inline-block">';
2088 $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
2089 $result .= img_picto('', 'note');
2090 $result .= '</a>';
2091 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
2092 //$result.='</a>';
2093 $result .= '</span>';
2094 }
2095 }
2096
2097 global $action, $hookmanager;
2098 $hookmanager->initHooks(array('invoicedao'));
2099 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value' => $save_lastsearch_value, 'target' => $target);
2100 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2101 if ($reshook > 0) {
2102 $result = $hookmanager->resPrint;
2103 } else {
2104 $result .= $hookmanager->resPrint;
2105 }
2106
2107 return $result;
2108 }
2109
2120 public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false)
2121 {
2122 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2123 return -1;
2124 }
2125
2126 $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2127 $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2128 $sql .= ', f.datef as df, f.date_pointoftax';
2129 $sql .= ', f.date_lim_reglement as dlr';
2130 $sql .= ', f.datec as datec';
2131 $sql .= ', f.date_valid as datev';
2132 $sql .= ', f.tms as datem';
2133 $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';
2134 $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
2135 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2136 $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2137 $sql .= ', f.fk_account';
2138 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2139 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2140 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2141 $sql .= ', f.fk_incoterms, f.location_incoterms';
2142 $sql .= ', f.module_source, f.pos_source';
2143 $sql .= ", i.libelle as label_incoterms";
2144 $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";
2145 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
2146 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2147 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
2148 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
2149
2150 if ($rowid) {
2151 $sql .= " WHERE f.rowid = ".((int) $rowid);
2152 } else {
2153 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
2154 if ($ref) {
2155 $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
2156 }
2157 if ($ref_ext) {
2158 $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
2159 }
2160 }
2161
2162 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2163 $resql = $this->db->query($sql);
2164 if ($resql) {
2165 if ($this->db->num_rows($resql)) {
2166 $obj = $this->db->fetch_object($resql);
2167
2168 $this->id = $obj->rowid;
2169 $this->entity = $obj->entity;
2170
2171 $this->ref = $obj->ref;
2172 $this->ref_client = $obj->ref_client;
2173 $this->ref_customer = $obj->ref_client;
2174 $this->ref_ext = $obj->ref_ext;
2175 $this->type = $obj->type;
2176 $this->subtype = $obj->subtype;
2177 $this->date = $this->db->jdate($obj->df);
2178 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2179 $this->date_creation = $this->db->jdate($obj->datec);
2180 $this->date_validation = $this->db->jdate($obj->datev);
2181 $this->date_modification = $this->db->jdate($obj->datem);
2182 $this->datem = $this->db->jdate($obj->datem);
2183 $this->total_ht = $obj->total_ht;
2184 $this->total_tva = $obj->total_tva;
2185 $this->total_localtax1 = $obj->localtax1;
2186 $this->total_localtax2 = $obj->localtax2;
2187 $this->total_ttc = $obj->total_ttc;
2188 $this->revenuestamp = $obj->revenuestamp;
2189 $this->paye = $obj->paye;
2190 $this->close_code = $obj->close_code;
2191 $this->close_note = $obj->close_note;
2192
2193 $this->socid = $obj->fk_soc;
2194 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2195
2196 $this->fk_project = $obj->fk_project;
2197 $this->project = null; // Clear if another value was already set by fetch_projet
2198
2199 $this->statut = $obj->status; // deprecated
2200 $this->status = $obj->status;
2201
2202 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2203 $this->mode_reglement_id = $obj->fk_mode_reglement;
2204 $this->mode_reglement_code = $obj->mode_reglement_code;
2205 $this->mode_reglement = $obj->mode_reglement_libelle;
2206 $this->cond_reglement_id = $obj->fk_cond_reglement;
2207 $this->cond_reglement_code = $obj->cond_reglement_code;
2208 $this->cond_reglement = $obj->cond_reglement_libelle;
2209 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2210 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2211 $this->fk_facture_source = $obj->fk_facture_source;
2212 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2213 $this->note = $obj->note_private; // deprecated
2214 $this->note_private = $obj->note_private;
2215 $this->note_public = $obj->note_public;
2216 $this->user_creation_id = $obj->fk_user_author;
2217 $this->user_validation_id = $obj->fk_user_valid;
2218 $this->user_modification_id = $obj->fk_user_modif;
2219 $this->fk_user_author = $obj->fk_user_author;
2220 $this->fk_user_valid = $obj->fk_user_valid;
2221 $this->fk_user_modif = $obj->fk_user_modif;
2222 $this->model_pdf = $obj->model_pdf;
2223 $this->last_main_doc = $obj->last_main_doc;
2224 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2225 $this->situation_counter = $obj->situation_counter;
2226 $this->situation_final = $obj->situation_final;
2227 $this->retained_warranty = $obj->retained_warranty;
2228 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2229 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2230
2231 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2232
2233 //Incoterms
2234 $this->fk_incoterms = $obj->fk_incoterms;
2235 $this->location_incoterms = $obj->location_incoterms;
2236 $this->label_incoterms = $obj->label_incoterms;
2237
2238 $this->module_source = $obj->module_source;
2239 $this->pos_source = $obj->pos_source;
2240
2241 // Multicurrency
2242 $this->fk_multicurrency = $obj->fk_multicurrency;
2243 $this->multicurrency_code = $obj->multicurrency_code;
2244 $this->multicurrency_tx = $obj->multicurrency_tx;
2245 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2246 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2247 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2248
2249 if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2251 }
2252
2253 // Retrieve all extrafield
2254 // fetch optionals attributes and labels
2255 $this->fetch_optionals();
2256
2257 // Lines
2258 $this->lines = array();
2259
2260 $result = $this->fetch_lines();
2261 if ($result < 0) {
2262 $this->error = $this->db->error();
2263 return -3;
2264 }
2265
2266 $this->db->free($resql);
2267
2268 return 1;
2269 } else {
2270 $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2271
2272 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2273 return 0;
2274 }
2275 } else {
2276 $this->error = $this->db->lasterror();
2277 return -1;
2278 }
2279 }
2280
2281
2282 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2291 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2292 {
2293 // phpcs:enable
2294 $this->lines = array();
2295
2296 $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,';
2297 $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,';
2298 $sql .= ' l.situation_percent, l.fk_prev_id,';
2299 $sql .= ' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2300 $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2301 $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,';
2302 $sql .= ' l.fk_unit,';
2303 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2304 $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';
2305 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
2306 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2307 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2308 $sql .= ' ORDER BY l.rang, l.rowid';
2309
2310 dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2311 $result = $this->db->query($sql);
2312 if ($result) {
2313 $num = $this->db->num_rows($result);
2314 $i = 0;
2315 while ($i < $num) {
2316 $objp = $this->db->fetch_object($result);
2317 $line = new FactureLigne($this->db);
2318
2319 $line->id = $objp->rowid;
2320 $line->rowid = $objp->rowid; // deprecated
2321 $line->fk_facture = $objp->fk_facture;
2322 $line->label = $objp->custom_label; // deprecated
2323 $line->desc = $objp->description; // Description line
2324 $line->description = $objp->description; // Description line
2325 $line->product_type = $objp->product_type; // Type of line
2326 $line->ref = $objp->product_ref; // Ref product
2327 $line->product_ref = $objp->product_ref; // Ref product
2328 $line->libelle = $objp->product_label; // deprecated
2329 $line->product_label = $objp->product_label; // Label product
2330 $line->product_barcode = $objp->product_barcode; // Barcode number product
2331 $line->product_desc = $objp->product_desc; // Description product
2332 $line->fk_product_type = $objp->fk_product_type; // Type of product
2333 $line->qty = $objp->qty;
2334 $line->subprice = $objp->subprice;
2335 $line->ref_ext = $objp->ref_ext; // line external ref
2336
2337 $line->vat_src_code = $objp->vat_src_code;
2338 $line->tva_tx = $objp->tva_tx;
2339 $line->localtax1_tx = $objp->localtax1_tx;
2340 $line->localtax2_tx = $objp->localtax2_tx;
2341 $line->localtax1_type = $objp->localtax1_type;
2342 $line->localtax2_type = $objp->localtax2_type;
2343 $line->remise_percent = $objp->remise_percent;
2344 $line->fk_remise_except = $objp->fk_remise_except;
2345 $line->fk_product = $objp->fk_product;
2346 $line->date_start = $this->db->jdate($objp->date_start);
2347 $line->date_end = $this->db->jdate($objp->date_end);
2348 $line->info_bits = $objp->info_bits;
2349 $line->total_ht = $objp->total_ht;
2350 $line->total_tva = $objp->total_tva;
2351 $line->total_localtax1 = $objp->total_localtax1;
2352 $line->total_localtax2 = $objp->total_localtax2;
2353 $line->total_ttc = $objp->total_ttc;
2354
2355 $line->fk_fournprice = $objp->fk_fournprice;
2356 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2357 $line->pa_ht = $marginInfos[0];
2358 $line->marge_tx = $marginInfos[1];
2359 $line->marque_tx = $marginInfos[2];
2360 $line->rang = $objp->rang;
2361 $line->special_code = $objp->special_code;
2362 $line->fk_parent_line = $objp->fk_parent_line;
2363 $line->situation_percent = $objp->situation_percent;
2364 $line->fk_prev_id = $objp->fk_prev_id;
2365 $line->fk_unit = $objp->fk_unit;
2366
2367 $line->batch = $objp->batch;
2368 $line->fk_warehouse = $objp->fk_warehouse;
2369
2370 // Accountancy
2371 $line->fk_accounting_account = $objp->fk_code_ventilation;
2372
2373 // Multicurrency
2374 $line->fk_multicurrency = $objp->fk_multicurrency;
2375 $line->multicurrency_code = $objp->multicurrency_code;
2376 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2377 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2378 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2379 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2380
2381 $line->fetch_optionals();
2382
2383 // multilangs
2384 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2385 $tmpproduct = new Product($this->db);
2386 $tmpproduct->fetch($objp->fk_product);
2387 $tmpproduct->getMultiLangs();
2388
2389 $line->multilangs = $tmpproduct->multilangs;
2390 }
2391
2392 $this->lines[$i] = $line;
2393
2394 $i++;
2395 }
2396 $this->db->free($result);
2397 return 1;
2398 } else {
2399 $this->error = $this->db->error();
2400 return -3;
2401 }
2402 }
2403
2411 {
2412 global $conf;
2413
2414 $this->tab_previous_situation_invoice = array();
2415 $this->tab_next_situation_invoice = array();
2416
2417 $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2418 $sql .= " WHERE rowid <> ".((int) $this->id);
2419 $sql .= ' AND entity = '.((int) $this->entity);
2420 $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2421 $sql .= ' ORDER BY situation_counter ASC';
2422
2423 dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2424 $result = $this->db->query($sql);
2425 if ($result && $this->db->num_rows($result) > 0) {
2426 while ($objp = $this->db->fetch_object($result)) {
2427 $invoice = new Facture($this->db);
2428 if ($invoice->fetch($objp->rowid) > 0) {
2429 if ($objp->situation_counter < $this->situation_counter
2430 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2431 ) {
2432 $this->tab_previous_situation_invoice[] = $invoice;
2433 } else {
2434 $this->tab_next_situation_invoice[] = $invoice;
2435 }
2436 }
2437 }
2438 }
2439 }
2440
2448 public function update(User $user, $notrigger = 0)
2449 {
2450 $error = 0;
2451
2452 // Clean parameters
2453 if (empty($this->type)) {
2454 $this->type = self::TYPE_STANDARD;
2455 }
2456 if (isset($this->subtype)) {
2457 $this->subtype = (int) trim((string) $this->subtype);
2458 }
2459 if (isset($this->ref)) {
2460 $this->ref = trim($this->ref);
2461 }
2462 if (isset($this->ref_ext)) {
2463 $this->ref_ext = trim($this->ref_ext);
2464 }
2465 // deprecated
2466 if (isset($this->ref_client)) {
2467 $this->ref_client = trim($this->ref_client);
2468 }
2469 if (isset($this->ref_customer)) {
2470 $this->ref_customer = trim($this->ref_customer);
2471 }
2472 if (isset($this->increment)) {
2473 $this->increment = trim($this->increment);
2474 }
2475 if (isset($this->close_code)) {
2476 $this->close_code = trim($this->close_code);
2477 }
2478 if (isset($this->close_note)) {
2479 $this->close_note = trim($this->close_note);
2480 }
2481 if (isset($this->note) || isset($this->note_private)) {
2482 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2483 }
2484 if (isset($this->note) || isset($this->note_private)) {
2485 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2486 }
2487 if (isset($this->note_public)) {
2488 $this->note_public = trim($this->note_public);
2489 }
2490 if (isset($this->model_pdf)) {
2491 $this->model_pdf = trim($this->model_pdf);
2492 }
2493 if (isset($this->import_key)) {
2494 $this->import_key = trim($this->import_key);
2495 }
2496 if (isset($this->retained_warranty)) {
2497 $this->retained_warranty = (float) $this->retained_warranty;
2498 }
2499 if (!isset($this->user_creation_id) && isset($this->fk_user_author) ) {
2500 $this->user_creation_id = $this->fk_user_author;
2501 }
2502 if (!isset($this->user_validation_id) && isset($this->fk_user_valid) ) {
2503 $this->user_validation_id = $this->fk_user_valid;
2504 }
2505
2506 // Update request
2507 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2508 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2509 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2510 $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
2511 $sql .= " subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) : "null").",";
2512 $sql .= " ref_client=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : (isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null")).",";
2513 $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2514 $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
2515 $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2516 $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2517 $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2518 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2519 $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
2520 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2521 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2522 $sql .= " total_tva=".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
2523 $sql .= " localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
2524 $sql .= " localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
2525 $sql .= " total_ht=".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
2526 $sql .= " total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
2527 $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? (float) $this->revenuestamp : "null").",";
2528 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
2529 $sql .= " fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) : "null").",";
2530 $sql .= " fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
2531 $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source : "null").",";
2532 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
2533 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
2534 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
2535 $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2536 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2537 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2538 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2539 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2540 $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : (int) $this->situation_cycle_ref).",";
2541 $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : (int) $this->situation_counter).",";
2542 $sql .= " situation_final=".(empty($this->situation_final) ? "0" : (int) $this->situation_final).",";
2543 $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : (float) $this->retained_warranty).",";
2544 $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2545 $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement : "null");
2546 $sql .= " WHERE rowid=".((int) $this->id);
2547
2548 $this->db->begin();
2549
2550 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2551 $resql = $this->db->query($sql);
2552 if (!$resql) {
2553 $error++;
2554 $this->errors[] = "Error ".$this->db->lasterror();
2555 }
2556
2557 if (!$error) {
2558 $result = $this->insertExtraFields();
2559 if ($result < 0) {
2560 $error++;
2561 }
2562 }
2563
2564 if (!$error && !$notrigger) {
2565 // Call trigger
2566 $result = $this->call_trigger('BILL_MODIFY', $user);
2567 if ($result < 0) {
2568 $error++;
2569 }
2570 // End call triggers
2571 }
2572
2573 // Commit or rollback
2574 if ($error) {
2575 foreach ($this->errors as $errmsg) {
2576 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2577 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2578 }
2579 $this->db->rollback();
2580 return -1 * $error;
2581 } else {
2582 $this->db->commit();
2583 return 1;
2584 }
2585 }
2586
2587
2588 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2595 public function insert_discount($idremise)
2596 {
2597 // phpcs:enable
2598 global $conf, $langs;
2599
2600 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2601 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2602
2603 $this->db->begin();
2604
2605 $remise = new DiscountAbsolute($this->db);
2606 $result = $remise->fetch($idremise);
2607
2608 if ($result > 0) {
2609 if ($remise->fk_facture) { // Protection against multiple submission
2610 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2611 $this->db->rollback();
2612 return -5;
2613 }
2614
2615 $facligne = new FactureLigne($this->db);
2616 $facligne->fk_facture = $this->id;
2617 $facligne->fk_remise_except = $remise->id;
2618 $facligne->desc = $remise->description; // Description ligne
2619 $facligne->vat_src_code = $remise->vat_src_code;
2620 $facligne->tva_tx = $remise->tva_tx;
2621 $facligne->subprice = -$remise->amount_ht;
2622 $facligne->fk_product = 0; // Id produit predefini
2623 $facligne->qty = 1;
2624 $facligne->remise_percent = 0;
2625 $facligne->rang = -1;
2626 $facligne->info_bits = 2;
2627
2628 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
2629 $facligne->rang = 1;
2630 $linecount = count($this->lines);
2631 for ($ii = 1; $ii <= $linecount; $ii++) {
2632 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2633 }
2634 }
2635
2636 // Get buy/cost price of invoice that is source of discount
2637 if ($remise->fk_facture_source > 0) {
2638 $srcinvoice = new Facture($this->db);
2639 $srcinvoice->fetch($remise->fk_facture_source);
2640 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2641 $formmargin = new FormMargin($this->db);
2642 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2643 $facligne->pa_ht = $arraytmp['pa_total'];
2644 }
2645
2646 $facligne->total_ht = -$remise->amount_ht;
2647 $facligne->total_tva = -$remise->amount_tva;
2648 $facligne->total_ttc = -$remise->amount_ttc;
2649
2650 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2651 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2652 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2653 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2654
2655 $lineid = $facligne->insert();
2656 if ($lineid > 0) {
2657 $result = $this->update_price(1);
2658 if ($result > 0) {
2659 // Create link between discount and invoice line
2660 $result = $remise->link_to_invoice($lineid, 0);
2661 if ($result < 0) {
2662 $this->error = $remise->error;
2663 $this->db->rollback();
2664 return -4;
2665 }
2666
2667 $this->db->commit();
2668 return 1;
2669 } else {
2670 $this->error = $facligne->error;
2671 $this->db->rollback();
2672 return -1;
2673 }
2674 } else {
2675 $this->error = $facligne->error;
2676 $this->db->rollback();
2677 return -2;
2678 }
2679 } else {
2680 $this->db->rollback();
2681 return -3;
2682 }
2683 }
2684
2685 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2693 public function set_ref_client($ref_client, $notrigger = 0)
2694 {
2695 // phpcs:enable
2696 global $user;
2697
2698 $error = 0;
2699
2700 $this->db->begin();
2701
2702 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2703 if (empty($ref_client)) {
2704 $sql .= ' SET ref_client = NULL';
2705 } else {
2706 $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
2707 }
2708 $sql .= " WHERE rowid = ".((int) $this->id);
2709
2710 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2711 $resql = $this->db->query($sql);
2712 if (!$resql) {
2713 $this->errors[] = $this->db->error();
2714 $error++;
2715 }
2716
2717 if (!$error) {
2718 $this->ref_client = $ref_client; //deprecated
2719 $this->ref_customer = $ref_client;
2720 }
2721
2722 if (!$notrigger && empty($error)) {
2723 // Call trigger
2724 $result = $this->call_trigger('BILL_MODIFY', $user);
2725 if ($result < 0) {
2726 $error++;
2727 }
2728 // End call triggers
2729 }
2730
2731 if (!$error) {
2732 $this->ref_client = $ref_client; //deprecated
2733 $this->ref_customer = $ref_client;
2734
2735 $this->db->commit();
2736 return 1;
2737 } else {
2738 foreach ($this->errors as $errmsg) {
2739 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2740 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2741 }
2742 $this->db->rollback();
2743 return -1 * $error;
2744 }
2745 }
2746
2755 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2756 {
2757 global $langs, $conf;
2758 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2759
2760 $rowid = $this->id;
2761
2762 dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
2763
2764 // Test to avoid invoice deletion (allowed if draft)
2765 $result = $this->is_erasable();
2766
2767 if ($result <= 0) {
2768 return 0;
2769 }
2770
2771 $error = 0;
2772
2773 $this->db->begin();
2774
2775 if (!$error && !$notrigger) {
2776 // Call trigger
2777 $result = $this->call_trigger('BILL_DELETE', $user);
2778 if ($result < 0) {
2779 $error++;
2780 }
2781 // End call triggers
2782 }
2783
2784 // Removed extrafields
2785 if (!$error) {
2786 $result = $this->deleteExtraFields();
2787 if ($result < 0) {
2788 $error++;
2789 dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
2790 }
2791 }
2792
2793 if (!$error) {
2794 // Delete linked object
2795 $res = $this->deleteObjectLinked();
2796 if ($res < 0) {
2797 $error++;
2798 }
2799 }
2800
2801 if (!$error) {
2802 // If invoice was converted into a discount not yet consumed, we remove discount
2803 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
2804 $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
2805 $sql .= ' AND fk_facture_line IS NULL';
2806 $resql = $this->db->query($sql);
2807
2808 // If invoice has consumed discounts
2809 $this->fetch_lines();
2810 $list_rowid_det = array();
2811 foreach ($this->lines as $key => $invoiceline) {
2812 $list_rowid_det[] = $invoiceline->id;
2813 }
2814
2815 // Consumed discounts are freed
2816 if (count($list_rowid_det)) {
2817 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2818 $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
2819 $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
2820
2821 if (!$this->db->query($sql)) {
2822 $this->error = $this->db->error()." sql=".$sql;
2823 $this->errors[] = $this->error;
2824 $this->db->rollback();
2825 return -5;
2826 }
2827 }
2828
2829 // Remove other links to the deleted invoice
2830
2831 $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
2832 $sql .= ' SET fk_invoice = NULL';
2833 $sql .= ' WHERE fk_invoice = '.((int) $rowid);
2834
2835 if (!$this->db->query($sql)) {
2836 $this->error = $this->db->error()." sql=".$sql;
2837 $this->errors[] = $this->error;
2838 $this->db->rollback();
2839 return -5;
2840 }
2841
2842 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
2843 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
2844 $sql .= ' WHERE invoice_id = '.((int) $rowid);
2845
2846 if (!$this->db->query($sql)) {
2847 $this->error = $this->db->error()." sql=".$sql;
2848 $this->errors[] = $this->error;
2849 $this->db->rollback();
2850 return -5;
2851 }
2852
2853 // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
2854 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2855 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2856 $langs->load("agenda");
2857
2858 $num = count($this->lines);
2859 for ($i = 0; $i < $num; $i++) {
2860 if ($this->lines[$i]->fk_product > 0) {
2861 $mouvP = new MouvementStock($this->db);
2862 $mouvP->origin = &$this;
2863 $mouvP->setOrigin($this->element, $this->id);
2864 // We decrease stock for product
2865 if ($this->type == self::TYPE_CREDIT_NOTE) {
2866 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
2867 } else {
2868 $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
2869 }
2870 }
2871 }
2872 }
2873
2874 // Invoice line extrafileds
2875 $main = MAIN_DB_PREFIX.'facturedet';
2876 $ef = $main."_extrafields";
2877 $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
2878 // Delete invoice line
2879 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
2880
2881 if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact() >= 0 ) {
2882 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
2883
2884 $resql = $this->db->query($sql);
2885 if ($resql) {
2886 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2887 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2888 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2889
2890 // On efface le repertoire de pdf provisoire
2891 $ref = dol_sanitizeFileName($this->ref);
2892 if ($conf->facture->dir_output && !empty($this->ref)) {
2893 $dir = $conf->facture->dir_output."/".$ref;
2894 $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
2895 if (file_exists($file)) { // We must delete all files before deleting directory
2896 $ret = dol_delete_preview($this);
2897
2898 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2899 $langs->load("errors");
2900 $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
2901 $this->errors[] = $this->error;
2902 $this->db->rollback();
2903 return 0;
2904 }
2905 }
2906 if (file_exists($dir)) {
2907 if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
2908 $langs->load("errors");
2909 $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
2910 $this->errors[] = $this->error;
2911 $this->db->rollback();
2912 return 0;
2913 }
2914 }
2915 }
2916
2917 $this->db->commit();
2918 return 1;
2919 } else {
2920 $this->error = $this->db->lasterror()." sql=".$sql;
2921 $this->errors[] = $this->error;
2922 $this->db->rollback();
2923 return -6;
2924 }
2925 } else {
2926 $this->error = $this->db->lasterror()." sql=".$sql;
2927 $this->errors[] = $this->error;
2928 $this->db->rollback();
2929 return -4;
2930 }
2931 } else {
2932 $this->db->rollback();
2933 return -2;
2934 }
2935 }
2936
2937 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2949 public function set_paid($user, $close_code = '', $close_note = '')
2950 {
2951 // phpcs:enable
2952 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2953 return $this->setPaid($user, $close_code, $close_note);
2954 }
2955
2966 public function setPaid($user, $close_code = '', $close_note = '')
2967 {
2968 $error = 0;
2969
2970 if ($this->paye != 1) {
2971 $this->db->begin();
2972
2973 $now = dol_now();
2974
2975 dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
2976
2977 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2978 $sql .= ' fk_statut='.self::STATUS_CLOSED;
2979 if (!$close_code) {
2980 $sql .= ', paye=1';
2981 }
2982 if ($close_code) {
2983 $sql .= ", close_code='".$this->db->escape($close_code)."'";
2984 }
2985 if ($close_note) {
2986 $sql .= ", close_note='".$this->db->escape($close_note)."'";
2987 }
2988 $sql .= ', fk_user_closing = '.((int) $user->id);
2989 $sql .= ", date_closing = '".$this->db->idate($now)."'";
2990 $sql .= " WHERE rowid = ".((int) $this->id);
2991
2992 $resql = $this->db->query($sql);
2993 if ($resql) {
2994 // Call trigger
2995 $result = $this->call_trigger('BILL_PAYED', $user);
2996 if ($result < 0) {
2997 $error++;
2998 }
2999 // End call triggers
3000 } else {
3001 $error++;
3002 $this->error = $this->db->lasterror();
3003 }
3004
3005 if (!$error) {
3006 $this->db->commit();
3007 return 1;
3008 } else {
3009 $this->db->rollback();
3010 return -1;
3011 }
3012 } else {
3013 return 0;
3014 }
3015 }
3016
3017
3018 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3029 public function set_unpaid($user)
3030 {
3031 // phpcs:enable
3032 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3033 return $this->setUnpaid($user);
3034 }
3035
3044 public function setUnpaid($user)
3045 {
3046 $error = 0;
3047
3048 $this->db->begin();
3049
3050 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3051 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
3052 $sql .= ' date_closing=null,';
3053 $sql .= ' fk_user_closing=null';
3054 $sql .= " WHERE rowid = ".((int) $this->id);
3055
3056 dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
3057 $resql = $this->db->query($sql);
3058 if ($resql) {
3059 // Call trigger
3060 $result = $this->call_trigger('BILL_UNPAYED', $user);
3061 if ($result < 0) {
3062 $error++;
3063 }
3064 // End call triggers
3065 } else {
3066 $error++;
3067 $this->error = $this->db->error();
3068 dol_print_error($this->db);
3069 }
3070
3071 if (!$error) {
3072 $this->db->commit();
3073 return 1;
3074 } else {
3075 $this->db->rollback();
3076 return -1;
3077 }
3078 }
3079
3080
3081 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3094 public function set_canceled($user, $close_code = '', $close_note = '')
3095 {
3096 // phpcs:enable
3097 dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3098 return $this->setCanceled($user, $close_code, $close_note);
3099 }
3100
3111 public function setCanceled($user, $close_code = '', $close_note = '')
3112 {
3113 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
3114
3115 $this->db->begin();
3116 $now = dol_now();
3117
3118 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3119 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
3120 if ($close_code) {
3121 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3122 }
3123 if ($close_note) {
3124 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3125 }
3126 $sql .= ', fk_user_closing = '.((int) $user->id);
3127 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3128 $sql .= " WHERE rowid = ".((int) $this->id);
3129
3130 $resql = $this->db->query($sql);
3131 if ($resql) {
3132 // Bound discounts are deducted from the invoice
3133 // as they have not been used since the invoice is abandoned.
3134 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3135 $sql .= ' SET fk_facture = NULL';
3136 $sql .= ' WHERE fk_facture = '.((int) $this->id);
3137
3138 $resql = $this->db->query($sql);
3139 if ($resql) {
3140 // Call trigger
3141 $result = $this->call_trigger('BILL_CANCEL', $user);
3142 if ($result < 0) {
3143 $this->db->rollback();
3144 return -1;
3145 }
3146 // End call triggers
3147
3148 $this->db->commit();
3149 return 1;
3150 } else {
3151 $this->error = $this->db->error()." sql=".$sql;
3152 $this->db->rollback();
3153 return -1;
3154 }
3155 } else {
3156 $this->error = $this->db->error()." sql=".$sql;
3157 $this->db->rollback();
3158 return -2;
3159 }
3160 }
3161
3173 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3174 {
3175 global $conf, $langs, $mysoc;
3176 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3177
3178 $productStatic = null;
3179 $warehouseStatic = null;
3180 if ($batch_rule > 0) {
3181 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3182 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3183 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3184 $productStatic = new Product($this->db);
3185 $warehouseStatic = new Entrepot($this->db);
3186 $productbatch = new Productbatch($this->db);
3187 }
3188
3189 $now = dol_now();
3190
3191 $error = 0;
3192 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3193
3194 // Force to have object complete for checks
3195 $this->fetch_thirdparty();
3196 $this->fetch_lines();
3197
3198 // Check parameters
3199 if ($this->status != self::STATUS_DRAFT) {
3200 dol_syslog(get_class($this)."::validate Current status is not draft. operation canceled.", LOG_WARNING);
3201 return 0;
3202 }
3203 if (count($this->lines) <= 0) {
3204 $langs->load("errors");
3205 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3206 return -1;
3207 }
3208 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'creer'))
3209 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'invoice_advance', 'validate'))) {
3210 $this->error = 'Permission denied';
3211 dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS=' . getDolGlobalString('MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3212 return -1;
3213 }
3214 if ((preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) && // empty should not happened, but when it occurs, the test save life
3215 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
3216 ) {
3217 $this->date = dol_now();
3218 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3219 }
3220 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
3221 $last_of_type = $this->willBeLastOfSameType(true);
3222 if (!$last_of_type[0]) {
3223 $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3224 return -1;
3225 }
3226 }
3227
3228 // Check for mandatory fields in thirdparty (defined into setup)
3229 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3230 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_CUSTOMER');
3231 foreach ($array_to_check as $key) {
3232 $keymin = strtolower($key);
3233 if (!property_exists($this->thirdparty, $keymin)) {
3234 continue;
3235 }
3236 $vallabel = $this->thirdparty->$keymin;
3237
3238 $i = (int) preg_replace('/[^0-9]/', '', $key);
3239 if ($i > 0) {
3240 if ($this->thirdparty->isACompany()) {
3241 // Check for mandatory prof id (but only if country is other than ours)
3242 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3243 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3244 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3245 $langs->load("errors");
3246 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3247 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3248 return -1;
3249 }
3250 }
3251 }
3252 } else {
3253 if ($key == 'EMAIL') {
3254 // Check for mandatory
3255 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
3256 $langs->load("errors");
3257 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3258 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3259 return -1;
3260 }
3261 }
3262 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3263 // Check for mandatory
3264 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta)) {
3265 $langs->load("errors");
3266 $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3267 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3268 return -1;
3269 }
3270 }
3271 }
3272 }
3273 }
3274
3275 // Check for mandatory fields in $this
3276 $array_to_check = array('REF_CLIENT' => 'RefCustomer');
3277 foreach ($array_to_check as $key => $val) {
3278 $keymin = strtolower($key);
3279 $vallabel = $this->$keymin;
3280
3281 // Check for mandatory
3282 $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3283 if (!$vallabel && getDolGlobalString($keymandatory)) {
3284 $langs->load("errors");
3285 $error++;
3286 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3287 }
3288 }
3289
3290 $this->db->begin();
3291
3292 // Check parameters
3293 if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3294 // Check that source invoice is known
3295 if ($this->fk_facture_source <= 0) {
3296 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3297 $this->db->rollback();
3298 return -10;
3299 }
3300
3301 // Load source invoice that has been replaced
3302 $facreplaced = new Facture($this->db);
3303 $result = $facreplaced->fetch($this->fk_facture_source);
3304 if ($result <= 0) {
3305 $this->error = $langs->trans("ErrorBadInvoice");
3306 $this->db->rollback();
3307 return -11;
3308 }
3309
3310 // Check that source invoice not already replaced by another one.
3311 $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3312 if ($idreplacement && $idreplacement != $this->id) {
3313 $facreplacement = new Facture($this->db);
3314 $facreplacement->fetch($idreplacement);
3315 $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3316 $this->db->rollback();
3317 return -12;
3318 }
3319
3320 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3321 if ($result < 0) {
3322 $this->error = $facreplaced->error;
3323 $this->db->rollback();
3324 return -13;
3325 }
3326 }
3327
3328 // Define new ref
3329 if ($force_number) {
3330 $num = $force_number;
3331 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3332 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3333 $this->date = dol_now();
3334 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3335 }
3336 $num = $this->getNextNumRef($this->thirdparty);
3337 } else {
3338 $num = $this->ref;
3339 }
3340
3341 $this->newref = dol_sanitizeFileName($num);
3342
3343 if ($num) {
3344 $this->update_price(1);
3345
3346 // Validate
3347 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3348 $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)."'";
3349 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3350 $sql .= ", datef='".$this->db->idate($this->date)."'";
3351 $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3352 }
3353 $sql .= " WHERE rowid = ".((int) $this->id);
3354
3355 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3356 $resql = $this->db->query($sql);
3357 if (!$resql) {
3358 $this->error = $this->db->lasterror();
3359 $error++;
3360 }
3361
3362 // We check if the invoice was provisional
3363 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref))) {
3364 // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
3365 }
3366
3367 if (!$error) {
3368 // Define third party as a customer
3369 $result = $this->thirdparty->setAsCustomer();
3370
3371 // If active (STOCK_CALCULATE_ON_BILL), we decrement the main product and its components at invoice validation
3372 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3373 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3374 $langs->load("agenda");
3375
3376 // Loop on each line
3377 $cpt = count($this->lines);
3378 for ($i = 0; $i < $cpt; $i++) {
3379 if ($this->lines[$i]->fk_product > 0) {
3380 $mouvP = new MouvementStock($this->db);
3381 $mouvP->origin = &$this; // deprecated
3382 $mouvP->setOrigin($this->element, $this->id);
3383
3384 // We decrease stock for product
3385 if ($this->type == self::TYPE_CREDIT_NOTE) {
3386 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3387 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3388 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num), '', '', $this->lines[$i]->batch);
3389 if ($result < 0) {
3390 $error++;
3391 $this->error = $mouvP->error;
3392 $this->errors = array_merge($this->errors, $mouvP->errors);
3393 }
3394 } else {
3395 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3396 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3397
3398 $is_batch_line = false;
3399 if ($batch_rule > 0) {
3400 $productStatic->fetch($this->lines[$i]->fk_product);
3401 if ($productStatic->hasbatch()) {
3402 $is_batch_line = true;
3403 $product_qty_remain = $this->lines[$i]->qty;
3404
3405 $sortfield = null;
3406 $sortorder = null;
3407 // find lot/serial by sellby (DLC) and eatby dates (DLUO) first
3409 $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3410 $sortorder = 'ASC,ASC,ASC,ASC';
3411 }
3412
3413 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (getDolGlobalInt('STOCK_ALLOW_NEGATIVE_TRANSFER') ? null : 0), $sortfield, $sortorder);
3414 if (!is_array($resBatchList)) {
3415 $error++;
3416 $this->error = $this->db->lasterror();
3417 }
3418
3419 if (!$error) {
3420 $batchList = $resBatchList;
3421 if (empty($batchList)) {
3422 $error++;
3423 $langs->load('errors');
3424 $warehouseStatic->fetch($idwarehouse);
3425 $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3426 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3427 }
3428
3429 foreach ($batchList as $batch) {
3430 if ($batch->qty <= 0) {
3431 continue; // try to decrement only batches have positive quantity first
3432 }
3433
3434 // enough quantity in this batch
3435 if ($batch->qty >= $product_qty_remain) {
3436 $product_batch_qty = $product_qty_remain;
3437 } else {
3438 // not enough (take all in batch)
3439 $product_batch_qty = $batch->qty;
3440 }
3441 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3442 if ($result < 0) {
3443 $error++;
3444 $this->error = $mouvP->error;
3445 $this->errors = array_merge($this->errors, $mouvP->errors);
3446 break;
3447 }
3448
3449 $product_qty_remain -= $product_batch_qty;
3450 // all product quantity was decremented
3451 if ($product_qty_remain <= 0) {
3452 break;
3453 }
3454 }
3455
3456 if (!$error && $product_qty_remain > 0) {
3457 if (getDolGlobalInt('STOCK_ALLOW_NEGATIVE_TRANSFER')) {
3458 // take in the first batch
3459 $batch = $batchList[0];
3460 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3461 if ($result < 0) {
3462 $error++;
3463 $this->error = $mouvP->error;
3464 $this->errors = array_merge($this->errors, $mouvP->errors);
3465 }
3466 } else {
3467 $error++;
3468 $langs->load('errors');
3469 $warehouseStatic->fetch($idwarehouse);
3470 $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3471 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3472 }
3473 }
3474 }
3475 }
3476 }
3477
3478 if (!$is_batch_line) { // If stock move not yet processed
3479 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3480 if ($result < 0) {
3481 $error++;
3482 $this->error = $mouvP->error;
3483 $this->errors = array_merge($this->errors, $mouvP->errors);
3484 }
3485 }
3486 }
3487 }
3488 }
3489 }
3490 }
3491
3492 /*
3493 * 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%)
3494 * So we can continue to create new invoice situation
3495 */
3496 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3497 $invoice_situation = new Facture($this->db);
3498 $result = $invoice_situation->fetch($this->fk_facture_source);
3499 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3500 $invoice_situation->situation_final = 0;
3501 // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3502 $result = $invoice_situation->setFinal($user, 1);
3503 }
3504 if ($result < 0) {
3505 $this->error = $invoice_situation->error;
3506 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3507 $error++;
3508 }
3509 }
3510
3511 // Trigger calls
3512 if (!$error && !$notrigger) {
3513 // Call trigger
3514 $result = $this->call_trigger('BILL_VALIDATE', $user);
3515 if ($result < 0) {
3516 $error++;
3517 }
3518 // End call triggers
3519 }
3520
3521 if (!$error) {
3522 $this->oldref = $this->ref;
3523
3524 // Rename directory if dir was a temporary ref
3525 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
3526 // Now we rename also files into index
3527 $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)."'";
3528 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3529 $resql = $this->db->query($sql);
3530 if (!$resql) {
3531 $error++;
3532 $this->error = $this->db->lasterror();
3533 }
3534 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'facture/".$this->db->escape($this->newref)."'";
3535 $sql .= " WHERE filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3536 $resql = $this->db->query($sql);
3537 if (!$resql) {
3538 $error++;
3539 $this->error = $this->db->lasterror();
3540 }
3541
3542 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
3543 $oldref = dol_sanitizeFileName($this->ref);
3544 $newref = dol_sanitizeFileName($num);
3545 $dirsource = $conf->facture->dir_output.'/'.$oldref;
3546 $dirdest = $conf->facture->dir_output.'/'.$newref;
3547 if (!$error && file_exists($dirsource)) {
3548 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
3549
3550 if (@rename($dirsource, $dirdest)) {
3551 dol_syslog("Rename ok");
3552 // Rename docs starting with $oldref with $newref
3553 $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
3554 foreach ($listoffiles as $fileentry) {
3555 $dirsource = $fileentry['name'];
3556 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
3557 $dirsource = $fileentry['path'].'/'.$dirsource;
3558 $dirdest = $fileentry['path'].'/'.$dirdest;
3559 @rename($dirsource, $dirdest);
3560 }
3561 }
3562 }
3563 }
3564 }
3565
3566 if (!$error && !$this->is_last_in_cycle()) {
3567 if (!$this->updatePriceNextInvoice($langs)) {
3568 $error++;
3569 }
3570 }
3571
3572 // Set new ref and define current status
3573 if (!$error) {
3574 $this->ref = $num;
3575 $this->statut = self::STATUS_VALIDATED; // deprecated
3577 $this->date_validation = $now;
3578 $i = 0;
3579
3580 if (getDolGlobalString('INVOICE_USE_SITUATION')) {
3581 $final = true;
3582 $nboflines = count($this->lines);
3583 while (($i < $nboflines) && $final) {
3584 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3585 $previousprogress = $this->lines[$i]->get_allprev_progress($this->lines[$i]->fk_facture);
3586 $current_progress = floatval($this->lines[$i]->situation_percent);
3587 $full_progress = $previousprogress + $current_progress;
3588 $final = ($full_progress == 100);
3589 } else {
3590 $final = ($this->lines[$i]->situation_percent == 100);
3591 }
3592 $i++;
3593 }
3594
3595 if (empty($final)) {
3596 $this->situation_final = 0;
3597 } else {
3598 $this->situation_final = 1;
3599 }
3600
3601 $this->setFinal($user);
3602 }
3603 }
3604 } else {
3605 $error++;
3606 }
3607
3608 if (!$error) {
3609 $this->db->commit();
3610 return 1;
3611 } else {
3612 $this->db->rollback();
3613 return -1;
3614 }
3615 }
3616
3623 public function updatePriceNextInvoice(&$langs)
3624 {
3625 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3626 $is_last = $next_invoice->is_last_in_cycle();
3627
3628 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3629 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3630 return false;
3631 }
3632
3633 foreach ($next_invoice->lines as $line) {
3634 $result = $next_invoice->updateline(
3635 $line->id,
3636 $line->desc,
3637 $line->subprice,
3638 $line->qty,
3639 $line->remise_percent,
3640 $line->date_start,
3641 $line->date_end,
3642 $line->tva_tx,
3643 $line->localtax1_tx,
3644 $line->localtax2_tx,
3645 'HT',
3646 $line->info_bits,
3647 $line->product_type,
3648 $line->fk_parent_line,
3649 0,
3650 $line->fk_fournprice,
3651 $line->pa_ht,
3652 $line->label,
3653 $line->special_code,
3654 $line->array_options,
3655 $line->situation_percent,
3656 $line->fk_unit
3657 );
3658
3659 if ($result < 0) {
3660 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3661 return false;
3662 }
3663 }
3664
3665 break; // Only the next invoice and not each next invoice
3666 }
3667
3668 return true;
3669 }
3670
3678 public function setDraft($user, $idwarehouse = -1)
3679 {
3680 // phpcs:enable
3681 global $conf, $langs;
3682
3683 $error = 0;
3684
3685 if ($this->status == self::STATUS_DRAFT) {
3686 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
3687 return 0;
3688 }
3689
3690 dol_syslog(__METHOD__, LOG_DEBUG);
3691
3692 $this->db->begin();
3693
3694 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3695 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
3696 $sql .= " WHERE rowid = ".((int) $this->id);
3697
3698 $result = $this->db->query($sql);
3699 if ($result) {
3700 if (!$error) {
3701 $this->oldcopy = clone $this;
3702 }
3703
3704 // If we decrease stock on invoice validation, we increase back
3705 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
3706 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3707 $langs->load("agenda");
3708
3709 $num = count($this->lines);
3710 for ($i = 0; $i < $num; $i++) {
3711 if ($this->lines[$i]->fk_product > 0) {
3712 $mouvP = new MouvementStock($this->db);
3713 $mouvP->origin = &$this;
3714 $mouvP->setOrigin($this->element, $this->id);
3715 // We decrease stock for product
3716 if ($this->type == self::TYPE_CREDIT_NOTE) {
3717 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
3718 } else {
3719 $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
3720 }
3721 }
3722 }
3723 }
3724
3725 if ($error == 0) {
3726 $old_statut = $this->status;
3727 $this->statut = self::STATUS_DRAFT; // deprecated
3728 $this->status = self::STATUS_DRAFT;
3729
3730 // Call trigger
3731 $result = $this->call_trigger('BILL_UNVALIDATE', $user);
3732 if ($result < 0) {
3733 $error++;
3734 $this->statut = $old_statut; // deprecated
3735 $this->status = $old_statut;
3736 }
3737 // End call triggers
3738 } else {
3739 $this->db->rollback();
3740 return -1;
3741 }
3742
3743 if ($error == 0) {
3744 $this->db->commit();
3745 return 1;
3746 } else {
3747 $this->db->rollback();
3748 return -1;
3749 }
3750 } else {
3751 $this->error = $this->db->error();
3752 $this->db->rollback();
3753 return -1;
3754 }
3755 }
3756
3757
3799 public function addline(
3800 $desc,
3801 $pu_ht,
3802 $qty,
3803 $txtva,
3804 $txlocaltax1 = 0,
3805 $txlocaltax2 = 0,
3806 $fk_product = 0,
3807 $remise_percent = 0,
3808 $date_start = '',
3809 $date_end = '',
3810 $fk_code_ventilation = 0,
3811 $info_bits = 0,
3812 $fk_remise_except = 0,
3813 $price_base_type = 'HT',
3814 $pu_ttc = 0,
3815 $type = 0,
3816 $rang = -1,
3817 $special_code = 0,
3818 $origin = '',
3819 $origin_id = 0,
3820 $fk_parent_line = 0,
3821 $fk_fournprice = null,
3822 $pa_ht = 0,
3823 $label = '',
3824 $array_options = array(),
3825 $situation_percent = 100,
3826 $fk_prev_id = 0,
3827 $fk_unit = null,
3828 $pu_ht_devise = 0,
3829 $ref_ext = '',
3830 $noupdateafterinsertline = 0
3831 ) {
3832 // Deprecation warning
3833 if ($label) {
3834 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3835 //var_dump(debug_backtrace(false));exit;
3836 }
3837
3838 global $mysoc, $conf, $langs;
3839
3840 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);
3841
3842 if ($this->status == self::STATUS_DRAFT) {
3843 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3844
3845 // Clean parameters
3846 if (empty($remise_percent)) {
3847 $remise_percent = 0;
3848 }
3849 if (empty($qty)) {
3850 $qty = 0;
3851 }
3852 if (empty($info_bits)) {
3853 $info_bits = 0;
3854 }
3855 if (empty($rang)) {
3856 $rang = 0;
3857 }
3858 if (empty($fk_code_ventilation)) {
3859 $fk_code_ventilation = 0;
3860 }
3861 if (empty($txtva)) {
3862 $txtva = 0;
3863 }
3864 if (empty($txlocaltax1)) {
3865 $txlocaltax1 = 0;
3866 }
3867 if (empty($txlocaltax2)) {
3868 $txlocaltax2 = 0;
3869 }
3870 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3871 $fk_parent_line = 0;
3872 }
3873 if (empty($fk_prev_id)) {
3874 $fk_prev_id = 'null';
3875 }
3876 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '' || $situation_percent == null) {
3877 // INVOICE_USE_SITUATION = 2 - Lines situation percent on new lines must be 0 (No cumulative)
3878 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalInt('INVOICE_USE_SITUATION') == 2 && (int) $situation_percent < 100) {
3879 $situation_percent = 0;
3880 } else {
3881 $situation_percent = 100;
3882 }
3883 }
3884 if (empty($ref_ext)) {
3885 $ref_ext = '';
3886 }
3887
3888 $remise_percent = (float) price2num($remise_percent);
3889 $qty = price2num($qty);
3890 $pu_ht = price2num($pu_ht);
3891 $pu_ht_devise = price2num($pu_ht_devise);
3892 $pu_ttc = price2num($pu_ttc);
3893 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
3894 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3895 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3896 }
3897 $txlocaltax1 = price2num($txlocaltax1);
3898 $txlocaltax2 = price2num($txlocaltax2);
3899
3900 if ($price_base_type == 'HT') {
3901 $pu = $pu_ht;
3902 } else {
3903 $pu = $pu_ttc;
3904 }
3905
3906 // Check parameters
3907 if ($type < 0) {
3908 return -1;
3909 }
3910
3911 if ($date_start && $date_end && $date_start > $date_end) {
3912 $langs->load("errors");
3913 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3914 return -1;
3915 }
3916
3917 $this->db->begin();
3918
3919 $product_type = $type;
3920 if (!empty($fk_product) && $fk_product > 0) {
3921 $product = new Product($this->db);
3922 $result = $product->fetch($fk_product);
3923 $product_type = $product->type;
3924
3925 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
3926 $langs->load("errors");
3927 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3928 $this->db->rollback();
3929 return -3;
3930 }
3931 }
3932
3933 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3934
3935 // Clean vat code
3936 $reg = array();
3937 $vat_src_code = '';
3938 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3939 $vat_src_code = $reg[1];
3940 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3941 }
3942
3943 // Calcul du total TTC et de la TVA pour la ligne a partir de
3944 // qty, pu, remise_percent et txtva
3945 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3946 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3947
3948 $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);
3949
3950 $total_ht = $tabprice[0];
3951 $total_tva = $tabprice[1];
3952 $total_ttc = $tabprice[2];
3953 $total_localtax1 = $tabprice[9];
3954 $total_localtax2 = $tabprice[10];
3955 $pu_ht = $tabprice[3];
3956
3957 // MultiCurrency
3958 $multicurrency_total_ht = $tabprice[16];
3959 $multicurrency_total_tva = $tabprice[17];
3960 $multicurrency_total_ttc = $tabprice[18];
3961 $pu_ht_devise = $tabprice[19];
3962
3963 // Rank to use
3964 $ranktouse = $rang;
3965 if ($ranktouse == -1) {
3966 $rangmax = $this->line_max($fk_parent_line);
3967 $ranktouse = $rangmax + 1;
3968 }
3969
3970 // Insert line
3971 $this->line = new FactureLigne($this->db);
3972
3973 $this->line->context = $this->context;
3974
3975 $this->line->fk_facture = $this->id;
3976 $this->line->label = $label; // deprecated
3977 $this->line->desc = $desc;
3978 $this->line->ref_ext = $ref_ext;
3979
3980 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
3981 $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
3982
3983 $this->line->vat_src_code = $vat_src_code;
3984 $this->line->tva_tx = $txtva;
3985 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3986 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3987 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
3988 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
3989
3990 $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
3991 $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
3992 $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
3993 $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
3994 $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
3995
3996 $this->line->fk_product = $fk_product;
3997 $this->line->product_type = $product_type;
3998 $this->line->remise_percent = $remise_percent;
3999 $this->line->date_start = $date_start;
4000 $this->line->date_end = $date_end;
4001 $this->line->fk_code_ventilation = $fk_code_ventilation;
4002 $this->line->rang = $ranktouse;
4003 $this->line->info_bits = $info_bits;
4004 $this->line->fk_remise_except = $fk_remise_except;
4005
4006 $this->line->special_code = $special_code;
4007 $this->line->fk_parent_line = $fk_parent_line;
4008 $this->line->origin = $origin;
4009 $this->line->origin_id = $origin_id;
4010 $this->line->situation_percent = $situation_percent;
4011 $this->line->fk_prev_id = $fk_prev_id;
4012 $this->line->fk_unit = $fk_unit;
4013
4014 // infos margin
4015 $this->line->fk_fournprice = $fk_fournprice;
4016 $this->line->pa_ht = $pa_ht;
4017
4018 // Multicurrency
4019 $this->line->fk_multicurrency = $this->fk_multicurrency;
4020 $this->line->multicurrency_code = $this->multicurrency_code;
4021 $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
4022
4023 $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
4024 $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
4025 $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
4026
4027 if (is_array($array_options) && count($array_options) > 0) {
4028 $this->line->array_options = $array_options;
4029 }
4030
4031 $result = $this->line->insert();
4032 if ($result > 0) {
4033 // Reorder if child line
4034 if (!empty($fk_parent_line)) {
4035 $this->line_order(true, 'DESC');
4036 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
4037 $linecount = count($this->lines);
4038 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4039 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
4040 }
4041 }
4042
4043 // Mise a jour information denormalisees au niveau de la facture meme
4044 if (empty($noupdateafterinsertline)) {
4045 $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.
4046 }
4047
4048 if ($result > 0) {
4049 $this->db->commit();
4050 return $this->line->id;
4051 } else {
4052 $this->error = $this->db->lasterror();
4053 $this->db->rollback();
4054 return -1;
4055 }
4056 } else {
4057 $this->error = $this->line->error;
4058 $this->errors = $this->line->errors;
4059 $this->db->rollback();
4060 return -2;
4061 }
4062 } else {
4063 $this->errors[] = 'status of invoice must be Draft to allow use of ->addline()';
4064 dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4065 return -3;
4066 }
4067 }
4068
4100 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)
4101 {
4102 global $conf, $user;
4103 // Deprecation warning
4104 if ($label) {
4105 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4106 }
4107
4108 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4109
4110 global $mysoc, $langs;
4111
4112 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);
4113
4114 if ($this->status == self::STATUS_DRAFT) {
4115 if (!$this->is_last_in_cycle() && empty($this->error)) {
4116 if (!$this->checkProgressLine($rowid, $situation_percent)) {
4117 if (!$this->error) {
4118 $this->error = $langs->trans('invoiceLineProgressError');
4119 }
4120 return -3;
4121 }
4122 }
4123
4124 if ($date_start && $date_end && $date_start > $date_end) {
4125 $langs->load("errors");
4126 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4127 return -1;
4128 }
4129
4130 $this->db->begin();
4131
4132 // Clean parameters
4133 if (empty($qty)) {
4134 $qty = 0;
4135 }
4136 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4137 $fk_parent_line = 0;
4138 }
4139 if (empty($special_code) || $special_code == 3) {
4140 $special_code = 0;
4141 }
4142 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '' || $situation_percent == null) {
4143 // INVOICE_USE_SITUATION = 2 - If there is no progress on a line, percent must not be 100% (No cumulative)
4144 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalInt('INVOICE_USE_SITUATION') == 2 && (int) $situation_percent < 100) {
4145 $situation_percent = 0;
4146 } else {
4147 $situation_percent = 100;
4148 }
4149 }
4150 if (empty($ref_ext)) {
4151 $ref_ext = '';
4152 }
4153
4154 $remise_percent = (float) price2num($remise_percent);
4155 $qty = price2num($qty);
4156 $pu = price2num($pu);
4157 $pu_ht_devise = price2num($pu_ht_devise);
4158 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4159 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4160 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4161 }
4162 $txlocaltax1 = (float) price2num($txlocaltax1);
4163 $txlocaltax2 = (float) price2num($txlocaltax2);
4164
4165 // Check parameters
4166 if ($type < 0) {
4167 return -1;
4168 }
4169
4170 // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
4171 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
4172 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
4173
4174 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4175
4176 // Clean vat code
4177 $reg = array();
4178 $vat_src_code = '';
4179 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4180 $vat_src_code = $reg[1];
4181 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4182 }
4183
4184 $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);
4185
4186 $total_ht = $tabprice[0];
4187 $total_tva = $tabprice[1];
4188 $total_ttc = $tabprice[2];
4189 $total_localtax1 = $tabprice[9];
4190 $total_localtax2 = $tabprice[10];
4191 $pu_ht = $tabprice[3];
4192 $pu_tva = $tabprice[4];
4193 $pu_ttc = $tabprice[5];
4194
4195 // MultiCurrency
4196 $multicurrency_total_ht = $tabprice[16];
4197 $multicurrency_total_tva = $tabprice[17];
4198 $multicurrency_total_ttc = $tabprice[18];
4199 $pu_ht_devise = $tabprice[19];
4200
4201 // Old properties: $price, $remise (deprecated)
4202 $price = $pu;
4203 $remise = 0;
4204 if ($remise_percent > 0) {
4205 $remise = round(((float) $pu * (float) $remise_percent / 100), 2);
4206 $price = ((float) $pu - $remise);
4207 }
4208 $price = price2num($price);
4209
4210 //Fetch current line from the database and then clone the object and set it in $oldline property
4211 $line = new FactureLigne($this->db);
4212 $line->fetch($rowid);
4213 $line->fetch_optionals();
4214
4215 if (!empty($line->fk_product)) {
4216 $product = new Product($this->db);
4217 $result = $product->fetch($line->fk_product);
4218 $product_type = $product->type;
4219
4220 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4221 $langs->load("errors");
4222 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4223 $this->db->rollback();
4224 return -3;
4225 }
4226 }
4227
4228 $staticline = clone $line;
4229
4230 $line->oldline = $staticline;
4231 $this->line = $line;
4232 $this->line->context = $this->context;
4233 $this->line->rang = $rang;
4234
4235 // Reorder if fk_parent_line change
4236 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4237 $rangmax = $this->line_max($fk_parent_line);
4238 $this->line->rang = $rangmax + 1;
4239 }
4240
4241 $this->line->id = $rowid;
4242 $this->line->rowid = $rowid;
4243 $this->line->label = $label;
4244 $this->line->desc = $desc;
4245 $this->line->ref_ext = $ref_ext;
4246 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
4247
4248 $this->line->vat_src_code = $vat_src_code;
4249 $this->line->tva_tx = $txtva;
4250 $this->line->localtax1_tx = $txlocaltax1;
4251 $this->line->localtax2_tx = $txlocaltax2;
4252 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4253 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4254
4255 $this->line->remise_percent = $remise_percent;
4256 $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
4257 $this->line->date_start = $date_start;
4258 $this->line->date_end = $date_end;
4259 $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
4260 $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
4261 $this->line->total_localtax1 = $total_localtax1;
4262 $this->line->total_localtax2 = $total_localtax2;
4263 $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
4264 $this->line->info_bits = $info_bits;
4265 $this->line->special_code = $special_code;
4266 $this->line->product_type = $type;
4267 $this->line->fk_parent_line = $fk_parent_line;
4268 $this->line->skip_update_total = $skip_update_total;
4269 $this->line->situation_percent = $situation_percent;
4270 $this->line->fk_unit = $fk_unit;
4271
4272 $this->line->fk_fournprice = $fk_fournprice;
4273 $this->line->pa_ht = $pa_ht;
4274
4275 // Multicurrency
4276 $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
4277 $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
4278 $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4279 $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4280
4281 if (is_array($array_options) && count($array_options) > 0) {
4282 // We replace values in this->line->array_options only for entries defined into $array_options
4283 foreach ($array_options as $key => $value) {
4284 $this->line->array_options[$key] = $array_options[$key];
4285 }
4286 }
4287
4288 $result = $this->line->update($user, $notrigger);
4289 if ($result > 0) {
4290 // Reorder if child line
4291 if (!empty($fk_parent_line)) {
4292 $this->line_order(true, 'DESC');
4293 }
4294
4295 // Mise a jour info denormalisees au niveau facture
4296 $this->update_price(1, 'auto');
4297 $this->db->commit();
4298 return $result;
4299 } else {
4300 $this->error = $this->line->error;
4301 $this->db->rollback();
4302 return -1;
4303 }
4304 } else {
4305 $this->error = "Invoice statut makes operation forbidden";
4306 return -2;
4307 }
4308 }
4309
4317 public function checkProgressLine($idline, $situation_percent)
4318 {
4319 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4320 INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4321 WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4322
4323 $result = $this->db->query($sql);
4324 if (!$result) {
4325 $this->error = $this->db->error();
4326 return false;
4327 }
4328
4329 $obj = $this->db->fetch_object($result);
4330
4331 if ($obj === null) {
4332 return true;
4333 } else {
4334 return ($situation_percent < $obj->situation_percent);
4335 }
4336 }
4337
4338 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4347 public function update_percent($line, $percent, $update_price = true)
4348 {
4349 // phpcs:enable
4350 global $mysoc, $user;
4351
4352 // Progress should never be changed for discount lines
4353 if (($line->info_bits & 2) == 2) {
4354 return;
4355 }
4356
4357 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4358
4359 // Cap percentages to 100
4360 if ($percent > 100) {
4361 $percent = 100;
4362 }
4363 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4364 $previous_progress = $line->get_allprev_progress($line->fk_facture);
4365 $current_progress = $percent - $previous_progress;
4366 $line->situation_percent = $current_progress;
4367 $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);
4368 } else {
4369 $line->situation_percent = $percent;
4370 $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);
4371 }
4372 $line->total_ht = $tabprice[0];
4373 $line->total_tva = $tabprice[1];
4374 $line->total_ttc = $tabprice[2];
4375 $line->total_localtax1 = $tabprice[9];
4376 $line->total_localtax2 = $tabprice[10];
4377 $line->multicurrency_total_ht = $tabprice[16];
4378 $line->multicurrency_total_tva = $tabprice[17];
4379 $line->multicurrency_total_ttc = $tabprice[18];
4380 $line->update($user);
4381
4382 // sometimes it is better to not update price for each line, ie when updating situation on all lines
4383 if ($update_price) {
4384 $this->update_price(1);
4385 }
4386 }
4387
4395 public function deleteLine($rowid, $id = 0)
4396 {
4397 global $user;
4398
4399 dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4400
4401 if ($this->status != self::STATUS_DRAFT) {
4402 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4403 return -1;
4404 }
4405
4406 $line = new FactureLigne($this->db);
4407
4408 $line->context = $this->context;
4409
4410 // Load line
4411 $result = $line->fetch($rowid);
4412 if (!($result > 0)) {
4413 dol_print_error($this->db, $line->error, $line->errors);
4414 return -1;
4415 }
4416
4417 if ($id > 0 && $line->fk_facture != $id) {
4418 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4419 return -1;
4420 }
4421
4422 $this->db->begin();
4423
4424 // Memorize previous line for triggers
4425 $staticline = clone $line;
4426 $line->oldline = $staticline;
4427
4428 if ($line->delete($user) > 0) {
4429 $result = $this->update_price(1);
4430
4431 if ($result > 0) {
4432 $this->db->commit();
4433 return 1;
4434 } else {
4435 $this->db->rollback();
4436 $this->error = $this->db->lasterror();
4437 return -1;
4438 }
4439 } else {
4440 $this->db->rollback();
4441 $this->error = $line->error;
4442 return -1;
4443 }
4444 }
4445
4446 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4457 public function set_remise($user, $remise, $notrigger = 0)
4458 {
4459 // phpcs:enable
4460 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4461 // @phan-suppress-next-line PhanDeprecatedFunction
4462 return $this->setDiscount($user, $remise, $notrigger);
4463 }
4464
4473 public function setDiscount($user, $remise, $notrigger = 0)
4474 {
4475 // Clean parameters
4476 if (empty($remise)) {
4477 $remise = 0;
4478 }
4479
4480 if ($user->hasRight('facture', 'creer')) {
4481 $remise = (float) price2num($remise, 2);
4482
4483 $error = 0;
4484
4485 $this->db->begin();
4486
4487 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4488 $sql .= " SET remise_percent = ".((float) $remise);
4489 $sql .= " WHERE rowid = ".((int) $this->id);
4490 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
4491
4492 dol_syslog(__METHOD__, LOG_DEBUG);
4493 $resql = $this->db->query($sql);
4494 if (!$resql) {
4495 $this->errors[] = $this->db->error();
4496 $error++;
4497 }
4498
4499 if (!$notrigger && empty($error)) {
4500 // Call trigger
4501 $result = $this->call_trigger('BILL_MODIFY', $user);
4502 if ($result < 0) {
4503 $error++;
4504 }
4505 // End call triggers
4506 }
4507
4508 if (!$error) {
4509 $this->remise_percent = $remise;
4510 $this->update_price(1);
4511
4512 $this->db->commit();
4513 return 1;
4514 } else {
4515 foreach ($this->errors as $errmsg) {
4516 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4517 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4518 }
4519 $this->db->rollback();
4520 return -1 * $error;
4521 }
4522 }
4523
4524 return 0;
4525 }
4526
4527
4528 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4537 /*
4538 public function set_remise_absolue($user, $remise, $notrigger = 0)
4539 {
4540 // phpcs:enable
4541 if (empty($remise)) {
4542 $remise = 0;
4543 }
4544
4545 if ($user->hasRight('facture', 'creer')) {
4546 $error = 0;
4547
4548 $this->db->begin();
4549
4550 $remise = price2num($remise);
4551
4552 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4553 $sql .= ' SET remise_absolue = '.((float) $remise);
4554 $sql .= " WHERE rowid = ".((int) $this->id);
4555 $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4556
4557 dol_syslog(__METHOD__, LOG_DEBUG);
4558 $resql = $this->db->query($sql);
4559 if (!$resql) {
4560 $this->errors[] = $this->db->error();
4561 $error++;
4562 }
4563
4564 if (!$error) {
4565 $this->oldcopy = clone $this;
4566 $this->remise_absolue = $remise;
4567 $this->update_price(1);
4568 }
4569
4570 if (!$notrigger && empty($error)) {
4571 // Call trigger
4572 $result = $this->call_trigger('BILL_MODIFY', $user);
4573 if ($result < 0) {
4574 $error++;
4575 }
4576 // End call triggers
4577 }
4578
4579 if (!$error) {
4580 $this->db->commit();
4581 return 1;
4582 } else {
4583 foreach ($this->errors as $errmsg) {
4584 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4585 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4586 }
4587 $this->db->rollback();
4588 return -1 * $error;
4589 }
4590 }
4591
4592 return 0;
4593 }
4594 */
4595
4604 public function getNextNumRef($soc, $mode = 'next')
4605 {
4606 global $conf, $langs;
4607
4608 if ($this->module_source == 'takepos') {
4609 $langs->load('cashdesk');
4610
4611 $moduleName = 'takepos';
4612 $moduleSourceName = 'Takepos';
4613 $addonConstName = 'TAKEPOS_REF_ADDON';
4614
4615 // Clean parameters (if not defined or using deprecated value)
4616 if (!getDolGlobalString('TAKEPOS_REF_ADDON')) {
4617 $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
4618 }
4619
4620 $addon = getDolGlobalString('TAKEPOS_REF_ADDON');
4621 } else {
4622 $langs->load('bills');
4623
4624 $moduleName = 'facture';
4625 $moduleSourceName = 'Invoice';
4626 $addonConstName = 'FACTURE_ADDON';
4627
4628 // Clean parameters (if not defined or using deprecated value)
4629 if (!getDolGlobalString('FACTURE_ADDON')) {
4630 $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4631 } elseif (getDolGlobalString('FACTURE_ADDON') == 'terre') {
4632 $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4633 } elseif (getDolGlobalString('FACTURE_ADDON') == 'mercure') {
4634 $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
4635 }
4636
4637 $addon = getDolGlobalString('FACTURE_ADDON');
4638 }
4639
4640 if (!empty($addon)) {
4641 dol_syslog("Call getNextNumRef with ".$addonConstName." = " . getDolGlobalString('FACTURE_ADDON').", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
4642
4643 $mybool = false;
4644
4645 $file = $addon.'.php';
4646 $classname = $addon;
4647
4648
4649 // Include file with class
4650 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
4651 foreach ($dirmodels as $reldir) {
4652 $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
4653
4654 // Load file with numbering class (if found)
4655 if (is_file($dir.$file) && is_readable($dir.$file)) {
4656 $mybool = ((bool) include_once $dir.$file) || $mybool;
4657 }
4658 }
4659
4660 // For compatibility
4661 if (!$mybool) {
4662 $file = $addon.'/'.$addon.'.modules.php';
4663 $classname = 'mod_'.$moduleName.'_'.$addon;
4664 $classname = preg_replace('/\-.*$/', '', $classname);
4665 // Include file with class
4666 foreach ($conf->file->dol_document_root as $dirroot) {
4667 $dir = $dirroot.'/core/modules/'.$moduleName.'/';
4668
4669 // Load file with numbering class (if found)
4670 if (is_file($dir.$file) && is_readable($dir.$file)) {
4671 $mybool = (include_once $dir.$file) || $mybool;
4672 }
4673 }
4674 }
4675
4676 if (!$mybool) {
4677 dol_print_error(null, 'Failed to include file '.$file);
4678 return '';
4679 }
4680
4681 $obj = new $classname();
4682 '@phan-var-force CommonNumRefGenerator $obj';
4683
4684 $numref = $obj->getNextValue($soc, $this, $mode);
4685
4686
4691 if ($mode != 'last' && !$numref) {
4692 $this->error = $obj->error;
4693 return '';
4694 }
4695
4696 return $numref;
4697 } else {
4698 $langs->load('errors');
4699 print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4700 return '';
4701 }
4702 }
4703
4710 public function info($id)
4711 {
4712 $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4713 $sql .= ' date_closing as dateclosing,';
4714 $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
4715 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
4716 $sql .= ' WHERE c.rowid = '.((int) $id);
4717
4718 $result = $this->db->query($sql);
4719 if ($result) {
4720 if ($this->db->num_rows($result)) {
4721 $obj = $this->db->fetch_object($result);
4722
4723 $this->id = $obj->rowid;
4724 $this->user_creation_id = $obj->fk_user_author;
4725 $this->user_validation_id = $obj->fk_user_valid;
4726 $this->user_closing_id = $obj->fk_user_closing;
4727
4728 $this->date_creation = $this->db->jdate($obj->datec);
4729 $this->date_modification = $this->db->jdate($obj->datem);
4730 $this->date_validation = $this->db->jdate($obj->datev);
4731 $this->date_closing = $this->db->jdate($obj->dateclosing);
4732 }
4733 $this->db->free($result);
4734 } else {
4735 dol_print_error($this->db);
4736 }
4737 }
4738
4739
4740 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4754 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
4755 {
4756 // phpcs:enable
4757 global $user;
4758
4759 $ga = array();
4760
4761 $sql = "SELECT s.rowid, s.nom as name, s.client,";
4762 $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
4763 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
4764 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4765 $sql .= " AND f.fk_soc = s.rowid";
4766 if ($draft) {
4767 $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
4768 }
4769 if (is_object($excluser)) {
4770 $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
4771 }
4772 // If the internal user must only see his customers, force searching by him
4773 $search_sale = 0;
4774 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
4775 $search_sale = $user->id;
4776 }
4777 // Search on sale representative
4778 if ($search_sale && $search_sale != '-1') {
4779 if ($search_sale == -2) {
4780 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4781 } elseif ($search_sale > 0) {
4782 $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).")";
4783 }
4784 }
4785 // Search on socid
4786 if ($socid) {
4787 $sql .= " AND f.fk_soc = ".((int) $socid);
4788 }
4789 $sql .= $this->db->order($sortfield, $sortorder);
4790 $sql .= $this->db->plimit($limit, $offset);
4791
4792 $result = $this->db->query($sql);
4793 if ($result) {
4794 $numc = $this->db->num_rows($result);
4795 if ($numc) {
4796 $i = 0;
4797 while ($i < $numc) {
4798 $obj = $this->db->fetch_object($result);
4799
4800 if ($shortlist == 1) {
4801 $ga[$obj->fid] = $obj->ref;
4802 } elseif ($shortlist == 2) {
4803 $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
4804 } else {
4805 $ga[$i]['id'] = $obj->fid;
4806 $ga[$i]['ref'] = $obj->ref;
4807 $ga[$i]['name'] = $obj->name;
4808 }
4809 $i++;
4810 }
4811 }
4812 return $ga;
4813 } else {
4814 dol_print_error($this->db);
4815 return -1;
4816 }
4817 }
4818
4819
4820 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4829 public function list_replacable_invoices($socid = 0)
4830 {
4831 // phpcs:enable
4832 global $conf;
4833
4834 $return = array();
4835
4836 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4837 $sql .= " ff.rowid as rowidnext";
4838 //$sql .= ", SUM(pf.amount) as alreadypaid";
4839 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4840 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4841 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
4842 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
4843 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4844 $sql .= " AND f.paye = 0"; // Not paid completely
4845 $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
4846 $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
4847 if ($socid > 0) {
4848 $sql .= " AND f.fk_soc = ".((int) $socid);
4849 }
4850 //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
4851 $sql .= " ORDER BY f.ref";
4852
4853 dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
4854 $resql = $this->db->query($sql);
4855 if ($resql) {
4856 while ($obj = $this->db->fetch_object($resql)) {
4857 $return[$obj->rowid] = array(
4858 'id' => $obj->rowid,
4859 'ref' => $obj->ref,
4860 'status' => $obj->status,
4861 'paid' => $obj->paid,
4862 'alreadypaid' => 0
4863 );
4864 }
4865 //print_r($return);
4866 return $return;
4867 } else {
4868 $this->error = $this->db->error();
4869 return -1;
4870 }
4871 }
4872
4873
4874 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4883 public function list_qualified_avoir_invoices($socid = 0)
4884 {
4885 // phpcs:enable
4886 global $conf;
4887
4888 $return = array();
4889
4890
4891 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4892 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4893 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4894 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
4895 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4896 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4897 // $sql.= " WHERE f.fk_statut >= 1";
4898 // $sql.= " AND (f.paye = 1"; // Classee payee completement
4899 // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
4900 $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de replacement
4901 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
4902
4903 if (getDolGlobalString('INVOICE_USE_SITUATION_CREDIT_NOTE')) {
4904 // Keep invoices that are not situation invoices or that are the last in series if it is a situation invoice
4905 $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
4906 $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID because of the group by later
4907 $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
4908 $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
4909 $sql .= " AND fs.type = ".self::TYPE_SITUATION;
4910 $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4911 if ($socid > 0) {
4912 $sql .= " AND fs.fk_soc = ".((int) $socid);
4913 }
4914 $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
4915 $sql .= ")";
4916 } else {
4917 $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
4918 }
4919
4920 if ($socid > 0) {
4921 $sql .= " AND f.fk_soc = ".((int) $socid);
4922 }
4923 $sql .= " ORDER BY f.ref";
4924
4925 dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
4926 $resql = $this->db->query($sql);
4927 if ($resql) {
4928 while ($obj = $this->db->fetch_object($resql)) {
4929 $qualified = 0;
4930 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4931 $qualified = 1;
4932 }
4933 if ($obj->fk_statut == self::STATUS_CLOSED) {
4934 $qualified = 1;
4935 }
4936 if ($qualified) {
4937 //$ref=$obj->ref;
4938 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4939 $return[$obj->rowid] = array('ref' => $obj->ref, 'status' => $obj->fk_statut, 'type' => $obj->type, 'paye' => $obj->paye, 'paymentornot' => $paymentornot);
4940 }
4941 }
4942
4943 return $return;
4944 } else {
4945 $this->error = $this->db->error();
4946 return -1;
4947 }
4948 }
4949
4950
4951 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4958 public function load_board($user)
4959 {
4960 // phpcs:enable
4961 global $conf, $langs;
4962
4963 $clause = " WHERE";
4964
4965 $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
4966 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4967 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
4968 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4969 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4970 $clause = " AND";
4971 }
4972 $sql .= $clause." f.paye=0";
4973 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4974 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
4975 if ($user->socid) {
4976 $sql .= " AND f.fk_soc = ".((int) $user->socid);
4977 }
4978
4979 $resql = $this->db->query($sql);
4980 if ($resql) {
4981 $langs->load("bills");
4982 $now = dol_now();
4983
4984 $response = new WorkboardResponse();
4985 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4986 $response->label = $langs->trans("CustomerBillsUnpaid");
4987 $response->labelShort = $langs->trans("Unpaid");
4988 $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4989 $response->img = img_object('', "bill");
4990
4991 $generic_facture = new Facture($this->db);
4992
4993 while ($obj = $this->db->fetch_object($resql)) {
4994 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4995 $generic_facture->statut = $obj->status;
4996 $generic_facture->status = $obj->status;
4997
4998 $response->nbtodo++;
4999 $response->total += $obj->total_ht;
5000
5001 if ($generic_facture->hasDelay()) {
5002 $response->nbtodolate++;
5003 $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5004 }
5005 }
5006
5007 $this->db->free($resql);
5008 return $response;
5009 } else {
5010 dol_print_error($this->db);
5011 $this->error = $this->db->error();
5012 return -1;
5013 }
5014 }
5015
5016
5017 /* gestion des contacts d'une facture */
5018
5024 public function getIdBillingContact()
5025 {
5026 return $this->getIdContact('external', 'BILLING');
5027 }
5028
5034 public function getIdShippingContact()
5035 {
5036 return $this->getIdContact('external', 'SHIPPING');
5037 }
5038
5039
5048 public function initAsSpecimen($option = '')
5049 {
5050 global $conf, $langs, $user;
5051
5052 $now = dol_now();
5053 $arraynow = dol_getdate($now);
5054 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
5055
5056 // Load array of products prodids
5057 $num_prods = 0;
5058 $prodids = array();
5059 $sql = "SELECT rowid";
5060 $sql .= " FROM ".MAIN_DB_PREFIX."product";
5061 $sql .= " WHERE entity IN (".getEntity('product').")";
5062 $sql .= $this->db->plimit(100);
5063
5064 $resql = $this->db->query($sql);
5065 if ($resql) {
5066 $num_prods = $this->db->num_rows($resql);
5067 $i = 0;
5068 while ($i < $num_prods) {
5069 $i++;
5070 $row = $this->db->fetch_row($resql);
5071 $prodids[$i] = $row[0];
5072 }
5073 }
5074 //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
5075 if (empty($num_prods)) {
5076 $num_prods = 1;
5077 $prodids[$num_prods] = 1;
5078 }
5079
5080 // Initialize parameters
5081 $this->id = 0;
5082 $this->entity = $conf->entity;
5083 $this->ref = 'SPECIMEN';
5084 $this->specimen = 1;
5085 $this->socid = 1;
5086 $this->date = $nownotime;
5087 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5088 $this->cond_reglement_id = 1;
5089 $this->cond_reglement_code = 'RECEP';
5090 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
5091 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
5092 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
5093
5094 $this->note_public = 'This is a comment (public)';
5095 $this->note_private = 'This is a comment (private)';
5096 $this->note = 'This is a comment (private)';
5097
5098 $this->fk_user_author = $user->id;
5099
5100 $this->multicurrency_tx = 1;
5101 $this->multicurrency_code = $conf->currency;
5102
5103 $this->fk_incoterms = 0;
5104 $this->location_incoterms = '';
5105
5106 if (empty($option) || $option != 'nolines') {
5107 // Lines
5108 $nbp = 5;
5109 $xnbp = 0;
5110 while ($xnbp < $nbp) {
5111 $line = new FactureLigne($this->db);
5112 $line->desc = $langs->trans("Description")." ".$xnbp;
5113 $line->qty = 1;
5114 $line->subprice = 100;
5115 $line->tva_tx = 19.6;
5116 $line->localtax1_tx = 0;
5117 $line->localtax2_tx = 0;
5118 $line->remise_percent = 0;
5119 if ($xnbp == 1) { // Qty is negative (product line)
5120 $prodid = mt_rand(1, $num_prods);
5121 $line->fk_product = $prodids[$prodid];
5122 $line->qty = -1;
5123 $line->total_ht = -100;
5124 $line->total_ttc = -119.6;
5125 $line->total_tva = -19.6;
5126 $line->multicurrency_total_ht = -200;
5127 $line->multicurrency_total_ttc = -239.2;
5128 $line->multicurrency_total_tva = -39.2;
5129 } elseif ($xnbp == 2) { // UP is negative (free line)
5130 $line->subprice = -100;
5131 $line->total_ht = -100;
5132 $line->total_ttc = -119.6;
5133 $line->total_tva = -19.6;
5134 $line->remise_percent = 0;
5135 $line->multicurrency_total_ht = -200;
5136 $line->multicurrency_total_ttc = -239.2;
5137 $line->multicurrency_total_tva = -39.2;
5138 } elseif ($xnbp == 3) { // Discount is 50% (product line)
5139 $prodid = mt_rand(1, $num_prods);
5140 $line->fk_product = $prodids[$prodid];
5141 $line->total_ht = 50;
5142 $line->total_ttc = 59.8;
5143 $line->total_tva = 9.8;
5144 $line->multicurrency_total_ht = 100;
5145 $line->multicurrency_total_ttc = 119.6;
5146 $line->multicurrency_total_tva = 19.6;
5147 $line->remise_percent = 50;
5148 } else { // (product line)
5149 $prodid = mt_rand(1, $num_prods);
5150 $line->fk_product = $prodids[$prodid];
5151 $line->total_ht = 100;
5152 $line->total_ttc = 119.6;
5153 $line->total_tva = 19.6;
5154 $line->multicurrency_total_ht = 200;
5155 $line->multicurrency_total_ttc = 239.2;
5156 $line->multicurrency_total_tva = 39.2;
5157 $line->remise_percent = 0;
5158 }
5159
5160 $this->lines[$xnbp] = $line;
5161
5162
5163 $this->total_ht += $line->total_ht;
5164 $this->total_tva += $line->total_tva;
5165 $this->total_ttc += $line->total_ttc;
5166
5167 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5168 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5169 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5170
5171 $xnbp++;
5172 }
5173 $this->revenuestamp = 0;
5174
5175 // Add a line "offered"
5176 $line = new FactureLigne($this->db);
5177 $line->desc = $langs->trans("Description")." (offered line)";
5178 $line->qty = 1;
5179 $line->subprice = 100;
5180 $line->tva_tx = 19.6;
5181 $line->localtax1_tx = 0;
5182 $line->localtax2_tx = 0;
5183 $line->remise_percent = 100;
5184 $line->total_ht = 0;
5185 $line->total_ttc = 0; // 90 * 1.196
5186 $line->total_tva = 0;
5187 $line->multicurrency_total_ht = 0;
5188 $line->multicurrency_total_ttc = 0;
5189 $line->multicurrency_total_tva = 0;
5190 $prodid = mt_rand(1, $num_prods);
5191 $line->fk_product = $prodids[$prodid];
5192
5193 $this->lines[$xnbp] = $line;
5194 $xnbp++;
5195 }
5196
5197 return 1;
5198 }
5199
5205 public function loadStateBoard()
5206 {
5207 global $conf, $user;
5208
5209 $this->nb = array();
5210
5211 $clause = "WHERE";
5212
5213 $sql = "SELECT count(f.rowid) as nb";
5214 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5215 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
5216 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5217 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5218 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5219 $clause = "AND";
5220 }
5221 $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
5222
5223 $resql = $this->db->query($sql);
5224 if ($resql) {
5225 while ($obj = $this->db->fetch_object($resql)) {
5226 $this->nb["invoices"] = $obj->nb;
5227 }
5228 $this->db->free($resql);
5229 return 1;
5230 } else {
5231 dol_print_error($this->db);
5232 $this->error = $this->db->error();
5233 return -1;
5234 }
5235 }
5236
5242 public function getLinesArray()
5243 {
5244 return $this->fetch_lines();
5245 }
5246
5258 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5259 {
5260 global $conf, $langs;
5261
5262 $outputlangs->loadLangs(array("bills", "products"));
5263
5264 if (!dol_strlen($modele)) {
5265 $modele = 'crabe';
5266 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5267
5268 if (!empty($this->model_pdf)) {
5269 $modele = $this->model_pdf;
5270 } elseif (getDolGlobalString($thisTypeConfName)) {
5271 $modele = getDolGlobalString($thisTypeConfName);
5272 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
5273 $modele = getDolGlobalString('FACTURE_ADDON_PDF');
5274 }
5275 }
5276
5277 $modelpath = "core/modules/facture/doc/";
5278
5279 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5280 }
5281
5287 public function newCycle()
5288 {
5289 $sql = "SELECT max(situation_cycle_ref) as maxsituationref";
5290 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5291 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5292
5293 $resql = $this->db->query($sql);
5294 if ($resql) {
5295 if ($this->db->num_rows($resql) > 0) {
5296 $ref = 0;
5297 $obj = $this->db->fetch_object($resql);
5298 if ($obj) {
5299 $ref = $obj->maxsituationref;
5300 }
5301 $ref++;
5302 } else {
5303 $ref = 1;
5304 }
5305 $this->db->free($resql);
5306 return $ref;
5307 } else {
5308 $this->error = $this->db->lasterror();
5309 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5310 return -1;
5311 }
5312 }
5313
5314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5320 public function is_first()
5321 {
5322 // phpcs:enable
5323 return ($this->situation_counter == 1);
5324 }
5325
5326 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5332 public function get_prev_sits()
5333 {
5334 // phpcs:enable
5335 global $conf;
5336
5337 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5338 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5339 $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5340 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5341 $resql = $this->db->query($sql);
5342 $res = array();
5343 if ($resql && $this->db->num_rows($resql) > 0) {
5344 while ($row = $this->db->fetch_object($resql)) {
5345 $id = $row->rowid;
5346 $situation = new Facture($this->db);
5347 $situation->fetch($id);
5348 $res[] = $situation;
5349 }
5350 } else {
5351 $this->error = $this->db->error();
5352 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5353 return -1;
5354 }
5355
5356 return $res;
5357 }
5358
5366 public function setFinal(User $user, $notrigger = 0)
5367 {
5368 $error = 0;
5369
5370 $this->db->begin();
5371
5372 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5373
5374 dol_syslog(__METHOD__, LOG_DEBUG);
5375 $resql = $this->db->query($sql);
5376 if (!$resql) {
5377 $this->errors[] = $this->db->error();
5378 $error++;
5379 }
5380
5381 if (!$notrigger && empty($error)) {
5382 // Call trigger
5383 $result = $this->call_trigger('BILL_MODIFY', $user);
5384 if ($result < 0) {
5385 $error++;
5386 }
5387 // End call triggers
5388 }
5389
5390 if (!$error) {
5391 $this->db->commit();
5392 return 1;
5393 } else {
5394 foreach ($this->errors as $errmsg) {
5395 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5396 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5397 }
5398 $this->db->rollback();
5399 return -1 * $error;
5400 }
5401 }
5402
5403 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5409 public function is_last_in_cycle()
5410 {
5411 // phpcs:enable
5412 global $conf;
5413
5414 if (!empty($this->situation_cycle_ref)) {
5415 // No point in testing anything if we're not inside a cycle
5416 $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5417 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5418 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5419 $resql = $this->db->query($sql);
5420
5421 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5422 $last = $res['max(situation_counter)'];
5423 return ($last == $this->situation_counter);
5424 } else {
5425 $this->error = $this->db->lasterror();
5426 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5427 return false;
5428 }
5429 } else {
5430 return true;
5431 }
5432 }
5433
5442 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5443 {
5444 $tables = array(
5445 'facture'
5446 );
5447
5448 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5449 }
5450
5459 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5460 {
5461 $tables = array(
5462 'facturedet'
5463 );
5464
5465 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
5466 }
5467
5473 public function hasDelay()
5474 {
5475 global $conf;
5476
5477 $now = dol_now();
5478
5479 // Paid invoices have status STATUS_CLOSED
5480 if ($this->status != Facture::STATUS_VALIDATED) {
5481 return false;
5482 }
5483
5484 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5485 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5486 $totalpaid = $this->getSommePaiement();
5487 $totalpaid = (float) $totalpaid;
5488 $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
5489 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5490 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5491 $hasDelay = 1;
5492 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5493 $hasDelay = 1;
5494 } else {
5495 $hasDelay = 0;
5496 }
5497 }
5498 }
5499
5500 return $hasDelay;
5501 }
5502
5507 public function displayRetainedWarranty()
5508 {
5509 global $conf;
5510
5511 // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
5512
5513 // 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
5514
5515 $displayWarranty = false;
5516 if (!empty($this->retained_warranty)) {
5517 $displayWarranty = true;
5518
5519 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
5520 // Check if this situation invoice is 100% for real
5521 $displayWarranty = false;
5522 if (!empty($this->situation_final)) {
5523 $displayWarranty = true;
5524 } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
5525 // $object->situation_final need validation to be done so this test is need for draft
5526 $displayWarranty = true;
5527
5528 foreach ($this->lines as $i => $line) {
5529 if ($line->product_type < 2 && $line->situation_percent < 100) {
5530 $displayWarranty = false;
5531 break;
5532 }
5533 }
5534 }
5535 }
5536 }
5537
5538 return $displayWarranty;
5539 }
5540
5545 public function getRetainedWarrantyAmount($rounding = -1)
5546 {
5547 global $conf;
5548 if (empty($this->retained_warranty)) {
5549 return -1;
5550 }
5551
5552 $retainedWarrantyAmount = 0;
5553
5554 // Billed - retained warranty
5555 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
5556 $displayWarranty = true;
5557 // Check if this situation invoice is 100% for real
5558 if (!empty($this->lines)) {
5559 foreach ($this->lines as $i => $line) {
5560 if ($line->product_type < 2 && $line->situation_percent < 100) {
5561 $displayWarranty = false;
5562 break;
5563 }
5564 }
5565 }
5566
5567 if ($displayWarranty && !empty($this->situation_final)) {
5569 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5570
5571 $total2BillWT = 0;
5572 foreach ($TPreviousIncoice as &$fac) {
5573 $total2BillWT += $fac->total_ttc;
5574 }
5575 $total2BillWT += $this->total_ttc;
5576
5577 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5578 } else {
5579 return -1;
5580 }
5581 } else {
5582 // Because one day retained warranty could be used on standard invoices
5583 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5584 }
5585
5586 if ($rounding < 0) {
5587 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
5588 }
5589
5590 if ($rounding > 0) {
5591 return round($retainedWarrantyAmount, $rounding);
5592 }
5593
5594 return $retainedWarrantyAmount;
5595 }
5596
5603 public function setRetainedWarranty($value)
5604 {
5605 dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
5606
5607 if ($this->status >= 0) {
5608 $fieldname = 'retained_warranty';
5609 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5610 $sql .= " SET ".$fieldname." = ".((float) $value);
5611 $sql .= ' WHERE rowid='.((int) $this->id);
5612
5613 if ($this->db->query($sql)) {
5614 $this->retained_warranty = (float) $value;
5615 return 1;
5616 } else {
5617 dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
5618 $this->error = $this->db->error();
5619 return -1;
5620 }
5621 } else {
5622 dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
5623 $this->error = 'Status of the object is incompatible '.$this->status;
5624 return -2;
5625 }
5626 }
5627
5628
5636 public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '')
5637 {
5638 if (!$timestamp && $dateYmd) {
5639 $timestamp = $this->db->jdate($dateYmd);
5640 }
5641
5642
5643 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
5644 if ($this->status >= 0) {
5645 $fieldname = 'retained_warranty_date_limit';
5646 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5647 $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
5648 $sql .= ' WHERE rowid = '.((int) $this->id);
5649
5650 if ($this->db->query($sql)) {
5651 $this->retained_warranty_date_limit = $timestamp;
5652 return 1;
5653 } else {
5654 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
5655 $this->error = $this->db->error();
5656 return -1;
5657 }
5658 } else {
5659 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5660 $this->error = 'Status of the object is incompatible '.$this->status;
5661 return -2;
5662 }
5663 }
5664
5665
5677 public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
5678 {
5679 global $conf, $langs, $user;
5680
5681 $error = 0;
5682 $this->output = '';
5683 $this->error = '';
5684 $nbMailSend = 0;
5685 $errorsMsg = array();
5686
5687 $langs->load("bills");
5688
5689 if (!isModEnabled('invoice')) { // Should not happen. If module disabled, cron job should not be visible.
5690 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5691 return 0;
5692 }
5693 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
5694 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5695 return 0;
5696 }
5697 /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
5698 $langs->load("bills");
5699 $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5700 return 0;
5701 }
5702 */
5703
5704 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5705 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
5706 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
5707 $formmail = new FormMail($this->db);
5708
5709 $now = dol_now();
5710 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
5711
5712 $tmpinvoice = new Facture($this->db);
5713
5714 dol_syslog(__METHOD__." start", LOG_INFO);
5715
5716 // Select all action comm reminder
5717 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
5718 if (!empty($paymentmode) && $paymentmode != 'all') {
5719 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
5720 }
5721 $sql .= " WHERE f.paye = 0"; // Only unpaid
5722 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
5723 if ($datetouse == 'invoicedate') {
5724 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
5725 } else {
5726 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
5727 }
5728 $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch process only one company (no sharing)
5729 if (!empty($paymentmode) && $paymentmode != 'all') {
5730 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
5731 }
5732 // TODO Add a filter to check there is no payment started yet
5733 if ($datetouse == 'invoicedate') {
5734 $sql .= $this->db->order("datef", "ASC");
5735 } else {
5736 $sql .= $this->db->order("date_lim_reglement", "ASC");
5737 }
5738
5739 $resql = $this->db->query($sql);
5740
5741 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
5742 if ($datetouse == 'invoicedate') {
5743 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedInvoicesWithDate", $stmpidate);
5744 } else {
5745 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
5746 }
5747 if (!empty($paymentmode) && $paymentmode != 'all') {
5748 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
5749 }
5750 $this->output .= '<br>';
5751
5752 if ($resql) {
5753 while ($obj = $this->db->fetch_object($resql)) {
5754 if (!$error) {
5755 // Load event
5756 $res = $tmpinvoice->fetch($obj->id);
5757 if ($res > 0) {
5758 $tmpinvoice->fetch_thirdparty();
5759
5760 $outputlangs = new Translate('', $conf);
5761 if ($tmpinvoice->thirdparty->default_lang) {
5762 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5763 $outputlangs->loadLangs(array("main", "bills"));
5764 } else {
5765 $outputlangs = $langs;
5766 }
5767
5768 // Select email template according to language of recipient
5769 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
5770 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5771 $langs->load("errors");
5772 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
5773 return 0;
5774 }
5775
5776 // PREPARE EMAIL
5777 $errormesg = '';
5778
5779 // Make substitution in email content
5780 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, '', $tmpinvoice);
5781
5782 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
5783
5784 // Topic
5785 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5786
5787 // Content
5788 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5789
5790 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
5791
5792 // Recipient
5793 $to = array();
5794 if ($forcerecipient) { // If a recipient was forced
5795 $to = array($forcerecipient);
5796 } else {
5797 $res = $tmpinvoice->fetch_thirdparty();
5798 $recipient = $tmpinvoice->thirdparty;
5799 if ($res > 0) {
5800 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
5801 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5802 foreach ($tmparraycontact as $data_email) {
5803 if (!empty($data_email['email'])) {
5804 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
5805 }
5806 }
5807 }
5808 if (empty($to) && !empty($recipient->email)) {
5809 $to[] = $recipient->email;
5810 }
5811 if (empty($to)) {
5812 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for invoice or customer.";
5813 $error++;
5814 }
5815 } else {
5816 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5817 $error++;
5818 }
5819 }
5820
5821 // Sender
5822 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
5823 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
5824 $from = $arraymessage->email_from;
5825 }
5826 if (empty($from)) {
5827 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5828 $error++;
5829 }
5830
5831 if (!$error && !empty($to)) {
5832 $this->db->begin();
5833
5834 $to = implode(',', $to);
5835 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
5836 $to = $to.','.$arraymessage->email_to;
5837 }
5838
5839 // Errors Recipient
5840 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
5841
5842 $trackid = 'inv'.$tmpinvoice->id;
5843 $sendcontext = 'standard';
5844
5845 $email_tocc = '';
5846 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
5847 $email_tocc = $arraymessage->email_tocc;
5848 }
5849
5850 $email_tobcc = '';
5851 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
5852 $email_tobcc = $arraymessage->email_tobcc;
5853 }
5854
5855 //join file is asked
5856 $joinFile = [];
5857 $joinFileName = [];
5858 $joinFileMime = [];
5859 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5860 $joinFile[] = DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc;
5861 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5862 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc);
5863 }
5864
5865 // Mail Creation
5866 $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
5867
5868 // Sending Mail
5869 if ($cMailFile->sendfile()) {
5870 $nbMailSend++;
5871
5872 // Add a line into event table
5873 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5874
5875 // Insert record of emails sent
5876 $actioncomm = new ActionComm($this->db);
5877
5878 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5879 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5880 $actioncomm->contact_id = 0;
5881
5882 $actioncomm->code = 'AC_EMAIL';
5883 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
5884 $actioncomm->note_private = $sendContent;
5885 $actioncomm->fk_project = $tmpinvoice->fk_project;
5886 $actioncomm->datep = dol_now();
5887 $actioncomm->datef = $actioncomm->datep;
5888 $actioncomm->percentage = -1; // Not applicable
5889 $actioncomm->authorid = $user->id; // User saving action
5890 $actioncomm->userownerid = $user->id; // Owner of action
5891 // Fields when action is an email (content should be added into note)
5892 $actioncomm->email_msgid = $cMailFile->msgid;
5893 $actioncomm->email_subject = $sendTopic;
5894 $actioncomm->email_from = $from;
5895 $actioncomm->email_sender = '';
5896 $actioncomm->email_to = $to;
5897 //$actioncomm->email_tocc = $sendtocc;
5898 //$actioncomm->email_tobcc = $sendtobcc;
5899 //$actioncomm->email_subject = $subject;
5900 $actioncomm->errors_to = $errors_to;
5901
5902 $actioncomm->elementtype = 'invoice';
5903 $actioncomm->fk_element = $tmpinvoice->id;
5904
5905 //$actioncomm->extraparams = $extraparams;
5906
5907 $actioncomm->create($user);
5908 } else {
5909 $errormesg = $cMailFile->error.' : '.$to;
5910 $error++;
5911
5912 // Add a line into event table
5913 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5914
5915 // Insert record of emails sent
5916 $actioncomm = new ActionComm($this->db);
5917
5918 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5919 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5920 $actioncomm->contact_id = 0;
5921
5922 $actioncomm->code = 'AC_EMAIL';
5923 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
5924 $actioncomm->note_private = $errormesg;
5925 $actioncomm->fk_project = $tmpinvoice->fk_project;
5926 $actioncomm->datep = dol_now();
5927 $actioncomm->datef = $actioncomm->datep;
5928 $actioncomm->percentage = -1; // Not applicable
5929 $actioncomm->authorid = $user->id; // User saving action
5930 $actioncomm->userownerid = $user->id; // Owner of action
5931 // Fields when action is an email (content should be added into note)
5932 $actioncomm->email_msgid = $cMailFile->msgid;
5933 $actioncomm->email_from = $from;
5934 $actioncomm->email_sender = '';
5935 $actioncomm->email_to = $to;
5936 //$actioncomm->email_tocc = $sendtocc;
5937 //$actioncomm->email_tobcc = $sendtobcc;
5938 //$actioncomm->email_subject = $subject;
5939 $actioncomm->errors_to = $errors_to;
5940
5941 //$actioncomm->extraparams = $extraparams;
5942
5943 $actioncomm->create($user);
5944 }
5945
5946 $this->db->commit(); // We always commit
5947 }
5948
5949 if ($errormesg) {
5950 $errorsMsg[] = $errormesg;
5951 }
5952 } else {
5953 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
5954 $error++;
5955 }
5956 }
5957 }
5958 } else {
5959 $error++;
5960 }
5961
5962 if (!$error) {
5963 $this->output .= 'Nb of emails sent : '.$nbMailSend;
5964
5965 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
5966
5967 return 0;
5968 } else {
5969 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
5970
5971 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
5972
5973 return $error;
5974 }
5975 }
5976
5983 public function willBeLastOfSameType($allow_validated_drafts = false)
5984 {
5985 // get date of last validated invoices of same type
5986 $sql = "SELECT datef";
5987 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
5988 $sql .= " WHERE type = " . (int) $this->type ;
5989 $sql .= " AND date_valid IS NOT NULL";
5990 $sql .= " AND entity IN (".getEntity('invoice').")";
5991 $sql .= " ORDER BY datef DESC LIMIT 1";
5992
5993 $result = $this->db->query($sql);
5994 if ($result) {
5995 // compare with current validation date
5996 if ($this->db->num_rows($result)) {
5997 $obj = $this->db->fetch_object($result);
5998 $last_date = $this->db->jdate($obj->datef);
5999 $invoice_date = $this->date;
6000
6001 $is_last_of_same_type = $invoice_date >= $last_date;
6002 if ($allow_validated_drafts) {
6003 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
6004 }
6005
6006 return array($is_last_of_same_type, $last_date);
6007 } else {
6008 // element is first of type to be validated
6009 return array(true);
6010 }
6011 } else {
6012 dol_print_error($this->db);
6013 }
6014
6015 return array();
6016 }
6017
6025 public function getKanbanView($option = '', $arraydata = null)
6026 {
6027 global $langs;
6028
6029 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6030
6031 $picto = $this->picto;
6032 if ($this->type == self::TYPE_REPLACEMENT) {
6033 $picto .= 'r'; // Replacement invoice
6034 }
6035 if ($this->type == self::TYPE_CREDIT_NOTE) {
6036 $picto .= 'a'; // Credit note
6037 }
6038 if ($this->type == self::TYPE_DEPOSIT) {
6039 $picto .= 'd'; // Deposit invoice
6040 }
6041
6042 $return = '<div class="box-flex-item box-flex-grow-zero">';
6043 $return .= '<div class="info-box info-box-sm">';
6044 $return .= '<span class="info-box-icon bg-infobox-action">';
6045 $return .= img_picto('', $picto);
6046 $return .= '</span>';
6047 $return .= '<div class="info-box-content">';
6048 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
6049 if ($selected >= 0) {
6050 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6051 }
6052 if (!empty($arraydata['thirdparty'])) {
6053 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
6054 }
6055 if (property_exists($this, 'date')) {
6056 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
6057 }
6058 if (property_exists($this, 'total_ht')) {
6059 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
6060 $return .= ' '.$langs->trans("HT");
6061 $return .= '</span>';
6062 }
6063 if (method_exists($this, 'getLibStatut')) {
6064 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
6065 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
6066 }
6067 $return .= '</div>';
6068 $return .= '</div>';
6069 $return .= '</div>';
6070 return $return;
6071 }
6072}
6073
6079{
6083 public $element = 'facturedet';
6084
6088 public $table_element = 'facturedet';
6089
6093 public $oldline;
6094
6100
6102 public $desc;
6103 public $ref_ext; // External reference of the line
6104
6105 public $localtax1_type; // Local tax 1 type
6106 public $localtax2_type; // Local tax 2 type
6107 public $fk_remise_except; // Link to line into llx_remise_except
6108 public $rang = 0;
6109
6110 public $fk_fournprice;
6111
6116 public $pa_ht;
6117 public $marge_tx;
6118 public $marque_tx;
6119
6123 public $tva_npr;
6124
6125 public $remise_percent;
6126
6130 public $batch;
6134 public $fk_warehouse;
6135
6136
6137 public $origin;
6138 public $origin_id;
6139
6143 public $fk_code_ventilation = 0;
6144
6145
6146 public $date_start;
6147 public $date_end;
6148
6149 public $skip_update_total; // Skip update price total for special lines
6150
6154 public $situation_percent;
6155
6159 public $fk_prev_id;
6160
6161
6167 public function __construct($db)
6168 {
6169 $this->db = $db;
6170 }
6171
6178 public function fetch($rowid)
6179 {
6180 $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,';
6181 $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
6182 $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,';
6183 $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
6184 $sql .= ' fd.fk_code_ventilation,';
6185 $sql .= ' fd.batch, fd.fk_warehouse,';
6186 $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
6187 $sql .= ' fd.situation_percent, fd.fk_prev_id,';
6188 $sql .= ' fd.multicurrency_subprice,';
6189 $sql .= ' fd.multicurrency_total_ht,';
6190 $sql .= ' fd.multicurrency_total_tva,';
6191 $sql .= ' fd.multicurrency_total_ttc,';
6192 $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
6193 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
6194 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
6195 $sql .= ' WHERE fd.rowid = '.((int) $rowid);
6196
6197 $result = $this->db->query($sql);
6198 if ($result) {
6199 $objp = $this->db->fetch_object($result);
6200
6201 if (!$objp) {
6202 $this->error = 'InvoiceLine with id '. $rowid .' not found sql='.$sql;
6203 return 0;
6204 }
6205
6206 $this->rowid = $objp->rowid;
6207 $this->id = $objp->rowid;
6208 $this->fk_facture = $objp->fk_facture;
6209 $this->fk_parent_line = $objp->fk_parent_line;
6210 $this->label = $objp->custom_label;
6211 $this->desc = $objp->description;
6212 $this->qty = $objp->qty;
6213 $this->subprice = $objp->subprice;
6214 $this->ref_ext = $objp->ref_ext;
6215 $this->vat_src_code = $objp->vat_src_code;
6216 $this->tva_tx = $objp->tva_tx;
6217 $this->localtax1_tx = $objp->localtax1_tx;
6218 $this->localtax2_tx = $objp->localtax2_tx;
6219 $this->remise_percent = $objp->remise_percent;
6220 $this->fk_remise_except = $objp->fk_remise_except;
6221 $this->fk_product = $objp->fk_product;
6222 $this->product_type = $objp->product_type;
6223 $this->date_start = $this->db->jdate($objp->date_start);
6224 $this->date_end = $this->db->jdate($objp->date_end);
6225 $this->info_bits = $objp->info_bits;
6226 $this->tva_npr = (($objp->info_bits & 1) == 1) ? 1 : 0;
6227 $this->special_code = $objp->special_code;
6228 $this->total_ht = $objp->total_ht;
6229 $this->total_tva = $objp->total_tva;
6230 $this->total_localtax1 = $objp->total_localtax1;
6231 $this->total_localtax2 = $objp->total_localtax2;
6232 $this->total_ttc = $objp->total_ttc;
6233 $this->fk_code_ventilation = $objp->fk_code_ventilation;
6234 $this->batch = $objp->batch;
6235 $this->fk_warehouse = $objp->fk_warehouse;
6236 $this->rang = $objp->rang;
6237 $this->fk_fournprice = $objp->fk_fournprice;
6238 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
6239 $this->pa_ht = $marginInfos[0];
6240 $this->marge_tx = $marginInfos[1];
6241 $this->marque_tx = $marginInfos[2];
6242
6243 $this->ref = $objp->product_ref; // deprecated
6244
6245 $this->product_ref = $objp->product_ref;
6246 $this->product_label = $objp->product_label;
6247 $this->product_desc = $objp->product_desc;
6248
6249 $this->fk_unit = $objp->fk_unit;
6250 $this->fk_user_modif = $objp->fk_user_modif;
6251 $this->fk_user_author = $objp->fk_user_author;
6252
6253 $this->situation_percent = $objp->situation_percent;
6254 $this->fk_prev_id = $objp->fk_prev_id;
6255
6256 $this->multicurrency_subprice = $objp->multicurrency_subprice;
6257 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
6258 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
6259 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
6260
6261 $this->fetch_optionals();
6262
6263 $this->db->free($result);
6264
6265 return 1;
6266 } else {
6267 $this->error = $this->db->lasterror();
6268 return -1;
6269 }
6270 }
6271
6279 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
6280 {
6281 global $langs, $user;
6282
6283 $error = 0;
6284
6285 $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'.
6286 $this->pa_ht = (float) $this->pa_ht; // convert to float after check if empty value
6287
6288 dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
6289
6290 // Clean parameters
6291 $this->desc = trim($this->desc);
6292 if (empty($this->tva_tx)) {
6293 $this->tva_tx = 0;
6294 }
6295 if (empty($this->localtax1_tx)) {
6296 $this->localtax1_tx = 0;
6297 }
6298 if (empty($this->localtax2_tx)) {
6299 $this->localtax2_tx = 0;
6300 }
6301 if (empty($this->localtax1_type)) {
6302 $this->localtax1_type = 0;
6303 }
6304 if (empty($this->localtax2_type)) {
6305 $this->localtax2_type = 0;
6306 }
6307 if (empty($this->total_localtax1)) {
6308 $this->total_localtax1 = 0;
6309 }
6310 if (empty($this->total_localtax2)) {
6311 $this->total_localtax2 = 0;
6312 }
6313 if (empty($this->rang)) {
6314 $this->rang = 0;
6315 }
6316 if (empty($this->remise_percent)) {
6317 $this->remise_percent = 0;
6318 }
6319 if (empty($this->info_bits)) {
6320 $this->info_bits = 0;
6321 }
6322 if (empty($this->subprice)) {
6323 $this->subprice = 0;
6324 }
6325 if (empty($this->ref_ext)) {
6326 $this->ref_ext = '';
6327 }
6328 if (empty($this->special_code)) {
6329 $this->special_code = 0;
6330 }
6331 if (empty($this->fk_parent_line)) {
6332 $this->fk_parent_line = 0;
6333 }
6334 if (empty($this->fk_prev_id)) {
6335 $this->fk_prev_id = 0;
6336 }
6337 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
6338 $this->situation_percent = 100;
6339 }
6340
6341 if (empty($this->multicurrency_subprice)) {
6342 $this->multicurrency_subprice = 0;
6343 }
6344 if (empty($this->multicurrency_total_ht)) {
6345 $this->multicurrency_total_ht = 0;
6346 }
6347 if (empty($this->multicurrency_total_tva)) {
6348 $this->multicurrency_total_tva = 0;
6349 }
6350 if (empty($this->multicurrency_total_ttc)) {
6351 $this->multicurrency_total_ttc = 0;
6352 }
6353
6354 // if buy price not defined, define buyprice as configured in margin admin
6355 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6356 $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6357 if ($result < 0) {
6358 return $result;
6359 } else {
6360 $this->pa_ht = $result;
6361 }
6362 }
6363
6364 // Check parameters
6365 if ($this->product_type < 0) {
6366 $this->error = 'ErrorProductTypeMustBe0orMore';
6367 return -1;
6368 }
6369 if (!empty($this->fk_product) && $this->fk_product > 0) {
6370 // Check product exists
6371 $result = Product::isExistingObject('product', $this->fk_product);
6372 if ($result <= 0) {
6373 $this->error = 'ErrorProductIdDoesNotExists';
6374 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6375 return -1;
6376 }
6377 }
6378
6379 $this->db->begin();
6380
6381 // Update line in database
6382 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
6383 $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
6384 $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6385 $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6386 $sql .= ' date_start, date_end, fk_code_ventilation,';
6387 $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6388 $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6389 $sql .= ' situation_percent, fk_prev_id,';
6390 $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
6391 $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc,';
6392 $sql .= ' batch, fk_warehouse';
6393 $sql .= ')';
6394 $sql .= " VALUES (".$this->fk_facture.",";
6395 $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
6396 $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
6397 $sql .= " '".$this->db->escape($this->desc)."',";
6398 $sql .= " ".price2num($this->qty).",";
6399 $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
6400 $sql .= " ".price2num($this->tva_tx).",";
6401 $sql .= " ".price2num($this->localtax1_tx).",";
6402 $sql .= " ".price2num($this->localtax2_tx).",";
6403 $sql .= " '".$this->db->escape($this->localtax1_type)."',";
6404 $sql .= " '".$this->db->escape($this->localtax2_type)."',";
6405 $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
6406 $sql .= " ".((int) $this->product_type).",";
6407 $sql .= " ".price2num($this->remise_percent).",";
6408 $sql .= " ".price2num($this->subprice).",";
6409 $sql .= " '".$this->db->escape($this->ref_ext)."',";
6410 $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
6411 $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
6412 $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
6413 $sql .= ' '.((int) $this->fk_code_ventilation).',';
6414 $sql .= ' '.((int) $this->rang).',';
6415 $sql .= ' '.((int) $this->special_code).',';
6416 $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
6417 $sql .= ' '.price2num($this->pa_ht).',';
6418 $sql .= " '".$this->db->escape($this->info_bits)."',";
6419 $sql .= " ".price2num($this->total_ht).",";
6420 $sql .= " ".price2num($this->total_tva).",";
6421 $sql .= " ".price2num($this->total_ttc).",";
6422 $sql .= " ".price2num($this->total_localtax1).",";
6423 $sql .= " ".price2num($this->total_localtax2);
6424 $sql .= ", ".((float) $this->situation_percent);
6425 $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
6426 $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6427 $sql .= ", ".((int) $user->id);
6428 $sql .= ", ".((int) $user->id);
6429 $sql .= ", ".(int) $this->fk_multicurrency;
6430 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
6431 $sql .= ", ".price2num($this->multicurrency_subprice);
6432 $sql .= ", ".price2num($this->multicurrency_total_ht);
6433 $sql .= ", ".price2num($this->multicurrency_total_tva);
6434 $sql .= ", ".price2num($this->multicurrency_total_ttc);
6435 $sql .= ", '".$this->db->escape($this->batch)."'";
6436 $sql .= ", ".((int) $this->fk_warehouse);
6437 $sql .= ')';
6438
6439 dol_syslog(get_class($this)."::insert", LOG_DEBUG);
6440 $resql = $this->db->query($sql);
6441 if ($resql) {
6442 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
6443 $this->rowid = $this->id; // For backward compatibility
6444
6445 if (!$error) {
6446 $result = $this->insertExtraFields();
6447 if ($result < 0) {
6448 $error++;
6449 }
6450 }
6451
6452 // If fk_remise_except is defined, the discount is linked to the invoice
6453 // which flags it as "consumed".
6454 if ($this->fk_remise_except) {
6455 $discount = new DiscountAbsolute($this->db);
6456 $result = $discount->fetch($this->fk_remise_except);
6457 if ($result >= 0) {
6458 // Check if discount was found
6459 if ($result > 0) {
6460 // Check if discount not already affected to another invoice
6461 if ($discount->fk_facture_line > 0) {
6462 if (empty($noerrorifdiscountalreadylinked)) {
6463 $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
6464 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6465 $this->db->rollback();
6466 return -3;
6467 }
6468 } else {
6469 $result = $discount->link_to_invoice($this->rowid, 0);
6470 if ($result < 0) {
6471 $this->error = $discount->error;
6472 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6473 $this->db->rollback();
6474 return -3;
6475 }
6476 }
6477 } else {
6478 $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
6479 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6480 $this->db->rollback();
6481 return -3;
6482 }
6483 } else {
6484 $this->error = $discount->error;
6485 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6486 $this->db->rollback();
6487 return -3;
6488 }
6489 }
6490
6491 if (!$notrigger) {
6492 // Call trigger
6493 $result = $this->call_trigger('LINEBILL_INSERT', $user);
6494 if ($result < 0) {
6495 $this->db->rollback();
6496 return -2;
6497 }
6498 // End call triggers
6499 }
6500
6501 $this->db->commit();
6502 return $this->id;
6503 } else {
6504 $this->error = $this->db->lasterror();
6505 $this->db->rollback();
6506 return -2;
6507 }
6508 }
6509
6517 public function update($user = null, $notrigger = 0)
6518 {
6519 global $user, $conf;
6520
6521 $error = 0;
6522
6523 $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'.
6524 $this->pa_ht = (float) $this->pa_ht; // convert to float after check if empty value
6525
6526 // Clean parameters
6527 $this->desc = trim($this->desc);
6528 if (empty($this->ref_ext)) {
6529 $this->ref_ext = '';
6530 }
6531 if (empty($this->tva_tx)) {
6532 $this->tva_tx = 0;
6533 }
6534 if (empty($this->localtax1_tx)) {
6535 $this->localtax1_tx = 0;
6536 }
6537 if (empty($this->localtax2_tx)) {
6538 $this->localtax2_tx = 0;
6539 }
6540 if (empty($this->localtax1_type)) {
6541 $this->localtax1_type = 0;
6542 }
6543 if (empty($this->localtax2_type)) {
6544 $this->localtax2_type = 0;
6545 }
6546 if (empty($this->total_localtax1)) {
6547 $this->total_localtax1 = 0;
6548 }
6549 if (empty($this->total_localtax2)) {
6550 $this->total_localtax2 = 0;
6551 }
6552 if (empty($this->remise_percent)) {
6553 $this->remise_percent = 0;
6554 }
6555 if (empty($this->info_bits)) {
6556 $this->info_bits = 0;
6557 }
6558 if (empty($this->special_code)) {
6559 $this->special_code = 0;
6560 }
6561 if (empty($this->product_type)) {
6562 $this->product_type = 0;
6563 }
6564 if (empty($this->fk_parent_line)) {
6565 $this->fk_parent_line = 0;
6566 }
6567 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
6568 $this->situation_percent = 100;
6569 }
6570
6571 if (empty($this->multicurrency_subprice)) {
6572 $this->multicurrency_subprice = 0;
6573 }
6574 if (empty($this->multicurrency_total_ht)) {
6575 $this->multicurrency_total_ht = 0;
6576 }
6577 if (empty($this->multicurrency_total_tva)) {
6578 $this->multicurrency_total_tva = 0;
6579 }
6580 if (empty($this->multicurrency_total_ttc)) {
6581 $this->multicurrency_total_ttc = 0;
6582 }
6583
6584 // Check parameters
6585 if ($this->product_type < 0) {
6586 return -1;
6587 }
6588
6589 // if buy price not provided, define buyprice as configured in margin admin
6590 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6591 // We call defineBuyPrice only if data was not provided (if input was '0', we will not go here and value will remaine '0')
6592 $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6593 if ($result < 0) {
6594 return $result;
6595 } else {
6596 $this->pa_ht = $result;
6597 }
6598 }
6599
6600 $this->db->begin();
6601
6602 // Update line in database
6603 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6604 $sql .= " description='".$this->db->escape($this->desc)."'";
6605 $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
6606 $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
6607 $sql .= ", subprice=".price2num($this->subprice);
6608 $sql .= ", remise_percent=".price2num($this->remise_percent);
6609 if ($this->fk_remise_except) {
6610 $sql .= ", fk_remise_except=".$this->fk_remise_except;
6611 } else {
6612 $sql .= ", fk_remise_except=null";
6613 }
6614 $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
6615 $sql .= ", tva_tx=".price2num($this->tva_tx);
6616 $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
6617 $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
6618 $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
6619 $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
6620 $sql .= ", qty=".price2num($this->qty);
6621 $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
6622 $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
6623 $sql .= ", product_type=".$this->product_type;
6624 $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
6625 $sql .= ", special_code=" . (int) $this->special_code;
6626 if (empty($this->skip_update_total)) {
6627 $sql .= ", total_ht=".price2num($this->total_ht);
6628 $sql .= ", total_tva=".price2num($this->total_tva);
6629 $sql .= ", total_ttc=".price2num($this->total_ttc);
6630 $sql .= ", total_localtax1=".price2num($this->total_localtax1);
6631 $sql .= ", total_localtax2=".price2num($this->total_localtax2);
6632 }
6633 $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
6634 $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)
6635 $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
6636 if (!empty($this->rang)) {
6637 $sql .= ", rang=".((int) $this->rang);
6638 }
6639 $sql .= ", situation_percent = ".((float) $this->situation_percent);
6640 $sql .= ", fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6641 $sql .= ", fk_user_modif = ".((int) $user->id);
6642
6643 // Multicurrency
6644 $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6645 $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6646 $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6647 $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6648
6649 $sql .= ", batch = '".$this->db->escape($this->batch)."'";
6650 $sql .= ", fk_warehouse = ".((int) $this->fk_warehouse);
6651
6652 $sql .= " WHERE rowid = ".((int) $this->rowid);
6653
6654 dol_syslog(get_class($this)."::update", LOG_DEBUG);
6655 $resql = $this->db->query($sql);
6656 if ($resql) {
6657 if (!$error) {
6658 $this->id = $this->rowid;
6659 $result = $this->insertExtraFields();
6660 if ($result < 0) {
6661 $error++;
6662 }
6663 }
6664
6665 if (!$error && !$notrigger) {
6666 // Call trigger
6667 $result = $this->call_trigger('LINEBILL_MODIFY', $user);
6668 if ($result < 0) {
6669 $this->db->rollback();
6670 return -2;
6671 }
6672 // End call triggers
6673 }
6674 $this->db->commit();
6675 return 1;
6676 } else {
6677 $this->error = $this->db->error();
6678 $this->db->rollback();
6679 return -2;
6680 }
6681 }
6682
6690 public function delete($tmpuser = null, $notrigger = 0)
6691 {
6692 global $user;
6693
6694 $this->db->begin();
6695
6696 // Call trigger
6697 if (empty($notrigger)) {
6698 $result = $this->call_trigger('LINEBILL_DELETE', $user);
6699 if ($result < 0) {
6700 $this->db->rollback();
6701 return -1;
6702 }
6703 }
6704 // End call triggers
6705
6706 // extrafields
6707 $result = $this->deleteExtraFields();
6708 if ($result < 0) {
6709 $this->db->rollback();
6710 return -1;
6711 }
6712
6713 // Free discount linked to invoice line
6714 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
6715 $sql .= ' SET fk_facture_line = NULL';
6716 $sql .= ' WHERE fk_facture_line = '.((int) $this->id);
6717
6718 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
6719 $result = $this->db->query($sql);
6720 if (!$result) {
6721 $this->error = $this->db->error();
6722 $this->errors[] = $this->error;
6723 $this->db->rollback();
6724 return -1;
6725 }
6726
6727 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
6728 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
6729 $sql .= ' WHERE invoice_line_id = '.((int) $this->id);
6730 if (!$this->db->query($sql)) {
6731 $this->error = $this->db->error()." sql=".$sql;
6732 $this->errors[] = $this->error;
6733 $this->db->rollback();
6734 return -1;
6735 }
6736
6737 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->id);
6738
6739 if ($this->db->query($sql)) {
6740 $this->db->commit();
6741 return 1;
6742 } else {
6743 $this->error = $this->db->error()." sql=".$sql;
6744 $this->errors[] = $this->error;
6745 $this->db->rollback();
6746 return -1;
6747 }
6748 }
6749
6750 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6757 public function update_total()
6758 {
6759 // phpcs:enable
6760 $this->db->begin();
6761 dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6762
6763 // Clean parameters
6764 if (empty($this->total_localtax1)) {
6765 $this->total_localtax1 = 0;
6766 }
6767 if (empty($this->total_localtax2)) {
6768 $this->total_localtax2 = 0;
6769 }
6770
6771 // Update line in database
6772 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6773 $sql .= " total_ht=".price2num($this->total_ht);
6774 $sql .= ",total_tva=".price2num($this->total_tva);
6775 $sql .= ",total_localtax1=".price2num($this->total_localtax1);
6776 $sql .= ",total_localtax2=".price2num($this->total_localtax2);
6777 $sql .= ",total_ttc=".price2num($this->total_ttc);
6778 $sql .= " WHERE rowid = ".((int) $this->rowid);
6779
6780 dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6781
6782 $resql = $this->db->query($sql);
6783 if ($resql) {
6784 $this->db->commit();
6785 return 1;
6786 } else {
6787 $this->error = $this->db->error();
6788 $this->db->rollback();
6789 return -2;
6790 }
6791 }
6792
6793 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6803 public function get_prev_progress($invoiceid, $include_credit_note = true)
6804 {
6805 // phpcs:enable
6806 global $invoicecache;
6807
6808 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
6809 return 0;
6810 } else {
6811 // If invoice is not a situation invoice, this->fk_prev_id is used for something else
6812 if (!isset($invoicecache[$invoiceid])) {
6813 $invoicecache[$invoiceid] = new Facture($this->db);
6814 $invoicecache[$invoiceid]->fetch($invoiceid);
6815 }
6816 if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
6817 return 0;
6818 }
6819
6820 $sql = "SELECT situation_percent FROM ".MAIN_DB_PREFIX."facturedet";
6821 $sql .= " WHERE rowid = ".((int) $this->fk_prev_id);
6822
6823 $resql = $this->db->query($sql);
6824
6825 if ($resql && $this->db->num_rows($resql) > 0) {
6826 $returnPercent = 0;
6827
6828 $obj = $this->db->fetch_object($resql);
6829 if ($obj) {
6830 $returnPercent = (float) $obj->situation_percent;
6831 }
6832
6833 if ($include_credit_note) {
6834 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
6835 $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
6836 $sql .= " WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6837 $sql .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
6838 $sql .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6839
6840 $res = $this->db->query($sql);
6841 if ($res) {
6842 while ($obj = $this->db->fetch_object($res)) {
6843 $returnPercent = $returnPercent + (float) $obj->situation_percent;
6844 }
6845 } else {
6846 dol_print_error($this->db);
6847 }
6848 }
6849
6850 return $returnPercent;
6851 } else {
6852 $this->error = $this->db->error();
6853 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6854 $this->db->rollback();
6855 return -1;
6856 }
6857 }
6858 }
6859
6860 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6870 public function get_allprev_progress($invoiceid, $include_credit_note = true)
6871 {
6872 // phpcs:enable
6873 global $invoicecache;
6874
6875 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
6876 return 0;
6877 } else {
6878 // If invoice is not a situation invoice, this->fk_prev_id is used for something else
6879 if (!isset($invoicecache[$invoiceid])) {
6880 $invoicecache[$invoiceid] = new Facture($this->db);
6881 $invoicecache[$invoiceid]->fetch($invoiceid);
6882 }
6883 if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
6884 return 0;
6885 }
6886
6887 $all_found = false;
6888 $lastprevid = $this->fk_prev_id;
6889 $cumulated_percent = 0.0;
6890
6891 while (!$all_found) {
6892 $sql = "SELECT situation_percent, fk_prev_id FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $lastprevid);
6893 $resql = $this->db->query($sql);
6894
6895 if ($resql && $this->db->num_rows($resql) > 0) {
6896 $obj = $this->db->fetch_object($resql);
6897 $cumulated_percent += floatval($obj->situation_percent);
6898
6899 if ($include_credit_note) {
6900 $sql_credit_note = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
6901 $sql_credit_note .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
6902 $sql_credit_note .= " WHERE fd.fk_prev_id = ".((int) $lastprevid);
6903 $sql_credit_note .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
6904 $sql_credit_note .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6905
6906 $res_credit_note = $this->db->query($sql_credit_note);
6907 if ($res_credit_note) {
6908 while ($cn = $this->db->fetch_object($res_credit_note)) {
6909 $cumulated_percent = $cumulated_percent + floatval($cn->situation_percent);
6910 }
6911 } else {
6912 dol_print_error($this->db);
6913 }
6914 }
6915
6916 // Si fk_prev_id, on continue
6917 if ($obj->fk_prev_id) {
6918 $lastprevid = $obj->fk_prev_id;
6919 } else { // Sinon on stoppe la boucle
6920 $all_found = true;
6921 }
6922 } else {
6923 $this->error = $this->db->error();
6924 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6925 $this->db->rollback();
6926 return -1;
6927 }
6928 }
6929 return $cumulated_percent;
6930 }
6931 }
6932}
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:2010
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:2010