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