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