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