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 // (unless the caller already set array_options, e.g. from a create form, so we don't overwrite them)
1188 if (empty($this->array_options)) {
1189 $this->fetch_optionals();
1190 }
1191
1192 if (!empty($this->array_options)) {
1193 $facture->array_options = $this->array_options;
1194 }
1195
1196 foreach ($this->lines as &$line) {
1197 $line->fetch_optionals(); //fetch extrafields
1198 }
1199
1200 $facture->fk_facture_source = $this->fk_facture_source;
1201 $facture->type = $this->type;
1202 $facture->subtype = $this->subtype;
1203 $facture->socid = $this->socid;
1204 $facture->date = $this->date;
1205 $facture->date_pointoftax = $this->date_pointoftax;
1206 $facture->note_public = $this->note_public;
1207 $facture->note_private = $this->note_private;
1208 $facture->ref_client = $this->ref_client;
1209 $facture->ref_customer = $this->ref_customer;
1210 $facture->model_pdf = $this->model_pdf;
1211 $facture->fk_project = $this->fk_project;
1212 $facture->cond_reglement_id = $this->cond_reglement_id;
1213 $facture->mode_reglement_id = $this->mode_reglement_id;
1214 //$facture->remise_absolue = $this->remise_absolue;
1215 //$facture->remise_percent = $this->remise_percent; // TODO deprecated
1216
1217 $facture->origin = $this->origin;
1218 $facture->origin_id = $this->origin_id;
1219 $facture->fk_account = $this->fk_account;
1220
1221 $facture->lines = $this->lines; // Array of lines of invoice
1222 $facture->situation_counter = $this->situation_counter;
1223 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1224 $facture->situation_final = $this->situation_final;
1225
1226 $facture->retained_warranty = $this->retained_warranty;
1227 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1228 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1229
1230 $facture->fk_user_author = $user->id;
1231 $facture->user_creation_id = $user->id;
1232
1233
1234 // Loop on each line of new invoice
1235 foreach ($facture->lines as $i => $tmpline) {
1236 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1237 if ($invertdetail) {
1238 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1239 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1240 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1241 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1242 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1243 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1244 $facture->lines[$i]->ref_ext = '';
1245 }
1246 }
1247
1248 dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1249
1250 $facid = $facture->create($user);
1251 if ($facid <= 0) {
1252 $this->error = $facture->error;
1253 $this->errors = $facture->errors;
1254 } elseif ($this->type == self::TYPE_SITUATION && getDolGlobalString('INVOICE_USE_SITUATION')) {
1255 $this->fetchObjectLinked(null, '', $this->id, 'facture');
1256
1257 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1258 foreach ($Tfk_object as $fk_object) {
1259 $facture->add_object_linked($typeObject, $fk_object);
1260 }
1261 }
1262
1263 $facture->add_object_linked('facture', $this->fk_facture_source);
1264 }
1265
1266 return $facid;
1267 }
1268
1269
1278 public function createFromClone(User $user, $fromid = 0, $forceentity = null)
1279 {
1280 global $conf, $hookmanager;
1281
1282 $error = 0;
1283
1284 $object = new Facture($this->db);
1285
1286 $this->db->begin();
1287
1288 $object->fetch($fromid);
1289 // fetch() clears $object->thirdparty, but the subsequent $object->create() path
1290 // reaches addLine() -> getLocalTaxesFromRate() -> get_localtax() and uses the
1291 // buyer thirdparty to decide whether IRPF/localtax2 applies. Without this fetch,
1292 // get_localtax() sees $thirdparty_buyer = null, returns 0 and the cloned lines
1293 // lose their localtax2_tx (see issue #29052).
1294 $object->fetch_thirdparty();
1295
1296 // Load source object
1297 $objFrom = clone $object;
1298
1299 // Change socid if needed
1300 if (!empty($this->socid) && $this->socid != $object->socid) {
1301 $objsoc = new Societe($this->db);
1302
1303 if ($objsoc->fetch($this->socid) > 0) {
1304 $object->socid = $objsoc->id;
1305 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1306 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1307 $object->fk_project = 0;
1308 $object->fk_delivery_address = 0;
1309 }
1310
1311 // TODO Change product price if multi-prices
1312 }
1313
1314 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1315
1316 $object->id = 0;
1317 $object->statut = self::STATUS_DRAFT;
1318 $object->status = self::STATUS_DRAFT;
1319
1320 // Clear fields
1321 $object->date = (empty($this->date) ? dol_now() : $this->date);
1322 $object->user_creation_id = $user->id;
1323 $object->user_validation_id = null;
1324 $object->user_modification_id = null;
1325 $object->fk_user_author = $user->id;
1326 $object->fk_user_valid = null;
1327 $object->fk_facture_source = 0;
1328 $object->fk_fac_rec_source = 0;
1329 $object->date_creation = '';
1330 $object->date_modification = '';
1331 $object->date_validation = '';
1332 $object->ref_client = '';
1333 $object->ref_customer = '';
1334 $object->close_code = '';
1335 $object->close_note = '';
1336 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1337 $object->note_private = '';
1338 $object->note_public = '';
1339 }
1340
1341 // Loop on each line of new invoice
1342 foreach ($object->lines as $i => $line) {
1343 '@phan-var-force FactureLigne $line';
1344 if (($line->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1345 unset($object->lines[$i]);
1346 continue;
1347 }
1348
1349 // Block to update dates of service (month by month only if previously filled and similar to start and end of month)
1350 // If it's a service with start and end dates
1351 if (getDolGlobalString('INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1352 // Get the dates
1353 $start = dol_getdate($line->date_start);
1354 $end = dol_getdate($line->date_end);
1355
1356 // Get the first and last day of the month
1357 $first = dol_get_first_day($start['year'], $start['mon']);
1358 $last = dol_get_last_day($end['year'], $end['mon']);
1359
1360 //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1361 //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1362 // If start date is first date of month and end date is last date of month
1363 if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1364 && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1365 $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1366 $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1367 $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1368 $object->lines[$i]->date_start = $newFirst;
1369 $object->lines[$i]->date_end = $newLast;
1370 }
1371 }
1372
1373 $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1374
1375 // Do not clone accountancy ventilation: a cloned invoice must reappear in "to dispatch" list
1376 $object->lines[$i]->fk_code_ventilation = 0;
1377 }
1378
1379 // Create clone
1380 $object->context['createfromclone'] = 'createfromclone';
1381 $result = $object->create($user);
1382 if ($result < 0) {
1383 $error++;
1384 $this->setErrorsFromObject($object);
1385 } else {
1386 // copy internal contacts
1387 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1388 $error++;
1389 $this->setErrorsFromObject($object);
1390 } elseif ($object->socid == $objFrom->socid) {
1391 // copy external contacts if same company
1392 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1393 $error++;
1394 $this->setErrorsFromObject($object);
1395 }
1396 }
1397 }
1398
1399 if (!$error) {
1400 // Hook of thirdparty module
1401 if (is_object($hookmanager)) {
1402 $parameters = array('objFrom' => $objFrom);
1403 $action = '';
1404 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1405 if ($reshook < 0) {
1406 $this->setErrorsFromObject($hookmanager);
1407 $error++;
1408 }
1409 }
1410 }
1411
1412 unset($object->context['createfromclone']);
1413
1414 // End
1415 if (!$error) {
1416 $this->db->commit();
1417 return $object->id;
1418 } else {
1419 $this->db->rollback();
1420 return -1;
1421 }
1422 }
1423
1431 public function createFromOrder($object, User $user)
1432 {
1433 global $hookmanager;
1434
1435 $error = 0;
1436
1437 // Closed order
1438 $this->date = dol_now();
1439 $this->source = 0;
1440
1441 // Avoid updating the row ranks
1442 $this->context['createfromclone'] = 1;
1443
1444 $num = count($object->lines);
1445 for ($i = 0; $i < $num; $i++) {
1446 $line = new FactureLigne($this->db);
1447 $src_line = $object->lines[$i];
1448 '@phan-var-force FactureLigne $src_line';
1449 $line->libelle = $src_line->libelle; // deprecated
1450 $line->label = $src_line->label;
1451 $line->desc = $src_line->desc;
1452 $line->subprice = $src_line->subprice;
1453 $line->total_ht = $src_line->total_ht;
1454 $line->total_tva = $src_line->total_tva;
1455 $line->total_localtax1 = $src_line->total_localtax1;
1456 $line->total_localtax2 = $src_line->total_localtax2;
1457 $line->total_ttc = $src_line->total_ttc;
1458 $line->vat_src_code = $src_line->vat_src_code;
1459 $line->tva_tx = $src_line->tva_tx;
1460 $line->localtax1_tx = $src_line->localtax1_tx;
1461 $line->localtax2_tx = $src_line->localtax2_tx;
1462 $line->qty = $src_line->qty;
1463 $line->fk_remise_except = $src_line->fk_remise_except;
1464 $line->remise_percent = $src_line->remise_percent;
1465 $line->fk_product = $src_line->fk_product;
1466 $line->info_bits = $src_line->info_bits;
1467 $line->product_type = $src_line->product_type;
1468 $line->rang = $src_line->rang;
1469 $line->special_code = $src_line->special_code;
1470 $line->fk_parent_line = $src_line->fk_parent_line;
1471 $line->fk_unit = $src_line->fk_unit;
1472 $line->date_start = $src_line->date_start;
1473 $line->date_end = $src_line->date_end;
1474
1475 // Multicurrency
1476 $line->fk_multicurrency = $src_line->fk_multicurrency;
1477 $line->multicurrency_code = $src_line->multicurrency_code;
1478 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1479 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1480 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1481 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1482
1483 $line->fk_fournprice = $src_line->fk_fournprice;
1484 $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);
1485 $line->pa_ht = $marginInfos[0];
1486
1487 // get extrafields from original line
1488 $src_line->fetch_optionals();
1489 foreach ($src_line->array_options as $options_key => $value) {
1490 $line->array_options[$options_key] = $value;
1491 }
1492
1493 $this->lines[$i] = $line;
1494 }
1495
1496 $this->socid = $object->socid;
1497 $this->fk_project = $object->fk_project;
1498 $this->fk_account = $object->fk_account;
1499 $this->cond_reglement_id = $object->cond_reglement_id;
1500 $this->mode_reglement_id = $object->mode_reglement_id;
1501 $this->fk_incoterms = $object->fk_incoterms;
1502 $this->location_incoterms = $object->location_incoterms;
1503 $this->availability_id = $object->availability_id;
1504 $this->demand_reason_id = $object->demand_reason_id;
1505 $this->delivery_date = $object->delivery_date;
1506 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1507 $this->contact_id = $object->contact_id;
1508 $this->ref_client = $object->ref_client;
1509 $this->ref_customer = $object->ref_client;
1510
1511 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1512 $this->note_private = $object->note_private;
1513 $this->note_public = $object->note_public;
1514 }
1515
1516 $this->module_source = $object->module_source;
1517 $this->pos_source = $object->pos_source;
1518
1519 $this->origin = $object->element;
1520 $this->origin_type = $object->element;
1521 $this->origin_id = $object->id;
1522
1523 $this->fk_user_author = $user->id;
1524 $this->user_creation_id = $user->id;
1525
1526 // get extrafields from original line
1527 $object->fetch_optionals();
1528 foreach ($object->array_options as $options_key => $value) {
1529 $this->array_options[$options_key] = $value;
1530 }
1531
1532 // Possibility to add external linked objects with hooks
1533 $this->linked_objects[$this->origin] = $this->origin_id;
1534 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1535 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1536 }
1537
1538 $ret = $this->create($user);
1539
1540 if ($ret > 0) {
1541 // Actions hooked (by external module)
1542 $hookmanager->initHooks(array('invoicedao'));
1543
1544 $parameters = array('objFrom' => $object);
1545 $action = '';
1546 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1547 if ($reshook < 0) {
1548 $this->setErrorsFromObject($hookmanager);
1549 $error++;
1550 }
1551
1552 if (!$error) {
1553 return 1;
1554 } else {
1555 return -1;
1556 }
1557 } else {
1558 return -1;
1559 }
1560 }
1561
1570 public function createFromContract($object, User $user, $lines = array())
1571 {
1572 global $hookmanager;
1573
1574 $error = 0;
1575
1576 // Closed order
1577 $this->date = dol_now();
1578 $this->source = 0;
1579
1580 $use_all_lines = empty($lines);
1581 $num = count($object->lines);
1582 for ($i = 0; $i < $num; $i++) {
1583 if (!$use_all_lines && !in_array($object->lines[$i]->id, $lines)) {
1584 continue;
1585 }
1586
1587 $line = new FactureLigne($this->db);
1588
1589 $line->libelle = $object->lines[$i]->libelle; // deprecated
1590 $line->label = $object->lines[$i]->label;
1591 $line->desc = $object->lines[$i]->desc;
1592 $line->subprice = $object->lines[$i]->subprice;
1593 $line->total_ht = $object->lines[$i]->total_ht;
1594 $line->total_tva = $object->lines[$i]->total_tva;
1595 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1596 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1597 $line->total_ttc = $object->lines[$i]->total_ttc;
1598 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1599 $line->tva_tx = $object->lines[$i]->tva_tx;
1600 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1601 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1602 $line->qty = $object->lines[$i]->qty;
1603 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1604 $line->remise_percent = $object->lines[$i]->remise_percent;
1605 $line->fk_product = $object->lines[$i]->fk_product;
1606 $line->info_bits = $object->lines[$i]->info_bits;
1607 $line->product_type = $object->lines[$i]->product_type;
1608 $line->rang = $object->lines[$i]->rang;
1609 $line->special_code = $object->lines[$i]->special_code;
1610 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1611 $line->fk_unit = $object->lines[$i]->fk_unit;
1612 $line->date_start = $object->lines[$i]->date_start;
1613 $line->date_end = $object->lines[$i]->date_end;
1614
1615 // Multicurrency
1616 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1617 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1618 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1619 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1620 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1621 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1622
1623 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1624 $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);
1625 $line->pa_ht = $marginInfos[0];
1626
1627 // get extrafields from original line
1628 $object->lines[$i]->fetch_optionals();
1629 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1630 $line->array_options[$options_key] = $value;
1631 }
1632
1633 $this->lines[$i] = $line;
1634 }
1635
1636 $this->socid = $object->socid;
1637 $this->fk_project = $object->fk_project;
1638 $this->fk_account = $object->fk_account;
1639 $this->cond_reglement_id = $object->cond_reglement_id;
1640 $this->mode_reglement_id = $object->mode_reglement_id;
1641 $this->availability_id = $object->availability_id;
1642 $this->demand_reason_id = $object->demand_reason_id;
1643 $this->delivery_date = $object->delivery_date;
1644 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1645 $this->contact_id = $object->contact_id;
1646 $this->ref_client = $object->ref_client;
1647
1648 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1649 $this->note_private = $object->note_private;
1650 $this->note_public = $object->note_public;
1651 }
1652
1653 $this->module_source = $object->module_source;
1654 $this->pos_source = $object->pos_source;
1655
1656 $this->origin = $object->element;
1657 $this->origin_id = $object->id;
1658
1659 $this->fk_user_author = $user->id;
1660 $this->user_creation_id = $user->id;
1661
1662 // get extrafields from original line
1663 $object->fetch_optionals();
1664 foreach ($object->array_options as $options_key => $value) {
1665 $this->array_options[$options_key] = $value;
1666 }
1667
1668 // Possibility to add external linked objects with hooks
1669 $this->linked_objects[$this->origin] = $this->origin_id;
1670 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1671 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1672 }
1673
1674 $ret = $this->create($user);
1675
1676 if ($ret > 0) {
1677 // Actions hooked (by external module)
1678 $hookmanager->initHooks(array('invoicedao'));
1679
1680 $parameters = array('objFrom' => $object);
1681 $action = '';
1682 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1683 if ($reshook < 0) {
1684 $this->setErrorsFromObject($hookmanager);
1685 $error++;
1686 }
1687
1688 if (!$error) {
1689 return 1;
1690 } else {
1691 return -1;
1692 }
1693 } else {
1694 return -1;
1695 }
1696 }
1697
1710 public static function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1711 {
1712 global $conf, $langs, $hookmanager, $action;
1713
1714 if (! in_array($origin->element, array('propal', 'commande'))) {
1715 $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1716 return null;
1717 }
1718
1719 if (empty($date)) {
1720 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1721 return null;
1722 }
1723
1724 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1725
1726 if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1727 $origin->error = 'ErrorDateIsInFuture';
1728 return null;
1729 }
1730
1731 if ($payment_terms_id <= 0) {
1732 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1733 return null;
1734 }
1735
1736 $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1737
1738 if (empty($payment_conditions_deposit_percent)) {
1739 $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1740 return null;
1741 }
1742
1743 if (empty($origin->deposit_percent)) {
1744 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1745 return null;
1746 }
1747
1748 $deposit = new self($origin->db);
1749 $deposit->socid = $origin->socid;
1750 $deposit->type = self::TYPE_DEPOSIT;
1751 $deposit->fk_project = $origin->fk_project;
1752 $deposit->ref_client = $origin->ref_client;
1753 $deposit->ref_customer = $origin->ref_client;
1754 $deposit->date = $date;
1755 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1756 $deposit->cond_reglement_id = $payment_terms_id;
1757 $deposit->availability_id = $origin->availability_id;
1758 $deposit->demand_reason_id = $origin->demand_reason_id;
1759 $deposit->fk_account = $origin->fk_account;
1760 $deposit->fk_incoterms = $origin->fk_incoterms;
1761 $deposit->location_incoterms = $origin->location_incoterms;
1762 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1763 $deposit->multicurrency_code = $origin->multicurrency_code;
1764 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1765 $deposit->module_source = $origin->module_source;
1766 $deposit->pos_source = $origin->pos_source;
1767 $deposit->model_pdf = 'crabe';
1768
1769 $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1770
1771 if (getDolGlobalString($modelByTypeConfName)) {
1772 $deposit->model_pdf = getDolGlobalString($modelByTypeConfName);
1773 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
1774 $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF');
1775 }
1776
1777 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1778 $deposit->note_private = $origin->note_private;
1779 $deposit->note_public = $origin->note_public;
1780 }
1781
1782 $deposit->origin = $origin->element;
1783 $deposit->origin_id = $origin->id;
1784
1785 $origin->fetch_optionals();
1786
1787 foreach ($origin->array_options as $extrakey => $value) {
1788 $deposit->array_options[$extrakey] = $value;
1789 }
1790
1791 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1792
1793 foreach ($overrideFields as $key => $value) {
1794 $deposit->$key = $value;
1795 }
1796
1797 $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1798
1799 $origin->db->begin();
1800
1801 // Facture::create() also imports contact from origin
1802 $createReturn = $deposit->create($user, $notrigger);
1803
1804 if ($createReturn <= 0) {
1805 $origin->db->rollback();
1806 $origin->error = $deposit->error;
1807 $origin->errors = $deposit->errors;
1808 return null;
1809 }
1810
1811 $amount_ttc_diff = 0;
1812 $amountdeposit = array();
1813 $descriptions = array();
1814
1815 // Bucket lines by tva_tx + vat_src_code so addline below receives the rate in
1816 // the "tva (CODE)" format that Facture::addline knows how to parse. Bucketing
1817 // on tva_tx alone wipes out the dictionary Code on the generated deposit line
1818 // and on every downstream document derived from it (see issue #38035).
1819 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1820 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1821
1822 $TTotalByTva = array();
1823 foreach ($origin->lines as &$line) {
1824 if (!empty($line->special_code)) {
1825 continue;
1826 }
1827 $key = $line->tva_tx . ($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
1828 if (!array_key_exists($key, $TTotalByTva)) {
1829 $TTotalByTva[$key] = 0;
1830 $descriptions[$key] = '';
1831 }
1832 $TTotalByTva[$key] += $line->total_ttc;
1833 $descriptions[$key] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1834 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1835 $descriptions[$key] .= $langs->trans('Qty') . ' : ' . $line->qty;
1836 $descriptions[$key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1837 }
1838
1839 foreach ($TTotalByTva as $tva => &$total) {
1840 $tva_rate_only = preg_replace('/\s*\‍(.*\‍)/', '', (string) $tva);
1841 $coef = $total / $origin->total_ttc; // Calc coef
1842 $am = $amount * $coef;
1843 $amount_ttc_diff += $am;
1844 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100); // Convert into HT for the addline
1845 }
1846 } else {
1847 $totalamount = 0;
1848 $lines = $origin->lines;
1849 $numlines = count($lines);
1850 for ($i = 0; $i < $numlines; $i++) {
1851 if (empty($lines[$i]->qty)) {
1852 continue; // We discard qty=0, it is an option
1853 }
1854 if (!empty($lines[$i]->special_code)) {
1855 continue; // We discard special_code (frais port, ecotaxe, option, ...)
1856 }
1857
1858 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1859 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ? ' ('.$lines[$i]->vat_src_code.')' : '');
1860 if (!isset($amountdeposit[$tva_key])) {
1861 $amountdeposit[$tva_key] = 0;
1862 $descriptions[$tva_key] = '';
1863 }
1864 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (float) $origin->deposit_percent) / 100;
1865 $descriptions[$tva_key] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1866 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1867 $descriptions[$tva_key] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1868 $descriptions[$tva_key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1869 }
1870
1871 if ($totalamount == 0) {
1872 $amountdeposit[0] = 0;
1873 }
1874
1875 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1876 }
1877
1878 foreach ($amountdeposit as $tva => $amount) {
1879 if (empty($amount)) {
1880 continue;
1881 }
1882
1883 $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1884
1885 // Hidden conf
1886 if (getDolGlobalString('INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1887 $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1888 }
1889
1890 $addlineResult = $deposit->addline(
1891 $descline,
1892 $amount, // subprice
1893 1, // quantity
1894 $tva, // vat rate
1895 0, // localtax1_tx
1896 0, // localtax2_tx
1897 (!getDolGlobalString('INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1898 0, // remise_percent
1899 0, // date_start
1900 0, // date_end
1901 0,
1902 0, // info_bits
1903 0,
1904 'HT',
1905 0,
1906 0, // product_type
1907 1,
1908 0, // special_code
1909 $deposit->origin,
1910 0,
1911 0,
1912 0,
1913 0
1914 //,$langs->trans('Deposit') //Deprecated
1915 );
1916
1917 if ($addlineResult < 0) {
1918 $origin->db->rollback();
1919 $origin->error = $deposit->error;
1920 $origin->errors = $deposit->errors;
1921 return null;
1922 }
1923 }
1924
1925 $diff = $deposit->total_ttc - $amount_ttc_diff;
1926
1927 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1928 $deposit->fetch_lines();
1929 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1930
1931 // Pass tva_tx in the "rate (CODE)" form so updateline preserves the vat_src_code
1932 // it received from addline; passing the bare rate would wipe the code.
1933 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ? ' ('.$deposit->lines[0]->vat_src_code.')' : '');
1934 $updatelineResult = $deposit->updateline(
1935 $deposit->lines[0]->id,
1936 $deposit->lines[0]->desc,
1937 $subprice_diff,
1938 $deposit->lines[0]->qty,
1939 $deposit->lines[0]->remise_percent,
1940 $deposit->lines[0]->date_start,
1941 $deposit->lines[0]->date_end,
1942 $tva_tx_with_code,
1943 0,
1944 0,
1945 'HT',
1946 $deposit->lines[0]->info_bits,
1947 $deposit->lines[0]->product_type,
1948 0,
1949 0,
1950 0,
1951 $deposit->lines[0]->pa_ht,
1952 $deposit->lines[0]->label,
1953 0,
1954 array(),
1955 100
1956 );
1957
1958 if ($updatelineResult < 0) {
1959 $origin->db->rollback();
1960 $origin->error = $deposit->error;
1961 $origin->errors = $deposit->errors;
1962 return null;
1963 }
1964 }
1965
1966 $hookmanager->initHooks(array('invoicedao'));
1967
1968 $parameters = array('objFrom' => $origin);
1969 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
1970 // modified by hook
1971 if ($reshook < 0) {
1972 $origin->db->rollback();
1973 $origin->error = $hookmanager->error;
1974 $origin->errors = $hookmanager->errors;
1975 return null;
1976 }
1977
1978 if (!empty($autoValidateDeposit)) {
1979 $validateReturn = $deposit->validate($user, '', 0, $notrigger);
1980
1981 if ($validateReturn < 0) {
1982 $origin->db->rollback();
1983 $origin->error = $deposit->error;
1984 $origin->errors = $deposit->errors;
1985 return null;
1986 }
1987 }
1988
1989 unset($deposit->context['createdepositfromorigin']);
1990
1991 $origin->db->commit();
1992
1993 return $deposit;
1994 }
1995
2003 public function getTooltipContentArray($params)
2004 {
2005 global $conf, $langs, $mysoc, $user;
2006
2007 $langs->load('bills');
2008
2009 $datas = [];
2010 $moretitle = $params['moretitle'] ?? '';
2011
2012 $picto = $this->picto;
2013 if ($this->type == self::TYPE_REPLACEMENT) {
2014 $picto .= 'r'; // Replacement invoice
2015 }
2016 if ($this->type == self::TYPE_CREDIT_NOTE) {
2017 $picto .= 'a'; // Credit note
2018 }
2019 if ($this->type == self::TYPE_DEPOSIT) {
2020 $picto .= 'd'; // Deposit invoice
2021 }
2022
2023 if ($user->hasRight("facture", "read")) {
2024 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
2025
2026 $datas['picto'] .= '&nbsp;'.$this->getLibType(1);
2027
2028 // Complete datas
2029 if (!empty($params['fromajaxtooltip']) && !isset($this->totalpaid)) {
2030 $this->totalpaid = $this->getSommePaiement(0);
2031 }
2032 if (!empty($params['fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2033 $this->totalcreditnotes = $this->getSumCreditNotesUsed(0);
2034 }
2035 if (!empty($params['fromajaxtooltip']) && !isset($this->totaldeposits)) {
2036 $this->totaldeposits = $this->getSumDepositsUsed(0);
2037 }
2038 if (isset($this->status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2039 $datas['picto'] .= ' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2040 }
2041 if ($moretitle) {
2042 $datas['picto'] .= ' - '.$moretitle;
2043 }
2044 if (!empty($this->ref)) {
2045 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2046 }
2047 if (!empty($this->ref_customer)) {
2048 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
2049 }
2050 if (!empty($this->date)) {
2051 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
2052 }
2053 if (!empty($this->total_ht)) {
2054 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2055 }
2056 if (!empty($this->total_tva)) {
2057 $datas['amountvat'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2058 }
2059 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2060 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2061 }
2062 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2063 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
2064 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2065 }
2066 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2067 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2068 }
2069 if (!empty($this->total_ttc)) {
2070 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2071 }
2072 }
2073
2074 return $datas;
2075 }
2076
2091 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
2092 {
2093 global $langs, $conf, $user;
2094
2095 if (!empty($conf->dol_no_mouse_hover)) {
2096 $notooltip = 1; // Force disable tooltips
2097 }
2098
2099 $result = '';
2100
2101 if ($option == 'withdraw') {
2102 $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
2103 } else {
2104 $url = DOL_URL_ROOT.'/compta/facture/card.php?id='.$this->id;
2105 }
2106
2107 if (!$user->hasRight("facture", "read")) {
2108 $option = 'nolink';
2109 }
2110
2111 if ($option !== 'nolink') {
2112 // Add param to save lastsearch_values or not
2113 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2114 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2115 $add_save_lastsearch_values = 1;
2116 }
2117 if ($add_save_lastsearch_values) {
2118 $url .= '&save_lastsearch_values=1';
2119 }
2120 }
2121
2122 if ($short) {
2123 return $url;
2124 }
2125
2126 $picto = $this->picto;
2127 if ($this->type == self::TYPE_REPLACEMENT) {
2128 $picto .= 'r'; // Replacement invoice
2129 }
2130 if ($this->type == self::TYPE_CREDIT_NOTE) {
2131 $picto .= 'a'; // Credit note
2132 }
2133 if ($this->type == self::TYPE_DEPOSIT) {
2134 $picto .= 'd'; // Deposit invoice
2135 }
2136
2137 $params = [
2138 'id' => $this->id,
2139 'objecttype' => $this->element,
2140 'moretitle' => $moretitle,
2141 'option' => $option,
2142 ];
2143 $classfortooltip = 'classfortooltip';
2144 $dataparams = '';
2145 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2146 $classfortooltip = 'classforajaxtooltip';
2147 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2148 $label = '';
2149 } else {
2150 $label = implode($this->getTooltipContentArray($params));
2151 }
2152
2153 $linkclose = ($target ? ' target="'.$target.'"' : '');
2154 if (empty($notooltip) && $user->hasRight("facture", "read")) {
2155 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2156 $label = $langs->trans("Invoice");
2157 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2158 }
2159 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2160 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2161 }
2162
2163 $linkstart = '<a href="'.$url.'"';
2164 $linkstart .= $linkclose.'>';
2165 $linkend = '</a>';
2166
2167 if ($option == 'nolink') {
2168 $linkstart = '';
2169 $linkend = '';
2170 }
2171
2172 $result .= $linkstart;
2173 if ($withpicto) {
2174 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2175 }
2176 if ($withpicto != 2) {
2177 $result .= ($max ? dol_trunc($this->ref, $max) : $this->ref);
2178 }
2179 $result .= $linkend;
2180
2181 if ($addlinktonotes) {
2182 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2183 if ($txttoshow) {
2184 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
2185 $result .= ' <span class="note inline-block">';
2186 $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dolPrintHTMLForAttribute($notetoshow).'">';
2187 $result .= img_picto('', 'note');
2188 $result .= '</a>';
2189 $result .= '</span>';
2190 }
2191 }
2192
2193 global $action, $hookmanager;
2194 $hookmanager->initHooks(array('invoicedao'));
2195 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value' => $save_lastsearch_value, 'target' => $target);
2196 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2197 if ($reshook > 0) {
2198 $result = $hookmanager->resPrint;
2199 } else {
2200 $result .= $hookmanager->resPrint;
2201 }
2202
2203 return $result;
2204 }
2205
2216 public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false)
2217 {
2218 global $conf, $extrafields;
2219
2220 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2221 return -1;
2222 }
2223
2224 $extraFieldsCheck = false;
2225 $doFetchInOneSqlRequest = getDolGlobalInt('MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2226
2227 if ($doFetchInOneSqlRequest) {
2228 // If $extrafields is not a known object, we initialize it
2229 if (!isset($extrafields) || !is_object($extrafields)) {
2230 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2231 $extrafields = new ExtraFields($this->db);
2232 }
2233
2234 // Load array of extrafields for elementype = $this->table_element
2235 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
2236 $extrafields->fetch_name_optionals_label($this->table_element);
2237 }
2238
2239 $extraFieldsCheck = (
2240 !empty($extrafields->attributes[$this->table_element]['label'])
2241 && is_array($extrafields->attributes[$this->table_element]['label'])
2242 && count($extrafields->attributes[$this->table_element]['label']) > 0
2243 );
2244 }
2245
2246
2247 // Original SQL query from fetch()
2248 $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2249 $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2250 $sql .= ', f.datef as df, f.date_pointoftax';
2251 $sql .= ', f.date_lim_reglement as dlr';
2252 $sql .= ', f.datec as datec';
2253 $sql .= ', f.date_valid as datev';
2254 $sql .= ', f.tms as datem';
2255 $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';
2256 $sql .= ", f.fk_input_reason";
2257 $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
2258 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2259 $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2260 $sql .= ', f.fk_account';
2261 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2262 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2263 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2264 $sql .= ', f.fk_incoterms, f.location_incoterms';
2265 $sql .= ', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2266 $sql .= ", i.libelle as label_incoterms";
2267 $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";
2268 $sql .= ", f.payment_reference, f.dispute_status";
2269
2270 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2271 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2272 $type = !empty($extrafields->attributes[$this->table_element]['type'][$key])
2273 ? $extrafields->attributes[$this->table_element]['type'][$key]
2274 : '';
2275
2276 if ($type !== 'separate') {
2277 if (in_array($type, array('point','multipts','linestrg','polygon'))) {
2278 $sql .= ", ST_AsWKT(ef.".$key.") as ".$key;
2279 } else {
2280 $sql .= ", ef.".$key;
2281 }
2282 }
2283 }
2284 }
2285
2286 $sql .= ' FROM '.$this->db->prefix().'facture as f';
2287
2288 // Add extrafields table to the join if we have extrafields for this entity
2289 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2290 // Add LEFT JOIN for extrafields
2291 $sql .= ' LEFT JOIN '.$this->db->prefix().$this->table_element.'_extrafields as ef ON f.rowid = ef.fk_object';
2292 }
2293
2294 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2295 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_paiement as p ON f.fk_mode_reglement = p.id';
2296 $sql .= " LEFT JOIN ".$this->db->prefix()."c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2297 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_incoterms as i ON f.fk_incoterms = i.rowid';
2298
2299 if ($rowid) {
2300 $sql .= " WHERE f.rowid = ".((int) $rowid);
2301 } else {
2302 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
2303 if ($ref) {
2304 $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
2305 }
2306 if ($ref_ext) {
2307 $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
2308 }
2309 }
2310
2311 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2312 $resql = $this->db->query($sql);
2313 if ($resql) {
2314 if ($this->db->num_rows($resql)) {
2315 $obj = $this->db->fetch_object($resql);
2316
2317 $this->id = $obj->rowid;
2318 $this->entity = $obj->entity;
2319
2320 $this->ref = $obj->ref;
2321 $this->ref_client = $obj->ref_client;
2322 $this->ref_customer = $obj->ref_client;
2323 $this->ref_ext = $obj->ref_ext;
2324 $this->type = $obj->type;
2325 $this->subtype = $obj->subtype;
2326 $this->date = $this->db->jdate($obj->df);
2327 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2328 $this->date_creation = $this->db->jdate($obj->datec);
2329 $this->date_validation = $this->db->jdate($obj->datev);
2330 $this->date_modification = $this->db->jdate($obj->datem);
2331 $this->datem = $this->db->jdate($obj->datem);
2332 $this->total_ht = $obj->total_ht;
2333 $this->total_tva = $obj->total_tva;
2334 $this->total_localtax1 = $obj->localtax1;
2335 $this->total_localtax2 = $obj->localtax2;
2336 $this->total_ttc = $obj->total_ttc;
2337 $this->revenuestamp = $obj->revenuestamp;
2338 $this->paye = $obj->paye;
2339 $this->close_code = $obj->close_code;
2340 $this->close_note = $obj->close_note;
2341
2342 $this->socid = $obj->fk_soc;
2343 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2344
2345 $this->fk_project = $obj->fk_project;
2346 $this->project = null; // Clear if another value was already set by fetch_projet
2347
2348 $this->statut = $obj->status; // deprecated
2349 $this->status = $obj->status;
2350
2351 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2352 $this->mode_reglement_id = $obj->fk_mode_reglement;
2353 $this->mode_reglement_code = $obj->mode_reglement_code;
2354 $this->mode_reglement = $obj->mode_reglement_libelle;
2355 $this->cond_reglement_id = $obj->fk_cond_reglement;
2356 $this->cond_reglement_code = $obj->cond_reglement_code;
2357 $this->cond_reglement = $obj->cond_reglement_libelle;
2358 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2359 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2360 $this->fk_facture_source = $obj->fk_facture_source;
2361 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2362 $this->note = $obj->note_private; // deprecated
2363 $this->note_private = $obj->note_private;
2364 $this->note_public = $obj->note_public;
2365 $this->user_creation_id = $obj->fk_user_author;
2366 $this->user_validation_id = $obj->fk_user_valid;
2367 $this->user_modification_id = $obj->fk_user_modif;
2368 $this->fk_user_author = $obj->fk_user_author;
2369 $this->fk_user_valid = $obj->fk_user_valid;
2370 $this->fk_user_modif = $obj->fk_user_modif;
2371 $this->model_pdf = $obj->model_pdf;
2372 $this->last_main_doc = $obj->last_main_doc;
2373 $this->demand_reason_id = $obj->fk_input_reason;
2374 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2375 $this->situation_counter = $obj->situation_counter;
2376 $this->situation_final = $obj->situation_final;
2377 $this->retained_warranty = $obj->retained_warranty;
2378 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2379 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2380
2381 $this->payment_reference = $obj->payment_reference;
2382 $this->dispute_status = $obj->dispute_status;
2383
2384 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2385
2386 //Incoterms
2387 $this->fk_incoterms = $obj->fk_incoterms;
2388 $this->location_incoterms = $obj->location_incoterms;
2389 $this->label_incoterms = $obj->label_incoterms;
2390
2391 $this->module_source = $obj->module_source;
2392 $this->pos_source = $obj->pos_source;
2393 $this->pos_print_counter = $obj->pos_print_counter;
2394 $this->email_sent_counter = $obj->email_sent_counter;
2395
2396 // Multicurrency
2397 $this->fk_multicurrency = $obj->fk_multicurrency;
2398 $this->multicurrency_code = $obj->multicurrency_code;
2399 $this->multicurrency_tx = $obj->multicurrency_tx;
2400 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2401 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2402 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2403
2404 // Now process extrafields
2405 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2406 $this->array_options = array();
2407
2408 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2409 $type = !empty($extrafields->attributes[$this->table_element]['type'][$key])
2410 ? $extrafields->attributes[$this->table_element]['type'][$key]
2411 : '';
2412
2413 if ($type !== 'separate') {
2414 $rawval = $obj->$key;
2415
2416 // date/datetime
2417 if (in_array($type, array('date', 'datetime'))) {
2418 $this->array_options['options_' . $key] = $this->db->jdate($rawval);
2419 } elseif ($type == 'password') {
2420 if (!empty($rawval) && preg_match('/^dolcrypt:/', $rawval)) {
2421 $this->array_options['options_' . $key] = dolDecrypt($rawval);
2422 } else {
2423 $this->array_options['options_' . $key] = $rawval;
2424 }
2425 } else {
2426 $this->array_options['options_' . $key] = $rawval;
2427 }
2428 }
2429 }
2430
2431 // Champs "computed"
2432 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
2433 if (!empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
2434 if (empty($conf->disable_compute)) {
2435 global $objectoffield;
2436 $objectoffield = $this;
2437 $this->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
2438 }
2439 }
2440 }
2441 }
2442
2443 if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2445 }
2446
2447 if (!$doFetchInOneSqlRequest) {
2448 // Retrieve all extrafield
2449 // fetch optionals attributes and labels
2450 $this->fetch_optionals();
2451 }
2452
2453 // Lines
2454 $this->lines = array();
2455
2456 $result = $this->fetch_lines();
2457 if ($result < 0) {
2458 $this->error = $this->db->error();
2459 return -3;
2460 }
2461
2462 $this->db->free($resql);
2463
2464 return 1;
2465 } else {
2466 $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2467
2468 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2469 return 0;
2470 }
2471 } else {
2472 $this->error = $this->db->lasterror();
2473 return -1;
2474 }
2475 }
2476
2477
2478 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2486 public function fetch_lines($only_type_product = '', $loadalsotranslation = 0)
2487 {
2488 global $conf, $extrafields;
2489
2490 // phpcs:enable
2491 $this->lines = array();
2492
2493 $extraFieldsCheck = false;
2494 $doFetchInOneSqlRequest = getDolGlobalInt('MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2495
2496 if ($doFetchInOneSqlRequest) {
2497 // If $extrafields is not a known object, we initialize it
2498 if (!isset($extrafields) || !is_object($extrafields)) {
2499 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2500 $extrafields = new ExtraFields($this->db);
2501 }
2502
2503 // Load array of extrafields for elementype = $this->table_element_line
2504 if (empty($extrafields->attributes[$this->table_element_line]['loaded'])) {
2505 $extrafields->fetch_name_optionals_label($this->table_element_line);
2506 }
2507
2508 $extraFieldsCheck = (
2509 !empty($extrafields->attributes[$this->table_element_line]['label'])
2510 && is_array($extrafields->attributes[$this->table_element_line]['label'])
2511 && count($extrafields->attributes[$this->table_element_line]['label']) > 0
2512 );
2513 }
2514
2515 $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,';
2516 $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,';
2517 $sql .= ' l.situation_percent, l.fk_prev_id,';
2518 $sql .= ' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2519 $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2520 $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,';
2521 $sql .= ' l.fk_unit, l.extraparams,';
2522 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2523 $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';
2524
2525 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2526 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2527 $type = !empty($extrafields->attributes[$this->table_element_line]['type'][$key])
2528 ? $extrafields->attributes[$this->table_element_line]['type'][$key]
2529 : '';
2530
2531 if ($type !== 'separate') {
2532 if (in_array($type, array('point','multipts','linestrg','polygon'))) {
2533 $sql .= ", ST_AsWKT(ef.".$key.") as ".$key;
2534 } else {
2535 $sql .= ", ef.".$key;
2536 }
2537 }
2538 }
2539 }
2540
2541 $sql .= ' FROM '.$this->db->prefix().'facturedet as l';
2542
2543 // Add extrafields table to the join if we have extrafields for this entity
2544 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2545 // Add LEFT JOIN for extrafields
2546 $sql .= ' LEFT JOIN '.$this->db->prefix().$this->table_element_line.'_extrafields as ef ON l.rowid = ef.fk_object';
2547 }
2548
2549 $sql .= ' LEFT JOIN '.$this->db->prefix().'product as p ON l.fk_product = p.rowid';
2550 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2551 if (is_int($only_type_product)) {
2552 $sql .= " AND p.fk_product_type = ".((int) $only_type_product);
2553 }
2554 $sql .= ' ORDER BY l.rang, l.rowid';
2555
2556 dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2557 $result = $this->db->query($sql);
2558 if ($result) {
2559 $num = $this->db->num_rows($result);
2560 $i = 0;
2561 while ($i < $num) {
2562 $objp = $this->db->fetch_object($result);
2563 $line = new FactureLigne($this->db);
2564
2565 $line->id = $objp->rowid;
2566 $line->rowid = $objp->rowid; // deprecated
2567 $line->fk_facture = $objp->fk_facture;
2568 $line->label = $objp->custom_label; // deprecated
2569 $line->desc = $objp->description; // Description line
2570 $line->description = $objp->description; // Description line
2571 $line->product_type = $objp->product_type; // Type of line
2572 $line->ref = $objp->product_ref; // Ref product
2573 $line->product_ref = $objp->product_ref; // Ref product
2574 $line->libelle = $objp->product_label; // deprecated
2575 $line->product_label = $objp->product_label; // Label product
2576 $line->product_barcode = $objp->product_barcode; // Barcode number product
2577 $line->product_desc = $objp->product_desc; // Description product
2578 $line->fk_product_type = $objp->fk_product_type; // Type of product
2579 $line->qty = $objp->qty;
2580 $line->subprice = $objp->subprice;
2581 $line->ref_ext = $objp->ref_ext; // line external ref
2582
2583 $line->vat_src_code = $objp->vat_src_code;
2584 $line->tva_tx = $objp->tva_tx;
2585 $line->localtax1_tx = $objp->localtax1_tx;
2586 $line->localtax2_tx = $objp->localtax2_tx;
2587 $line->localtax1_type = $objp->localtax1_type;
2588 $line->localtax2_type = $objp->localtax2_type;
2589 $line->remise_percent = $objp->remise_percent;
2590 $line->fk_remise_except = $objp->fk_remise_except;
2591 $line->fk_product = $objp->fk_product;
2592 $line->date_start = $this->db->jdate($objp->date_start);
2593 $line->date_end = $this->db->jdate($objp->date_end);
2594 $line->info_bits = $objp->info_bits;
2595 $line->total_ht = $objp->total_ht;
2596 $line->total_tva = $objp->total_tva;
2597 $line->total_localtax1 = $objp->total_localtax1;
2598 $line->total_localtax2 = $objp->total_localtax2;
2599 $line->total_ttc = $objp->total_ttc;
2600
2601 $line->fk_fournprice = $objp->fk_fournprice;
2602 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2603 $line->pa_ht = $marginInfos[0];
2604 $line->marge_tx = (string) $marginInfos[1];
2605 $line->marque_tx = (string) $marginInfos[2];
2606 $line->rang = $objp->rang;
2607 $line->special_code = $objp->special_code;
2608 $line->fk_parent_line = $objp->fk_parent_line;
2609 $line->situation_percent = $objp->situation_percent;
2610 $line->fk_prev_id = $objp->fk_prev_id;
2611 $line->fk_unit = $objp->fk_unit;
2612
2613 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2614
2615 $line->batch = $objp->batch;
2616 $line->fk_warehouse = $objp->fk_warehouse;
2617
2618 // Accountancy
2619 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2620
2621 // Multicurrency
2622 $line->fk_multicurrency = $objp->fk_multicurrency;
2623 $line->multicurrency_code = $objp->multicurrency_code;
2624 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2625 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2626 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2627 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2628
2629 $line->array_options = array();
2630 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2631 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2632 $type = !empty($extrafields->attributes[$this->table_element_line]['type'][$key])
2633 ? $extrafields->attributes[$this->table_element_line]['type'][$key]
2634 : '';
2635
2636 if ($type !== 'separate') {
2637 $rawval = $objp->$key;
2638
2639 // date/datetime
2640 if (in_array($type, array('date', 'datetime'))) {
2641 $line->array_options['options_' . $key] = $this->db->jdate($rawval);
2642 } elseif ($type == 'password') {
2643 if (!empty($rawval) && preg_match('/^dolcrypt:/', $rawval)) {
2644 $line->array_options['options_' . $key] = dolDecrypt($rawval);
2645 } else {
2646 $line->array_options['options_' . $key] = $rawval;
2647 }
2648 } else {
2649 $line->array_options['options_' . $key] = $rawval;
2650 }
2651 }
2652 }
2653
2654 // Champs "computed"
2655 foreach ($extrafields->attributes[$this->table_element_line]['label'] as $key => $val) {
2656 if (!empty($extrafields->attributes[$this->table_element_line]['computed'][$key])) {
2657 if (empty($conf->disable_compute)) {
2658 global $objectoffield;
2659 $objectoffield = $line;
2660 $line->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element_line]['computed'][$key], 1, 0, '2');
2661 }
2662 }
2663 }
2664 }
2665
2666 if (!$doFetchInOneSqlRequest) {
2667 // Retrieve all extrafield
2668 $line->fetch_optionals();
2669 }
2670
2671 // multilangs
2672 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2673 $tmpproduct = new Product($this->db);
2674 $tmpproduct->fetch($objp->fk_product);
2675 $tmpproduct->getMultiLangs();
2676
2677 $line->multilangs = $tmpproduct->multilangs;
2678 }
2679
2680 $this->lines[$i] = $line;
2681
2682 $i++;
2683 }
2684 $this->db->free($result);
2685 return 1;
2686 } else {
2687 $this->error = $this->db->error();
2688 return -3;
2689 }
2690 }
2691
2699 {
2700 global $conf;
2701
2702 $this->tab_previous_situation_invoice = array();
2703 $this->tab_next_situation_invoice = array();
2704
2705 $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2706 $sql .= " WHERE rowid <> ".((int) $this->id);
2707 $sql .= ' AND entity = '.((int) $this->entity);
2708 $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2709 $sql .= ' ORDER BY situation_counter ASC';
2710
2711 dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2712 $result = $this->db->query($sql);
2713 if ($result && $this->db->num_rows($result) > 0) {
2714 while ($objp = $this->db->fetch_object($result)) {
2715 $invoice = new Facture($this->db);
2716 if ($invoice->fetch($objp->rowid) > 0) {
2717 if ($objp->situation_counter < $this->situation_counter
2718 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2719 ) {
2720 $this->tab_previous_situation_invoice[] = $invoice;
2721 } else {
2722 $this->tab_next_situation_invoice[] = $invoice;
2723 }
2724 }
2725 }
2726 }
2727 }
2728
2736 public function update(User $user, $notrigger = 0)
2737 {
2738 $error = 0;
2739
2740 // Clean parameters
2741 if (empty($this->type)) {
2742 $this->type = self::TYPE_STANDARD;
2743 }
2744 if (isset($this->subtype)) {
2745 $this->subtype = (int) $this->subtype;
2746 }
2747 if (isset($this->ref)) {
2748 $this->ref = trim($this->ref);
2749 }
2750 if (isset($this->ref_ext)) {
2751 $this->ref_ext = trim($this->ref_ext);
2752 }
2753 if (!empty($this->ref_customer)) {
2754 $this->ref_customer = trim($this->ref_customer);
2755 }
2756 if (isset($this->increment)) {
2757 $this->increment = trim($this->increment);
2758 }
2759 if (isset($this->close_code)) {
2760 $this->close_code = trim($this->close_code);
2761 }
2762 if (isset($this->close_note)) {
2763 $this->close_note = trim($this->close_note);
2764 }
2765 if (isset($this->note) || isset($this->note_private)) {
2766 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2767 }
2768 if (isset($this->note) || isset($this->note_private)) {
2769 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2770 }
2771 if (isset($this->note_public)) {
2772 $this->note_public = trim($this->note_public);
2773 }
2774 if (isset($this->model_pdf)) {
2775 $this->model_pdf = trim($this->model_pdf);
2776 }
2777 if (isset($this->import_key)) {
2778 $this->import_key = trim($this->import_key);
2779 }
2780 if (isset($this->retained_warranty)) {
2781 $this->retained_warranty = (float) $this->retained_warranty;
2782 }
2783 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2784 $this->user_creation_id = $this->fk_user_author;
2785 }
2786 if (!isset($this->user_modification_id) && !empty($user->id)) {
2787 $this->user_modification_id = $user->id;
2788 }
2789 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2790 $this->user_validation_id = $this->fk_user_valid;
2791 }
2792
2793 // Update request
2794 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2795 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2796 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2797 $sql .= " type=".(isset($this->type) ? $this->db->escape((string) $this->type) : "null").",";
2798 $sql .= " subtype=".(isset($this->subtype) ? (int) $this->subtype : "null").",";
2799 $sql .= " ref_client=".(!empty($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : (isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null")).",";
2800 $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2801 $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape((string) $this->socid) : "null").",";
2802 $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2803 $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2804 $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2805 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2806 $sql .= " paye=".(isset($this->paye) ? $this->db->escape((string) $this->paye) : 0).",";
2807 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2808 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2809 $sql .= " total_tva=".((float) $this->total_tva).",";
2810 $sql .= " localtax1=".((float) $this->total_localtax1).",";
2811 $sql .= " localtax2=".((float) $this->total_localtax2).",";
2812 $sql .= " total_ht=".((float) $this->total_ht).",";
2813 $sql .= " total_ttc=".((float) $this->total_ttc).",";
2814 $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? (float) $this->revenuestamp : "null").",";
2815 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
2816 $sql .= " fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) : "null").",";
2817 $sql .= " fk_user_modif=".(!empty($user->id) ? ((int) $user->id) : "null").",";
2818 $sql .= " fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
2819 $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source : "null").",";
2820 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
2821 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
2822 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
2823 $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2824 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2825 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2826 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2827 $sql .= " import_key = ".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2828 $sql .= " module_source = ".(isset($this->module_source) ? "'".$this->db->escape($this->module_source)."'" : "null").",";
2829 $sql .= " pos_source = ".(isset($this->pos_source) ? "'".$this->db->escape($this->pos_source)."'" : "null").",";
2830 $sql .= " pos_print_counter = ".(int) $this->pos_print_counter.",";
2831 $sql .= " situation_cycle_ref = ".(empty($this->situation_cycle_ref) ? "null" : (int) $this->situation_cycle_ref).",";
2832 $sql .= " situation_counter = ".(empty($this->situation_counter) ? "null" : (int) $this->situation_counter).",";
2833 $sql .= " situation_final = ".(empty($this->situation_final) ? "0" : (int) $this->situation_final).",";
2834 $sql .= " retained_warranty = ".(empty($this->retained_warranty) ? "0" : (float) $this->retained_warranty).",";
2835 $sql .= " retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2836 $sql .= " retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement : "null");
2837 $sql .= " WHERE rowid = ".((int) $this->id);
2838
2839 $this->db->begin();
2840
2841 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2842 $resql = $this->db->query($sql);
2843 if (!$resql) {
2844 $error++;
2845 $this->errors[] = "Error ".$this->db->lasterror();
2846 }
2847
2848 if (!$error) {
2849 $result = $this->insertExtraFields();
2850 if ($result < 0) {
2851 $error++;
2852 }
2853 }
2854
2855 if (!$error && !$notrigger) {
2856 // Call trigger
2857 $result = $this->call_trigger('BILL_MODIFY', $user);
2858 if ($result < 0) {
2859 $error++;
2860 }
2861 // End call triggers
2862 }
2863
2864 // Commit or rollback
2865 if ($error) {
2866 foreach ($this->errors as $errmsg) {
2867 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2868 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2869 }
2870 $this->db->rollback();
2871 return -1 * $error;
2872 } else {
2873 $this->db->commit();
2874 return 1;
2875 }
2876 }
2877
2878
2879 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2886 public function insert_discount($idremise)
2887 {
2888 // phpcs:enable
2889 global $langs;
2890
2891 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2892 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2893
2894 $this->db->begin();
2895
2896 $remise = new DiscountAbsolute($this->db);
2897 $result = $remise->fetch($idremise);
2898
2899 if ($result > 0) {
2900 if ($remise->fk_facture) { // Protection against multiple submission
2901 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2902 $this->db->rollback();
2903 return -5;
2904 }
2905
2906 $facligne = new FactureLigne($this->db);
2907 $facligne->fk_facture = $this->id;
2908 $facligne->fk_remise_except = $remise->id;
2909 $facligne->desc = $remise->description; // Description ligne
2910 $facligne->vat_src_code = $remise->vat_src_code;
2911 $facligne->tva_tx = $remise->tva_tx;
2912 $facligne->subprice = -(float) $remise->total_ht;
2913 $facligne->fk_product = 0; // Id produit predefini
2914 $facligne->qty = 1;
2915 $facligne->remise_percent = 0;
2916 $facligne->rang = -1;
2917 $facligne->info_bits = 2;
2918
2919 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
2920 $facligne->rang = 1;
2921 $linecount = count($this->lines);
2922 for ($ii = 1; $ii <= $linecount; $ii++) {
2923 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2924 }
2925 }
2926
2927 // Get buy/cost price of invoice that is source of discount
2928 if ($remise->fk_facture_source > 0) {
2929 $srcinvoice = new Facture($this->db);
2930 $srcinvoice->fetch($remise->fk_facture_source);
2931 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2932 $formmargin = new FormMargin($this->db);
2933 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2934 $facligne->pa_ht = $arraytmp['pa_total'];
2935 }
2936
2937 $facligne->total_ht = -(float) $remise->total_ht;
2938 $facligne->total_tva = -(float) $remise->total_tva;
2939 $facligne->total_ttc = -(float) $remise->total_ttc;
2940
2941 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2942 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
2943 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
2944 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
2945
2946 $lineid = $facligne->insert();
2947 if ($lineid > 0) {
2948 $result = $this->update_price(1);
2949 if ($result > 0) {
2950 // Create link between discount and invoice line
2951 $result = $remise->link_to_invoice($lineid, 0);
2952 if ($result < 0) {
2953 $this->error = $remise->error;
2954 $this->db->rollback();
2955 return -4;
2956 }
2957
2958 $this->db->commit();
2959 return 1;
2960 } else {
2961 $this->error = $facligne->error;
2962 $this->db->rollback();
2963 return -1;
2964 }
2965 } else {
2966 $this->error = $facligne->error;
2967 $this->db->rollback();
2968 return -2;
2969 }
2970 } else {
2971 $this->db->rollback();
2972 return -3;
2973 }
2974 }
2975
2976 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2984 public function set_ref_client($ref_client, $notrigger = 0)
2985 {
2986 // phpcs:enable
2987 global $user;
2988
2989 $error = 0;
2990
2991 $this->db->begin();
2992
2993 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
2994 if (empty($ref_client)) {
2995 $sql .= " SET ref_client = NULL";
2996 } else {
2997 $sql .= " SET ref_client = '".$this->db->escape($ref_client)."'";
2998 }
2999 $sql .= " WHERE rowid = ".((int) $this->id);
3000
3001 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
3002 $resql = $this->db->query($sql);
3003 if (!$resql) {
3004 $this->errors[] = $this->db->error();
3005 $error++;
3006 }
3007
3008 if (!$error) {
3009 $this->ref_client = $ref_client; //deprecated
3010 $this->ref_customer = $ref_client;
3011 }
3012
3013 if (!$notrigger && empty($error)) {
3014 // Call trigger
3015 $result = $this->call_trigger('BILL_MODIFY', $user);
3016 if ($result < 0) {
3017 $error++;
3018 }
3019 // End call triggers
3020 }
3021
3022 if (!$error) {
3023 $this->ref_client = $ref_client; //deprecated
3024 $this->ref_customer = $ref_client;
3025
3026 $this->db->commit();
3027 return 1;
3028 } else {
3029 foreach ($this->errors as $errmsg) {
3030 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3031 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3032 }
3033 $this->db->rollback();
3034 return -1 * $error;
3035 }
3036 }
3037
3038 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3046 public function setInputReason($inputReasonId, $notrigger = 0)
3047 {
3048 // phpcs:enable
3049 global $user;
3050
3051 $error = 0;
3052
3053 dol_syslog(__METHOD__.' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3054 if ($this->status >= self::STATUS_DRAFT) {
3055 $this->oldcopy = dol_clone($this, 2);
3056 $this->demand_reason_id = $inputReasonId;
3057
3058 $this->db->begin();
3059
3060 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3061 $sql .= " SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId : 'null');
3062 $sql .= " WHERE rowid = ".((int) $this->id);
3063
3064 dol_syslog(__METHOD__, LOG_DEBUG);
3065 $res = $this->db->query($sql);
3066 if (!$res) {
3067 $error++;
3068 $this->error = $this->db->lasterror();
3069 $this->errors[] = $this->error;
3070 }
3071
3072 if (!$error) {
3073 if (!$notrigger) {
3074 // Call trigger
3075 $result = $this->call_trigger('BILL_MODIFY', $user);
3076 if ($result < 0) {
3077 $error++;
3078 }
3079 // End call triggers
3080 }
3081 }
3082
3083 if (!$error) {
3084 $this->db->commit();
3085 } else {
3086 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3087 $this->db->rollback();
3088 dol_syslog(__METHOD__.' Error : '.$this->errorsToString(), LOG_ERR);
3089 }
3090
3091 if (!$error) {
3092 return 1;
3093 } else {
3094 return -1;
3095 }
3096 }
3097
3098 return 0;
3099 }
3100
3109 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3110 {
3111 global $langs, $conf;
3112 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3113
3114 $rowid = $this->id;
3115
3116 dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
3117
3118 // Test to avoid invoice deletion (allowed if draft)
3119 $result = $this->is_erasable();
3120
3121 if ($result <= 0) {
3122 return 0;
3123 }
3124
3125 $error = 0;
3126
3127 $this->db->begin();
3128
3129 if (!$error && !$notrigger) {
3130 // Call trigger
3131 $result = $this->call_trigger('BILL_DELETE', $user);
3132 if ($result < 0) {
3133 $error++;
3134 }
3135 // End call triggers
3136 }
3137
3138 // Remove linked categories.
3139 if (!$error) {
3140 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_invoice";
3141 $sql .= " WHERE fk_invoice = ".((int) $this->id);
3142
3143 $result = $this->db->query($sql);
3144 if (!$result) {
3145 $error++;
3146 $this->errors[] = $this->db->lasterror();
3147 }
3148 }
3149
3150 // Removed extrafields
3151 if (!$error) {
3152 $result = $this->deleteExtraFields();
3153 if ($result < 0) {
3154 $error++;
3155 dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
3156 }
3157 }
3158
3159 if (!$error) {
3160 // Delete linked object
3161 $res = $this->deleteObjectLinked();
3162 if ($res < 0) {
3163 $error++;
3164 }
3165 }
3166
3167 if (!$error) {
3168 // If invoice was converted into a discount not yet consumed, we remove discount
3169 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
3170 $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
3171 $sql .= ' AND fk_facture_line IS NULL';
3172 $resql = $this->db->query($sql);
3173
3174 // If invoice has consumed discounts
3175 $this->fetch_lines();
3176 $list_rowid_det = array();
3177 foreach ($this->lines as $key => $invoiceline) {
3178 $list_rowid_det[] = $invoiceline->id;
3179 }
3180
3181 // Consumed discounts are freed
3182 if (count($list_rowid_det)) {
3183 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3184 $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
3185 $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
3186
3187 if (!$this->db->query($sql)) {
3188 $this->error = $this->db->error()." sql=".$sql;
3189 $this->errors[] = $this->error;
3190 $this->db->rollback();
3191 return -5;
3192 }
3193 }
3194
3195 // Remove other links to the deleted invoice
3196
3197 $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
3198 $sql .= ' SET fk_invoice = NULL';
3199 $sql .= ' WHERE fk_invoice = '.((int) $rowid);
3200
3201 if (!$this->db->query($sql)) {
3202 $this->error = $this->db->error()." sql=".$sql;
3203 $this->errors[] = $this->error;
3204 $this->db->rollback();
3205 return -5;
3206 }
3207
3208 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
3209 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
3210 $sql .= ' WHERE invoice_id = '.((int) $rowid);
3211
3212 if (!$this->db->query($sql)) {
3213 $this->error = $this->db->error()." sql=".$sql;
3214 $this->errors[] = $this->error;
3215 $this->db->rollback();
3216 return -5;
3217 }
3218
3219 // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
3220 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
3221 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3222 $langs->load("agenda");
3223
3224 $num = count($this->lines);
3225 for ($i = 0; $i < $num; $i++) {
3226 if ($this->lines[$i]->fk_product > 0) {
3227 $mouvP = new MouvementStock($this->db);
3228 $mouvP->origin = &$this;
3229 $mouvP->setOrigin($this->element, $this->id);
3230 // We decrease stock for product
3231 if ($this->type == self::TYPE_CREDIT_NOTE) {
3232 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
3233 } else {
3234 $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
3235 }
3236 }
3237 }
3238 }
3239
3240 // Invoice line extrafields
3241 $main = MAIN_DB_PREFIX.'facturedet';
3242 $ef = $main."_extrafields";
3243 $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
3244 // Delete invoice line
3245 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
3246
3247 if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact() >= 0) {
3248 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
3249
3250 $resql = $this->db->query($sql);
3251 if ($resql) {
3252 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
3253 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3254 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3255
3256 // On efface le repertoire de pdf provisoire
3257 $ref = dol_sanitizeFileName($this->ref);
3258 if ($conf->facture->dir_output && !empty($this->ref)) {
3259 $dir = $conf->facture->dir_output."/".$ref;
3260 $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
3261 if (file_exists($file)) { // We must delete all files before deleting directory
3262 $ret = dol_delete_preview($this);
3263
3264 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
3265 $langs->load("errors");
3266 $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
3267 $this->errors[] = $this->error;
3268 $this->db->rollback();
3269 return 0;
3270 }
3271 }
3272 if (file_exists($dir)) {
3273 if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
3274 $langs->load("errors");
3275 $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
3276 $this->errors[] = $this->error;
3277 $this->db->rollback();
3278 return 0;
3279 }
3280 }
3281 }
3282
3283 $this->db->commit();
3284 return 1;
3285 } else {
3286 $this->error = $this->db->lasterror()." sql=".$sql;
3287 $this->errors[] = $this->error;
3288 $this->db->rollback();
3289 return -6;
3290 }
3291 } else {
3292 $this->error = $this->db->lasterror()." sql=".$sql;
3293 $this->errors[] = $this->error;
3294 $this->db->rollback();
3295 return -4;
3296 }
3297 } else {
3298 $this->db->rollback();
3299 return -2;
3300 }
3301 }
3302
3303 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3315 public function set_paid($user, $close_code = '', $close_note = '')
3316 {
3317 // phpcs:enable
3318 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3319 return $this->setPaid($user, $close_code, $close_note);
3320 }
3321
3332 public function setPaid($user, $close_code = '', $close_note = '')
3333 {
3334 $error = 0;
3335
3336 if ($this->paye != 1 || $this->status != self::STATUS_CLOSED) {
3337 $this->db->begin();
3338
3339 $now = dol_now();
3340
3341 dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
3342
3343 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3344 $sql .= ' fk_statut = '.self::STATUS_CLOSED;
3345 if (!$close_code) {
3346 $sql .= ', paye = 1';
3347 }
3348 if ($close_code) {
3349 $sql .= ", close_code = '".$this->db->escape($close_code)."'";
3350 }
3351 if ($close_note) {
3352 $sql .= ", close_note = '".$this->db->escape($close_note)."'";
3353 }
3354 $sql .= ', fk_user_closing = '.((int) $user->id);
3355 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3356 $sql .= " WHERE rowid = ".((int) $this->id);
3357
3358 $resql = $this->db->query($sql);
3359 if ($resql) {
3360 // Call trigger
3361 $result = $this->call_trigger('BILL_PAYED', $user);
3362 if ($result < 0) {
3363 $error++;
3364 }
3365 // End call triggers
3366 } else {
3367 $error++;
3368 $this->error = $this->db->lasterror();
3369 }
3370
3371 if (!$error) {
3372 $this->paye = 1;
3373 $this->status = self::STATUS_CLOSED;
3374 $this->db->commit();
3375 return 1;
3376 } else {
3377 $this->db->rollback();
3378 return -1;
3379 }
3380 } else {
3381 return 0;
3382 }
3383 }
3384
3385
3386 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3397 public function set_unpaid($user)
3398 {
3399 // phpcs:enable
3400 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3401 return $this->setUnpaid($user);
3402 }
3403
3412 public function setUnpaid($user)
3413 {
3414 $error = 0;
3415
3416 $this->db->begin();
3417
3418 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3419 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
3420 $sql .= ' date_closing=null,';
3421 $sql .= ' fk_user_closing=null';
3422 $sql .= " WHERE rowid = ".((int) $this->id);
3423
3424 dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
3425 $resql = $this->db->query($sql);
3426 if ($resql) {
3427 // Call trigger
3428 $result = $this->call_trigger('BILL_UNPAYED', $user);
3429 if ($result < 0) {
3430 $error++;
3431 }
3432 // End call triggers
3433 } else {
3434 $error++;
3435 $this->error = $this->db->error();
3436 dol_print_error($this->db);
3437 }
3438
3439 if (!$error) {
3440 $this->db->commit();
3441 return 1;
3442 } else {
3443 $this->db->rollback();
3444 return -1;
3445 }
3446 }
3447
3448
3449 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3462 public function set_canceled($user, $close_code = '', $close_note = '')
3463 {
3464 // phpcs:enable
3465 dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3466 return $this->setCanceled($user, $close_code, $close_note);
3467 }
3468
3479 public function setCanceled($user, $close_code = '', $close_note = '')
3480 {
3481 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
3482
3483 $this->db->begin();
3484 $now = dol_now();
3485
3486 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3487 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
3488 if ($close_code) {
3489 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3490 }
3491 if ($close_note) {
3492 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3493 }
3494 $sql .= ', fk_user_closing = '.((int) $user->id);
3495 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3496 $sql .= " WHERE rowid = ".((int) $this->id);
3497
3498 $resql = $this->db->query($sql);
3499 if ($resql) {
3500 // Bound discounts are deducted from the invoice
3501 // as they have not been used since the invoice is abandoned.
3502 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3503 $sql .= ' SET fk_facture = NULL';
3504 $sql .= ' WHERE fk_facture = '.((int) $this->id);
3505
3506 $resql = $this->db->query($sql);
3507 if ($resql) {
3508 // Call trigger
3509 $result = $this->call_trigger('BILL_CANCEL', $user);
3510 if ($result < 0) {
3511 $this->db->rollback();
3512 return -1;
3513 }
3514 // End call triggers
3515
3516 $this->db->commit();
3517 return 1;
3518 } else {
3519 $this->error = $this->db->error()." sql=".$sql;
3520 $this->db->rollback();
3521 return -1;
3522 }
3523 } else {
3524 $this->error = $this->db->error()." sql=".$sql;
3525 $this->db->rollback();
3526 return -2;
3527 }
3528 }
3529
3542 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3543 {
3544 global $conf, $langs, $mysoc;
3545 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3546
3547 $productStatic = null;
3548 $warehouseStatic = null;
3549 $productbatch = null;
3550 if ($batch_rule > 0) {
3551 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3552 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3553 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3554 $productStatic = new Product($this->db);
3555 $warehouseStatic = new Entrepot($this->db);
3556 $productbatch = new Productbatch($this->db);
3557 }
3558
3559 $now = dol_now();
3560
3561 $error = 0;
3562 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3563
3564 // Force to have object complete for checks
3565 $this->fetch_thirdparty();
3566 $this->fetch_lines();
3567
3568 // Check parameters
3569 if ($this->status != self::STATUS_DRAFT) {
3570 dol_syslog(get_class($this)."::validate Current status is not draft. operation canceled.", LOG_WARNING);
3571 return 0;
3572 }
3573 if (count($this->lines) <= 0) {
3574 $langs->load("errors");
3575 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3576 return -1;
3577 }
3578 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'creer'))
3579 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'invoice_advance', 'validate'))) {
3580 $this->error = 'Permission denied';
3581 dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS=' . getDolGlobalString('MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3582 return -1;
3583 }
3584 if ((preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) && // empty should not happened, but when it occurs, the test save life
3585 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
3586 ) {
3587 $this->date = dol_now();
3588 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3589 }
3590 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
3591 $last_of_type = $this->willBeLastOfSameType(true);
3592 if (!$last_of_type[0]) {
3593 $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3594 return -1;
3595 }
3596 }
3597
3598 // Check for mandatory fields in thirdparty (defined into setup)
3599 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3600 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER');
3601 foreach ($array_to_check as $key) {
3602 $keymin = strtolower($key);
3603 if (!property_exists($this->thirdparty, $keymin)) {
3604 continue;
3605 }
3606 $vallabel = $this->thirdparty->$keymin;
3607
3608 $i = (int) preg_replace('/[^0-9]/', '', $key);
3609 if ($i > 0) {
3610 if ($this->thirdparty->isACompany()) {
3611 // Check for mandatory prof id (but only if country is other than ours)
3612 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3613 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3614 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
3615 $langs->load("errors");
3616 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3617 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3618 return -1;
3619 }
3620 }
3621 }
3622 } else {
3623 if ($key == 'EMAIL') {
3624 // Check for mandatory
3625 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
3626 $langs->load("errors");
3627 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3628 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3629 return -1;
3630 }
3631 }
3632 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3633 // Check for mandatory
3634 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3635 $langs->load("errors");
3636 $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3637 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3638 return -1;
3639 }
3640 }
3641 if ($key == 'TVA_INTRA') {
3642 // Check for mandatory vat number
3643 if (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') == 'eeconly') {
3644 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3645 $langs->load("errors");
3646 $this->error = $langs->trans('ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3647 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3648 return -1;
3649 }
3650 } elseif (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3651 $langs->load("errors");
3652 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3653 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3654 return -1;
3655 }
3656 }
3657 }
3658 }
3659 }
3660
3661 // Check for mandatory fields in $this
3662 $array_to_check = array('REF_CLIENT' => 'RefCustomer');
3663 foreach ($array_to_check as $key => $val) {
3664 $keymin = strtolower($key);
3665 $vallabel = $this->$keymin;
3666
3667 // Check for mandatory
3668 $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3669 if (!$vallabel && getDolGlobalString($keymandatory)) {
3670 $langs->load("errors");
3671 $error++;
3672 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3673 }
3674 }
3675
3676 $this->db->begin();
3677
3678 // Check parameters
3679 if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3680 // Check that source invoice is known
3681 if ($this->fk_facture_source <= 0) {
3682 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3683 $this->db->rollback();
3684 return -10;
3685 }
3686
3687 // Load source invoice that has been replaced
3688 $facreplaced = new Facture($this->db);
3689 $result = $facreplaced->fetch($this->fk_facture_source);
3690 if ($result <= 0) {
3691 $this->error = $langs->trans("ErrorBadInvoice");
3692 $this->db->rollback();
3693 return -11;
3694 }
3695
3696 // Check that source invoice not already replaced by another one.
3697 $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3698 if ($idreplacement && $idreplacement != $this->id) {
3699 $facreplacement = new Facture($this->db);
3700 $facreplacement->fetch($idreplacement);
3701 $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3702 $this->db->rollback();
3703 return -12;
3704 }
3705
3706 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3707 if ($result < 0) {
3708 $this->error = $facreplaced->error;
3709 $this->db->rollback();
3710 return -13;
3711 }
3712 }
3713
3714 // Define new ref
3715 if ($force_number) {
3716 $num = $force_number;
3717 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3718 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3719 $this->date = dol_now();
3720 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3721 }
3722 $num = $this->getNextNumRef($this->thirdparty);
3723 } else {
3724 $num = (string) $this->ref;
3725 }
3726
3727 if (!$num) {
3728 $error++;
3729 } else {
3730 $this->oldref = $this->ref;
3731 $this->newref = dol_sanitizeFileName($num);
3732 }
3733
3734 if (!$error) {
3735 $this->update_price(1);
3736
3737 // Validate
3738 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3739 $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)."'";
3740 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3741 $sql .= ", datef='".$this->db->idate($this->date)."'";
3742 $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3743 }
3744 $sql .= " WHERE rowid = ".((int) $this->id);
3745
3746 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3747 $resql = $this->db->query($sql);
3748 if (!$resql) {
3749 $this->error = $this->db->lasterror();
3750 $error++;
3751 }
3752 }
3753
3754 if (!$error) {
3755 // Define third party as a customer
3756 $result = $this->thirdparty->setAsCustomer();
3757
3758 // If active (STOCK_CALCULATE_ON_BILL), we decrement the main product and its components at invoice validation
3759 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3760 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3761 $langs->load("agenda");
3762
3763 // Loop on each line
3764 $cpt = count($this->lines);
3765 for ($i = 0; $i < $cpt; $i++) {
3766 if ($this->lines[$i]->fk_product > 0) {
3767 $mouvP = new MouvementStock($this->db);
3768 $mouvP->origin = &$this; // deprecated
3769 $mouvP->setOrigin($this->element, $this->id);
3770
3771 // We decrease stock for product
3772 if ($this->type == self::TYPE_CREDIT_NOTE) {
3773 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3774 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3775 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num), '', '', $this->lines[$i]->batch);
3776 if ($result < 0) {
3777 $error++;
3778 $this->setErrorsFromObject($mouvP);
3779 }
3780 } else {
3781 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3782 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3783
3784 $is_batch_line = false;
3785 if ($batch_rule > 0) {
3786 $productStatic->fetch($this->lines[$i]->fk_product);
3787 if ($productStatic->hasbatch() && is_object($productbatch)) {
3788 $is_batch_line = true;
3789 $product_qty_remain = $this->lines[$i]->qty;
3790
3791 $sortfield = '';
3792 $sortorder = '';
3793 // find lot/serial by sellby (DLC) and eatby dates (DLUO) first
3795 $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3796 $sortorder = 'ASC,ASC,ASC,ASC';
3797 }
3798
3799 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 : null), $sortfield, $sortorder);
3800 if (!is_array($resBatchList)) {
3801 $error++;
3802 $this->error = $this->db->lasterror();
3803 }
3804
3805 if (!$error) {
3806 $batchList = $resBatchList;
3807 if (empty($batchList)) {
3808 $error++;
3809 $langs->load('errors');
3810 $warehouseStatic->fetch($idwarehouse);
3811 $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3812 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3813 }
3814
3815 foreach ($batchList as $batch) {
3816 if ($batch->qty <= 0) {
3817 continue; // try to decrement only batches have positive quantity first
3818 }
3819
3820 // enough quantity in this batch
3821 if ($batch->qty >= $product_qty_remain) {
3822 $product_batch_qty = $product_qty_remain;
3823 } else {
3824 // not enough (take all in batch)
3825 $product_batch_qty = $batch->qty;
3826 }
3827 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3828 if ($result < 0) {
3829 $error++;
3830 $this->setErrorsFromObject($mouvP);
3831 break;
3832 }
3833
3834 $product_qty_remain -= $product_batch_qty;
3835 // all product quantity was decremented
3836 if ($product_qty_remain <= 0) {
3837 break;
3838 }
3839 }
3840
3841 if (!$error && $product_qty_remain > 0) {
3842 if (getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER')) {
3843 $error++;
3844 $langs->load('errors');
3845 $warehouseStatic->fetch($idwarehouse);
3846 $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3847 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3848 } else {
3849 // take in the first batch
3850 $batch = $batchList[0];
3851 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3852 if ($result < 0) {
3853 $error++;
3854 $this->setErrorsFromObject($mouvP);
3855 }
3856 }
3857 }
3858 }
3859 }
3860 }
3861
3862 if (!$is_batch_line) { // If stock move not yet processed
3863 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3864 if ($result < 0) {
3865 $error++;
3866 $this->setErrorsFromObject($mouvP);
3867 }
3868 }
3869 }
3870 }
3871 }
3872 }
3873
3874 /*
3875 * 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%)
3876 * So we can continue to create new invoice situation
3877 */
3878 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3879 $invoice_situation = new Facture($this->db);
3880 $result = $invoice_situation->fetch($this->fk_facture_source);
3881 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3882 $invoice_situation->situation_final = 0;
3883 // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3884 $result = $invoice_situation->setFinal($user, 1);
3885 }
3886 if ($result < 0) {
3887 $this->error = $invoice_situation->error;
3888 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3889 $error++;
3890 }
3891 }
3892
3893 // Trigger calls
3894 if (!$error && !$notrigger) {
3895 // Call trigger
3896 $result = $this->call_trigger('BILL_VALIDATE', $user);
3897 if ($result < 0) {
3898 $error++;
3899 }
3900 // End call triggers
3901 }
3902
3903 if (!$error) {
3904 // Rename directory in index entry if dir was a temporary ref
3905 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
3906 // Now we rename also files into index
3907 $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)."'";
3908 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".(int) $conf->entity;
3909 $resql = $this->db->query($sql);
3910 if (!$resql) {
3911 $error++;
3912 $this->error = $this->db->lasterror();
3913 }
3914 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'facture/".$this->db->escape($this->newref)."'";
3915 $sql .= " WHERE filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".(int) $conf->entity;
3916 $resql = $this->db->query($sql);
3917 if (!$resql) {
3918 $error++;
3919 $this->error = $this->db->lasterror();
3920 }
3921 }
3922 }
3923
3924 if (!$error && !$this->is_last_in_cycle()) {
3925 $resupdatenext = $this->updatePriceNextInvoice($langs);
3926 if (!$resupdatenext) {
3927 $error++;
3928 }
3929 }
3930
3931 // Set new ref and define current status
3932 if (!$error) {
3933 $this->ref = $num;
3934 $this->statut = self::STATUS_VALIDATED; // deprecated
3936 $this->date_validation = $now;
3937 $i = 0;
3938
3939 if (getDolGlobalInt('INVOICE_USE_SITUATION')) {
3940 $final = true;
3941 $nboflines = count($this->lines);
3942 while (($i < $nboflines) && $final) {
3943 $line = $this->lines[$i];
3944 '@phan-var-force FactureLigne $line';
3945 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3946 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3947 $current_progress = (float) $line->situation_percent;
3948 $full_progress = $previousprogress + $current_progress;
3949 $final = ($full_progress == 100);
3950 } else {
3951 $final = ($line->situation_percent == 100);
3952 }
3953 $i++;
3954 }
3955
3956 if (!$final) {
3957 if ($this->situation_final) {
3958 // If we must change situation_final
3959 $this->situation_final = 0;
3960 $this->setFinal($user, 1); // Trigger is disabled, already run by the validate
3961 }
3962 } else {
3963 if (!$this->situation_final) {
3964 // If we must change situation_final
3965 $this->situation_final = 1;
3966 $this->setFinal($user, 1); // Trigger is disabled, already run by the validate
3967 }
3968 }
3969 }
3970 }
3971 }
3972
3973 // All database actions are now complete
3974 // We rename the directory and files on disk if old dir was a temporary ref.
3975 if (!$error && preg_match('/^[\‍(]?PROV/i', $this->oldref)) {
3976 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
3977 $oldref = dol_sanitizeFileName($this->oldref);
3978 $newref = dol_sanitizeFileName($num);
3979 $dirsource = $conf->facture->dir_output.'/'.$oldref;
3980 $dirdest = $conf->facture->dir_output.'/'.$newref;
3981 if (!$error && file_exists($dirsource)) {
3982 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
3983
3984 if (@rename($dirsource, $dirdest)) {
3985 dol_syslog("Rename ok");
3986 // Rename also docs starting with $oldref with $newref
3987 $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
3988 foreach ($listoffiles as $fileentry) {
3989 $dirsource = $fileentry['name'];
3990 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
3991 $dirsource = $fileentry['path'].'/'.$dirsource;
3992 $dirdest = $fileentry['path'].'/'.$dirdest;
3993 @rename($dirsource, $dirdest);
3994 }
3995 }
3996 }
3997 }
3998
3999 if (!$error) {
4000 $this->db->commit();
4001 return 1;
4002 } else {
4003 $this->db->rollback();
4004 return -1;
4005 }
4006 }
4007
4014 public function updatePriceNextInvoice(&$langs)
4015 {
4016 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4017 $is_last = $next_invoice->is_last_in_cycle();
4018
4019 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4020 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4021 return false;
4022 }
4023
4024 foreach ($next_invoice->lines as $line) {
4025 '@phan-var-force FactureLigne $line';
4026 $result = $next_invoice->updateline(
4027 $line->id,
4028 $line->desc,
4029 $line->subprice,
4030 $line->qty,
4031 $line->remise_percent,
4032 $line->date_start,
4033 $line->date_end,
4034 $line->tva_tx,
4035 $line->localtax1_tx,
4036 $line->localtax2_tx,
4037 'HT',
4038 $line->info_bits,
4039 $line->product_type,
4040 $line->fk_parent_line,
4041 0,
4042 $line->fk_fournprice,
4043 $line->pa_ht,
4044 $line->label,
4045 $line->special_code,
4046 $line->array_options,
4047 $line->situation_percent,
4048 $line->fk_unit
4049 );
4050
4051 if ($result < 0) {
4052 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4053 return false;
4054 }
4055 }
4056
4057 break; // Only the next invoice and not each next invoice
4058 }
4059
4060 return true;
4061 }
4062
4070 public function setDraft($user, $idwarehouse = -1)
4071 {
4072 // phpcs:enable
4073 global $langs;
4074
4075 $error = 0;
4076
4077 if ($this->status == self::STATUS_DRAFT) {
4078 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
4079 return 0;
4080 }
4081
4082 dol_syslog(__METHOD__, LOG_DEBUG);
4083
4084 $this->db->begin();
4085
4086 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4087 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
4088 $sql .= " WHERE rowid = ".((int) $this->id);
4089
4090 $result = $this->db->query($sql);
4091 if ($result) {
4092 if (!$error) {
4093 $this->oldcopy = clone $this;
4094 }
4095
4096 // If we decrease stock on invoice validation, we increase back
4097 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
4098 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
4099 $langs->load("agenda");
4100
4101 $num = count($this->lines);
4102 for ($i = 0; $i < $num; $i++) {
4103 if ($this->lines[$i]->fk_product > 0) {
4104 $mouvP = new MouvementStock($this->db);
4105 $mouvP->origin = &$this;
4106 $mouvP->setOrigin($this->element, $this->id);
4107 // We decrease stock for product
4108 if ($this->type == self::TYPE_CREDIT_NOTE) {
4109 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
4110 } else {
4111 $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
4112 }
4113 }
4114 }
4115 }
4116
4117 if ($error == 0) {
4118 $old_statut = $this->status;
4119 $this->statut = self::STATUS_DRAFT; // deprecated
4120 $this->status = self::STATUS_DRAFT;
4121
4122 // Call trigger
4123 $result = $this->call_trigger('BILL_UNVALIDATE', $user);
4124 if ($result < 0) {
4125 $error++;
4126 $this->statut = $old_statut; // deprecated
4127 $this->status = $old_statut;
4128 }
4129 // End call triggers
4130 } else {
4131 $this->db->rollback();
4132 return -1;
4133 }
4134
4135 if ($error == 0) {
4136 $this->db->commit();
4137 return 1;
4138 } else {
4139 $this->db->rollback();
4140 return -1;
4141 }
4142 } else {
4143 $this->error = $this->db->error();
4144 $this->db->rollback();
4145 return -1;
4146 }
4147 }
4148
4149
4191 public function addline(
4192 $desc,
4193 $pu_ht,
4194 $qty,
4195 $txtva,
4196 $txlocaltax1 = 0,
4197 $txlocaltax2 = 0,
4198 $fk_product = 0,
4199 $remise_percent = 0,
4200 $date_start = '',
4201 $date_end = '',
4202 $fk_code_ventilation = 0,
4203 $info_bits = 0,
4204 $fk_remise_except = 0,
4205 $price_base_type = 'HT',
4206 $pu_ttc = 0,
4207 $type = 0,
4208 $rang = -1,
4209 $special_code = 0,
4210 $origin = '',
4211 $origin_id = 0,
4212 $fk_parent_line = 0,
4213 $fk_fournprice = null,
4214 $pa_ht = 0,
4215 $label = '',
4216 $array_options = array(),
4217 $situation_percent = 100,
4218 $fk_prev_id = 0,
4219 $fk_unit = null,
4220 $pu_ht_devise = 0,
4221 $ref_ext = '',
4222 $noupdateafterinsertline = 0
4223 ) {
4224 // Deprecation warning
4225 if ($label) {
4226 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4227 //var_dump(getCallerInfoString());exit;
4228 }
4229
4230 global $mysoc, $langs;
4231
4232 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);
4233
4234 if ($this->status == self::STATUS_DRAFT) {
4235 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4236
4237 // Clean parameters
4238 if (empty($remise_percent)) {
4239 $remise_percent = 0;
4240 }
4241 if (empty($qty)) {
4242 $qty = 0;
4243 }
4244 if (empty($info_bits)) {
4245 $info_bits = 0;
4246 }
4247 if (empty($rang)) {
4248 $rang = 0;
4249 }
4250 if (empty($fk_code_ventilation)) {
4251 $fk_code_ventilation = 0;
4252 }
4253 if (empty($txtva)) {
4254 $txtva = 0;
4255 }
4256 if (empty($txlocaltax1)) {
4257 $txlocaltax1 = 0;
4258 }
4259 if (empty($txlocaltax2)) {
4260 $txlocaltax2 = 0;
4261 }
4262 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4263 $fk_parent_line = 0;
4264 }
4265 if (empty($fk_prev_id)) {
4266 $fk_prev_id = 'null';
4267 }
4268
4269 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
4270 // 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.
4271 if ($this->isSituationInvoice() && getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4272 $situation_percent = 0;
4273 } else {
4274 $situation_percent = 100;
4275 }
4276 }
4277
4278 if (empty($ref_ext)) {
4279 $ref_ext = '';
4280 }
4281
4282 $remise_percent = (float) price2num($remise_percent);
4283
4284 $qty = (float) price2num($qty);
4285 $pu_ht = (float) price2num($pu_ht);
4286 $pu_ht_devise = (float) price2num($pu_ht_devise);
4287 $pu_ttc = (float) price2num($pu_ttc);
4288 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4289 if (strpos((string) $txtva, '*') !== false) {
4290 $info_bits |= 1;
4291 }
4292 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4293 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4294 }
4295 $txlocaltax1 = (float) price2num($txlocaltax1);
4296 $txlocaltax2 = (float) price2num($txlocaltax2);
4297
4298 if ($price_base_type == 'HT') {
4299 $pu = $pu_ht;
4300 } else {
4301 $pu = $pu_ttc;
4302 }
4303
4304 // Check parameters
4305 if ($type < 0) {
4306 return -1;
4307 }
4308
4309 if ($date_start && $date_end && $date_start > $date_end) {
4310 $langs->load("errors");
4311 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4312 return -1;
4313 }
4314
4315 $this->db->begin();
4316
4317 $product_type = $type;
4318 if (!empty($fk_product) && $fk_product > 0) {
4319 $product = new Product($this->db);
4320 $result = $product->fetch($fk_product);
4321 $product_type = $product->type;
4322
4323 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4324 // get real stock
4325 $productChildrenNb = 0;
4326 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
4327 $productChildrenNb = $product->hasFatherOrChild(1);
4328 }
4329 if ($productChildrenNb > 0) {
4330 // compute real stock from each subcomponent
4331 $product_stock = null;
4332 $product->loadStockForVirtualProduct('warehouseopen', $qty);
4333 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4334 if ($product_stock === null) {
4335 $product_stock = $componentStockWarehouse->real;
4336 } else {
4337 $product_stock = min($product_stock, $componentStockWarehouse->real);
4338 }
4339 }
4340 if ($product_stock === null) {
4341 $product_stock = 0;
4342 }
4343 } else {
4344 $product_stock = $product->stock_reel;
4345 }
4346
4347 if ($product_stock < $qty) {
4348 $langs->load("errors");
4349 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4350 $this->db->rollback();
4351 return -3;
4352 }
4353 }
4354
4355 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
4356 $tmpproduct = new Product($this->db);
4357 $result = $tmpproduct->fetch($fk_product);
4358 if (abs((float) $qty) < $tmpproduct->packaging) {
4359 $qty = (float) $tmpproduct->packaging;
4360 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
4361 } else {
4362 if (!empty($tmpproduct->packaging) && (float) price2num(fmod((float) $qty, (float) $tmpproduct->packaging), 'MS')) {
4363 $coeff = intval(abs((float) $qty) / $tmpproduct->packaging) + 1;
4364 $qty = price2num((float) $tmpproduct->packaging * $coeff, 'MS');
4365 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
4366 }
4367 }
4368 }
4369 }
4370
4371 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4372
4373 // Clean vat code
4374 $reg = array();
4375 $vat_src_code = '';
4376 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4377 $vat_src_code = $reg[1];
4378 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4379 }
4380
4381 // Calcul du total TTC et de la TVA pour la ligne a partir de
4382 // qty, pu, remise_percent et txtva
4383 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
4384 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
4385
4386 $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);
4387
4388 $total_ht = $tabprice[0];
4389 $total_tva = $tabprice[1];
4390 $total_ttc = $tabprice[2];
4391 $total_localtax1 = $tabprice[9];
4392 $total_localtax2 = $tabprice[10];
4393 $pu_ht = $tabprice[3];
4394
4395 // MultiCurrency
4396 $multicurrency_total_ht = $tabprice[16];
4397 $multicurrency_total_tva = $tabprice[17];
4398 $multicurrency_total_ttc = $tabprice[18];
4399 $pu_ht_devise = $tabprice[19];
4400
4401 // Rank to use
4402 $ranktouse = $rang;
4403 if (empty($ranktouse) || $ranktouse == -1) {
4404 $rangmax = $this->line_max($fk_parent_line);
4405 $ranktouse = $rangmax + 1;
4406 }
4407
4408 // Insert line
4409 $this->line = new FactureLigne($this->db);
4410
4411 $this->line->context = $this->context;
4412
4413 $this->line->fk_facture = $this->id;
4414 $this->line->label = $label; // deprecated
4415 $this->line->desc = $desc;
4416 $this->line->ref_ext = $ref_ext;
4417
4418 $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
4419 $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
4420
4421 $this->line->vat_src_code = $vat_src_code;
4422 $this->line->tva_tx = $txtva;
4423 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4424 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4425 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4426 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4427
4428 $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
4429 $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
4430 $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
4431 $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
4432 $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
4433
4434 $this->line->fk_product = $fk_product;
4435 $this->line->product_type = $product_type;
4436 $this->line->remise_percent = $remise_percent;
4437 $this->line->date_start = $date_start;
4438 $this->line->date_end = $date_end;
4439 $this->line->fk_code_ventilation = $fk_code_ventilation;
4440 $this->line->rang = $ranktouse;
4441 $this->line->info_bits = $info_bits;
4442 $this->line->fk_remise_except = $fk_remise_except;
4443
4444 $this->line->special_code = $special_code;
4445 $this->line->fk_parent_line = $fk_parent_line;
4446 $this->line->origin = $origin;
4447 $this->line->origin_id = $origin_id;
4448 $this->line->situation_percent = $situation_percent;
4449 $this->line->fk_prev_id = $fk_prev_id;
4450 $this->line->fk_unit = $fk_unit;
4451
4452 // infos margin
4453 $this->line->fk_fournprice = $fk_fournprice;
4454 $this->line->pa_ht = $pa_ht;
4455
4456 // Multicurrency
4457 $this->line->fk_multicurrency = $this->fk_multicurrency;
4458 $this->line->multicurrency_code = $this->multicurrency_code;
4459 $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
4460
4461 $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
4462 $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
4463 $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
4464
4465 if (is_array($array_options) && count($array_options) > 0) {
4466 $this->line->array_options = $array_options;
4467 }
4468
4469 $result = $this->line->insert();
4470 if ($result > 0) {
4471 // Update denormalized fields at the order level
4472 if (empty($noupdateafterinsertline)) {
4473 $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.
4474 }
4475
4476 if (!isset($this->context['createfromclone'])) {
4477 if (!empty($fk_parent_line)) {
4478 // Always reorder if child line
4479 $this->line_order(true, 'DESC');
4480 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4481 // Update all rank of all other lines starting from the same $ranktouse
4482 $linecount = count($this->lines);
4483 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4484 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
4485 }
4486 }
4487
4488 $this->lines[] = $this->line;
4489 } else {
4490 foreach ($this->lines as $line) {
4491 if ($line->id == $origin_id) {
4492 $this->line->extraparams = $line->extraparams;
4493 $this->line->setExtraParameters();
4494 }
4495 }
4496 }
4497
4498 if ($result > 0) {
4499 $this->db->commit();
4500 return $this->line->id;
4501 } else {
4502 $this->error = $this->db->lasterror();
4503 $this->db->rollback();
4504 return -1;
4505 }
4506 } else {
4507 $this->error = $this->line->error;
4508 $this->errors = $this->line->errors;
4509 $this->db->rollback();
4510 return -2;
4511 }
4512 } else {
4513 $this->errors[] = 'status of invoice must be Draft to allow use of ->addline()';
4514 dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4515 return -3;
4516 }
4517 }
4518
4550 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)
4551 {
4552 global $user;
4553
4554 // Deprecation warning
4555 if ($label) {
4556 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4557 }
4558
4559 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4560
4561 global $mysoc, $langs;
4562
4563 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);
4564
4565 if ($this->status == self::STATUS_DRAFT) {
4566 if (!$this->is_last_in_cycle() && empty($this->error)) {
4567 if (!$this->checkProgressLine($rowid, $situation_percent)) {
4568 if (!$this->error) {
4569 $this->error = $langs->trans('invoiceLineProgressError');
4570 }
4571 return -3;
4572 }
4573 }
4574
4575 if ($date_start && $date_end && $date_start > $date_end) {
4576 $langs->load("errors");
4577 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4578 return -1;
4579 }
4580
4581 $this->db->begin();
4582
4583 // Clean parameters
4584 if (empty($qty)) {
4585 $qty = 0;
4586 }
4587 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4588 $fk_parent_line = 0;
4589 }
4590 if (empty($special_code) || $special_code == 3) {
4591 $special_code = 0;
4592 }
4593 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '' || $situation_percent == null) {
4594 // INVOICE_USE_SITUATION = 2 - If there is no progress on a line, percent must not be 100% (No cumulative)
4595 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalInt('INVOICE_USE_SITUATION') == 2 && (int) $situation_percent < 100) {
4596 $situation_percent = 0;
4597 } else {
4598 $situation_percent = 100;
4599 }
4600 }
4601 if (empty($ref_ext)) {
4602 $ref_ext = '';
4603 }
4604
4605 $remise_percent = (float) price2num($remise_percent);
4606
4607 $qty = (float) price2num($qty);
4608 $pu = (float) price2num($pu);
4609 $pu_ht_devise = (float) price2num($pu_ht_devise);
4610 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4611
4612 if (strpos((string) $txtva, '*') !== false) {
4613 $info_bits |= 1;
4614 }
4615 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4616 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4617 }
4618 $txlocaltax1 = (float) price2num($txlocaltax1);
4619 $txlocaltax2 = (float) price2num($txlocaltax2);
4620
4621 // Check parameters
4622 if ($type < 0) {
4623 return -1;
4624 }
4625
4626 // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
4627 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
4628 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
4629
4630 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4631
4632 // Clean vat code
4633 $reg = array();
4634 $vat_src_code = '';
4635 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4636 $vat_src_code = $reg[1];
4637 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4638 }
4639
4640 $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);
4641
4642 $total_ht = $tabprice[0];
4643 $total_tva = $tabprice[1];
4644 $total_ttc = $tabprice[2];
4645 $total_localtax1 = $tabprice[9];
4646 $total_localtax2 = $tabprice[10];
4647 $pu_ht = $tabprice[3];
4648 $pu_tva = $tabprice[4];
4649 $pu_ttc = $tabprice[5];
4650
4651 // MultiCurrency
4652 $multicurrency_total_ht = $tabprice[16];
4653 $multicurrency_total_tva = $tabprice[17];
4654 $multicurrency_total_ttc = $tabprice[18];
4655 $pu_ht_devise = $tabprice[19];
4656
4657 // Old properties: $price, $remise (deprecated)
4658 $price = $pu;
4659 $remise = 0;
4660 if ($remise_percent > 0) {
4661 $remise = round(((float) $pu * (float) $remise_percent / 100), 2);
4662 $price = ((float) $pu - $remise);
4663 }
4664 $price = price2num($price);
4665
4666 // Fetch current line from the database and then clone the object and set it in $oldline property
4667 $line = new FactureLigne($this->db);
4668 $line->fetch($rowid);
4669 $line->fetch_optionals();
4670
4671 if (!empty($line->fk_product)) {
4672 $product = new Product($this->db);
4673 $result = $product->fetch($line->fk_product);
4674 $product_type = $product->type;
4675
4676 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4677 // get real stock
4678 $productChildrenNb = 0;
4679 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
4680 $productChildrenNb = $product->hasFatherOrChild(1);
4681 }
4682 if ($productChildrenNb > 0) {
4683 // compute real stock from each subcomponent
4684 $product_stock = null;
4685 $product->loadStockForVirtualProduct('warehouseopen', $qty);
4686 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4687 if ($product_stock === null) {
4688 $product_stock = $componentStockWarehouse->real;
4689 } else {
4690 $product_stock = min($product_stock, $componentStockWarehouse->real);
4691 }
4692 }
4693 if ($product_stock === null) {
4694 $product_stock = 0;
4695 }
4696 } else {
4697 $product_stock = $product->stock_reel;
4698 }
4699
4700 if ($product_stock < $qty) {
4701 $langs->load("errors");
4702 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', (string) $product->ref);
4703 $this->db->rollback();
4704 return -3;
4705 }
4706 }
4707 }
4708
4709 $staticline = clone $line;
4710
4711 $line->oldline = $staticline;
4712 $this->line = $line;
4713 $this->line->context = $this->context;
4714 $this->line->rang = $rang;
4715
4716 // Reorder if fk_parent_line change
4717 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4718 $rangmax = $this->line_max($fk_parent_line);
4719 $this->line->rang = $rangmax + 1;
4720 }
4721 $apply_abs_price_on_credit_note = false;
4722 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
4723 $apply_abs_price_on_credit_note = true;
4724 }
4725
4726
4727 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
4728 if ($qty < $this->line->packaging) {
4729 $qty = $this->line->packaging;
4730 setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'warnings');
4731 } else {
4732 if (!empty($this->line->packaging)
4733 && is_numeric($this->line->packaging)
4734 && (float) $this->line->packaging > 0
4735 && (float) price2num(fmod((float) $qty, (float) $this->line->packaging), 'MS')) {
4736 $coeff = intval($qty / $this->line->packaging) + 1;
4737 $qty = $this->line->packaging * $coeff;
4738 setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'warnings');
4739 }
4740 }
4741 }
4742
4743 $this->line->id = $rowid;
4744 $this->line->rowid = $rowid;
4745 $this->line->label = $label;
4746 $this->line->desc = $desc;
4747 $this->line->ref_ext = $ref_ext;
4748 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
4749
4750 $this->line->vat_src_code = $vat_src_code;
4751 $this->line->tva_tx = $txtva;
4752 $this->line->localtax1_tx = $txlocaltax1;
4753 $this->line->localtax2_tx = $txlocaltax2;
4754 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4755 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4756
4757 $this->line->remise_percent = $remise_percent;
4758 $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
4759 $this->line->date_start = $date_start;
4760 $this->line->date_end = $date_end;
4761 $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
4762 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva);
4763 $this->line->total_localtax1 = (float) $total_localtax1;
4764 $this->line->total_localtax2 = (float) $total_localtax2;
4765 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc);
4766 $this->line->info_bits = $info_bits;
4767 $this->line->special_code = $special_code;
4768 $this->line->product_type = $type;
4769 $this->line->fk_parent_line = $fk_parent_line;
4770 $this->line->skip_update_total = $skip_update_total;
4771 $this->line->situation_percent = $situation_percent;
4772 $this->line->fk_unit = $fk_unit;
4773
4774 $this->line->fk_fournprice = $fk_fournprice;
4775 $this->line->pa_ht = $pa_ht;
4776
4777 // Multicurrency
4778 $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
4779 $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
4780 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4781 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4782
4783 if (is_array($array_options) && count($array_options) > 0) {
4784 // We replace values in this->line->array_options only for entries defined into $array_options
4785 foreach ($array_options as $key => $value) {
4786 $this->line->array_options[$key] = $array_options[$key];
4787 }
4788 }
4789
4790 $result = $this->line->update($user, $notrigger);
4791 if ($result > 0) {
4792 // Reorder if child line
4793 if (!empty($fk_parent_line)) {
4794 $this->line_order(true, 'DESC');
4795 }
4796
4797 // Mise a jour info denormalisees au niveau facture
4798 $this->update_price(1, 'auto');
4799 $this->db->commit();
4800 return $result;
4801 } else {
4802 $this->error = $this->line->error;
4803 $this->db->rollback();
4804 return -1;
4805 }
4806 } else {
4807 $this->error = "Invoice statut makes operation forbidden";
4808 return -2;
4809 }
4810 }
4811
4819 public function checkProgressLine($idline, $situation_percent)
4820 {
4821 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4822 INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4823 WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4824
4825 $result = $this->db->query($sql);
4826 if (!$result) {
4827 $this->error = $this->db->error();
4828 return false;
4829 }
4830
4831 $obj = $this->db->fetch_object($result);
4832
4833 if ($obj === null) {
4834 return true;
4835 } else {
4836 return ($situation_percent < $obj->situation_percent);
4837 }
4838 }
4839
4840 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4849 public function update_percent($line, $percent, $update_price = true)
4850 {
4851 // phpcs:enable
4852 global $mysoc, $user;
4853
4854 // Progress should never be changed for discount lines
4855 if (($line->info_bits & 2) == 2) {
4856 return;
4857 }
4858
4859 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4860
4861 // Cap percentages to 100
4862 if ($percent > 100) {
4863 $percent = 100;
4864 }
4865 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4866 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4867 $current_progress = $percent - $previous_progress;
4868 $line->situation_percent = $current_progress;
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(), $current_progress);
4870 } else {
4871 $line->situation_percent = $percent;
4872 $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);
4873 }
4874 $line->total_ht = (float) $tabprice[0];
4875 $line->total_tva = (float) $tabprice[1];
4876 $line->total_ttc = (float) $tabprice[2];
4877 $line->total_localtax1 = (float) $tabprice[9];
4878 $line->total_localtax2 = (float) $tabprice[10];
4879 $line->multicurrency_total_ht = (float) $tabprice[16];
4880 $line->multicurrency_total_tva = (float) $tabprice[17];
4881 $line->multicurrency_total_ttc = (float) $tabprice[18];
4882 $line->update($user);
4883
4884 // sometimes it is better to not update price for each line, ie when updating situation on all lines
4885 if ($update_price) {
4886 $this->update_price(1);
4887 }
4888 }
4889
4897 public function deleteLine($rowid, $id = 0)
4898 {
4899 global $user;
4900
4901 dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4902
4903 if ($this->status != self::STATUS_DRAFT) {
4904 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4905 return -1;
4906 }
4907
4908 $line = new FactureLigne($this->db);
4909
4910 $line->context = $this->context;
4911
4912 // Load line
4913 $result = $line->fetch($rowid);
4914 if (!($result > 0)) {
4915 dol_print_error($this->db, $line->error, $line->errors);
4916 return -1;
4917 }
4918
4919 if ($id > 0 && $line->fk_facture != $id) {
4920 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4921 return -1;
4922 }
4923
4924 $this->db->begin();
4925
4926 // Memorize previous line for triggers
4927 $staticline = clone $line;
4928 $line->oldline = $staticline;
4929
4930 if ($line->delete($user) > 0) {
4931 $result = $this->update_price(1);
4932
4933 if ($result > 0) {
4934 $this->db->commit();
4935 return 1;
4936 } else {
4937 $this->db->rollback();
4938 $this->error = $this->db->lasterror();
4939 return -1;
4940 }
4941 } else {
4942 $this->db->rollback();
4943 $this->error = $line->error;
4944 return -1;
4945 }
4946 }
4947
4948 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4959 public function set_remise($user, $remise, $notrigger = 0)
4960 {
4961 // phpcs:enable
4962 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4963 // @phan-suppress-next-line PhanDeprecatedFunction
4964 return $this->setDiscount($user, $remise, $notrigger);
4965 }
4966
4975 public function setDiscount($user, $remise, $notrigger = 0)
4976 {
4977 // Clean parameters
4978 if (empty($remise)) {
4979 $remise = 0;
4980 }
4981
4982 if ($user->hasRight('facture', 'creer')) {
4983 $remise = (float) price2num($remise, 2);
4984
4985 $error = 0;
4986
4987 $this->db->begin();
4988
4989 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4990 $sql .= " SET remise_percent = ".((float) $remise);
4991 $sql .= " WHERE rowid = ".((int) $this->id);
4992 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
4993
4994 dol_syslog(__METHOD__, LOG_DEBUG);
4995 $resql = $this->db->query($sql);
4996 if (!$resql) {
4997 $this->errors[] = $this->db->error();
4998 $error++;
4999 }
5000
5001 if (!$notrigger && empty($error)) {
5002 // Call trigger
5003 $result = $this->call_trigger('BILL_MODIFY', $user);
5004 if ($result < 0) {
5005 $error++;
5006 }
5007 // End call triggers
5008 }
5009
5010 if (!$error) {
5011 $this->remise_percent = $remise;
5012 $this->update_price(1);
5013
5014 $this->db->commit();
5015 return 1;
5016 } else {
5017 foreach ($this->errors as $errmsg) {
5018 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5019 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5020 }
5021 $this->db->rollback();
5022 return -1 * $error;
5023 }
5024 }
5025
5026 return 0;
5027 }
5028
5029
5030 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5039 /*
5040 public function set_remise_absolue($user, $remise, $notrigger = 0)
5041 {
5042 // phpcs:enable
5043 if (empty($remise)) {
5044 $remise = 0;
5045 }
5046
5047 if ($user->hasRight('facture', 'creer')) {
5048 $error = 0;
5049
5050 $this->db->begin();
5051
5052 $remise = price2num($remise);
5053
5054 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
5055 $sql .= ' SET remise_absolue = '.((float) $remise);
5056 $sql .= " WHERE rowid = ".((int) $this->id);
5057 $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
5058
5059 dol_syslog(__METHOD__, LOG_DEBUG);
5060 $resql = $this->db->query($sql);
5061 if (!$resql) {
5062 $this->errors[] = $this->db->error();
5063 $error++;
5064 }
5065
5066 if (!$error) {
5067 $this->oldcopy = clone $this;
5068 $this->remise_absolue = $remise;
5069 $this->update_price(1);
5070 }
5071
5072 if (!$notrigger && empty($error)) {
5073 // Call trigger
5074 $result = $this->call_trigger('BILL_MODIFY', $user);
5075 if ($result < 0) {
5076 $error++;
5077 }
5078 // End call triggers
5079 }
5080
5081 if (!$error) {
5082 $this->db->commit();
5083 return 1;
5084 } else {
5085 foreach ($this->errors as $errmsg) {
5086 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5087 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5088 }
5089 $this->db->rollback();
5090 return -1 * $error;
5091 }
5092 }
5093
5094 return 0;
5095 }
5096 */
5097
5108 public function setCategories($categories)
5109 {
5110 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
5111 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5112 }
5113
5122 public function getNextNumRef($soc, $mode = 'next')
5123 {
5124 global $conf, $langs;
5125
5126 if ($this->module_source == 'takepos') {
5127 $langs->load('cashdesk');
5128
5129 $moduleName = 'takepos';
5130 $moduleSourceName = 'Takepos';
5131 $addonConstName = 'TAKEPOS_REF_ADDON';
5132
5133 // Clean parameters (if not defined or using deprecated value)
5134 if (!getDolGlobalString('TAKEPOS_REF_ADDON')) {
5135 $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
5136 }
5137
5138 $addon = getDolGlobalString('TAKEPOS_REF_ADDON');
5139 } else {
5140 $langs->load('bills');
5141
5142 $moduleName = 'facture';
5143 $moduleSourceName = 'Invoice';
5144 $addonConstName = 'FACTURE_ADDON';
5145
5146 // Clean parameters (if not defined or using deprecated value)
5147 if (!getDolGlobalString('FACTURE_ADDON')) {
5148 $conf->global->FACTURE_ADDON = 'mod_facture_mars';
5149 } elseif (getDolGlobalString('FACTURE_ADDON') == 'terre') { // terre is deprecated
5150 $conf->global->FACTURE_ADDON = 'mod_facture_mars';
5151 } elseif (getDolGlobalString('FACTURE_ADDON') == 'mercure') {
5152 $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
5153 }
5154
5155 $addon = getDolGlobalString('FACTURE_ADDON');
5156 }
5157
5158 if (!empty($addon)) {
5159 dol_syslog("Call getNextNumRef with ".$addonConstName." = " . getDolGlobalString('FACTURE_ADDON').", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
5160
5161 $mybool = false;
5162
5163 $file = $addon.'.php';
5164 $classname = $addon;
5165
5166
5167 // Include file with class
5168 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
5169 foreach ($dirmodels as $reldir) {
5170 $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
5171
5172 // Load file with numbering class (if found)
5173 if (is_file($dir.$file) && is_readable($dir.$file)) {
5174 $mybool = ((bool) include_once $dir.$file) || $mybool;
5175 }
5176 }
5177
5178 // For compatibility
5179 if (!$mybool) {
5180 $file = $addon.'/'.$addon.'.modules.php';
5181 $classname = 'mod_'.$moduleName.'_'.$addon;
5182 $classname = preg_replace('/\-.*$/', '', $classname);
5183 // Include file with class
5184 foreach ($conf->file->dol_document_root as $dirroot) {
5185 $dir = $dirroot.'/core/modules/'.$moduleName.'/';
5186
5187 // Load file with numbering class (if found)
5188 if (is_file($dir.$file) && is_readable($dir.$file)) {
5189 $mybool = (include_once $dir.$file) || $mybool;
5190 }
5191 }
5192 }
5193
5194 if (!$mybool) {
5195 dol_print_error(null, 'Failed to include file '.$file);
5196 return '';
5197 }
5198
5199 $obj = new $classname();
5200 '@phan-var-force ModeleNumRefFactures $obj';
5201
5202 $numref = $obj->getNextValue($soc, $this, $mode);
5203
5204
5209 if ($mode != 'last' && !$numref) {
5210 $this->error = $obj->error;
5211 return '';
5212 }
5213
5214 return $numref;
5215 } else {
5216 $langs->load('errors');
5217 print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5218 return '';
5219 }
5220 }
5221
5228 public function info($id)
5229 {
5230 $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5231 $sql .= ' date_closing as dateclosing,';
5232 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5233 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
5234 $sql .= ' WHERE c.rowid = '.((int) $id);
5235
5236 $result = $this->db->query($sql);
5237 if ($result) {
5238 if ($this->db->num_rows($result)) {
5239 $obj = $this->db->fetch_object($result);
5240
5241 $this->id = $obj->rowid;
5242 $this->user_creation_id = $obj->fk_user_author;
5243 $this->user_modification_id = $obj->fk_user_modif;
5244 $this->user_validation_id = $obj->fk_user_valid;
5245 $this->user_closing_id = $obj->fk_user_closing;
5246
5247 $this->date_creation = $this->db->jdate($obj->datec);
5248 $this->date_modification = $this->db->jdate($obj->datem);
5249 $this->date_validation = $this->db->jdate($obj->datev);
5250 $this->date_closing = $this->db->jdate($obj->dateclosing);
5251 }
5252 $this->db->free($result);
5253 } else {
5254 dol_print_error($this->db);
5255 }
5256 }
5257
5258
5259 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5273 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
5274 {
5275 // phpcs:enable
5276 global $user;
5277
5278 $ga = array();
5279
5280 $sql = "SELECT s.rowid, s.nom as name, s.client,";
5281 $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
5282 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
5283 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5284 $sql .= " AND f.fk_soc = s.rowid";
5285 if ($draft) {
5286 $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
5287 }
5288 if (is_object($excluser)) {
5289 $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
5290 }
5291 // If the internal user must only see his customers, force searching by him
5292 $search_sale = 0;
5293 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5294 $search_sale = $user->id;
5295 }
5296 // Search on sale representative
5297 if ($search_sale && $search_sale != '-1') {
5298 if ($search_sale == -2) {
5299 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5300 } elseif ($search_sale > 0) {
5301 $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).")";
5302 }
5303 }
5304 // Search on socid
5305 if ($socid) {
5306 $sql .= " AND f.fk_soc = ".((int) $socid);
5307 }
5308 $sql .= $this->db->order($sortfield, $sortorder);
5309 $sql .= $this->db->plimit($limit, $offset);
5310
5311 $result = $this->db->query($sql);
5312 if ($result) {
5313 $numc = $this->db->num_rows($result);
5314 if ($numc) {
5315 $i = 0;
5316 while ($i < $numc) {
5317 $obj = $this->db->fetch_object($result);
5318
5319 if ($shortlist == 1) {
5320 $ga[$obj->fid] = $obj->ref;
5321 } elseif ($shortlist == 2) {
5322 $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
5323 } else {
5324 $ga[$i]['id'] = $obj->fid;
5325 $ga[$i]['ref'] = $obj->ref;
5326 $ga[$i]['name'] = $obj->name;
5327 }
5328 $i++;
5329 }
5330 }
5331 return $ga;
5332 } else {
5333 dol_print_error($this->db);
5334 return -1;
5335 }
5336 }
5337
5338
5339 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5348 public function list_replacable_invoices($socid = 0)
5349 {
5350 // phpcs:enable
5351 global $conf;
5352
5353 $return = array();
5354
5355 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5356 $sql .= " ff.rowid as rowidnext";
5357 //$sql .= ", SUM(pf.amount) as alreadypaid";
5358 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5359 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
5360 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
5361 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
5362 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5363 $sql .= " AND f.paye = 0"; // Not paid completely
5364 $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
5365 $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
5366 if ($socid > 0) {
5367 $sql .= " AND f.fk_soc = ".((int) $socid);
5368 }
5369 //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
5370 $sql .= " ORDER BY f.ref";
5371
5372 dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
5373 $resql = $this->db->query($sql);
5374 if ($resql) {
5375 while ($obj = $this->db->fetch_object($resql)) {
5376 $return[$obj->rowid] = array(
5377 'id' => $obj->rowid,
5378 'ref' => $obj->ref,
5379 'status' => $obj->status,
5380 'paid' => $obj->paid,
5381 'alreadypaid' => 0
5382 );
5383 }
5384 //print_r($return);
5385 return $return;
5386 } else {
5387 $this->error = $this->db->error();
5388 return -1;
5389 }
5390 }
5391
5392
5393 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5403 public function list_qualified_avoir_invoices($socid = 0)
5404 {
5405 // phpcs:enable
5406 global $conf;
5407
5408 $return = array();
5409
5410
5411 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
5412 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5413 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
5414 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
5415 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5416 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5417 // $sql.= " WHERE f.fk_statut >= 1";
5418 // $sql.= " AND (f.paye = 1"; // Classee payee completement
5419 // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
5420 $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de replacement
5421 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
5422
5423 if (getDolGlobalString('INVOICE_USE_SITUATION_CREDIT_NOTE')) {
5424 // Keep invoices that are not situation invoices or that are the last in series if it is a situation invoice
5425 $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
5426 $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID because of the group by later
5427 $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
5428 $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
5429 $sql .= " AND fs.type = ".self::TYPE_SITUATION;
5430 $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5431 if ($socid > 0) {
5432 $sql .= " AND fs.fk_soc = ".((int) $socid);
5433 }
5434 $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
5435 $sql .= ")";
5436 } else {
5437 $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
5438 }
5439
5440 if ($socid > 0) {
5441 $sql .= " AND f.fk_soc = ".((int) $socid);
5442 }
5443
5444 if (getDolGlobalInt('LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5445 $sql .= " ORDER BY CASE WHEN f.rowid = ".((int) GETPOST('fac_avoir'))." THEN 0 ELSE 1 END, f.ref";
5446 $sql .= " DESC";
5447 $sql .= $this->db->plimit(getDolGlobalInt('LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5448 } else {
5449 $sql .= " ORDER BY f.ref";
5450 }
5451
5452 dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
5453 $resql = $this->db->query($sql);
5454 if ($resql) {
5455 while ($obj = $this->db->fetch_object($resql)) {
5456 $qualified = 0;
5457 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5458 $qualified = 1;
5459 }
5460 if ($obj->fk_statut == self::STATUS_CLOSED) {
5461 $qualified = 1;
5462 }
5463 if ($qualified) {
5464 //$ref=$obj->ref;
5465 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5466 $return[$obj->rowid] = array('ref' => $obj->ref, 'status' => $obj->fk_statut, 'type' => $obj->type, 'paye' => $obj->paye, 'paymentornot' => $paymentornot);
5467 }
5468 }
5469
5470 return $return;
5471 } else {
5472 $this->error = $this->db->error();
5473 return -1;
5474 }
5475 }
5476
5477
5478 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5485 public function load_board($user)
5486 {
5487 // phpcs:enable
5488 global $conf, $langs;
5489
5490 $clause = " WHERE";
5491
5492 $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5493 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5494 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5495 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5496 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5497 $clause = " AND";
5498 }
5499 $sql .= $clause." f.paye=0";
5500 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5501 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
5502 if ($user->socid) {
5503 $sql .= " AND f.fk_soc = ".((int) $user->socid);
5504 }
5505
5506 $resql = $this->db->query($sql);
5507 if ($resql) {
5508 $langs->load("bills");
5509 $now = dol_now();
5510 $response = new WorkboardResponse();
5511 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
5512 $response->label = $langs->trans("CustomerBillsUnpaid");
5513 $response->labelShort = $langs->trans("Unpaid");
5514 $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5515 $response->img = img_object('', "bill");
5516
5517 $generic_facture = new Facture($this->db);
5518
5519 while ($obj = $this->db->fetch_object($resql)) {
5520 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5521 $generic_facture->statut = $obj->status;
5522 $generic_facture->status = $obj->status;
5523
5524 $response->nbtodo++;
5525 $response->total += $obj->total_ht;
5526
5527 if ($generic_facture->hasDelay()) {
5528 $response->nbtodolate++;
5529 $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5530 }
5531 }
5532
5533 $this->db->free($resql);
5534 return $response;
5535 } else {
5536 dol_print_error($this->db);
5537 $this->error = $this->db->error();
5538 return -1;
5539 }
5540 }
5541
5542
5543 /* gestion des contacts d'une facture */
5544
5550 public function getIdBillingContact()
5551 {
5552 return $this->getIdContact('external', 'BILLING');
5553 }
5554
5560 public function getIdShippingContact()
5561 {
5562 return $this->getIdContact('external', 'SHIPPING');
5563 }
5564
5565
5574 public function initAsSpecimen($option = '')
5575 {
5576 global $conf, $langs, $user;
5577
5578 $now = dol_now();
5579 $arraynow = dol_getdate($now);
5580 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
5581
5582 // Load array of products prodids
5583 $num_prods = 0;
5584 $prodids = array();
5585 $sql = "SELECT rowid";
5586 $sql .= " FROM ".MAIN_DB_PREFIX."product";
5587 $sql .= " WHERE entity IN (".getEntity('product').")";
5588 $sql .= $this->db->plimit(100);
5589
5590 $resql = $this->db->query($sql);
5591 if ($resql) {
5592 $num_prods = $this->db->num_rows($resql);
5593 $i = 0;
5594 while ($i < $num_prods) {
5595 $i++;
5596 $row = $this->db->fetch_row($resql);
5597 $prodids[$i] = $row[0];
5598 }
5599 }
5600 //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
5601 if (empty($num_prods)) {
5602 $num_prods = 1;
5603 $prodids[$num_prods] = 1;
5604 }
5605
5606 // Initialize parameters
5607 $this->id = 0;
5608 $this->entity = $conf->entity;
5609 $this->ref = 'SPECIMEN';
5610 $this->specimen = 1;
5611 $this->socid = 1;
5612 $this->date = $nownotime;
5613 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5614 $this->cond_reglement_id = 1;
5615 $this->cond_reglement_code = 'RECEP';
5616 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
5617 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
5618 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
5619
5620 $this->note_public = 'This is a comment (public)';
5621 $this->note_private = 'This is a comment (private)';
5622
5623 $this->user_creation_id = $user->id;
5624
5625 $this->multicurrency_tx = 1;
5626 $this->multicurrency_code = $conf->currency;
5627
5628 $this->fk_incoterms = 0;
5629 $this->location_incoterms = '';
5630
5631 $this->pos_print_counter = 0; // Already printed 0 times
5632 $this->email_sent_counter = 0; // Already sent by email 0 times
5633
5634 $this->status = 0;
5635
5636 if (empty($option) || $option != 'nolines') {
5637 // Lines
5638 $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)
5639 $xnbp = 0;
5640 while ($xnbp < $nbp) {
5641 $line = new FactureLigne($this->db);
5642 $line->desc = $langs->trans("Description")." ".$xnbp;
5643 $line->qty = 1;
5644 $line->subprice = 100;
5645 $line->tva_tx = 19.6;
5646 $line->localtax1_tx = 0;
5647 $line->localtax2_tx = 0;
5648 $line->remise_percent = 0;
5649 if ($xnbp == 1 && $option != 'takepos') { // Qty is negative (product line)
5650 $prodid = mt_rand(1, $num_prods);
5651 if (isset($prodids[$prodid])) {
5652 $line->fk_product = $prodids[$prodid];
5653 }
5654 $line->qty = -1;
5655 $line->total_ht = -100;
5656 $line->total_ttc = -119.6;
5657 $line->total_tva = -19.6;
5658 $line->multicurrency_total_ht = -200;
5659 $line->multicurrency_total_ttc = -239.2;
5660 $line->multicurrency_total_tva = -39.2;
5661 } elseif ($xnbp == 2 && $option != 'takepos') { // UP is negative (free line)
5662 $line->subprice = -100;
5663 $line->total_ht = -100;
5664 $line->total_ttc = -119.6;
5665 $line->total_tva = -19.6;
5666 $line->remise_percent = 0;
5667 $line->multicurrency_total_ht = -200;
5668 $line->multicurrency_total_ttc = -239.2;
5669 $line->multicurrency_total_tva = -39.2;
5670 } elseif ($xnbp == 3) { // Discount is 50% (product line)
5671 $prodid = mt_rand(1, $num_prods);
5672 if (isset($prodids[$prodid])) {
5673 $line->fk_product = $prodids[$prodid];
5674 }
5675 $line->total_ht = 50;
5676 $line->total_ttc = 59.8;
5677 $line->total_tva = 9.8;
5678 $line->multicurrency_total_ht = 100;
5679 $line->multicurrency_total_ttc = 119.6;
5680 $line->multicurrency_total_tva = 19.6;
5681 $line->remise_percent = 50;
5682 } else { // (product line)
5683 $prodid = mt_rand(1, $num_prods);
5684 if (isset($prodids[$prodid])) {
5685 $line->fk_product = $prodids[$prodid];
5686 }
5687 $line->total_ht = 100;
5688 $line->total_ttc = 119.6;
5689 $line->total_tva = 19.6;
5690 $line->multicurrency_total_ht = 200;
5691 $line->multicurrency_total_ttc = 239.2;
5692 $line->multicurrency_total_tva = 39.2;
5693 $line->remise_percent = 0;
5694 }
5695
5696 $this->lines[$xnbp] = $line;
5697
5698
5699 $this->total_ht += $line->total_ht;
5700 $this->total_tva += $line->total_tva;
5701 $this->total_ttc += $line->total_ttc;
5702
5703 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5704 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5705 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5706
5707 $xnbp++;
5708 }
5709 $this->revenuestamp = 0;
5710
5711 // Add a line "offered"
5712 if ($option != 'takepos') {
5713 $line = new FactureLigne($this->db);
5714 $line->desc = $langs->trans("Description")." (offered line)";
5715 $line->qty = 1;
5716 $line->subprice = 100;
5717 $line->tva_tx = 19.6;
5718 $line->localtax1_tx = 0;
5719 $line->localtax2_tx = 0;
5720 $line->remise_percent = 100;
5721 $line->total_ht = 0;
5722 $line->total_ttc = 0; // 90 * 1.196
5723 $line->total_tva = 0;
5724 $line->multicurrency_total_ht = 0;
5725 $line->multicurrency_total_ttc = 0;
5726 $line->multicurrency_total_tva = 0;
5727 $prodid = mt_rand(1, $num_prods);
5728 if (isset($prodids[$prodid])) {
5729 $line->fk_product = $prodids[$prodid];
5730 }
5731
5732 $this->lines[$xnbp] = $line;
5733 $xnbp++;
5734 }
5735 }
5736
5737 return 1;
5738 }
5739
5745 public function loadStateBoard()
5746 {
5747 global $user;
5748
5749 $this->nb = array();
5750
5751 $clause = "WHERE";
5752
5753 $sql = "SELECT count(f.rowid) as nb";
5754 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5755 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
5756 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5757 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5758 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5759 $clause = "AND";
5760 }
5761 $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
5762
5763 $resql = $this->db->query($sql);
5764 if ($resql) {
5765 while ($obj = $this->db->fetch_object($resql)) {
5766 $this->nb["invoices"] = $obj->nb;
5767 }
5768 $this->db->free($resql);
5769 return 1;
5770 } else {
5771 dol_print_error($this->db);
5772 $this->error = $this->db->error();
5773 return -1;
5774 }
5775 }
5776
5782 public function getLinesArray()
5783 {
5784 return $this->fetch_lines();
5785 }
5786
5798 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5799 {
5800 $outputlangs->loadLangs(array("bills", "products"));
5801
5802 if (!dol_strlen($modele)) {
5803 $modele = 'crabe';
5804 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5805
5806 if (!empty($this->model_pdf)) {
5807 $modele = $this->model_pdf;
5808 } elseif (getDolGlobalString($thisTypeConfName)) {
5809 $modele = getDolGlobalString($thisTypeConfName);
5810 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
5811 $modele = getDolGlobalString('FACTURE_ADDON_PDF');
5812 }
5813 }
5814
5815 $modelpath = "core/modules/facture/doc/";
5816
5817 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5818 }
5819
5825 public function newCycle()
5826 {
5827 $sql = "SELECT max(situation_cycle_ref) as maxsituationref";
5828 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5829 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5830
5831 $resql = $this->db->query($sql);
5832 if ($resql) {
5833 if ($this->db->num_rows($resql) > 0) {
5834 $ref = 0;
5835 $obj = $this->db->fetch_object($resql);
5836 if ($obj) {
5837 $ref = $obj->maxsituationref;
5838 }
5839 $ref++;
5840 } else {
5841 $ref = 1;
5842 }
5843 $this->db->free($resql);
5844 return $ref;
5845 } else {
5846 $this->error = $this->db->lasterror();
5847 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5848 return -1;
5849 }
5850 }
5851
5852 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5858 public function is_first()
5859 {
5860 // phpcs:enable
5861 return ($this->situation_counter == 1);
5862 }
5863
5864 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5870 public function get_prev_sits()
5871 {
5872 // phpcs:enable
5873 global $conf;
5874
5875 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5876 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5877 $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5878 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5879 $resql = $this->db->query($sql);
5880 $res = array();
5881 if ($resql && $this->db->num_rows($resql) > 0) {
5882 while ($row = $this->db->fetch_object($resql)) {
5883 $id = $row->rowid;
5884 $situation = new Facture($this->db);
5885 $situation->fetch($id);
5886 $res[] = $situation;
5887 }
5888 } else {
5889 $this->error = $this->db->error();
5890 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5891 return -1;
5892 }
5893
5894 return $res;
5895 }
5896
5904 public function setFinal(User $user, $notrigger = 0)
5905 {
5906 $error = 0;
5907
5908 $this->db->begin();
5909
5910 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5911
5912 dol_syslog(__METHOD__, LOG_DEBUG);
5913 $resql = $this->db->query($sql);
5914 if (!$resql) {
5915 $this->errors[] = $this->db->error();
5916 $error++;
5917 }
5918
5919 if (!$notrigger && empty($error)) {
5920 // Call trigger
5921 $result = $this->call_trigger('BILL_MODIFY', $user);
5922 if ($result < 0) {
5923 $error++;
5924 }
5925 // End call triggers
5926 }
5927
5928 if (!$error) {
5929 $this->db->commit();
5930 return 1;
5931 } else {
5932 foreach ($this->errors as $errmsg) {
5933 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5934 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5935 }
5936 $this->db->rollback();
5937 return -1 * $error;
5938 }
5939 }
5940
5941 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5947 public function is_last_in_cycle()
5948 {
5949 // phpcs:enable
5950 global $conf;
5951
5952 if (!empty($this->situation_cycle_ref)) {
5953 // No point in testing anything if we're not inside a cycle
5954 $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5955 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5956 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5957 $resql = $this->db->query($sql);
5958
5959 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5960 $last = $res['max(situation_counter)'];
5961 return ($last == $this->situation_counter);
5962 } else {
5963 $this->error = $this->db->lasterror();
5964 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5965 return false;
5966 }
5967 } else {
5968 return true;
5969 }
5970 }
5971
5980 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5981 {
5982 $tables = array(
5983 'facture'
5984 );
5985
5986 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5987 }
5988
5997 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5998 {
5999 $tables = array(
6000 'facturedet'
6001 );
6002
6003 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
6004 }
6005
6011 public function hasDelay()
6012 {
6013 global $conf;
6014
6015 $now = dol_now();
6016
6017 // Paid invoices have status STATUS_CLOSED
6018 if ($this->status != Facture::STATUS_VALIDATED) {
6019 return false;
6020 }
6021
6022 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
6023 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6024 $totalpaid = $this->getSommePaiement(0);
6025 $totalpaid = (float) $totalpaid;
6026 $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
6027 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
6028 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
6029 $hasDelay = 1;
6030 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
6031 $hasDelay = 1;
6032 } else {
6033 $hasDelay = 0;
6034 }
6035 }
6036 }
6037
6038 return $hasDelay;
6039 }
6040
6046 public function isSituationInvoice()
6047 {
6048 return $this->situation_cycle_ref;
6049 }
6050
6055 public function displayRetainedWarranty()
6056 {
6057 // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
6058
6059 // 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
6060
6061 $displayWarranty = false;
6062 if (!empty($this->retained_warranty)) {
6063 $displayWarranty = true;
6064
6065 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
6066 // Check if this situation invoice is 100% for real
6067 $displayWarranty = false;
6068 if (!empty($this->situation_final)) {
6069 $displayWarranty = true;
6070 } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
6071 // $object->situation_final need validation to be done so this test is need for draft
6072 $displayWarranty = true;
6073
6074 foreach ($this->lines as $i => $line) {
6075 if ($line->product_type < 2 && $line->situation_percent < 100) {
6076 $displayWarranty = false;
6077 break;
6078 }
6079 }
6080 }
6081 }
6082 }
6083
6084 return $displayWarranty;
6085 }
6086
6091 public function getRetainedWarrantyAmount($rounding = -1)
6092 {
6093 if (empty($this->retained_warranty)) {
6094 return -1;
6095 }
6096
6097 $retainedWarrantyAmount = 0;
6098
6099 // Billed - retained warranty
6100 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
6101 $displayWarranty = true;
6102 // Check if this situation invoice is 100% for real
6103 if (!empty($this->lines)) {
6104 foreach ($this->lines as $i => $line) {
6105 if ($line->product_type < 2 && $line->situation_percent < 100) {
6106 $displayWarranty = false;
6107 break;
6108 }
6109 }
6110 }
6111
6112 if ($displayWarranty && !empty($this->situation_final)) {
6114 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6115
6116 $total2BillWT = 0;
6117 foreach ($TPreviousIncoice as &$fac) {
6118 $total2BillWT += $fac->total_ttc;
6119 }
6120 $total2BillWT += $this->total_ttc;
6121
6122 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6123 } else {
6124 return -1;
6125 }
6126 } else {
6127 // Because one day retained warranty could be used on standard invoices
6128 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6129 }
6130
6131 if ($rounding < 0) {
6132 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
6133 }
6134
6135 if ($rounding > 0) {
6136 return round($retainedWarrantyAmount, $rounding);
6137 }
6138
6139 return $retainedWarrantyAmount;
6140 }
6141
6148 public function setRetainedWarranty($value)
6149 {
6150 dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
6151
6152 if ($this->status >= 0) {
6153 $fieldname = 'retained_warranty';
6154 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6155 $sql .= " SET ".$fieldname." = ".((float) $value);
6156 $sql .= ' WHERE rowid='.((int) $this->id);
6157
6158 if ($this->db->query($sql)) {
6159 $this->retained_warranty = (float) $value;
6160 return 1;
6161 } else {
6162 dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
6163 $this->error = $this->db->error();
6164 return -1;
6165 }
6166 } else {
6167 dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
6168 $this->error = 'Status of the object is incompatible '.$this->status;
6169 return -2;
6170 }
6171 }
6172
6173
6181 public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '')
6182 {
6183 if (!$timestamp && $dateYmd) {
6184 $timestamp = $this->db->jdate($dateYmd);
6185 }
6186
6187
6188 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
6189 if ($this->status >= 0) {
6190 $fieldname = 'retained_warranty_date_limit';
6191 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6192 $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
6193 $sql .= ' WHERE rowid = '.((int) $this->id);
6194
6195 if ($this->db->query($sql)) {
6196 $this->retained_warranty_date_limit = $timestamp;
6197 return 1;
6198 } else {
6199 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
6200 $this->error = $this->db->error();
6201 return -1;
6202 }
6203 } else {
6204 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6205 $this->error = 'Status of the object is incompatible '.$this->status;
6206 return -2;
6207 }
6208 }
6209
6210
6222 public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
6223 {
6224 global $conf, $langs, $user;
6225
6226 $error = 0;
6227 $this->output = '';
6228 $this->error = '';
6229 $nbMailSend = 0;
6230 $errorsMsg = array();
6231
6232 $langs->load("bills");
6233
6234 if (!isModEnabled('invoice')) { // Should not happen. If module disabled, cron job should not be visible.
6235 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Invoice"));
6236 return 0;
6237 }
6238 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
6239 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6240 return 0;
6241 }
6242 /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
6243 $langs->load("bills");
6244 $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Invoice"));
6245 return 0;
6246 }
6247 */
6248
6249 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
6250 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
6251 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
6252 $formmail = new FormMail($this->db);
6253
6254 $now = dol_now();
6255 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
6256
6257 $tmpinvoice = new Facture($this->db);
6258
6259 dol_syslog(__METHOD__." start", LOG_INFO);
6260
6261 // Select all action comm reminder
6262 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
6263 if (!empty($paymentmode) && $paymentmode != 'all') {
6264 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
6265 }
6266 $sql .= " WHERE f.paye = 0"; // Only unpaid
6267 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
6268 if ($datetouse == 'invoicedate') {
6269 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
6270 } else {
6271 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
6272 }
6273 $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch processes only one company (no sharing)
6274 if (!empty($paymentmode) && $paymentmode != 'all') {
6275 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
6276 }
6277 // TODO Add a filter to check there is no payment started yet
6278 if ($datetouse == 'invoicedate') {
6279 $sql .= $this->db->order("datef", "ASC");
6280 } else {
6281 $sql .= $this->db->order("date_lim_reglement", "ASC");
6282 }
6283 // 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.
6284
6285 $resql = $this->db->query($sql);
6286
6287 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
6288 if ($datetouse == 'invoicedate') {
6289 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedInvoicesWithDate", $stmpidate);
6290 } else {
6291 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
6292 }
6293 if (!empty($paymentmode) && $paymentmode != 'all') {
6294 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
6295 }
6296 $this->output .= '<br>';
6297
6298 if ($resql) {
6299 while ($obj = $this->db->fetch_object($resql)) {
6300 // Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
6301 $loopError = 0;
6302
6303 // Load event
6304 $res = $tmpinvoice->fetch($obj->id);
6305 if ($res > 0) {
6306 $tmpinvoice->fetch_thirdparty();
6307
6308 $outputlangs = new Translate('', $conf);
6309 if ($tmpinvoice->thirdparty->default_lang) {
6310 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6311 $outputlangs->loadLangs(array("main", "bills"));
6312 } else {
6313 $outputlangs = $langs;
6314 }
6315
6316 // Select email template according to language of recipient
6317 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
6318 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6319 $langs->load("errors");
6320 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
6321 return 0;
6322 }
6323
6324 // PREPARE EMAIL
6325 $errormesg = '';
6326
6327 // Make substitution in email content
6328 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $tmpinvoice);
6329
6330 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
6331
6332 // Topic
6333 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6334
6335 // Content
6336 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6337
6338 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
6339
6340 // Recipient
6341 $to = array();
6342 if ($forcerecipient) { // If a recipient was forced
6343 $to = array($forcerecipient);
6344 } else {
6345 $res = $tmpinvoice->fetch_thirdparty();
6346 $recipient = $tmpinvoice->thirdparty;
6347 if ($res > 0) {
6348 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
6349 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6350 foreach ($tmparraycontact as $data_email) {
6351 if (!empty($data_email['email'])) {
6352 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
6353 }
6354 }
6355 }
6356 if (empty($to) && !empty($recipient->email)) {
6357 $to[] = $recipient->email;
6358 }
6359 if (empty($to)) {
6360 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for invoice or customer.";
6361 $loopError++;
6362 }
6363 } else {
6364 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6365 $loopError++;
6366 }
6367 }
6368
6369 // Sender
6370 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
6371 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
6372 $from = (string) $arraymessage->email_from;
6373 }
6374 if (empty($from)) {
6375 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6376 $loopError++;
6377 }
6378
6379 if (!$loopError && !empty($to)) {
6380 $to = implode(',', $to);
6381 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
6382 $to = $to.','.$arraymessage->email_to;
6383 }
6384
6385 // Errors Recipient
6386 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
6387
6388 $trackid = 'inv'.$tmpinvoice->id;
6389 $sendcontext = 'standard';
6390
6391 $email_tocc = '';
6392 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
6393 $email_tocc = (string) $arraymessage->email_tocc;
6394 }
6395
6396 $email_tobcc = '';
6397 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
6398 $email_tobcc = (string) $arraymessage->email_tobcc;
6399 }
6400
6401 //join file is asked
6402 $joinFile = [];
6403 $joinFileName = [];
6404 $joinFileMime = [];
6405 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6406 $joinFile[] = DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc;
6407 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6408 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc);
6409 }
6410
6411 // Mail Creation
6412 $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
6413
6414 $resultsendmail = $cMailFile->sendfile();
6415
6416 $this->db->begin();
6417
6418 // Sending Mail
6419 if ($resultsendmail) {
6420 $nbMailSend++;
6421
6422 // Add a line into event table
6423 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6424
6425 // Insert record of emails sent
6426 $actioncomm = new ActionComm($this->db);
6427
6428 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6429 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6430 $actioncomm->contact_id = 0;
6431
6432 $actioncomm->code = 'AC_EMAIL';
6433 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
6434 $actioncomm->note_private = $sendContent;
6435 $actioncomm->fk_project = $tmpinvoice->fk_project;
6436 $actioncomm->datep = dol_now();
6437 $actioncomm->datef = $actioncomm->datep;
6438 $actioncomm->percentage = -1; // Not applicable
6439 $actioncomm->authorid = $user->id; // User saving action
6440 $actioncomm->userownerid = $user->id; // Owner of action
6441 // Fields when action is an email (content should be added into note)
6442 $actioncomm->email_msgid = $cMailFile->msgid;
6443 $actioncomm->email_subject = $sendTopic;
6444 $actioncomm->email_from = $from;
6445 $actioncomm->email_sender = '';
6446 $actioncomm->email_to = $to;
6447 //$actioncomm->email_tocc = $sendtocc;
6448 //$actioncomm->email_tobcc = $sendtobcc;
6449 //$actioncomm->email_subject = $subject;
6450 $actioncomm->errors_to = $errors_to;
6451
6452 $actioncomm->elementtype = 'invoice';
6453 $actioncomm->elementid = $tmpinvoice->id;
6454
6455 //$actioncomm->extraparams = $extraparams;
6456
6457 $actioncomm->create($user);
6458 } else {
6459 $errormesg = $cMailFile->error.' : '.$to;
6460 $loopError++;
6461
6462 // Add a line into event table
6463 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6464
6465 // Insert record of emails sent
6466 $actioncomm = new ActionComm($this->db);
6467
6468 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6469 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6470 $actioncomm->contact_id = 0;
6471
6472 $actioncomm->code = 'AC_EMAIL';
6473 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
6474 $actioncomm->note_private = $errormesg;
6475 $actioncomm->fk_project = $tmpinvoice->fk_project;
6476 $actioncomm->datep = dol_now();
6477 $actioncomm->datef = $actioncomm->datep;
6478 $actioncomm->percentage = -1; // Not applicable
6479 $actioncomm->authorid = $user->id; // User saving action
6480 $actioncomm->userownerid = $user->id; // Owner of action
6481 // Fields when action is an email (content should be added into note)
6482 $actioncomm->email_msgid = $cMailFile->msgid;
6483 $actioncomm->email_subject = $sendTopic;
6484 $actioncomm->email_from = $from;
6485 $actioncomm->email_sender = '';
6486 $actioncomm->email_to = $to;
6487 //$actioncomm->email_tocc = $sendtocc;
6488 //$actioncomm->email_tobcc = $sendtobcc;
6489 //$actioncomm->email_subject = $subject;
6490 $actioncomm->errors_to = $errors_to;
6491
6492 $actioncomm->elementtype = 'invoice';
6493 $actioncomm->elementid = $tmpinvoice->id;
6494
6495 //$actioncomm->extraparams = $extraparams;
6496
6497 $actioncomm->create($user);
6498 }
6499
6500 $this->db->commit(); // We always commit
6501 }
6502
6503 if ($errormesg) {
6504 $errorsMsg[] = $errormesg;
6505 }
6506 } else {
6507 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
6508 $loopError++;
6509 }
6510
6511 $error += $loopError;
6512 }
6513 } else {
6514 $error++;
6515 }
6516
6517 if (!$error) {
6518 $this->output .= 'Nb of emails sent : '.$nbMailSend;
6519
6520 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
6521
6522 return 0;
6523 } else {
6524 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
6525
6526 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
6527
6528 return $error;
6529 }
6530 }
6531
6538 public function willBeLastOfSameType($allow_validated_drafts = false)
6539 {
6540 // get date of last validated invoices of same type
6541 $sql = "SELECT datef";
6542 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
6543 $sql .= " WHERE type = " . (int) $this->type ;
6544 $sql .= " AND date_valid IS NOT NULL";
6545 $sql .= " AND entity IN (".getEntity('invoice').")";
6546 $sql .= " ORDER BY datef DESC LIMIT 1";
6547
6548 $result = $this->db->query($sql);
6549 if ($result) {
6550 // compare with current validation date
6551 if ($this->db->num_rows($result)) {
6552 $obj = $this->db->fetch_object($result);
6553 $last_date = $this->db->jdate($obj->datef);
6554 $invoice_date = $this->date;
6555
6556 $is_last_of_same_type = $invoice_date >= $last_date;
6557 if ($allow_validated_drafts) {
6558 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
6559 }
6560
6561 return array($is_last_of_same_type, $last_date);
6562 } else {
6563 // element is first of type to be validated
6564 return array(true);
6565 }
6566 } else {
6567 dol_print_error($this->db);
6568 }
6569
6570 return array();
6571 }
6572
6580 public function getKanbanView($option = '', $arraydata = null)
6581 {
6582 global $langs;
6583
6584 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6585
6586 $picto = $this->picto;
6587 if ($this->type == self::TYPE_REPLACEMENT) {
6588 $picto .= 'r'; // Replacement invoice
6589 }
6590 if ($this->type == self::TYPE_CREDIT_NOTE) {
6591 $picto .= 'a'; // Credit note
6592 }
6593 if ($this->type == self::TYPE_DEPOSIT) {
6594 $picto .= 'd'; // Deposit invoice
6595 }
6596
6597 $return = '<div class="box-flex-item box-flex-grow-zero">';
6598 $return .= '<div class="info-box info-box-sm">';
6599 $return .= '<span class="info-box-icon bg-infobox-action">';
6600 $return .= img_picto('', $picto);
6601 $return .= '</span>';
6602 $return .= '<div class="info-box-content">';
6603 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
6604 if ($selected >= 0) {
6605 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6606 }
6607 if (!empty($arraydata['thirdparty'])) {
6608 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
6609 }
6610 if (property_exists($this, 'date')) {
6611 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
6612 }
6613 if (property_exists($this, 'total_ht')) {
6614 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
6615 $return .= ' '.$langs->trans("HT");
6616 $return .= '</span>';
6617 }
6618 if (method_exists($this, 'getLibStatut')) {
6619 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
6620 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
6621 }
6622 $return .= '</div>';
6623 $return .= '</div>';
6624 $return .= '</div>';
6625 return $return;
6626 }
6627}
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.