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