dolibarr 21.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-2024 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) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
22 * Copyright (C) 2023 Nick Fragoulis
23 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
24 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <https://www.gnu.org/licenses/>.
38 */
39
46require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
47require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/factureligne.class.php';
48require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
49require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
50require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
51require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
52
53if (isModEnabled('accounting')) {
54 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
55}
56if (isModEnabled('accounting')) {
57 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
58}
59
64{
68 public $element = 'facture';
69
73 public $table_element = 'facture';
74
78 public $table_element_line = 'facturedet';
79
83 public $class_element_line = 'FactureLigne';
84
88 public $fk_element = 'fk_facture';
89
93 public $picto = 'bill';
94
99 public $restrictiononfksoc = 1;
100
104 protected $table_ref_field = 'ref';
105
110 public $fk_user_author;
111
116 public $fk_user_valid;
117
122 public $fk_user_modif;
123
127 public $datem;
128
132 public $delivery_date; // Date expected of shipment (date of start of shipment, not the reception that occurs some days after)
133
139 public $ref_client;
140
144 public $ref_customer;
145
149 public $total_ht;
153 public $total_tva;
157 public $total_localtax1;
161 public $total_localtax2;
165 public $total_ttc;
169 public $revenuestamp;
170
174 public $resteapayer;
175
181 public $paye;
182
186 public $module_source;
190 public $pos_source;
194 public $fk_fac_rec_source;
198 public $fk_facture_source;
199
200 public $linked_objects = array();
201
205 public $fk_bank;
206
210 public $lines = array();
211
215 public $line;
219 public $extraparams = array();
220
224 public $fac_rec;
225
229 public $date_pointoftax;
230
231
235 public $situation_cycle_ref;
236
240 public $situation_counter;
241
245 public $situation_final;
246
250 public $tab_previous_situation_invoice = array();
251
255 public $tab_next_situation_invoice = array();
256
260 public $retained_warranty;
261
265 public $retained_warranty_date_limit;
266
270 public $retained_warranty_fk_cond_reglement;
271
275 public $availability_id;
276
280 public $date_closing;
281
285 public $source;
286
291 public $remise_percent;
292
296 public $online_payment_url;
297
298
299
324 // BEGIN MODULEBUILDER PROPERTIES
328 public $fields = array(
329 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 1),
330 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 5),
331 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
332 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 10),
333 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 12),
334 'type' => array('type' => 'smallint(6)', 'label' => 'Type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
335 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
336 //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
337 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 50),
338 'datef' => array('type' => 'date', 'label' => 'DateInvoice', 'enabled' => 1, 'visible' => 1, 'position' => 20),
339 'date_valid' => array('type' => 'date', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 22),
340 'date_lim_reglement' => array('type' => 'date', 'label' => 'DateDue', 'enabled' => 1, 'visible' => 1, 'position' => 25),
341 'date_closing' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 30),
342 'paye' => array('type' => 'smallint(6)', 'label' => 'InvoicePaidCompletely', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 80),
343 //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85),
344 //'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
345 //'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>91),
346 //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
347 'close_code' => array('type' => 'varchar(16)', 'label' => 'EarlyClosingReason', 'enabled' => 1, 'visible' => -1, 'position' => 92),
348 'close_note' => array('type' => 'varchar(128)', 'label' => 'EarlyClosingComment', 'enabled' => 1, 'visible' => -1, 'position' => 93),
349 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 95, 'isameasure' => 1),
350 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => -1, 'position' => 100, 'isameasure' => 1),
351 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => -1, 'position' => 110, 'isameasure' => 1),
352 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => -1, 'position' => 120, 'isameasure' => 1),
353 'revenuestamp' => array('type' => 'double(24,8)', 'label' => 'RevenueStamp', 'enabled' => 1, 'visible' => -1, 'position' => 115, 'isameasure' => 1),
354 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
355 'fk_facture_source' => array('type' => 'integer', 'label' => 'SourceInvoice', 'enabled' => 1, 'visible' => -1, 'position' => 170),
356 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => 1, 'visible' => -1, 'position' => 175),
357 'fk_account' => array('type' => 'integer', 'label' => 'Fk account', 'enabled' => 1, 'visible' => -1, 'position' => 180),
358 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'CurrencyCode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
359 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 190),
360 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 195),
361 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 205),
362 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 210),
363 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 215),
364 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
365 'situation_cycle_ref' => array('type' => 'smallint(6)', 'label' => 'Situation cycle ref', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 230),
366 'situation_counter' => array('type' => 'smallint(6)', 'label' => 'Situation counter', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 235),
367 'situation_final' => array('type' => 'smallint(6)', 'label' => 'Situation final', 'enabled' => 'getDolGlobalInt("INVOICE_USE_SITUATION")', 'visible' => -1, 'position' => 240),
368 'retained_warranty' => array('type' => 'double', 'label' => 'Retained warranty', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 245),
369 'retained_warranty_date_limit' => array('type' => 'date', 'label' => 'Retained warranty date limit', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 250),
370 'retained_warranty_fk_cond_reglement' => array('type' => 'integer', 'label' => 'Retained warranty fk cond reglement', 'enabled' => 'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")', 'visible' => -1, 'position' => 255),
371 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 260),
372 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 265),
373 'date_pointoftax' => array('type' => 'date', 'label' => 'DatePointOfTax', 'enabled' => 'getDolGlobalString("INVOICE_POINTOFTAX_DATE")', 'visible' => -1, 'position' => 270),
374 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyID', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 275),
375 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 280),
376 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 285, 'isameasure' => 1),
377 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 290, 'isameasure' => 1),
378 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 291, 'isameasure' => 1),
379 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 292, 'isameasure' => 1),
380 'fk_fac_rec_source' => array('type' => 'integer', 'label' => 'RecurringInvoiceSource', 'enabled' => 1, 'visible' => -1, 'position' => 305),
381 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 310),
382 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 315),
383 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 320),
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 const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandoned remain - escompte
454 const CLOSECODE_BADDEBT = 'badcustomer'; // Abandoned remain - bad customer
455 const CLOSECODE_BANKCHARGE = 'bankcharge'; // Abandoned remain - bank charge
456 const CLOSECODE_OTHER = 'other'; // Abandoned remain - other
457
458 const CLOSECODE_ABANDONED = 'abandon'; // Abandoned - other
459 const CLOSECODE_REPLACED = 'replaced'; // Closed after doing a replacement invoice
460
461
467 public function __construct(DoliDB $db)
468 {
469 $this->db = $db;
470
471 $this->ismultientitymanaged = 1;
472 $this->isextrafieldmanaged = 1;
473 }
474
485 public function create(User $user, $notrigger = 0, $forceduedate = 0)
486 {
487 global $langs, $conf, $mysoc, $hookmanager;
488 $error = 0;
489 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
490 // Clean parameters
491 if (empty($this->type)) {
492 $this->type = self::TYPE_STANDARD;
493 }
494
495 $this->ref_client = trim($this->ref_client); // deprecated
496 $this->ref_customer = trim($this->ref_customer);
497
498 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : '');
499 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private); // deprecated
500 $this->note_public = (isset($this->note_public) ? trim($this->note_public) : '');
501
502 if (!$this->cond_reglement_id) {
503 $this->cond_reglement_id = 0;
504 }
505 if (!$this->mode_reglement_id) {
506 $this->mode_reglement_id = 0;
507 }
508 $this->status = self::STATUS_DRAFT;
509 $this->statut = self::STATUS_DRAFT; // deprecated
510
511 if (!empty($this->multicurrency_code)) {
512 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate of multicurrency_code only if not using original rate)
513 if (empty($this->multicurrency_tx)) {
514 // If original rate is not set, we take a default value from date
515 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
516 } else {
517 // original rate multicurrency_tx and multicurrency_code are set, we use them
518 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
519 }
520 } else {
521 $this->fk_multicurrency = 0;
522 }
523 if (empty($this->fk_multicurrency)) {
524 $this->multicurrency_code = $conf->currency;
525 $this->fk_multicurrency = 0;
526 $this->multicurrency_tx = 1;
527 }
528 $this->entity = setEntity($this);
529
530 dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
531
532 // Check parameters
533 if (empty($this->date)) {
534 $this->error = "Try to create an invoice with an empty parameter (date)";
535 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
536 return -3;
537 }
538 $soc = new Societe($this->db);
539 $result = $soc->fetch($this->socid);
540 if ($result < 0) {
541 $this->error = "Failed to fetch company: ".$soc->error;
542 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
543 return -2;
544 }
545
546 $now = dol_now();
547 $this->date_creation = $now;
548
549 $this->db->begin();
550
551 $originaldatewhen = null;
552 $nextdatewhen = null;
553 $previousdaynextdatewhen = null;
554
555 $_facrec = null;
556
557 // Erase some properties of the invoice to create with the one of the recurring invoice
558 if ($this->fac_rec > 0) {
559 $this->fk_fac_rec_source = $this->fac_rec;
560
561 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
562 $_facrec = new FactureRec($this->db);
563 $result = $_facrec->fetch($this->fac_rec);
564 $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
565
566 if (getDolGlobalString('MODEL_FAC_REC_AUTHOR')) {
567 // If option MODEL_FAC_REC_AUTHOR is set, we want the same author than the author of recurring invoice instead of current user
568 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
569 }
570
571 // Define some dates
572 $originaldatewhen = $_facrec->date_when;
573 $nextdatewhen = null;
574 $previousdaynextdatewhen = null;
575 if ($originaldatewhen) {
576 $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
577 $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
578 }
579
580 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.
581 $this->socid = $_facrec->socid;
582 }
583 $this->entity = $_facrec->entity; // Invoice created in same entity than template
584
585 // Fields coming from GUI.
586 // @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
587 // set by posted page with $object->xxx = ... and this section should be removed.
588 $this->fk_project = GETPOSTINT('projectid') > 0 ? GETPOSTINT('projectid') : $_facrec->fk_project;
589 $this->note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
590 $this->note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
591 $this->model_pdf = GETPOSTISSET('model') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
592 $this->cond_reglement_id = GETPOSTINT('cond_reglement_id') > 0 ? GETPOSTINT('cond_reglement_id') : $_facrec->cond_reglement_id;
593 $this->mode_reglement_id = GETPOSTINT('mode_reglement_id') > 0 ? GETPOSTINT('mode_reglement_id') : $_facrec->mode_reglement_id;
594 $this->fk_account = GETPOST('fk_account') > 0 ? GETPOSTINT('fk_account') : $_facrec->fk_account;
595
596 // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
597 $this->total_ht = $_facrec->total_ht;
598 $this->total_ttc = $_facrec->total_ttc;
599
600 // Fields always coming from template
601 //$this->remise_absolue = $_facrec->remise_absolue;
602 //$this->remise_percent = $_facrec->remise_percent; // TODO deprecated
603 $this->fk_incoterms = $_facrec->fk_incoterms;
604 $this->location_incoterms = $_facrec->location_incoterms;
605
606 // Clean parameters
607 if (!$this->type) {
608 $this->type = self::TYPE_STANDARD;
609 }
610 $this->ref_client = trim($this->ref_client);
611 $this->ref_customer = trim($this->ref_customer);
612 $this->note_public = trim($this->note_public);
613 $this->note_private = trim($this->note_private);
614 $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
615
616 $this->array_options = $_facrec->array_options;
617
618 if (!$this->mode_reglement_id) {
619 $this->mode_reglement_id = 0;
620 }
621 $this->status = self::STATUS_DRAFT;
622 $this->statut = self::STATUS_DRAFT; // deprecated
623
624 $this->linked_objects = $_facrec->linkedObjectsIds;
625 // We do not add link to template invoice or next invoice will be linked to all generated invoices
626 //$this->linked_objects['facturerec'][0] = $this->fac_rec;
627
628 // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
629 if ($_facrec->frequency > 0) {
630 dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
631 if (empty($_facrec->date_when)) {
632 $_facrec->date_when = $now;
633 }
634 $next_date = $_facrec->getNextDate(); // Calculate next date
635 $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
636 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
637 $result = $_facrec->setNextDate($next_date, 1);
638 }
639
640 // Define lang of customer
641 $outputlangs = $langs;
642 $newlang = '';
643
644 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
645 $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
646 }
647 // @phan-suppress-next-line PhanUndeclaredProperty
648 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
649 $newlang = $this->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
650 }
651 if (!empty($newlang)) {
652 $outputlangs = new Translate("", $conf);
653 $outputlangs->setDefaultLang($newlang);
654 }
655
656 // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
657 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
658 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
659 $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
660 $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
661 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
662 $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
663 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
664 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
665 $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
666 $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
667 // Only for template invoice
668 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ? dol_print_date($originaldatewhen, 'dayhour') : '');
669 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ? dol_print_date($nextdatewhen, 'dayhour') : '');
670 $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '');
671 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
672 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
673
674 //var_dump($substitutionarray);exit;
675
676 complete_substitutions_array($substitutionarray, $outputlangs);
677
678 $this->note_public = make_substitutions($this->note_public, $substitutionarray);
679 $this->note_private = make_substitutions($this->note_private, $substitutionarray);
680 }
681
682 // Define due date if not already defined
683 if (empty($forceduedate)) {
684 $duedate = $this->calculate_date_lim_reglement();
685 /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
686 dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
687 return -1;
688 }*/
689 $this->date_lim_reglement = $duedate;
690 } else {
691 $this->date_lim_reglement = $forceduedate;
692 }
693
694 // Insert into database
695 $socid = $this->socid;
696
697 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
698 $sql .= " ref";
699 $sql .= ", entity";
700 $sql .= ", ref_ext";
701 $sql .= ", type";
702 $sql .= ", subtype";
703 $sql .= ", fk_soc";
704 $sql .= ", datec";
705 $sql .= ", datef";
706 $sql .= ", date_pointoftax";
707 $sql .= ", note_private";
708 $sql .= ", note_public";
709 $sql .= ", ref_client";
710 $sql .= ", fk_account";
711 $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
712 $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
713 $sql .= ", situation_cycle_ref, situation_counter, situation_final";
714 $sql .= ", fk_incoterms, location_incoterms";
715 $sql .= ", fk_multicurrency";
716 $sql .= ", multicurrency_code";
717 $sql .= ", multicurrency_tx";
718 $sql .= ", retained_warranty";
719 $sql .= ", retained_warranty_date_limit";
720 $sql .= ", retained_warranty_fk_cond_reglement";
721 $sql .= ")";
722 $sql .= " VALUES (";
723 $sql .= "'(PROV)'";
724 $sql .= ", ".(int) $this->entity;
725 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
726 $sql .= ", '".$this->db->escape($this->type)."'";
727 $sql .= ", ".($this->subtype ? "'".$this->db->escape($this->subtype)."'" : "null");
728 $sql .= ", ".((int) $socid);
729 $sql .= ", '".$this->db->idate($this->date_creation)."'";
730 $sql .= ", '".$this->db->idate($this->date)."'";
731 $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
732 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
733 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
734 $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : ($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"));
735 $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
736 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
737 $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
738 $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
739 $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
740 $sql .= ", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id : "null");
741 $sql .= ", ".($this->fk_project ? (int) $this->fk_project : "null");
742 $sql .= ", ".((int) $this->cond_reglement_id);
743 $sql .= ", ".((int) $this->mode_reglement_id);
744 $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
745 $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
746 $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
747 $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
748 $sql .= ", ".($this->situation_final ? (int) $this->situation_final : 0);
749 $sql .= ", ".(int) $this->fk_incoterms;
750 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
751 $sql .= ", ".(int) $this->fk_multicurrency;
752 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
753 $sql .= ", ".(float) $this->multicurrency_tx;
754 $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty));
755 $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
756 $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
757 $sql .= ")";
758
759 $resql = $this->db->query($sql);
760 if ($resql) {
761 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
762
763 // Update ref with new one
764 $this->ref = '(PROV'.$this->id.')';
765 $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
766
767 $resql = $this->db->query($sql);
768 if (!$resql) {
769 $error++;
770 }
771
772 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
773 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
774 }
775
776 // Add object linked
777 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
778 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
779 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, ...))
780 foreach ($tmp_origin_id as $origin_id) {
781 $ret = $this->add_object_linked($origin, $origin_id);
782 if (!$ret) {
783 $this->error = $this->db->lasterror();
784 $error++;
785 }
786 }
787 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
788 $origin_id = $tmp_origin_id;
789 $ret = $this->add_object_linked($origin, $origin_id);
790 if (!$ret) {
791 $this->error = $this->db->lasterror();
792 $error++;
793 }
794 }
795 }
796 }
797
798 // Propagate contacts
799 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
800 $originforcontact = $this->origin;
801 $originidforcontact = $this->origin_id;
802 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
803 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
804 $exp = new Expedition($this->db);
805 $exp->fetch($this->origin_id);
806 $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
807 if (count($exp->linkedObjectsIds['commande']) > 0) {
808 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
809 $originforcontact = 'commande';
810 if (is_object($value)) {
811 $originidforcontact = $value->id;
812 } else {
813 $originidforcontact = $value;
814 }
815 break; // We take first one
816 }
817 }
818 }
819
820 $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
821 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
822
823 $resqlcontact = $this->db->query($sqlcontact);
824 if ($resqlcontact) {
825 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
826 //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
827 $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
828 }
829 } else {
830 dol_print_error($this->db);
831 }
832 }
833
834 /*
835 * Insert lines of invoices, if not from template invoice, into database
836 */
837 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
838 $fk_parent_line = 0;
839
840 dol_syslog("There is ".count($this->lines)." lines into ->lines that are InvoiceLines");
841 foreach ($this->lines as $i => $val) {
842 $newinvoiceline = $this->lines[$i];
843 '@phan-var-force FactureLigne $newinvoiceline';
844
845 $newinvoiceline->context = $this->context;
846
847 $newinvoiceline->fk_facture = $this->id;
848
849 $newinvoiceline->origin = $this->lines[$i]->element;
850 $newinvoiceline->origin_id = $this->lines[$i]->id;
851
852 // Auto set date of service ?
853 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
854 $newinvoiceline->date_start = $originaldatewhen;
855 }
856 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
857 $newinvoiceline->date_end = $previousdaynextdatewhen;
858 }
859
860 if ($result >= 0) {
861 // Reset fk_parent_line for no child products and special product
862 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
863 $fk_parent_line = 0;
864 }
865
866 // Complete vat rate with code
867 $vatrate = $newinvoiceline->tva_tx;
868 if ($newinvoiceline->vat_src_code && ! preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
869 $vatrate .= ' ('.$newinvoiceline->vat_src_code.')';
870 }
871
872 $newinvoiceline->fk_parent_line = $fk_parent_line;
873
874 if ($this->type == Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
875 $discount = new DiscountAbsolute($this->db);
876 $discount->fetch($newinvoiceline->fk_remise_except);
877
878 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
879 $newinvoiceline->fk_remise_except = $discountId;
880 }
881
882 $result = $this->addline(
883 $newinvoiceline->desc,
884 $newinvoiceline->subprice,
885 $newinvoiceline->qty,
886 $vatrate,
887 $newinvoiceline->localtax1_tx,
888 $newinvoiceline->localtax2_tx,
889 $newinvoiceline->fk_product,
890 $newinvoiceline->remise_percent,
891 $newinvoiceline->date_start,
892 $newinvoiceline->date_end,
893 $newinvoiceline->fk_code_ventilation,
894 $newinvoiceline->info_bits,
895 $newinvoiceline->fk_remise_except,
896 'HT',
897 0,
898 $newinvoiceline->product_type,
899 $newinvoiceline->rang,
900 $newinvoiceline->special_code,
901 $newinvoiceline->element,
902 $newinvoiceline->id,
903 $fk_parent_line,
904 $newinvoiceline->fk_fournprice,
905 $newinvoiceline->pa_ht,
906 $newinvoiceline->label,
907 $newinvoiceline->array_options,
908 $newinvoiceline->situation_percent,
909 $newinvoiceline->fk_prev_id,
910 $newinvoiceline->fk_unit,
911 $newinvoiceline->multicurrency_subprice,
912 $newinvoiceline->ref_ext,
913 1
914 );
915
916 if ($result < 0) {
917 $this->error = $newinvoiceline->error;
918 $this->errors = array_merge($this->errors, $newinvoiceline->errors);
919 $error++;
920 break;
921 }
922
923 // Defined the new fk_parent_line
924 if ($result > 0 && $newinvoiceline->product_type == 9) {
925 $fk_parent_line = $result;
926 }
927 }
928 }
929 } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
930 $fk_parent_line = 0;
931
932 dol_syslog("There is ".count($this->lines)." lines into ->lines as a simple array");
933
934 foreach ($this->lines as $i => $val) {
935 $line = $this->lines[$i];
936 '@phan-var-force FactureLigne $line';
937
938 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
939 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
940 if (!is_object($line)) {
941 $line = (object) $line;
942 }
943
944 if ($result >= 0) {
945 // Reset fk_parent_line for no child products and special product
946 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
947 $fk_parent_line = 0;
948 }
949
950 // Complete vat rate with code
951 $vatrate = $line->tva_tx;
952 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
953 $vatrate .= ' ('.$line->vat_src_code.')';
954 }
955
956 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
957 $originid = $line->origin_id;
958 $origintype = $line->origin;
959 } else {
960 $originid = $line->id;
961 $origintype = $this->element;
962 }
963
964 // init ref_ext
965 if (empty($line->ref_ext)) {
966 $line->ref_ext = '';
967 }
968
969 $result = $this->addline(
970 $line->desc,
971 $line->subprice,
972 $line->qty,
973 $vatrate,
974 $line->localtax1_tx,
975 $line->localtax2_tx,
976 $line->fk_product,
977 $line->remise_percent,
978 $line->date_start,
979 $line->date_end,
980 $line->fk_code_ventilation,
981 $line->info_bits,
982 $line->fk_remise_except,
983 'HT',
984 0,
985 $line->product_type,
986 $line->rang,
987 $line->special_code,
988 $origintype,
989 $originid,
990 $fk_parent_line,
991 $line->fk_fournprice,
992 $line->pa_ht,
993 $line->label,
994 $line->array_options,
995 $line->situation_percent,
996 $line->fk_prev_id,
997 $line->fk_unit,
998 $line->multicurrency_subprice,
999 $line->ref_ext,
1000 1
1001 );
1002 if ($result < 0) {
1003 $this->error = $this->db->lasterror();
1004 dol_print_error($this->db);
1005 $this->db->rollback();
1006 return -1;
1007 }
1008
1009 // Defined the new fk_parent_line
1010 if ($result > 0 && $line->product_type == 9) {
1011 $fk_parent_line = $result;
1012 }
1013 }
1014 }
1015 }
1016
1017 /*
1018 * Insert lines coming from the template invoice
1019 */
1020 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1021 dol_syslog("There is ".count($_facrec->lines)." lines from recurring invoice");
1022 $fk_parent_line = 0;
1023
1024 foreach ($_facrec->lines as $i => $val) {
1025 // Reset fk_parent_line for no child products and special product
1026 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1027 $fk_parent_line = 0;
1028 }
1029
1030 // For line from template invoice, we use data from template invoice
1031 /*
1032 if ($_facrec->lines[$i]->fk_product) {
1033 $prod = new Product($this->db);
1034 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
1035 }
1036
1037 $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
1038 $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
1039 if (empty($tva_tx)) $tva_npr=0;
1040 $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
1041 $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
1042 */
1043 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
1044 $tva_npr = $_facrec->lines[$i]->info_bits;
1045 if (empty($tva_tx)) {
1046 $tva_npr = 0;
1047 }
1048 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1049 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1050
1051 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1052 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1053
1054 // If buyprice not defined from template invoice, we try to guess the best value
1055 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1056 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1057 $producttmp = new ProductFournisseur($this->db);
1058 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1059
1060 // If margin module defined on costprice, we try the costprice
1061 // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
1062 // else we get the best supplier price
1063 if (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($producttmp->cost_price)) {
1064 $buyprice = $producttmp->cost_price;
1065 } elseif (isModEnabled('stock') && (getDolGlobalString('MARGIN_TYPE') == 'costprice' || getDolGlobalString('MARGIN_TYPE') == 'pmp') && !empty($producttmp->pmp)) {
1066 $buyprice = $producttmp->pmp;
1067 } else {
1068 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1069 if ($producttmp->product_fourn_price_id > 0) {
1070 $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
1071 }
1072 }
1073 }
1074 }
1075
1076 $result_insert = $this->addline(
1077 $_facrec->lines[$i]->desc,
1078 $_facrec->lines[$i]->subprice,
1079 $_facrec->lines[$i]->qty,
1080 $tva_tx,
1081 $localtax1_tx,
1082 $localtax2_tx,
1083 $_facrec->lines[$i]->fk_product,
1084 $_facrec->lines[$i]->remise_percent,
1085 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
1086 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
1087 0,
1088 $tva_npr,
1089 0, // fk_remise_except
1090 'HT',
1091 0,
1092 $_facrec->lines[$i]->product_type,
1093 $_facrec->lines[$i]->rang,
1094 $_facrec->lines[$i]->special_code,
1095 '',
1096 0,
1097 $fk_parent_line,
1098 $fk_product_fournisseur_price,
1099 $buyprice,
1100 $_facrec->lines[$i]->label,
1101 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1102 100, // situation percent is undefined on recurring invoice lines
1103 0, // fk_prev_id
1104 $_facrec->lines[$i]->fk_unit,
1105 $_facrec->lines[$i]->multicurrency_subprice,
1106 $_facrec->lines[$i]->ref_ext,
1107 1
1108 );
1109
1110 // Defined the new fk_parent_line
1111 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1112 $fk_parent_line = $result_insert;
1113 }
1114
1115 if ($result_insert < 0) {
1116 $error++;
1117 $this->error = $this->db->error();
1118 break;
1119 }
1120 }
1121 }
1122
1123 if (!$error) {
1124 $result = $this->update_price(1, 'auto', 0, $mysoc);
1125 if ($result > 0) {
1126 $action = 'create';
1127
1128 // Actions on extra fields
1129 $result = $this->insertExtraFields();
1130 if ($result < 0) {
1131 $error++;
1132 }
1133
1134 if (!$error && !$notrigger) {
1135 // Call trigger
1136 $result = $this->call_trigger('BILL_CREATE', $user);
1137 if ($result < 0) {
1138 $error++;
1139 }
1140 }
1141
1142 if (!$error) {
1143 $this->db->commit();
1144 return $this->id;
1145 } else {
1146 $this->db->rollback();
1147 return -4;
1148 }
1149 } else {
1150 $this->error = $langs->trans('FailedToUpdatePrice');
1151 $this->db->rollback();
1152 return -3;
1153 }
1154 } else {
1155 dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
1156 $this->db->rollback();
1157 return -2;
1158 }
1159 } else {
1160 $this->error = $this->db->error();
1161 $this->db->rollback();
1162 return -1;
1163 }
1164 }
1165
1166
1174 public function createFromCurrent(User $user, $invertdetail = 0)
1175 {
1176 // Source invoice load
1177 $facture = new Facture($this->db);
1178
1179 // Retrieve all extrafield
1180 // fetch optionals attributes and labels
1181 $this->fetch_optionals();
1182
1183 if (!empty($this->array_options)) {
1184 $facture->array_options = $this->array_options;
1185 }
1186
1187 foreach ($this->lines as &$line) {
1188 $line->fetch_optionals(); //fetch extrafields
1189 }
1190
1191 $facture->fk_facture_source = $this->fk_facture_source;
1192 $facture->type = $this->type;
1193 $facture->subtype = $this->subtype;
1194 $facture->socid = $this->socid;
1195 $facture->date = $this->date;
1196 $facture->date_pointoftax = $this->date_pointoftax;
1197 $facture->note_public = $this->note_public;
1198 $facture->note_private = $this->note_private;
1199 $facture->ref_client = $this->ref_client;
1200 $facture->ref_customer = $this->ref_customer;
1201 $facture->model_pdf = $this->model_pdf;
1202 $facture->fk_project = $this->fk_project;
1203 $facture->cond_reglement_id = $this->cond_reglement_id;
1204 $facture->mode_reglement_id = $this->mode_reglement_id;
1205 //$facture->remise_absolue = $this->remise_absolue;
1206 //$facture->remise_percent = $this->remise_percent; // TODO deprecated
1207
1208 $facture->origin = $this->origin;
1209 $facture->origin_id = $this->origin_id;
1210 $facture->fk_account = $this->fk_account;
1211
1212 $facture->lines = $this->lines; // Array of lines of invoice
1213 $facture->situation_counter = $this->situation_counter;
1214 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1215 $facture->situation_final = $this->situation_final;
1216
1217 $facture->retained_warranty = $this->retained_warranty;
1218 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1219 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1220
1221 $facture->fk_user_author = $user->id;
1222 $facture->user_creation_id = $user->id;
1223
1224
1225 // Loop on each line of new invoice
1226 foreach ($facture->lines as $i => $tmpline) {
1227 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1228 if ($invertdetail) {
1229 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1230 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1231 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1232 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1233 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1234 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1235 $facture->lines[$i]->ref_ext = '';
1236 }
1237 }
1238
1239 dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1240
1241 $facid = $facture->create($user);
1242 if ($facid <= 0) {
1243 $this->error = $facture->error;
1244 $this->errors = $facture->errors;
1245 } elseif ($this->type == self::TYPE_SITUATION && getDolGlobalString('INVOICE_USE_SITUATION')) {
1246 $this->fetchObjectLinked(null, '', $this->id, 'facture');
1247
1248 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1249 foreach ($Tfk_object as $fk_object) {
1250 $facture->add_object_linked($typeObject, $fk_object);
1251 }
1252 }
1253
1254 $facture->add_object_linked('facture', $this->fk_facture_source);
1255 }
1256
1257 return $facid;
1258 }
1259
1260
1268 public function createFromClone(User $user, $fromid = 0)
1269 {
1270 global $conf, $hookmanager;
1271
1272 $error = 0;
1273
1274 $object = new Facture($this->db);
1275
1276 $this->db->begin();
1277
1278 $object->fetch($fromid);
1279 // fetch() clears $object->thirdparty, but the subsequent $object->create() path
1280 // reaches addLine() -> getLocalTaxesFromRate() -> get_localtax() and uses the
1281 // buyer thirdparty to decide whether IRPF/localtax2 applies. Without this fetch,
1282 // get_localtax() sees $thirdparty_buyer = null, returns 0 and the cloned lines
1283 // lose their localtax2_tx (see issue #29052).
1284 $object->fetch_thirdparty();
1285
1286 // Load source object
1287 $objFrom = clone $object;
1288
1289 // Change socid if needed
1290 if (!empty($this->socid) && $this->socid != $object->socid) {
1291 $objsoc = new Societe($this->db);
1292
1293 if ($objsoc->fetch($this->socid) > 0) {
1294 $object->socid = $objsoc->id;
1295 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1296 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1297 $object->fk_project = 0;
1298 $object->fk_delivery_address = 0;
1299 }
1300
1301 // TODO Change product price if multi-prices
1302 }
1303
1304 $object->id = 0;
1305 $object->statut = self::STATUS_DRAFT;
1306 $object->status = self::STATUS_DRAFT;
1307
1308 // Clear fields
1309 $object->date = (empty($this->date) ? dol_now() : $this->date);
1310 $object->user_creation_id = $user->id;
1311 $object->user_validation_id = null;
1312 $object->fk_user_author = $user->id;
1313 $object->fk_user_valid = null;
1314 $object->fk_facture_source = 0;
1315 $object->fk_fac_rec_source = 0;
1316 $object->date_creation = '';
1317 $object->date_modification = '';
1318 $object->date_validation = '';
1319 $object->ref_client = '';
1320 $object->ref_customer = '';
1321 $object->close_code = '';
1322 $object->close_note = '';
1323 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1324 $object->note_private = '';
1325 $object->note_public = '';
1326 }
1327
1328 // Loop on each line of new invoice
1329 foreach ($object->lines as $i => $line) {
1330 '@phan-var-force FactureLigne $line';
1331 if (($line->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1332 unset($object->lines[$i]);
1333 continue;
1334 }
1335
1336 // Block to update dates of service (month by month only if previously filled and similar to start and end of month)
1337 // If it's a service with start and end dates
1338 if (getDolGlobalString('INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1339 // Get the dates
1340 $start = dol_getdate($line->date_start);
1341 $end = dol_getdate($line->date_end);
1342
1343 // Get the first and last day of the month
1344 $first = dol_get_first_day($start['year'], $start['mon']);
1345 $last = dol_get_last_day($end['year'], $end['mon']);
1346
1347 //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1348 //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1349 // If start date is first date of month and end date is last date of month
1350 if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1351 && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1352 $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1353 $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1354 $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1355 $object->lines[$i]->date_start = $newFirst;
1356 $object->lines[$i]->date_end = $newLast;
1357 }
1358 }
1359
1360 $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1361 }
1362
1363 // Create clone
1364 $object->context['createfromclone'] = 'createfromclone';
1365 $result = $object->create($user);
1366 if ($result < 0) {
1367 $error++;
1368 $this->error = $object->error;
1369 $this->errors = $object->errors;
1370 } else {
1371 // copy internal contacts
1372 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1373 $error++;
1374 $this->error = $object->error;
1375 $this->errors = $object->errors;
1376 } elseif ($object->socid == $objFrom->socid) {
1377 // copy external contacts if same company
1378 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1379 $error++;
1380 $this->error = $object->error;
1381 $this->errors = $object->errors;
1382 }
1383 }
1384 }
1385
1386 if (!$error) {
1387 // Hook of thirdparty module
1388 if (is_object($hookmanager)) {
1389 $parameters = array('objFrom' => $objFrom);
1390 $action = '';
1391 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1392 if ($reshook < 0) {
1393 $this->setErrorsFromObject($hookmanager);
1394 $error++;
1395 }
1396 }
1397 }
1398
1399 unset($object->context['createfromclone']);
1400
1401 // End
1402 if (!$error) {
1403 $this->db->commit();
1404 return $object->id;
1405 } else {
1406 $this->db->rollback();
1407 return -1;
1408 }
1409 }
1410
1418 public function createFromOrder($object, User $user)
1419 {
1420 global $conf, $hookmanager;
1421
1422 $error = 0;
1423
1424 // Closed order
1425 $this->date = dol_now();
1426 $this->source = 0;
1427
1428 // Avoid updating the row ranks
1429 $this->context['createfromclone'] = 1;
1430
1431 $num = count($object->lines);
1432 for ($i = 0; $i < $num; $i++) {
1433 $line = new FactureLigne($this->db);
1434 $src_line = $object->lines[$i];
1435 '@phan-var-force FactureLigne $src_line';
1436 $line->libelle = $src_line->libelle; // deprecated
1437 $line->label = $src_line->label;
1438 $line->desc = $src_line->desc;
1439 $line->subprice = $src_line->subprice;
1440 $line->total_ht = $src_line->total_ht;
1441 $line->total_tva = $src_line->total_tva;
1442 $line->total_localtax1 = $src_line->total_localtax1;
1443 $line->total_localtax2 = $src_line->total_localtax2;
1444 $line->total_ttc = $src_line->total_ttc;
1445 $line->vat_src_code = $src_line->vat_src_code;
1446 $line->tva_tx = $src_line->tva_tx;
1447 $line->localtax1_tx = $src_line->localtax1_tx;
1448 $line->localtax2_tx = $src_line->localtax2_tx;
1449 $line->qty = $src_line->qty;
1450 $line->fk_remise_except = $src_line->fk_remise_except;
1451 $line->remise_percent = $src_line->remise_percent;
1452 $line->fk_product = $src_line->fk_product;
1453 $line->info_bits = $src_line->info_bits;
1454 $line->product_type = $src_line->product_type;
1455 $line->rang = $src_line->rang;
1456 $line->special_code = $src_line->special_code;
1457 $line->fk_parent_line = $src_line->fk_parent_line;
1458 $line->fk_unit = $src_line->fk_unit;
1459 $line->date_start = $src_line->date_start;
1460 $line->date_end = $src_line->date_end;
1461
1462 // Multicurrency
1463 $line->fk_multicurrency = $src_line->fk_multicurrency;
1464 $line->multicurrency_code = $src_line->multicurrency_code;
1465 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1466 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1467 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1468 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1469
1470 $line->fk_fournprice = $src_line->fk_fournprice;
1471 $marginInfos = getMarginInfos($src_line->subprice, $src_line->remise_percent, $src_line->tva_tx, $src_line->localtax1_tx, $src_line->localtax2_tx, $src_line->fk_fournprice, $src_line->pa_ht);
1472 $line->pa_ht = $marginInfos[0];
1473
1474 // get extrafields from original line
1475 $src_line->fetch_optionals();
1476 foreach ($src_line->array_options as $options_key => $value) {
1477 $line->array_options[$options_key] = $value;
1478 }
1479
1480 $this->lines[$i] = $line;
1481 }
1482
1483 $this->socid = $object->socid;
1484 $this->fk_project = $object->fk_project;
1485 $this->fk_account = $object->fk_account;
1486 $this->cond_reglement_id = $object->cond_reglement_id;
1487 $this->mode_reglement_id = $object->mode_reglement_id;
1488 $this->fk_incoterms = $object->fk_incoterms;
1489 $this->location_incoterms = $object->location_incoterms;
1490 $this->availability_id = $object->availability_id;
1491 $this->demand_reason_id = $object->demand_reason_id;
1492 $this->delivery_date = $object->delivery_date;
1493 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1494 $this->contact_id = $object->contact_id;
1495 $this->ref_client = $object->ref_client;
1496
1497 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1498 $this->note_private = $object->note_private;
1499 $this->note_public = $object->note_public;
1500 }
1501
1502 $this->module_source = $object->module_source;
1503 $this->pos_source = $object->pos_source;
1504
1505 $this->origin = $object->element;
1506 $this->origin_type = $object->element;
1507 $this->origin_id = $object->id;
1508
1509 $this->fk_user_author = $user->id;
1510
1511 // get extrafields from original line
1512 $object->fetch_optionals();
1513 foreach ($object->array_options as $options_key => $value) {
1514 $this->array_options[$options_key] = $value;
1515 }
1516
1517 // Possibility to add external linked objects with hooks
1518 $this->linked_objects[$this->origin] = $this->origin_id;
1519 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1520 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1521 }
1522
1523 $ret = $this->create($user);
1524
1525 if ($ret > 0) {
1526 // Actions hooked (by external module)
1527 $hookmanager->initHooks(array('invoicedao'));
1528
1529 $parameters = array('objFrom' => $object);
1530 $action = '';
1531 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1532 if ($reshook < 0) {
1533 $this->setErrorsFromObject($hookmanager);
1534 $error++;
1535 }
1536
1537 if (!$error) {
1538 return 1;
1539 } else {
1540 return -1;
1541 }
1542 } else {
1543 return -1;
1544 }
1545 }
1546
1555 public function createFromContract($object, User $user, $lines = array())
1556 {
1557 global $conf, $hookmanager;
1558
1559 $error = 0;
1560
1561 // Closed order
1562 $this->date = dol_now();
1563 $this->source = 0;
1564
1565 $use_all_lines = empty($lines);
1566 $num = count($object->lines);
1567 for ($i = 0; $i < $num; $i++) {
1568 if (!$use_all_lines && !in_array($object->lines[$i]->id, $lines)) {
1569 continue;
1570 }
1571
1572 $line = new FactureLigne($this->db);
1573
1574 $line->libelle = $object->lines[$i]->libelle; // deprecated
1575 $line->label = $object->lines[$i]->label;
1576 $line->desc = $object->lines[$i]->desc;
1577 $line->subprice = $object->lines[$i]->subprice;
1578 $line->total_ht = $object->lines[$i]->total_ht;
1579 $line->total_tva = $object->lines[$i]->total_tva;
1580 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1581 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1582 $line->total_ttc = $object->lines[$i]->total_ttc;
1583 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1584 $line->tva_tx = $object->lines[$i]->tva_tx;
1585 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1586 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1587 $line->qty = $object->lines[$i]->qty;
1588 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1589 $line->remise_percent = $object->lines[$i]->remise_percent;
1590 $line->fk_product = $object->lines[$i]->fk_product;
1591 $line->info_bits = $object->lines[$i]->info_bits;
1592 $line->product_type = $object->lines[$i]->product_type;
1593 $line->rang = $object->lines[$i]->rang;
1594 $line->special_code = $object->lines[$i]->special_code;
1595 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1596 $line->fk_unit = $object->lines[$i]->fk_unit;
1597 $line->date_start = $object->lines[$i]->date_start;
1598 $line->date_end = $object->lines[$i]->date_end;
1599
1600 // Multicurrency
1601 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1602 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1603 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1604 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1605 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1606 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1607
1608 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1609 $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);
1610 $line->pa_ht = $marginInfos[0];
1611
1612 // get extrafields from original line
1613 $object->lines[$i]->fetch_optionals();
1614 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1615 $line->array_options[$options_key] = $value;
1616 }
1617
1618 $this->lines[$i] = $line;
1619 }
1620
1621 $this->socid = $object->socid;
1622 $this->fk_project = $object->fk_project;
1623 $this->fk_account = $object->fk_account;
1624 $this->cond_reglement_id = $object->cond_reglement_id;
1625 $this->mode_reglement_id = $object->mode_reglement_id;
1626 $this->availability_id = $object->availability_id;
1627 $this->demand_reason_id = $object->demand_reason_id;
1628 $this->delivery_date = $object->delivery_date;
1629 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1630 $this->contact_id = $object->contact_id;
1631 $this->ref_client = $object->ref_client;
1632
1633 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1634 $this->note_private = $object->note_private;
1635 $this->note_public = $object->note_public;
1636 }
1637
1638 $this->module_source = $object->module_source;
1639 $this->pos_source = $object->pos_source;
1640
1641 $this->origin = $object->element;
1642 $this->origin_id = $object->id;
1643
1644 $this->fk_user_author = $user->id;
1645
1646 // get extrafields from original line
1647 $object->fetch_optionals();
1648 foreach ($object->array_options as $options_key => $value) {
1649 $this->array_options[$options_key] = $value;
1650 }
1651
1652 // Possibility to add external linked objects with hooks
1653 $this->linked_objects[$this->origin] = $this->origin_id;
1654 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1655 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1656 }
1657
1658 $ret = $this->create($user);
1659
1660 if ($ret > 0) {
1661 // Actions hooked (by external module)
1662 $hookmanager->initHooks(array('invoicedao'));
1663
1664 $parameters = array('objFrom' => $object);
1665 $action = '';
1666 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1667 if ($reshook < 0) {
1668 $this->setErrorsFromObject($hookmanager);
1669 $error++;
1670 }
1671
1672 if (!$error) {
1673 return 1;
1674 } else {
1675 return -1;
1676 }
1677 } else {
1678 return -1;
1679 }
1680 }
1681
1694 public static function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1695 {
1696 global $conf, $langs, $hookmanager, $action;
1697
1698 if (! in_array($origin->element, array('propal', 'commande'))) {
1699 $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1700 return null;
1701 }
1702
1703 if (empty($date)) {
1704 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1705 return null;
1706 }
1707
1708 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1709
1710 if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1711 $origin->error = 'ErrorDateIsInFuture';
1712 return null;
1713 }
1714
1715 if ($payment_terms_id <= 0) {
1716 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1717 return null;
1718 }
1719
1720 $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1721
1722 if (empty($payment_conditions_deposit_percent)) {
1723 $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1724 return null;
1725 }
1726
1727 if (empty($origin->deposit_percent)) {
1728 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1729 return null;
1730 }
1731
1732 $deposit = new self($origin->db);
1733 $deposit->socid = $origin->socid;
1734 $deposit->type = self::TYPE_DEPOSIT;
1735 $deposit->fk_project = $origin->fk_project;
1736 $deposit->ref_client = $origin->ref_client;
1737 $deposit->date = $date;
1738 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1739 $deposit->cond_reglement_id = $payment_terms_id;
1740 $deposit->availability_id = $origin->availability_id;
1741 $deposit->demand_reason_id = $origin->demand_reason_id;
1742 $deposit->fk_account = $origin->fk_account;
1743 $deposit->fk_incoterms = $origin->fk_incoterms;
1744 $deposit->location_incoterms = $origin->location_incoterms;
1745 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1746 $deposit->multicurrency_code = $origin->multicurrency_code;
1747 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1748 $deposit->module_source = $origin->module_source;
1749 $deposit->pos_source = $origin->pos_source;
1750 $deposit->model_pdf = 'crabe';
1751
1752 $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1753
1754 if (getDolGlobalString($modelByTypeConfName)) {
1755 $deposit->model_pdf = getDolGlobalString($modelByTypeConfName);
1756 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
1757 $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF');
1758 }
1759
1760 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1761 $deposit->note_private = $origin->note_private;
1762 $deposit->note_public = $origin->note_public;
1763 }
1764
1765 $deposit->origin = $origin->element;
1766 $deposit->origin_id = $origin->id;
1767
1768 $origin->fetch_optionals();
1769
1770 foreach ($origin->array_options as $extrakey => $value) {
1771 $deposit->array_options[$extrakey] = $value;
1772 }
1773
1774 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1775
1776 foreach ($overrideFields as $key => $value) {
1777 $deposit->$key = $value;
1778 }
1779
1780 $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1781
1782 $origin->db->begin();
1783
1784 // Facture::create() also imports contact from origin
1785 $createReturn = $deposit->create($user, $notrigger);
1786
1787 if ($createReturn <= 0) {
1788 $origin->db->rollback();
1789 $origin->error = $deposit->error;
1790 $origin->errors = $deposit->errors;
1791 return null;
1792 }
1793
1794 $amount_ttc_diff = 0;
1795 $amountdeposit = array();
1796 $descriptions = array();
1797
1798 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1799 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1800
1801 $TTotalByTva = array();
1802 foreach ($origin->lines as &$line) {
1803 if (!empty($line->special_code)) {
1804 continue;
1805 }
1806 $key = $line->tva_tx;
1807 if (!array_key_exists($key, $TTotalByTva)) {
1808 $TTotalByTva[$key] = 0;
1809 $descriptions[$key] = '';
1810 }
1811 $TTotalByTva[$key] += $line->total_ttc;
1812 $descriptions[$key] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1813 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1814 $descriptions[$key] .= $langs->trans('Qty') . ' : ' . $line->qty;
1815 $descriptions[$key] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1816 }
1817
1818 foreach ($TTotalByTva as $tva => &$total) {
1819 $coef = $total / $origin->total_ttc; // Calc coef
1820 $am = $amount * $coef;
1821 $amount_ttc_diff += $am;
1822 $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
1823 }
1824 } else {
1825 $totalamount = 0;
1826 $lines = $origin->lines;
1827 $numlines = count($lines);
1828 for ($i = 0; $i < $numlines; $i++) {
1829 if (empty($lines[$i]->qty)) {
1830 continue; // We discard qty=0, it is an option
1831 }
1832 if (!empty($lines[$i]->special_code)) {
1833 continue; // We discard special_code (frais port, ecotaxe, option, ...)
1834 }
1835
1836 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1837 $tva_tx = $lines[$i]->tva_tx;
1838 $amountdeposit[$tva_tx] += ((float) $lines[$i]->total_ht * (float) $origin->deposit_percent) / 100;
1839 $descriptions[$tva_tx] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1840 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1841 $descriptions[$tva_tx] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1842 $descriptions[$tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1843 }
1844
1845 if ($totalamount == 0) {
1846 $amountdeposit[0] = 0;
1847 }
1848
1849 $amount_ttc_diff = $amountdeposit[0];
1850 }
1851
1852 foreach ($amountdeposit as $tva => $amount) {
1853 if (empty($amount)) {
1854 continue;
1855 }
1856
1857 $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1858
1859 // Hidden conf
1860 if (getDolGlobalString('INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1861 $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1862 }
1863
1864 $addlineResult = $deposit->addline(
1865 $descline,
1866 $amount, // subprice
1867 1, // quantity
1868 $tva, // vat rate
1869 0, // localtax1_tx
1870 0, // localtax2_tx
1871 (!getDolGlobalString('INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1872 0, // remise_percent
1873 0, // date_start
1874 0, // date_end
1875 0,
1876 0, // info_bits
1877 0,
1878 'HT',
1879 0,
1880 0, // product_type
1881 1,
1882 0, // special_code
1883 $deposit->origin,
1884 0,
1885 0,
1886 0,
1887 0
1888 //,$langs->trans('Deposit') //Deprecated
1889 );
1890
1891 if ($addlineResult < 0) {
1892 $origin->db->rollback();
1893 $origin->error = $deposit->error;
1894 $origin->errors = $deposit->errors;
1895 return null;
1896 }
1897 }
1898
1899 $diff = $deposit->total_ttc - $amount_ttc_diff;
1900
1901 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1902 $deposit->fetch_lines();
1903 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1904
1905 $updatelineResult = $deposit->updateline(
1906 $deposit->lines[0]->id,
1907 $deposit->lines[0]->desc,
1908 $subprice_diff,
1909 $deposit->lines[0]->qty,
1910 $deposit->lines[0]->remise_percent,
1911 $deposit->lines[0]->date_start,
1912 $deposit->lines[0]->date_end,
1913 $deposit->lines[0]->tva_tx,
1914 0,
1915 0,
1916 'HT',
1917 $deposit->lines[0]->info_bits,
1918 $deposit->lines[0]->product_type,
1919 0,
1920 0,
1921 0,
1922 $deposit->lines[0]->pa_ht,
1923 $deposit->lines[0]->label,
1924 0,
1925 array(),
1926 100
1927 );
1928
1929 if ($updatelineResult < 0) {
1930 $origin->db->rollback();
1931 $origin->error = $deposit->error;
1932 $origin->errors = $deposit->errors;
1933 return null;
1934 }
1935 }
1936
1937 $hookmanager->initHooks(array('invoicedao'));
1938
1939 $parameters = array('objFrom' => $origin);
1940 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
1941 // modified by hook
1942 if ($reshook < 0) {
1943 $origin->db->rollback();
1944 $origin->error = $hookmanager->error;
1945 $origin->errors = $hookmanager->errors;
1946 return null;
1947 }
1948
1949 if (!empty($autoValidateDeposit)) {
1950 $validateReturn = $deposit->validate($user, '', 0, $notrigger);
1951
1952 if ($validateReturn < 0) {
1953 $origin->db->rollback();
1954 $origin->error = $deposit->error;
1955 $origin->errors = $deposit->errors;
1956 return null;
1957 }
1958 }
1959
1960 unset($deposit->context['createdepositfromorigin']);
1961
1962 $origin->db->commit();
1963
1964 return $deposit;
1965 }
1966
1974 public function getTooltipContentArray($params)
1975 {
1976 global $conf, $langs, $mysoc, $user;
1977
1978 $langs->load('bills');
1979
1980 $datas = [];
1981 $moretitle = $params['moretitle'] ?? '';
1982
1983 $picto = $this->picto;
1984 if ($this->type == self::TYPE_REPLACEMENT) {
1985 $picto .= 'r'; // Replacement invoice
1986 }
1987 if ($this->type == self::TYPE_CREDIT_NOTE) {
1988 $picto .= 'a'; // Credit note
1989 }
1990 if ($this->type == self::TYPE_DEPOSIT) {
1991 $picto .= 'd'; // Deposit invoice
1992 }
1993
1994 if ($user->hasRight("facture", "read")) {
1995 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
1996
1997 $datas['picto'] .= '&nbsp;'.$this->getLibType(1);
1998
1999 // Complete datas
2000 if (!empty($params['fromajaxtooltip']) && !isset($this->totalpaid)) {
2001 $this->totalpaid = $this->getSommePaiement(0);
2002 }
2003 if (!empty($params['fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2004 $this->totalcreditnotes = $this->getSumCreditNotesUsed(0);
2005 }
2006 if (!empty($params['fromajaxtooltip']) && !isset($this->totaldeposits)) {
2007 $this->totaldeposits = $this->getSumDepositsUsed(0);
2008 }
2009 if (isset($this->status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2010 $datas['picto'] .= ' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2011 }
2012 if ($moretitle) {
2013 $datas['picto'] .= ' - '.$moretitle;
2014 }
2015 if (!empty($this->ref)) {
2016 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2017 }
2018 if (!empty($this->ref_customer)) {
2019 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
2020 }
2021 if (!empty($this->date)) {
2022 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
2023 }
2024 if (!empty($this->total_ht)) {
2025 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2026 }
2027 if (!empty($this->total_tva)) {
2028 $datas['amountvat'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2029 }
2030 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2031 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2032 }
2033 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2034 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
2035 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2036 }
2037 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2038 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2039 }
2040 if (!empty($this->total_ttc)) {
2041 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2042 }
2043 }
2044
2045 return $datas;
2046 }
2047
2062 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
2063 {
2064 global $langs, $conf, $user;
2065
2066 if (!empty($conf->dol_no_mouse_hover)) {
2067 $notooltip = 1; // Force disable tooltips
2068 }
2069
2070 $result = '';
2071
2072 if ($option == 'withdraw') {
2073 $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
2074 } else {
2075 $url = DOL_URL_ROOT.'/compta/facture/card.php?id='.$this->id;
2076 }
2077
2078 if (!$user->hasRight("facture", "read")) {
2079 $option = 'nolink';
2080 }
2081
2082 if ($option !== 'nolink') {
2083 // Add param to save lastsearch_values or not
2084 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2085 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2086 $add_save_lastsearch_values = 1;
2087 }
2088 if ($add_save_lastsearch_values) {
2089 $url .= '&save_lastsearch_values=1';
2090 }
2091 }
2092
2093 if ($short) {
2094 return $url;
2095 }
2096
2097 $picto = $this->picto;
2098 if ($this->type == self::TYPE_REPLACEMENT) {
2099 $picto .= 'r'; // Replacement invoice
2100 }
2101 if ($this->type == self::TYPE_CREDIT_NOTE) {
2102 $picto .= 'a'; // Credit note
2103 }
2104 if ($this->type == self::TYPE_DEPOSIT) {
2105 $picto .= 'd'; // Deposit invoice
2106 }
2107
2108 $params = [
2109 'id' => $this->id,
2110 'objecttype' => $this->element,
2111 'moretitle' => $moretitle,
2112 'option' => $option,
2113 ];
2114 $classfortooltip = 'classfortooltip';
2115 $dataparams = '';
2116 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2117 $classfortooltip = 'classforajaxtooltip';
2118 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2119 $label = '';
2120 } else {
2121 $label = implode($this->getTooltipContentArray($params));
2122 }
2123
2124 $linkclose = ($target ? ' target="'.$target.'"' : '');
2125 if (empty($notooltip) && $user->hasRight("facture", "read")) {
2126 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2127 $label = $langs->trans("Invoice");
2128 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2129 }
2130 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2131 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2132 }
2133
2134 $linkstart = '<a href="'.$url.'"';
2135 $linkstart .= $linkclose.'>';
2136 $linkend = '</a>';
2137
2138 if ($option == 'nolink') {
2139 $linkstart = '';
2140 $linkend = '';
2141 }
2142
2143 $result .= $linkstart;
2144 if ($withpicto) {
2145 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2146 }
2147 if ($withpicto != 2) {
2148 $result .= ($max ? dol_trunc($this->ref, $max) : $this->ref);
2149 }
2150 $result .= $linkend;
2151
2152 if ($addlinktonotes) {
2153 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2154 if ($txttoshow) {
2155 //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
2156 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
2157 $result .= ' <span class="note inline-block">';
2158 $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
2159 $result .= img_picto('', 'note');
2160 $result .= '</a>';
2161 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
2162 //$result.='</a>';
2163 $result .= '</span>';
2164 }
2165 }
2166
2167 global $action, $hookmanager;
2168 $hookmanager->initHooks(array('invoicedao'));
2169 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value' => $save_lastsearch_value, 'target' => $target);
2170 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2171 if ($reshook > 0) {
2172 $result = $hookmanager->resPrint;
2173 } else {
2174 $result .= $hookmanager->resPrint;
2175 }
2176
2177 return $result;
2178 }
2179
2190 public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false)
2191 {
2192 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2193 return -1;
2194 }
2195
2196 $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2197 $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2198 $sql .= ', f.datef as df, f.date_pointoftax';
2199 $sql .= ', f.date_lim_reglement as dlr';
2200 $sql .= ', f.datec as datec';
2201 $sql .= ', f.date_valid as datev';
2202 $sql .= ', f.tms as datem';
2203 $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';
2204 $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
2205 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2206 $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2207 $sql .= ', f.fk_account';
2208 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2209 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2210 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2211 $sql .= ', f.fk_incoterms, f.location_incoterms';
2212 $sql .= ', f.module_source, f.pos_source';
2213 $sql .= ", i.libelle as label_incoterms";
2214 $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";
2215 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
2216 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2217 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
2218 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
2219
2220 if ($rowid) {
2221 $sql .= " WHERE f.rowid = ".((int) $rowid);
2222 } else {
2223 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
2224 if ($ref) {
2225 $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
2226 }
2227 if ($ref_ext) {
2228 $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
2229 }
2230 }
2231
2232 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2233 $resql = $this->db->query($sql);
2234 if ($resql) {
2235 if ($this->db->num_rows($resql)) {
2236 $obj = $this->db->fetch_object($resql);
2237
2238 $this->id = $obj->rowid;
2239 $this->entity = $obj->entity;
2240
2241 $this->ref = $obj->ref;
2242 $this->ref_client = $obj->ref_client;
2243 $this->ref_customer = $obj->ref_client;
2244 $this->ref_ext = $obj->ref_ext;
2245 $this->type = $obj->type;
2246 $this->subtype = $obj->subtype;
2247 $this->date = $this->db->jdate($obj->df);
2248 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2249 $this->date_creation = $this->db->jdate($obj->datec);
2250 $this->date_validation = $this->db->jdate($obj->datev);
2251 $this->date_modification = $this->db->jdate($obj->datem);
2252 $this->datem = $this->db->jdate($obj->datem);
2253 $this->total_ht = $obj->total_ht;
2254 $this->total_tva = $obj->total_tva;
2255 $this->total_localtax1 = $obj->localtax1;
2256 $this->total_localtax2 = $obj->localtax2;
2257 $this->total_ttc = $obj->total_ttc;
2258 $this->revenuestamp = $obj->revenuestamp;
2259 $this->paye = $obj->paye;
2260 $this->close_code = $obj->close_code;
2261 $this->close_note = $obj->close_note;
2262
2263 $this->socid = $obj->fk_soc;
2264 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2265
2266 $this->fk_project = $obj->fk_project;
2267 $this->project = null; // Clear if another value was already set by fetch_projet
2268
2269 $this->statut = $obj->status; // deprecated
2270 $this->status = $obj->status;
2271
2272 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2273 $this->mode_reglement_id = $obj->fk_mode_reglement;
2274 $this->mode_reglement_code = $obj->mode_reglement_code;
2275 $this->mode_reglement = $obj->mode_reglement_libelle;
2276 $this->cond_reglement_id = $obj->fk_cond_reglement;
2277 $this->cond_reglement_code = $obj->cond_reglement_code;
2278 $this->cond_reglement = $obj->cond_reglement_libelle;
2279 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2280 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2281 $this->fk_facture_source = $obj->fk_facture_source;
2282 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2283 $this->note = $obj->note_private; // deprecated
2284 $this->note_private = $obj->note_private;
2285 $this->note_public = $obj->note_public;
2286 $this->user_creation_id = $obj->fk_user_author;
2287 $this->user_validation_id = $obj->fk_user_valid;
2288 $this->user_modification_id = $obj->fk_user_modif;
2289 $this->fk_user_author = $obj->fk_user_author;
2290 $this->fk_user_valid = $obj->fk_user_valid;
2291 $this->fk_user_modif = $obj->fk_user_modif;
2292 $this->model_pdf = $obj->model_pdf;
2293 $this->last_main_doc = $obj->last_main_doc;
2294 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2295 $this->situation_counter = $obj->situation_counter;
2296 $this->situation_final = $obj->situation_final;
2297 $this->retained_warranty = $obj->retained_warranty;
2298 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2299 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2300
2301 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2302
2303 //Incoterms
2304 $this->fk_incoterms = $obj->fk_incoterms;
2305 $this->location_incoterms = $obj->location_incoterms;
2306 $this->label_incoterms = $obj->label_incoterms;
2307
2308 $this->module_source = $obj->module_source;
2309 $this->pos_source = $obj->pos_source;
2310
2311 // Multicurrency
2312 $this->fk_multicurrency = $obj->fk_multicurrency;
2313 $this->multicurrency_code = $obj->multicurrency_code;
2314 $this->multicurrency_tx = $obj->multicurrency_tx;
2315 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2316 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2317 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2318
2319 if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2321 }
2322
2323 // Retrieve all extrafield
2324 // fetch optionals attributes and labels
2325 $this->fetch_optionals();
2326
2327 // Lines
2328 $this->lines = array();
2329
2330 $result = $this->fetch_lines();
2331 if ($result < 0) {
2332 $this->error = $this->db->error();
2333 return -3;
2334 }
2335
2336 $this->db->free($resql);
2337
2338 return 1;
2339 } else {
2340 $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2341
2342 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2343 return 0;
2344 }
2345 } else {
2346 $this->error = $this->db->lasterror();
2347 return -1;
2348 }
2349 }
2350
2351
2352 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2361 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2362 {
2363 // phpcs:enable
2364 $this->lines = array();
2365
2366 $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,';
2367 $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,';
2368 $sql .= ' l.situation_percent, l.fk_prev_id,';
2369 $sql .= ' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2370 $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2371 $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,';
2372 $sql .= ' l.fk_unit,';
2373 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2374 $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';
2375 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
2376 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2377 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2378 $sql .= ' ORDER BY l.rang, l.rowid';
2379
2380 dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2381 $result = $this->db->query($sql);
2382 if ($result) {
2383 $num = $this->db->num_rows($result);
2384 $i = 0;
2385 while ($i < $num) {
2386 $objp = $this->db->fetch_object($result);
2387 $line = new FactureLigne($this->db);
2388
2389 $line->id = $objp->rowid;
2390 $line->rowid = $objp->rowid; // deprecated
2391 $line->fk_facture = $objp->fk_facture;
2392 $line->label = $objp->custom_label; // deprecated
2393 $line->desc = $objp->description; // Description line
2394 $line->description = $objp->description; // Description line
2395 $line->product_type = $objp->product_type; // Type of line
2396 $line->ref = $objp->product_ref; // Ref product
2397 $line->product_ref = $objp->product_ref; // Ref product
2398 $line->libelle = $objp->product_label; // deprecated
2399 $line->product_label = $objp->product_label; // Label product
2400 $line->product_barcode = $objp->product_barcode; // Barcode number product
2401 $line->product_desc = $objp->product_desc; // Description product
2402 $line->fk_product_type = $objp->fk_product_type; // Type of product
2403 $line->qty = $objp->qty;
2404 $line->subprice = $objp->subprice;
2405 $line->ref_ext = $objp->ref_ext; // line external ref
2406
2407 $line->vat_src_code = $objp->vat_src_code;
2408 $line->tva_tx = $objp->tva_tx;
2409 $line->localtax1_tx = $objp->localtax1_tx;
2410 $line->localtax2_tx = $objp->localtax2_tx;
2411 $line->localtax1_type = $objp->localtax1_type;
2412 $line->localtax2_type = $objp->localtax2_type;
2413 $line->remise_percent = $objp->remise_percent;
2414 $line->fk_remise_except = $objp->fk_remise_except;
2415 $line->fk_product = $objp->fk_product;
2416 $line->date_start = $this->db->jdate($objp->date_start);
2417 $line->date_end = $this->db->jdate($objp->date_end);
2418 $line->info_bits = $objp->info_bits;
2419 $line->total_ht = $objp->total_ht;
2420 $line->total_tva = $objp->total_tva;
2421 $line->total_localtax1 = $objp->total_localtax1;
2422 $line->total_localtax2 = $objp->total_localtax2;
2423 $line->total_ttc = $objp->total_ttc;
2424
2425 $line->fk_fournprice = $objp->fk_fournprice;
2426 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2427 $line->pa_ht = $marginInfos[0];
2428 $line->marge_tx = (string) $marginInfos[1];
2429 $line->marque_tx = (string) $marginInfos[2];
2430 $line->rang = $objp->rang;
2431 $line->special_code = $objp->special_code;
2432 $line->fk_parent_line = $objp->fk_parent_line;
2433 $line->situation_percent = $objp->situation_percent;
2434 $line->fk_prev_id = $objp->fk_prev_id;
2435 $line->fk_unit = $objp->fk_unit;
2436
2437 $line->batch = $objp->batch;
2438 $line->fk_warehouse = $objp->fk_warehouse;
2439
2440 // Accountancy
2441 $line->fk_accounting_account = $objp->fk_code_ventilation;
2442
2443 // Multicurrency
2444 $line->fk_multicurrency = $objp->fk_multicurrency;
2445 $line->multicurrency_code = $objp->multicurrency_code;
2446 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2447 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2448 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2449 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2450
2451 $line->fetch_optionals();
2452
2453 // multilangs
2454 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2455 $tmpproduct = new Product($this->db);
2456 $tmpproduct->fetch($objp->fk_product);
2457 $tmpproduct->getMultiLangs();
2458
2459 $line->multilangs = $tmpproduct->multilangs;
2460 }
2461
2462 $this->lines[$i] = $line;
2463
2464 $i++;
2465 }
2466 $this->db->free($result);
2467 return 1;
2468 } else {
2469 $this->error = $this->db->error();
2470 return -3;
2471 }
2472 }
2473
2481 {
2482 global $conf;
2483
2484 $this->tab_previous_situation_invoice = array();
2485 $this->tab_next_situation_invoice = array();
2486
2487 $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2488 $sql .= " WHERE rowid <> ".((int) $this->id);
2489 $sql .= ' AND entity = '.((int) $this->entity);
2490 $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2491 $sql .= ' ORDER BY situation_counter ASC';
2492
2493 dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2494 $result = $this->db->query($sql);
2495 if ($result && $this->db->num_rows($result) > 0) {
2496 while ($objp = $this->db->fetch_object($result)) {
2497 $invoice = new Facture($this->db);
2498 if ($invoice->fetch($objp->rowid) > 0) {
2499 if ($objp->situation_counter < $this->situation_counter
2500 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2501 ) {
2502 $this->tab_previous_situation_invoice[] = $invoice;
2503 } else {
2504 $this->tab_next_situation_invoice[] = $invoice;
2505 }
2506 }
2507 }
2508 }
2509 }
2510
2518 public function update(User $user, $notrigger = 0)
2519 {
2520 $error = 0;
2521
2522 // Clean parameters
2523 if (empty($this->type)) {
2524 $this->type = self::TYPE_STANDARD;
2525 }
2526 if (isset($this->subtype)) {
2527 $this->subtype = (int) trim((string) $this->subtype);
2528 }
2529 if (isset($this->ref)) {
2530 $this->ref = trim($this->ref);
2531 }
2532 if (isset($this->ref_ext)) {
2533 $this->ref_ext = trim($this->ref_ext);
2534 }
2535 // deprecated
2536 if (!empty($this->ref_client)) {
2537 $this->ref_client = trim($this->ref_client);
2538 }
2539 if (!empty($this->ref_customer)) {
2540 $this->ref_customer = trim($this->ref_customer);
2541 }
2542 if (isset($this->increment)) {
2543 $this->increment = trim($this->increment);
2544 }
2545 if (isset($this->close_code)) {
2546 $this->close_code = trim($this->close_code);
2547 }
2548 if (isset($this->close_note)) {
2549 $this->close_note = trim($this->close_note);
2550 }
2551 if (isset($this->note) || isset($this->note_private)) {
2552 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2553 }
2554 if (isset($this->note) || isset($this->note_private)) {
2555 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2556 }
2557 if (isset($this->note_public)) {
2558 $this->note_public = trim($this->note_public);
2559 }
2560 if (isset($this->model_pdf)) {
2561 $this->model_pdf = trim($this->model_pdf);
2562 }
2563 if (isset($this->import_key)) {
2564 $this->import_key = trim($this->import_key);
2565 }
2566 if (isset($this->retained_warranty)) {
2567 $this->retained_warranty = (float) $this->retained_warranty;
2568 }
2569 if (!isset($this->user_creation_id) && isset($this->fk_user_author) ) {
2570 $this->user_creation_id = $this->fk_user_author;
2571 }
2572 if (!isset($this->user_validation_id) && isset($this->fk_user_valid) ) {
2573 $this->user_validation_id = $this->fk_user_valid;
2574 }
2575
2576 // Update request
2577 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2578 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2579 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2580 $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
2581 $sql .= " subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) : "null").",";
2582 $sql .= " ref_client=".(!empty($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : (isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null")).",";
2583 $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2584 $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
2585 $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2586 $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2587 $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2588 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2589 $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
2590 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2591 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2592 $sql .= " total_tva=".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
2593 $sql .= " localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
2594 $sql .= " localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
2595 $sql .= " total_ht=".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
2596 $sql .= " total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
2597 $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? (float) $this->revenuestamp : "null").",";
2598 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
2599 $sql .= " fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) : "null").",";
2600 $sql .= " fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
2601 $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source : "null").",";
2602 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
2603 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
2604 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
2605 $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2606 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2607 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2608 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2609 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2610 $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : (int) $this->situation_cycle_ref).",";
2611 $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : (int) $this->situation_counter).",";
2612 $sql .= " situation_final=".(empty($this->situation_final) ? "0" : (int) $this->situation_final).",";
2613 $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : (float) $this->retained_warranty).",";
2614 $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2615 $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement : "null");
2616 $sql .= " WHERE rowid=".((int) $this->id);
2617
2618 $this->db->begin();
2619
2620 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2621 $resql = $this->db->query($sql);
2622 if (!$resql) {
2623 $error++;
2624 $this->errors[] = "Error ".$this->db->lasterror();
2625 }
2626
2627 if (!$error) {
2628 $result = $this->insertExtraFields();
2629 if ($result < 0) {
2630 $error++;
2631 }
2632 }
2633
2634 if (!$error && !$notrigger) {
2635 // Call trigger
2636 $result = $this->call_trigger('BILL_MODIFY', $user);
2637 if ($result < 0) {
2638 $error++;
2639 }
2640 // End call triggers
2641 }
2642
2643 // Commit or rollback
2644 if ($error) {
2645 foreach ($this->errors as $errmsg) {
2646 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2647 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2648 }
2649 $this->db->rollback();
2650 return -1 * $error;
2651 } else {
2652 $this->db->commit();
2653 return 1;
2654 }
2655 }
2656
2657
2658 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2665 public function insert_discount($idremise)
2666 {
2667 // phpcs:enable
2668 global $langs;
2669
2670 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2671 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2672
2673 $this->db->begin();
2674
2675 $remise = new DiscountAbsolute($this->db);
2676 $result = $remise->fetch($idremise);
2677
2678 if ($result > 0) {
2679 if ($remise->fk_facture) { // Protection against multiple submission
2680 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2681 $this->db->rollback();
2682 return -5;
2683 }
2684
2685 $facligne = new FactureLigne($this->db);
2686 $facligne->fk_facture = $this->id;
2687 $facligne->fk_remise_except = $remise->id;
2688 $facligne->desc = $remise->description; // Description ligne
2689 $facligne->vat_src_code = $remise->vat_src_code;
2690 $facligne->tva_tx = $remise->tva_tx;
2691 $facligne->subprice = -(float) $remise->amount_ht;
2692 $facligne->fk_product = 0; // Id produit predefini
2693 $facligne->qty = 1;
2694 $facligne->remise_percent = 0;
2695 $facligne->rang = -1;
2696 $facligne->info_bits = 2;
2697
2698 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
2699 $facligne->rang = 1;
2700 $linecount = count($this->lines);
2701 for ($ii = 1; $ii <= $linecount; $ii++) {
2702 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2703 }
2704 }
2705
2706 // Get buy/cost price of invoice that is source of discount
2707 if ($remise->fk_facture_source > 0) {
2708 $srcinvoice = new Facture($this->db);
2709 $srcinvoice->fetch($remise->fk_facture_source);
2710 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2711 $formmargin = new FormMargin($this->db);
2712 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2713 $facligne->pa_ht = $arraytmp['pa_total'];
2714 }
2715
2716 $facligne->total_ht = -(float) $remise->amount_ht;
2717 $facligne->total_tva = -(float) $remise->amount_tva;
2718 $facligne->total_ttc = -(float) $remise->amount_ttc;
2719
2720 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2721 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_amount_ht;
2722 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_amount_tva;
2723 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_amount_ttc;
2724
2725 $lineid = $facligne->insert();
2726 if ($lineid > 0) {
2727 $result = $this->update_price(1);
2728 if ($result > 0) {
2729 // Create link between discount and invoice line
2730 $result = $remise->link_to_invoice($lineid, 0);
2731 if ($result < 0) {
2732 $this->error = $remise->error;
2733 $this->db->rollback();
2734 return -4;
2735 }
2736
2737 $this->db->commit();
2738 return 1;
2739 } else {
2740 $this->error = $facligne->error;
2741 $this->db->rollback();
2742 return -1;
2743 }
2744 } else {
2745 $this->error = $facligne->error;
2746 $this->db->rollback();
2747 return -2;
2748 }
2749 } else {
2750 $this->db->rollback();
2751 return -3;
2752 }
2753 }
2754
2755 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2763 public function set_ref_client($ref_client, $notrigger = 0)
2764 {
2765 // phpcs:enable
2766 global $user;
2767
2768 $error = 0;
2769
2770 $this->db->begin();
2771
2772 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2773 if (empty($ref_client)) {
2774 $sql .= ' SET ref_client = NULL';
2775 } else {
2776 $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
2777 }
2778 $sql .= " WHERE rowid = ".((int) $this->id);
2779
2780 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2781 $resql = $this->db->query($sql);
2782 if (!$resql) {
2783 $this->errors[] = $this->db->error();
2784 $error++;
2785 }
2786
2787 if (!$error) {
2788 $this->ref_client = $ref_client; //deprecated
2789 $this->ref_customer = $ref_client;
2790 }
2791
2792 if (!$notrigger && empty($error)) {
2793 // Call trigger
2794 $result = $this->call_trigger('BILL_MODIFY', $user);
2795 if ($result < 0) {
2796 $error++;
2797 }
2798 // End call triggers
2799 }
2800
2801 if (!$error) {
2802 $this->ref_client = $ref_client; //deprecated
2803 $this->ref_customer = $ref_client;
2804
2805 $this->db->commit();
2806 return 1;
2807 } else {
2808 foreach ($this->errors as $errmsg) {
2809 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2810 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2811 }
2812 $this->db->rollback();
2813 return -1 * $error;
2814 }
2815 }
2816
2825 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2826 {
2827 global $langs, $conf;
2828 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2829
2830 $rowid = $this->id;
2831
2832 dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
2833
2834 // Test to avoid invoice deletion (allowed if draft)
2835 $result = $this->is_erasable();
2836
2837 if ($result <= 0) {
2838 return 0;
2839 }
2840
2841 $error = 0;
2842
2843 $this->db->begin();
2844
2845 if (!$error && !$notrigger) {
2846 // Call trigger
2847 $result = $this->call_trigger('BILL_DELETE', $user);
2848 if ($result < 0) {
2849 $error++;
2850 }
2851 // End call triggers
2852 }
2853
2854 // Removed extrafields
2855 if (!$error) {
2856 $result = $this->deleteExtraFields();
2857 if ($result < 0) {
2858 $error++;
2859 dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
2860 }
2861 }
2862
2863 if (!$error) {
2864 // Delete linked object
2865 $res = $this->deleteObjectLinked();
2866 if ($res < 0) {
2867 $error++;
2868 }
2869 }
2870
2871 if (!$error) {
2872 // If invoice was converted into a discount not yet consumed, we remove discount
2873 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
2874 $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
2875 $sql .= ' AND fk_facture_line IS NULL';
2876 $resql = $this->db->query($sql);
2877
2878 // If invoice has consumed discounts
2879 $this->fetch_lines();
2880 $list_rowid_det = array();
2881 foreach ($this->lines as $key => $invoiceline) {
2882 $list_rowid_det[] = $invoiceline->id;
2883 }
2884
2885 // Consumed discounts are freed
2886 if (count($list_rowid_det)) {
2887 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2888 $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
2889 $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
2890
2891 if (!$this->db->query($sql)) {
2892 $this->error = $this->db->error()." sql=".$sql;
2893 $this->errors[] = $this->error;
2894 $this->db->rollback();
2895 return -5;
2896 }
2897 }
2898
2899 // Remove other links to the deleted invoice
2900
2901 $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
2902 $sql .= ' SET fk_invoice = NULL';
2903 $sql .= ' WHERE fk_invoice = '.((int) $rowid);
2904
2905 if (!$this->db->query($sql)) {
2906 $this->error = $this->db->error()." sql=".$sql;
2907 $this->errors[] = $this->error;
2908 $this->db->rollback();
2909 return -5;
2910 }
2911
2912 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
2913 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
2914 $sql .= ' WHERE invoice_id = '.((int) $rowid);
2915
2916 if (!$this->db->query($sql)) {
2917 $this->error = $this->db->error()." sql=".$sql;
2918 $this->errors[] = $this->error;
2919 $this->db->rollback();
2920 return -5;
2921 }
2922
2923 // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
2924 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2925 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2926 $langs->load("agenda");
2927
2928 $num = count($this->lines);
2929 for ($i = 0; $i < $num; $i++) {
2930 if ($this->lines[$i]->fk_product > 0) {
2931 $mouvP = new MouvementStock($this->db);
2932 $mouvP->origin = &$this;
2933 $mouvP->setOrigin($this->element, $this->id);
2934 // We decrease stock for product
2935 if ($this->type == self::TYPE_CREDIT_NOTE) {
2936 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
2937 } else {
2938 $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
2939 }
2940 }
2941 }
2942 }
2943
2944 // Invoice line extrafileds
2945 $main = MAIN_DB_PREFIX.'facturedet';
2946 $ef = $main."_extrafields";
2947 $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
2948 // Delete invoice line
2949 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
2950
2951 if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact() >= 0) {
2952 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
2953
2954 $resql = $this->db->query($sql);
2955 if ($resql) {
2956 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2957 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2958 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2959
2960 // On efface le repertoire de pdf provisoire
2961 $ref = dol_sanitizeFileName($this->ref);
2962 if ($conf->facture->dir_output && !empty($this->ref)) {
2963 $dir = $conf->facture->dir_output."/".$ref;
2964 $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
2965 if (file_exists($file)) { // We must delete all files before deleting directory
2966 $ret = dol_delete_preview($this);
2967
2968 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2969 $langs->load("errors");
2970 $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
2971 $this->errors[] = $this->error;
2972 $this->db->rollback();
2973 return 0;
2974 }
2975 }
2976 if (file_exists($dir)) {
2977 if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
2978 $langs->load("errors");
2979 $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
2980 $this->errors[] = $this->error;
2981 $this->db->rollback();
2982 return 0;
2983 }
2984 }
2985 }
2986
2987 $this->db->commit();
2988 return 1;
2989 } else {
2990 $this->error = $this->db->lasterror()." sql=".$sql;
2991 $this->errors[] = $this->error;
2992 $this->db->rollback();
2993 return -6;
2994 }
2995 } else {
2996 $this->error = $this->db->lasterror()." sql=".$sql;
2997 $this->errors[] = $this->error;
2998 $this->db->rollback();
2999 return -4;
3000 }
3001 } else {
3002 $this->db->rollback();
3003 return -2;
3004 }
3005 }
3006
3007 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3019 public function set_paid($user, $close_code = '', $close_note = '')
3020 {
3021 // phpcs:enable
3022 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3023 return $this->setPaid($user, $close_code, $close_note);
3024 }
3025
3036 public function setPaid($user, $close_code = '', $close_note = '')
3037 {
3038 $error = 0;
3039
3040 if ($this->paye != 1) {
3041 $this->db->begin();
3042
3043 $now = dol_now();
3044
3045 dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
3046
3047 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3048 $sql .= ' fk_statut='.self::STATUS_CLOSED;
3049 if (!$close_code) {
3050 $sql .= ', paye=1';
3051 }
3052 if ($close_code) {
3053 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3054 }
3055 if ($close_note) {
3056 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3057 }
3058 $sql .= ', fk_user_closing = '.((int) $user->id);
3059 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3060 $sql .= " WHERE rowid = ".((int) $this->id);
3061
3062 $resql = $this->db->query($sql);
3063 if ($resql) {
3064 // Call trigger
3065 $result = $this->call_trigger('BILL_PAYED', $user);
3066 if ($result < 0) {
3067 $error++;
3068 }
3069 // End call triggers
3070 } else {
3071 $error++;
3072 $this->error = $this->db->lasterror();
3073 }
3074
3075 if (!$error) {
3076 $this->db->commit();
3077 return 1;
3078 } else {
3079 $this->db->rollback();
3080 return -1;
3081 }
3082 } else {
3083 return 0;
3084 }
3085 }
3086
3087
3088 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3099 public function set_unpaid($user)
3100 {
3101 // phpcs:enable
3102 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3103 return $this->setUnpaid($user);
3104 }
3105
3114 public function setUnpaid($user)
3115 {
3116 $error = 0;
3117
3118 $this->db->begin();
3119
3120 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3121 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
3122 $sql .= ' date_closing=null,';
3123 $sql .= ' fk_user_closing=null';
3124 $sql .= " WHERE rowid = ".((int) $this->id);
3125
3126 dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
3127 $resql = $this->db->query($sql);
3128 if ($resql) {
3129 // Call trigger
3130 $result = $this->call_trigger('BILL_UNPAYED', $user);
3131 if ($result < 0) {
3132 $error++;
3133 }
3134 // End call triggers
3135 } else {
3136 $error++;
3137 $this->error = $this->db->error();
3138 dol_print_error($this->db);
3139 }
3140
3141 if (!$error) {
3142 $this->db->commit();
3143 return 1;
3144 } else {
3145 $this->db->rollback();
3146 return -1;
3147 }
3148 }
3149
3150
3151 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3164 public function set_canceled($user, $close_code = '', $close_note = '')
3165 {
3166 // phpcs:enable
3167 dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3168 return $this->setCanceled($user, $close_code, $close_note);
3169 }
3170
3181 public function setCanceled($user, $close_code = '', $close_note = '')
3182 {
3183 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
3184
3185 $this->db->begin();
3186 $now = dol_now();
3187
3188 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3189 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
3190 if ($close_code) {
3191 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3192 }
3193 if ($close_note) {
3194 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3195 }
3196 $sql .= ', fk_user_closing = '.((int) $user->id);
3197 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3198 $sql .= " WHERE rowid = ".((int) $this->id);
3199
3200 $resql = $this->db->query($sql);
3201 if ($resql) {
3202 // Bound discounts are deducted from the invoice
3203 // as they have not been used since the invoice is abandoned.
3204 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3205 $sql .= ' SET fk_facture = NULL';
3206 $sql .= ' WHERE fk_facture = '.((int) $this->id);
3207
3208 $resql = $this->db->query($sql);
3209 if ($resql) {
3210 // Call trigger
3211 $result = $this->call_trigger('BILL_CANCEL', $user);
3212 if ($result < 0) {
3213 $this->db->rollback();
3214 return -1;
3215 }
3216 // End call triggers
3217
3218 $this->db->commit();
3219 return 1;
3220 } else {
3221 $this->error = $this->db->error()." sql=".$sql;
3222 $this->db->rollback();
3223 return -1;
3224 }
3225 } else {
3226 $this->error = $this->db->error()." sql=".$sql;
3227 $this->db->rollback();
3228 return -2;
3229 }
3230 }
3231
3243 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3244 {
3245 global $conf, $langs, $mysoc;
3246 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3247
3248 $productStatic = null;
3249 $warehouseStatic = null;
3250 $productbatch = null;
3251 if ($batch_rule > 0) {
3252 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3253 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3254 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3255 $productStatic = new Product($this->db);
3256 $warehouseStatic = new Entrepot($this->db);
3257 $productbatch = new Productbatch($this->db);
3258 }
3259
3260 $now = dol_now();
3261
3262 $error = 0;
3263 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3264
3265 // Force to have object complete for checks
3266 $this->fetch_thirdparty();
3267 $this->fetch_lines();
3268
3269 // Check parameters
3270 if ($this->status != self::STATUS_DRAFT) {
3271 dol_syslog(get_class($this)."::validate Current status is not draft. operation canceled.", LOG_WARNING);
3272 return 0;
3273 }
3274 if (count($this->lines) <= 0) {
3275 $langs->load("errors");
3276 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3277 return -1;
3278 }
3279 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'creer'))
3280 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'invoice_advance', 'validate'))) {
3281 $this->error = 'Permission denied';
3282 dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS=' . getDolGlobalString('MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3283 return -1;
3284 }
3285 if ((preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) && // empty should not happened, but when it occurs, the test save life
3286 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
3287 ) {
3288 $this->date = dol_now();
3289 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3290 }
3291 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
3292 $last_of_type = $this->willBeLastOfSameType(true);
3293 if (!$last_of_type[0]) {
3294 $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3295 return -1;
3296 }
3297 }
3298
3299 // Check for mandatory fields in thirdparty (defined into setup)
3300 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3301 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER');
3302 foreach ($array_to_check as $key) {
3303 $keymin = strtolower($key);
3304 if (!property_exists($this->thirdparty, $keymin)) {
3305 continue;
3306 }
3307 $vallabel = $this->thirdparty->$keymin;
3308
3309 $i = (int) preg_replace('/[^0-9]/', '', $key);
3310 if ($i > 0) {
3311 if ($this->thirdparty->isACompany()) {
3312 // Check for mandatory prof id (but only if country is other than ours)
3313 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3314 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3315 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
3316 $langs->load("errors");
3317 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3318 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3319 return -1;
3320 }
3321 }
3322 }
3323 } else {
3324 if ($key == 'EMAIL') {
3325 // Check for mandatory
3326 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
3327 $langs->load("errors");
3328 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3329 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3330 return -1;
3331 }
3332 }
3333 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3334 // Check for mandatory
3335 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3336 $langs->load("errors");
3337 $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3338 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3339 return -1;
3340 }
3341 }
3342 if ($key == 'TVA_INTRA') {
3343 // Check for mandatory vat number
3344 if (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') == 'eeconly') {
3345 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3346 $langs->load("errors");
3347 $this->error = $langs->trans('ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3348 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3349 return -1;
3350 }
3351 } elseif (getDolGlobalString('SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3352 $langs->load("errors");
3353 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv('VATIntra')).' ('.$langs->transnoentitiesnoconv("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3354 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3355 return -1;
3356 }
3357 }
3358 }
3359 }
3360 }
3361
3362 // Check for mandatory fields in $this
3363 $array_to_check = array('REF_CLIENT' => 'RefCustomer');
3364 foreach ($array_to_check as $key => $val) {
3365 $keymin = strtolower($key);
3366 $vallabel = $this->$keymin;
3367
3368 // Check for mandatory
3369 $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3370 if (!$vallabel && getDolGlobalString($keymandatory)) {
3371 $langs->load("errors");
3372 $error++;
3373 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3374 }
3375 }
3376
3377 $this->db->begin();
3378
3379 // Check parameters
3380 if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3381 // Check that source invoice is known
3382 if ($this->fk_facture_source <= 0) {
3383 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3384 $this->db->rollback();
3385 return -10;
3386 }
3387
3388 // Load source invoice that has been replaced
3389 $facreplaced = new Facture($this->db);
3390 $result = $facreplaced->fetch($this->fk_facture_source);
3391 if ($result <= 0) {
3392 $this->error = $langs->trans("ErrorBadInvoice");
3393 $this->db->rollback();
3394 return -11;
3395 }
3396
3397 // Check that source invoice not already replaced by another one.
3398 $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3399 if ($idreplacement && $idreplacement != $this->id) {
3400 $facreplacement = new Facture($this->db);
3401 $facreplacement->fetch($idreplacement);
3402 $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3403 $this->db->rollback();
3404 return -12;
3405 }
3406
3407 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3408 if ($result < 0) {
3409 $this->error = $facreplaced->error;
3410 $this->db->rollback();
3411 return -13;
3412 }
3413 }
3414
3415 // Define new ref
3416 if ($force_number) {
3417 $num = $force_number;
3418 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3419 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3420 $this->date = dol_now();
3421 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3422 }
3423 $num = $this->getNextNumRef($this->thirdparty);
3424 } else {
3425 $num = $this->ref;
3426 }
3427
3428 if (!$num) {
3429 $error++;
3430 } else {
3431 $this->oldref = $this->ref;
3432 $this->newref = dol_sanitizeFileName($num);
3433 }
3434
3435 if (!$error) {
3436 $this->update_price(1);
3437
3438 // Validate
3439 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3440 $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)."'";
3441 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3442 $sql .= ", datef='".$this->db->idate($this->date)."'";
3443 $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3444 }
3445 $sql .= " WHERE rowid = ".((int) $this->id);
3446
3447 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3448 $resql = $this->db->query($sql);
3449 if (!$resql) {
3450 $this->error = $this->db->lasterror();
3451 $error++;
3452 }
3453 }
3454
3455 if (!$error) {
3456 // Define third party as a customer
3457 $result = $this->thirdparty->setAsCustomer();
3458
3459 // If active (STOCK_CALCULATE_ON_BILL), we decrement the main product and its components at invoice validation
3460 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3461 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3462 $langs->load("agenda");
3463
3464 // Loop on each line
3465 $cpt = count($this->lines);
3466 for ($i = 0; $i < $cpt; $i++) {
3467 if ($this->lines[$i]->fk_product > 0) {
3468 $mouvP = new MouvementStock($this->db);
3469 $mouvP->origin = &$this; // deprecated
3470 $mouvP->setOrigin($this->element, $this->id);
3471
3472 // We decrease stock for product
3473 if ($this->type == self::TYPE_CREDIT_NOTE) {
3474 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3475 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3476 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num), '', '', $this->lines[$i]->batch);
3477 if ($result < 0) {
3478 $error++;
3479 $this->error = $mouvP->error;
3480 $this->errors = array_merge($this->errors, $mouvP->errors);
3481 }
3482 } else {
3483 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3484 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3485
3486 $is_batch_line = false;
3487 if ($batch_rule > 0) {
3488 $productStatic->fetch($this->lines[$i]->fk_product);
3489 if ($productStatic->hasbatch() && is_object($productbatch)) {
3490 $is_batch_line = true;
3491 $product_qty_remain = $this->lines[$i]->qty;
3492
3493 $sortfield = null;
3494 $sortorder = null;
3495 // find lot/serial by sellby (DLC) and eatby dates (DLUO) first
3497 $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3498 $sortorder = 'ASC,ASC,ASC,ASC';
3499 }
3500
3501 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (getDolGlobalInt('STOCK_ALLOW_NEGATIVE_TRANSFER') ? null : 0), $sortfield, $sortorder);
3502 if (!is_array($resBatchList)) {
3503 $error++;
3504 $this->error = $this->db->lasterror();
3505 }
3506
3507 if (!$error) {
3508 $batchList = $resBatchList;
3509 if (empty($batchList)) {
3510 $error++;
3511 $langs->load('errors');
3512 $warehouseStatic->fetch($idwarehouse);
3513 $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3514 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3515 }
3516
3517 foreach ($batchList as $batch) {
3518 if ($batch->qty <= 0) {
3519 continue; // try to decrement only batches have positive quantity first
3520 }
3521
3522 // enough quantity in this batch
3523 if ($batch->qty >= $product_qty_remain) {
3524 $product_batch_qty = $product_qty_remain;
3525 } else {
3526 // not enough (take all in batch)
3527 $product_batch_qty = $batch->qty;
3528 }
3529 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3530 if ($result < 0) {
3531 $error++;
3532 $this->error = $mouvP->error;
3533 $this->errors = array_merge($this->errors, $mouvP->errors);
3534 break;
3535 }
3536
3537 $product_qty_remain -= $product_batch_qty;
3538 // all product quantity was decremented
3539 if ($product_qty_remain <= 0) {
3540 break;
3541 }
3542 }
3543
3544 if (!$error && $product_qty_remain > 0) {
3545 if (getDolGlobalInt('STOCK_ALLOW_NEGATIVE_TRANSFER')) {
3546 // take in the first batch
3547 $batch = $batchList[0];
3548 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3549 if ($result < 0) {
3550 $error++;
3551 $this->error = $mouvP->error;
3552 $this->errors = array_merge($this->errors, $mouvP->errors);
3553 }
3554 } else {
3555 $error++;
3556 $langs->load('errors');
3557 $warehouseStatic->fetch($idwarehouse);
3558 $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3559 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3560 }
3561 }
3562 }
3563 }
3564 }
3565
3566 if (!$is_batch_line) { // If stock move not yet processed
3567 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3568 if ($result < 0) {
3569 $error++;
3570 $this->error = $mouvP->error;
3571 $this->errors = array_merge($this->errors, $mouvP->errors);
3572 }
3573 }
3574 }
3575 }
3576 }
3577 }
3578
3579 /*
3580 * 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%)
3581 * So we can continue to create new invoice situation
3582 */
3583 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3584 $invoice_situation = new Facture($this->db);
3585 $result = $invoice_situation->fetch($this->fk_facture_source);
3586 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3587 $invoice_situation->situation_final = 0;
3588 // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3589 $result = $invoice_situation->setFinal($user, 1);
3590 }
3591 if ($result < 0) {
3592 $this->error = $invoice_situation->error;
3593 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3594 $error++;
3595 }
3596 }
3597
3598 // Trigger calls
3599 if (!$error && !$notrigger) {
3600 // Call trigger
3601 $result = $this->call_trigger('BILL_VALIDATE', $user);
3602 if ($result < 0) {
3603 $error++;
3604 }
3605 // End call triggers
3606 }
3607
3608 if (!$error) {
3609 // Rename directory if dir was a temporary ref
3610 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
3611 // Now we rename also files into index
3612 $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)."'";
3613 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3614 $resql = $this->db->query($sql);
3615 if (!$resql) {
3616 $error++;
3617 $this->error = $this->db->lasterror();
3618 }
3619 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'facture/".$this->db->escape($this->newref)."'";
3620 $sql .= " WHERE filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3621 $resql = $this->db->query($sql);
3622 if (!$resql) {
3623 $error++;
3624 $this->error = $this->db->lasterror();
3625 }
3626 }
3627 }
3628
3629 if (!$error && !$this->is_last_in_cycle()) {
3630 if (!$this->updatePriceNextInvoice($langs)) {
3631 $error++;
3632 }
3633 }
3634
3635 // Set new ref and define current status
3636 if (!$error) {
3637 $this->ref = $num;
3638 $this->statut = self::STATUS_VALIDATED; // deprecated
3640 $this->date_validation = $now;
3641 $i = 0;
3642
3643 if (getDolGlobalInt('INVOICE_USE_SITUATION')) {
3644 $final = true;
3645 $nboflines = count($this->lines);
3646 while (($i < $nboflines) && $final) {
3647 $line = $this->lines[$i];
3648 '@phan-var-force FactureLigne $line';
3649 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3650 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3651 $current_progress = (float) $line->situation_percent;
3652 $full_progress = $previousprogress + $current_progress;
3653 $final = ($full_progress == 100);
3654 } else {
3655 $final = ($line->situation_percent == 100);
3656 }
3657 $i++;
3658 }
3659
3660 if (empty($final)) {
3661 $this->situation_final = 0;
3662 } else {
3663 $this->situation_final = 1;
3664 }
3665
3666 $this->setFinal($user);
3667 }
3668 }
3669 }
3670
3671 // Rename directory if dir was a temporary ref
3672 if (!$error && preg_match('/^[\‍(]?PROV/i', $this->oldref)) {
3673 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
3674 $oldref = dol_sanitizeFileName($this->oldref);
3675 $newref = dol_sanitizeFileName($num);
3676 $dirsource = $conf->facture->dir_output.'/'.$oldref;
3677 $dirdest = $conf->facture->dir_output.'/'.$newref;
3678 if (!$error && file_exists($dirsource)) {
3679 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
3680
3681 if (@rename($dirsource, $dirdest)) {
3682 dol_syslog("Rename ok");
3683 // Rename docs starting with $oldref with $newref
3684 $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
3685 foreach ($listoffiles as $fileentry) {
3686 $dirsource = $fileentry['name'];
3687 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
3688 $dirsource = $fileentry['path'].'/'.$dirsource;
3689 $dirdest = $fileentry['path'].'/'.$dirdest;
3690 @rename($dirsource, $dirdest);
3691 }
3692 }
3693 }
3694 }
3695
3696 if (!$error) {
3697 $this->db->commit();
3698 return 1;
3699 } else {
3700 $this->db->rollback();
3701 return -1;
3702 }
3703 }
3704
3711 public function updatePriceNextInvoice(&$langs)
3712 {
3713 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3714 $is_last = $next_invoice->is_last_in_cycle();
3715
3716 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3717 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3718 return false;
3719 }
3720
3721 foreach ($next_invoice->lines as $line) {
3722 '@phan-var-force FactureLigne $line';
3723 $result = $next_invoice->updateline(
3724 $line->id,
3725 $line->desc,
3726 $line->subprice,
3727 $line->qty,
3728 $line->remise_percent,
3729 $line->date_start,
3730 $line->date_end,
3731 $line->tva_tx,
3732 $line->localtax1_tx,
3733 $line->localtax2_tx,
3734 'HT',
3735 $line->info_bits,
3736 $line->product_type,
3737 $line->fk_parent_line,
3738 0,
3739 $line->fk_fournprice,
3740 $line->pa_ht,
3741 $line->label,
3742 $line->special_code,
3743 $line->array_options,
3744 $line->situation_percent,
3745 $line->fk_unit
3746 );
3747
3748 if ($result < 0) {
3749 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3750 return false;
3751 }
3752 }
3753
3754 break; // Only the next invoice and not each next invoice
3755 }
3756
3757 return true;
3758 }
3759
3767 public function setDraft($user, $idwarehouse = -1)
3768 {
3769 // phpcs:enable
3770 global $conf, $langs;
3771
3772 $error = 0;
3773
3774 if ($this->status == self::STATUS_DRAFT) {
3775 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
3776 return 0;
3777 }
3778
3779 dol_syslog(__METHOD__, LOG_DEBUG);
3780
3781 $this->db->begin();
3782
3783 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3784 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
3785 $sql .= " WHERE rowid = ".((int) $this->id);
3786
3787 $result = $this->db->query($sql);
3788 if ($result) {
3789 if (!$error) {
3790 $this->oldcopy = clone $this;
3791 }
3792
3793 // If we decrease stock on invoice validation, we increase back
3794 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
3795 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3796 $langs->load("agenda");
3797
3798 $num = count($this->lines);
3799 for ($i = 0; $i < $num; $i++) {
3800 if ($this->lines[$i]->fk_product > 0) {
3801 $mouvP = new MouvementStock($this->db);
3802 $mouvP->origin = &$this;
3803 $mouvP->setOrigin($this->element, $this->id);
3804 // We decrease stock for product
3805 if ($this->type == self::TYPE_CREDIT_NOTE) {
3806 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
3807 } else {
3808 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
3809 }
3810 }
3811 }
3812 }
3813
3814 if ($error == 0) {
3815 $old_statut = $this->status;
3816 $this->statut = self::STATUS_DRAFT; // deprecated
3817 $this->status = self::STATUS_DRAFT;
3818
3819 // Call trigger
3820 $result = $this->call_trigger('BILL_UNVALIDATE', $user);
3821 if ($result < 0) {
3822 $error++;
3823 $this->statut = $old_statut; // deprecated
3824 $this->status = $old_statut;
3825 }
3826 // End call triggers
3827 } else {
3828 $this->db->rollback();
3829 return -1;
3830 }
3831
3832 if ($error == 0) {
3833 $this->db->commit();
3834 return 1;
3835 } else {
3836 $this->db->rollback();
3837 return -1;
3838 }
3839 } else {
3840 $this->error = $this->db->error();
3841 $this->db->rollback();
3842 return -1;
3843 }
3844 }
3845
3846
3888 public function addline(
3889 $desc,
3890 $pu_ht,
3891 $qty,
3892 $txtva,
3893 $txlocaltax1 = 0,
3894 $txlocaltax2 = 0,
3895 $fk_product = 0,
3896 $remise_percent = 0,
3897 $date_start = '',
3898 $date_end = '',
3899 $fk_code_ventilation = 0,
3900 $info_bits = 0,
3901 $fk_remise_except = 0,
3902 $price_base_type = 'HT',
3903 $pu_ttc = 0,
3904 $type = 0,
3905 $rang = -1,
3906 $special_code = 0,
3907 $origin = '',
3908 $origin_id = 0,
3909 $fk_parent_line = 0,
3910 $fk_fournprice = null,
3911 $pa_ht = 0,
3912 $label = '',
3913 $array_options = array(),
3914 $situation_percent = 100,
3915 $fk_prev_id = 0,
3916 $fk_unit = null,
3917 $pu_ht_devise = 0,
3918 $ref_ext = '',
3919 $noupdateafterinsertline = 0
3920 ) {
3921 // Deprecation warning
3922 if ($label) {
3923 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3924 //var_dump(getCallerInfoString());exit;
3925 }
3926
3927 global $mysoc, $conf, $langs;
3928
3929 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);
3930
3931 if ($this->status == self::STATUS_DRAFT) {
3932 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3933
3934 // Clean parameters
3935 if (empty($remise_percent)) {
3936 $remise_percent = 0;
3937 }
3938 if (empty($qty)) {
3939 $qty = 0;
3940 }
3941 if (empty($info_bits)) {
3942 $info_bits = 0;
3943 }
3944 if (empty($rang)) {
3945 $rang = 0;
3946 }
3947 if (empty($fk_code_ventilation)) {
3948 $fk_code_ventilation = 0;
3949 }
3950 if (empty($txtva)) {
3951 $txtva = 0;
3952 }
3953 if (empty($txlocaltax1)) {
3954 $txlocaltax1 = 0;
3955 }
3956 if (empty($txlocaltax2)) {
3957 $txlocaltax2 = 0;
3958 }
3959 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3960 $fk_parent_line = 0;
3961 }
3962 if (empty($fk_prev_id)) {
3963 $fk_prev_id = 'null';
3964 }
3965 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
3966 // INVOICE_USE_SITUATION = 2 - Lines situation percent on new lines must be 0 (No cumulative)
3967 if ($this->isSituationInvoice() && getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3968 $situation_percent = 0;
3969 } else {
3970 $situation_percent = 100;
3971 }
3972 }
3973 if (empty($ref_ext)) {
3974 $ref_ext = '';
3975 }
3976
3977 $remise_percent = (float) price2num($remise_percent);
3978
3979 $qty = (float) price2num($qty);
3980 $pu_ht = (float) price2num($pu_ht);
3981 $pu_ht_devise = (float) price2num($pu_ht_devise);
3982 $pu_ttc = (float) price2num($pu_ttc);
3983 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
3984
3985 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3986 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3987 }
3988 $txlocaltax1 = (float) price2num($txlocaltax1);
3989 $txlocaltax2 = (float) price2num($txlocaltax2);
3990
3991 if ($price_base_type == 'HT') {
3992 $pu = $pu_ht;
3993 } else {
3994 $pu = $pu_ttc;
3995 }
3996
3997 // Check parameters
3998 if ($type < 0) {
3999 return -1;
4000 }
4001
4002 if ($date_start && $date_end && $date_start > $date_end) {
4003 $langs->load("errors");
4004 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4005 return -1;
4006 }
4007
4008 $this->db->begin();
4009
4010 $product_type = $type;
4011 if (!empty($fk_product) && $fk_product > 0) {
4012 $product = new Product($this->db);
4013 $result = $product->fetch($fk_product);
4014 $product_type = $product->type;
4015
4016 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4017 $langs->load("errors");
4018 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4019 $this->db->rollback();
4020 return -3;
4021 }
4022 }
4023
4024 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4025
4026 // Clean vat code
4027 $reg = array();
4028 $vat_src_code = '';
4029 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4030 $vat_src_code = $reg[1];
4031 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4032 }
4033
4034 // Calcul du total TTC et de la TVA pour la ligne a partir de
4035 // qty, pu, remise_percent et txtva
4036 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
4037 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
4038
4039 $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);
4040
4041 $total_ht = $tabprice[0];
4042 $total_tva = $tabprice[1];
4043 $total_ttc = $tabprice[2];
4044 $total_localtax1 = $tabprice[9];
4045 $total_localtax2 = $tabprice[10];
4046 $pu_ht = $tabprice[3];
4047
4048 // MultiCurrency
4049 $multicurrency_total_ht = $tabprice[16];
4050 $multicurrency_total_tva = $tabprice[17];
4051 $multicurrency_total_ttc = $tabprice[18];
4052 $pu_ht_devise = $tabprice[19];
4053
4054 // Rank to use
4055 $ranktouse = $rang;
4056 if ($ranktouse == -1) {
4057 $rangmax = $this->line_max($fk_parent_line);
4058 $ranktouse = $rangmax + 1;
4059 }
4060
4061 // Insert line
4062 $this->line = new FactureLigne($this->db);
4063
4064 $this->line->context = $this->context;
4065
4066 $this->line->fk_facture = $this->id;
4067 $this->line->label = $label; // deprecated
4068 $this->line->desc = $desc;
4069 $this->line->ref_ext = $ref_ext;
4070
4071 $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
4072 $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
4073
4074 $this->line->vat_src_code = $vat_src_code;
4075 $this->line->tva_tx = $txtva;
4076 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4077 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4078 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4079 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4080
4081 $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
4082 $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
4083 $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
4084 $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
4085 $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
4086
4087 $this->line->fk_product = $fk_product;
4088 $this->line->product_type = $product_type;
4089 $this->line->remise_percent = $remise_percent;
4090 $this->line->date_start = $date_start;
4091 $this->line->date_end = $date_end;
4092 $this->line->fk_code_ventilation = $fk_code_ventilation;
4093 $this->line->rang = $ranktouse;
4094 $this->line->info_bits = $info_bits;
4095 $this->line->fk_remise_except = $fk_remise_except;
4096
4097 $this->line->special_code = $special_code;
4098 $this->line->fk_parent_line = $fk_parent_line;
4099 $this->line->origin = $origin;
4100 $this->line->origin_id = $origin_id;
4101 $this->line->situation_percent = $situation_percent;
4102 $this->line->fk_prev_id = $fk_prev_id;
4103 $this->line->fk_unit = $fk_unit;
4104
4105 // infos margin
4106 $this->line->fk_fournprice = $fk_fournprice;
4107 $this->line->pa_ht = $pa_ht;
4108
4109 // Multicurrency
4110 $this->line->fk_multicurrency = $this->fk_multicurrency;
4111 $this->line->multicurrency_code = $this->multicurrency_code;
4112 $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
4113
4114 $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
4115 $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
4116 $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
4117
4118 if (is_array($array_options) && count($array_options) > 0) {
4119 $this->line->array_options = $array_options;
4120 }
4121
4122 $result = $this->line->insert();
4123 if ($result > 0) {
4124 // Update denormalized fields at the order level
4125 if (empty($noupdateafterinsertline)) {
4126 $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.
4127 }
4128
4129 if (!isset($this->context['createfromclone'])) {
4130 if (!empty($fk_parent_line)) {
4131 // Always reorder if child line
4132 $this->line_order(true, 'DESC');
4133 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4134 // Update all rank of all other lines starting from the same $ranktouse
4135 $linecount = count($this->lines);
4136 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4137 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
4138 }
4139 }
4140
4141 $this->lines[] = $this->line;
4142 }
4143
4144 if ($result > 0) {
4145 $this->db->commit();
4146 return $this->line->id;
4147 } else {
4148 $this->error = $this->db->lasterror();
4149 $this->db->rollback();
4150 return -1;
4151 }
4152 } else {
4153 $this->error = $this->line->error;
4154 $this->errors = $this->line->errors;
4155 $this->db->rollback();
4156 return -2;
4157 }
4158 } else {
4159 $this->errors[] = 'status of invoice must be Draft to allow use of ->addline()';
4160 dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4161 return -3;
4162 }
4163 }
4164
4196 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)
4197 {
4198 global $user;
4199
4200 // Deprecation warning
4201 if ($label) {
4202 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4203 }
4204
4205 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4206
4207 global $mysoc, $langs;
4208
4209 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);
4210
4211 if ($this->status == self::STATUS_DRAFT) {
4212 if (!$this->is_last_in_cycle() && empty($this->error)) {
4213 if (!$this->checkProgressLine($rowid, $situation_percent)) {
4214 if (!$this->error) {
4215 $this->error = $langs->trans('invoiceLineProgressError');
4216 }
4217 return -3;
4218 }
4219 }
4220
4221 if ($date_start && $date_end && $date_start > $date_end) {
4222 $langs->load("errors");
4223 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4224 return -1;
4225 }
4226
4227 $this->db->begin();
4228
4229 // Clean parameters
4230 if (empty($qty)) {
4231 $qty = 0;
4232 }
4233 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4234 $fk_parent_line = 0;
4235 }
4236 if (empty($special_code) || $special_code == 3) {
4237 $special_code = 0;
4238 }
4239 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '' || $situation_percent == null) {
4240 // INVOICE_USE_SITUATION = 2 - If there is no progress on a line, percent must not be 100% (No cumulative)
4241 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalInt('INVOICE_USE_SITUATION') == 2 && (int) $situation_percent < 100) {
4242 $situation_percent = 0;
4243 } else {
4244 $situation_percent = 100;
4245 }
4246 }
4247 if (empty($ref_ext)) {
4248 $ref_ext = '';
4249 }
4250
4251 $remise_percent = (float) price2num($remise_percent);
4252
4253 $qty = (float) price2num($qty);
4254 $pu = (float) price2num($pu);
4255 $pu_ht_devise = (float) price2num($pu_ht_devise);
4256 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
4257
4258 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4259 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4260 }
4261 $txlocaltax1 = (float) price2num($txlocaltax1);
4262 $txlocaltax2 = (float) price2num($txlocaltax2);
4263
4264 // Check parameters
4265 if ($type < 0) {
4266 return -1;
4267 }
4268
4269 // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
4270 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
4271 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
4272
4273 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4274
4275 // Clean vat code
4276 $reg = array();
4277 $vat_src_code = '';
4278 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4279 $vat_src_code = $reg[1];
4280 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4281 }
4282
4283 $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);
4284
4285 $total_ht = $tabprice[0];
4286 $total_tva = $tabprice[1];
4287 $total_ttc = $tabprice[2];
4288 $total_localtax1 = $tabprice[9];
4289 $total_localtax2 = $tabprice[10];
4290 $pu_ht = $tabprice[3];
4291 $pu_tva = $tabprice[4];
4292 $pu_ttc = $tabprice[5];
4293
4294 // MultiCurrency
4295 $multicurrency_total_ht = $tabprice[16];
4296 $multicurrency_total_tva = $tabprice[17];
4297 $multicurrency_total_ttc = $tabprice[18];
4298 $pu_ht_devise = $tabprice[19];
4299
4300 // Old properties: $price, $remise (deprecated)
4301 $price = $pu;
4302 $remise = 0;
4303 if ($remise_percent > 0) {
4304 $remise = round(((float) $pu * (float) $remise_percent / 100), 2);
4305 $price = ((float) $pu - $remise);
4306 }
4307 $price = price2num($price);
4308
4309 // Fetch current line from the database and then clone the object and set it in $oldline property
4310 $line = new FactureLigne($this->db);
4311 $line->fetch($rowid);
4312 $line->fetch_optionals();
4313
4314 if (!empty($line->fk_product)) {
4315 $product = new Product($this->db);
4316 $result = $product->fetch($line->fk_product);
4317 $product_type = $product->type;
4318
4319 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4320 $langs->load("errors");
4321 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4322 $this->db->rollback();
4323 return -3;
4324 }
4325 }
4326
4327 $staticline = clone $line;
4328
4329 $line->oldline = $staticline;
4330 $this->line = $line;
4331 $this->line->context = $this->context;
4332 $this->line->rang = $rang;
4333
4334 // Reorder if fk_parent_line change
4335 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4336 $rangmax = $this->line_max($fk_parent_line);
4337 $this->line->rang = $rangmax + 1;
4338 }
4339 $apply_abs_price_on_credit_note=false;
4340 if ($this->type == self::TYPE_CREDIT_NOTE && !getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && !getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN')) {
4341 $apply_abs_price_on_credit_note = true;
4342 }
4343
4344
4345 $this->line->id = $rowid;
4346 $this->line->rowid = $rowid;
4347 $this->line->label = $label;
4348 $this->line->desc = $desc;
4349 $this->line->ref_ext = $ref_ext;
4350 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
4351
4352 $this->line->vat_src_code = $vat_src_code;
4353 $this->line->tva_tx = $txtva;
4354 $this->line->localtax1_tx = $txlocaltax1;
4355 $this->line->localtax2_tx = $txlocaltax2;
4356 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4357 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4358
4359 $this->line->remise_percent = $remise_percent;
4360 $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
4361 $this->line->date_start = $date_start;
4362 $this->line->date_end = $date_end;
4363 $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
4364 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva);
4365 $this->line->total_localtax1 = (float) $total_localtax1;
4366 $this->line->total_localtax2 = (float) $total_localtax2;
4367 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc);
4368 $this->line->info_bits = $info_bits;
4369 $this->line->special_code = $special_code;
4370 $this->line->product_type = $type;
4371 $this->line->fk_parent_line = $fk_parent_line;
4372 $this->line->skip_update_total = $skip_update_total;
4373 $this->line->situation_percent = $situation_percent;
4374 $this->line->fk_unit = $fk_unit;
4375
4376 $this->line->fk_fournprice = $fk_fournprice;
4377 $this->line->pa_ht = $pa_ht;
4378
4379 // Multicurrency
4380 $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
4381 $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
4382 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4383 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4384
4385 if (is_array($array_options) && count($array_options) > 0) {
4386 // We replace values in this->line->array_options only for entries defined into $array_options
4387 foreach ($array_options as $key => $value) {
4388 $this->line->array_options[$key] = $array_options[$key];
4389 }
4390 }
4391
4392 $result = $this->line->update($user, $notrigger);
4393 if ($result > 0) {
4394 // Reorder if child line
4395 if (!empty($fk_parent_line)) {
4396 $this->line_order(true, 'DESC');
4397 }
4398
4399 // Mise a jour info denormalisees au niveau facture
4400 $this->update_price(1, 'auto');
4401 $this->db->commit();
4402 return $result;
4403 } else {
4404 $this->error = $this->line->error;
4405 $this->db->rollback();
4406 return -1;
4407 }
4408 } else {
4409 $this->error = "Invoice statut makes operation forbidden";
4410 return -2;
4411 }
4412 }
4413
4421 public function checkProgressLine($idline, $situation_percent)
4422 {
4423 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4424 INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4425 WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4426
4427 $result = $this->db->query($sql);
4428 if (!$result) {
4429 $this->error = $this->db->error();
4430 return false;
4431 }
4432
4433 $obj = $this->db->fetch_object($result);
4434
4435 if ($obj === null) {
4436 return true;
4437 } else {
4438 return ($situation_percent < $obj->situation_percent);
4439 }
4440 }
4441
4442 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4451 public function update_percent($line, $percent, $update_price = true)
4452 {
4453 // phpcs:enable
4454 global $mysoc, $user;
4455
4456 // Progress should never be changed for discount lines
4457 if (($line->info_bits & 2) == 2) {
4458 return;
4459 }
4460
4461 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4462
4463 // Cap percentages to 100
4464 if ($percent > 100) {
4465 $percent = 100;
4466 }
4467 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4468 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4469 $current_progress = $percent - $previous_progress;
4470 $line->situation_percent = $current_progress;
4471 $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);
4472 } else {
4473 $line->situation_percent = $percent;
4474 $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);
4475 }
4476 $line->total_ht = (float) $tabprice[0];
4477 $line->total_tva = (float) $tabprice[1];
4478 $line->total_ttc = (float) $tabprice[2];
4479 $line->total_localtax1 = (float) $tabprice[9];
4480 $line->total_localtax2 = (float) $tabprice[10];
4481 $line->multicurrency_total_ht = (float) $tabprice[16];
4482 $line->multicurrency_total_tva = (float) $tabprice[17];
4483 $line->multicurrency_total_ttc = (float) $tabprice[18];
4484 $line->update($user);
4485
4486 // sometimes it is better to not update price for each line, ie when updating situation on all lines
4487 if ($update_price) {
4488 $this->update_price(1);
4489 }
4490 }
4491
4499 public function deleteLine($rowid, $id = 0)
4500 {
4501 global $user;
4502
4503 dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4504
4505 if ($this->status != self::STATUS_DRAFT) {
4506 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4507 return -1;
4508 }
4509
4510 $line = new FactureLigne($this->db);
4511
4512 $line->context = $this->context;
4513
4514 // Load line
4515 $result = $line->fetch($rowid);
4516 if (!($result > 0)) {
4517 dol_print_error($this->db, $line->error, $line->errors);
4518 return -1;
4519 }
4520
4521 if ($id > 0 && $line->fk_facture != $id) {
4522 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4523 return -1;
4524 }
4525
4526 $this->db->begin();
4527
4528 // Memorize previous line for triggers
4529 $staticline = clone $line;
4530 $line->oldline = $staticline;
4531
4532 if ($line->delete($user) > 0) {
4533 $result = $this->update_price(1);
4534
4535 if ($result > 0) {
4536 $this->db->commit();
4537 return 1;
4538 } else {
4539 $this->db->rollback();
4540 $this->error = $this->db->lasterror();
4541 return -1;
4542 }
4543 } else {
4544 $this->db->rollback();
4545 $this->error = $line->error;
4546 return -1;
4547 }
4548 }
4549
4550 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4561 public function set_remise($user, $remise, $notrigger = 0)
4562 {
4563 // phpcs:enable
4564 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4565 // @phan-suppress-next-line PhanDeprecatedFunction
4566 return $this->setDiscount($user, $remise, $notrigger);
4567 }
4568
4577 public function setDiscount($user, $remise, $notrigger = 0)
4578 {
4579 // Clean parameters
4580 if (empty($remise)) {
4581 $remise = 0;
4582 }
4583
4584 if ($user->hasRight('facture', 'creer')) {
4585 $remise = (float) price2num($remise, 2);
4586
4587 $error = 0;
4588
4589 $this->db->begin();
4590
4591 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4592 $sql .= " SET remise_percent = ".((float) $remise);
4593 $sql .= " WHERE rowid = ".((int) $this->id);
4594 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
4595
4596 dol_syslog(__METHOD__, LOG_DEBUG);
4597 $resql = $this->db->query($sql);
4598 if (!$resql) {
4599 $this->errors[] = $this->db->error();
4600 $error++;
4601 }
4602
4603 if (!$notrigger && empty($error)) {
4604 // Call trigger
4605 $result = $this->call_trigger('BILL_MODIFY', $user);
4606 if ($result < 0) {
4607 $error++;
4608 }
4609 // End call triggers
4610 }
4611
4612 if (!$error) {
4613 $this->remise_percent = $remise;
4614 $this->update_price(1);
4615
4616 $this->db->commit();
4617 return 1;
4618 } else {
4619 foreach ($this->errors as $errmsg) {
4620 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4621 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4622 }
4623 $this->db->rollback();
4624 return -1 * $error;
4625 }
4626 }
4627
4628 return 0;
4629 }
4630
4631
4632 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4641 /*
4642 public function set_remise_absolue($user, $remise, $notrigger = 0)
4643 {
4644 // phpcs:enable
4645 if (empty($remise)) {
4646 $remise = 0;
4647 }
4648
4649 if ($user->hasRight('facture', 'creer')) {
4650 $error = 0;
4651
4652 $this->db->begin();
4653
4654 $remise = price2num($remise);
4655
4656 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4657 $sql .= ' SET remise_absolue = '.((float) $remise);
4658 $sql .= " WHERE rowid = ".((int) $this->id);
4659 $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4660
4661 dol_syslog(__METHOD__, LOG_DEBUG);
4662 $resql = $this->db->query($sql);
4663 if (!$resql) {
4664 $this->errors[] = $this->db->error();
4665 $error++;
4666 }
4667
4668 if (!$error) {
4669 $this->oldcopy = clone $this;
4670 $this->remise_absolue = $remise;
4671 $this->update_price(1);
4672 }
4673
4674 if (!$notrigger && empty($error)) {
4675 // Call trigger
4676 $result = $this->call_trigger('BILL_MODIFY', $user);
4677 if ($result < 0) {
4678 $error++;
4679 }
4680 // End call triggers
4681 }
4682
4683 if (!$error) {
4684 $this->db->commit();
4685 return 1;
4686 } else {
4687 foreach ($this->errors as $errmsg) {
4688 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4689 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4690 }
4691 $this->db->rollback();
4692 return -1 * $error;
4693 }
4694 }
4695
4696 return 0;
4697 }
4698 */
4699
4708 public function getNextNumRef($soc, $mode = 'next')
4709 {
4710 global $conf, $langs;
4711
4712 if ($this->module_source == 'takepos') {
4713 $langs->load('cashdesk');
4714
4715 $moduleName = 'takepos';
4716 $moduleSourceName = 'Takepos';
4717 $addonConstName = 'TAKEPOS_REF_ADDON';
4718
4719 // Clean parameters (if not defined or using deprecated value)
4720 if (!getDolGlobalString('TAKEPOS_REF_ADDON')) {
4721 $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
4722 }
4723
4724 $addon = getDolGlobalString('TAKEPOS_REF_ADDON');
4725 } else {
4726 $langs->load('bills');
4727
4728 $moduleName = 'facture';
4729 $moduleSourceName = 'Invoice';
4730 $addonConstName = 'FACTURE_ADDON';
4731
4732 // Clean parameters (if not defined or using deprecated value)
4733 if (!getDolGlobalString('FACTURE_ADDON')) {
4734 $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4735 } elseif (getDolGlobalString('FACTURE_ADDON') == 'terre') {
4736 $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4737 } elseif (getDolGlobalString('FACTURE_ADDON') == 'mercure') {
4738 $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
4739 }
4740
4741 $addon = getDolGlobalString('FACTURE_ADDON');
4742 }
4743
4744 if (!empty($addon)) {
4745 dol_syslog("Call getNextNumRef with ".$addonConstName." = " . getDolGlobalString('FACTURE_ADDON').", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
4746
4747 $mybool = false;
4748
4749 $file = $addon.'.php';
4750 $classname = $addon;
4751
4752
4753 // Include file with class
4754 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
4755 foreach ($dirmodels as $reldir) {
4756 $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
4757
4758 // Load file with numbering class (if found)
4759 if (is_file($dir.$file) && is_readable($dir.$file)) {
4760 $mybool = ((bool) include_once $dir.$file) || $mybool;
4761 }
4762 }
4763
4764 // For compatibility
4765 if (!$mybool) {
4766 $file = $addon.'/'.$addon.'.modules.php';
4767 $classname = 'mod_'.$moduleName.'_'.$addon;
4768 $classname = preg_replace('/\-.*$/', '', $classname);
4769 // Include file with class
4770 foreach ($conf->file->dol_document_root as $dirroot) {
4771 $dir = $dirroot.'/core/modules/'.$moduleName.'/';
4772
4773 // Load file with numbering class (if found)
4774 if (is_file($dir.$file) && is_readable($dir.$file)) {
4775 $mybool = (include_once $dir.$file) || $mybool;
4776 }
4777 }
4778 }
4779
4780 if (!$mybool) {
4781 dol_print_error(null, 'Failed to include file '.$file);
4782 return '';
4783 }
4784
4785 $obj = new $classname();
4786 '@phan-var-force ModeleNumRefFactures $obj';
4787
4788 $numref = $obj->getNextValue($soc, $this, $mode);
4789
4790
4795 if ($mode != 'last' && !$numref) {
4796 $this->error = $obj->error;
4797 return '';
4798 }
4799
4800 return $numref;
4801 } else {
4802 $langs->load('errors');
4803 print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4804 return '';
4805 }
4806 }
4807
4814 public function info($id)
4815 {
4816 $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4817 $sql .= ' date_closing as dateclosing,';
4818 $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
4819 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
4820 $sql .= ' WHERE c.rowid = '.((int) $id);
4821
4822 $result = $this->db->query($sql);
4823 if ($result) {
4824 if ($this->db->num_rows($result)) {
4825 $obj = $this->db->fetch_object($result);
4826
4827 $this->id = $obj->rowid;
4828 $this->user_creation_id = $obj->fk_user_author;
4829 $this->user_validation_id = $obj->fk_user_valid;
4830 $this->user_closing_id = $obj->fk_user_closing;
4831
4832 $this->date_creation = $this->db->jdate($obj->datec);
4833 $this->date_modification = $this->db->jdate($obj->datem);
4834 $this->date_validation = $this->db->jdate($obj->datev);
4835 $this->date_closing = $this->db->jdate($obj->dateclosing);
4836 }
4837 $this->db->free($result);
4838 } else {
4839 dol_print_error($this->db);
4840 }
4841 }
4842
4843
4844 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4858 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
4859 {
4860 // phpcs:enable
4861 global $user;
4862
4863 $ga = array();
4864
4865 $sql = "SELECT s.rowid, s.nom as name, s.client,";
4866 $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
4867 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
4868 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4869 $sql .= " AND f.fk_soc = s.rowid";
4870 if ($draft) {
4871 $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
4872 }
4873 if (is_object($excluser)) {
4874 $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
4875 }
4876 // If the internal user must only see his customers, force searching by him
4877 $search_sale = 0;
4878 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
4879 $search_sale = $user->id;
4880 }
4881 // Search on sale representative
4882 if ($search_sale && $search_sale != '-1') {
4883 if ($search_sale == -2) {
4884 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4885 } elseif ($search_sale > 0) {
4886 $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).")";
4887 }
4888 }
4889 // Search on socid
4890 if ($socid) {
4891 $sql .= " AND f.fk_soc = ".((int) $socid);
4892 }
4893 $sql .= $this->db->order($sortfield, $sortorder);
4894 $sql .= $this->db->plimit($limit, $offset);
4895
4896 $result = $this->db->query($sql);
4897 if ($result) {
4898 $numc = $this->db->num_rows($result);
4899 if ($numc) {
4900 $i = 0;
4901 while ($i < $numc) {
4902 $obj = $this->db->fetch_object($result);
4903
4904 if ($shortlist == 1) {
4905 $ga[$obj->fid] = $obj->ref;
4906 } elseif ($shortlist == 2) {
4907 $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
4908 } else {
4909 $ga[$i]['id'] = $obj->fid;
4910 $ga[$i]['ref'] = $obj->ref;
4911 $ga[$i]['name'] = $obj->name;
4912 }
4913 $i++;
4914 }
4915 }
4916 return $ga;
4917 } else {
4918 dol_print_error($this->db);
4919 return -1;
4920 }
4921 }
4922
4923
4924 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4933 public function list_replacable_invoices($socid = 0)
4934 {
4935 // phpcs:enable
4936 global $conf;
4937
4938 $return = array();
4939
4940 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4941 $sql .= " ff.rowid as rowidnext";
4942 //$sql .= ", SUM(pf.amount) as alreadypaid";
4943 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4944 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4945 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
4946 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
4947 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4948 $sql .= " AND f.paye = 0"; // Not paid completely
4949 $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
4950 $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
4951 if ($socid > 0) {
4952 $sql .= " AND f.fk_soc = ".((int) $socid);
4953 }
4954 //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
4955 $sql .= " ORDER BY f.ref";
4956
4957 dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
4958 $resql = $this->db->query($sql);
4959 if ($resql) {
4960 while ($obj = $this->db->fetch_object($resql)) {
4961 $return[$obj->rowid] = array(
4962 'id' => $obj->rowid,
4963 'ref' => $obj->ref,
4964 'status' => $obj->status,
4965 'paid' => $obj->paid,
4966 'alreadypaid' => 0
4967 );
4968 }
4969 //print_r($return);
4970 return $return;
4971 } else {
4972 $this->error = $this->db->error();
4973 return -1;
4974 }
4975 }
4976
4977
4978 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4988 public function list_qualified_avoir_invoices($socid = 0)
4989 {
4990 // phpcs:enable
4991 global $conf;
4992
4993 $return = array();
4994
4995
4996 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4997 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4998 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4999 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
5000 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
5001 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5002 // $sql.= " WHERE f.fk_statut >= 1";
5003 // $sql.= " AND (f.paye = 1"; // Classee payee completement
5004 // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
5005 $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de replacement
5006 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
5007
5008 if (getDolGlobalString('INVOICE_USE_SITUATION_CREDIT_NOTE')) {
5009 // Keep invoices that are not situation invoices or that are the last in series if it is a situation invoice
5010 $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
5011 $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID because of the group by later
5012 $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
5013 $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
5014 $sql .= " AND fs.type = ".self::TYPE_SITUATION;
5015 $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
5016 if ($socid > 0) {
5017 $sql .= " AND fs.fk_soc = ".((int) $socid);
5018 }
5019 $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
5020 $sql .= ")";
5021 } else {
5022 $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
5023 }
5024
5025 if ($socid > 0) {
5026 $sql .= " AND f.fk_soc = ".((int) $socid);
5027 }
5028 $sql .= " ORDER BY f.ref";
5029
5030 dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
5031 $resql = $this->db->query($sql);
5032 if ($resql) {
5033 while ($obj = $this->db->fetch_object($resql)) {
5034 $qualified = 0;
5035 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5036 $qualified = 1;
5037 }
5038 if ($obj->fk_statut == self::STATUS_CLOSED) {
5039 $qualified = 1;
5040 }
5041 if ($qualified) {
5042 //$ref=$obj->ref;
5043 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5044 $return[$obj->rowid] = array('ref' => $obj->ref, 'status' => $obj->fk_statut, 'type' => $obj->type, 'paye' => $obj->paye, 'paymentornot' => $paymentornot);
5045 }
5046 }
5047
5048 return $return;
5049 } else {
5050 $this->error = $this->db->error();
5051 return -1;
5052 }
5053 }
5054
5055
5056 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5063 public function load_board($user)
5064 {
5065 // phpcs:enable
5066 global $conf, $langs;
5067
5068 $clause = " WHERE";
5069
5070 $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5071 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5072 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5073 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5074 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5075 $clause = " AND";
5076 }
5077 $sql .= $clause." f.paye=0";
5078 $sql .= " AND f.entity IN (".getEntity('invoice').")";
5079 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
5080 if ($user->socid) {
5081 $sql .= " AND f.fk_soc = ".((int) $user->socid);
5082 }
5083
5084 $resql = $this->db->query($sql);
5085 if ($resql) {
5086 $langs->load("bills");
5087 $now = dol_now();
5088
5089 $response = new WorkboardResponse();
5090 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
5091 $response->label = $langs->trans("CustomerBillsUnpaid");
5092 $response->labelShort = $langs->trans("Unpaid");
5093 $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5094 $response->img = img_object('', "bill");
5095
5096 $generic_facture = new Facture($this->db);
5097
5098 while ($obj = $this->db->fetch_object($resql)) {
5099 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5100 $generic_facture->statut = $obj->status;
5101 $generic_facture->status = $obj->status;
5102
5103 $response->nbtodo++;
5104 $response->total += $obj->total_ht;
5105
5106 if ($generic_facture->hasDelay()) {
5107 $response->nbtodolate++;
5108 $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5109 }
5110 }
5111
5112 $this->db->free($resql);
5113 return $response;
5114 } else {
5115 dol_print_error($this->db);
5116 $this->error = $this->db->error();
5117 return -1;
5118 }
5119 }
5120
5121
5122 /* gestion des contacts d'une facture */
5123
5129 public function getIdBillingContact()
5130 {
5131 return $this->getIdContact('external', 'BILLING');
5132 }
5133
5139 public function getIdShippingContact()
5140 {
5141 return $this->getIdContact('external', 'SHIPPING');
5142 }
5143
5144
5153 public function initAsSpecimen($option = '')
5154 {
5155 global $conf, $langs, $user;
5156
5157 $now = dol_now();
5158 $arraynow = dol_getdate($now);
5159 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
5160
5161 // Load array of products prodids
5162 $num_prods = 0;
5163 $prodids = array();
5164 $sql = "SELECT rowid";
5165 $sql .= " FROM ".MAIN_DB_PREFIX."product";
5166 $sql .= " WHERE entity IN (".getEntity('product').")";
5167 $sql .= $this->db->plimit(100);
5168
5169 $resql = $this->db->query($sql);
5170 if ($resql) {
5171 $num_prods = $this->db->num_rows($resql);
5172 $i = 0;
5173 while ($i < $num_prods) {
5174 $i++;
5175 $row = $this->db->fetch_row($resql);
5176 $prodids[$i] = $row[0];
5177 }
5178 }
5179 //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
5180 if (empty($num_prods)) {
5181 $num_prods = 1;
5182 $prodids[$num_prods] = 1;
5183 }
5184
5185 // Initialize parameters
5186 $this->id = 0;
5187 $this->entity = $conf->entity;
5188 $this->ref = 'SPECIMEN';
5189 $this->specimen = 1;
5190 $this->socid = 1;
5191 $this->date = $nownotime;
5192 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5193 $this->cond_reglement_id = 1;
5194 $this->cond_reglement_code = 'RECEP';
5195 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
5196 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
5197 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
5198
5199 $this->note_public = 'This is a comment (public)';
5200 $this->note_private = 'This is a comment (private)';
5201 $this->note = 'This is a comment (private)';
5202
5203 $this->fk_user_author = $user->id;
5204
5205 $this->multicurrency_tx = 1;
5206 $this->multicurrency_code = $conf->currency;
5207
5208 $this->fk_incoterms = 0;
5209 $this->location_incoterms = '';
5210
5211 if (empty($option) || $option != 'nolines') {
5212 // Lines
5213 $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)
5214 $xnbp = 0;
5215 while ($xnbp < $nbp) {
5216 $line = new FactureLigne($this->db);
5217 $line->desc = $langs->trans("Description")." ".$xnbp;
5218 $line->qty = 1;
5219 $line->subprice = 100;
5220 $line->tva_tx = 19.6;
5221 $line->localtax1_tx = 0;
5222 $line->localtax2_tx = 0;
5223 $line->remise_percent = 0;
5224 if ($xnbp == 1) { // Qty is negative (product line)
5225 $prodid = mt_rand(1, $num_prods);
5226 $line->fk_product = $prodids[$prodid];
5227 $line->qty = -1;
5228 $line->total_ht = -100;
5229 $line->total_ttc = -119.6;
5230 $line->total_tva = -19.6;
5231 $line->multicurrency_total_ht = -200;
5232 $line->multicurrency_total_ttc = -239.2;
5233 $line->multicurrency_total_tva = -39.2;
5234 } elseif ($xnbp == 2) { // UP is negative (free line)
5235 $line->subprice = -100;
5236 $line->total_ht = -100;
5237 $line->total_ttc = -119.6;
5238 $line->total_tva = -19.6;
5239 $line->remise_percent = 0;
5240 $line->multicurrency_total_ht = -200;
5241 $line->multicurrency_total_ttc = -239.2;
5242 $line->multicurrency_total_tva = -39.2;
5243 } elseif ($xnbp == 3) { // Discount is 50% (product line)
5244 $prodid = mt_rand(1, $num_prods);
5245 $line->fk_product = $prodids[$prodid];
5246 $line->total_ht = 50;
5247 $line->total_ttc = 59.8;
5248 $line->total_tva = 9.8;
5249 $line->multicurrency_total_ht = 100;
5250 $line->multicurrency_total_ttc = 119.6;
5251 $line->multicurrency_total_tva = 19.6;
5252 $line->remise_percent = 50;
5253 } else { // (product line)
5254 $prodid = mt_rand(1, $num_prods);
5255 $line->fk_product = $prodids[$prodid];
5256 $line->total_ht = 100;
5257 $line->total_ttc = 119.6;
5258 $line->total_tva = 19.6;
5259 $line->multicurrency_total_ht = 200;
5260 $line->multicurrency_total_ttc = 239.2;
5261 $line->multicurrency_total_tva = 39.2;
5262 $line->remise_percent = 0;
5263 }
5264
5265 $this->lines[$xnbp] = $line;
5266
5267
5268 $this->total_ht += $line->total_ht;
5269 $this->total_tva += $line->total_tva;
5270 $this->total_ttc += $line->total_ttc;
5271
5272 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5273 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5274 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5275
5276 $xnbp++;
5277 }
5278 $this->revenuestamp = 0;
5279
5280 // Add a line "offered"
5281 $line = new FactureLigne($this->db);
5282 $line->desc = $langs->trans("Description")." (offered line)";
5283 $line->qty = 1;
5284 $line->subprice = 100;
5285 $line->tva_tx = 19.6;
5286 $line->localtax1_tx = 0;
5287 $line->localtax2_tx = 0;
5288 $line->remise_percent = 100;
5289 $line->total_ht = 0;
5290 $line->total_ttc = 0; // 90 * 1.196
5291 $line->total_tva = 0;
5292 $line->multicurrency_total_ht = 0;
5293 $line->multicurrency_total_ttc = 0;
5294 $line->multicurrency_total_tva = 0;
5295 $prodid = mt_rand(1, $num_prods);
5296 $line->fk_product = $prodids[$prodid];
5297
5298 $this->lines[$xnbp] = $line;
5299 $xnbp++;
5300 }
5301
5302 return 1;
5303 }
5304
5310 public function loadStateBoard()
5311 {
5312 global $conf, $user;
5313
5314 $this->nb = array();
5315
5316 $clause = "WHERE";
5317
5318 $sql = "SELECT count(f.rowid) as nb";
5319 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5320 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
5321 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
5322 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5323 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5324 $clause = "AND";
5325 }
5326 $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
5327
5328 $resql = $this->db->query($sql);
5329 if ($resql) {
5330 while ($obj = $this->db->fetch_object($resql)) {
5331 $this->nb["invoices"] = $obj->nb;
5332 }
5333 $this->db->free($resql);
5334 return 1;
5335 } else {
5336 dol_print_error($this->db);
5337 $this->error = $this->db->error();
5338 return -1;
5339 }
5340 }
5341
5347 public function getLinesArray()
5348 {
5349 return $this->fetch_lines();
5350 }
5351
5363 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5364 {
5365 global $conf, $langs;
5366
5367 $outputlangs->loadLangs(array("bills", "products"));
5368
5369 if (!dol_strlen($modele)) {
5370 $modele = 'crabe';
5371 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5372
5373 if (!empty($this->model_pdf)) {
5374 $modele = $this->model_pdf;
5375 } elseif (getDolGlobalString($thisTypeConfName)) {
5376 $modele = getDolGlobalString($thisTypeConfName);
5377 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
5378 $modele = getDolGlobalString('FACTURE_ADDON_PDF');
5379 }
5380 }
5381
5382 $modelpath = "core/modules/facture/doc/";
5383
5384 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5385 }
5386
5392 public function newCycle()
5393 {
5394 $sql = "SELECT max(situation_cycle_ref) as maxsituationref";
5395 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5396 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5397
5398 $resql = $this->db->query($sql);
5399 if ($resql) {
5400 if ($this->db->num_rows($resql) > 0) {
5401 $ref = 0;
5402 $obj = $this->db->fetch_object($resql);
5403 if ($obj) {
5404 $ref = $obj->maxsituationref;
5405 }
5406 $ref++;
5407 } else {
5408 $ref = 1;
5409 }
5410 $this->db->free($resql);
5411 return $ref;
5412 } else {
5413 $this->error = $this->db->lasterror();
5414 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5415 return -1;
5416 }
5417 }
5418
5419 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5425 public function is_first()
5426 {
5427 // phpcs:enable
5428 return ($this->situation_counter == 1);
5429 }
5430
5431 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5437 public function get_prev_sits()
5438 {
5439 // phpcs:enable
5440 global $conf;
5441
5442 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5443 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5444 $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5445 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5446 $resql = $this->db->query($sql);
5447 $res = array();
5448 if ($resql && $this->db->num_rows($resql) > 0) {
5449 while ($row = $this->db->fetch_object($resql)) {
5450 $id = $row->rowid;
5451 $situation = new Facture($this->db);
5452 $situation->fetch($id);
5453 $res[] = $situation;
5454 }
5455 } else {
5456 $this->error = $this->db->error();
5457 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5458 return -1;
5459 }
5460
5461 return $res;
5462 }
5463
5471 public function setFinal(User $user, $notrigger = 0)
5472 {
5473 $error = 0;
5474
5475 $this->db->begin();
5476
5477 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5478
5479 dol_syslog(__METHOD__, LOG_DEBUG);
5480 $resql = $this->db->query($sql);
5481 if (!$resql) {
5482 $this->errors[] = $this->db->error();
5483 $error++;
5484 }
5485
5486 if (!$notrigger && empty($error)) {
5487 // Call trigger
5488 $result = $this->call_trigger('BILL_MODIFY', $user);
5489 if ($result < 0) {
5490 $error++;
5491 }
5492 // End call triggers
5493 }
5494
5495 if (!$error) {
5496 $this->db->commit();
5497 return 1;
5498 } else {
5499 foreach ($this->errors as $errmsg) {
5500 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5501 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5502 }
5503 $this->db->rollback();
5504 return -1 * $error;
5505 }
5506 }
5507
5508 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5514 public function is_last_in_cycle()
5515 {
5516 // phpcs:enable
5517 global $conf;
5518
5519 if (!empty($this->situation_cycle_ref)) {
5520 // No point in testing anything if we're not inside a cycle
5521 $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5522 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5523 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5524 $resql = $this->db->query($sql);
5525
5526 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5527 $last = $res['max(situation_counter)'];
5528 return ($last == $this->situation_counter);
5529 } else {
5530 $this->error = $this->db->lasterror();
5531 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5532 return false;
5533 }
5534 } else {
5535 return true;
5536 }
5537 }
5538
5547 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5548 {
5549 $tables = array(
5550 'facture'
5551 );
5552
5553 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5554 }
5555
5564 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5565 {
5566 $tables = array(
5567 'facturedet'
5568 );
5569
5570 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
5571 }
5572
5578 public function hasDelay()
5579 {
5580 global $conf;
5581
5582 $now = dol_now();
5583
5584 // Paid invoices have status STATUS_CLOSED
5585 if ($this->status != Facture::STATUS_VALIDATED) {
5586 return false;
5587 }
5588
5589 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5590 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5591 $totalpaid = $this->getSommePaiement();
5592 $totalpaid = (float) $totalpaid;
5593 $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
5594 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5595 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5596 $hasDelay = 1;
5597 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5598 $hasDelay = 1;
5599 } else {
5600 $hasDelay = 0;
5601 }
5602 }
5603 }
5604
5605 return $hasDelay;
5606 }
5607
5613 public function isSituationInvoice()
5614 {
5615 return $this->situation_cycle_ref;
5616 }
5617
5622 public function displayRetainedWarranty()
5623 {
5624 // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
5625
5626 // 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
5627
5628 $displayWarranty = false;
5629 if (!empty($this->retained_warranty)) {
5630 $displayWarranty = true;
5631
5632 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
5633 // Check if this situation invoice is 100% for real
5634 $displayWarranty = false;
5635 if (!empty($this->situation_final)) {
5636 $displayWarranty = true;
5637 } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
5638 // $object->situation_final need validation to be done so this test is need for draft
5639 $displayWarranty = true;
5640
5641 foreach ($this->lines as $i => $line) {
5642 if ($line->product_type < 2 && $line->situation_percent < 100) {
5643 $displayWarranty = false;
5644 break;
5645 }
5646 }
5647 }
5648 }
5649 }
5650
5651 return $displayWarranty;
5652 }
5653
5658 public function getRetainedWarrantyAmount($rounding = -1)
5659 {
5660 if (empty($this->retained_warranty)) {
5661 return -1;
5662 }
5663
5664 $retainedWarrantyAmount = 0;
5665
5666 // Billed - retained warranty
5667 if ($this->isSituationInvoice() && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
5668 $displayWarranty = true;
5669 // Check if this situation invoice is 100% for real
5670 if (!empty($this->lines)) {
5671 foreach ($this->lines as $i => $line) {
5672 if ($line->product_type < 2 && $line->situation_percent < 100) {
5673 $displayWarranty = false;
5674 break;
5675 }
5676 }
5677 }
5678
5679 if ($displayWarranty && !empty($this->situation_final)) {
5681 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5682
5683 $total2BillWT = 0;
5684 foreach ($TPreviousIncoice as &$fac) {
5685 $total2BillWT += $fac->total_ttc;
5686 }
5687 $total2BillWT += $this->total_ttc;
5688
5689 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5690 } else {
5691 return -1;
5692 }
5693 } else {
5694 // Because one day retained warranty could be used on standard invoices
5695 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5696 }
5697
5698 if ($rounding < 0) {
5699 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
5700 }
5701
5702 if ($rounding > 0) {
5703 return round($retainedWarrantyAmount, $rounding);
5704 }
5705
5706 return $retainedWarrantyAmount;
5707 }
5708
5715 public function setRetainedWarranty($value)
5716 {
5717 dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
5718
5719 if ($this->status >= 0) {
5720 $fieldname = 'retained_warranty';
5721 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5722 $sql .= " SET ".$fieldname." = ".((float) $value);
5723 $sql .= ' WHERE rowid='.((int) $this->id);
5724
5725 if ($this->db->query($sql)) {
5726 $this->retained_warranty = (float) $value;
5727 return 1;
5728 } else {
5729 dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
5730 $this->error = $this->db->error();
5731 return -1;
5732 }
5733 } else {
5734 dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
5735 $this->error = 'Status of the object is incompatible '.$this->status;
5736 return -2;
5737 }
5738 }
5739
5740
5748 public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '')
5749 {
5750 if (!$timestamp && $dateYmd) {
5751 $timestamp = $this->db->jdate($dateYmd);
5752 }
5753
5754
5755 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
5756 if ($this->status >= 0) {
5757 $fieldname = 'retained_warranty_date_limit';
5758 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5759 $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
5760 $sql .= ' WHERE rowid = '.((int) $this->id);
5761
5762 if ($this->db->query($sql)) {
5763 $this->retained_warranty_date_limit = $timestamp;
5764 return 1;
5765 } else {
5766 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
5767 $this->error = $this->db->error();
5768 return -1;
5769 }
5770 } else {
5771 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5772 $this->error = 'Status of the object is incompatible '.$this->status;
5773 return -2;
5774 }
5775 }
5776
5777
5789 public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
5790 {
5791 global $conf, $langs, $user;
5792
5793 $error = 0;
5794 $this->output = '';
5795 $this->error = '';
5796 $nbMailSend = 0;
5797 $errorsMsg = array();
5798
5799 $langs->load("bills");
5800
5801 if (!isModEnabled('invoice')) { // Should not happen. If module disabled, cron job should not be visible.
5802 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5803 return 0;
5804 }
5805 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
5806 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5807 return 0;
5808 }
5809 /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
5810 $langs->load("bills");
5811 $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5812 return 0;
5813 }
5814 */
5815
5816 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5817 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
5818 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
5819 $formmail = new FormMail($this->db);
5820
5821 $now = dol_now();
5822 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
5823
5824 $tmpinvoice = new Facture($this->db);
5825
5826 dol_syslog(__METHOD__." start", LOG_INFO);
5827
5828 // Select all action comm reminder
5829 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
5830 if (!empty($paymentmode) && $paymentmode != 'all') {
5831 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
5832 }
5833 $sql .= " WHERE f.paye = 0"; // Only unpaid
5834 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
5835 if ($datetouse == 'invoicedate') {
5836 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
5837 } else {
5838 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
5839 }
5840 $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch process only one company (no sharing)
5841 if (!empty($paymentmode) && $paymentmode != 'all') {
5842 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
5843 }
5844 // TODO Add a filter to check there is no payment started yet
5845 if ($datetouse == 'invoicedate') {
5846 $sql .= $this->db->order("datef", "ASC");
5847 } else {
5848 $sql .= $this->db->order("date_lim_reglement", "ASC");
5849 }
5850
5851 $resql = $this->db->query($sql);
5852
5853 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
5854 if ($datetouse == 'invoicedate') {
5855 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedInvoicesWithDate", $stmpidate);
5856 } else {
5857 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
5858 }
5859 if (!empty($paymentmode) && $paymentmode != 'all') {
5860 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
5861 }
5862 $this->output .= '<br>';
5863
5864 if ($resql) {
5865 while ($obj = $this->db->fetch_object($resql)) {
5866 // Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
5867 $loopError = 0;
5868
5869 // Load event
5870 $res = $tmpinvoice->fetch($obj->id);
5871 if ($res > 0) {
5872 $tmpinvoice->fetch_thirdparty();
5873
5874 $outputlangs = new Translate('', $conf);
5875 if ($tmpinvoice->thirdparty->default_lang) {
5876 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5877 $outputlangs->loadLangs(array("main", "bills"));
5878 } else {
5879 $outputlangs = $langs;
5880 }
5881
5882 // Select email template according to language of recipient
5883 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
5884 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5885 $langs->load("errors");
5886 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
5887 return 0;
5888 }
5889
5890 // PREPARE EMAIL
5891 $errormesg = '';
5892
5893 // Make substitution in email content
5894 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $tmpinvoice);
5895
5896 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
5897
5898 // Topic
5899 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5900
5901 // Content
5902 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5903
5904 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
5905
5906 // Recipient
5907 $to = array();
5908 if ($forcerecipient) { // If a recipient was forced
5909 $to = array($forcerecipient);
5910 } else {
5911 $res = $tmpinvoice->fetch_thirdparty();
5912 $recipient = $tmpinvoice->thirdparty;
5913 if ($res > 0) {
5914 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
5915 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5916 foreach ($tmparraycontact as $data_email) {
5917 if (!empty($data_email['email'])) {
5918 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
5919 }
5920 }
5921 }
5922 if (empty($to) && !empty($recipient->email)) {
5923 $to[] = $recipient->email;
5924 }
5925 if (empty($to)) {
5926 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for invoice or customer.";
5927 $loopError++;
5928 }
5929 } else {
5930 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5931 $loopError++;
5932 }
5933 }
5934
5935 // Sender
5936 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
5937 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
5938 $from = $arraymessage->email_from;
5939 }
5940 if (empty($from)) {
5941 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5942 $loopError++;
5943 }
5944
5945 if (!$loopError && !empty($to)) {
5946 $this->db->begin();
5947
5948 $to = implode(',', $to);
5949 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
5950 $to = $to.','.$arraymessage->email_to;
5951 }
5952
5953 // Errors Recipient
5954 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
5955
5956 $trackid = 'inv'.$tmpinvoice->id;
5957 $sendcontext = 'standard';
5958
5959 $email_tocc = '';
5960 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
5961 $email_tocc = $arraymessage->email_tocc;
5962 }
5963
5964 $email_tobcc = '';
5965 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
5966 $email_tobcc = $arraymessage->email_tobcc;
5967 }
5968
5969 //join file is asked
5970 $joinFile = [];
5971 $joinFileName = [];
5972 $joinFileMime = [];
5973 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5974 $joinFile[] = DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc;
5975 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5976 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc);
5977 }
5978
5979 // Mail Creation
5980 $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
5981
5982 // Sending Mail
5983 if ($cMailFile->sendfile()) {
5984 $nbMailSend++;
5985
5986 // Add a line into event table
5987 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5988
5989 // Insert record of emails sent
5990 $actioncomm = new ActionComm($this->db);
5991
5992 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5993 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5994 $actioncomm->contact_id = 0;
5995
5996 $actioncomm->code = 'AC_EMAIL';
5997 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
5998 $actioncomm->note_private = $sendContent;
5999 $actioncomm->fk_project = $tmpinvoice->fk_project;
6000 $actioncomm->datep = dol_now();
6001 $actioncomm->datef = $actioncomm->datep;
6002 $actioncomm->percentage = -1; // Not applicable
6003 $actioncomm->authorid = $user->id; // User saving action
6004 $actioncomm->userownerid = $user->id; // Owner of action
6005 // Fields when action is an email (content should be added into note)
6006 $actioncomm->email_msgid = $cMailFile->msgid;
6007 $actioncomm->email_subject = $sendTopic;
6008 $actioncomm->email_from = $from;
6009 $actioncomm->email_sender = '';
6010 $actioncomm->email_to = $to;
6011 //$actioncomm->email_tocc = $sendtocc;
6012 //$actioncomm->email_tobcc = $sendtobcc;
6013 //$actioncomm->email_subject = $subject;
6014 $actioncomm->errors_to = $errors_to;
6015
6016 $actioncomm->elementtype = 'invoice';
6017 $actioncomm->fk_element = $tmpinvoice->id;
6018
6019 //$actioncomm->extraparams = $extraparams;
6020
6021 $actioncomm->create($user);
6022 } else {
6023 $errormesg = $cMailFile->error.' : '.$to;
6024 $loopError++;
6025
6026 // Add a line into event table
6027 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
6028
6029 // Insert record of emails sent
6030 $actioncomm = new ActionComm($this->db);
6031
6032 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
6033 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
6034 $actioncomm->contact_id = 0;
6035
6036 $actioncomm->code = 'AC_EMAIL';
6037 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
6038 $actioncomm->note_private = $errormesg;
6039 $actioncomm->fk_project = $tmpinvoice->fk_project;
6040 $actioncomm->datep = dol_now();
6041 $actioncomm->datef = $actioncomm->datep;
6042 $actioncomm->percentage = -1; // Not applicable
6043 $actioncomm->authorid = $user->id; // User saving action
6044 $actioncomm->userownerid = $user->id; // Owner of action
6045 // Fields when action is an email (content should be added into note)
6046 $actioncomm->email_msgid = $cMailFile->msgid;
6047 $actioncomm->email_from = $from;
6048 $actioncomm->email_sender = '';
6049 $actioncomm->email_to = $to;
6050 //$actioncomm->email_tocc = $sendtocc;
6051 //$actioncomm->email_tobcc = $sendtobcc;
6052 //$actioncomm->email_subject = $subject;
6053 $actioncomm->errors_to = $errors_to;
6054
6055 //$actioncomm->extraparams = $extraparams;
6056
6057 $actioncomm->create($user);
6058 }
6059
6060 $this->db->commit(); // We always commit
6061 }
6062
6063 if ($errormesg) {
6064 $errorsMsg[] = $errormesg;
6065 }
6066 } else {
6067 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
6068 $loopError++;
6069 }
6070
6071 $error += $loopError;
6072 }
6073 } else {
6074 $error++;
6075 }
6076
6077 if (!$error) {
6078 $this->output .= 'Nb of emails sent : '.$nbMailSend;
6079
6080 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
6081
6082 return 0;
6083 } else {
6084 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
6085
6086 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
6087
6088 return $error;
6089 }
6090 }
6091
6098 public function willBeLastOfSameType($allow_validated_drafts = false)
6099 {
6100 // get date of last validated invoices of same type
6101 $sql = "SELECT datef";
6102 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
6103 $sql .= " WHERE type = " . (int) $this->type ;
6104 $sql .= " AND date_valid IS NOT NULL";
6105 $sql .= " AND entity IN (".getEntity('invoice').")";
6106 $sql .= " ORDER BY datef DESC LIMIT 1";
6107
6108 $result = $this->db->query($sql);
6109 if ($result) {
6110 // compare with current validation date
6111 if ($this->db->num_rows($result)) {
6112 $obj = $this->db->fetch_object($result);
6113 $last_date = $this->db->jdate($obj->datef);
6114 $invoice_date = $this->date;
6115
6116 $is_last_of_same_type = $invoice_date >= $last_date;
6117 if ($allow_validated_drafts) {
6118 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
6119 }
6120
6121 return array($is_last_of_same_type, $last_date);
6122 } else {
6123 // element is first of type to be validated
6124 return array(true);
6125 }
6126 } else {
6127 dol_print_error($this->db);
6128 }
6129
6130 return array();
6131 }
6132
6140 public function getKanbanView($option = '', $arraydata = null)
6141 {
6142 global $langs;
6143
6144 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6145
6146 $picto = $this->picto;
6147 if ($this->type == self::TYPE_REPLACEMENT) {
6148 $picto .= 'r'; // Replacement invoice
6149 }
6150 if ($this->type == self::TYPE_CREDIT_NOTE) {
6151 $picto .= 'a'; // Credit note
6152 }
6153 if ($this->type == self::TYPE_DEPOSIT) {
6154 $picto .= 'd'; // Deposit invoice
6155 }
6156
6157 $return = '<div class="box-flex-item box-flex-grow-zero">';
6158 $return .= '<div class="info-box info-box-sm">';
6159 $return .= '<span class="info-box-icon bg-infobox-action">';
6160 $return .= img_picto('', $picto);
6161 $return .= '</span>';
6162 $return .= '<div class="info-box-content">';
6163 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
6164 if ($selected >= 0) {
6165 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6166 }
6167 if (!empty($arraydata['thirdparty'])) {
6168 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
6169 }
6170 if (property_exists($this, 'date')) {
6171 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
6172 }
6173 if (property_exists($this, 'total_ht')) {
6174 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
6175 $return .= ' '.$langs->trans("HT");
6176 $return .= '</span>';
6177 }
6178 if (method_exists($this, 'getLibStatut')) {
6179 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
6180 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
6181 }
6182 $return .= '</div>';
6183 $return .= '</div>';
6184 $return .= '</div>';
6185 return $return;
6186 }
6187}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
$object ref
Definition info.php:89
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Retourne id des contacts clients de livraison.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines.
update(User $user, $notrigger=0)
Update database.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Retourne id des contacts clients de facturation.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clickable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
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')
Set absolute discount.
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.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
getRetainedWarrantyAmount($rounding=-1)
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
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.
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 getIdFromCode($dbs, $code)
Get id of currency from code.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:660
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:646
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:600
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:538
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:619
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
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 '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
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_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.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:150