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