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