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