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