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