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