dolibarr 20.0.4
facture.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
5 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
6 * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
7 * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
9 * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
10 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
11 * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
12 * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
13 * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
14 * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
15 * Copyright (C) 2013 Cedric Gross <c.gross@kreiz-it.fr>
16 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
17 * Copyright (C) 2016-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.'/core/class/commonobjectline.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
119
120 public $datem;
121
125 public $delivery_date; // Date expected of shipment (date of start of shipment, not the reception that occurs some days after)
126
132 public $ref_client;
133
137 public $ref_customer;
138
139 public $total_ht;
140 public $total_tva;
141 public $total_localtax1;
142 public $total_localtax2;
143 public $total_ttc;
144 public $revenuestamp;
145
146 public $resteapayer;
147
151 public $paye;
152
161 public $linked_objects = array();
162
166 public $fk_bank;
167
171 public $lines = array();
172
176 public $line;
177 public $extraparams = array();
178
182 public $fac_rec;
183
184 public $date_pointoftax;
185
186
190 public $situation_cycle_ref;
191
195 public $situation_counter;
196
200 public $situation_final;
201
205 public $tab_previous_situation_invoice = array();
206
210 public $tab_next_situation_invoice = array();
211
215 public $oldcopy;
216
220 public $retained_warranty;
221
225 public $retained_warranty_date_limit;
226
230 public $retained_warranty_fk_cond_reglement;
231
235 public $availability_id;
236
237 public $date_closing;
238
242 public $source;
243
248 public $remise_percent;
249
253 public $online_payment_url;
254
255
256
281 // BEGIN MODULEBUILDER PROPERTIES
285 public $fields = array(
286 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 1),
287 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 5),
288 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
289 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 10),
290 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'Ref ext', 'enabled' => 1, 'visible' => 0, 'position' => 12),
291 'type' => array('type' => 'smallint(6)', 'label' => 'Type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
292 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
293 //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
294 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 50),
295 'datef' => array('type' => 'date', 'label' => 'DateInvoice', 'enabled' => 1, 'visible' => 1, 'position' => 20),
296 'date_valid' => array('type' => 'date', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 22),
297 'date_lim_reglement' => array('type' => 'date', 'label' => 'DateDue', 'enabled' => 1, 'visible' => 1, 'position' => 25),
298 'date_closing' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 30),
299 'paye' => array('type' => 'smallint(6)', 'label' => 'InvoicePaidCompletely', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 80),
300 //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85),
301 //'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
302 //'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>91),
303 //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
304 'close_code' => array('type' => 'varchar(16)', 'label' => 'EarlyClosingReason', 'enabled' => 1, 'visible' => -1, 'position' => 92),
305 'close_note' => array('type' => 'varchar(128)', 'label' => 'EarlyClosingComment', 'enabled' => 1, 'visible' => -1, 'position' => 93),
306 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 95, 'isameasure' => 1),
307 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => -1, 'position' => 100, 'isameasure' => 1),
308 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => -1, 'position' => 110, 'isameasure' => 1),
309 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => -1, 'position' => 120, 'isameasure' => 1),
310 'revenuestamp' => array('type' => 'double(24,8)', 'label' => 'RevenueStamp', 'enabled' => 1, 'visible' => -1, 'position' => 115, 'isameasure' => 1),
311 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
312 'fk_facture_source' => array('type' => 'integer', 'label' => 'SourceInvoice', 'enabled' => 1, 'visible' => -1, 'position' => 170),
313 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => 1, 'visible' => -1, 'position' => 175),
314 'fk_account' => array('type' => 'integer', 'label' => 'Fk account', 'enabled' => 1, 'visible' => -1, 'position' => 180),
315 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'CurrencyCode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
316 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 190),
317 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 195),
318 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 205),
319 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 210),
320 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 215),
321 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
322 'situation_cycle_ref' => array('type' => 'smallint(6)', 'label' => 'Situation cycle ref', 'enabled' => '$conf->global->INVOICE_USE_SITUATION', 'visible' => -1, 'position' => 230),
323 'situation_counter' => array('type' => 'smallint(6)', 'label' => 'Situation counter', 'enabled' => '$conf->global->INVOICE_USE_SITUATION', 'visible' => -1, 'position' => 235),
324 'situation_final' => array('type' => 'smallint(6)', 'label' => 'Situation final', 'enabled' => 'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1', 'visible' => -1, 'position' => 240),
325 'retained_warranty' => array('type' => 'double', 'label' => 'Retained warranty', 'enabled' => '$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible' => -1, 'position' => 245),
326 'retained_warranty_date_limit' => array('type' => 'date', 'label' => 'Retained warranty date limit', 'enabled' => '$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible' => -1, 'position' => 250),
327 'retained_warranty_fk_cond_reglement' => array('type' => 'integer', 'label' => 'Retained warranty fk cond reglement', 'enabled' => '$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible' => -1, 'position' => 255),
328 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => '$conf->incoterm->enabled', 'visible' => -1, 'position' => 260),
329 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => '$conf->incoterm->enabled', 'visible' => -1, 'position' => 265),
330 'date_pointoftax' => array('type' => 'date', 'label' => 'DatePointOfTax', 'enabled' => '$conf->global->INVOICE_POINTOFTAX_DATE', 'visible' => -1, 'position' => 270),
331 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyID', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 275),
332 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 280),
333 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 285, 'isameasure' => 1),
334 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 290, 'isameasure' => 1),
335 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 291, 'isameasure' => 1),
336 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 292, 'isameasure' => 1),
337 'fk_fac_rec_source' => array('type' => 'integer', 'label' => 'RecurringInvoiceSource', 'enabled' => 1, 'visible' => -1, 'position' => 305),
338 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 310),
339 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 315),
340 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'visible' => -1, 'position' => 320),
341 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 500),
342 'tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 502),
343 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 506),
344 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModification', 'enabled' => 1, 'visible' => -1, 'notnull' => -1, 'position' => 508),
345 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 510),
346 'fk_user_closing' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 512),
347 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
348 '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')),
349 );
350 // END MODULEBUILDER PROPERTIES
351
355 const TYPE_STANDARD = 0;
356
361
366
370 const TYPE_DEPOSIT = 3;
371
375 const TYPE_PROFORMA = 4;
376
380 const TYPE_SITUATION = 5;
381
385 const STATUS_DRAFT = 0;
386
391
399 const STATUS_CLOSED = 2;
400
409
410 const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandoned remain - escompte
411 const CLOSECODE_BADDEBT = 'badcustomer'; // Abandoned remain - bad customer
412 const CLOSECODE_BANKCHARGE = 'bankcharge'; // Abandoned remain - bank charge
413 const CLOSECODE_OTHER = 'other'; // Abandoned remain - other
414
415 const CLOSECODE_ABANDONED = 'abandon'; // Abandoned - other
416 const CLOSECODE_REPLACED = 'replaced'; // Closed after doing a replacement invoice
417
418
424 public function __construct(DoliDB $db)
425 {
426 $this->db = $db;
427
428 $this->ismultientitymanaged = 1;
429 $this->isextrafieldmanaged = 1;
430 }
431
442 public function create(User $user, $notrigger = 0, $forceduedate = 0)
443 {
444 global $langs, $conf, $mysoc, $hookmanager;
445 $error = 0;
446 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
447 // Clean parameters
448 if (empty($this->type)) {
449 $this->type = self::TYPE_STANDARD;
450 }
451
452 $this->ref_client = trim($this->ref_client); // deprecated
453 $this->ref_customer = trim($this->ref_customer);
454
455 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : '');
456 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private); // deprecated
457 $this->note_public = (isset($this->note_public) ? trim($this->note_public) : '');
458
459 if (!$this->cond_reglement_id) {
460 $this->cond_reglement_id = 0;
461 }
462 if (!$this->mode_reglement_id) {
463 $this->mode_reglement_id = 0;
464 }
465 $this->status = self::STATUS_DRAFT;
466 $this->statut = self::STATUS_DRAFT; // deprecated
467
468 if (!empty($this->multicurrency_code)) {
469 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate of multicurrency_code only if not using original rate)
470 if (empty($this->multicurrency_tx)) {
471 // If original rate is not set, we take a default value from date
472 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
473 } else {
474 // original rate multicurrency_tx and multicurrency_code are set, we use them
475 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
476 }
477 } else {
478 $this->fk_multicurrency = 0;
479 }
480 if (empty($this->fk_multicurrency)) {
481 $this->multicurrency_code = $conf->currency;
482 $this->fk_multicurrency = 0;
483 $this->multicurrency_tx = 1;
484 }
485
486 dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
487
488 // Check parameters
489 if (empty($this->date)) {
490 $this->error = "Try to create an invoice with an empty parameter (date)";
491 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
492 return -3;
493 }
494 $soc = new Societe($this->db);
495 $result = $soc->fetch($this->socid);
496 if ($result < 0) {
497 $this->error = "Failed to fetch company: ".$soc->error;
498 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
499 return -2;
500 }
501
502 $now = dol_now();
503 $this->date_creation = $now;
504
505 $this->db->begin();
506
507 $originaldatewhen = null;
508 $nextdatewhen = null;
509 $previousdaynextdatewhen = null;
510
511 // Erase some properties of the invoice to create with the one of the recurring invoice
512 if ($this->fac_rec > 0) {
513 $this->fk_fac_rec_source = $this->fac_rec;
514
515 if (getDolGlobalString('MODEL_FAC_REC_AUTHOR')) {
516 $origin_user_author_id = ($this->fk_user_author > 0 ? $this->fk_user_author : $origin_user_author_id);
517 }
518 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
519 $_facrec = new FactureRec($this->db);
520 $result = $_facrec->fetch($this->fac_rec);
521 $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
522
523 // Define some dates
524 $originaldatewhen = $_facrec->date_when;
525 $nextdatewhen = null;
526 $previousdaynextdatewhen = null;
527 if ($originaldatewhen) {
528 $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
529 $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
530 }
531
532 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.
533 $this->socid = $_facrec->socid;
534 }
535 $this->entity = $_facrec->entity; // Invoice created in same entity than template
536
537 // Fields coming from GUI.
538 // @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
539 // set by posted page with $object->xxx = ... and this section should be removed.
540 $this->fk_project = GETPOSTINT('projectid') > 0 ? GETPOSTINT('projectid') : $_facrec->fk_project;
541 $this->note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
542 $this->note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
543 $this->model_pdf = GETPOSTISSET('model') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
544 $this->cond_reglement_id = GETPOSTINT('cond_reglement_id') > 0 ? GETPOSTINT('cond_reglement_id') : $_facrec->cond_reglement_id;
545 $this->mode_reglement_id = GETPOSTINT('mode_reglement_id') > 0 ? GETPOSTINT('mode_reglement_id') : $_facrec->mode_reglement_id;
546 $this->fk_account = GETPOST('fk_account') > 0 ? GETPOSTINT('fk_account') : $_facrec->fk_account;
547
548 // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
549 $this->total_ht = $_facrec->total_ht;
550 $this->total_ttc = $_facrec->total_ttc;
551
552 // Fields always coming from template
553 //$this->remise_absolue = $_facrec->remise_absolue;
554 //$this->remise_percent = $_facrec->remise_percent; // TODO deprecated
555 $this->fk_incoterms = $_facrec->fk_incoterms;
556 $this->location_incoterms = $_facrec->location_incoterms;
557
558 // Clean parameters
559 if (!$this->type) {
560 $this->type = self::TYPE_STANDARD;
561 }
562 $this->ref_client = trim($this->ref_client);
563 $this->ref_customer = trim($this->ref_customer);
564 $this->note_public = trim($this->note_public);
565 $this->note_private = trim($this->note_private);
566 $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
567
568 $this->array_options = $_facrec->array_options;
569
570 if (!$this->mode_reglement_id) {
571 $this->mode_reglement_id = 0;
572 }
573 $this->status = self::STATUS_DRAFT;
574 $this->statut = self::STATUS_DRAFT; // deprecated
575
576 $this->linked_objects = $_facrec->linkedObjectsIds;
577 // We do not add link to template invoice or next invoice will be linked to all generated invoices
578 //$this->linked_objects['facturerec'][0] = $this->fac_rec;
579
580 // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
581 if ($_facrec->frequency > 0) {
582 dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
583 if (empty($_facrec->date_when)) {
584 $_facrec->date_when = $now;
585 }
586 $next_date = $_facrec->getNextDate(); // Calculate next date
587 $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
588 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
589 $result = $_facrec->setNextDate($next_date, 1);
590 }
591
592 // Define lang of customer
593 $outputlangs = $langs;
594 $newlang = '';
595
596 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
597 $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
598 }
599 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
600 $newlang = $this->default_lang; // for thirdparty
601 }
602 if (!empty($newlang)) {
603 $outputlangs = new Translate("", $conf);
604 $outputlangs->setDefaultLang($newlang);
605 }
606
607 // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
608 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
609 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
610 $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
611 $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
612 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
613 $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
614 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
615 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
616 $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
617 $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
618 // Only for template invoice
619 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ? dol_print_date($originaldatewhen, 'dayhour') : '');
620 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ? dol_print_date($nextdatewhen, 'dayhour') : '');
621 $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '');
622 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
623 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
624
625 //var_dump($substitutionarray);exit;
626
627 complete_substitutions_array($substitutionarray, $outputlangs);
628
629 $this->note_public = make_substitutions($this->note_public, $substitutionarray);
630 $this->note_private = make_substitutions($this->note_private, $substitutionarray);
631 }
632
633 // Define due date if not already defined
634 if (empty($forceduedate)) {
635 $duedate = $this->calculate_date_lim_reglement();
636 /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
637 dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
638 return -1;
639 }*/
640 $this->date_lim_reglement = $duedate;
641 } else {
642 $this->date_lim_reglement = $forceduedate;
643 }
644
645 // Insert into database
646 $socid = $this->socid;
647
648 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
649 $sql .= " ref";
650 $sql .= ", entity";
651 $sql .= ", ref_ext";
652 $sql .= ", type";
653 $sql .= ", subtype";
654 $sql .= ", fk_soc";
655 $sql .= ", datec";
656 $sql .= ", datef";
657 $sql .= ", date_pointoftax";
658 $sql .= ", note_private";
659 $sql .= ", note_public";
660 $sql .= ", ref_client";
661 $sql .= ", fk_account";
662 $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
663 $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
664 $sql .= ", situation_cycle_ref, situation_counter, situation_final";
665 $sql .= ", fk_incoterms, location_incoterms";
666 $sql .= ", fk_multicurrency";
667 $sql .= ", multicurrency_code";
668 $sql .= ", multicurrency_tx";
669 $sql .= ", retained_warranty";
670 $sql .= ", retained_warranty_date_limit";
671 $sql .= ", retained_warranty_fk_cond_reglement";
672 $sql .= ")";
673 $sql .= " VALUES (";
674 $sql .= "'(PROV)'";
675 $sql .= ", ".setEntity($this);
676 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
677 $sql .= ", '".$this->db->escape($this->type)."'";
678 $sql .= ", ".($this->subtype ? "'".$this->db->escape($this->subtype)."'" : "null");
679 $sql .= ", ".((int) $socid);
680 $sql .= ", '".$this->db->idate($this->date_creation)."'";
681 $sql .= ", '".$this->db->idate($this->date)."'";
682 $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
683 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
684 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
685 $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : ($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"));
686 $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
687 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
688 $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
689 $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
690 $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
691 $sql .= ", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id : "null");
692 $sql .= ", ".($this->fk_project ? (int) $this->fk_project : "null");
693 $sql .= ", ".((int) $this->cond_reglement_id);
694 $sql .= ", ".((int) $this->mode_reglement_id);
695 $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
696 $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
697 $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
698 $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
699 $sql .= ", ".($this->situation_final ? (int) $this->situation_final : 0);
700 $sql .= ", ".(int) $this->fk_incoterms;
701 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
702 $sql .= ", ".(int) $this->fk_multicurrency;
703 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
704 $sql .= ", ".(float) $this->multicurrency_tx;
705 $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty));
706 $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
707 $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
708 $sql .= ")";
709
710 $resql = $this->db->query($sql);
711 if ($resql) {
712 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
713
714 // Update ref with new one
715 $this->ref = '(PROV'.$this->id.')';
716 $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
717
718 $resql = $this->db->query($sql);
719 if (!$resql) {
720 $error++;
721 }
722
723 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
724 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
725 }
726
727 // Add object linked
728 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
729 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
730 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, ...))
731 foreach ($tmp_origin_id as $origin_id) {
732 $ret = $this->add_object_linked($origin, $origin_id);
733 if (!$ret) {
734 $this->error = $this->db->lasterror();
735 $error++;
736 }
737 }
738 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
739 $origin_id = $tmp_origin_id;
740 $ret = $this->add_object_linked($origin, $origin_id);
741 if (!$ret) {
742 $this->error = $this->db->lasterror();
743 $error++;
744 }
745 }
746 }
747 }
748
749 // Propagate contacts
750 if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
751 $originforcontact = $this->origin;
752 $originidforcontact = $this->origin_id;
753 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
754 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
755 $exp = new Expedition($this->db);
756 $exp->fetch($this->origin_id);
757 $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
758 if (count($exp->linkedObjectsIds['commande']) > 0) {
759 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
760 $originforcontact = 'commande';
761 if (is_object($value)) {
762 $originidforcontact = $value->id;
763 } else {
764 $originidforcontact = $value;
765 }
766 break; // We take first one
767 }
768 }
769 }
770
771 $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";
772 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
773
774 $resqlcontact = $this->db->query($sqlcontact);
775 if ($resqlcontact) {
776 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
777 //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
778 $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
779 }
780 } else {
781 dol_print_error($resqlcontact);
782 }
783 }
784
785 /*
786 * Insert lines of invoices, if not from template invoice, into database
787 */
788 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
789 $fk_parent_line = 0;
790
791 dol_syslog("There is ".count($this->lines)." lines into ->lines that are InvoiceLines");
792 foreach ($this->lines as $i => $val) {
793 $newinvoiceline = $this->lines[$i];
794
795 $newinvoiceline->context = $this->context;
796
797 $newinvoiceline->fk_facture = $this->id;
798
799 $newinvoiceline->origin = $this->lines[$i]->element;
800 $newinvoiceline->origin_id = $this->lines[$i]->id;
801
802 // Auto set date of service ?
803 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
804 $newinvoiceline->date_start = $originaldatewhen;
805 }
806 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
807 $newinvoiceline->date_end = $previousdaynextdatewhen;
808 }
809
810 if ($result >= 0) {
811 // Reset fk_parent_line for no child products and special product
812 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
813 $fk_parent_line = 0;
814 }
815
816 // Complete vat rate with code
817 $vatrate = $newinvoiceline->tva_tx;
818 if ($newinvoiceline->vat_src_code && ! preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
819 $vatrate .= ' ('.$newinvoiceline->vat_src_code.')';
820 }
821
822 $newinvoiceline->fk_parent_line = $fk_parent_line;
823
824 if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
825 $discount = new DiscountAbsolute($this->db);
826 $discount->fetch($newinvoiceline->fk_remise_except);
827
828 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
829 $newinvoiceline->fk_remise_except = $discountId;
830 }
831
832 $result = $this->addline(
833 $newinvoiceline->desc,
834 $newinvoiceline->subprice,
835 $newinvoiceline->qty,
836 $vatrate,
837 $newinvoiceline->localtax1_tx,
838 $newinvoiceline->localtax2_tx,
839 $newinvoiceline->fk_product,
840 $newinvoiceline->remise_percent,
841 $newinvoiceline->date_start,
842 $newinvoiceline->date_end,
843 $newinvoiceline->fk_code_ventilation,
844 $newinvoiceline->info_bits,
845 $newinvoiceline->fk_remise_except,
846 'HT',
847 0,
848 $newinvoiceline->product_type,
849 $newinvoiceline->rang,
850 $newinvoiceline->special_code,
851 $newinvoiceline->element,
852 $newinvoiceline->id,
853 $fk_parent_line,
854 $newinvoiceline->fk_fournprice,
855 $newinvoiceline->pa_ht,
856 $newinvoiceline->label,
857 $newinvoiceline->array_options,
858 $newinvoiceline->situation_percent,
859 $newinvoiceline->fk_prev_id,
860 $newinvoiceline->fk_unit,
861 $newinvoiceline->multicurrency_subprice,
862 $newinvoiceline->ref_ext,
863 1
864 );
865
866 if ($result < 0) {
867 $this->error = $newinvoiceline->error;
868 $this->errors = array_merge($this->errors, $newinvoiceline->errors);
869 $error++;
870 break;
871 }
872
873 // Defined the new fk_parent_line
874 if ($result > 0 && $newinvoiceline->product_type == 9) {
875 $fk_parent_line = $result;
876 }
877 }
878 }
879 } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
880 $fk_parent_line = 0;
881
882 dol_syslog("There is ".count($this->lines)." lines into ->lines as a simple array");
883
884 foreach ($this->lines as $i => $val) {
885 $line = $this->lines[$i];
886
887 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
888 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
889 if (!is_object($line)) {
890 $line = (object) $line;
891 }
892
893 if ($result >= 0) {
894 // Reset fk_parent_line for no child products and special product
895 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
896 $fk_parent_line = 0;
897 }
898
899 // Complete vat rate with code
900 $vatrate = $line->tva_tx;
901 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
902 $vatrate .= ' ('.$line->vat_src_code.')';
903 }
904
905 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
906 $originid = $line->origin_id;
907 $origintype = $line->origin;
908 } else {
909 $originid = $line->id;
910 $origintype = $this->element;
911 }
912
913 // init ref_ext
914 if (empty($line->ref_ext)) {
915 $line->ref_ext = '';
916 }
917
918 $result = $this->addline(
919 $line->desc,
920 $line->subprice,
921 $line->qty,
922 $vatrate,
923 $line->localtax1_tx,
924 $line->localtax2_tx,
925 $line->fk_product,
926 $line->remise_percent,
927 $line->date_start,
928 $line->date_end,
929 $line->fk_code_ventilation,
930 $line->info_bits,
931 $line->fk_remise_except,
932 'HT',
933 0,
934 $line->product_type,
935 $line->rang,
936 $line->special_code,
937 $origintype,
938 $originid,
939 $fk_parent_line,
940 $line->fk_fournprice,
941 $line->pa_ht,
942 $line->label,
943 $line->array_options,
944 $line->situation_percent,
945 $line->fk_prev_id,
946 $line->fk_unit,
947 $line->multicurrency_subprice,
948 $line->ref_ext,
949 1
950 );
951 if ($result < 0) {
952 $this->error = $this->db->lasterror();
953 dol_print_error($this->db);
954 $this->db->rollback();
955 return -1;
956 }
957
958 // Defined the new fk_parent_line
959 if ($result > 0 && $line->product_type == 9) {
960 $fk_parent_line = $result;
961 }
962 }
963 }
964 }
965
966 /*
967 * Insert lines coming from the template invoice
968 */
969 if (!$error && $this->fac_rec > 0) {
970 dol_syslog("There is ".count($_facrec->lines)." lines from recurring invoice");
971 $fk_parent_line = 0;
972
973 foreach ($_facrec->lines as $i => $val) {
974 if ($_facrec->lines[$i]->fk_product) {
975 $prod = new Product($this->db);
976 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
977 }
978
979 // Reset fk_parent_line for no child products and special product
980 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
981 $fk_parent_line = 0;
982 }
983
984 // For line from template invoice, we use data from template invoice
985 /*
986 $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
987 $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
988 if (empty($tva_tx)) $tva_npr=0;
989 $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
990 $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
991 */
992 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
993 $tva_npr = $_facrec->lines[$i]->info_bits;
994 if (empty($tva_tx)) {
995 $tva_npr = 0;
996 }
997 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
998 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
999
1000 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1001 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1002
1003 // If buyprice not defined from template invoice, we try to guess the best value
1004 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1005 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1006 $producttmp = new ProductFournisseur($this->db);
1007 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1008
1009 // If margin module defined on costprice, we try the costprice
1010 // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
1011 // else we get the best supplier price
1012 if (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($producttmp->cost_price)) {
1013 $buyprice = $producttmp->cost_price;
1014 } elseif (isModEnabled('stock') && (getDolGlobalString('MARGIN_TYPE') == 'costprice' || getDolGlobalString('MARGIN_TYPE') == 'pmp') && !empty($producttmp->pmp)) {
1015 $buyprice = $producttmp->pmp;
1016 } else {
1017 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1018 if ($producttmp->product_fourn_price_id > 0) {
1019 $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
1020 }
1021 }
1022 }
1023 }
1024
1025 $result_insert = $this->addline(
1026 $_facrec->lines[$i]->desc,
1027 $_facrec->lines[$i]->subprice,
1028 $_facrec->lines[$i]->qty,
1029 $tva_tx,
1030 $localtax1_tx,
1031 $localtax2_tx,
1032 $_facrec->lines[$i]->fk_product,
1033 $_facrec->lines[$i]->remise_percent,
1034 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
1035 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
1036 0,
1037 $tva_npr,
1038 '',
1039 'HT',
1040 0,
1041 $_facrec->lines[$i]->product_type,
1042 $_facrec->lines[$i]->rang,
1043 $_facrec->lines[$i]->special_code,
1044 '',
1045 0,
1046 $fk_parent_line,
1047 $fk_product_fournisseur_price,
1048 $buyprice,
1049 $_facrec->lines[$i]->label,
1050 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1051 100, // situation percent is undefined on recurring invoice lines
1052 '',
1053 $_facrec->lines[$i]->fk_unit,
1054 $_facrec->lines[$i]->multicurrency_subprice,
1055 $_facrec->lines[$i]->ref_ext,
1056 1
1057 );
1058
1059 // Defined the new fk_parent_line
1060 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1061 $fk_parent_line = $result_insert;
1062 }
1063
1064 if ($result_insert < 0) {
1065 $error++;
1066 $this->error = $this->db->error();
1067 break;
1068 }
1069 }
1070 }
1071
1072 if (!$error) {
1073 $result = $this->update_price(1, 'auto', 0, $mysoc);
1074 if ($result > 0) {
1075 $action = 'create';
1076
1077 // Actions on extra fields
1078 if (!$error) {
1079 $result = $this->insertExtraFields();
1080 if ($result < 0) {
1081 $error++;
1082 }
1083 }
1084
1085 if (!$error && !$notrigger) {
1086 // Call trigger
1087 $result = $this->call_trigger('BILL_CREATE', $user);
1088 if ($result < 0) {
1089 $error++;
1090 }
1091 }
1092
1093 if (!$error) {
1094 $this->db->commit();
1095 return $this->id;
1096 } else {
1097 $this->db->rollback();
1098 return -4;
1099 }
1100 } else {
1101 $this->error = $langs->trans('FailedToUpdatePrice');
1102 $this->db->rollback();
1103 return -3;
1104 }
1105 } else {
1106 dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
1107 $this->db->rollback();
1108 return -2;
1109 }
1110 } else {
1111 $this->error = $this->db->error();
1112 $this->db->rollback();
1113 return -1;
1114 }
1115 }
1116
1117
1125 public function createFromCurrent(User $user, $invertdetail = 0)
1126 {
1127 // Source invoice load
1128 $facture = new Facture($this->db);
1129
1130 // Retrieve all extrafield
1131 // fetch optionals attributes and labels
1132 $this->fetch_optionals();
1133
1134 if (!empty($this->array_options)) {
1135 $facture->array_options = $this->array_options;
1136 }
1137
1138 foreach ($this->lines as &$line) {
1139 $line->fetch_optionals(); //fetch extrafields
1140 }
1141
1142 $facture->fk_facture_source = $this->fk_facture_source;
1143 $facture->type = $this->type;
1144 $facture->subtype = $this->subtype;
1145 $facture->socid = $this->socid;
1146 $facture->date = $this->date;
1147 $facture->date_pointoftax = $this->date_pointoftax;
1148 $facture->note_public = $this->note_public;
1149 $facture->note_private = $this->note_private;
1150 $facture->ref_client = $this->ref_client;
1151 $facture->ref_customer = $this->ref_customer;
1152 $facture->model_pdf = $this->model_pdf;
1153 $facture->fk_project = $this->fk_project;
1154 $facture->cond_reglement_id = $this->cond_reglement_id;
1155 $facture->mode_reglement_id = $this->mode_reglement_id;
1156 //$facture->remise_absolue = $this->remise_absolue;
1157 //$facture->remise_percent = $this->remise_percent; // TODO deprecated
1158
1159 $facture->origin = $this->origin;
1160 $facture->origin_id = $this->origin_id;
1161 $facture->fk_account = $this->fk_account;
1162
1163 $facture->lines = $this->lines; // Array of lines of invoice
1164 $facture->situation_counter = $this->situation_counter;
1165 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1166 $facture->situation_final = $this->situation_final;
1167
1168 $facture->retained_warranty = $this->retained_warranty;
1169 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1170 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1171
1172 $facture->fk_user_author = $user->id;
1173 $facture->user_creation_id = $user->id;
1174
1175
1176 // Loop on each line of new invoice
1177 foreach ($facture->lines as $i => $tmpline) {
1178 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1179 if ($invertdetail) {
1180 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1181 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1182 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1183 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1184 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1185 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1186 $facture->lines[$i]->ref_ext = '';
1187 }
1188 }
1189
1190 dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
1191
1192 $facid = $facture->create($user);
1193 if ($facid <= 0) {
1194 $this->error = $facture->error;
1195 $this->errors = $facture->errors;
1196 } elseif ($this->type == self::TYPE_SITUATION && getDolGlobalString('INVOICE_USE_SITUATION')) {
1197 $this->fetchObjectLinked('', '', $this->id, 'facture');
1198
1199 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1200 foreach ($Tfk_object as $fk_object) {
1201 $facture->add_object_linked($typeObject, $fk_object);
1202 }
1203 }
1204
1205 $facture->add_object_linked('facture', $this->fk_facture_source);
1206 }
1207
1208 return $facid;
1209 }
1210
1211
1219 public function createFromClone(User $user, $fromid = 0)
1220 {
1221 global $conf, $hookmanager;
1222
1223 $error = 0;
1224
1225 $object = new Facture($this->db);
1226
1227 $this->db->begin();
1228
1229 $object->fetch($fromid);
1230
1231 // Load source object
1232 $objFrom = clone $object;
1233
1234 // Change socid if needed
1235 if (!empty($this->socid) && $this->socid != $object->socid) {
1236 $objsoc = new Societe($this->db);
1237
1238 if ($objsoc->fetch($this->socid) > 0) {
1239 $object->socid = $objsoc->id;
1240 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1241 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1242 $object->fk_project = 0;
1243 $object->fk_delivery_address = 0;
1244 }
1245
1246 // TODO Change product price if multi-prices
1247 }
1248
1249 $object->id = 0;
1250 $object->statut = self::STATUS_DRAFT;
1251 $object->status = self::STATUS_DRAFT;
1252
1253 // Clear fields
1254 $object->date = (empty($this->date) ? dol_now() : $this->date);
1255 $object->user_creation_id = $user->id;
1256 $object->user_validation_id = null;
1257 $object->fk_user_author = $user->id;
1258 $object->fk_user_valid = null;
1259 $object->fk_facture_source = 0;
1260 $object->date_creation = '';
1261 $object->date_modification = '';
1262 $object->date_validation = '';
1263 $object->ref_client = '';
1264 $object->close_code = '';
1265 $object->close_note = '';
1266 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1267 $object->note_private = '';
1268 $object->note_public = '';
1269 }
1270
1271 // Loop on each line of new invoice
1272 foreach ($object->lines as $i => $line) {
1273 if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
1274 unset($object->lines[$i]);
1275 continue;
1276 }
1277
1278 // Block to update dates of service (month by month only if previously filled and similar to start and end of month)
1279 // If it's a service with start and end dates
1280 if (getDolGlobalString('INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1281 // Get the dates
1282 $start = dol_getdate($line->date_start);
1283 $end = dol_getdate($line->date_end);
1284
1285 // Get the first and last day of the month
1286 $first = dol_get_first_day($start['year'], $start['mon']);
1287 $last = dol_get_last_day($end['year'], $end['mon']);
1288
1289 //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
1290 //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
1291 // If start date is first date of month and end date is last date of month
1292 if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
1293 && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
1294 $nextMonth = dol_get_next_month($end['mon'], $end['year']);
1295 $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
1296 $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
1297 $object->lines[$i]->date_start = $newFirst;
1298 $object->lines[$i]->date_end = $newLast;
1299 }
1300 }
1301
1302 $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
1303 }
1304
1305 // Create clone
1306 $object->context['createfromclone'] = 'createfromclone';
1307 $result = $object->create($user);
1308 if ($result < 0) {
1309 $error++;
1310 $this->error = $object->error;
1311 $this->errors = $object->errors;
1312 } else {
1313 // copy internal contacts
1314 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1315 $error++;
1316 $this->error = $object->error;
1317 $this->errors = $object->errors;
1318 } elseif ($object->socid == $objFrom->socid) {
1319 // copy external contacts if same company
1320 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1321 $error++;
1322 $this->error = $object->error;
1323 $this->errors = $object->errors;
1324 }
1325 }
1326 }
1327
1328 if (!$error) {
1329 // Hook of thirdparty module
1330 if (is_object($hookmanager)) {
1331 $parameters = array('objFrom' => $objFrom);
1332 $action = '';
1333 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1334 if ($reshook < 0) {
1335 $this->setErrorsFromObject($hookmanager);
1336 $error++;
1337 }
1338 }
1339 }
1340
1341 unset($object->context['createfromclone']);
1342
1343 // End
1344 if (!$error) {
1345 $this->db->commit();
1346 return $object->id;
1347 } else {
1348 $this->db->rollback();
1349 return -1;
1350 }
1351 }
1352
1360 public function createFromOrder($object, User $user)
1361 {
1362 global $conf, $hookmanager;
1363
1364 $error = 0;
1365
1366 // Closed order
1367 $this->date = dol_now();
1368 $this->source = 0;
1369
1370 $num = count($object->lines);
1371 for ($i = 0; $i < $num; $i++) {
1372 $line = new FactureLigne($this->db);
1373
1374 $line->libelle = $object->lines[$i]->libelle; // deprecated
1375 $line->label = $object->lines[$i]->label;
1376 $line->desc = $object->lines[$i]->desc;
1377 $line->subprice = $object->lines[$i]->subprice;
1378 $line->total_ht = $object->lines[$i]->total_ht;
1379 $line->total_tva = $object->lines[$i]->total_tva;
1380 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1381 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1382 $line->total_ttc = $object->lines[$i]->total_ttc;
1383 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1384 $line->tva_tx = $object->lines[$i]->tva_tx;
1385 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1386 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1387 $line->qty = $object->lines[$i]->qty;
1388 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1389 $line->remise_percent = $object->lines[$i]->remise_percent;
1390 $line->fk_product = $object->lines[$i]->fk_product;
1391 $line->info_bits = $object->lines[$i]->info_bits;
1392 $line->product_type = $object->lines[$i]->product_type;
1393 $line->rang = $object->lines[$i]->rang;
1394 $line->special_code = $object->lines[$i]->special_code;
1395 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1396 $line->fk_unit = $object->lines[$i]->fk_unit;
1397 $line->date_start = $object->lines[$i]->date_start;
1398 $line->date_end = $object->lines[$i]->date_end;
1399
1400 // Multicurrency
1401 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1402 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1403 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1404 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1405 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1406 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1407
1408 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1409 $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);
1410 $line->pa_ht = $marginInfos[0];
1411
1412 // get extrafields from original line
1413 $object->lines[$i]->fetch_optionals();
1414 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1415 $line->array_options[$options_key] = $value;
1416 }
1417
1418 $this->lines[$i] = $line;
1419 }
1420
1421 $this->socid = $object->socid;
1422 $this->fk_project = $object->fk_project;
1423 $this->fk_account = $object->fk_account;
1424 $this->cond_reglement_id = $object->cond_reglement_id;
1425 $this->mode_reglement_id = $object->mode_reglement_id;
1426 $this->availability_id = $object->availability_id;
1427 $this->demand_reason_id = $object->demand_reason_id;
1428 $this->delivery_date = $object->delivery_date;
1429 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1430 $this->contact_id = $object->contact_id;
1431 $this->ref_client = $object->ref_client;
1432
1433 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1434 $this->note_private = $object->note_private;
1435 $this->note_public = $object->note_public;
1436 }
1437
1438 $this->module_source = $object->module_source;
1439 $this->pos_source = $object->pos_source;
1440
1441 $this->origin = $object->element;
1442 $this->origin_id = $object->id;
1443
1444 $this->fk_user_author = $user->id;
1445
1446 // get extrafields from original line
1447 $object->fetch_optionals();
1448 foreach ($object->array_options as $options_key => $value) {
1449 $this->array_options[$options_key] = $value;
1450 }
1451
1452 // Possibility to add external linked objects with hooks
1453 $this->linked_objects[$this->origin] = $this->origin_id;
1454 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1455 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1456 }
1457
1458 $ret = $this->create($user);
1459
1460 if ($ret > 0) {
1461 // Actions hooked (by external module)
1462 $hookmanager->initHooks(array('invoicedao'));
1463
1464 $parameters = array('objFrom' => $object);
1465 $action = '';
1466 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1467 if ($reshook < 0) {
1468 $this->setErrorsFromObject($hookmanager);
1469 $error++;
1470 }
1471
1472 if (!$error) {
1473 return 1;
1474 } else {
1475 return -1;
1476 }
1477 } else {
1478 return -1;
1479 }
1480 }
1481
1490 public function createFromContract($object, User $user, $lines = array())
1491 {
1492 global $conf, $hookmanager;
1493
1494 $error = 0;
1495
1496 // Closed order
1497 $this->date = dol_now();
1498 $this->source = 0;
1499
1500 $use_all_lines = empty($lines);
1501 $num = count($object->lines);
1502 for ($i = 0; $i < $num; $i++) {
1503 if (!$use_all_lines && !in_array($object->lines[$i]->id, $lines)) {
1504 continue;
1505 }
1506
1507 $line = new FactureLigne($this->db);
1508
1509 $line->libelle = $object->lines[$i]->libelle; // deprecated
1510 $line->label = $object->lines[$i]->label;
1511 $line->desc = $object->lines[$i]->desc;
1512 $line->subprice = $object->lines[$i]->subprice;
1513 $line->total_ht = $object->lines[$i]->total_ht;
1514 $line->total_tva = $object->lines[$i]->total_tva;
1515 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1516 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1517 $line->total_ttc = $object->lines[$i]->total_ttc;
1518 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1519 $line->tva_tx = $object->lines[$i]->tva_tx;
1520 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1521 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1522 $line->qty = $object->lines[$i]->qty;
1523 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1524 $line->remise_percent = $object->lines[$i]->remise_percent;
1525 $line->fk_product = $object->lines[$i]->fk_product;
1526 $line->info_bits = $object->lines[$i]->info_bits;
1527 $line->product_type = $object->lines[$i]->product_type;
1528 $line->rang = $object->lines[$i]->rang;
1529 $line->special_code = $object->lines[$i]->special_code;
1530 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1531 $line->fk_unit = $object->lines[$i]->fk_unit;
1532 $line->date_start = $object->lines[$i]->date_start;
1533 $line->date_end = $object->lines[$i]->date_end;
1534
1535 // Multicurrency
1536 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1537 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1538 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1539 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1540 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1541 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1542
1543 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1544 $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);
1545 $line->pa_ht = $marginInfos[0];
1546
1547 // get extrafields from original line
1548 $object->lines[$i]->fetch_optionals();
1549 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1550 $line->array_options[$options_key] = $value;
1551 }
1552
1553 $this->lines[$i] = $line;
1554 }
1555
1556 $this->socid = $object->socid;
1557 $this->fk_project = $object->fk_project;
1558 $this->fk_account = $object->fk_account;
1559 $this->cond_reglement_id = $object->cond_reglement_id;
1560 $this->mode_reglement_id = $object->mode_reglement_id;
1561 $this->availability_id = $object->availability_id;
1562 $this->demand_reason_id = $object->demand_reason_id;
1563 $this->delivery_date = $object->delivery_date;
1564 $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
1565 $this->contact_id = $object->contact_id;
1566 $this->ref_client = $object->ref_client;
1567
1568 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1569 $this->note_private = $object->note_private;
1570 $this->note_public = $object->note_public;
1571 }
1572
1573 $this->module_source = $object->module_source;
1574 $this->pos_source = $object->pos_source;
1575
1576 $this->origin = $object->element;
1577 $this->origin_id = $object->id;
1578
1579 $this->fk_user_author = $user->id;
1580
1581 // get extrafields from original line
1582 $object->fetch_optionals();
1583 foreach ($object->array_options as $options_key => $value) {
1584 $this->array_options[$options_key] = $value;
1585 }
1586
1587 // Possibility to add external linked objects with hooks
1588 $this->linked_objects[$this->origin] = $this->origin_id;
1589 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1590 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1591 }
1592
1593 $ret = $this->create($user);
1594
1595 if ($ret > 0) {
1596 // Actions hooked (by external module)
1597 $hookmanager->initHooks(array('invoicedao'));
1598
1599 $parameters = array('objFrom' => $object);
1600 $action = '';
1601 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1602 if ($reshook < 0) {
1603 $this->setErrorsFromObject($hookmanager);
1604 $error++;
1605 }
1606
1607 if (!$error) {
1608 return 1;
1609 } else {
1610 return -1;
1611 }
1612 } else {
1613 return -1;
1614 }
1615 }
1616
1629 public static function createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger = 0, $autoValidateDeposit = false, $overrideFields = array())
1630 {
1631 global $conf, $langs, $hookmanager, $action;
1632
1633 if (! in_array($origin->element, array('propal', 'commande'))) {
1634 $origin->error = 'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1635 return null;
1636 }
1637
1638 if (empty($date)) {
1639 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice'));
1640 return null;
1641 }
1642
1643 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
1644
1645 if ($date > (dol_get_last_hour(dol_now('tzuserrel')) + getDolGlobalInt('INVOICE_MAX_FUTURE_DELAY'))) {
1646 $origin->error = 'ErrorDateIsInFuture';
1647 return null;
1648 }
1649
1650 if ($payment_terms_id <= 0) {
1651 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('PaymentConditionsShort'));
1652 return null;
1653 }
1654
1655 $payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $origin->cond_reglement_id);
1656
1657 if (empty($payment_conditions_deposit_percent)) {
1658 $origin->error = 'ErrorPaymentConditionsNotEligibleToDepositCreation';
1659 return null;
1660 }
1661
1662 if (empty($origin->deposit_percent)) {
1663 $origin->error = $langs->trans('ErrorFieldRequired', $langs->transnoentities('DepositPercent'));
1664 return null;
1665 }
1666
1667 $deposit = new self($origin->db);
1668 $deposit->socid = $origin->socid;
1669 $deposit->type = self::TYPE_DEPOSIT;
1670 $deposit->fk_project = $origin->fk_project;
1671 $deposit->ref_client = $origin->ref_client;
1672 $deposit->date = $date;
1673 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1674 $deposit->cond_reglement_id = $payment_terms_id;
1675 $deposit->availability_id = $origin->availability_id;
1676 $deposit->demand_reason_id = $origin->demand_reason_id;
1677 $deposit->fk_account = $origin->fk_account;
1678 $deposit->fk_incoterms = $origin->fk_incoterms;
1679 $deposit->location_incoterms = $origin->location_incoterms;
1680 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1681 $deposit->multicurrency_code = $origin->multicurrency_code;
1682 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1683 $deposit->module_source = $origin->module_source;
1684 $deposit->pos_source = $origin->pos_source;
1685 $deposit->model_pdf = 'crabe';
1686
1687 $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type;
1688
1689 if (getDolGlobalString($modelByTypeConfName)) {
1690 $deposit->model_pdf = getDolGlobalString($modelByTypeConfName);
1691 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
1692 $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF');
1693 }
1694
1695 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1696 $deposit->note_private = $origin->note_private;
1697 $deposit->note_public = $origin->note_public;
1698 }
1699
1700 $deposit->origin = $origin->element;
1701 $deposit->origin_id = $origin->id;
1702
1703 $origin->fetch_optionals();
1704
1705 foreach ($origin->array_options as $extrakey => $value) {
1706 $deposit->array_options[$extrakey] = $value;
1707 }
1708
1709 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1710
1711 foreach ($overrideFields as $key => $value) {
1712 $deposit->$key = $value;
1713 }
1714
1715 $deposit->context['createdepositfromorigin'] = 'createdepositfromorigin';
1716
1717 $origin->db->begin();
1718
1719 // Facture::create() also imports contact from origin
1720 $createReturn = $deposit->create($user, $notrigger);
1721
1722 if ($createReturn <= 0) {
1723 $origin->db->rollback();
1724 $origin->error = $deposit->error;
1725 $origin->errors = $deposit->errors;
1726 return null;
1727 }
1728
1729 $amount_ttc_diff = 0;
1730 $amountdeposit = array();
1731 $descriptions = array();
1732
1733 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA')) {
1734 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1735
1736 $TTotalByTva = array();
1737 foreach ($origin->lines as &$line) {
1738 if (!empty($line->special_code)) {
1739 continue;
1740 }
1741 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1742 $descriptions[$line->tva_tx] .= '<li>' . (!empty($line->product_ref) ? $line->product_ref . ' - ' : '');
1743 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label . ' - ' : '');
1744 $descriptions[$line->tva_tx] .= $langs->trans('Qty') . ' : ' . $line->qty;
1745 $descriptions[$line->tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($line->total_ht) . '</li>';
1746 }
1747
1748 foreach ($TTotalByTva as $tva => &$total) {
1749 $coef = $total / $origin->total_ttc; // Calc coef
1750 $am = $amount * $coef;
1751 $amount_ttc_diff += $am;
1752 $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
1753 }
1754 } else {
1755 $totalamount = 0;
1756 $lines = $origin->lines;
1757 $numlines = count($lines);
1758 for ($i = 0; $i < $numlines; $i++) {
1759 if (empty($lines[$i]->qty)) {
1760 continue; // We discard qty=0, it is an option
1761 }
1762 if (!empty($lines[$i]->special_code)) {
1763 continue; // We discard special_code (frais port, ecotaxe, option, ...)
1764 }
1765
1766 $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1767 $tva_tx = $lines[$i]->tva_tx;
1768 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1769 $descriptions[$tva_tx] .= '<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref . ' - ' : '');
1770 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label . ' - ' : '');
1771 $descriptions[$tva_tx] .= $langs->trans('Qty') . ' : ' . $lines[$i]->qty;
1772 $descriptions[$tva_tx] .= ' - ' . $langs->trans('TotalHT') . ' : ' . price($lines[$i]->total_ht) . '</li>';
1773 }
1774
1775 if ($totalamount == 0) {
1776 $amountdeposit[0] = 0;
1777 }
1778
1779 $amount_ttc_diff = $amountdeposit[0];
1780 }
1781
1782 foreach ($amountdeposit as $tva => $amount) {
1783 if (empty($amount)) {
1784 continue;
1785 }
1786
1787 $descline = '(DEPOSIT) ('. $origin->deposit_percent .'%) - '.$origin->ref;
1788
1789 // Hidden conf
1790 if (getDolGlobalString('INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1791 $descline .= '<ul>' . $descriptions[$tva] . '</ul>';
1792 }
1793
1794 $addlineResult = $deposit->addline(
1795 $descline,
1796 $amount, // subprice
1797 1, // quantity
1798 $tva, // vat rate
1799 0, // localtax1_tx
1800 0, // localtax2_tx
1801 (!getDolGlobalString('INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1802 0, // remise_percent
1803 0, // date_start
1804 0, // date_end
1805 0,
1806 0, // info_bits
1807 0,
1808 'HT',
1809 0,
1810 0, // product_type
1811 1,
1812 0, // special_code
1813 $deposit->origin,
1814 0,
1815 0,
1816 0,
1817 0
1818 //,$langs->trans('Deposit') //Deprecated
1819 );
1820
1821 if ($addlineResult < 0) {
1822 $origin->db->rollback();
1823 $origin->error = $deposit->error;
1824 $origin->errors = $deposit->errors;
1825 return null;
1826 }
1827 }
1828
1829 $diff = $deposit->total_ttc - $amount_ttc_diff;
1830
1831 if (getDolGlobalString('MAIN_DEPOSIT_MULTI_TVA') && $diff != 0) {
1832 $deposit->fetch_lines();
1833 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1834
1835 $updatelineResult = $deposit->updateline(
1836 $deposit->lines[0]->id,
1837 $deposit->lines[0]->desc,
1838 $subprice_diff,
1839 $deposit->lines[0]->qty,
1840 $deposit->lines[0]->remise_percent,
1841 $deposit->lines[0]->date_start,
1842 $deposit->lines[0]->date_end,
1843 $deposit->lines[0]->tva_tx,
1844 0,
1845 0,
1846 'HT',
1847 $deposit->lines[0]->info_bits,
1848 $deposit->lines[0]->product_type,
1849 0,
1850 0,
1851 0,
1852 $deposit->lines[0]->pa_ht,
1853 $deposit->lines[0]->label,
1854 0,
1855 array(),
1856 100
1857 );
1858
1859 if ($updatelineResult < 0) {
1860 $origin->db->rollback();
1861 $origin->error = $deposit->error;
1862 $origin->errors = $deposit->errors;
1863 return null;
1864 }
1865 }
1866
1867 $hookmanager->initHooks(array('invoicedao'));
1868
1869 $parameters = array('objFrom' => $origin);
1870 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $deposit, $action); // Note that $action and $object may have been
1871 // modified by hook
1872 if ($reshook < 0) {
1873 $origin->db->rollback();
1874 $origin->error = $hookmanager->error;
1875 $origin->errors = $hookmanager->errors;
1876 return null;
1877 }
1878
1879 if (!empty($autoValidateDeposit)) {
1880 $validateReturn = $deposit->validate($user, '', 0, $notrigger);
1881
1882 if ($validateReturn < 0) {
1883 $origin->db->rollback();
1884 $origin->error = $deposit->error;
1885 $origin->errors = $deposit->errors;
1886 return null;
1887 }
1888 }
1889
1890 unset($deposit->context['createdepositfromorigin']);
1891
1892 $origin->db->commit();
1893
1894 return $deposit;
1895 }
1896
1904 public function getTooltipContentArray($params)
1905 {
1906 global $conf, $langs, $mysoc, $user;
1907
1908 $langs->load('bills');
1909
1910 $datas = [];
1911 $moretitle = $params['moretitle'] ?? '';
1912
1913 $picto = $this->picto;
1914 if ($this->type == self::TYPE_REPLACEMENT) {
1915 $picto .= 'r'; // Replacement invoice
1916 }
1917 if ($this->type == self::TYPE_CREDIT_NOTE) {
1918 $picto .= 'a'; // Credit note
1919 }
1920 if ($this->type == self::TYPE_DEPOSIT) {
1921 $picto .= 'd'; // Deposit invoice
1922 }
1923
1924 if ($user->hasRight("facture", "read")) {
1925 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
1926
1927 $datas['picto'] .= '&nbsp;'.$this->getLibType(1);
1928
1929 // Complete datas
1930 if (!empty($params['fromajaxtooltip']) && !isset($this->totalpaid)) {
1931 // Load the totalpaid field
1932 $this->totalpaid = $this->getSommePaiement(0);
1933 }
1934 if (isset($this->status) && isset($this->totalpaid)) {
1935 $datas['picto'] .= ' '.$this->getLibStatut(5, $this->totalpaid);
1936 }
1937 if ($moretitle) {
1938 $datas['picto'] .= ' - '.$moretitle;
1939 }
1940 if (!empty($this->ref)) {
1941 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1942 }
1943 if (!empty($this->ref_customer)) {
1944 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
1945 }
1946 if (!empty($this->date)) {
1947 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1948 }
1949 if (!empty($this->total_ht)) {
1950 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1951 }
1952 if (!empty($this->total_tva)) {
1953 $datas['amountvat'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1954 }
1955 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
1956 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
1957 }
1958 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1959 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
1960 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1961 }
1962 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1963 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1964 }
1965 if (!empty($this->total_ttc)) {
1966 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1967 }
1968 }
1969
1970 return $datas;
1971 }
1972
1987 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
1988 {
1989 global $langs, $conf, $user;
1990
1991 if (!empty($conf->dol_no_mouse_hover)) {
1992 $notooltip = 1; // Force disable tooltips
1993 }
1994
1995 $result = '';
1996
1997 if ($option == 'withdraw') {
1998 $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
1999 } else {
2000 $url = DOL_URL_ROOT.'/compta/facture/card.php?id='.$this->id;
2001 }
2002
2003 if (!$user->hasRight("facture", "read")) {
2004 $option = 'nolink';
2005 }
2006
2007 if ($option !== 'nolink') {
2008 // Add param to save lastsearch_values or not
2009 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2010 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2011 $add_save_lastsearch_values = 1;
2012 }
2013 if ($add_save_lastsearch_values) {
2014 $url .= '&save_lastsearch_values=1';
2015 }
2016 }
2017
2018 if ($short) {
2019 return $url;
2020 }
2021
2022 $picto = $this->picto;
2023 if ($this->type == self::TYPE_REPLACEMENT) {
2024 $picto .= 'r'; // Replacement invoice
2025 }
2026 if ($this->type == self::TYPE_CREDIT_NOTE) {
2027 $picto .= 'a'; // Credit note
2028 }
2029 if ($this->type == self::TYPE_DEPOSIT) {
2030 $picto .= 'd'; // Deposit invoice
2031 }
2032
2033 $params = [
2034 'id' => $this->id,
2035 'objecttype' => $this->element,
2036 'moretitle' => $moretitle,
2037 'option' => $option,
2038 ];
2039 $classfortooltip = 'classfortooltip';
2040 $dataparams = '';
2041 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2042 $classfortooltip = 'classforajaxtooltip';
2043 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2044 $label = '';
2045 } else {
2046 $label = implode($this->getTooltipContentArray($params));
2047 }
2048
2049 $linkclose = ($target ? ' target="'.$target.'"' : '');
2050 if (empty($notooltip) && $user->hasRight("facture", "read")) {
2051 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2052 $label = $langs->trans("Invoice");
2053 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2054 }
2055 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2056 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2057 }
2058
2059 $linkstart = '<a href="'.$url.'"';
2060 $linkstart .= $linkclose.'>';
2061 $linkend = '</a>';
2062
2063 if ($option == 'nolink') {
2064 $linkstart = '';
2065 $linkend = '';
2066 }
2067
2068 $result .= $linkstart;
2069 if ($withpicto) {
2070 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2071 }
2072 if ($withpicto != 2) {
2073 $result .= ($max ? dol_trunc($this->ref, $max) : $this->ref);
2074 }
2075 $result .= $linkend;
2076
2077 if ($addlinktonotes) {
2078 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2079 if ($txttoshow) {
2080 //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
2081 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
2082 $result .= ' <span class="note inline-block">';
2083 $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
2084 $result .= img_picto('', 'note');
2085 $result .= '</a>';
2086 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
2087 //$result.='</a>';
2088 $result .= '</span>';
2089 }
2090 }
2091
2092 global $action, $hookmanager;
2093 $hookmanager->initHooks(array('invoicedao'));
2094 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value' => $save_lastsearch_value, 'target' => $target);
2095 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2096 if ($reshook > 0) {
2097 $result = $hookmanager->resPrint;
2098 } else {
2099 $result .= $hookmanager->resPrint;
2100 }
2101
2102 return $result;
2103 }
2104
2115 public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false)
2116 {
2117 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2118 return -1;
2119 }
2120
2121 $sql = 'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2122 $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2123 $sql .= ', f.datef as df, f.date_pointoftax';
2124 $sql .= ', f.date_lim_reglement as dlr';
2125 $sql .= ', f.datec as datec';
2126 $sql .= ', f.date_valid as datev';
2127 $sql .= ', f.tms as datem';
2128 $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';
2129 $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
2130 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2131 $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2132 $sql .= ', f.fk_account';
2133 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2134 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2135 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2136 $sql .= ', f.fk_incoterms, f.location_incoterms';
2137 $sql .= ', f.module_source, f.pos_source';
2138 $sql .= ", i.libelle as label_incoterms";
2139 $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";
2140 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
2141 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2142 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
2143 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
2144
2145 if ($rowid) {
2146 $sql .= " WHERE f.rowid = ".((int) $rowid);
2147 } else {
2148 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Don't use entity if you use rowid
2149 if ($ref) {
2150 $sql .= " AND f.ref = '".$this->db->escape($ref)."'";
2151 }
2152 if ($ref_ext) {
2153 $sql .= " AND f.ref_ext = '".$this->db->escape($ref_ext)."'";
2154 }
2155 }
2156
2157 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2158 $resql = $this->db->query($sql);
2159 if ($resql) {
2160 if ($this->db->num_rows($resql)) {
2161 $obj = $this->db->fetch_object($resql);
2162
2163 $this->id = $obj->rowid;
2164 $this->entity = $obj->entity;
2165
2166 $this->ref = $obj->ref;
2167 $this->ref_client = $obj->ref_client;
2168 $this->ref_customer = $obj->ref_client;
2169 $this->ref_ext = $obj->ref_ext;
2170 $this->type = $obj->type;
2171 $this->subtype = $obj->subtype;
2172 $this->date = $this->db->jdate($obj->df);
2173 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2174 $this->date_creation = $this->db->jdate($obj->datec);
2175 $this->date_validation = $this->db->jdate($obj->datev);
2176 $this->date_modification = $this->db->jdate($obj->datem);
2177 $this->datem = $this->db->jdate($obj->datem);
2178 $this->total_ht = $obj->total_ht;
2179 $this->total_tva = $obj->total_tva;
2180 $this->total_localtax1 = $obj->localtax1;
2181 $this->total_localtax2 = $obj->localtax2;
2182 $this->total_ttc = $obj->total_ttc;
2183 $this->revenuestamp = $obj->revenuestamp;
2184 $this->paye = $obj->paye;
2185 $this->close_code = $obj->close_code;
2186 $this->close_note = $obj->close_note;
2187
2188 $this->socid = $obj->fk_soc;
2189 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2190
2191 $this->fk_project = $obj->fk_project;
2192 $this->project = null; // Clear if another value was already set by fetch_projet
2193
2194 $this->statut = $obj->status; // deprecated
2195 $this->status = $obj->status;
2196
2197 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2198 $this->mode_reglement_id = $obj->fk_mode_reglement;
2199 $this->mode_reglement_code = $obj->mode_reglement_code;
2200 $this->mode_reglement = $obj->mode_reglement_libelle;
2201 $this->cond_reglement_id = $obj->fk_cond_reglement;
2202 $this->cond_reglement_code = $obj->cond_reglement_code;
2203 $this->cond_reglement = $obj->cond_reglement_libelle;
2204 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2205 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2206 $this->fk_facture_source = $obj->fk_facture_source;
2207 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2208 $this->note = $obj->note_private; // deprecated
2209 $this->note_private = $obj->note_private;
2210 $this->note_public = $obj->note_public;
2211 $this->user_creation_id = $obj->fk_user_author;
2212 $this->user_validation_id = $obj->fk_user_valid;
2213 $this->user_modification_id = $obj->fk_user_modif;
2214 $this->fk_user_author = $obj->fk_user_author;
2215 $this->fk_user_valid = $obj->fk_user_valid;
2216 $this->fk_user_modif = $obj->fk_user_modif;
2217 $this->model_pdf = $obj->model_pdf;
2218 $this->last_main_doc = $obj->last_main_doc;
2219 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2220 $this->situation_counter = $obj->situation_counter;
2221 $this->situation_final = $obj->situation_final;
2222 $this->retained_warranty = $obj->retained_warranty;
2223 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2224 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2225
2226 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2227
2228 //Incoterms
2229 $this->fk_incoterms = $obj->fk_incoterms;
2230 $this->location_incoterms = $obj->location_incoterms;
2231 $this->label_incoterms = $obj->label_incoterms;
2232
2233 $this->module_source = $obj->module_source;
2234 $this->pos_source = $obj->pos_source;
2235
2236 // Multicurrency
2237 $this->fk_multicurrency = $obj->fk_multicurrency;
2238 $this->multicurrency_code = $obj->multicurrency_code;
2239 $this->multicurrency_tx = $obj->multicurrency_tx;
2240 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2241 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2242 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2243
2244 if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2246 }
2247
2248 // Retrieve all extrafield
2249 // fetch optionals attributes and labels
2250 $this->fetch_optionals();
2251
2252 // Lines
2253 $this->lines = array();
2254
2255 $result = $this->fetch_lines();
2256 if ($result < 0) {
2257 $this->error = $this->db->error();
2258 return -3;
2259 }
2260
2261 $this->db->free($resql);
2262
2263 return 1;
2264 } else {
2265 $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
2266
2267 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2268 return 0;
2269 }
2270 } else {
2271 $this->error = $this->db->lasterror();
2272 return -1;
2273 }
2274 }
2275
2276
2277 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2286 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2287 {
2288 // phpcs:enable
2289 $this->lines = array();
2290
2291 $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,';
2292 $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,';
2293 $sql .= ' l.situation_percent, l.fk_prev_id,';
2294 $sql .= ' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2295 $sql .= ' l.date_start as date_start, l.date_end as date_end,';
2296 $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,';
2297 $sql .= ' l.fk_unit,';
2298 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2299 $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';
2300 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
2301 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2302 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
2303 $sql .= ' ORDER BY l.rang, l.rowid';
2304
2305 dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
2306 $result = $this->db->query($sql);
2307 if ($result) {
2308 $num = $this->db->num_rows($result);
2309 $i = 0;
2310 while ($i < $num) {
2311 $objp = $this->db->fetch_object($result);
2312 $line = new FactureLigne($this->db);
2313
2314 $line->id = $objp->rowid;
2315 $line->rowid = $objp->rowid; // deprecated
2316 $line->fk_facture = $objp->fk_facture;
2317 $line->label = $objp->custom_label; // deprecated
2318 $line->desc = $objp->description; // Description line
2319 $line->description = $objp->description; // Description line
2320 $line->product_type = $objp->product_type; // Type of line
2321 $line->ref = $objp->product_ref; // Ref product
2322 $line->product_ref = $objp->product_ref; // Ref product
2323 $line->libelle = $objp->product_label; // deprecated
2324 $line->product_label = $objp->product_label; // Label product
2325 $line->product_barcode = $objp->product_barcode; // Barcode number product
2326 $line->product_desc = $objp->product_desc; // Description product
2327 $line->fk_product_type = $objp->fk_product_type; // Type of product
2328 $line->qty = $objp->qty;
2329 $line->subprice = $objp->subprice;
2330 $line->ref_ext = $objp->ref_ext; // line external ref
2331
2332 $line->vat_src_code = $objp->vat_src_code;
2333 $line->tva_tx = $objp->tva_tx;
2334 $line->localtax1_tx = $objp->localtax1_tx;
2335 $line->localtax2_tx = $objp->localtax2_tx;
2336 $line->localtax1_type = $objp->localtax1_type;
2337 $line->localtax2_type = $objp->localtax2_type;
2338 $line->remise_percent = $objp->remise_percent;
2339 $line->fk_remise_except = $objp->fk_remise_except;
2340 $line->fk_product = $objp->fk_product;
2341 $line->date_start = $this->db->jdate($objp->date_start);
2342 $line->date_end = $this->db->jdate($objp->date_end);
2343 $line->info_bits = $objp->info_bits;
2344 $line->total_ht = $objp->total_ht;
2345 $line->total_tva = $objp->total_tva;
2346 $line->total_localtax1 = $objp->total_localtax1;
2347 $line->total_localtax2 = $objp->total_localtax2;
2348 $line->total_ttc = $objp->total_ttc;
2349
2350 $line->fk_fournprice = $objp->fk_fournprice;
2351 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2352 $line->pa_ht = $marginInfos[0];
2353 $line->marge_tx = $marginInfos[1];
2354 $line->marque_tx = $marginInfos[2];
2355 $line->rang = $objp->rang;
2356 $line->special_code = $objp->special_code;
2357 $line->fk_parent_line = $objp->fk_parent_line;
2358 $line->situation_percent = $objp->situation_percent;
2359 $line->fk_prev_id = $objp->fk_prev_id;
2360 $line->fk_unit = $objp->fk_unit;
2361
2362 $line->batch = $objp->batch;
2363 $line->fk_warehouse = $objp->fk_warehouse;
2364
2365 // Accountancy
2366 $line->fk_accounting_account = $objp->fk_code_ventilation;
2367
2368 // Multicurrency
2369 $line->fk_multicurrency = $objp->fk_multicurrency;
2370 $line->multicurrency_code = $objp->multicurrency_code;
2371 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2372 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2373 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2374 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2375
2376 $line->fetch_optionals();
2377
2378 // multilangs
2379 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2380 $tmpproduct = new Product($this->db);
2381 $tmpproduct->fetch($objp->fk_product);
2382 $tmpproduct->getMultiLangs();
2383
2384 $line->multilangs = $tmpproduct->multilangs;
2385 }
2386
2387 $this->lines[$i] = $line;
2388
2389 $i++;
2390 }
2391 $this->db->free($result);
2392 return 1;
2393 } else {
2394 $this->error = $this->db->error();
2395 return -3;
2396 }
2397 }
2398
2406 {
2407 global $conf;
2408
2409 $this->tab_previous_situation_invoice = array();
2410 $this->tab_next_situation_invoice = array();
2411
2412 $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
2413 $sql .= " WHERE rowid <> ".((int) $this->id);
2414 $sql .= ' AND entity = '.((int) $this->entity);
2415 $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2416 $sql .= ' ORDER BY situation_counter ASC';
2417
2418 dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2419 $result = $this->db->query($sql);
2420 if ($result && $this->db->num_rows($result) > 0) {
2421 while ($objp = $this->db->fetch_object($result)) {
2422 $invoice = new Facture($this->db);
2423 if ($invoice->fetch($objp->rowid) > 0) {
2424 if ($objp->situation_counter < $this->situation_counter
2425 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
2426 ) {
2427 $this->tab_previous_situation_invoice[] = $invoice;
2428 } else {
2429 $this->tab_next_situation_invoice[] = $invoice;
2430 }
2431 }
2432 }
2433 }
2434 }
2435
2443 public function update(User $user, $notrigger = 0)
2444 {
2445 $error = 0;
2446
2447 // Clean parameters
2448 if (empty($this->type)) {
2449 $this->type = self::TYPE_STANDARD;
2450 }
2451 if (isset($this->subtype)) {
2452 $this->subtype = (int) trim((string) $this->subtype);
2453 }
2454 if (isset($this->ref)) {
2455 $this->ref = trim($this->ref);
2456 }
2457 if (isset($this->ref_ext)) {
2458 $this->ref_ext = trim($this->ref_ext);
2459 }
2460 // deprecated
2461 if (isset($this->ref_client)) {
2462 $this->ref_client = trim($this->ref_client);
2463 }
2464 if (isset($this->ref_customer)) {
2465 $this->ref_customer = trim($this->ref_customer);
2466 }
2467 if (isset($this->increment)) {
2468 $this->increment = trim($this->increment);
2469 }
2470 if (isset($this->close_code)) {
2471 $this->close_code = trim($this->close_code);
2472 }
2473 if (isset($this->close_note)) {
2474 $this->close_note = trim($this->close_note);
2475 }
2476 if (isset($this->note) || isset($this->note_private)) {
2477 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
2478 }
2479 if (isset($this->note) || isset($this->note_private)) {
2480 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2481 }
2482 if (isset($this->note_public)) {
2483 $this->note_public = trim($this->note_public);
2484 }
2485 if (isset($this->model_pdf)) {
2486 $this->model_pdf = trim($this->model_pdf);
2487 }
2488 if (isset($this->import_key)) {
2489 $this->import_key = trim($this->import_key);
2490 }
2491 if (isset($this->retained_warranty)) {
2492 $this->retained_warranty = (float) $this->retained_warranty;
2493 }
2494
2495
2496 // Check parameters
2497 // Put here code to add control on parameters values
2498
2499 // Update request
2500 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
2501 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
2502 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
2503 $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
2504 $sql .= " subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) : "null").",";
2505 $sql .= " ref_client=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : (isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null")).",";
2506 $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
2507 $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
2508 $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
2509 $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
2510 $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
2511 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
2512 $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
2513 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
2514 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
2515 $sql .= " total_tva=".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
2516 $sql .= " localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
2517 $sql .= " localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
2518 $sql .= " total_ht=".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
2519 $sql .= " total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
2520 $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? (float) $this->revenuestamp : "null").",";
2521 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
2522 $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? (int) $this->fk_user_valid : "null").",";
2523 $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source : "null").",";
2524 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
2525 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
2526 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
2527 $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
2528 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2529 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2530 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2531 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
2532 $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : (int) $this->situation_cycle_ref).",";
2533 $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : (int) $this->situation_counter).",";
2534 $sql .= " situation_final=".(empty($this->situation_final) ? "0" : (int) $this->situation_final).",";
2535 $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : (float) $this->retained_warranty).",";
2536 $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
2537 $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement : "null");
2538 $sql .= " WHERE rowid=".((int) $this->id);
2539
2540 $this->db->begin();
2541
2542 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2543 $resql = $this->db->query($sql);
2544 if (!$resql) {
2545 $error++;
2546 $this->errors[] = "Error ".$this->db->lasterror();
2547 }
2548
2549 if (!$error) {
2550 $result = $this->insertExtraFields();
2551 if ($result < 0) {
2552 $error++;
2553 }
2554 }
2555
2556 if (!$error && !$notrigger) {
2557 // Call trigger
2558 $result = $this->call_trigger('BILL_MODIFY', $user);
2559 if ($result < 0) {
2560 $error++;
2561 }
2562 // End call triggers
2563 }
2564
2565 // Commit or rollback
2566 if ($error) {
2567 foreach ($this->errors as $errmsg) {
2568 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2569 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2570 }
2571 $this->db->rollback();
2572 return -1 * $error;
2573 } else {
2574 $this->db->commit();
2575 return 1;
2576 }
2577 }
2578
2579
2580 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2587 public function insert_discount($idremise)
2588 {
2589 // phpcs:enable
2590 global $conf, $langs;
2591
2592 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2593 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2594
2595 $this->db->begin();
2596
2597 $remise = new DiscountAbsolute($this->db);
2598 $result = $remise->fetch($idremise);
2599
2600 if ($result > 0) {
2601 if ($remise->fk_facture) { // Protection against multiple submission
2602 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2603 $this->db->rollback();
2604 return -5;
2605 }
2606
2607 $facligne = new FactureLigne($this->db);
2608 $facligne->fk_facture = $this->id;
2609 $facligne->fk_remise_except = $remise->id;
2610 $facligne->desc = $remise->description; // Description ligne
2611 $facligne->vat_src_code = $remise->vat_src_code;
2612 $facligne->tva_tx = $remise->tva_tx;
2613 $facligne->subprice = -$remise->amount_ht;
2614 $facligne->fk_product = 0; // Id produit predefini
2615 $facligne->qty = 1;
2616 $facligne->remise_percent = 0;
2617 $facligne->rang = -1;
2618 $facligne->info_bits = 2;
2619
2620 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
2621 $facligne->rang = 1;
2622 $linecount = count($this->lines);
2623 for ($ii = 1; $ii <= $linecount; $ii++) {
2624 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2625 }
2626 }
2627
2628 // Get buy/cost price of invoice that is source of discount
2629 if ($remise->fk_facture_source > 0) {
2630 $srcinvoice = new Facture($this->db);
2631 $srcinvoice->fetch($remise->fk_facture_source);
2632 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
2633 $formmargin = new FormMargin($this->db);
2634 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
2635 $facligne->pa_ht = $arraytmp['pa_total'];
2636 }
2637
2638 $facligne->total_ht = -$remise->amount_ht;
2639 $facligne->total_tva = -$remise->amount_tva;
2640 $facligne->total_ttc = -$remise->amount_ttc;
2641
2642 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2643 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2644 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2645 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2646
2647 $lineid = $facligne->insert();
2648 if ($lineid > 0) {
2649 $result = $this->update_price(1);
2650 if ($result > 0) {
2651 // Create link between discount and invoice line
2652 $result = $remise->link_to_invoice($lineid, 0);
2653 if ($result < 0) {
2654 $this->error = $remise->error;
2655 $this->db->rollback();
2656 return -4;
2657 }
2658
2659 $this->db->commit();
2660 return 1;
2661 } else {
2662 $this->error = $facligne->error;
2663 $this->db->rollback();
2664 return -1;
2665 }
2666 } else {
2667 $this->error = $facligne->error;
2668 $this->db->rollback();
2669 return -2;
2670 }
2671 } else {
2672 $this->db->rollback();
2673 return -3;
2674 }
2675 }
2676
2677 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2685 public function set_ref_client($ref_client, $notrigger = 0)
2686 {
2687 // phpcs:enable
2688 global $user;
2689
2690 $error = 0;
2691
2692 $this->db->begin();
2693
2694 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2695 if (empty($ref_client)) {
2696 $sql .= ' SET ref_client = NULL';
2697 } else {
2698 $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
2699 }
2700 $sql .= " WHERE rowid = ".((int) $this->id);
2701
2702 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2703 $resql = $this->db->query($sql);
2704 if (!$resql) {
2705 $this->errors[] = $this->db->error();
2706 $error++;
2707 }
2708
2709 if (!$error) {
2710 $this->ref_client = $ref_client; //deprecated
2711 $this->ref_customer = $ref_client;
2712 }
2713
2714 if (!$notrigger && empty($error)) {
2715 // Call trigger
2716 $result = $this->call_trigger('BILL_MODIFY', $user);
2717 if ($result < 0) {
2718 $error++;
2719 }
2720 // End call triggers
2721 }
2722
2723 if (!$error) {
2724 $this->ref_client = $ref_client; //deprecated
2725 $this->ref_customer = $ref_client;
2726
2727 $this->db->commit();
2728 return 1;
2729 } else {
2730 foreach ($this->errors as $errmsg) {
2731 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2732 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2733 }
2734 $this->db->rollback();
2735 return -1 * $error;
2736 }
2737 }
2738
2747 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2748 {
2749 global $langs, $conf;
2750 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2751
2752 $rowid = $this->id;
2753
2754 dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
2755
2756 // Test to avoid invoice deletion (allowed if draft)
2757 $result = $this->is_erasable();
2758
2759 if ($result <= 0) {
2760 return 0;
2761 }
2762
2763 $error = 0;
2764
2765 $this->db->begin();
2766
2767 if (!$error && !$notrigger) {
2768 // Call trigger
2769 $result = $this->call_trigger('BILL_DELETE', $user);
2770 if ($result < 0) {
2771 $error++;
2772 }
2773 // End call triggers
2774 }
2775
2776 // Removed extrafields
2777 if (!$error) {
2778 $result = $this->deleteExtraFields();
2779 if ($result < 0) {
2780 $error++;
2781 dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
2782 }
2783 }
2784
2785 if (!$error) {
2786 // Delete linked object
2787 $res = $this->deleteObjectLinked();
2788 if ($res < 0) {
2789 $error++;
2790 }
2791 }
2792
2793 if (!$error) {
2794 // If invoice was converted into a discount not yet consumed, we remove discount
2795 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
2796 $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
2797 $sql .= ' AND fk_facture_line IS NULL';
2798 $resql = $this->db->query($sql);
2799
2800 // If invoice has consumed discounts
2801 $this->fetch_lines();
2802 $list_rowid_det = array();
2803 foreach ($this->lines as $key => $invoiceline) {
2804 $list_rowid_det[] = $invoiceline->id;
2805 }
2806
2807 // Consumed discounts are freed
2808 if (count($list_rowid_det)) {
2809 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2810 $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
2811 $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
2812
2813 if (!$this->db->query($sql)) {
2814 $this->error = $this->db->error()." sql=".$sql;
2815 $this->errors[] = $this->error;
2816 $this->db->rollback();
2817 return -5;
2818 }
2819 }
2820
2821 // Remove other links to the deleted invoice
2822
2823 $sql = 'UPDATE '.MAIN_DB_PREFIX.'eventorganization_conferenceorboothattendee';
2824 $sql .= ' SET fk_invoice = NULL';
2825 $sql .= ' WHERE fk_invoice = '.((int) $rowid);
2826
2827 if (!$this->db->query($sql)) {
2828 $this->error = $this->db->error()." sql=".$sql;
2829 $this->errors[] = $this->error;
2830 $this->db->rollback();
2831 return -5;
2832 }
2833
2834 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
2835 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
2836 $sql .= ' WHERE invoice_id = '.((int) $rowid);
2837
2838 if (!$this->db->query($sql)) {
2839 $this->error = $this->db->error()." sql=".$sql;
2840 $this->errors[] = $this->error;
2841 $this->db->rollback();
2842 return -5;
2843 }
2844
2845 // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
2846 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2847 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2848 $langs->load("agenda");
2849
2850 $num = count($this->lines);
2851 for ($i = 0; $i < $num; $i++) {
2852 if ($this->lines[$i]->fk_product > 0) {
2853 $mouvP = new MouvementStock($this->db);
2854 $mouvP->origin = &$this;
2855 $mouvP->setOrigin($this->element, $this->id);
2856 // We decrease stock for product
2857 if ($this->type == self::TYPE_CREDIT_NOTE) {
2858 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
2859 } else {
2860 $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
2861 }
2862 }
2863 }
2864 }
2865
2866 // Invoice line extrafileds
2867 $main = MAIN_DB_PREFIX.'facturedet';
2868 $ef = $main."_extrafields";
2869 $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
2870 // Delete invoice line
2871 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
2872
2873 if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact() >= 0 ) {
2874 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
2875
2876 $resql = $this->db->query($sql);
2877 if ($resql) {
2878 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2879 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2880 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2881
2882 // On efface le repertoire de pdf provisoire
2883 $ref = dol_sanitizeFileName($this->ref);
2884 if ($conf->facture->dir_output && !empty($this->ref)) {
2885 $dir = $conf->facture->dir_output."/".$ref;
2886 $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
2887 if (file_exists($file)) { // We must delete all files before deleting directory
2888 $ret = dol_delete_preview($this);
2889
2890 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2891 $langs->load("errors");
2892 $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
2893 $this->errors[] = $this->error;
2894 $this->db->rollback();
2895 return 0;
2896 }
2897 }
2898 if (file_exists($dir)) {
2899 if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
2900 $langs->load("errors");
2901 $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
2902 $this->errors[] = $this->error;
2903 $this->db->rollback();
2904 return 0;
2905 }
2906 }
2907 }
2908
2909 $this->db->commit();
2910 return 1;
2911 } else {
2912 $this->error = $this->db->lasterror()." sql=".$sql;
2913 $this->errors[] = $this->error;
2914 $this->db->rollback();
2915 return -6;
2916 }
2917 } else {
2918 $this->error = $this->db->lasterror()." sql=".$sql;
2919 $this->errors[] = $this->error;
2920 $this->db->rollback();
2921 return -4;
2922 }
2923 } else {
2924 $this->db->rollback();
2925 return -2;
2926 }
2927 }
2928
2929 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2941 public function set_paid($user, $close_code = '', $close_note = '')
2942 {
2943 // phpcs:enable
2944 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2945 return $this->setPaid($user, $close_code, $close_note);
2946 }
2947
2958 public function setPaid($user, $close_code = '', $close_note = '')
2959 {
2960 $error = 0;
2961
2962 if ($this->paye != 1) {
2963 $this->db->begin();
2964
2965 $now = dol_now();
2966
2967 dol_syslog(get_class($this)."::setPaid rowid=".((int) $this->id), LOG_DEBUG);
2968
2969 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
2970 $sql .= ' fk_statut='.self::STATUS_CLOSED;
2971 if (!$close_code) {
2972 $sql .= ', paye=1';
2973 }
2974 if ($close_code) {
2975 $sql .= ", close_code='".$this->db->escape($close_code)."'";
2976 }
2977 if ($close_note) {
2978 $sql .= ", close_note='".$this->db->escape($close_note)."'";
2979 }
2980 $sql .= ', fk_user_closing = '.((int) $user->id);
2981 $sql .= ", date_closing = '".$this->db->idate($now)."'";
2982 $sql .= " WHERE rowid = ".((int) $this->id);
2983
2984 $resql = $this->db->query($sql);
2985 if ($resql) {
2986 // Call trigger
2987 $result = $this->call_trigger('BILL_PAYED', $user);
2988 if ($result < 0) {
2989 $error++;
2990 }
2991 // End call triggers
2992 } else {
2993 $error++;
2994 $this->error = $this->db->lasterror();
2995 }
2996
2997 if (!$error) {
2998 $this->db->commit();
2999 return 1;
3000 } else {
3001 $this->db->rollback();
3002 return -1;
3003 }
3004 } else {
3005 return 0;
3006 }
3007 }
3008
3009
3010 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3021 public function set_unpaid($user)
3022 {
3023 // phpcs:enable
3024 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3025 return $this->setUnpaid($user);
3026 }
3027
3036 public function setUnpaid($user)
3037 {
3038 $error = 0;
3039
3040 $this->db->begin();
3041
3042 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3043 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
3044 $sql .= ' date_closing=null,';
3045 $sql .= ' fk_user_closing=null';
3046 $sql .= " WHERE rowid = ".((int) $this->id);
3047
3048 dol_syslog(get_class($this)."::setUnpaid", LOG_DEBUG);
3049 $resql = $this->db->query($sql);
3050 if ($resql) {
3051 // Call trigger
3052 $result = $this->call_trigger('BILL_UNPAYED', $user);
3053 if ($result < 0) {
3054 $error++;
3055 }
3056 // End call triggers
3057 } else {
3058 $error++;
3059 $this->error = $this->db->error();
3060 dol_print_error($this->db);
3061 }
3062
3063 if (!$error) {
3064 $this->db->commit();
3065 return 1;
3066 } else {
3067 $this->db->rollback();
3068 return -1;
3069 }
3070 }
3071
3072
3073 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3086 public function set_canceled($user, $close_code = '', $close_note = '')
3087 {
3088 // phpcs:enable
3089 dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3090 return $this->setCanceled($user, $close_code, $close_note);
3091 }
3092
3103 public function setCanceled($user, $close_code = '', $close_note = '')
3104 {
3105 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
3106
3107 $this->db->begin();
3108 $now = dol_now();
3109
3110 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
3111 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
3112 if ($close_code) {
3113 $sql .= ", close_code='".$this->db->escape($close_code)."'";
3114 }
3115 if ($close_note) {
3116 $sql .= ", close_note='".$this->db->escape($close_note)."'";
3117 }
3118 $sql .= ', fk_user_closing = '.((int) $user->id);
3119 $sql .= ", date_closing = '".$this->db->idate($now)."'";
3120 $sql .= " WHERE rowid = ".((int) $this->id);
3121
3122 $resql = $this->db->query($sql);
3123 if ($resql) {
3124 // Bound discounts are deducted from the invoice
3125 // as they have not been used since the invoice is abandoned.
3126 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
3127 $sql .= ' SET fk_facture = NULL';
3128 $sql .= ' WHERE fk_facture = '.((int) $this->id);
3129
3130 $resql = $this->db->query($sql);
3131 if ($resql) {
3132 // Call trigger
3133 $result = $this->call_trigger('BILL_CANCEL', $user);
3134 if ($result < 0) {
3135 $this->db->rollback();
3136 return -1;
3137 }
3138 // End call triggers
3139
3140 $this->db->commit();
3141 return 1;
3142 } else {
3143 $this->error = $this->db->error()." sql=".$sql;
3144 $this->db->rollback();
3145 return -1;
3146 }
3147 } else {
3148 $this->error = $this->db->error()." sql=".$sql;
3149 $this->db->rollback();
3150 return -2;
3151 }
3152 }
3153
3165 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3166 {
3167 global $conf, $langs, $mysoc;
3168 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3169
3170 $productStatic = null;
3171 $warehouseStatic = null;
3172 if ($batch_rule > 0) {
3173 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3174 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
3175 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
3176 $productStatic = new Product($this->db);
3177 $warehouseStatic = new Entrepot($this->db);
3178 $productbatch = new Productbatch($this->db);
3179 }
3180
3181 $now = dol_now();
3182
3183 $error = 0;
3184 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
3185
3186 // Force to have object complete for checks
3187 $this->fetch_thirdparty();
3188 $this->fetch_lines();
3189
3190 // Check parameters
3191 if ($this->status != self::STATUS_DRAFT) {
3192 dol_syslog(get_class($this)."::validate Current status is not draft. operation canceled.", LOG_WARNING);
3193 return 0;
3194 }
3195 if (count($this->lines) <= 0) {
3196 $langs->load("errors");
3197 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
3198 return -1;
3199 }
3200 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'creer'))
3201 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('facture', 'invoice_advance', 'validate'))) {
3202 $this->error = 'Permission denied';
3203 dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS=' . getDolGlobalString('MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3204 return -1;
3205 }
3206 if ((preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) && // empty should not happened, but when it occurs, the test save life
3207 getDolGlobalString('FAC_FORCE_DATE_VALIDATION') // If option enabled, we force invoice date
3208 ) {
3209 $this->date = dol_now();
3210 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3211 }
3212 if (getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
3213 $last_of_type = $this->willBeLastOfSameType(true);
3214 if (!$last_of_type[0]) {
3215 $this->error = $langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $this->ref, dol_print_date($this->date, 'day'), dol_print_date($last_of_type[1], 'day'));
3216 return -1;
3217 }
3218 }
3219
3220 // Check for mandatory fields in thirdparty (defined into setup)
3221 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3222 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_CUSTOMER');
3223 foreach ($array_to_check as $key) {
3224 $keymin = strtolower($key);
3225 if (!property_exists($this->thirdparty, $keymin)) {
3226 continue;
3227 }
3228 $vallabel = $this->thirdparty->$keymin;
3229
3230 $i = (int) preg_replace('/[^0-9]/', '', $key);
3231 if ($i > 0) {
3232 if ($this->thirdparty->isACompany()) {
3233 // Check for mandatory prof id (but only if country is other than ours)
3234 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3235 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
3236 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3237 $langs->load("errors");
3238 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3239 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3240 return -1;
3241 }
3242 }
3243 }
3244 } else {
3245 if ($key == 'EMAIL') {
3246 // Check for mandatory
3247 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
3248 $langs->load("errors");
3249 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
3250 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3251 return -1;
3252 }
3253 }
3254 if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') {
3255 // Check for mandatory
3256 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta)) {
3257 $langs->load("errors");
3258 $this->error = $langs->trans("ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
3259 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
3260 return -1;
3261 }
3262 }
3263 }
3264 }
3265 }
3266
3267 // Check for mandatory fields in $this
3268 $array_to_check = array('REF_CLIENT' => 'RefCustomer');
3269 foreach ($array_to_check as $key => $val) {
3270 $keymin = strtolower($key);
3271 $vallabel = $this->$keymin;
3272
3273 // Check for mandatory
3274 $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
3275 if (!$vallabel && getDolGlobalString($keymandatory)) {
3276 $langs->load("errors");
3277 $error++;
3278 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3279 }
3280 }
3281
3282 $this->db->begin();
3283
3284 // Check parameters
3285 if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
3286 // Check that source invoice is known
3287 if ($this->fk_facture_source <= 0) {
3288 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
3289 $this->db->rollback();
3290 return -10;
3291 }
3292
3293 // Load source invoice that has been replaced
3294 $facreplaced = new Facture($this->db);
3295 $result = $facreplaced->fetch($this->fk_facture_source);
3296 if ($result <= 0) {
3297 $this->error = $langs->trans("ErrorBadInvoice");
3298 $this->db->rollback();
3299 return -11;
3300 }
3301
3302 // Check that source invoice not already replaced by another one.
3303 $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
3304 if ($idreplacement && $idreplacement != $this->id) {
3305 $facreplacement = new Facture($this->db);
3306 $facreplacement->fetch($idreplacement);
3307 $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3308 $this->db->rollback();
3309 return -12;
3310 }
3311
3312 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
3313 if ($result < 0) {
3314 $this->error = $facreplaced->error;
3315 $this->db->rollback();
3316 return -13;
3317 }
3318 }
3319
3320 // Define new ref
3321 if ($force_number) {
3322 $num = $force_number;
3323 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
3324 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3325 $this->date = dol_now();
3326 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
3327 }
3328 $num = $this->getNextNumRef($this->thirdparty);
3329 } else {
3330 $num = $this->ref;
3331 }
3332
3333 $this->newref = dol_sanitizeFileName($num);
3334
3335 if ($num) {
3336 $this->update_price(1);
3337
3338 // Validate
3339 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
3340 $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)."'";
3341 if (getDolGlobalString('FAC_FORCE_DATE_VALIDATION')) { // If option enabled, we force invoice date
3342 $sql .= ", datef='".$this->db->idate($this->date)."'";
3343 $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
3344 }
3345 $sql .= " WHERE rowid = ".((int) $this->id);
3346
3347 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
3348 $resql = $this->db->query($sql);
3349 if (!$resql) {
3350 $this->error = $this->db->lasterror();
3351 $error++;
3352 }
3353
3354 // We check if the invoice was provisional
3355 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref))) {
3356 // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
3357 }
3358
3359 if (!$error) {
3360 // Define third party as a customer
3361 $result = $this->thirdparty->setAsCustomer();
3362
3363 // If active (STOCK_CALCULATE_ON_BILL), we decrement the main product and its components at invoice validation
3364 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3365 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3366 $langs->load("agenda");
3367
3368 // Loop on each line
3369 $cpt = count($this->lines);
3370 for ($i = 0; $i < $cpt; $i++) {
3371 if ($this->lines[$i]->fk_product > 0) {
3372 $mouvP = new MouvementStock($this->db);
3373 $mouvP->origin = &$this; // deprecated
3374 $mouvP->setOrigin($this->element, $this->id);
3375
3376 // We decrease stock for product
3377 if ($this->type == self::TYPE_CREDIT_NOTE) {
3378 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3379 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3380 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num), '', '', $this->lines[$i]->batch);
3381 if ($result < 0) {
3382 $error++;
3383 $this->error = $mouvP->error;
3384 $this->errors = array_merge($this->errors, $mouvP->errors);
3385 }
3386 } else {
3387 // TODO If warehouseid has been set into invoice line, we should use this value in priority
3388 // $newidwarehouse = $this->lines[$i]->fk_warehouse ? $this->lines[$i]->fk_warehouse : $idwarehouse;
3389
3390 $is_batch_line = false;
3391 if ($batch_rule > 0) {
3392 $productStatic->fetch($this->lines[$i]->fk_product);
3393 if ($productStatic->hasbatch()) {
3394 $is_batch_line = true;
3395 $product_qty_remain = $this->lines[$i]->qty;
3396
3397 $sortfield = null;
3398 $sortorder = null;
3399 // find lot/serial by sellby (DLC) and eatby dates (DLUO) first
3401 $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3402 $sortorder = 'ASC,ASC,ASC,ASC';
3403 }
3404
3405 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (getDolGlobalInt('STOCK_ALLOW_NEGATIVE_TRANSFER') ? null : 0), $sortfield, $sortorder);
3406 if (!is_array($resBatchList)) {
3407 $error++;
3408 $this->error = $this->db->lasterror();
3409 }
3410
3411 if (!$error) {
3412 $batchList = $resBatchList;
3413 if (empty($batchList)) {
3414 $error++;
3415 $langs->load('errors');
3416 $warehouseStatic->fetch($idwarehouse);
3417 $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3418 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3419 }
3420
3421 foreach ($batchList as $batch) {
3422 if ($batch->qty <= 0) {
3423 continue; // try to decrement only batches have positive quantity first
3424 }
3425
3426 // enough quantity in this batch
3427 if ($batch->qty >= $product_qty_remain) {
3428 $product_batch_qty = $product_qty_remain;
3429 } else {
3430 // not enough (take all in batch)
3431 $product_batch_qty = $batch->qty;
3432 }
3433 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3434 if ($result < 0) {
3435 $error++;
3436 $this->error = $mouvP->error;
3437 $this->errors = array_merge($this->errors, $mouvP->errors);
3438 break;
3439 }
3440
3441 $product_qty_remain -= $product_batch_qty;
3442 // all product quantity was decremented
3443 if ($product_qty_remain <= 0) {
3444 break;
3445 }
3446 }
3447
3448 if (!$error && $product_qty_remain > 0) {
3449 if (getDolGlobalInt('STOCK_ALLOW_NEGATIVE_TRANSFER')) {
3450 // take in the first batch
3451 $batch = $batchList[0];
3452 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
3453 if ($result < 0) {
3454 $error++;
3455 $this->error = $mouvP->error;
3456 $this->errors = array_merge($this->errors, $mouvP->errors);
3457 }
3458 } else {
3459 $error++;
3460 $langs->load('errors');
3461 $warehouseStatic->fetch($idwarehouse);
3462 $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3463 dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3464 }
3465 }
3466 }
3467 }
3468 }
3469
3470 if (!$is_batch_line) { // If stock move not yet processed
3471 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
3472 if ($result < 0) {
3473 $error++;
3474 $this->error = $mouvP->error;
3475 $this->errors = array_merge($this->errors, $mouvP->errors);
3476 }
3477 }
3478 }
3479 }
3480 }
3481 }
3482 }
3483
3484 /*
3485 * 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%)
3486 * So we can continue to create new invoice situation
3487 */
3488 if (!$error && $this->type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3489 $invoice_situation = new Facture($this->db);
3490 $result = $invoice_situation->fetch($this->fk_facture_source);
3491 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3492 $invoice_situation->situation_final = 0;
3493 // Disable triggers because module can force situation_final to 1 by triggers (ex: SubTotal)
3494 $result = $invoice_situation->setFinal($user, 1);
3495 }
3496 if ($result < 0) {
3497 $this->error = $invoice_situation->error;
3498 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3499 $error++;
3500 }
3501 }
3502
3503 // Trigger calls
3504 if (!$error && !$notrigger) {
3505 // Call trigger
3506 $result = $this->call_trigger('BILL_VALIDATE', $user);
3507 if ($result < 0) {
3508 $error++;
3509 }
3510 // End call triggers
3511 }
3512
3513 if (!$error) {
3514 $this->oldref = $this->ref;
3515
3516 // Rename directory if dir was a temporary ref
3517 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
3518 // Now we rename also files into index
3519 $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)."'";
3520 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3521 $resql = $this->db->query($sql);
3522 if (!$resql) {
3523 $error++;
3524 $this->error = $this->db->lasterror();
3525 }
3526 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'facture/".$this->db->escape($this->newref)."'";
3527 $sql .= " WHERE filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
3528 $resql = $this->db->query($sql);
3529 if (!$resql) {
3530 $error++;
3531 $this->error = $this->db->lasterror();
3532 }
3533
3534 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
3535 $oldref = dol_sanitizeFileName($this->ref);
3536 $newref = dol_sanitizeFileName($num);
3537 $dirsource = $conf->facture->dir_output.'/'.$oldref;
3538 $dirdest = $conf->facture->dir_output.'/'.$newref;
3539 if (!$error && file_exists($dirsource)) {
3540 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
3541
3542 if (@rename($dirsource, $dirdest)) {
3543 dol_syslog("Rename ok");
3544 // Rename docs starting with $oldref with $newref
3545 $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
3546 foreach ($listoffiles as $fileentry) {
3547 $dirsource = $fileentry['name'];
3548 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
3549 $dirsource = $fileentry['path'].'/'.$dirsource;
3550 $dirdest = $fileentry['path'].'/'.$dirdest;
3551 @rename($dirsource, $dirdest);
3552 }
3553 }
3554 }
3555 }
3556 }
3557
3558 if (!$error && !$this->is_last_in_cycle()) {
3559 if (!$this->updatePriceNextInvoice($langs)) {
3560 $error++;
3561 }
3562 }
3563
3564 // Set new ref and define current status
3565 if (!$error) {
3566 $this->ref = $num;
3567 $this->statut = self::STATUS_VALIDATED; // deprecated
3569 $this->date_validation = $now;
3570 $i = 0;
3571
3572 if (getDolGlobalString('INVOICE_USE_SITUATION')) {
3573 $final = true;
3574 $nboflines = count($this->lines);
3575 while (($i < $nboflines) && $final) {
3576 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
3577 $previousprogress = $this->lines[$i]->get_allprev_progress($this->lines[$i]->fk_facture);
3578 $current_progress = floatval($this->lines[$i]->situation_percent);
3579 $full_progress = $previousprogress + $current_progress;
3580 $final = ($full_progress == 100);
3581 } else {
3582 $final = ($this->lines[$i]->situation_percent == 100);
3583 }
3584 $i++;
3585 }
3586
3587 if (empty($final)) {
3588 $this->situation_final = 0;
3589 } else {
3590 $this->situation_final = 1;
3591 }
3592
3593 $this->setFinal($user);
3594 }
3595 }
3596 } else {
3597 $error++;
3598 }
3599
3600 if (!$error) {
3601 $this->db->commit();
3602 return 1;
3603 } else {
3604 $this->db->rollback();
3605 return -1;
3606 }
3607 }
3608
3615 public function updatePriceNextInvoice(&$langs)
3616 {
3617 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3618 $is_last = $next_invoice->is_last_in_cycle();
3619
3620 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3621 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3622 return false;
3623 }
3624
3625 foreach ($next_invoice->lines as $line) {
3626 $result = $next_invoice->updateline(
3627 $line->id,
3628 $line->desc,
3629 $line->subprice,
3630 $line->qty,
3631 $line->remise_percent,
3632 $line->date_start,
3633 $line->date_end,
3634 $line->tva_tx,
3635 $line->localtax1_tx,
3636 $line->localtax2_tx,
3637 'HT',
3638 $line->info_bits,
3639 $line->product_type,
3640 $line->fk_parent_line,
3641 0,
3642 $line->fk_fournprice,
3643 $line->pa_ht,
3644 $line->label,
3645 $line->special_code,
3646 $line->array_options,
3647 $line->situation_percent,
3648 $line->fk_unit
3649 );
3650
3651 if ($result < 0) {
3652 $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3653 return false;
3654 }
3655 }
3656
3657 break; // Only the next invoice and not each next invoice
3658 }
3659
3660 return true;
3661 }
3662
3670 public function setDraft($user, $idwarehouse = -1)
3671 {
3672 // phpcs:enable
3673 global $conf, $langs;
3674
3675 $error = 0;
3676
3677 if ($this->status == self::STATUS_DRAFT) {
3678 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
3679 return 0;
3680 }
3681
3682 dol_syslog(__METHOD__, LOG_DEBUG);
3683
3684 $this->db->begin();
3685
3686 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
3687 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
3688 $sql .= " WHERE rowid = ".((int) $this->id);
3689
3690 $result = $this->db->query($sql);
3691 if ($result) {
3692 if (!$error) {
3693 $this->oldcopy = clone $this;
3694 }
3695
3696 // If we decrease stock on invoice validation, we increase back
3697 if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
3698 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3699 $langs->load("agenda");
3700
3701 $num = count($this->lines);
3702 for ($i = 0; $i < $num; $i++) {
3703 if ($this->lines[$i]->fk_product > 0) {
3704 $mouvP = new MouvementStock($this->db);
3705 $mouvP->origin = &$this;
3706 $mouvP->setOrigin($this->element, $this->id);
3707 // We decrease stock for product
3708 if ($this->type == self::TYPE_CREDIT_NOTE) {
3709 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
3710 } else {
3711 $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
3712 }
3713 }
3714 }
3715 }
3716
3717 if ($error == 0) {
3718 $old_statut = $this->status;
3719 $this->statut = self::STATUS_DRAFT; // deprecated
3720 $this->status = self::STATUS_DRAFT;
3721
3722 // Call trigger
3723 $result = $this->call_trigger('BILL_UNVALIDATE', $user);
3724 if ($result < 0) {
3725 $error++;
3726 $this->statut = $old_statut; // deprecated
3727 $this->status = $old_statut;
3728 }
3729 // End call triggers
3730 } else {
3731 $this->db->rollback();
3732 return -1;
3733 }
3734
3735 if ($error == 0) {
3736 $this->db->commit();
3737 return 1;
3738 } else {
3739 $this->db->rollback();
3740 return -1;
3741 }
3742 } else {
3743 $this->error = $this->db->error();
3744 $this->db->rollback();
3745 return -1;
3746 }
3747 }
3748
3749
3791 public function addline(
3792 $desc,
3793 $pu_ht,
3794 $qty,
3795 $txtva,
3796 $txlocaltax1 = 0,
3797 $txlocaltax2 = 0,
3798 $fk_product = 0,
3799 $remise_percent = 0,
3800 $date_start = '',
3801 $date_end = '',
3802 $fk_code_ventilation = 0,
3803 $info_bits = 0,
3804 $fk_remise_except = 0,
3805 $price_base_type = 'HT',
3806 $pu_ttc = 0,
3807 $type = 0,
3808 $rang = -1,
3809 $special_code = 0,
3810 $origin = '',
3811 $origin_id = 0,
3812 $fk_parent_line = 0,
3813 $fk_fournprice = null,
3814 $pa_ht = 0,
3815 $label = '',
3816 $array_options = array(),
3817 $situation_percent = 100,
3818 $fk_prev_id = 0,
3819 $fk_unit = null,
3820 $pu_ht_devise = 0,
3821 $ref_ext = '',
3822 $noupdateafterinsertline = 0
3823 ) {
3824 // Deprecation warning
3825 if ($label) {
3826 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
3827 //var_dump(debug_backtrace(false));exit;
3828 }
3829
3830 global $mysoc, $conf, $langs;
3831
3832 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);
3833
3834 if ($this->status == self::STATUS_DRAFT) {
3835 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3836
3837 // Clean parameters
3838 if (empty($remise_percent)) {
3839 $remise_percent = 0;
3840 }
3841 if (empty($qty)) {
3842 $qty = 0;
3843 }
3844 if (empty($info_bits)) {
3845 $info_bits = 0;
3846 }
3847 if (empty($rang)) {
3848 $rang = 0;
3849 }
3850 if (empty($fk_code_ventilation)) {
3851 $fk_code_ventilation = 0;
3852 }
3853 if (empty($txtva)) {
3854 $txtva = 0;
3855 }
3856 if (empty($txlocaltax1)) {
3857 $txlocaltax1 = 0;
3858 }
3859 if (empty($txlocaltax2)) {
3860 $txlocaltax2 = 0;
3861 }
3862 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3863 $fk_parent_line = 0;
3864 }
3865 if (empty($fk_prev_id)) {
3866 $fk_prev_id = 'null';
3867 }
3868 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
3869 $situation_percent = 100;
3870 }
3871 if (empty($ref_ext)) {
3872 $ref_ext = '';
3873 }
3874
3875 $remise_percent = (float) price2num($remise_percent);
3876 $qty = price2num($qty);
3877 $pu_ht = price2num($pu_ht);
3878 $pu_ht_devise = price2num($pu_ht_devise);
3879 $pu_ttc = price2num($pu_ttc);
3880 $pa_ht = price2num($pa_ht);
3881 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3882 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3883 }
3884 $txlocaltax1 = price2num($txlocaltax1);
3885 $txlocaltax2 = price2num($txlocaltax2);
3886
3887 if ($price_base_type == 'HT') {
3888 $pu = $pu_ht;
3889 } else {
3890 $pu = $pu_ttc;
3891 }
3892
3893 // Check parameters
3894 if ($type < 0) {
3895 return -1;
3896 }
3897
3898 if ($date_start && $date_end && $date_start > $date_end) {
3899 $langs->load("errors");
3900 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3901 return -1;
3902 }
3903
3904 $this->db->begin();
3905
3906 $product_type = $type;
3907 if (!empty($fk_product) && $fk_product > 0) {
3908 $product = new Product($this->db);
3909 $result = $product->fetch($fk_product);
3910 $product_type = $product->type;
3911
3912 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
3913 $langs->load("errors");
3914 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3915 $this->db->rollback();
3916 return -3;
3917 }
3918 }
3919
3920 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3921
3922 // Clean vat code
3923 $reg = array();
3924 $vat_src_code = '';
3925 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3926 $vat_src_code = $reg[1];
3927 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3928 }
3929
3930 // Calcul du total TTC et de la TVA pour la ligne a partir de
3931 // qty, pu, remise_percent et txtva
3932 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3933 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3934
3935 $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);
3936
3937 $total_ht = $tabprice[0];
3938 $total_tva = $tabprice[1];
3939 $total_ttc = $tabprice[2];
3940 $total_localtax1 = $tabprice[9];
3941 $total_localtax2 = $tabprice[10];
3942 $pu_ht = $tabprice[3];
3943
3944 // MultiCurrency
3945 $multicurrency_total_ht = $tabprice[16];
3946 $multicurrency_total_tva = $tabprice[17];
3947 $multicurrency_total_ttc = $tabprice[18];
3948 $pu_ht_devise = $tabprice[19];
3949
3950 // Rank to use
3951 $ranktouse = $rang;
3952 if ($ranktouse == -1) {
3953 $rangmax = $this->line_max($fk_parent_line);
3954 $ranktouse = $rangmax + 1;
3955 }
3956
3957 // Insert line
3958 $this->line = new FactureLigne($this->db);
3959
3960 $this->line->context = $this->context;
3961
3962 $this->line->fk_facture = $this->id;
3963 $this->line->label = $label; // deprecated
3964 $this->line->desc = $desc;
3965 $this->line->ref_ext = $ref_ext;
3966
3967 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
3968 $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
3969
3970 $this->line->vat_src_code = $vat_src_code;
3971 $this->line->tva_tx = $txtva;
3972 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3973 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3974 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
3975 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
3976
3977 $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
3978 $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc); // For credit note and if qty is negative, total is negative
3979 $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva); // For credit note and if qty is negative, total is negative
3980 $this->line->total_localtax1 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1); // For credit note and if qty is negative, total is negative
3981 $this->line->total_localtax2 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2); // For credit note and if qty is negative, total is negative
3982
3983 $this->line->fk_product = $fk_product;
3984 $this->line->product_type = $product_type;
3985 $this->line->remise_percent = $remise_percent;
3986 $this->line->date_start = $date_start;
3987 $this->line->date_end = $date_end;
3988 $this->line->fk_code_ventilation = $fk_code_ventilation;
3989 $this->line->rang = $ranktouse;
3990 $this->line->info_bits = $info_bits;
3991 $this->line->fk_remise_except = $fk_remise_except;
3992
3993 $this->line->special_code = $special_code;
3994 $this->line->fk_parent_line = $fk_parent_line;
3995 $this->line->origin = $origin;
3996 $this->line->origin_id = $origin_id;
3997 $this->line->situation_percent = $situation_percent;
3998 $this->line->fk_prev_id = $fk_prev_id;
3999 $this->line->fk_unit = $fk_unit;
4000
4001 // infos margin
4002 $this->line->fk_fournprice = $fk_fournprice;
4003 $this->line->pa_ht = $pa_ht;
4004
4005 // Multicurrency
4006 $this->line->fk_multicurrency = $this->fk_multicurrency;
4007 $this->line->multicurrency_code = $this->multicurrency_code;
4008 $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
4009
4010 $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
4011 $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
4012 $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
4013
4014 if (is_array($array_options) && count($array_options) > 0) {
4015 $this->line->array_options = $array_options;
4016 }
4017
4018 $result = $this->line->insert();
4019 if ($result > 0) {
4020 // Reorder if child line
4021 if (!empty($fk_parent_line)) {
4022 $this->line_order(true, 'DESC');
4023 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
4024 $linecount = count($this->lines);
4025 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4026 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
4027 }
4028 }
4029
4030 // Mise a jour information denormalisees au niveau de la facture meme
4031 if (empty($noupdateafterinsertline)) {
4032 $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.
4033 }
4034
4035 if ($result > 0) {
4036 $this->db->commit();
4037 return $this->line->id;
4038 } else {
4039 $this->error = $this->db->lasterror();
4040 $this->db->rollback();
4041 return -1;
4042 }
4043 } else {
4044 $this->error = $this->line->error;
4045 $this->errors = $this->line->errors;
4046 $this->db->rollback();
4047 return -2;
4048 }
4049 } else {
4050 $this->errors[] = 'status of invoice must be Draft to allow use of ->addline()';
4051 dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4052 return -3;
4053 }
4054 }
4055
4087 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)
4088 {
4089 global $conf, $user;
4090 // Deprecation warning
4091 if ($label) {
4092 dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
4093 }
4094
4095 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4096
4097 global $mysoc, $langs;
4098
4099 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);
4100
4101 if ($this->status == self::STATUS_DRAFT) {
4102 if (!$this->is_last_in_cycle() && empty($this->error)) {
4103 if (!$this->checkProgressLine($rowid, $situation_percent)) {
4104 if (!$this->error) {
4105 $this->error = $langs->trans('invoiceLineProgressError');
4106 }
4107 return -3;
4108 }
4109 }
4110
4111 if ($date_start && $date_end && $date_start > $date_end) {
4112 $langs->load("errors");
4113 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
4114 return -1;
4115 }
4116
4117 $this->db->begin();
4118
4119 // Clean parameters
4120 if (empty($qty)) {
4121 $qty = 0;
4122 }
4123 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4124 $fk_parent_line = 0;
4125 }
4126 if (empty($special_code) || $special_code == 3) {
4127 $special_code = 0;
4128 }
4129 if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
4130 $situation_percent = 100;
4131 }
4132 if (empty($ref_ext)) {
4133 $ref_ext = '';
4134 }
4135
4136 $remise_percent = (float) price2num($remise_percent);
4137 $qty = price2num($qty);
4138 $pu = price2num($pu);
4139 $pu_ht_devise = price2num($pu_ht_devise);
4140 $pa_ht = price2num($pa_ht);
4141 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
4142 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
4143 }
4144 $txlocaltax1 = (float) price2num($txlocaltax1);
4145 $txlocaltax2 = (float) price2num($txlocaltax2);
4146
4147 // Check parameters
4148 if ($type < 0) {
4149 return -1;
4150 }
4151
4152 // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
4153 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
4154 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
4155
4156 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
4157
4158 // Clean vat code
4159 $reg = array();
4160 $vat_src_code = '';
4161 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
4162 $vat_src_code = $reg[1];
4163 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
4164 }
4165
4166 $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);
4167
4168 $total_ht = $tabprice[0];
4169 $total_tva = $tabprice[1];
4170 $total_ttc = $tabprice[2];
4171 $total_localtax1 = $tabprice[9];
4172 $total_localtax2 = $tabprice[10];
4173 $pu_ht = $tabprice[3];
4174 $pu_tva = $tabprice[4];
4175 $pu_ttc = $tabprice[5];
4176
4177 // MultiCurrency
4178 $multicurrency_total_ht = $tabprice[16];
4179 $multicurrency_total_tva = $tabprice[17];
4180 $multicurrency_total_ttc = $tabprice[18];
4181 $pu_ht_devise = $tabprice[19];
4182
4183 // Old properties: $price, $remise (deprecated)
4184 $price = $pu;
4185 $remise = 0;
4186 if ($remise_percent > 0) {
4187 $remise = round(((float) $pu * (float) $remise_percent / 100), 2);
4188 $price = ((float) $pu - $remise);
4189 }
4190 $price = price2num($price);
4191
4192 //Fetch current line from the database and then clone the object and set it in $oldline property
4193 $line = new FactureLigne($this->db);
4194 $line->fetch($rowid);
4195 $line->fetch_optionals();
4196
4197 if (!empty($line->fk_product)) {
4198 $product = new Product($this->db);
4199 $result = $product->fetch($line->fk_product);
4200 $product_type = $product->type;
4201
4202 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4203 $langs->load("errors");
4204 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4205 $this->db->rollback();
4206 return -3;
4207 }
4208 }
4209
4210 $staticline = clone $line;
4211
4212 $line->oldline = $staticline;
4213 $this->line = $line;
4214 $this->line->context = $this->context;
4215 $this->line->rang = $rang;
4216
4217 // Reorder if fk_parent_line change
4218 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4219 $rangmax = $this->line_max($fk_parent_line);
4220 $this->line->rang = $rangmax + 1;
4221 }
4222
4223 $this->line->id = $rowid;
4224 $this->line->rowid = $rowid;
4225 $this->line->label = $label;
4226 $this->line->desc = $desc;
4227 $this->line->ref_ext = $ref_ext;
4228 $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : $qty); // For credit note, quantity is always positive and unit price negative
4229
4230 $this->line->vat_src_code = $vat_src_code;
4231 $this->line->tva_tx = $txtva;
4232 $this->line->localtax1_tx = $txlocaltax1;
4233 $this->line->localtax2_tx = $txlocaltax2;
4234 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4235 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4236
4237 $this->line->remise_percent = $remise_percent;
4238 $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
4239 $this->line->date_start = $date_start;
4240 $this->line->date_end = $date_end;
4241 $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
4242 $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
4243 $this->line->total_localtax1 = $total_localtax1;
4244 $this->line->total_localtax2 = $total_localtax2;
4245 $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
4246 $this->line->info_bits = $info_bits;
4247 $this->line->special_code = $special_code;
4248 $this->line->product_type = $type;
4249 $this->line->fk_parent_line = $fk_parent_line;
4250 $this->line->skip_update_total = $skip_update_total;
4251 $this->line->situation_percent = $situation_percent;
4252 $this->line->fk_unit = $fk_unit;
4253
4254 $this->line->fk_fournprice = $fk_fournprice;
4255 $this->line->pa_ht = $pa_ht;
4256
4257 // Multicurrency
4258 $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
4259 $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
4260 $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4261 $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4262
4263 if (is_array($array_options) && count($array_options) > 0) {
4264 // We replace values in this->line->array_options only for entries defined into $array_options
4265 foreach ($array_options as $key => $value) {
4266 $this->line->array_options[$key] = $array_options[$key];
4267 }
4268 }
4269
4270 $result = $this->line->update($user, $notrigger);
4271 if ($result > 0) {
4272 // Reorder if child line
4273 if (!empty($fk_parent_line)) {
4274 $this->line_order(true, 'DESC');
4275 }
4276
4277 // Mise a jour info denormalisees au niveau facture
4278 $this->update_price(1, 'auto');
4279 $this->db->commit();
4280 return $result;
4281 } else {
4282 $this->error = $this->line->error;
4283 $this->db->rollback();
4284 return -1;
4285 }
4286 } else {
4287 $this->error = "Invoice statut makes operation forbidden";
4288 return -2;
4289 }
4290 }
4291
4299 public function checkProgressLine($idline, $situation_percent)
4300 {
4301 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
4302 INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
4303 WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
4304
4305 $result = $this->db->query($sql);
4306 if (!$result) {
4307 $this->error = $this->db->error();
4308 return false;
4309 }
4310
4311 $obj = $this->db->fetch_object($result);
4312
4313 if ($obj === null) {
4314 return true;
4315 } else {
4316 return ($situation_percent < $obj->situation_percent);
4317 }
4318 }
4319
4320 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4329 public function update_percent($line, $percent, $update_price = true)
4330 {
4331 // phpcs:enable
4332 global $mysoc, $user;
4333
4334 // Progress should never be changed for discount lines
4335 if (($line->info_bits & 2) == 2) {
4336 return;
4337 }
4338
4339 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4340
4341 // Cap percentages to 100
4342 if ($percent > 100) {
4343 $percent = 100;
4344 }
4345 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
4346 $previous_progress = $line->get_allprev_progress($line->fk_facture);
4347 $current_progress = $percent - $previous_progress;
4348 $line->situation_percent = $current_progress;
4349 $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, '', $current_progress);
4350 } else {
4351 $line->situation_percent = $percent;
4352 $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, '', $percent);
4353 }
4354 $line->total_ht = $tabprice[0];
4355 $line->total_tva = $tabprice[1];
4356 $line->total_ttc = $tabprice[2];
4357 $line->total_localtax1 = $tabprice[9];
4358 $line->total_localtax2 = $tabprice[10];
4359 $line->multicurrency_total_ht = $tabprice[16];
4360 $line->multicurrency_total_tva = $tabprice[17];
4361 $line->multicurrency_total_ttc = $tabprice[18];
4362 $line->update($user);
4363
4364 // sometimes it is better to not update price for each line, ie when updating situation on all lines
4365 if ($update_price) {
4366 $this->update_price(1);
4367 }
4368 }
4369
4377 public function deleteLine($rowid, $id = 0)
4378 {
4379 global $user;
4380
4381 dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
4382
4383 if ($this->status != self::STATUS_DRAFT) {
4384 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
4385 return -1;
4386 }
4387
4388 $line = new FactureLigne($this->db);
4389
4390 $line->context = $this->context;
4391
4392 // Load line
4393 $result = $line->fetch($rowid);
4394 if (!($result > 0)) {
4395 dol_print_error($this->db, $line->error, $line->errors);
4396 return -1;
4397 }
4398
4399 if ($id > 0 && $line->fk_facture != $id) {
4400 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
4401 return -1;
4402 }
4403
4404 $this->db->begin();
4405
4406 // Memorize previous line for triggers
4407 $staticline = clone $line;
4408 $line->oldline = $staticline;
4409
4410 if ($line->delete($user) > 0) {
4411 $result = $this->update_price(1);
4412
4413 if ($result > 0) {
4414 $this->db->commit();
4415 return 1;
4416 } else {
4417 $this->db->rollback();
4418 $this->error = $this->db->lasterror();
4419 return -1;
4420 }
4421 } else {
4422 $this->db->rollback();
4423 $this->error = $line->error;
4424 return -1;
4425 }
4426 }
4427
4428 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4439 public function set_remise($user, $remise, $notrigger = 0)
4440 {
4441 // phpcs:enable
4442 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4443 // @phan-suppress-next-line PhanDeprecatedFunction
4444 return $this->setDiscount($user, $remise, $notrigger);
4445 }
4446
4455 public function setDiscount($user, $remise, $notrigger = 0)
4456 {
4457 // Clean parameters
4458 if (empty($remise)) {
4459 $remise = 0;
4460 }
4461
4462 if ($user->hasRight('facture', 'creer')) {
4463 $remise = (float) price2num($remise, 2);
4464
4465 $error = 0;
4466
4467 $this->db->begin();
4468
4469 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
4470 $sql .= " SET remise_percent = ".((float) $remise);
4471 $sql .= " WHERE rowid = ".((int) $this->id);
4472 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
4473
4474 dol_syslog(__METHOD__, LOG_DEBUG);
4475 $resql = $this->db->query($sql);
4476 if (!$resql) {
4477 $this->errors[] = $this->db->error();
4478 $error++;
4479 }
4480
4481 if (!$notrigger && empty($error)) {
4482 // Call trigger
4483 $result = $this->call_trigger('BILL_MODIFY', $user);
4484 if ($result < 0) {
4485 $error++;
4486 }
4487 // End call triggers
4488 }
4489
4490 if (!$error) {
4491 $this->remise_percent = $remise;
4492 $this->update_price(1);
4493
4494 $this->db->commit();
4495 return 1;
4496 } else {
4497 foreach ($this->errors as $errmsg) {
4498 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4499 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4500 }
4501 $this->db->rollback();
4502 return -1 * $error;
4503 }
4504 }
4505
4506 return 0;
4507 }
4508
4509
4510 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4519 /*
4520 public function set_remise_absolue($user, $remise, $notrigger = 0)
4521 {
4522 // phpcs:enable
4523 if (empty($remise)) {
4524 $remise = 0;
4525 }
4526
4527 if ($user->hasRight('facture', 'creer')) {
4528 $error = 0;
4529
4530 $this->db->begin();
4531
4532 $remise = price2num($remise);
4533
4534 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
4535 $sql .= ' SET remise_absolue = '.((float) $remise);
4536 $sql .= " WHERE rowid = ".((int) $this->id);
4537 $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
4538
4539 dol_syslog(__METHOD__, LOG_DEBUG);
4540 $resql = $this->db->query($sql);
4541 if (!$resql) {
4542 $this->errors[] = $this->db->error();
4543 $error++;
4544 }
4545
4546 if (!$error) {
4547 $this->oldcopy = clone $this;
4548 $this->remise_absolue = $remise;
4549 $this->update_price(1);
4550 }
4551
4552 if (!$notrigger && empty($error)) {
4553 // Call trigger
4554 $result = $this->call_trigger('BILL_MODIFY', $user);
4555 if ($result < 0) {
4556 $error++;
4557 }
4558 // End call triggers
4559 }
4560
4561 if (!$error) {
4562 $this->db->commit();
4563 return 1;
4564 } else {
4565 foreach ($this->errors as $errmsg) {
4566 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
4567 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4568 }
4569 $this->db->rollback();
4570 return -1 * $error;
4571 }
4572 }
4573
4574 return 0;
4575 }
4576 */
4577
4586 public function getNextNumRef($soc, $mode = 'next')
4587 {
4588 global $conf, $langs;
4589
4590 if ($this->module_source == 'takepos') {
4591 $langs->load('cashdesk');
4592
4593 $moduleName = 'takepos';
4594 $moduleSourceName = 'Takepos';
4595 $addonConstName = 'TAKEPOS_REF_ADDON';
4596
4597 // Clean parameters (if not defined or using deprecated value)
4598 if (!getDolGlobalString('TAKEPOS_REF_ADDON')) {
4599 $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
4600 }
4601
4602 $addon = getDolGlobalString('TAKEPOS_REF_ADDON');
4603 } else {
4604 $langs->load('bills');
4605
4606 $moduleName = 'facture';
4607 $moduleSourceName = 'Invoice';
4608 $addonConstName = 'FACTURE_ADDON';
4609
4610 // Clean parameters (if not defined or using deprecated value)
4611 if (!getDolGlobalString('FACTURE_ADDON')) {
4612 $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4613 } elseif (getDolGlobalString('FACTURE_ADDON') == 'terre') {
4614 $conf->global->FACTURE_ADDON = 'mod_facture_terre';
4615 } elseif (getDolGlobalString('FACTURE_ADDON') == 'mercure') {
4616 $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
4617 }
4618
4619 $addon = getDolGlobalString('FACTURE_ADDON');
4620 }
4621
4622 if (!empty($addon)) {
4623 dol_syslog("Call getNextNumRef with ".$addonConstName." = " . getDolGlobalString('FACTURE_ADDON').", thirdparty=".$soc->name.", type=".$soc->typent_code.", mode=".$mode, LOG_DEBUG);
4624
4625 $mybool = false;
4626
4627 $file = $addon.'.php';
4628 $classname = $addon;
4629
4630
4631 // Include file with class
4632 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
4633 foreach ($dirmodels as $reldir) {
4634 $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
4635
4636 // Load file with numbering class (if found)
4637 if (is_file($dir.$file) && is_readable($dir.$file)) {
4638 $mybool = ((bool) include_once $dir.$file) || $mybool;
4639 }
4640 }
4641
4642 // For compatibility
4643 if (!$mybool) {
4644 $file = $addon.'/'.$addon.'.modules.php';
4645 $classname = 'mod_'.$moduleName.'_'.$addon;
4646 $classname = preg_replace('/\-.*$/', '', $classname);
4647 // Include file with class
4648 foreach ($conf->file->dol_document_root as $dirroot) {
4649 $dir = $dirroot.'/core/modules/'.$moduleName.'/';
4650
4651 // Load file with numbering class (if found)
4652 if (is_file($dir.$file) && is_readable($dir.$file)) {
4653 $mybool = (include_once $dir.$file) || $mybool;
4654 }
4655 }
4656 }
4657
4658 if (!$mybool) {
4659 dol_print_error(null, 'Failed to include file '.$file);
4660 return '';
4661 }
4662
4663 $obj = new $classname();
4664 '@phan-var-force CommonNumRefGenerator $obj';
4665
4666 $numref = $obj->getNextValue($soc, $this, $mode);
4667
4668
4673 if ($mode != 'last' && !$numref) {
4674 $this->error = $obj->error;
4675 return '';
4676 }
4677
4678 return $numref;
4679 } else {
4680 $langs->load('errors');
4681 print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4682 return '';
4683 }
4684 }
4685
4692 public function info($id)
4693 {
4694 $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4695 $sql .= ' date_closing as dateclosing,';
4696 $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
4697 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
4698 $sql .= ' WHERE c.rowid = '.((int) $id);
4699
4700 $result = $this->db->query($sql);
4701 if ($result) {
4702 if ($this->db->num_rows($result)) {
4703 $obj = $this->db->fetch_object($result);
4704
4705 $this->id = $obj->rowid;
4706 $this->user_creation_id = $obj->fk_user_author;
4707 $this->user_validation_id = $obj->fk_user_valid;
4708 $this->user_closing_id = $obj->fk_user_closing;
4709
4710 $this->date_creation = $this->db->jdate($obj->datec);
4711 $this->date_modification = $this->db->jdate($obj->datem);
4712 $this->date_validation = $this->db->jdate($obj->datev);
4713 $this->date_closing = $this->db->jdate($obj->dateclosing);
4714 }
4715 $this->db->free($result);
4716 } else {
4717 dol_print_error($this->db);
4718 }
4719 }
4720
4721
4722 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4736 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
4737 {
4738 // phpcs:enable
4739 global $user;
4740
4741 $ga = array();
4742
4743 $sql = "SELECT s.rowid, s.nom as name, s.client,";
4744 $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
4745 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
4746 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4747 $sql .= " AND f.fk_soc = s.rowid";
4748 if ($draft) {
4749 $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
4750 }
4751 if (is_object($excluser)) {
4752 $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
4753 }
4754 // If the internal user must only see his customers, force searching by him
4755 $search_sale = 0;
4756 if (!$user->hasRight('societe', 'client', 'voir')) {
4757 $search_sale = $user->id;
4758 }
4759 // Search on sale representative
4760 if ($search_sale && $search_sale != '-1') {
4761 if ($search_sale == -2) {
4762 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4763 } elseif ($search_sale > 0) {
4764 $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).")";
4765 }
4766 }
4767 // Search on socid
4768 if ($socid) {
4769 $sql .= " AND f.fk_soc = ".((int) $socid);
4770 }
4771 $sql .= $this->db->order($sortfield, $sortorder);
4772 $sql .= $this->db->plimit($limit, $offset);
4773
4774 $result = $this->db->query($sql);
4775 if ($result) {
4776 $numc = $this->db->num_rows($result);
4777 if ($numc) {
4778 $i = 0;
4779 while ($i < $numc) {
4780 $obj = $this->db->fetch_object($result);
4781
4782 if ($shortlist == 1) {
4783 $ga[$obj->fid] = $obj->ref;
4784 } elseif ($shortlist == 2) {
4785 $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
4786 } else {
4787 $ga[$i]['id'] = $obj->fid;
4788 $ga[$i]['ref'] = $obj->ref;
4789 $ga[$i]['name'] = $obj->name;
4790 }
4791 $i++;
4792 }
4793 }
4794 return $ga;
4795 } else {
4796 dol_print_error($this->db);
4797 return -1;
4798 }
4799 }
4800
4801
4802 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4811 public function list_replacable_invoices($socid = 0)
4812 {
4813 // phpcs:enable
4814 global $conf;
4815
4816 $return = array();
4817
4818 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4819 $sql .= " ff.rowid as rowidnext";
4820 //$sql .= ", SUM(pf.amount) as alreadypaid";
4821 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4822 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4823 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
4824 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
4825 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4826 $sql .= " AND f.paye = 0"; // Not paid completely
4827 $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
4828 $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
4829 if ($socid > 0) {
4830 $sql .= " AND f.fk_soc = ".((int) $socid);
4831 }
4832 //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
4833 $sql .= " ORDER BY f.ref";
4834
4835 dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
4836 $resql = $this->db->query($sql);
4837 if ($resql) {
4838 while ($obj = $this->db->fetch_object($resql)) {
4839 $return[$obj->rowid] = array(
4840 'id' => $obj->rowid,
4841 'ref' => $obj->ref,
4842 'status' => $obj->status,
4843 'paid' => $obj->paid,
4844 'alreadypaid' => 0
4845 );
4846 }
4847 //print_r($return);
4848 return $return;
4849 } else {
4850 $this->error = $this->db->error();
4851 return -1;
4852 }
4853 }
4854
4855
4856 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4865 public function list_qualified_avoir_invoices($socid = 0)
4866 {
4867 // phpcs:enable
4868 global $conf;
4869
4870 $return = array();
4871
4872
4873 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4874 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4875 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
4876 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
4877 $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
4878 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4879 // $sql.= " WHERE f.fk_statut >= 1";
4880 // $sql.= " AND (f.paye = 1"; // Classee payee completement
4881 // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
4882 $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de replacement
4883 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
4884
4885 if (getDolGlobalString('INVOICE_USE_SITUATION_CREDIT_NOTE')) {
4886 // Keep invoices that are not situation invoices or that are the last in series if it is a situation invoice
4887 $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
4888 $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID because of the group by later
4889 $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
4890 $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
4891 $sql .= " AND fs.type = ".self::TYPE_SITUATION;
4892 $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
4893 if ($socid > 0) {
4894 $sql .= " AND fs.fk_soc = ".((int) $socid);
4895 }
4896 $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
4897 $sql .= ")";
4898 } else {
4899 $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
4900 }
4901
4902 if ($socid > 0) {
4903 $sql .= " AND f.fk_soc = ".((int) $socid);
4904 }
4905 $sql .= " ORDER BY f.ref";
4906
4907 dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
4908 $resql = $this->db->query($sql);
4909 if ($resql) {
4910 while ($obj = $this->db->fetch_object($resql)) {
4911 $qualified = 0;
4912 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4913 $qualified = 1;
4914 }
4915 if ($obj->fk_statut == self::STATUS_CLOSED) {
4916 $qualified = 1;
4917 }
4918 if ($qualified) {
4919 //$ref=$obj->ref;
4920 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4921 $return[$obj->rowid] = array('ref' => $obj->ref, 'status' => $obj->fk_statut, 'type' => $obj->type, 'paye' => $obj->paye, 'paymentornot' => $paymentornot);
4922 }
4923 }
4924
4925 return $return;
4926 } else {
4927 $this->error = $this->db->error();
4928 return -1;
4929 }
4930 }
4931
4932
4933 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4940 public function load_board($user)
4941 {
4942 // phpcs:enable
4943 global $conf, $langs;
4944
4945 $clause = " WHERE";
4946
4947 $sql = "SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
4948 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
4949 if (!$user->hasRight('societe', 'client', 'voir')) {
4950 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4951 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4952 $clause = " AND";
4953 }
4954 $sql .= $clause." f.paye=0";
4955 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4956 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
4957 if ($user->socid) {
4958 $sql .= " AND f.fk_soc = ".((int) $user->socid);
4959 }
4960
4961 $resql = $this->db->query($sql);
4962 if ($resql) {
4963 $langs->load("bills");
4964 $now = dol_now();
4965
4966 $response = new WorkboardResponse();
4967 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4968 $response->label = $langs->trans("CustomerBillsUnpaid");
4969 $response->labelShort = $langs->trans("Unpaid");
4970 $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4971 $response->img = img_object('', "bill");
4972
4973 $generic_facture = new Facture($this->db);
4974
4975 while ($obj = $this->db->fetch_object($resql)) {
4976 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4977 $generic_facture->statut = $obj->status;
4978 $generic_facture->status = $obj->status;
4979
4980 $response->nbtodo++;
4981 $response->total += $obj->total_ht;
4982
4983 if ($generic_facture->hasDelay()) {
4984 $response->nbtodolate++;
4985 $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4986 }
4987 }
4988
4989 $this->db->free($resql);
4990 return $response;
4991 } else {
4992 dol_print_error($this->db);
4993 $this->error = $this->db->error();
4994 return -1;
4995 }
4996 }
4997
4998
4999 /* gestion des contacts d'une facture */
5000
5006 public function getIdBillingContact()
5007 {
5008 return $this->getIdContact('external', 'BILLING');
5009 }
5010
5016 public function getIdShippingContact()
5017 {
5018 return $this->getIdContact('external', 'SHIPPING');
5019 }
5020
5021
5030 public function initAsSpecimen($option = '')
5031 {
5032 global $conf, $langs, $user;
5033
5034 $now = dol_now();
5035 $arraynow = dol_getdate($now);
5036 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
5037
5038 // Load array of products prodids
5039 $num_prods = 0;
5040 $prodids = array();
5041 $sql = "SELECT rowid";
5042 $sql .= " FROM ".MAIN_DB_PREFIX."product";
5043 $sql .= " WHERE entity IN (".getEntity('product').")";
5044 $sql .= $this->db->plimit(100);
5045
5046 $resql = $this->db->query($sql);
5047 if ($resql) {
5048 $num_prods = $this->db->num_rows($resql);
5049 $i = 0;
5050 while ($i < $num_prods) {
5051 $i++;
5052 $row = $this->db->fetch_row($resql);
5053 $prodids[$i] = $row[0];
5054 }
5055 }
5056 //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
5057 if (empty($num_prods)) {
5058 $num_prods = 1;
5059 }
5060
5061 // Initialize parameters
5062 $this->id = 0;
5063 $this->entity = 1;
5064 $this->ref = 'SPECIMEN';
5065 $this->specimen = 1;
5066 $this->socid = 1;
5067 $this->date = $nownotime;
5068 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5069 $this->cond_reglement_id = 1;
5070 $this->cond_reglement_code = 'RECEP';
5071 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
5072 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
5073 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
5074
5075 $this->note_public = 'This is a comment (public)';
5076 $this->note_private = 'This is a comment (private)';
5077 $this->note = 'This is a comment (private)';
5078
5079 $this->fk_user_author = $user->id;
5080
5081 $this->multicurrency_tx = 1;
5082 $this->multicurrency_code = $conf->currency;
5083
5084 $this->fk_incoterms = 0;
5085 $this->location_incoterms = '';
5086
5087 if (empty($option) || $option != 'nolines') {
5088 // Lines
5089 $nbp = 5;
5090 $xnbp = 0;
5091 while ($xnbp < $nbp) {
5092 $line = new FactureLigne($this->db);
5093 $line->desc = $langs->trans("Description")." ".$xnbp;
5094 $line->qty = 1;
5095 $line->subprice = 100;
5096 $line->tva_tx = 19.6;
5097 $line->localtax1_tx = 0;
5098 $line->localtax2_tx = 0;
5099 $line->remise_percent = 0;
5100 if ($xnbp == 1) { // Qty is negative (product line)
5101 $prodid = mt_rand(1, $num_prods);
5102 $line->fk_product = $prodids[$prodid];
5103 $line->qty = -1;
5104 $line->total_ht = -100;
5105 $line->total_ttc = -119.6;
5106 $line->total_tva = -19.6;
5107 $line->multicurrency_total_ht = -200;
5108 $line->multicurrency_total_ttc = -239.2;
5109 $line->multicurrency_total_tva = -39.2;
5110 } elseif ($xnbp == 2) { // UP is negative (free line)
5111 $line->subprice = -100;
5112 $line->total_ht = -100;
5113 $line->total_ttc = -119.6;
5114 $line->total_tva = -19.6;
5115 $line->remise_percent = 0;
5116 $line->multicurrency_total_ht = -200;
5117 $line->multicurrency_total_ttc = -239.2;
5118 $line->multicurrency_total_tva = -39.2;
5119 } elseif ($xnbp == 3) { // Discount is 50% (product line)
5120 $prodid = mt_rand(1, $num_prods);
5121 $line->fk_product = $prodids[$prodid];
5122 $line->total_ht = 50;
5123 $line->total_ttc = 59.8;
5124 $line->total_tva = 9.8;
5125 $line->multicurrency_total_ht = 100;
5126 $line->multicurrency_total_ttc = 119.6;
5127 $line->multicurrency_total_tva = 19.6;
5128 $line->remise_percent = 50;
5129 } else { // (product line)
5130 $prodid = mt_rand(1, $num_prods);
5131 $line->fk_product = $prodids[$prodid];
5132 $line->total_ht = 100;
5133 $line->total_ttc = 119.6;
5134 $line->total_tva = 19.6;
5135 $line->multicurrency_total_ht = 200;
5136 $line->multicurrency_total_ttc = 239.2;
5137 $line->multicurrency_total_tva = 39.2;
5138 $line->remise_percent = 0;
5139 }
5140
5141 $this->lines[$xnbp] = $line;
5142
5143
5144 $this->total_ht += $line->total_ht;
5145 $this->total_tva += $line->total_tva;
5146 $this->total_ttc += $line->total_ttc;
5147
5148 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5149 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5150 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5151
5152 $xnbp++;
5153 }
5154 $this->revenuestamp = 0;
5155
5156 // Add a line "offered"
5157 $line = new FactureLigne($this->db);
5158 $line->desc = $langs->trans("Description")." (offered line)";
5159 $line->qty = 1;
5160 $line->subprice = 100;
5161 $line->tva_tx = 19.6;
5162 $line->localtax1_tx = 0;
5163 $line->localtax2_tx = 0;
5164 $line->remise_percent = 100;
5165 $line->total_ht = 0;
5166 $line->total_ttc = 0; // 90 * 1.196
5167 $line->total_tva = 0;
5168 $line->multicurrency_total_ht = 0;
5169 $line->multicurrency_total_ttc = 0;
5170 $line->multicurrency_total_tva = 0;
5171 $prodid = mt_rand(1, $num_prods);
5172 $line->fk_product = $prodids[$prodid];
5173
5174 $this->lines[$xnbp] = $line;
5175 $xnbp++;
5176 }
5177
5178 return 1;
5179 }
5180
5186 public function loadStateBoard()
5187 {
5188 global $conf, $user;
5189
5190 $this->nb = array();
5191
5192 $clause = "WHERE";
5193
5194 $sql = "SELECT count(f.rowid) as nb";
5195 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5196 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
5197 if (!$user->hasRight('societe', 'client', 'voir')) {
5198 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5199 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
5200 $clause = "AND";
5201 }
5202 $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
5203
5204 $resql = $this->db->query($sql);
5205 if ($resql) {
5206 while ($obj = $this->db->fetch_object($resql)) {
5207 $this->nb["invoices"] = $obj->nb;
5208 }
5209 $this->db->free($resql);
5210 return 1;
5211 } else {
5212 dol_print_error($this->db);
5213 $this->error = $this->db->error();
5214 return -1;
5215 }
5216 }
5217
5223 public function getLinesArray()
5224 {
5225 return $this->fetch_lines();
5226 }
5227
5239 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5240 {
5241 global $conf, $langs;
5242
5243 $outputlangs->loadLangs(array("bills", "products"));
5244
5245 if (!dol_strlen($modele)) {
5246 $modele = 'crabe';
5247 $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
5248
5249 if (!empty($this->model_pdf)) {
5250 $modele = $this->model_pdf;
5251 } elseif (getDolGlobalString($thisTypeConfName)) {
5252 $modele = getDolGlobalString($thisTypeConfName);
5253 } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) {
5254 $modele = getDolGlobalString('FACTURE_ADDON_PDF');
5255 }
5256 }
5257
5258 $modelpath = "core/modules/facture/doc/";
5259
5260 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5261 }
5262
5268 public function newCycle()
5269 {
5270 $sql = "SELECT max(situation_cycle_ref) as maxsituationref";
5271 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
5272 $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
5273
5274 $resql = $this->db->query($sql);
5275 if ($resql) {
5276 if ($this->db->num_rows($resql) > 0) {
5277 $ref = 0;
5278 $obj = $this->db->fetch_object($resql);
5279 if ($obj) {
5280 $ref = $obj->maxsituationref;
5281 }
5282 $ref++;
5283 } else {
5284 $ref = 1;
5285 }
5286 $this->db->free($resql);
5287 return $ref;
5288 } else {
5289 $this->error = $this->db->lasterror();
5290 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5291 return -1;
5292 }
5293 }
5294
5295 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5301 public function is_first()
5302 {
5303 // phpcs:enable
5304 return ($this->situation_counter == 1);
5305 }
5306
5307 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5313 public function get_prev_sits()
5314 {
5315 // phpcs:enable
5316 global $conf;
5317
5318 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
5319 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5320 $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
5321 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5322 $resql = $this->db->query($sql);
5323 $res = array();
5324 if ($resql && $this->db->num_rows($resql) > 0) {
5325 while ($row = $this->db->fetch_object($resql)) {
5326 $id = $row->rowid;
5327 $situation = new Facture($this->db);
5328 $situation->fetch($id);
5329 $res[] = $situation;
5330 }
5331 } else {
5332 $this->error = $this->db->error();
5333 dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
5334 return -1;
5335 }
5336
5337 return $res;
5338 }
5339
5347 public function setFinal(User $user, $notrigger = 0)
5348 {
5349 $error = 0;
5350
5351 $this->db->begin();
5352
5353 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
5354
5355 dol_syslog(__METHOD__, LOG_DEBUG);
5356 $resql = $this->db->query($sql);
5357 if (!$resql) {
5358 $this->errors[] = $this->db->error();
5359 $error++;
5360 }
5361
5362 if (!$notrigger && empty($error)) {
5363 // Call trigger
5364 $result = $this->call_trigger('BILL_MODIFY', $user);
5365 if ($result < 0) {
5366 $error++;
5367 }
5368 // End call triggers
5369 }
5370
5371 if (!$error) {
5372 $this->db->commit();
5373 return 1;
5374 } else {
5375 foreach ($this->errors as $errmsg) {
5376 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
5377 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
5378 }
5379 $this->db->rollback();
5380 return -1 * $error;
5381 }
5382 }
5383
5384 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5390 public function is_last_in_cycle()
5391 {
5392 // phpcs:enable
5393 global $conf;
5394
5395 if (!empty($this->situation_cycle_ref)) {
5396 // No point in testing anything if we're not inside a cycle
5397 $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
5398 $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5399 $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5400 $resql = $this->db->query($sql);
5401
5402 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5403 $last = $res['max(situation_counter)'];
5404 return ($last == $this->situation_counter);
5405 } else {
5406 $this->error = $this->db->lasterror();
5407 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
5408 return false;
5409 }
5410 } else {
5411 return true;
5412 }
5413 }
5414
5423 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
5424 {
5425 $tables = array(
5426 'facture'
5427 );
5428
5429 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
5430 }
5431
5440 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
5441 {
5442 $tables = array(
5443 'facturedet'
5444 );
5445
5446 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
5447 }
5448
5454 public function hasDelay()
5455 {
5456 global $conf;
5457
5458 $now = dol_now();
5459
5460 // Paid invoices have status STATUS_CLOSED
5461 if ($this->status != Facture::STATUS_VALIDATED) {
5462 return false;
5463 }
5464
5465 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5466 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5467 $totalpaid = $this->getSommePaiement();
5468 $totalpaid = (float) $totalpaid;
5469 $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
5470 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5471 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5472 $hasDelay = 1;
5473 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5474 $hasDelay = 1;
5475 } else {
5476 $hasDelay = 0;
5477 }
5478 }
5479 }
5480
5481 return $hasDelay;
5482 }
5483
5488 public function displayRetainedWarranty()
5489 {
5490 global $conf;
5491
5492 // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
5493
5494 // 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
5495
5496 $displayWarranty = false;
5497 if (!empty($this->retained_warranty)) {
5498 $displayWarranty = true;
5499
5500 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
5501 // Check if this situation invoice is 100% for real
5502 $displayWarranty = false;
5503 if (!empty($this->situation_final)) {
5504 $displayWarranty = true;
5505 } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
5506 // $object->situation_final need validation to be done so this test is need for draft
5507 $displayWarranty = true;
5508
5509 foreach ($this->lines as $i => $line) {
5510 if ($line->product_type < 2 && $line->situation_percent < 100) {
5511 $displayWarranty = false;
5512 break;
5513 }
5514 }
5515 }
5516 }
5517 }
5518
5519 return $displayWarranty;
5520 }
5521
5526 public function getRetainedWarrantyAmount($rounding = -1)
5527 {
5528 global $conf;
5529 if (empty($this->retained_warranty)) {
5530 return -1;
5531 }
5532
5533 $retainedWarrantyAmount = 0;
5534
5535 // Billed - retained warranty
5536 if ($this->type == Facture::TYPE_SITUATION && getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION')) {
5537 $displayWarranty = true;
5538 // Check if this situation invoice is 100% for real
5539 if (!empty($this->lines)) {
5540 foreach ($this->lines as $i => $line) {
5541 if ($line->product_type < 2 && $line->situation_percent < 100) {
5542 $displayWarranty = false;
5543 break;
5544 }
5545 }
5546 }
5547
5548 if ($displayWarranty && !empty($this->situation_final)) {
5550 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5551
5552 $total2BillWT = 0;
5553 foreach ($TPreviousIncoice as &$fac) {
5554 $total2BillWT += $fac->total_ttc;
5555 }
5556 $total2BillWT += $this->total_ttc;
5557
5558 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5559 } else {
5560 return -1;
5561 }
5562 } else {
5563 // Because one day retained warranty could be used on standard invoices
5564 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5565 }
5566
5567 if ($rounding < 0) {
5568 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
5569 }
5570
5571 if ($rounding > 0) {
5572 return round($retainedWarrantyAmount, $rounding);
5573 }
5574
5575 return $retainedWarrantyAmount;
5576 }
5577
5584 public function setRetainedWarranty($value)
5585 {
5586 dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
5587
5588 if ($this->status >= 0) {
5589 $fieldname = 'retained_warranty';
5590 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5591 $sql .= " SET ".$fieldname." = ".((float) $value);
5592 $sql .= ' WHERE rowid='.((int) $this->id);
5593
5594 if ($this->db->query($sql)) {
5595 $this->retained_warranty = (float) $value;
5596 return 1;
5597 } else {
5598 dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
5599 $this->error = $this->db->error();
5600 return -1;
5601 }
5602 } else {
5603 dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
5604 $this->error = 'Status of the object is incompatible '.$this->status;
5605 return -2;
5606 }
5607 }
5608
5609
5617 public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '')
5618 {
5619 if (!$timestamp && $dateYmd) {
5620 $timestamp = $this->db->jdate($dateYmd);
5621 }
5622
5623
5624 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
5625 if ($this->status >= 0) {
5626 $fieldname = 'retained_warranty_date_limit';
5627 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5628 $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
5629 $sql .= ' WHERE rowid = '.((int) $this->id);
5630
5631 if ($this->db->query($sql)) {
5632 $this->retained_warranty_date_limit = $timestamp;
5633 return 1;
5634 } else {
5635 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
5636 $this->error = $this->db->error();
5637 return -1;
5638 }
5639 } else {
5640 dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5641 $this->error = 'Status of the object is incompatible '.$this->status;
5642 return -2;
5643 }
5644 }
5645
5646
5658 public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
5659 {
5660 global $conf, $langs, $user;
5661
5662 $error = 0;
5663 $this->output = '';
5664 $this->error = '';
5665 $nbMailSend = 0;
5666 $errorsMsg = array();
5667
5668 $langs->load("bills");
5669
5670 if (!isModEnabled('invoice')) { // Should not happen. If module disabled, cron job should not be visible.
5671 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5672 return 0;
5673 }
5674 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
5675 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5676 return 0;
5677 }
5678 /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
5679 $langs->load("bills");
5680 $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
5681 return 0;
5682 }
5683 */
5684
5685 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5686 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
5687 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
5688 $formmail = new FormMail($this->db);
5689
5690 $now = dol_now();
5691 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
5692
5693 $tmpinvoice = new Facture($this->db);
5694
5695 dol_syslog(__METHOD__." start", LOG_INFO);
5696
5697 // Select all action comm reminder
5698 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
5699 if (!empty($paymentmode) && $paymentmode != 'all') {
5700 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
5701 }
5702 $sql .= " WHERE f.paye = 0"; // Only unpaid
5703 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
5704 if ($datetouse == 'invoicedate') {
5705 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
5706 } else {
5707 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
5708 }
5709 $sql .= " AND f.entity IN (".getEntity('facture', 0).")"; // One batch process only one company (no sharing)
5710 if (!empty($paymentmode) && $paymentmode != 'all') {
5711 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
5712 }
5713 // TODO Add a filter to check there is no payment started yet
5714 if ($datetouse == 'invoicedate') {
5715 $sql .= $this->db->order("datef", "ASC");
5716 } else {
5717 $sql .= $this->db->order("date_lim_reglement", "ASC");
5718 }
5719
5720 $resql = $this->db->query($sql);
5721
5722 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
5723 if ($datetouse == 'invoicedate') {
5724 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedInvoicesWithDate", $stmpidate);
5725 } else {
5726 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
5727 }
5728 if (!empty($paymentmode) && $paymentmode != 'all') {
5729 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
5730 }
5731 $this->output .= '<br>';
5732
5733 if ($resql) {
5734 while ($obj = $this->db->fetch_object($resql)) {
5735 if (!$error) {
5736 // Load event
5737 $res = $tmpinvoice->fetch($obj->id);
5738 if ($res > 0) {
5739 $tmpinvoice->fetch_thirdparty();
5740
5741 $outputlangs = new Translate('', $conf);
5742 if ($tmpinvoice->thirdparty->default_lang) {
5743 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5744 $outputlangs->loadLangs(array("main", "bills"));
5745 } else {
5746 $outputlangs = $langs;
5747 }
5748
5749 // Select email template according to language of recipient
5750 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
5751 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5752 $langs->load("errors");
5753 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
5754 return 0;
5755 }
5756
5757 // PREPARE EMAIL
5758 $errormesg = '';
5759
5760 // Make substitution in email content
5761 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, '', $tmpinvoice);
5762
5763 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
5764
5765 // Topic
5766 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5767
5768 // Content
5769 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5770
5771 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
5772
5773 // Recipient
5774 $to = array();
5775 if ($forcerecipient) { // If a recipient was forced
5776 $to = array($forcerecipient);
5777 } else {
5778 $res = $tmpinvoice->fetch_thirdparty();
5779 $recipient = $tmpinvoice->thirdparty;
5780 if ($res > 0) {
5781 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'external', 0, 'BILLING');
5782 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5783 foreach ($tmparraycontact as $data_email) {
5784 if (!empty($data_email['email'])) {
5785 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email['id'], 'email');
5786 }
5787 }
5788 }
5789 if (empty($to) && !empty($recipient->email)) {
5790 $to[] = $recipient->email;
5791 }
5792 if (empty($to)) {
5793 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for invoice or customer.";
5794 $error++;
5795 }
5796 } else {
5797 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5798 $error++;
5799 }
5800 }
5801
5802 // Sender
5803 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
5804 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
5805 $from = $arraymessage->email_from;
5806 }
5807 if (empty($from)) {
5808 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5809 $error++;
5810 }
5811
5812 if (!$error && !empty($to)) {
5813 $this->db->begin();
5814
5815 $to = implode(',', $to);
5816 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
5817 $to = $to.','.$arraymessage->email_to;
5818 }
5819
5820 // Errors Recipient
5821 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
5822
5823 $trackid = 'inv'.$tmpinvoice->id;
5824 $sendcontext = 'standard';
5825
5826 $email_tocc = '';
5827 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
5828 $email_tocc = $arraymessage->email_tocc;
5829 }
5830
5831 $email_tobcc = '';
5832 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
5833 $email_tobcc = $arraymessage->email_tobcc;
5834 }
5835
5836 //join file is asked
5837 $joinFile = [];
5838 $joinFileName = [];
5839 $joinFileMime = [];
5840 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5841 $joinFile[] = DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc;
5842 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5843 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$tmpinvoice->last_main_doc);
5844 }
5845
5846 // Mail Creation
5847 $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
5848
5849 // Sending Mail
5850 if ($cMailFile->sendfile()) {
5851 $nbMailSend++;
5852
5853 // Add a line into event table
5854 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5855
5856 // Insert record of emails sent
5857 $actioncomm = new ActionComm($this->db);
5858
5859 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5860 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5861 $actioncomm->contact_id = 0;
5862
5863 $actioncomm->code = 'AC_EMAIL';
5864 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
5865 $actioncomm->note_private = $sendContent;
5866 $actioncomm->fk_project = $tmpinvoice->fk_project;
5867 $actioncomm->datep = dol_now();
5868 $actioncomm->datef = $actioncomm->datep;
5869 $actioncomm->percentage = -1; // Not applicable
5870 $actioncomm->authorid = $user->id; // User saving action
5871 $actioncomm->userownerid = $user->id; // Owner of action
5872 // Fields when action is an email (content should be added into note)
5873 $actioncomm->email_msgid = $cMailFile->msgid;
5874 $actioncomm->email_subject = $sendTopic;
5875 $actioncomm->email_from = $from;
5876 $actioncomm->email_sender = '';
5877 $actioncomm->email_to = $to;
5878 //$actioncomm->email_tocc = $sendtocc;
5879 //$actioncomm->email_tobcc = $sendtobcc;
5880 //$actioncomm->email_subject = $subject;
5881 $actioncomm->errors_to = $errors_to;
5882
5883 $actioncomm->elementtype = 'invoice';
5884 $actioncomm->fk_element = $tmpinvoice->id;
5885
5886 //$actioncomm->extraparams = $extraparams;
5887
5888 $actioncomm->create($user);
5889 } else {
5890 $errormesg = $cMailFile->error.' : '.$to;
5891 $error++;
5892
5893 // Add a line into event table
5894 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
5895
5896 // Insert record of emails sent
5897 $actioncomm = new ActionComm($this->db);
5898
5899 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
5900 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
5901 $actioncomm->contact_id = 0;
5902
5903 $actioncomm->code = 'AC_EMAIL';
5904 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
5905 $actioncomm->note_private = $errormesg;
5906 $actioncomm->fk_project = $tmpinvoice->fk_project;
5907 $actioncomm->datep = dol_now();
5908 $actioncomm->datef = $actioncomm->datep;
5909 $actioncomm->percentage = -1; // Not applicable
5910 $actioncomm->authorid = $user->id; // User saving action
5911 $actioncomm->userownerid = $user->id; // Owner of action
5912 // Fields when action is an email (content should be added into note)
5913 $actioncomm->email_msgid = $cMailFile->msgid;
5914 $actioncomm->email_from = $from;
5915 $actioncomm->email_sender = '';
5916 $actioncomm->email_to = $to;
5917 //$actioncomm->email_tocc = $sendtocc;
5918 //$actioncomm->email_tobcc = $sendtobcc;
5919 //$actioncomm->email_subject = $subject;
5920 $actioncomm->errors_to = $errors_to;
5921
5922 //$actioncomm->extraparams = $extraparams;
5923
5924 $actioncomm->create($user);
5925 }
5926
5927 $this->db->commit(); // We always commit
5928 }
5929
5930 if ($errormesg) {
5931 $errorsMsg[] = $errormesg;
5932 }
5933 } else {
5934 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
5935 $error++;
5936 }
5937 }
5938 }
5939 } else {
5940 $error++;
5941 }
5942
5943 if (!$error) {
5944 $this->output .= 'Nb of emails sent : '.$nbMailSend;
5945
5946 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
5947
5948 return 0;
5949 } else {
5950 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg) ? implode(', ', $errorsMsg) : $error);
5951
5952 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
5953
5954 return $error;
5955 }
5956 }
5957
5964 public function willBeLastOfSameType($allow_validated_drafts = false)
5965 {
5966 // get date of last validated invoices of same type
5967 $sql = "SELECT datef";
5968 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
5969 $sql .= " WHERE type = " . (int) $this->type ;
5970 $sql .= " AND date_valid IS NOT NULL";
5971 $sql .= " AND entity IN (".getEntity('invoice').")";
5972 $sql .= " ORDER BY datef DESC LIMIT 1";
5973
5974 $result = $this->db->query($sql);
5975 if ($result) {
5976 // compare with current validation date
5977 if ($this->db->num_rows($result)) {
5978 $obj = $this->db->fetch_object($result);
5979 $last_date = $this->db->jdate($obj->datef);
5980 $invoice_date = $this->date;
5981
5982 $is_last_of_same_type = $invoice_date >= $last_date;
5983 if ($allow_validated_drafts) {
5984 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->ref, 'PROV') && $this->status == self::STATUS_DRAFT);
5985 }
5986
5987 return array($is_last_of_same_type, $last_date);
5988 } else {
5989 // element is first of type to be validated
5990 return array(true);
5991 }
5992 } else {
5993 dol_print_error($this->db);
5994 }
5995
5996 return array();
5997 }
5998
6006 public function getKanbanView($option = '', $arraydata = null)
6007 {
6008 global $langs;
6009
6010 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
6011
6012 $picto = $this->picto;
6013 if ($this->type == self::TYPE_REPLACEMENT) {
6014 $picto .= 'r'; // Replacement invoice
6015 }
6016 if ($this->type == self::TYPE_CREDIT_NOTE) {
6017 $picto .= 'a'; // Credit note
6018 }
6019 if ($this->type == self::TYPE_DEPOSIT) {
6020 $picto .= 'd'; // Deposit invoice
6021 }
6022
6023 $return = '<div class="box-flex-item box-flex-grow-zero">';
6024 $return .= '<div class="info-box info-box-sm">';
6025 $return .= '<span class="info-box-icon bg-infobox-action">';
6026 $return .= img_picto('', $picto);
6027 $return .= '</span>';
6028 $return .= '<div class="info-box-content">';
6029 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
6030 if ($selected >= 0) {
6031 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
6032 }
6033 if (!empty($arraydata['thirdparty'])) {
6034 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
6035 }
6036 if (property_exists($this, 'date')) {
6037 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
6038 }
6039 if (property_exists($this, 'total_ht')) {
6040 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
6041 $return .= ' '.$langs->trans("HT");
6042 $return .= '</span>';
6043 }
6044 if (method_exists($this, 'getLibStatut')) {
6045 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
6046 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
6047 }
6048 $return .= '</div>';
6049 $return .= '</div>';
6050 $return .= '</div>';
6051 return $return;
6052 }
6053}
6054
6060{
6064 public $element = 'facturedet';
6065
6069 public $table_element = 'facturedet';
6070
6074 public $oldline;
6075
6081
6083 public $desc;
6084 public $ref_ext; // External reference of the line
6085
6086 public $localtax1_type; // Local tax 1 type
6087 public $localtax2_type; // Local tax 2 type
6088 public $fk_remise_except; // Link to line into llx_remise_except
6089 public $rang = 0;
6090
6091 public $fk_fournprice;
6092 public $pa_ht;
6093 public $marge_tx;
6094 public $marque_tx;
6095
6099 public $tva_npr;
6100
6101 public $remise_percent;
6102
6106 public $batch;
6110 public $fk_warehouse;
6111
6112
6113 public $origin;
6114 public $origin_id;
6115
6119 public $fk_code_ventilation = 0;
6120
6121
6122 public $date_start;
6123 public $date_end;
6124
6125 public $skip_update_total; // Skip update price total for special lines
6126
6130 public $situation_percent;
6131
6135 public $fk_prev_id;
6136
6137
6143 public function __construct($db)
6144 {
6145 $this->db = $db;
6146 }
6147
6154 public function fetch($rowid)
6155 {
6156 $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,';
6157 $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
6158 $sql .= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
6159 $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
6160 $sql .= ' fd.fk_code_ventilation,';
6161 $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
6162 $sql .= ' fd.situation_percent, fd.fk_prev_id,';
6163 $sql .= ' fd.multicurrency_subprice,';
6164 $sql .= ' fd.multicurrency_total_ht,';
6165 $sql .= ' fd.multicurrency_total_tva,';
6166 $sql .= ' fd.multicurrency_total_ttc,';
6167 $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
6168 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
6169 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
6170 $sql .= ' WHERE fd.rowid = '.((int) $rowid);
6171
6172 $result = $this->db->query($sql);
6173 if ($result) {
6174 $objp = $this->db->fetch_object($result);
6175
6176 if (!$objp) {
6177 $this->error = 'InvoiceLine with id '. $rowid .' not found sql='.$sql;
6178 return 0;
6179 }
6180
6181 $this->rowid = $objp->rowid;
6182 $this->id = $objp->rowid;
6183 $this->fk_facture = $objp->fk_facture;
6184 $this->fk_parent_line = $objp->fk_parent_line;
6185 $this->label = $objp->custom_label;
6186 $this->desc = $objp->description;
6187 $this->qty = $objp->qty;
6188 $this->subprice = $objp->subprice;
6189 $this->ref_ext = $objp->ref_ext;
6190 $this->vat_src_code = $objp->vat_src_code;
6191 $this->tva_tx = $objp->tva_tx;
6192 $this->localtax1_tx = $objp->localtax1_tx;
6193 $this->localtax2_tx = $objp->localtax2_tx;
6194 $this->remise_percent = $objp->remise_percent;
6195 $this->fk_remise_except = $objp->fk_remise_except;
6196 $this->fk_product = $objp->fk_product;
6197 $this->product_type = $objp->product_type;
6198 $this->date_start = $this->db->jdate($objp->date_start);
6199 $this->date_end = $this->db->jdate($objp->date_end);
6200 $this->info_bits = $objp->info_bits;
6201 $this->tva_npr = (($objp->info_bits & 1) == 1) ? 1 : 0;
6202 $this->special_code = $objp->special_code;
6203 $this->total_ht = $objp->total_ht;
6204 $this->total_tva = $objp->total_tva;
6205 $this->total_localtax1 = $objp->total_localtax1;
6206 $this->total_localtax2 = $objp->total_localtax2;
6207 $this->total_ttc = $objp->total_ttc;
6208 $this->fk_code_ventilation = $objp->fk_code_ventilation;
6209 $this->rang = $objp->rang;
6210 $this->fk_fournprice = $objp->fk_fournprice;
6211 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
6212 $this->pa_ht = $marginInfos[0];
6213 $this->marge_tx = $marginInfos[1];
6214 $this->marque_tx = $marginInfos[2];
6215
6216 $this->ref = $objp->product_ref; // deprecated
6217
6218 $this->product_ref = $objp->product_ref;
6219 $this->product_label = $objp->product_label;
6220 $this->product_desc = $objp->product_desc;
6221
6222 $this->fk_unit = $objp->fk_unit;
6223 $this->fk_user_modif = $objp->fk_user_modif;
6224 $this->fk_user_author = $objp->fk_user_author;
6225
6226 $this->situation_percent = $objp->situation_percent;
6227 $this->fk_prev_id = $objp->fk_prev_id;
6228
6229 $this->multicurrency_subprice = $objp->multicurrency_subprice;
6230 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
6231 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
6232 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
6233
6234 $this->fetch_optionals();
6235
6236 $this->db->free($result);
6237
6238 return 1;
6239 } else {
6240 $this->error = $this->db->lasterror();
6241 return -1;
6242 }
6243 }
6244
6252 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
6253 {
6254 global $langs, $user;
6255
6256 $error = 0;
6257
6258 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
6259
6260 dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
6261
6262 // Clean parameters
6263 $this->desc = trim($this->desc);
6264 if (empty($this->tva_tx)) {
6265 $this->tva_tx = 0;
6266 }
6267 if (empty($this->localtax1_tx)) {
6268 $this->localtax1_tx = 0;
6269 }
6270 if (empty($this->localtax2_tx)) {
6271 $this->localtax2_tx = 0;
6272 }
6273 if (empty($this->localtax1_type)) {
6274 $this->localtax1_type = 0;
6275 }
6276 if (empty($this->localtax2_type)) {
6277 $this->localtax2_type = 0;
6278 }
6279 if (empty($this->total_localtax1)) {
6280 $this->total_localtax1 = 0;
6281 }
6282 if (empty($this->total_localtax2)) {
6283 $this->total_localtax2 = 0;
6284 }
6285 if (empty($this->rang)) {
6286 $this->rang = 0;
6287 }
6288 if (empty($this->remise_percent)) {
6289 $this->remise_percent = 0;
6290 }
6291 if (empty($this->info_bits)) {
6292 $this->info_bits = 0;
6293 }
6294 if (empty($this->subprice)) {
6295 $this->subprice = 0;
6296 }
6297 if (empty($this->ref_ext)) {
6298 $this->ref_ext = '';
6299 }
6300 if (empty($this->special_code)) {
6301 $this->special_code = 0;
6302 }
6303 if (empty($this->fk_parent_line)) {
6304 $this->fk_parent_line = 0;
6305 }
6306 if (empty($this->fk_prev_id)) {
6307 $this->fk_prev_id = 0;
6308 }
6309 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
6310 $this->situation_percent = 100;
6311 }
6312
6313 if (empty($this->pa_ht)) {
6314 $this->pa_ht = 0;
6315 }
6316 if (empty($this->multicurrency_subprice)) {
6317 $this->multicurrency_subprice = 0;
6318 }
6319 if (empty($this->multicurrency_total_ht)) {
6320 $this->multicurrency_total_ht = 0;
6321 }
6322 if (empty($this->multicurrency_total_tva)) {
6323 $this->multicurrency_total_tva = 0;
6324 }
6325 if (empty($this->multicurrency_total_ttc)) {
6326 $this->multicurrency_total_ttc = 0;
6327 }
6328
6329 // if buy price not defined, define buyprice as configured in margin admin
6330 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6331 $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6332 if ($result < 0) {
6333 return $result;
6334 } else {
6335 $this->pa_ht = $result;
6336 }
6337 }
6338
6339 // Check parameters
6340 if ($this->product_type < 0) {
6341 $this->error = 'ErrorProductTypeMustBe0orMore';
6342 return -1;
6343 }
6344 if (!empty($this->fk_product) && $this->fk_product > 0) {
6345 // Check product exists
6346 $result = Product::isExistingObject('product', $this->fk_product);
6347 if ($result <= 0) {
6348 $this->error = 'ErrorProductIdDoesNotExists';
6349 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6350 return -1;
6351 }
6352 }
6353
6354 $this->db->begin();
6355
6356 // Update line in database
6357 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
6358 $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
6359 $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6360 $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6361 $sql .= ' date_start, date_end, fk_code_ventilation,';
6362 $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6363 $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6364 $sql .= ' situation_percent, fk_prev_id,';
6365 $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
6366 $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc,';
6367 $sql .= ' batch, fk_warehouse';
6368 $sql .= ')';
6369 $sql .= " VALUES (".$this->fk_facture.",";
6370 $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
6371 $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
6372 $sql .= " '".$this->db->escape($this->desc)."',";
6373 $sql .= " ".price2num($this->qty).",";
6374 $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
6375 $sql .= " ".price2num($this->tva_tx).",";
6376 $sql .= " ".price2num($this->localtax1_tx).",";
6377 $sql .= " ".price2num($this->localtax2_tx).",";
6378 $sql .= " '".$this->db->escape($this->localtax1_type)."',";
6379 $sql .= " '".$this->db->escape($this->localtax2_type)."',";
6380 $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
6381 $sql .= " ".((int) $this->product_type).",";
6382 $sql .= " ".price2num($this->remise_percent).",";
6383 $sql .= " ".price2num($this->subprice).",";
6384 $sql .= " '".$this->db->escape($this->ref_ext)."',";
6385 $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
6386 $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
6387 $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
6388 $sql .= ' '.((int) $this->fk_code_ventilation).',';
6389 $sql .= ' '.((int) $this->rang).',';
6390 $sql .= ' '.((int) $this->special_code).',';
6391 $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
6392 $sql .= ' '.price2num($this->pa_ht).',';
6393 $sql .= " '".$this->db->escape($this->info_bits)."',";
6394 $sql .= " ".price2num($this->total_ht).",";
6395 $sql .= " ".price2num($this->total_tva).",";
6396 $sql .= " ".price2num($this->total_ttc).",";
6397 $sql .= " ".price2num($this->total_localtax1).",";
6398 $sql .= " ".price2num($this->total_localtax2);
6399 $sql .= ", ".((float) $this->situation_percent);
6400 $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
6401 $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6402 $sql .= ", ".((int) $user->id);
6403 $sql .= ", ".((int) $user->id);
6404 $sql .= ", ".(int) $this->fk_multicurrency;
6405 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
6406 $sql .= ", ".price2num($this->multicurrency_subprice);
6407 $sql .= ", ".price2num($this->multicurrency_total_ht);
6408 $sql .= ", ".price2num($this->multicurrency_total_tva);
6409 $sql .= ", ".price2num($this->multicurrency_total_ttc);
6410 $sql .= ", '".$this->db->escape($this->batch)."'";
6411 $sql .= ", ".((int) $this->fk_warehouse);
6412 $sql .= ')';
6413
6414 dol_syslog(get_class($this)."::insert", LOG_DEBUG);
6415 $resql = $this->db->query($sql);
6416 if ($resql) {
6417 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
6418 $this->rowid = $this->id; // For backward compatibility
6419
6420 if (!$error) {
6421 $result = $this->insertExtraFields();
6422 if ($result < 0) {
6423 $error++;
6424 }
6425 }
6426
6427 // If fk_remise_except is defined, the discount is linked to the invoice
6428 // which flags it as "consumed".
6429 if ($this->fk_remise_except) {
6430 $discount = new DiscountAbsolute($this->db);
6431 $result = $discount->fetch($this->fk_remise_except);
6432 if ($result >= 0) {
6433 // Check if discount was found
6434 if ($result > 0) {
6435 // Check if discount not already affected to another invoice
6436 if ($discount->fk_facture_line > 0) {
6437 if (empty($noerrorifdiscountalreadylinked)) {
6438 $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
6439 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6440 $this->db->rollback();
6441 return -3;
6442 }
6443 } else {
6444 $result = $discount->link_to_invoice($this->rowid, 0);
6445 if ($result < 0) {
6446 $this->error = $discount->error;
6447 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6448 $this->db->rollback();
6449 return -3;
6450 }
6451 }
6452 } else {
6453 $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
6454 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6455 $this->db->rollback();
6456 return -3;
6457 }
6458 } else {
6459 $this->error = $discount->error;
6460 dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
6461 $this->db->rollback();
6462 return -3;
6463 }
6464 }
6465
6466 if (!$notrigger) {
6467 // Call trigger
6468 $result = $this->call_trigger('LINEBILL_INSERT', $user);
6469 if ($result < 0) {
6470 $this->db->rollback();
6471 return -2;
6472 }
6473 // End call triggers
6474 }
6475
6476 $this->db->commit();
6477 return $this->id;
6478 } else {
6479 $this->error = $this->db->lasterror();
6480 $this->db->rollback();
6481 return -2;
6482 }
6483 }
6484
6492 public function update($user = null, $notrigger = 0)
6493 {
6494 global $user, $conf;
6495
6496 $error = 0;
6497
6498 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
6499
6500 // Clean parameters
6501 $this->desc = trim($this->desc);
6502 if (empty($this->ref_ext)) {
6503 $this->ref_ext = '';
6504 }
6505 if (empty($this->tva_tx)) {
6506 $this->tva_tx = 0;
6507 }
6508 if (empty($this->localtax1_tx)) {
6509 $this->localtax1_tx = 0;
6510 }
6511 if (empty($this->localtax2_tx)) {
6512 $this->localtax2_tx = 0;
6513 }
6514 if (empty($this->localtax1_type)) {
6515 $this->localtax1_type = 0;
6516 }
6517 if (empty($this->localtax2_type)) {
6518 $this->localtax2_type = 0;
6519 }
6520 if (empty($this->total_localtax1)) {
6521 $this->total_localtax1 = 0;
6522 }
6523 if (empty($this->total_localtax2)) {
6524 $this->total_localtax2 = 0;
6525 }
6526 if (empty($this->remise_percent)) {
6527 $this->remise_percent = 0;
6528 }
6529 if (empty($this->info_bits)) {
6530 $this->info_bits = 0;
6531 }
6532 if (empty($this->special_code)) {
6533 $this->special_code = 0;
6534 }
6535 if (empty($this->product_type)) {
6536 $this->product_type = 0;
6537 }
6538 if (empty($this->fk_parent_line)) {
6539 $this->fk_parent_line = 0;
6540 }
6541 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
6542 $this->situation_percent = 100;
6543 }
6544 if (empty($this->pa_ht)) {
6545 $this->pa_ht = 0;
6546 }
6547
6548 if (empty($this->multicurrency_subprice)) {
6549 $this->multicurrency_subprice = 0;
6550 }
6551 if (empty($this->multicurrency_total_ht)) {
6552 $this->multicurrency_total_ht = 0;
6553 }
6554 if (empty($this->multicurrency_total_tva)) {
6555 $this->multicurrency_total_tva = 0;
6556 }
6557 if (empty($this->multicurrency_total_ttc)) {
6558 $this->multicurrency_total_ttc = 0;
6559 }
6560
6561 // Check parameters
6562 if ($this->product_type < 0) {
6563 return -1;
6564 }
6565
6566 // if buy price not provided, define buyprice as configured in margin admin
6567 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6568 // We call defineBuyPrice only if data was not provided (if input was '0', we will not go here and value will remaine '0')
6569 $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6570 if ($result < 0) {
6571 return $result;
6572 } else {
6573 $this->pa_ht = $result;
6574 }
6575 }
6576
6577 $this->db->begin();
6578
6579 // Update line in database
6580 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6581 $sql .= " description='".$this->db->escape($this->desc)."'";
6582 $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
6583 $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
6584 $sql .= ", subprice=".price2num($this->subprice);
6585 $sql .= ", remise_percent=".price2num($this->remise_percent);
6586 if ($this->fk_remise_except) {
6587 $sql .= ", fk_remise_except=".$this->fk_remise_except;
6588 } else {
6589 $sql .= ", fk_remise_except=null";
6590 }
6591 $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
6592 $sql .= ", tva_tx=".price2num($this->tva_tx);
6593 $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
6594 $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
6595 $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
6596 $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
6597 $sql .= ", qty=".price2num($this->qty);
6598 $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
6599 $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
6600 $sql .= ", product_type=".$this->product_type;
6601 $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
6602 $sql .= ", special_code=" . (int) $this->special_code;
6603 if (empty($this->skip_update_total)) {
6604 $sql .= ", total_ht=".price2num($this->total_ht);
6605 $sql .= ", total_tva=".price2num($this->total_tva);
6606 $sql .= ", total_ttc=".price2num($this->total_ttc);
6607 $sql .= ", total_localtax1=".price2num($this->total_localtax1);
6608 $sql .= ", total_localtax2=".price2num($this->total_localtax2);
6609 }
6610 $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
6611 $sql .= ", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht === '0') ? price2num($this->pa_ht) : "null"); // $this->pa_ht should always be defined (set to 0 or to sell price depending on option)
6612 $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
6613 if (!empty($this->rang)) {
6614 $sql .= ", rang=".((int) $this->rang);
6615 }
6616 $sql .= ", situation_percent = ".((float) $this->situation_percent);
6617 $sql .= ", fk_unit = ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
6618 $sql .= ", fk_user_modif = ".((int) $user->id);
6619
6620 // Multicurrency
6621 $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6622 $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6623 $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6624 $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6625
6626 $sql .= ", batch = '".$this->db->escape($this->batch)."'";
6627 $sql .= ", fk_warehouse = ".((int) $this->fk_warehouse);
6628
6629 $sql .= " WHERE rowid = ".((int) $this->rowid);
6630
6631 dol_syslog(get_class($this)."::update", LOG_DEBUG);
6632 $resql = $this->db->query($sql);
6633 if ($resql) {
6634 if (!$error) {
6635 $this->id = $this->rowid;
6636 $result = $this->insertExtraFields();
6637 if ($result < 0) {
6638 $error++;
6639 }
6640 }
6641
6642 if (!$error && !$notrigger) {
6643 // Call trigger
6644 $result = $this->call_trigger('LINEBILL_MODIFY', $user);
6645 if ($result < 0) {
6646 $this->db->rollback();
6647 return -2;
6648 }
6649 // End call triggers
6650 }
6651 $this->db->commit();
6652 return 1;
6653 } else {
6654 $this->error = $this->db->error();
6655 $this->db->rollback();
6656 return -2;
6657 }
6658 }
6659
6667 public function delete($tmpuser = null, $notrigger = 0)
6668 {
6669 global $user;
6670
6671 $this->db->begin();
6672
6673 // Call trigger
6674 if (empty($notrigger)) {
6675 $result = $this->call_trigger('LINEBILL_DELETE', $user);
6676 if ($result < 0) {
6677 $this->db->rollback();
6678 return -1;
6679 }
6680 }
6681 // End call triggers
6682
6683 // extrafields
6684 $result = $this->deleteExtraFields();
6685 if ($result < 0) {
6686 $this->db->rollback();
6687 return -1;
6688 }
6689
6690 // Free discount linked to invoice line
6691 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
6692 $sql .= ' SET fk_facture_line = NULL';
6693 $sql .= ' WHERE fk_facture_line = '.((int) $this->id);
6694
6695 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
6696 $result = $this->db->query($sql);
6697 if (!$result) {
6698 $this->error = $this->db->error();
6699 $this->errors[] = $this->error;
6700 $this->db->rollback();
6701 return -1;
6702 }
6703
6704 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time';
6705 $sql .= ' SET invoice_id = NULL, invoice_line_id = NULL';
6706 $sql .= ' WHERE invoice_line_id = '.((int) $this->id);
6707 if (!$this->db->query($sql)) {
6708 $this->error = $this->db->error()." sql=".$sql;
6709 $this->errors[] = $this->error;
6710 $this->db->rollback();
6711 return -1;
6712 }
6713
6714 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->id);
6715
6716 if ($this->db->query($sql)) {
6717 $this->db->commit();
6718 return 1;
6719 } else {
6720 $this->error = $this->db->error()." sql=".$sql;
6721 $this->errors[] = $this->error;
6722 $this->db->rollback();
6723 return -1;
6724 }
6725 }
6726
6727 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6734 public function update_total()
6735 {
6736 // phpcs:enable
6737 $this->db->begin();
6738 dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6739
6740 // Clean parameters
6741 if (empty($this->total_localtax1)) {
6742 $this->total_localtax1 = 0;
6743 }
6744 if (empty($this->total_localtax2)) {
6745 $this->total_localtax2 = 0;
6746 }
6747
6748 // Update line in database
6749 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
6750 $sql .= " total_ht=".price2num($this->total_ht);
6751 $sql .= ",total_tva=".price2num($this->total_tva);
6752 $sql .= ",total_localtax1=".price2num($this->total_localtax1);
6753 $sql .= ",total_localtax2=".price2num($this->total_localtax2);
6754 $sql .= ",total_ttc=".price2num($this->total_ttc);
6755 $sql .= " WHERE rowid = ".((int) $this->rowid);
6756
6757 dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
6758
6759 $resql = $this->db->query($sql);
6760 if ($resql) {
6761 $this->db->commit();
6762 return 1;
6763 } else {
6764 $this->error = $this->db->error();
6765 $this->db->rollback();
6766 return -2;
6767 }
6768 }
6769
6770 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6780 public function get_prev_progress($invoiceid, $include_credit_note = true)
6781 {
6782 // phpcs:enable
6783 global $invoicecache;
6784
6785 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
6786 return 0;
6787 } else {
6788 // If invoice is not a situation invoice, this->fk_prev_id is used for something else
6789 if (!isset($invoicecache[$invoiceid])) {
6790 $invoicecache[$invoiceid] = new Facture($this->db);
6791 $invoicecache[$invoiceid]->fetch($invoiceid);
6792 }
6793 if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
6794 return 0;
6795 }
6796
6797 $sql = "SELECT situation_percent FROM ".MAIN_DB_PREFIX."facturedet";
6798 $sql .= " WHERE rowid = ".((int) $this->fk_prev_id);
6799
6800 $resql = $this->db->query($sql);
6801
6802 if ($resql && $this->db->num_rows($resql) > 0) {
6803 $returnPercent = 0;
6804
6805 $obj = $this->db->fetch_object($resql);
6806 if ($obj) {
6807 $returnPercent = (float) $obj->situation_percent;
6808 }
6809
6810 if ($include_credit_note) {
6811 $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
6812 $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
6813 $sql .= " WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6814 $sql .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
6815 $sql .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6816
6817 $res = $this->db->query($sql);
6818 if ($res) {
6819 while ($obj = $this->db->fetch_object($res)) {
6820 $returnPercent = $returnPercent + (float) $obj->situation_percent;
6821 }
6822 } else {
6823 dol_print_error($this->db);
6824 }
6825 }
6826
6827 return $returnPercent;
6828 } else {
6829 $this->error = $this->db->error();
6830 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6831 $this->db->rollback();
6832 return -1;
6833 }
6834 }
6835 }
6836
6837 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6847 public function get_allprev_progress($invoiceid, $include_credit_note = true)
6848 {
6849 // phpcs:enable
6850 global $invoicecache;
6851
6852 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
6853 return 0;
6854 } else {
6855 // If invoice is not a situation invoice, this->fk_prev_id is used for something else
6856 if (!isset($invoicecache[$invoiceid])) {
6857 $invoicecache[$invoiceid] = new Facture($this->db);
6858 $invoicecache[$invoiceid]->fetch($invoiceid);
6859 }
6860 if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
6861 return 0;
6862 }
6863
6864 $all_found = false;
6865 $lastprevid = $this->fk_prev_id;
6866 $cumulated_percent = 0.0;
6867
6868 while (!$all_found) {
6869 $sql = "SELECT situation_percent, fk_prev_id FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $lastprevid);
6870 $resql = $this->db->query($sql);
6871
6872 if ($resql && $this->db->num_rows($resql) > 0) {
6873 $obj = $this->db->fetch_object($resql);
6874 $cumulated_percent += floatval($obj->situation_percent);
6875
6876 if ($include_credit_note) {
6877 $sql_credit_note = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
6878 $sql_credit_note .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
6879 $sql_credit_note .= " WHERE fd.fk_prev_id = ".((int) $lastprevid);
6880 $sql_credit_note .= " AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
6881 $sql_credit_note .= " AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6882
6883 $res_credit_note = $this->db->query($sql_credit_note);
6884 if ($res_credit_note) {
6885 while ($cn = $this->db->fetch_object($res_credit_note)) {
6886 $cumulated_percent = $cumulated_percent + floatval($cn->situation_percent);
6887 }
6888 } else {
6889 dol_print_error($this->db);
6890 }
6891 }
6892
6893 // Si fk_prev_id, on continue
6894 if ($obj->fk_prev_id) {
6895 $lastprevid = $obj->fk_prev_id;
6896 } else { // Sinon on stoppe la boucle
6897 $all_found = true;
6898 }
6899 } else {
6900 $this->error = $this->db->error();
6901 dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
6902 $this->db->rollback();
6903 return -1;
6904 }
6905 }
6906 return $cumulated_percent;
6907 }
6908 }
6909}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:637
$object ref
Definition info.php:79
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoices classes.
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 for details of elements (invoices, contracts,...
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
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
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
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 shipments.
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)
$fk_facture_source
id of source invoice if replacement invoice or credit note
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.
$fk_fac_rec_source
id of template invoice when generated from a template invoice
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 clicable 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.
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
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.
$pos_source
key of pos source ('0', '1', ...)
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 clicable 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.
$module_source
key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos',...
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 an order and create a new invoice into database.
Class to manage invoice lines.
$desc
Description ligne.
$fk_parent_line
Id parent line.
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
fetch($rowid)
Load invoice line from database.
update($user=null, $notrigger=0)
Update line into database.
$fk_facture
From llx_facturedet Id facture.
__construct($db)
Constructor.
update_total()
Update DB line fields total_xxx Used by migration.
get_allprev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of all the previous line.
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.
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:655
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:641
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:595
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:533
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:614
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:88
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:137
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e e e e e statut
Definition invoice.php:2010
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e rowid
Definition invoice.php:2010