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