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