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