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