dolibarr 25.0.0-alpha
fournisseur.facture.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
5 * Copyright (C) 2005 Marc Barilley <marc@ocebo.com>
6 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
7 * Copyright (C) 2010-2023 Juanjo Menent <jmenent@simnandez.es>
8 * Copyright (C) 2013-2019 Philippe Grand <philippe.grand@atoo-net.com>
9 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10 * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2015 Bahfir Abbes <bafbes@gmail.com>
12 * Copyright (C) 2015-2022 Ferran Marcet <fmarcet@2byte.es>
13 * Copyright (C) 2016-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
14 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
15 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
17 * Copyright (C) 2023 Nick Fragoulis
18 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
19 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
20 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
21 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
22 *
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 3 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <https://www.gnu.org/licenses/>.
35 */
36
43require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
44require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
45require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.ligne.class.php';
46require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
47require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
48
49if (isModEnabled('accounting')) {
50 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
51 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
52}
53
58{
59 use CommonSubtotal;
60
64 public $element = 'invoice_supplier';
65
69 public $table_element = 'facture_fourn';
70
74 public $table_element_line = 'facture_fourn_det';
75
79 public $class_element_line = 'SupplierInvoiceLine';
83 public $fk_element = 'fk_facture_fourn';
84
88 public $picto = 'supplier_invoice';
89
94 public $restrictiononfksoc = 1;
95
99 protected $table_ref_field = 'ref';
100
104 public $rowid;
105
109 public $ref;
110
114 public $ref_supplier;
115
120 public $libelle;
124 public $label;
125
126 //Check constants for types
127 public $type = self::TYPE_STANDARD;
128
135 public $statut;
136
142 public $status;
143
150 public $fk_statut;
151
157 public $paye;
162 public $paid;
163
168 public $author;
169
174 public $fk_user_valid;
175
181 public $datec;
182
188 public $date_echeance;
189
194 public $amount = 0;
199 public $remise = 0;
200
205 public $tva;
206
207 // Warning: Do not set default value into property definition. it must stay null.
208 // For example to avoid to have substitution done when object is generic and not yet defined.
210 public $localtax1;
212 public $localtax2;
214 public $total_ht;
216 public $total_tva;
218 public $total_localtax1;
220 public $total_localtax2;
222 public $total_ttc;
223
229 public $note;
231 public $note_private;
233 public $note_public;
235 public $propalid;
236
240 public $fk_account; // default bank account
241
245 public $transport_mode_id;
246
250 public $vat_reverse_charge;
251
255 public $extraparams = array();
256
260 public $lines = array();
261
266 public $fournisseur;
267
269
272 public $fk_facture_source;
273
275 public $fac_rec;
277 public $fk_fac_rec_source;
278
279 public $fields = array(
280 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
281 'ref' => array('type' => 'varchar(255)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 15),
282 'ref_supplier' => array('type' => 'varchar(255)', 'label' => 'RefSupplier', 'enabled' => 1, 'visible' => -1, 'position' => 20),
283 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 25, 'index' => 1),
284 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 30),
285 'type' => array('type' => 'smallint(6)', 'label' => 'Type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 35),
286 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 36),
287 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 40),
288 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 45),
289 'datef' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => -1, 'position' => 50),
290 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 55),
291 'libelle' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => -1, 'position' => 60),
292 'paye' => array('type' => 'smallint(6)', 'label' => 'Paye', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 65),
293 'amount' => array('type' => 'double(24,8)', 'label' => 'Amount', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 70),
294 'remise' => array('type' => 'double(24,8)', 'label' => 'Discount', 'enabled' => 1, 'visible' => -1, 'position' => 75),
295 'close_code' => array('type' => 'varchar(16)', 'label' => 'CloseCode', 'enabled' => 1, 'visible' => -1, 'position' => 80),
296 'close_note' => array('type' => 'varchar(128)', 'label' => 'CloseNote', 'enabled' => 1, 'visible' => -1, 'position' => 85),
297 'tva' => array('type' => 'double(24,8)', 'label' => 'Tva', 'enabled' => 1, 'visible' => -1, 'position' => 90),
298 'localtax1' => array('type' => 'double(24,8)', 'label' => 'Localtax1', 'enabled' => 1, 'visible' => -1, 'position' => 95),
299 'localtax2' => array('type' => 'double(24,8)', 'label' => 'Localtax2', 'enabled' => 1, 'visible' => -1, 'position' => 100),
300 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 105),
301 'total_tva' => array('type' => 'double(24,8)', 'label' => 'TotalVAT', 'enabled' => 1, 'visible' => -1, 'position' => 110),
302 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 115),
303 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 125),
304 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 130),
305 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 135),
306 'fk_facture_source' => array('type' => 'integer', 'label' => 'SourceInvoice', 'enabled' => 1, 'visible' => -1, 'position' => 140),
307 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 145),
308 'fk_account' => array('type' => 'integer', 'label' => 'Account', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 150),
309 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 155),
310 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 160),
311 'date_lim_reglement' => array('type' => 'date', 'label' => 'DateLimReglement', 'enabled' => 1, 'visible' => -1, 'position' => 165),
312 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 170),
313 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 175),
314 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPdf', 'enabled' => 1, 'visible' => 0, 'position' => 180),
315 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 190),
316 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 1, 'visible' => -1, 'position' => 195),
317 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLocation', 'enabled' => 1, 'visible' => -1, 'position' => 200),
318 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyId', 'enabled' => 1, 'visible' => -1, 'position' => 205),
319 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCode', 'enabled' => 1, 'visible' => -1, 'position' => 210),
320 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 1, 'visible' => -1, 'position' => 215),
321 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyTotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 220),
322 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyTotalVAT', 'enabled' => 1, 'visible' => -1, 'position' => 225),
323 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyTotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 230),
324 'date_pointoftax' => array('type' => 'date', 'label' => 'DatePointOfTax', 'enabled' => 'getDolGlobalString("INVOICE_POINTOFTAX_DATE")', 'visible' => -1, 'position' => 235),
325 'date_valid' => array('type' => 'date', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 240),
326 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'Last main doc', 'enabled' => 1, 'visible' => -1, 'position' => 245),
327 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500),
328 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
329 );
330
331
335 const TYPE_STANDARD = 0;
336
341
346
350 const TYPE_DEPOSIT = 3;
351
355 const STATUS_DRAFT = 0;
356
361
369 const STATUS_CLOSED = 2;
370
379
380 const CLOSECODE_DISCOUNTVAT = 'discount_vat';
381 const CLOSECODE_BADCREDIT = 'badsupplier';
382 const CLOSECODE_ABANDONED = 'abandon';
383 const CLOSECODE_REPLACED = 'replaced';
384
385
391 public function __construct($db)
392 {
393 $this->db = $db;
394
395 $this->ismultientitymanaged = 1;
396 }
397
404 public function create($user)
405 {
406 global $langs, $conf, $hookmanager;
407
408 $error = 0;
409 $now = dol_now();
410
411 // Clean parameters
412 if (isset($this->ref_supplier)) {
413 $this->ref_supplier = trim($this->ref_supplier);
414 }
415 if (empty($this->type)) {
416 $this->type = self::TYPE_STANDARD;
417 }
418 if (empty($this->date)) {
419 $this->date = $now;
420 }
421
422 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
423 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
424 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
425 } else {
426 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
427 }
428 if (empty($this->fk_multicurrency)) {
429 $this->multicurrency_code = $conf->currency;
430 $this->fk_multicurrency = 0;
431 $this->multicurrency_tx = 1;
432 }
433 $this->entity = setEntity($this);
434
435 $this->db->begin();
436
437 // Defaults
438 $originaldatewhen = 0;
439 $nextdatewhen = 0;
440 $previousdaynextdatewhen = 0;
441 $_facrec = null;
442
443 // Create invoice from a template recurring invoice
444 if ($this->fac_rec > 0) {
445 $this->fk_fac_rec_source = $this->fac_rec;
446
447 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture-rec.class.php';
448 $_facrec = new FactureFournisseurRec($this->db);
449 $result = $_facrec->fetch($this->fac_rec);
450 $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
451
452 // Define some dates
453 if (!empty($_facrec->frequency)) {
454 $originaldatewhen = $_facrec->date_when;
455 // date_when is read from database in the timezone of the server (jdate), so delays must be added in this timezone
456 $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency, 0, 'tzserver');
457 $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd', 0, 'tzserver');
458 $this->socid = $_facrec->socid;
459 }
460
461 $this->entity = $_facrec->entity; // Invoice created in same entity than template
462
463 // Fields coming from GUI
464 // @TODO Value of template should be used as default value on the form on the GUI, and we should here always use the value from GUI
465 // set by posted page with $object->xxx = ... and this section should be removed.
466 $this->fk_project = GETPOSTINT('projectid') > 0 ? (GETPOSTINT('projectid')) : $_facrec->fk_project;
467 $this->note_public = GETPOST('note_public', 'restricthtml') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
468 $this->note_private = GETPOST('note_private', 'restricthtml') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
469 $this->model_pdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
470 $this->cond_reglement_id = GETPOSTINT('cond_reglement_id') > 0 ? (GETPOSTINT('cond_reglement_id')) : $_facrec->cond_reglement_id;
471 $this->mode_reglement_id = GETPOSTINT('mode_reglement_id') > 0 ? (GETPOSTINT('mode_reglement_id')) : $_facrec->mode_reglement_id;
472 $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
473
474 // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
475 $this->total_ht = $_facrec->total_ht;
476 $this->total_ttc = $_facrec->total_ttc;
477
478 // Fields always coming from template
479 $this->fk_incoterms = $_facrec->fk_incoterms;
480 $this->location_incoterms = $_facrec->location_incoterms;
481
482 // Clean parameters
483 if (! $this->type) {
484 $this->type = self::TYPE_STANDARD;
485 }
486 $this->note_public = trim((string) $this->note_public);
487 $this->note_private = trim((string) $this->note_private);
488 $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->title));
489
490 $this->array_options = $_facrec->array_options;
491
492 if (! $this->mode_reglement_id) {
493 $this->mode_reglement_id = 0;
494 }
495 $this->status = self::STATUS_DRAFT;
496 $this->statut = self::STATUS_DRAFT; // deprecated
497
498 $this->linked_objects = $_facrec->linkedObjectsIds;
499 // We do not add link to template invoice or next invoice will be linked to all generated invoices
500 //$this->linked_objects['facturerec'][0] = $this->fac_rec;
501
502 $forceduedate = $this->calculate_date_lim_reglement();
503
504 // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
505 if ($_facrec->frequency > 0) {
506 $this->ref_supplier = trim($this->ref_supplier . '_' . ($_facrec->nb_gen_done + 1));
507 dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
508 if (empty($_facrec->date_when)) {
509 $_facrec->date_when = $now;
510 }
511 $next_date = $_facrec->getNextDate(); // Calculate next date
512 $result = $_facrec->setValueFrom('date_last_gen', $now, '', 0, 'date', '', $user, '');
513 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
514 $result = $_facrec->setNextDate($next_date, 1);
515 }
516
517 // Define lang of customer
518 $outputlangs = $langs;
519 $newlang = '';
520
521 if (getDolGlobalInt('MAIN_MULTILANGS') && isset($this->thirdparty->default_lang)) {
522 $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
523 }
524 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($this, 'default_lang') && isset($this->default_lang)) { // @phan-suppress-current-line PhanUndeclaredProperty
525 $newlang = $this->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
526 }
527 if (!empty($newlang)) {
528 $outputlangs = new Translate("", $conf);
529 $outputlangs->setDefaultLang($newlang);
530 } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
531 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
532 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm', 0, 'tzserver'), '%m');
533 $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
534 $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm', 0, 'tzserver'), '%m');
535 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm', 0, 'tzserver'), '%B');
536 $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
537 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm', 0, 'tzserver'), '%B');
538 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y', 0, 'tzserver'), '%Y');
539 $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
540 $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y', 0, 'tzserver'), '%Y'); // Only for template invoice
541 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $originaldatewhen ? dol_print_date($originaldatewhen, 'dayhour') : '';
542 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $nextdatewhen ? dol_print_date($nextdatewhen, 'dayhour') : '';
543 $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = $previousdaynextdatewhen ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '';
544 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
545 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
546
547 complete_substitutions_array($substitutionarray, $outputlangs);
548
549 $this->note_public = make_substitutions($this->note_public, $substitutionarray);
550 $this->note_private = make_substitutions($this->note_private, $substitutionarray);
551 }
552
553 // Define due date if not already defined
554 if (!empty($forceduedate)) {
555 $this->date_echeance = $forceduedate;
556 }
557
558 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
559 $sql .= "ref";
560 $sql .= ", ref_supplier";
561 $sql .= ", ref_ext";
562 $sql .= ", entity";
563 $sql .= ", type";
564 $sql .= ", subtype";
565 $sql .= ", libelle";
566 $sql .= ", fk_soc";
567 $sql .= ", datec";
568 $sql .= ", datef";
569 $sql .= ", date_pointoftax";
570 $sql .= ", vat_reverse_charge";
571 $sql .= ", fk_projet";
572 $sql .= ", fk_cond_reglement";
573 $sql .= ", fk_mode_reglement";
574 $sql .= ", fk_account";
575 $sql .= ", note_private";
576 $sql .= ", note_public";
577 $sql .= ", fk_user_author";
578 $sql .= ", date_lim_reglement";
579 $sql .= ", fk_incoterms, location_incoterms";
580 $sql .= ", fk_multicurrency";
581 $sql .= ", multicurrency_code";
582 $sql .= ", multicurrency_tx";
583 $sql .= ", fk_facture_source";
584 $sql .= ", fk_fac_rec_source";
585 $sql .= ")";
586 $sql .= " VALUES (";
587 $sql .= "'(PROV)'";
588 $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
589 $sql .= ", '".$this->db->escape((string) $this->ref_ext)."'";
590 $sql .= ", ".((int) $this->entity);
591 $sql .= ", '".$this->db->escape((string) $this->type)."'";
592 $sql .= ", ".(isset($this->subtype) ? (int) $this->subtype : "null");
593 $sql .= ", '".$this->db->escape(isset($this->label) ? $this->label : (isset($this->libelle) ? $this->libelle : ''))."'";
594 $sql .= ", ".((int) $this->socid);
595 $sql .= ", '".$this->db->idate($now)."'";
596 $sql .= ", '".$this->db->idate($this->date)."'";
597 $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
598 $sql .= ", ".($this->vat_reverse_charge != '' ? ((int) $this->vat_reverse_charge) : 0);
599 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
600 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
601 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
602 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
603 $sql .= ", '".$this->db->escape($this->note_private)."'";
604 $sql .= ", '".$this->db->escape($this->note_public)."'";
605 $sql .= ", ".((int) $user->id).",";
606 $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null";
607 $sql .= ", ".(int) $this->fk_incoterms;
608 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
609 $sql .= ", ".(int) $this->fk_multicurrency;
610 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
611 $sql .= ", ".(float) $this->multicurrency_tx;
612 $sql .= ", ".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null");
613 $sql .= ", ".(isset($this->fk_fac_rec_source) ? ((int) $this->fk_fac_rec_source) : "NULL");
614 $sql .= ")";
615
616 dol_syslog(get_class($this)."::create", LOG_DEBUG);
617 $resql = $this->db->query($sql);
618 if ($resql) {
619 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
620
621 // Update ref with new one
622 $this->ref = '(PROV'.$this->id.')';
623 $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
624
625 dol_syslog(get_class($this)."::create", LOG_DEBUG);
626 $resql = $this->db->query($sql);
627 if (!$resql) {
628 $error++;
629 }
630
631 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
632 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
633 }
634
635 // Add object linked
636 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
637 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
638 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, ...))
639 foreach ($tmp_origin_id as $origin_id) {
640 $ret = $this->add_object_linked($origin, $origin_id);
641 if (!$ret) {
642 dol_print_error($this->db);
643 $error++;
644 }
645 }
646 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
647 $origin_id = $tmp_origin_id;
648 $ret = $this->add_object_linked($origin, $origin_id);
649 if (!$ret) {
650 dol_print_error($this->db);
651 $error++;
652 }
653 }
654 }
655 }
656
657 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
658 dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
659 foreach ($this->lines as $i => $val) {
660 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code, fk_remise_except)';
661 $sql .= " VALUES (".((int) $this->id).", ".((int) $this->lines[$i]->special_code).", ".($this->lines[$i]->fk_remise_except > 0 ? ((int) $this->lines[$i]->fk_remise_except) : 'NULL').')';
662
663 $resql_insert = $this->db->query($sql);
664 if ($resql_insert) {
665 $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
666
667 // Preserve the original entry mode of the line so the total is computed from the typed value (no rounding drift).
668 $line_price_base_type = $this->lines[$i]->getPriceBaseType();
669 $line_pu = ($line_price_base_type === 'TTC') ? (float) $this->lines[$i]->subprice_ttc : $this->lines[$i]->subprice;
670 $res = $this->updateline(
671 $idligne,
672 $this->lines[$i]->desc ? $this->lines[$i]->desc : $this->lines[$i]->description,
673 $line_pu,
674 $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''),
675 $this->lines[$i]->localtax1_tx,
676 $this->lines[$i]->localtax2_tx,
677 $this->lines[$i]->qty,
678 $this->lines[$i]->fk_product,
679 $line_price_base_type,
680 (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''),
681 $this->lines[$i]->product_type,
682 $this->lines[$i]->remise_percent,
683 0,
684 $this->lines[$i]->date_start,
685 $this->lines[$i]->date_end,
686 $this->lines[$i]->array_options,
687 $this->lines[$i]->fk_unit,
688 $this->lines[$i]->multicurrency_subprice,
689 $this->lines[$i]->ref_supplier
690 );
691 } else {
692 $this->error = $this->db->lasterror();
693 $this->db->rollback();
694 return -5;
695 }
696 }
697 } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
698 dol_syslog("There is ".count($this->lines)." lines that are array lines");
699 foreach ($this->lines as $i => $val) {
700 $line = $this->lines[$i];
701
702 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
703 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
704 if (!is_object($line)) {
705 $line = (object) $line;
706 }
707
708 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code, fk_remise_except)';
709 $sql .= " VALUES (".((int) $this->id).", ".((int) $this->lines[$i]->special_code).", ".($this->lines[$i]->fk_remise_except > 0 ? ((int) $this->lines[$i]->fk_remise_except) : 'NULL').')';
710
711 $resql_insert = $this->db->query($sql);
712 if ($resql_insert) {
713 $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
714
715 $this->updateline(
716 $idligne,
717 $line->desc ? $line->desc : $line->description,
718 $line->subprice,
719 $line->tva_tx,
720 $line->localtax1_tx,
721 $line->localtax2_tx,
722 $line->qty,
723 $line->fk_product,
724 'HT',
725 (!empty($line->info_bits) ? $line->info_bits : ''),
726 $line->product_type,
727 $line->remise_percent,
728 0,
729 $line->date_start,
730 $line->date_end,
731 $line->array_options,
732 $line->fk_unit,
733 $line->multicurrency_subprice,
734 $line->ref_supplier
735 );
736 } else {
737 $this->error = $this->db->lasterror();
738 $this->db->rollback();
739 return -5;
740 }
741 }
742 }
743
744 /*
745 * Insert lines of template invoices
746 */
747 if (! $error && $this->fac_rec > 0 && $_facrec instanceof FactureFournisseurRec) {
748 foreach ($_facrec->lines as $i => $val) {
749 $product_type = $_facrec->lines[$i]->product_type;
750 if ($_facrec->lines[$i]->fk_product) {
751 $prod = new Product($this->db);
752 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
753 }
754
755 // For line from template invoice, we use data from template invoice
756 /*
757 $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
758 $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
759 if (empty($tva_tx)) $tva_npr=0;
760 $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
761 $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
762 */
763 $tva_tx = $_facrec->lines[$i]->tva_tx . ($_facrec->lines[$i]->vat_src_code ? '(' . $_facrec->lines[$i]->vat_src_code . ')' : '');
764 $tva_npr = $_facrec->lines[$i]->info_bits;
765 if (empty($tva_tx)) {
766 $tva_npr = 0;
767 }
768 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
769 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
770
771 // $fk_product_fournisseur_price not used and does not exist on line
772 // $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
773 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
774
775 // If buyprice not defined from template invoice, we try to guess the best value
776 if (! $buyprice && $_facrec->lines[$i]->fk_product > 0) {
777 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
778 $producttmp = new ProductFournisseur($this->db);
779 $producttmp->fetch($_facrec->lines[$i]->fk_product);
780
781 // If margin module defined on costprice, we try the costprice
782 // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
783 // else we get the best supplier price
784 if (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($producttmp->cost_price)) {
785 $buyprice = $producttmp->cost_price;
786 } elseif (isModEnabled('stock') && (getDolGlobalString('MARGIN_TYPE') == 'costprice' || getDolGlobalString('MARGIN_TYPE') == 'pmp') && !empty($producttmp->pmp)) {
787 $buyprice = $producttmp->pmp;
788 } else {
789 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
790 if ($producttmp->product_fourn_price_id > 0) {
791 $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
792 }
793 }
794 }
795 }
796
797 $result_insert = $this->addline(
798 $_facrec->lines[$i]->desc ? $_facrec->lines[$i]->desc : $_facrec->lines[$i]->description,
799 $_facrec->lines[$i]->pu_ht,
800 $tva_tx,
801 $localtax1_tx,
802 $localtax2_tx,
803 $_facrec->lines[$i]->qty,
804 $_facrec->lines[$i]->fk_product,
805 $_facrec->lines[$i]->remise_percent,
806 ($_facrec->lines[$i]->date_start == 1 && $this->date) ? $this->date : '',
807 ($_facrec->lines[$i]->date_end == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
808 0,
809 $_facrec->lines[$i]->info_bits,
810 'HT',
811 $product_type,
812 $_facrec->lines[$i]->rang,
813 0,
814 $_facrec->lines[$i]->array_options,
815 $_facrec->lines[$i]->fk_unit,
816 0,
817 0,
818 $_facrec->lines[$i]->ref_supplier,
819 $_facrec->lines[$i]->special_code,
820 0,
821 0
822 );
823 if ($result_insert < 0) {
824 $error++;
825 $this->error = $this->db->error();
826 break;
827 }
828 }
829 }
830
831
832 // Update total price
833 $result = $this->update_price(1);
834 if ($result > 0) {
835 // Actions on extra fields
836 if (!$error) {
837 $result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found
838 if ($result < 0) {
839 $error++;
840 }
841 }
842
843 if (!$error) {
844 // Call trigger
845 $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user);
846 if ($result < 0) {
847 $error++;
848 }
849 // End call triggers
850 }
851
852 if (!$error) {
853 $this->db->commit();
854 return $this->id;
855 } else {
856 $this->db->rollback();
857 return -4;
858 }
859 } else {
860 $this->error = $langs->trans('FailedToUpdatePrice');
861 $this->db->rollback();
862 return -3;
863 }
864 } else {
865 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
866 $this->error = $langs->trans('ErrorRefAlreadyExists');
867 $this->db->rollback();
868 return -1;
869 } else {
870 $this->error = $this->db->lasterror();
871 $this->db->rollback();
872 return -2;
873 }
874 }
875 }
876
885 public function fetch($id = 0, $ref = '', $ref_ext = '')
886 {
887 if (empty($id) && empty($ref) && empty($ref_ext)) {
888 return -1;
889 }
890
891 $sql = "SELECT";
892 $sql .= " t.rowid,";
893 $sql .= " t.ref,";
894 $sql .= " t.ref_supplier,";
895 $sql .= " t.ref_ext,";
896 $sql .= " t.entity,";
897 $sql .= " t.type,";
898 $sql .= " t.subtype,";
899 $sql .= " t.fk_soc,";
900 $sql .= " t.datec,";
901 $sql .= " t.datef,";
902 $sql .= " t.date_pointoftax,";
903 $sql .= " t.tms as datem,";
904 $sql .= " t.libelle as label,";
905 $sql .= " t.paye as paid,";
906 $sql .= " t.close_code,";
907 $sql .= " t.close_note,";
908 $sql .= " t.tva,";
909 $sql .= " t.localtax1,";
910 $sql .= " t.localtax2,";
911 $sql .= " t.total_ht,";
912 $sql .= " t.total_tva,";
913 $sql .= " t.total_ttc,";
914 $sql .= " t.fk_statut as status,";
915 $sql .= " t.fk_user_author,";
916 $sql .= " t.fk_user_valid,";
917 $sql .= " t.fk_facture_source,";
918 $sql .= " t.vat_reverse_charge,";
919 $sql .= " t.fk_fac_rec_source,";
920 $sql .= " t.fk_projet as fk_project,";
921 $sql .= " t.fk_cond_reglement,";
922 $sql .= " t.fk_account,";
923 $sql .= " t.fk_mode_reglement,";
924 $sql .= " t.date_lim_reglement,";
925 $sql .= " t.note_private,";
926 $sql .= " t.note_public,";
927 $sql .= " t.model_pdf,";
928 $sql .= " t.last_main_doc,";
929 $sql .= " t.import_key,";
930 $sql .= " t.extraparams,";
931 $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,";
932 $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_label,";
933 $sql .= ' s.nom as socnom, s.rowid as socid,';
934 $sql .= ' t.fk_incoterms, t.location_incoterms,';
935 $sql .= " i.libelle as label_incoterms,";
936 $sql .= ' t.fk_transport_mode,';
937 $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
938 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
939 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
940 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid";
941 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id";
942 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
943 if ($id) {
944 $sql .= " WHERE t.rowid = ".((int) $id);
945 } else {
946 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')'; // Don't use entity if you use rowid
947 if ($ref) {
948 $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
949 }
950 if ($ref_ext) {
951 $sql .= " AND t.ref_ext = '".$this->db->escape($ref_ext)."'";
952 }
953 }
954
955 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
956 $resql = $this->db->query($sql);
957 if ($resql) {
958 if ($this->db->num_rows($resql)) {
959 $obj = $this->db->fetch_object($resql);
960
961 $this->id = $obj->rowid;
962 $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility
963
964 $this->ref_supplier = $obj->ref_supplier;
965 $this->ref_ext = $obj->ref_ext;
966 $this->entity = $obj->entity;
967 $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type;
968 $this->subtype = $obj->subtype;
969 $this->socid = $obj->fk_soc;
970 $this->date = $this->db->jdate($obj->datef);
971 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
972 $this->date_creation = $this->db->jdate($obj->datec);
973 $this->datec = $this->db->jdate($obj->datec);
974 $this->date_modification = $this->db->jdate($obj->datem);
975 $this->tms = $this->db->jdate($obj->datem);
976 $this->libelle = $obj->label; // deprecated
977 $this->label = $obj->label;
978 $this->paye = $obj->paid;
979 $this->paid = $obj->paid;
980 $this->close_code = $obj->close_code;
981 $this->close_note = $obj->close_note;
982 $this->total_localtax1 = $obj->localtax1;
983 $this->total_localtax2 = $obj->localtax2;
984 $this->total_ht = $obj->total_ht;
985 $this->total_tva = $obj->total_tva;
986 $this->total_ttc = $obj->total_ttc;
987 $this->status = $obj->status;
988 $this->statut = $obj->status; // For backward compatibility
989 $this->fk_statut = $obj->status; // For backward compatibility
990 $this->user_creation_id = $obj->fk_user_author;
991 $this->author = $obj->fk_user_author; // deprecated
992 $this->user_validation_id = $obj->fk_user_valid;
993 $this->fk_user_valid = $obj->fk_user_valid;
994 $this->fk_facture_source = $obj->fk_facture_source;
995 $this->vat_reverse_charge = empty($obj->vat_reverse_charge) ? 0 : 1;
996 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
997 $this->fk_project = $obj->fk_project;
998 $this->cond_reglement_id = $obj->fk_cond_reglement;
999 $this->cond_reglement_code = $obj->cond_reglement_code;
1000 $this->cond_reglement_label = $obj->cond_reglement_label;
1001 $this->cond_reglement_doc = $obj->cond_reglement_doc;
1002 $this->fk_account = $obj->fk_account;
1003 $this->mode_reglement_id = $obj->fk_mode_reglement;
1004 $this->mode_reglement_code = $obj->mode_reglement_code;
1005 $this->mode_reglement = $obj->mode_reglement_label;
1006 $this->date_echeance = $this->db->jdate($obj->date_lim_reglement);
1007 $this->note = $obj->note_private; // deprecated
1008 $this->note_private = $obj->note_private;
1009 $this->note_public = $obj->note_public;
1010 $this->model_pdf = $obj->model_pdf;
1011 $this->last_main_doc = $obj->last_main_doc;
1012 $this->import_key = $obj->import_key;
1013
1014 //Incoterms
1015 $this->fk_incoterms = $obj->fk_incoterms;
1016 $this->location_incoterms = $obj->location_incoterms;
1017 $this->label_incoterms = $obj->label_incoterms;
1018 $this->transport_mode_id = $obj->fk_transport_mode;
1019
1020 // Multicurrency
1021 $this->fk_multicurrency = $obj->fk_multicurrency;
1022 $this->multicurrency_code = $obj->multicurrency_code;
1023 $this->multicurrency_tx = $obj->multicurrency_tx;
1024 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1025 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1026 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1027
1028 $this->extraparams = isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
1029
1030 $this->socid = $obj->socid;
1031
1032 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
1033
1034 // Retrieve all extrafield
1035 // fetch optionals attributes and labels
1036 $this->fetch_optionals();
1037
1038 $result = $this->fetch_lines();
1039 if ($result < 0) {
1040 $this->error = $this->db->lasterror();
1041 return -3;
1042 }
1043 } else {
1044 $this->error = 'Bill with id '.$id.' not found';
1045 dol_syslog(get_class($this).'::fetch '.$this->error);
1046 return 0;
1047 }
1048
1049 $this->db->free($resql);
1050 return 1;
1051 } else {
1052 $this->error = "Error ".$this->db->lasterror();
1053 return -1;
1054 }
1055 }
1056
1057
1058 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1064 public function fetch_lines()
1065 {
1066 // phpcs:enable
1067 $this->lines = array();
1068
1069 $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description as line_desc, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
1070 $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn, f.fk_remise_except';
1071 $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit, f.extraparams';
1072 $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.barcode as product_barcode, p.description as product_desc';
1073 $sql .= ', f.fk_code_ventilation, f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
1074 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
1075 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
1076 $sql .= ' WHERE fk_facture_fourn='.((int) $this->id);
1077 $sql .= ' ORDER BY f.rang, f.rowid';
1078
1079 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1080
1081 $resql_rows = $this->db->query($sql);
1082 if ($resql_rows) {
1083 $num_rows = $this->db->num_rows($resql_rows);
1084 if ($num_rows) {
1085 $i = 0;
1086 while ($i < $num_rows) {
1087 $obj = $this->db->fetch_object($resql_rows);
1088
1089 $line = new SupplierInvoiceLine($this->db);
1090
1091 $line->id = $obj->rowid;
1092 $line->rowid = $obj->rowid;
1093
1094 $line->description = $obj->line_desc;
1095 $line->desc = $obj->line_desc;
1096 $line->date_start = $this->db->jdate($obj->date_start);
1097 $line->date_end = $this->db->jdate($obj->date_end);
1098
1099 $line->product_ref = $obj->product_ref;
1100 $line->ref = $obj->product_ref;
1101 $line->ref_supplier = $obj->ref_supplier;
1102 $line->libelle = $obj->label;
1103 $line->label = $obj->label;
1104 $line->product_barcode = $obj->product_barcode;
1105 $line->product_desc = $obj->product_desc;
1106 $line->subprice = $obj->pu_ht;
1107 $line->pu_ht = $obj->pu_ht; // deprecated
1108 $line->subprice_ttc = $obj->pu_ttc;
1109 $line->pu_ttc = $obj->pu_ttc; // deprcated
1110 $line->vat_src_code = $obj->vat_src_code;
1111 $line->tva_tx = $obj->tva_tx;
1112 $line->localtax1_tx = $obj->localtax1_tx;
1113 $line->localtax2_tx = $obj->localtax2_tx;
1114 $line->localtax1_type = $obj->localtax1_type;
1115 $line->localtax2_type = $obj->localtax2_type;
1116 $line->qty = $obj->qty;
1117 $line->remise_percent = $obj->remise_percent;
1118 $line->fk_remise_except = $obj->fk_remise_except;
1119 //$line->tva = $obj->total_tva; // deprecated
1120 $line->total_ht = $obj->total_ht;
1121 $line->total_ttc = $obj->total_ttc;
1122 $line->total_tva = $obj->total_tva;
1123 $line->total_localtax1 = $obj->total_localtax1;
1124 $line->total_localtax2 = $obj->total_localtax2;
1125 $line->fk_facture_fourn = $obj->fk_facture_fourn;
1126 $line->fk_product = $obj->fk_product;
1127 $line->product_type = $obj->product_type;
1128 $line->product_label = $obj->label;
1129 $line->info_bits = $obj->info_bits;
1130 $line->fk_parent_line = $obj->fk_parent_line;
1131 $line->special_code = $obj->special_code;
1132 $line->rang = $obj->rang;
1133 $line->fk_unit = $obj->fk_unit;
1134
1135 $line->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
1136
1137 // Accountancy
1138 $line->fk_code_ventilation = $obj->fk_code_ventilation;
1139
1140 // Multicurrency
1141 $line->fk_multicurrency = $obj->fk_multicurrency;
1142 $line->multicurrency_code = $obj->multicurrency_code;
1143 $line->multicurrency_subprice = $obj->multicurrency_subprice;
1144 $line->multicurrency_total_ht = $obj->multicurrency_total_ht;
1145 $line->multicurrency_total_tva = $obj->multicurrency_total_tva;
1146 $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1147
1148 // Extra fields
1149 $line->fetch_optionals();
1150
1151 $this->lines[$i] = $line;
1152
1153 $i++;
1154 }
1155 }
1156 $this->db->free($resql_rows);
1157 return 1;
1158 } else {
1159 $this->error = $this->db->error();
1160 dol_syslog(get_class($this)."::fetch_lines - No lines:{$this->error} Error:{$this->error}", LOG_DEBUG);
1161 return -3;
1162 }
1163 }
1164
1165
1173 public function update($user = null, $notrigger = 0)
1174 {
1175 global $langs;
1176 $error = 0;
1177
1178 // Clean parameters
1179 if (empty($this->type)) {
1180 $this->type = self::TYPE_STANDARD;
1181 }
1182 if (isset($this->ref)) {
1183 $this->ref = trim($this->ref);
1184 }
1185 if (isset($this->ref_supplier)) {
1186 $this->ref_supplier = trim($this->ref_supplier);
1187 }
1188 if (isset($this->ref_ext)) {
1189 $this->ref_ext = trim($this->ref_ext);
1190 }
1191 if (isset($this->entity)) {
1192 $this->entity = (int) $this->entity;
1193 }
1194 if (isset($this->type)) {
1195 $this->type = (int) $this->type;
1196 }
1197 if (isset($this->subtype)) {
1198 $this->subtype = (int) $this->subtype;
1199 }
1200 if (isset($this->socid)) {
1201 $this->socid = (int) $this->socid;
1202 }
1203 if (isset($this->label)) {
1204 $this->label = trim($this->label);
1205 }
1206 if (isset($this->paid)) {
1207 $this->paid = (int) (bool) $this->paid;
1208 $this->paye = $this->paid; // deprecated
1209 } elseif (isset($this->paye)) {
1210 $this->paid = (int) (bool) $this->paye;
1211 $this->paye = $this->paid; // deprecared
1212 }
1213 if (isset($this->close_code)) {
1214 $this->close_code = trim($this->close_code);
1215 }
1216 if (isset($this->close_note)) {
1217 $this->close_note = trim($this->close_note);
1218 }
1219 if (empty($this->total_ht)) {
1220 $this->total_ht = 0;
1221 }
1222 if (empty($this->total_tva)) {
1223 $this->total_tva = 0;
1224 }
1225 if (empty($this->total_localtax1)) {
1226 $this->total_localtax1 = 0;
1227 }
1228 if (empty($this->total_localtax2)) {
1229 $this->total_localtax2 = 0;
1230 }
1231 if (isset($this->total_ttc)) {
1232 $this->total_ttc = (float) $this->total_ttc;
1233 }
1234 if (isset($this->status)) {
1235 $this->status = (int) $this->status;
1236 $this->statut = $this->status;
1237 } elseif (isset($this->statut)) {
1238 $this->status = (int) $this->statut;
1239 $this->statut = $this->status;
1240 }
1241 if (isset($this->author)) { // TODO: user_creation_id?
1242 $this->author = (int) $this->author;
1243 }
1244 if (isset($this->fk_user_valid)) {
1245 $this->fk_user_valid = (int) $this->fk_user_valid;
1246 }
1247 if (isset($this->fk_facture_source)) {
1248 $this->fk_facture_source = (int) $this->fk_facture_source;
1249 }
1250 if (isset($this->fk_project)) {
1251 if (empty($this->fk_project)) {
1252 $this->fk_project = 0;
1253 } else {
1254 $this->fk_project = (int) $this->fk_project;
1255 }
1256 }
1257 if (isset($this->mode_reglement_id)) {
1258 $this->mode_reglement_id = (int) $this->mode_reglement_id;
1259 }
1260 if (isset($this->cond_reglement_id)) {
1261 $this->cond_reglement_id = (int) $this->cond_reglement_id;
1262 }
1263 if (isset($this->note_private)) {
1264 $this->note_private = trim($this->note_private);
1265 $this->note = $this->note_private;
1266 }
1267 if (isset($this->note_public)) {
1268 $this->note_public = trim($this->note_public);
1269 }
1270 if (isset($this->model_pdf)) {
1271 $this->model_pdf = trim($this->model_pdf);
1272 }
1273 if (isset($this->import_key)) {
1274 $this->import_key = trim($this->import_key);
1275 }
1276
1277
1278 // Check parameters
1279 // Put here code to add control on parameters values
1280
1281 if (dol_strlen((string) $this->date_modification) == 0) {
1282 $this->tms = dol_now();
1283 }
1284
1285 // The point of tax date of a validated invoice can't be changed
1286 if ($this->checkPointOfTaxNotChanged() < 0) {
1287 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1288 return -1;
1289 }
1290
1291 // Update request
1292 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
1293 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1294 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1295 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1296 $sql .= " entity=".(isset($this->entity) ? ((int) $this->entity) : "null").",";
1297 $sql .= " type=".(isset($this->type) ? ((int) $this->type) : "null").",";
1298 $sql .= " subtype=".(isset($this->subtype) ? (int) $this->subtype : "null").",";
1299 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
1300 $sql .= " datec=".(dol_strlen((string) $this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
1301 $sql .= " datef=".(dol_strlen((string) $this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
1302 $sql .= " date_pointoftax=".(dol_strlen((string) $this->date_pointoftax) != 0 ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
1303 if (dol_strlen((string) $this->date_modification) != 0) {
1304 $sql .= " tms=".(dol_strlen((string) $this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : 'null').",";
1305 } elseif (dol_strlen((string) $this->tms) != 0) { // For backward compatibility
1306 $sql .= " tms=".(dol_strlen((string) $this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
1307 }
1308 $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
1309 $sql .= " paye=".(isset($this->paid) ? ((int) $this->paid) : "0").",";
1310 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
1311 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
1312 $sql .= " localtax1=".(isset($this->total_localtax1) ? ((float) $this->total_localtax1) : "null").",";
1313 $sql .= " localtax2=".(isset($this->total_localtax2) ? ((float) $this->total_localtax2) : "null").",";
1314 $sql .= " total_ht=".(isset($this->total_ht) ? ((float) $this->total_ht) : "null").",";
1315 $sql .= " total_tva=".(isset($this->total_tva) ? ((float) $this->total_tva) : "null").",";
1316 $sql .= " total_ttc=".(isset($this->total_ttc) ? ((float) $this->total_ttc) : "null").",";
1317 $sql .= " fk_statut=".(isset($this->status) ? ((int) $this->status) : (isset($this->statut) ? ((int) $this->statut) : "null")).",";
1318 $sql .= " fk_user_author=".(isset($this->author) ? ((int) $this->author) : "null").",";
1319 $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? ((int) $this->fk_user_valid) : "null").",";
1320 $sql .= " fk_facture_source=".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null").",";
1321 $sql .= " vat_reverse_charge = ".($this->vat_reverse_charge != '' ? ((int) $this->vat_reverse_charge) : 0).",";
1322 $sql .= " fk_projet=".(!empty($this->fk_project) ? ((int) $this->fk_project) : "null").",";
1323 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? ((int) $this->mode_reglement_id) : "null").",";
1324 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? ((int) $this->cond_reglement_id) : "null").",";
1325 $sql .= " date_lim_reglement=".(dol_strlen((string) $this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
1326 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1327 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1328 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1329 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1330 $sql .= " WHERE rowid=".((int) $this->id);
1331
1332 $this->db->begin();
1333
1334 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1335 $resql = $this->db->query($sql);
1336
1337 if (!$resql) {
1338 $error++;
1339
1340 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1341 $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
1342 } else {
1343 $this->errors[] = "Error ".$this->db->lasterror();
1344 }
1345 }
1346
1347 if (!$error) {
1348 $result = $this->insertExtraFields();
1349 if ($result < 0) {
1350 $error++;
1351 }
1352 }
1353
1354 if (!$error && !$notrigger) {
1355 // Call trigger
1356 $result = $this->call_trigger('BILL_SUPPLIER_MODIFY', $user);
1357 if ($result < 0) {
1358 $error++;
1359 }
1360 // End call triggers
1361 }
1362
1363 // Commit or rollback
1364 if ($error) {
1365 foreach ($this->errors as $errmsg) {
1366 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1367 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1368 }
1369 $this->db->rollback();
1370 return -1 * $error;
1371 } else {
1372 $this->db->commit();
1373 return 1;
1374 }
1375 }
1376
1377 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1384 public function insert_discount($idremise)
1385 {
1386 // phpcs:enable
1387 global $langs;
1388
1389 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1390 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1391
1392 $this->db->begin();
1393
1394 $remise = new DiscountAbsolute($this->db);
1395 $result = $remise->fetch($idremise);
1396
1397 if ($result > 0) {
1398 if ($this->socid > 0 && $remise->fk_soc != $this->socid) { // The discount must belong to the thirdparty of the invoice
1399 $this->error = $langs->trans("ErrorDiscountNotSameCompany");
1400 $this->db->rollback();
1401 return -6;
1402 }
1403 if ($remise->fk_invoice_supplier) { // Protection against multiple submission
1404 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
1405 $this->db->rollback();
1406 return -5;
1407 }
1408
1409 $facligne = new SupplierInvoiceLine($this->db);
1410 $facligne->fk_facture_fourn = $this->id;
1411 $facligne->fk_remise_except = $remise->id;
1412 $facligne->desc = $remise->description; // Line description
1413 $facligne->vat_src_code = $remise->vat_src_code;
1414 $facligne->tva_tx = $remise->tva_tx;
1415 $facligne->localtax1_tx = $remise->localtax1_tx;
1416 $facligne->localtax1_type = $remise->localtax1_type;
1417 $facligne->localtax2_tx = $remise->localtax1_tx;
1418 $facligne->localtax2_type = $remise->localtax1_type;
1419 $facligne->subprice = -(float) $remise->amount_ht;
1420 $facligne->fk_product = 0; // Predefined Product ID
1421 $facligne->product_type = 0;
1422 $facligne->qty = 1;
1423 $facligne->remise_percent = 0;
1424 $facligne->rang = -1;
1425 $facligne->info_bits = 2;
1426
1427 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
1428 $facligne->rang = 1;
1429 $linecount = count($this->lines);
1430 for ($ii = 1; $ii <= $linecount; $ii++) {
1431 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
1432 }
1433 }
1434
1435 // Get buy/cost price of invoice that is source of discount
1436 if ($remise->fk_invoice_supplier_source > 0) {
1437 $srcinvoice = new FactureFournisseur($this->db);
1438 $srcinvoice->fetch($remise->fk_invoice_supplier_source);
1439 $totalcostpriceofinvoice = 0;
1440 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
1441 $formmargin = new FormMargin($this->db);
1442 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
1443 $facligne->pa_ht = $arraytmp['pa_total'];
1444 }
1445
1446 $facligne->total_ht = -(float) $remise->amount_ht;
1447 $facligne->total_tva = -(float) $remise->amount_tva;
1448 $facligne->total_ttc = -(float) $remise->amount_ttc;
1449 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
1450 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
1451
1452 // The discount line must carry the currency of the invoice, like any other line
1453 $facligne->fk_multicurrency = $this->fk_multicurrency;
1454 $facligne->multicurrency_code = $this->multicurrency_code;
1455 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
1456 $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht;
1457 $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva;
1458 $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc;
1459
1460 $lineid = $facligne->insert();
1461 if ($lineid > 0) {
1462 $result = $this->update_price(1);
1463 if ($result > 0) {
1464 // Create link between discount and invoice line
1465 $result = $remise->link_to_invoice($lineid, 0);
1466 if ($result < 0) {
1467 $this->error = $remise->error;
1468 $this->db->rollback();
1469 return -4;
1470 }
1471
1472 $this->db->commit();
1473 return 1;
1474 } else {
1475 $this->error = $facligne->error;
1476 $this->db->rollback();
1477 return -1;
1478 }
1479 } else {
1480 $this->error = $facligne->error;
1481 $this->db->rollback();
1482 return -2;
1483 }
1484 } else {
1485 $this->db->rollback();
1486 return -3;
1487 }
1488 }
1489
1490
1498 public function delete(User $user, $notrigger = 0)
1499 {
1500 global $conf;
1501
1502 $rowid = $this->id;
1503
1504 dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
1505
1506 // Test to avoid invoice deletion (invoice transferred into accountancy, with payment, ...), same test as Facture::delete() does
1507 $result = $this->is_erasable();
1508 if ($result <= 0) {
1509 dol_syslog(get_class($this)."::delete refused, invoice is not erasable (code ".$result.")", LOG_DEBUG);
1510 return 0;
1511 }
1512
1513 $error = 0;
1514 $this->db->begin();
1515
1516 if (!$notrigger) {
1517 // Call trigger
1518 $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user);
1519 if ($result < 0) {
1520 $this->db->rollback();
1521 return -1;
1522 }
1523 // Fin appel triggers
1524 }
1525
1526 // Remove linked categories.
1527 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_supplier_invoice";
1528 $sql .= " WHERE fk_supplier_invoice = ".((int) $this->id);
1529
1530 $result = $this->db->query($sql);
1531 if (!$result) {
1532 $error++;
1533 $this->error = $this->db->lasterror();
1534 $this->errors[] = $this->error;
1535 }
1536
1537 if (!$error) {
1538 // If invoice was converted into a discount not yet consumed, we remove discount
1539 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
1540 $sql .= ' WHERE fk_invoice_supplier_source = '.((int) $rowid);
1541 $sql .= ' AND fk_invoice_supplier_line IS NULL';
1542 $resql = $this->db->query($sql);
1543
1544 // If invoice has consumned discounts
1545 $this->fetch_lines();
1546 $list_rowid_det = array();
1547 foreach ($this->lines as $key => $invoiceline) {
1548 $list_rowid_det[] = $invoiceline->id;
1549 }
1550
1551 // Consumned discounts are freed
1552 if (count($list_rowid_det)) {
1553 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
1554 $sql .= ' SET fk_invoice_supplier = NULL, fk_invoice_supplier_line = NULL';
1555 $sql .= ' WHERE fk_invoice_supplier_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
1556
1557 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1558 if (!$this->db->query($sql)) {
1559 $error++;
1560 }
1561 }
1562 }
1563
1564 if (!$error) {
1565 $sql_main_table = MAIN_DB_PREFIX.'facture_fourn_det';
1566 $sql_ef_table = $sql_main_table."_extrafields";
1567 $sqlef = "DELETE FROM $sql_ef_table WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table." WHERE fk_facture_fourn = ".((int) $rowid).")";
1568 $resqlef = $this->db->query($sqlef);
1569 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.((int) $rowid);
1570 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1571 $resql = $this->db->query($sql);
1572 if ($resqlef && $resql) {
1573 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.((int) $rowid);
1574 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1575 $resql2 = $this->db->query($sql);
1576 if (!$resql2) {
1577 $error++;
1578 }
1579 } else {
1580 $error++;
1581 }
1582 }
1583
1584 if (!$error) {
1585 // Delete linked object
1586 $res = $this->deleteObjectLinked();
1587 if ($res < 0) {
1588 $error++;
1589 }
1590 }
1591
1592 if (!$error) {
1593 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
1594 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1595 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
1596
1597 // We remove directory
1598 $ref = dol_sanitizeFileName($this->ref);
1599 if ($conf->fournisseur->facture->dir_output && !empty($ref)) {
1600 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1601
1602 $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$ref;
1603 $file = $dir."/".$ref.".pdf";
1604 if (file_exists($file)) {
1605 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
1606 $this->error = 'ErrorFailToDeleteFile';
1607 $error++;
1608 }
1609 }
1610 if (file_exists($dir)) {
1611 $res = @dol_delete_dir_recursive($dir);
1612
1613 if (!$res) {
1614 $this->error = 'ErrorFailToDeleteDir';
1615 $error++;
1616 }
1617 }
1618 }
1619 }
1620
1621 // Remove extrafields
1622 if (!$error) {
1623 $result = $this->deleteExtraFields();
1624 if ($result < 0) {
1625 $error++;
1626 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1627 }
1628 }
1629
1630 if (!$error) {
1631 dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1632 $this->db->commit();
1633 return 1;
1634 } else {
1635 $this->error = $this->db->lasterror();
1636 $this->db->rollback();
1637 return -$error;
1638 }
1639 }
1640
1641
1642 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1653 public function set_paid($user, $close_code = '', $close_note = '')
1654 {
1655 // phpcs:enable
1656 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
1657 return $this->setPaid($user, $close_code, $close_note);
1658 }
1659
1668 public function setPaid($user, $close_code = '', $close_note = '')
1669 {
1670 $error = 0;
1671
1672 if ($this->paid != 1) {
1673 $this->db->begin();
1674
1675 $now = dol_now();
1676
1677 dol_syslog("FactureFournisseur::setPaid", LOG_DEBUG);
1678
1679 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn SET';
1680 $sql .= ' fk_statut = '.self::STATUS_CLOSED;
1681 if (!$close_code) {
1682 $sql .= ', paye=1';
1683 }
1684 if ($close_code) {
1685 $sql .= ", close_code='".$this->db->escape($close_code)."'";
1686 }
1687 if ($close_note) {
1688 $sql .= ", close_note='".$this->db->escape($close_note)."'";
1689 }
1690 $sql .= ', fk_user_closing = '.((int) $user->id);
1691 $sql .= ", date_closing = '".$this->db->idate($now)."'";
1692 $sql .= ' WHERE rowid = '.((int) $this->id);
1693
1694 $resql = $this->db->query($sql);
1695 if ($resql) {
1696 // Call trigger
1697 $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user);
1698 if ($result < 0) {
1699 $error++;
1700 }
1701 // End call triggers
1702 } else {
1703 $error++;
1704 $this->error = $this->db->error();
1705 dol_print_error($this->db);
1706 }
1707
1708 if (!$error) {
1709 $this->db->commit();
1710 return 1;
1711 } else {
1712 $this->db->rollback();
1713 return -1;
1714 }
1715 } else {
1716 return 0;
1717 }
1718 }
1719
1720 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1731 public function set_unpaid($user)
1732 {
1733 // phpcs:enable
1734 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
1735 return $this->setUnpaid($user);
1736 }
1737
1746 public function setUnpaid($user)
1747 {
1748 $error = 0;
1749
1750 $this->db->begin();
1751
1752 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
1753 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
1754 $sql .= ' date_closing=null,';
1755 $sql .= ' fk_user_closing=null';
1756 $sql .= ' WHERE rowid = '.((int) $this->id);
1757
1758 dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
1759 $resql = $this->db->query($sql);
1760 if ($resql) {
1761 // Call trigger
1762 $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user);
1763 if ($result < 0) {
1764 $error++;
1765 }
1766 // End call triggers
1767 } else {
1768 $error++;
1769 $this->error = $this->db->error();
1770 dol_print_error($this->db);
1771 }
1772
1773 if (!$error) {
1774 $this->db->commit();
1775 return 1;
1776 } else {
1777 $this->db->rollback();
1778 return -1;
1779 }
1780 }
1781
1792 public function setCanceled($user, $close_code = '', $close_note = '')
1793 {
1794 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
1795
1796 $this->db->begin();
1797
1798 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn SET';
1799 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
1800 if ($close_code) {
1801 $sql .= ", close_code='".$this->db->escape($close_code)."'";
1802 }
1803 if ($close_note) {
1804 $sql .= ", close_note='".$this->db->escape($close_note)."'";
1805 }
1806 $sql .= " WHERE rowid = ".((int) $this->id);
1807
1808 $resql = $this->db->query($sql);
1809 if ($resql) {
1810 // Bound discounts are deducted from the invoice
1811 // as they have not been used since the invoice is abandoned.
1812 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
1813 $sql .= ' SET fk_invoice_supplier = NULL';
1814 $sql .= ' WHERE fk_invoice_supplier = '.((int) $this->id);
1815
1816 $resql = $this->db->query($sql);
1817 if ($resql) {
1818 // Call trigger
1819 $result = $this->call_trigger('BILL_SUPPLIER_CANCEL', $user);
1820 if ($result < 0) {
1821 $this->db->rollback();
1822 return -1;
1823 }
1824 // End call triggers
1825
1826 $this->db->commit();
1827 return 1;
1828 } else {
1829 $this->error = $this->db->error()." sql=".$sql;
1830 $this->db->rollback();
1831 return -1;
1832 }
1833 } else {
1834 $this->error = $this->db->error()." sql=".$sql;
1835 $this->db->rollback();
1836 return -2;
1837 }
1838 }
1839
1849 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1850 {
1851 global $mysoc, $conf, $langs;
1852
1853 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1854
1855 $now = dol_now();
1856
1857 $error = 0;
1858 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
1859
1860 // Force to have object complete for checks
1861 $this->fetch_thirdparty();
1862 $this->fetch_lines();
1863
1864 // Check parameters
1865 if ($this->status > self::STATUS_DRAFT) { // This is to avoid to validate twice (avoid errors on logs and stock management)
1866 dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
1867 return 0;
1868 }
1869 if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ', '/').'/', $this->ref_supplier)) {
1870 $langs->load("errors");
1871 $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
1872 return -1;
1873 }
1874 if (count($this->lines) <= 0) {
1875 $langs->load("errors");
1876 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
1877 return -1;
1878 }
1879
1880 // Check for mandatory fields in thirdparty (defined into setup)
1881 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
1882 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_SUPPLIER');
1883 foreach ($array_to_check as $key) {
1884 $keymin = strtolower($key);
1885 if ($keymin == 'accountancy_code_supplier') {
1886 $keymin = 'code_compta_fournisseur';
1887 }
1888 if (!property_exists($this->thirdparty, $keymin)) {
1889 continue;
1890 }
1891 $vallabel = $this->thirdparty->$keymin;
1892
1893 $i = (int) preg_replace('/[^0-9]/', '', $key);
1894 if ($i > 0) {
1895 if ($this->thirdparty->isACompany()) {
1896 // Check for mandatory prof id (but only if country is other than ours)
1897 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
1898 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
1899 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1900 $langs->load("errors");
1901 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
1902 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
1903 return -1;
1904 }
1905 }
1906 }
1907 } else {
1908 if ($key == 'EMAIL') {
1909 // Check for mandatory
1910 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
1911 $langs->load("errors");
1912 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
1913 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
1914 return -1;
1915 }
1916 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1917 // Check for mandatory
1918 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_fournisseur)) {
1919 $langs->load("errors");
1920 $this->error = $langs->trans("ErrorAccountancyCodeSupplierIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
1921 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
1922 return -1;
1923 }
1924 }
1925 }
1926 }
1927 }
1928
1929 $this->db->begin();
1930
1931 // Define new ref
1932 if ($force_number) {
1933 $num = $force_number;
1934 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1935 $num = $this->getNextNumRef($this->thirdparty);
1936 } else {
1937 $num = (string) $this->ref;
1938 }
1939 $this->newref = dol_sanitizeFileName($num);
1940
1941 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1942 $sql .= " SET ref='".$this->db->escape($num)."', fk_statut = 1, fk_user_valid = ".((int) $user->id).", date_valid = '".$this->db->idate($now)."'";
1943 $sql .= " WHERE rowid = ".((int) $this->id);
1944
1945 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
1946 $resql = $this->db->query($sql);
1947 if ($resql) {
1948 // If we increment the main product and its components upon validation of the supplier invoice
1949 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
1950 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1951 $langs->load("agenda");
1952
1953 $cpt = count($this->lines);
1954 for ($i = 0; $i < $cpt; $i++) {
1955 if ($this->lines[$i]->fk_product > 0) {
1956 $mouvP = new MouvementStock($this->db);
1957 $mouvP->origin = &$this;
1958 $mouvP->setOrigin($this->element, $this->id);
1959 // We increase stock for product
1960 $up_ht_disc = $this->lines[$i]->subprice;
1961 if (!empty($this->lines[$i]->remise_percent) && !getDolGlobalString('STOCK_EXCLUDE_DISCOUNT_FOR_PMP')) {
1962 $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1963 }
1965 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->transnoentitiesnoconv("InvoiceValidatedInDolibarr", $num));
1966 } else {
1967 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->transnoentitiesnoconv("InvoiceValidatedInDolibarr", $num));
1968 }
1969 if ($result < 0) {
1970 $this->setErrorsFromObject($mouvP);
1971 return -2;
1972 }
1973 }
1974 }
1975 }
1976
1977 // Triggers call
1978 if (empty($notrigger)) {
1979 // Call trigger
1980 $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user);
1981 if ($result < 0) {
1982 $error++;
1983 }
1984 // End call triggers
1985 }
1986
1987 if (!$error) {
1988 $this->oldref = $this->ref;
1989
1990 // Rename directory if dir was a temporary ref
1991 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1992 // Now we rename also files into index
1993 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/facture/".$this->db->escape(get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier')).$this->db->escape($this->newref)."'";
1994 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".$this->db->escape(get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier')).$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1995 $resql = $this->db->query($sql);
1996 if (!$resql) {
1997 $error++;
1998 $this->error = $this->db->lasterror();
1999 }
2000 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'fournisseur/facture/".$this->db->escape(get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier')).$this->db->escape($this->newref)."'";
2001 $sql .= " WHERE filepath = 'fournisseur/facture/".$this->db->escape(get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier')).$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2002 $resql = $this->db->query($sql);
2003 if (!$resql) {
2004 $error++;
2005 $this->error = $this->db->lasterror();
2006 }
2007
2008 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
2009 $oldref = dol_sanitizeFileName($this->ref);
2010 $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref;
2011 $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->newref;
2012 if (!$error && file_exists($dirsource)) {
2013 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
2014
2015 if (@rename($dirsource, $dirdest)) {
2016 dol_syslog("Rename ok");
2017 // Rename docs starting with $oldref with $this->newref
2018 $listoffiles = dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->newref, 'files', 1, '^'.preg_quote($oldref, '/'));
2019 foreach ($listoffiles as $fileentry) {
2020 $dirsource = $fileentry['name'];
2021 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $this->newref, $dirsource);
2022 $dirsource = $fileentry['path'].'/'.$dirsource;
2023 $dirdest = $fileentry['path'].'/'.$dirdest;
2024 @rename($dirsource, $dirdest);
2025 }
2026 }
2027 }
2028 }
2029 }
2030
2031 // Set new ref and define current status
2032 if (!$error) {
2033 $this->ref = $this->newref;
2034 $this->statut = self::STATUS_VALIDATED;
2036 //$this->date_validation=$now; this is stored into log table
2037 }
2038
2039 if (!$error) {
2040 $this->db->commit();
2041 return 1;
2042 } else {
2043 $this->db->rollback();
2044 return -1;
2045 }
2046 } else {
2047 $this->error = $this->db->error();
2048 $this->db->rollback();
2049 return -1;
2050 }
2051 }
2052
2061 public function setDraft($user, $idwarehouse = -1, $notrigger = 0)
2062 {
2063 // phpcs:enable
2064 global $langs;
2065
2066 $error = 0;
2067
2068 if ($this->status == self::STATUS_DRAFT) {
2069 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
2070 return 0;
2071 }
2072
2073 dol_syslog(__METHOD__, LOG_DEBUG);
2074
2075 $this->db->begin();
2076
2077 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
2078 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2079 $sql .= " WHERE rowid = ".((int) $this->id);
2080
2081 $result = $this->db->query($sql);
2082 if ($result) {
2083 $this->oldcopy = clone $this;
2084
2085 // If we increment the main product and its components upon supplier invoice validation, we decrement upon customer invoice validation
2086 if ($result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
2087 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2088 $langs->load("agenda");
2089
2090 $cpt = count($this->lines);
2091 for ($i = 0; $i < $cpt; $i++) {
2092 if ($this->lines[$i]->fk_product > 0) {
2093 $mouvP = new MouvementStock($this->db);
2094 $mouvP->origin = &$this;
2095 $mouvP->setOrigin($this->element, $this->id);
2096 // We increase stock for product
2098 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv("InvoiceBackToDraftInDolibarr", $this->ref));
2099 } else {
2100 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv("InvoiceBackToDraftInDolibarr", $this->ref));
2101 }
2102 if ($result < 0) {
2103 $error++;
2104 $this->setErrorsFromObject($mouvP);
2105 dol_syslog(__METHOD__." stock movement failed for line ".$i.": ".$mouvP->error, LOG_ERR);
2106 break;
2107 }
2108 }
2109 }
2110 }
2111 // Triggers call
2112 if (!$error && empty($notrigger)) {
2113 // Call trigger
2114 $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user);
2115 if ($result < 0) {
2116 $error++;
2117 }
2118 // End call triggers
2119 }
2120 if ($error == 0) {
2121 $this->db->commit();
2122 return 1;
2123 } else {
2124 $this->db->rollback();
2125 return -1;
2126 }
2127 } else {
2128 $this->error = $this->db->error();
2129 $this->db->rollback();
2130 return -1;
2131 }
2132 }
2133
2134
2169 public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = 0, $date_end = 0, $fk_code_ventilation = 0, $info_bits = 0, $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = 0, $array_options = [], $fk_unit = null, $origin_id = 0, $pu_devise = 0, $ref_supplier = '', $special_code = 0, $fk_parent_line = 0, $fk_remise_except = 0, $origin_type = '')
2170 {
2171 global $langs, $mysoc;
2172
2173 dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$fk_code_ventilation,$info_bits,$price_base_type,$type,$fk_unit,fk_remise_except=$fk_remise_except", LOG_DEBUG);
2174 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2175
2176 if ($this->status == self::STATUS_DRAFT) {
2177 // Clean parameters
2178 if (empty($remise_percent)) {
2179 $remise_percent = 0;
2180 }
2181 if (empty($qty)) {
2182 $qty = 0;
2183 }
2184 if (empty($info_bits)) {
2185 $info_bits = 0;
2186 }
2187 if (empty($rang)) {
2188 $rang = 0;
2189 }
2190 if (empty($fk_code_ventilation)) {
2191 $fk_code_ventilation = 0;
2192 }
2193 if (empty($txtva)) {
2194 $txtva = 0;
2195 }
2196 if (empty($txlocaltax1)) {
2197 $txlocaltax1 = 0;
2198 }
2199 if (empty($txlocaltax2)) {
2200 $txlocaltax2 = 0;
2201 }
2202
2203 $remise_percent = price2num($remise_percent);
2204 $qty = price2num($qty);
2205 $pu = price2num($pu);
2206 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
2207 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
2208 }
2209 $txlocaltax1 = price2num($txlocaltax1);
2210 $txlocaltax2 = price2num($txlocaltax2);
2211
2212 if ($date_start && $date_end && $date_start > $date_end) {
2213 $langs->load("errors");
2214 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2215 return -1;
2216 }
2217
2218 $this->db->begin();
2219
2220 if ($fk_product > 0) {
2221 if (getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY') == 1) { // Not the common case
2222 // Check quantity is enough
2223 dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." qty=".$qty." ref_supplier=".$ref_supplier);
2224 $prod = new ProductFournisseur($this->db);
2225 if ($prod->fetch($fk_product) > 0) {
2226 $product_type = $prod->type;
2227 $label = $prod->label;
2228 $fk_prod_fourn_price = 0;
2229
2230 // We use 'none' instead of $ref_supplier, because $ref_supplier may not exists anymore. So we will take the first supplier price ok.
2231 // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
2232 $result = $prod->get_buyprice($fk_prod_fourn_price, (float) $qty, $fk_product, 'none', ($this->fk_soc ? $this->fk_soc : $this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc
2233 if ($result > 0) {
2234 if (empty($pu)) {
2235 $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
2236 }
2237 $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
2238 // is remise percent not keyed but present for the product we add it
2239 if ($remise_percent == 0 && $prod->remise_percent != 0) {
2240 $remise_percent = $prod->remise_percent;
2241 }
2242 }
2243 if ($result == 0) { // If result == 0, we failed to found the supplier reference price
2244 $langs->load("errors");
2245 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2246 $this->db->rollback();
2247 dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
2248 //$pu = $prod->fourn_pu; // We do not overwrite unit price
2249 //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
2250 return -1;
2251 }
2252 if ($result == -1) {
2253 $langs->load("errors");
2254 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2255 $this->db->rollback();
2256 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
2257 return -1;
2258 }
2259 if ($result < -1) {
2260 $this->error = $prod->error;
2261 $this->db->rollback();
2262 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
2263 return -1;
2264 }
2265 } else {
2266 $this->error = $prod->error;
2267 $this->db->rollback();
2268 return -1;
2269 }
2270 }
2271 } else {
2272 $product_type = $type;
2273 }
2274
2275 if (isModEnabled("multicurrency") && $pu_devise > 0) {
2276 $pu = 0;
2277 }
2278
2279 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2280
2281 // Clean vat code
2282 $reg = array();
2283 $vat_src_code = '';
2284 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
2285 $vat_src_code = $reg[1];
2286 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
2287 }
2288
2289 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
2290 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
2291 // and this is done at the line level, which has its own VAT rate
2292
2293 $tabprice = calcul_price_total((float) $qty, $pu, (float) $remise_percent, $txtva, (float) $txlocaltax1, (float) $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_devise, $this->multicurrency_code);
2294 $total_ht = $tabprice[0];
2295 $total_tva = $tabprice[1];
2296 $total_ttc = $tabprice[2];
2297 $total_localtax1 = $tabprice[9];
2298 $total_localtax2 = $tabprice[10];
2299 $pu_ht = $tabprice[3];
2300
2301 // MultiCurrency
2302 $multicurrency_total_ht = $tabprice[16];
2303 $multicurrency_total_tva = $tabprice[17];
2304 $multicurrency_total_ttc = $tabprice[18];
2305 $pu_ht_devise = $tabprice[19];
2306
2307 // Check parameters
2308 if ($type < 0) {
2309 return -1;
2310 }
2311
2312 if ($rang < 0) {
2313 $rangmax = $this->line_max();
2314 $rang = $rangmax + 1;
2315 }
2316
2317 // Same gate as on the customer invoice side: the -abs() forcing on credit note lines is relaxed only when
2318 // both FACTURE_ENABLE_NEGATIVE_LINES and INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN are enabled.
2319 $apply_abs_price_on_credit_note = false;
2320 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
2321 $apply_abs_price_on_credit_note = true;
2322 }
2323
2324 // Insert line
2325 $supplierinvoiceline = new SupplierInvoiceLine($this->db);
2326
2327 $supplierinvoiceline->context = $this->context;
2328
2329 $supplierinvoiceline->fk_facture_fourn = $this->id;
2330 //$supplierinvoiceline->label=$label; // deprecated
2331 $supplierinvoiceline->desc = $desc;
2332 $supplierinvoiceline->ref_supplier = $ref_supplier;
2333
2334 $supplierinvoiceline->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : (float) $qty); // For credit note, quantity is always positive and unit price negative
2335
2336 $supplierinvoiceline->subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht) : (float) $pu_ht); // For credit note, unit price always negative, always positive otherwise
2337 // Only keep the TTC unit price when the line was entered including tax, so it acts as a reliable "TTC entry mode" marker.
2338 $supplierinvoiceline->subprice_ttc = ($price_base_type === 'TTC') ? ($apply_abs_price_on_credit_note ? -abs((float) $tabprice[5]) : (float) $tabprice[5]) : 0;
2339
2340 $supplierinvoiceline->vat_src_code = $vat_src_code;
2341 $supplierinvoiceline->tva_tx = $txtva;
2342 $supplierinvoiceline->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
2343 $supplierinvoiceline->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
2344 $supplierinvoiceline->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
2345 $supplierinvoiceline->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
2346
2347 $supplierinvoiceline->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ht) : (float) $total_ht); // For credit note and if qty is negative, total is negative
2348 $supplierinvoiceline->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva); // For credit note and if qty is negative, total is negative
2349 $supplierinvoiceline->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_localtax1) : (float) $total_localtax1); // For credit note and if qty is negative, total is negative
2350 $supplierinvoiceline->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_localtax2) : (float) $total_localtax2); // For credit note and if qty is negative, total is negative
2351 $supplierinvoiceline->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc); // For credit note and if qty is negative, total is negative
2352
2353 $supplierinvoiceline->fk_product = $fk_product;
2354 $supplierinvoiceline->product_type = $type;
2355 $supplierinvoiceline->remise_percent = $remise_percent;
2356 $supplierinvoiceline->date_start = $date_start;
2357 $supplierinvoiceline->date_end = $date_end;
2358 $supplierinvoiceline->fk_code_ventilation = $fk_code_ventilation;
2359 $supplierinvoiceline->rang = $rang;
2360 $supplierinvoiceline->info_bits = $info_bits;
2361 $supplierinvoiceline->fk_remise_except = $fk_remise_except;
2362
2363
2364 $supplierinvoiceline->special_code = (int) $special_code;
2365 $supplierinvoiceline->fk_parent_line = $fk_parent_line;
2366 $supplierinvoiceline->origin = $this->origin;
2367 $supplierinvoiceline->origin_type = $origin_type;
2368 $supplierinvoiceline->origin_id = $origin_id;
2369 $supplierinvoiceline->fk_unit = $fk_unit;
2370
2371 // Multicurrency
2372 $supplierinvoiceline->fk_multicurrency = $this->fk_multicurrency;
2373 $supplierinvoiceline->multicurrency_code = $this->multicurrency_code;
2374 $supplierinvoiceline->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht_devise) : (float) $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
2375
2376 $supplierinvoiceline->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ht) : (float) $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
2377 $supplierinvoiceline->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
2378 $supplierinvoiceline->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
2379
2380 if (is_array($array_options) && count($array_options) > 0) {
2381 $supplierinvoiceline->array_options = $array_options;
2382 }
2383
2384 $result = $supplierinvoiceline->insert($notrigger);
2385 if ($result > 0) {
2386 // Update denormalized fields at the order level
2387 $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
2388
2389 if ($result > 0) {
2390 if (!isset($this->context['createfromclone'])) {
2391 if (!empty($fk_parent_line)) {
2392 // Always reorder if child line
2393 $this->line_order(true, 'DESC');
2394 } elseif ($rang > 0 && $rang <= count($this->lines)) {
2395 // Update all rank of all other lines starting from the same $ranktouse
2396 $linecount = count($this->lines);
2397 for ($ii = $rang; $ii <= $linecount; $ii++) {
2398 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2399 }
2400 }
2401
2402 $this->lines[] = $supplierinvoiceline;
2403 }
2404
2405 $this->db->commit();
2406 return $supplierinvoiceline->id;
2407 } else {
2408 $this->error = $this->db->error();
2409 $this->db->rollback();
2410 return -1;
2411 }
2412 } else {
2413 $this->error = $supplierinvoiceline->error;
2414 $this->errors = $supplierinvoiceline->errors;
2415 $this->db->rollback();
2416 return -2;
2417 }
2418 } else {
2419 return 0;
2420 }
2421 }
2422
2448 public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1 = 0, $txlocaltax2 = 0, $qty = 1, $idproduct = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $remise_percent = 0, $notrigger = 0, $date_start = '', $date_end = '', $array_options = [], $fk_unit = null, $pu_devise = 0, $ref_supplier = '', $rang = 0)
2449 {
2450 global $mysoc, $langs;
2451
2452 if (!$this->isLineOfObject($id)) {
2453 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2454 return -1;
2455 }
2456
2457 dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$notrigger,$date_start,$date_end,$fk_unit,$pu_devise,$ref_supplier", LOG_DEBUG);
2458 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2459
2460 $pu = price2num($pu);
2461 $qty = price2num($qty);
2462 $remise_percent = (float) price2num($remise_percent);
2463 $pu_devise = price2num($pu_devise);
2464
2465 // Check parameters
2466 //if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
2467 if ($type < 0) {
2468 return -1;
2469 }
2470
2471 if ($date_start && $date_end && $date_start > $date_end) {
2472 $langs->load("errors");
2473 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2474 return -1;
2475 }
2476
2477 // Clean parameters
2478 if (empty($vatrate)) {
2479 $vatrate = 0;
2480 }
2481 if (empty($txlocaltax1)) {
2482 $txlocaltax1 = 0;
2483 }
2484 if (empty($txlocaltax2)) {
2485 $txlocaltax2 = 0;
2486 }
2487
2488 $txlocaltax1 = (float) price2num($txlocaltax1);
2489 $txlocaltax2 = (float) price2num($txlocaltax2);
2490
2491 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
2492 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
2493 // and this is done at the line level, which has its own VAT rate
2494
2495 $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty);
2496
2497 $reg = array();
2498
2499 // Clean vat code
2500 $vat_src_code = '';
2501 if (preg_match('/\‍((.*)\‍)/', (string) $vatrate, $reg)) {
2502 $vat_src_code = $reg[1];
2503 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', (string) $vatrate); // Remove code into vatrate.
2504 }
2505
2506 $tabprice = calcul_price_total((float) $qty, (float) $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_devise, $this->multicurrency_code);
2507 $total_ht = $tabprice[0];
2508 $total_tva = $tabprice[1];
2509 $total_ttc = $tabprice[2];
2510 $pu_ht = $tabprice[3];
2511 $pu_tva = $tabprice[4];
2512 $pu_ttc = $tabprice[5];
2513 $total_localtax1 = $tabprice[9];
2514 $total_localtax2 = $tabprice[10];
2515
2516 // MultiCurrency
2517 $multicurrency_total_ht = $tabprice[16];
2518 $multicurrency_total_tva = $tabprice[17];
2519 $multicurrency_total_ttc = $tabprice[18];
2520 $pu_ht_devise = $tabprice[19];
2521
2522 if (empty($info_bits)) {
2523 $info_bits = 0;
2524 }
2525
2526 // Fetch current line from the database and then clone the object and set it in $oldline property
2527 $line = new SupplierInvoiceLine($this->db);
2528 $line->fetch($id);
2529 $line->fetch_optionals();
2530
2531 $staticline = clone $line;
2532
2533 if ($idproduct) {
2534 $product = new Product($this->db);
2535 $result = $product->fetch($idproduct);
2536 $product_type = $product->type;
2537 } else {
2538 $idproduct = $staticline->fk_product;
2539 $product_type = $type;
2540 }
2541
2542 $line->oldline = $staticline;
2543 $line->context = $this->context;
2544
2545 // Same gate as on the customer invoice side: the -abs() forcing on credit note lines is relaxed only when
2546 // both FACTURE_ENABLE_NEGATIVE_LINES and INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN are enabled.
2547 $apply_abs_price_on_credit_note = false;
2548 if ($this->type == self::TYPE_CREDIT_NOTE && !(getDolGlobalInt('FACTURE_ENABLE_NEGATIVE_LINES') && getDolGlobalInt('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN'))) {
2549 $apply_abs_price_on_credit_note = true;
2550 }
2551
2552 $line->desc = $desc;
2553 $line->description = $desc;
2554 $line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : (float) $qty); // For credit note, quantity is always positive and unit price negative
2555
2556 $line->subprice = ($apply_abs_price_on_credit_note ? -abs((float) $pu_ht) : (float) $pu_ht); // For credit note, unit price always negative, always positive otherwise
2557 // Only keep the TTC unit price when the line was entered including tax, so it acts as a reliable "TTC entry mode" marker.
2558 $line->subprice_ttc = ($price_base_type === 'TTC') ? ($apply_abs_price_on_credit_note ? -abs((float) $pu_ttc) : (float) $pu_ttc) : 0; // For credit note, unit price always negative, always positive otherwise
2559
2560 $line->remise_percent = $remise_percent;
2561 $line->ref_supplier = $ref_supplier;
2562
2563 $line->date_start = $date_start;
2564 $line->date_end = $date_end;
2565
2566 $line->vat_src_code = $vat_src_code;
2567 $line->tva_tx = $vatrate;
2568 $line->localtax1_tx = $txlocaltax1;
2569 $line->localtax2_tx = $txlocaltax2;
2570 $line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
2571 $line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
2572
2573 $line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ht) : (float) $total_ht);
2574 $line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva);
2575 $line->total_localtax1 = (float) $total_localtax1;
2576 $line->total_localtax2 = (float) $total_localtax2;
2577 $line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc);
2578
2579 $line->fk_product = $idproduct;
2580 $line->product_type = $product_type;
2581 $line->info_bits = $info_bits;
2582 $line->fk_unit = $fk_unit;
2583 $line->rang = $rang;
2584
2585 if (is_array($array_options) && count($array_options) > 0) {
2586 // We replace values in this->line->array_options only for entries defined into $array_options
2587 foreach ($array_options as $key => $value) {
2588 $line->array_options[$key] = $array_options[$key];
2589 }
2590 }
2591
2592 // Multicurrency
2593 $line->multicurrency_subprice = (float) $pu_ht_devise;
2594 $line->multicurrency_total_ht = (float) $multicurrency_total_ht;
2595 $line->multicurrency_total_tva = (float) $multicurrency_total_tva;
2596 $line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
2597
2598 $res = $line->update($notrigger);
2599
2600 if ($res < 1) {
2601 $this->setErrorsFromObject($line);
2602 } else {
2603 // Update total price into invoice record
2604 $res = $this->update_price(1, 'auto', 0, $this->thirdparty);
2605 }
2606
2607 return $res;
2608 }
2609
2617 public function deleteLine($rowid, $notrigger = 0)
2618 {
2619 if (!$rowid) {
2620 $rowid = $this->id;
2621 }
2622
2623 $line = new SupplierInvoiceLine($this->db);
2624
2625 if ($line->fetch($rowid) < 1) {
2626 return -1;
2627 }
2628 if ($this->id > 0 && (int) $line->fk_facture_fourn !== (int) $this->id) {
2629 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2630 return -1;
2631 }
2632
2633 $this->db->begin();
2634
2635 // Free the discount linked to a line of invoice
2636 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2637 $sql .= ' SET fk_invoice_supplier_line = NULL';
2638 $sql .= ' WHERE fk_invoice_supplier_line = '.((int) $rowid);
2639
2640 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
2641 $result = $this->db->query($sql);
2642 if (!$result) {
2643 $this->error = $this->db->error();
2644 $this->db->rollback();
2645 return -2;
2646 }
2647
2648 $res = $line->delete($notrigger);
2649
2650 if ($res < 1) {
2651 $this->errors[] = $line->error;
2652 $this->db->rollback();
2653 return -3;
2654 } else {
2655 $res = $this->update_price(1);
2656
2657 if ($res > 0) {
2658 $this->db->commit();
2659 return 1;
2660 } else {
2661 $this->db->rollback();
2662 $this->error = $this->db->lasterror();
2663 return -4;
2664 }
2665 }
2666 }
2667
2668
2675 public function info($id)
2676 {
2677 $sql = 'SELECT c.rowid, datec, tms as datem, ';
2678 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid';
2679 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
2680 $sql .= ' WHERE c.rowid = '.((int) $id);
2681
2682 $result = $this->db->query($sql);
2683 if ($result) {
2684 if ($this->db->num_rows($result)) {
2685 $obj = $this->db->fetch_object($result);
2686
2687 $this->id = $obj->rowid;
2688
2689 $this->user_creation_id = $obj->fk_user_author;
2690 $this->user_validation_id = $obj->fk_user_valid;
2691 $this->user_modification_id = $obj->fk_user_modif;
2692 $this->date_creation = $this->db->jdate($obj->datec);
2693 $this->date_modification = $this->db->jdate($obj->datem);
2694 //$this->date_validation = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders)
2695 }
2696 $this->db->free($result);
2697 } else {
2698 dol_print_error($this->db);
2699 }
2700 }
2701
2702 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2711 public function list_replacable_supplier_invoices($socid = 0)
2712 {
2713 // phpcs:enable
2714 global $conf;
2715
2716 $return = array();
2717
2718 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut,";
2719 $sql .= " ff.rowid as rowidnext";
2720 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2721 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
2722 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source";
2723 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
2724 $sql .= " AND f.entity = ".((int) $conf->entity);
2725 $sql .= " AND f.paye = 0"; // Not closed completely
2726 $sql .= " AND pf.fk_paiementfourn IS NULL"; // No payment already done
2727 $sql .= " AND ff.fk_statut IS NULL"; // Return true (is null) if it is not a replacing invoice (we can't replace a replacing invoice)
2728 if ($socid > 0) {
2729 $sql .= " AND f.fk_soc = ".((int) $socid);
2730 }
2731 $sql .= " ORDER BY f.ref";
2732
2733 dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG);
2734 $resql = $this->db->query($sql);
2735 if ($resql) {
2736 while ($obj = $this->db->fetch_object($resql)) {
2737 $return[$obj->rowid] = array(
2738 'id' => $obj->rowid,
2739 'ref' => $obj->ref,
2740 'status' => $obj->fk_statut
2741 );
2742 }
2743 //print_r($return);
2744 return $return;
2745 } else {
2746 $this->error = $this->db->error();
2747 return -1;
2748 }
2749 }
2750
2751 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2760 public function list_qualified_avoir_supplier_invoices($socid = 0)
2761 {
2762 // phpcs:enable
2763 global $conf;
2764
2765 $return = array();
2766
2767 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye as paid, pf.fk_paiementfourn";
2768 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2769 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
2770 $sql .= " WHERE f.entity = ".((int) $conf->entity);
2771 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
2772 $sql .= " AND NOT EXISTS (SELECT rowid from ".MAIN_DB_PREFIX."facture_fourn as ff WHERE f.rowid = ff.fk_facture_source";
2773 $sql .= " AND ff.type=".self::TYPE_REPLACEMENT.")";
2774 $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
2775 if ($socid > 0) {
2776 $sql .= " AND f.fk_soc = ".((int) $socid);
2777 }
2778 $sql .= " ORDER BY f.ref";
2779
2780 dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG);
2781 $resql = $this->db->query($sql);
2782 if ($resql) {
2783 while ($obj = $this->db->fetch_object($resql)) {
2784 $qualified = 0;
2785 if ($obj->fk_statut == self::STATUS_VALIDATED) {
2786 $qualified = 1;
2787 }
2788 if ($obj->fk_statut == self::STATUS_CLOSED) {
2789 $qualified = 1;
2790 }
2791 if ($qualified) {
2792 $paymentornot = ($obj->fk_paiementfourn ? 1 : 0);
2793 $return[$obj->rowid] = array('ref' => (string) $obj->ref, 'status' => (int) $obj->fk_statut, 'type' => (int) $obj->type, 'paid' => (int) $obj->paid, 'paye' => (int) $obj->paid, 'paymentornot' => (int) $paymentornot);
2794 }
2795 }
2796
2797 return $return;
2798 } else {
2799 $this->error = $this->db->error();
2800 return -1;
2801 }
2802 }
2803
2804 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2811 public function load_board($user)
2812 {
2813 // phpcs:enable
2814 global $conf, $langs;
2815
2816 $now = dol_now();
2817
2818 // The count, the total and the number of late invoices are computed by the database: reading every unpaid invoice to
2819 // count them in PHP took seconds on the home page of an instance with a lot of unpaid invoices. An invoice is late when
2820 // it has a due date and that date is before now minus the warning delay, the rule of hasDelay() for a validated invoice.
2821 $sql = 'SELECT COUNT(ff.rowid) as nb, SUM(ff.total_ht) as total,';
2822 $sql .= " SUM(CASE WHEN ff.date_lim_reglement IS NOT NULL AND ff.date_lim_reglement < '".$this->db->idate($now - $conf->facture->fournisseur->warning_delay)."' THEN 1 ELSE 0 END) as nblate";
2823 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
2824 if (empty($user->socid) && !$user->hasRight("societe", "client", "voir")) {
2825 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ff.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2826 }
2827 $sql .= ' WHERE ff.paye = 0';
2828 $sql .= " AND ff.fk_statut IN (".self::STATUS_VALIDATED.")";
2829 $sql .= " AND ff.entity = ".((int) $conf->entity);
2830 if ($user->socid) {
2831 $sql .= ' AND ff.fk_soc = '.((int) $user->socid);
2832 }
2833
2834 $resql = $this->db->query($sql);
2835 if ($resql) {
2836 $langs->load("bills");
2837
2838 $response = new WorkboardResponse();
2839 $response->warning_delay = $conf->warning_delays['supplier_invoice'] / 60 / 60 / 24;
2840 $response->label = $langs->trans("SupplierBillsToPay");
2841 $response->labelShort = $langs->trans("StatusToPay");
2842
2843 $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills';
2844 $response->img = img_object($langs->trans("Bills"), "bill");
2845
2846 $obj = $this->db->fetch_object($resql);
2847 if ($obj) {
2848 $response->nbtodo = (int) $obj->nb;
2849 $response->total = (float) $obj->total;
2850 $response->nbtodolate = (int) $obj->nblate;
2851 if ($response->nbtodolate > 0) {
2852 $response->url_late = DOL_URL_ROOT.'/fourn/facture/list.php?search_option=late&mainmenu=billing&leftmenu=suppliers_bills';
2853 }
2854 }
2855
2856 $this->db->free($resql);
2857 return $response;
2858 } else {
2859 dol_print_error($this->db);
2860 $this->error = $this->db->error();
2861 return -1;
2862 }
2863 }
2864
2872 public function getTooltipContentArray($params)
2873 {
2874 global $conf, $langs, $mysoc;
2875
2876 $langs->load('bills');
2877
2878 $datas = [];
2879 $moretitle = $params['moretitle'] ?? '';
2880
2881 $picto = $this->picto;
2882 if ($this->type == self::TYPE_REPLACEMENT) {
2883 $picto .= 'r'; // Replacement invoice
2884 }
2885 if ($this->type == self::TYPE_CREDIT_NOTE) {
2886 $picto .= 'a'; // Credit note
2887 }
2888 if ($this->type == self::TYPE_DEPOSIT) {
2889 $picto .= 'd'; // Deposit invoice
2890 }
2891
2892 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("SupplierInvoice").'</u>';
2893 if ($this->type == self::TYPE_REPLACEMENT) {
2894 $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplacement").'</u>';
2895 } elseif ($this->type == self::TYPE_CREDIT_NOTE) {
2896 $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
2897 } elseif ($this->type == self::TYPE_DEPOSIT) {
2898 $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
2899 }
2900 if (isset($this->status)) {
2901 $alreadypaid = -1;
2902 if (isset($this->totalpaid)) {
2903 $alreadypaid = $this->totalpaid;
2904 }
2905
2906 $datas['picto'] .= ' '.$this->getLibStatut(5, $alreadypaid);
2907 }
2908 if ($moretitle) {
2909 $datas['picto'] .= ' - '.$moretitle;
2910 }
2911 if (!empty($this->ref)) {
2912 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2913 }
2914 if (!empty($this->ref_supplier)) {
2915 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2916 }
2917 if (empty($params['nofetch'])) {
2918 $langs->load('companies');
2919 if (empty($this->thirdparty)) {
2920 $this->fetch_thirdparty();
2921 }
2922 if (is_object($this->thirdparty)) {
2923 $datas['supplier'] = '<br><b>'.$langs->trans('Supplier').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2924 }
2925 }
2926 if (!empty($this->label)) {
2927 $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
2928 }
2929 if (!empty($this->date)) {
2930 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
2931 }
2932 if (!empty($this->date_echeance)) {
2933 $datas['date_echeance'] = '<br><b>'.$langs->trans('DateDue').':</b> '.dol_print_date($this->date_echeance, 'day');
2934 }
2935 if (!empty($this->total_ht)) {
2936 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2937 }
2938 if (!empty($this->total_tva)) {
2939 $datas['totaltva'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2940 }
2941 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2942 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
2943 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2944 }
2945 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2946 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2947 }
2948 if (!empty($this->revenuestamp)) {
2949 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2950 }
2951 if (!empty($this->total_ttc)) {
2952 $datas['totalttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2953 }
2954 return $datas;
2955 }
2956
2964 {
2965 global $mysoc;
2966
2967 $context = parent::getObjectLinesDisplayContext();
2968 // The supplier is the seller, an empty third party is used if it is not loaded (same as a failed fetch in the card)
2969 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
2970 $context['seller'] = (is_object($this->thirdparty) ? $this->thirdparty : new Societe($this->db));
2971 $context['buyer'] = $mysoc;
2972 $context['forceall'] = 1;
2973 $context['inputalsopricewithtax'] = 1;
2974 // 2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum
2975 $context['senderissupplier'] = (getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY') ? getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY') : 2);
2976
2977 return $context;
2978 }
2979
2993 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
2994 {
2995 global $langs, $user, $hookmanager;
2996
2997 $result = '';
2998
2999 if ($option == 'withdraw') {
3000 $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer';
3001 } elseif ($option == 'document') {
3002 $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
3003 } else {
3004 $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
3005 }
3006
3007 if ($short) {
3008 return $url;
3009 }
3010
3011 if ($option !== 'nolink') {
3012 // Add param to save lastsearch_values or not
3013 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3014 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3015 $add_save_lastsearch_values = 1;
3016 }
3017 if ($add_save_lastsearch_values) {
3018 $url .= '&save_lastsearch_values=1';
3019 }
3020 }
3021
3022 $picto = $this->picto;
3023 if ($this->type == self::TYPE_REPLACEMENT) {
3024 $picto .= 'r'; // Replacement invoice
3025 }
3026 if ($this->type == self::TYPE_CREDIT_NOTE) {
3027 $picto .= 'a'; // Credit note
3028 }
3029 if ($this->type == self::TYPE_DEPOSIT) {
3030 $picto .= 'd'; // Deposit invoice
3031 }
3032
3033 $params = [
3034 'id' => $this->id,
3035 'objecttype' => $this->element,
3036 'option' => $option,
3037 'moretitle' => $moretitle,
3038 ];
3039 $classfortooltip = 'classfortooltip';
3040 $dataparams = '';
3041 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3042 $classfortooltip = 'classforajaxtooltip';
3043 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3044 $label = '';
3045 } else {
3046 $label = $this->getTooltipContent($params);
3047 }
3048
3049 $ref = $this->ref;
3050 if (empty($ref)) {
3051 $ref = $this->id;
3052 }
3053
3054 $linkclose = '';
3055 if (empty($notooltip)) {
3056 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3057 $label = $langs->trans("ShowSupplierInvoice");
3058 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3059 }
3060 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3061 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
3062 }
3063
3064 $linkstart = '<a href="'.$url.'"';
3065 $linkstart .= $linkclose.'>';
3066 $linkend = '</a>';
3067
3068 $result .= $linkstart;
3069 if ($withpicto) {
3070 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
3071 }
3072 if ($withpicto != 2) {
3073 $result .= ($max ? dol_trunc($ref, $max) : $ref);
3074 }
3075 $result .= $linkend;
3076
3077 if ($addlinktonotes) {
3078 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
3079 if ($txttoshow) {
3080 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
3081 $result .= ' <span class="note inline-block">';
3082 $result .= '<a href="'.DOL_URL_ROOT.'/fourn/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
3083 $result .= img_picto('', 'note');
3084 $result .= '</a>';
3085 $result .= '</span>';
3086 }
3087 }
3088 global $action;
3089 $hookmanager->initHooks(array($this->element . 'dao'));
3090 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
3091 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3092 if ($reshook > 0) {
3093 $result = $hookmanager->resPrint;
3094 } else {
3095 $result .= $hookmanager->resPrint;
3096 }
3097 return $result;
3098 }
3099
3110 public function setCategories($categories)
3111 {
3112 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3113 return parent::setCategoriesCommon($categories, Categorie::TYPE_SUPPLIER_INVOICE);
3114 }
3115
3124 public function getNextNumRef($soc, $mode = 'next')
3125 {
3126 global $langs, $conf;
3127 $langs->load("orders");
3128
3129 // Clean parameters (if not defined or using deprecated value)
3130 if (!getDolGlobalString('INVOICE_SUPPLIER_ADDON_NUMBER')) {
3131 $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus';
3132 }
3133
3134 $mybool = false;
3135
3136 $file = getDolGlobalString('INVOICE_SUPPLIER_ADDON_NUMBER') . ".php";
3137 $classname = getDolGlobalString('INVOICE_SUPPLIER_ADDON_NUMBER');
3138
3139 // Include file with class
3140 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3141
3142 foreach ($dirmodels as $reldir) {
3143 $dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
3144
3145 // Load file with numbering class (if found)
3146 $mybool = ((bool) @include_once $dir.$file) || $mybool;
3147 }
3148
3149 if (!$mybool) {
3150 dol_print_error(null, "Failed to include file ".$file);
3151 return '';
3152 }
3153
3154 $obj = new $classname();
3155 '@phan-var-force ModeleNumRefSuppliersInvoices $obj';
3156 $numref = "";
3157 $numref = $obj->getNextValue($soc, $this, $mode);
3158
3159 if ($numref != "") {
3160 return $numref;
3161 } else {
3162 $this->error = $obj->error;
3163 return -1;
3164 }
3165 }
3166
3167
3176 public function initAsSpecimen($option = '')
3177 {
3178 global $langs, $conf;
3179 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3180
3181 $now = dol_now();
3182
3183 // Load array of products prodids
3184 $num_prods = 0;
3185 $prodids = array();
3186
3187 $sql = "SELECT rowid";
3188 $sql .= " FROM ".MAIN_DB_PREFIX."product";
3189 $sql .= " WHERE entity IN (".getEntity('product').")";
3190 $sql .= $this->db->plimit(100);
3191
3192 $resql = $this->db->query($sql);
3193 if ($resql) {
3194 $num_prods = $this->db->num_rows($resql);
3195 $i = 0;
3196 while ($i < $num_prods) {
3197 $i++;
3198 $row = $this->db->fetch_row($resql);
3199 $prodids[$i] = $row[0];
3200 }
3201 }
3202
3203 // Initialise parameters
3204 $this->id = 0;
3205 $this->ref = 'SPECIMEN';
3206 $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
3207 $this->specimen = 1;
3208 $this->socid = 1;
3209 $this->date = $now;
3210 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
3211 $this->cond_reglement_code = 'RECEP';
3212 $this->mode_reglement_code = 'CHQ';
3213
3214 $this->note_public = 'This is a comment (public)';
3215 $this->note_private = 'This is a comment (private)';
3216
3217 $this->multicurrency_tx = 1;
3218 $this->multicurrency_code = $conf->currency;
3219
3220 $xnbp = 0;
3221 if (empty($option) || $option != 'nolines') {
3222 // Lines
3223 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
3224 while ($xnbp < $nbp) {
3225 $line = new SupplierInvoiceLine($this->db);
3226 $line->desc = $langs->trans("Description")." ".$xnbp;
3227 $line->qty = 1;
3228 $line->subprice = 100;
3229 $line->price = 100;
3230 $line->tva_tx = 19.6;
3231 $line->localtax1_tx = 0;
3232 $line->localtax2_tx = 0;
3233 if ($xnbp == 2) {
3234 $line->total_ht = 50;
3235 $line->total_ttc = 59.8;
3236 $line->total_tva = 9.8;
3237 $line->remise_percent = 50;
3238 } else {
3239 $line->total_ht = 100;
3240 $line->total_ttc = 119.6;
3241 $line->total_tva = 19.6;
3242 $line->remise_percent = 0;
3243 }
3244
3245 if ($num_prods > 0) {
3246 $prodid = mt_rand(1, $num_prods);
3247 $line->fk_product = $prodids[$prodid];
3248 }
3249 $line->product_type = 0;
3250
3251 $this->lines[$xnbp] = $line;
3252
3253 $this->total_ht += $line->total_ht;
3254 $this->total_tva += $line->total_tva;
3255 $this->total_ttc += $line->total_ttc;
3256
3257 $xnbp++;
3258 }
3259 }
3260
3261 $this->total_ht = $xnbp * 100;
3262 $this->total_tva = $xnbp * 19.6;
3263 $this->total_ttc = $xnbp * 119.6;
3264
3265 return 1;
3266 }
3267
3273 public function loadStateBoard()
3274 {
3275 global $conf, $user;
3276
3277 $this->nb = array();
3278
3279 $clause = "WHERE";
3280
3281 $sql = "SELECT count(f.rowid) as nb";
3282 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
3283 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
3284 if (empty($user->socid) && !$user->hasRight("societe", "client", "voir")) {
3285 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3286 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3287 $clause = "AND";
3288 }
3289 $sql .= " ".$clause." f.entity = ".((int) $conf->entity);
3290
3291 $resql = $this->db->query($sql);
3292 if ($resql) {
3293 while ($obj = $this->db->fetch_object($resql)) {
3294 $this->nb["supplier_invoices"] = $obj->nb;
3295 }
3296 $this->db->free($resql);
3297 return 1;
3298 } else {
3299 dol_print_error($this->db);
3300 $this->error = $this->db->error();
3301 return -1;
3302 }
3303 }
3304
3313 public function createFromClone(User $user, $fromid, $invertdetail = 0)
3314 {
3315 global $langs, $hookmanager;
3316
3317 $error = 0;
3318
3319 $object = new FactureFournisseur($this->db);
3320
3321 $this->db->begin();
3322
3323 // Load source object
3324 $object->fetch($fromid);
3325 $objFrom = clone $object;
3326
3327 $object->id = 0;
3328 $object->statut = self::STATUS_DRAFT; // For backward compatibility
3329 $object->status = self::STATUS_DRAFT;
3330
3331 $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor
3332
3333 // Clear fields
3334 $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier);
3335 $object->author = $user->id; // FIXME? user_validation_id is replacement for author
3336 $object->user_validation_id = 0; // FIXME? user_validation_id is replacement for author
3337 $object->fk_facture_source = 0;
3338 $object->date_creation = '';
3339 $object->date_validation = '';
3340 $object->date = (empty($this->date) ? dol_now() : $this->date);
3341 $object->ref_client = '';
3342 $object->close_code = '';
3343 $object->close_note = '';
3344 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
3345 $object->note_private = '';
3346 $object->note_public = '';
3347 }
3348
3349 $object->date_echeance = $object->calculate_date_lim_reglement();
3350
3351 // Loop on each line of new invoice
3352 foreach ($object->lines as $i => $line) {
3353 if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
3354 unset($object->lines[$i]);
3355 }
3356 }
3357
3358 // Create clone
3359 $object->context['createfromclone'] = 'createfromclone';
3360 $result = $object->create($user);
3361
3362 // Other options
3363 if ($result < 0) {
3364 $this->error = $object->error;
3365 $this->errors = $object->errors;
3366 $error++;
3367 }
3368
3369 if (!$error) {
3370 // Hook of thirdparty module
3371 if (is_object($hookmanager)) {
3372 $parameters = array('objFrom' => $objFrom);
3373 $action = '';
3374 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
3375 if ($reshook < 0) {
3376 $this->setErrorsFromObject($hookmanager);
3377 $error++;
3378 }
3379 }
3380 }
3381
3382 unset($object->context['createfromclone']);
3383
3384 // End
3385 if (!$error) {
3386 $this->db->commit();
3387 return $object->id;
3388 } else {
3389 $this->db->rollback();
3390 return -1;
3391 }
3392 }
3393
3405 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3406 {
3407 global $langs;
3408
3409 $langs->load("suppliers");
3410 $outputlangs->load("products");
3411
3412 // Set the model on the model name to use
3413 if (empty($modele)) {
3414 if (getDolGlobalString('INVOICE_SUPPLIER_ADDON_PDF')) {
3415 $modele = getDolGlobalString('INVOICE_SUPPLIER_ADDON_PDF');
3416 } else {
3417 $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation
3418 }
3419 } elseif ($modele == 'auto') {
3420 $modele = 'canelle';
3421 }
3422
3423 if (empty($modele)) {
3424 return 0;
3425 } else {
3426 $modelpath = "core/modules/supplier_invoice/doc/";
3427
3428 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3429 }
3430 }
3431
3439 public function hasUserPermission(User $user, $mode = 'write')
3440 {
3441 if ($mode == 'create') {
3442 $mode = 'write';
3443 }
3444 if (!in_array($mode, array('read', 'write', 'delete'))) {
3445 return false;
3446 }
3447
3448 return (bool) $user->hasRight("fournisseur", "facture", $mode);
3449 }
3450
3459 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3460 {
3461 $tables = array(
3462 'facture_fourn'
3463 );
3464
3465 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3466 }
3467
3476 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
3477 {
3478 $tables = array(
3479 'facture_fourn_det'
3480 );
3481
3482 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
3483 }
3484
3490 public function hasDelay()
3491 {
3492 global $conf;
3493
3494 $now = dol_now();
3495
3496 if (!$this->date_echeance) {
3497 return false;
3498 }
3499
3500 $status = isset($this->status) ? $this->status : $this->statut;
3501
3502 return ($status == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay));
3503 }
3504
3510 public function isCreditNoteUsed()
3511 {
3512 $isUsed = false;
3513
3514 $sql = "SELECT fk_invoice_supplier FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_invoice_supplier_source = ".((int) $this->id);
3515 $resql = $this->db->query($sql);
3516 if (!empty($resql)) {
3517 $obj = $this->db->fetch_object($resql);
3518 if (!empty($obj->fk_invoice_supplier)) {
3519 $isUsed = true;
3520 }
3521 }
3522
3523 return $isUsed;
3524 }
3532 public function getKanbanView($option = '', $arraydata = null)
3533 {
3534 global $langs;
3535
3536 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3537
3538 $picto = $this->picto;
3539 if ($this->type == self::TYPE_REPLACEMENT) {
3540 $picto .= 'r'; // Replacement invoice
3541 }
3542 if ($this->type == self::TYPE_CREDIT_NOTE) {
3543 $picto .= 'a'; // Credit note
3544 }
3545 if ($this->type == self::TYPE_DEPOSIT) {
3546 $picto .= 'd'; // Deposit invoice
3547 }
3548
3549 $return = '<div class="box-flex-item box-flex-grow-zero">';
3550 $return .= '<div class="info-box info-box-sm">';
3551 $return .= '<span class="info-box-icon bg-infobox-action">';
3552 $return .= img_picto('', $picto);
3553 $return .= '</span>';
3554 $return .= '<div class="info-box-content">';
3555 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl(1) . '</span>';
3556 if ($selected >= 0) {
3557 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3558 }
3559 if (!empty($arraydata['thirdparty'])) {
3560 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
3561 }
3562 if (!empty($this->date)) {
3563 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
3564 }
3565 if (!empty($this->total_ht)) {
3566 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
3567 $return .= ' '.$langs->trans("HT");
3568 $return .= '</span>';
3569 }
3570 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
3571 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
3572
3573 $return .= '</div>';
3574 $return .= '</div>';
3575 $return .= '</div>';
3576
3577 return $return;
3578 }
3579
3586 public function setVATReverseCharge($vatreversecharge)
3587 {
3588 if (!$this->table_element) {
3589 dol_syslog(get_class($this)."::setVATReverseCharge was called on object with property table_element not defined", LOG_ERR);
3590 return -1;
3591 }
3592
3593 dol_syslog(get_class($this).'::setVATReverseCharge('.$vatreversecharge.')');
3594
3595 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3596 $sql .= " SET vat_reverse_charge = ".((int) $vatreversecharge);
3597 $sql .= " WHERE rowid=".((int) $this->id);
3598
3599 if ($this->db->query($sql)) {
3600 $this->vat_reverse_charge = ($vatreversecharge == 0) ? 0 : 1;
3601 return 1;
3602 } else {
3603 dol_syslog(get_class($this).'::setVATReverseCharge Error ', LOG_DEBUG);
3604 $this->error = $this->db->error();
3605 return 0;
3606 }
3607 }
3608
3621 public function sendEmailsRemindersOnSupplierInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = 'internalfollowingcontact')
3622 {
3623 global $conf, $langs, $user;
3624
3625 $this->output = '';
3626 $this->error = '';
3627 $nbMailSend = 0;
3628
3629 $error = 0;
3630 $errorsMsg = array();
3631
3632 $langs->load('bills');
3633
3634 if (!isModEnabled(!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') ? 'fournisseur' : 'supplier_invoice')) { // Should not happen. If module disabled, cron job should not be visible.
3635 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv('Suppliers'));
3636 return 0;
3637 }
3638 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
3639 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
3640 return 0;
3641 }
3642
3643 // Build list of forced recipients (separator is ';' because cron splits parameters on ',')
3644 $arrayforcerecipient = array();
3645 foreach (explode(';', (string) $forcerecipient) as $tmpvalue) {
3646 $tmpvalue = trim($tmpvalue);
3647 if ($tmpvalue !== '') {
3648 if (!in_array($tmpvalue, array('thirdpartyemail', 'internalfollowingcontact', 'salesrepresentative')) && !isValidEmail($tmpvalue)) {
3649 $this->output .= 'Bad value "'.$tmpvalue.'" for parameter forcerecipient. Must be an email, "thirdpartyemail", "internalfollowingcontact" or "salesrepresentative"';
3650 return 0;
3651 }
3652 $arrayforcerecipient[] = $tmpvalue;
3653 }
3654 }
3655 if (empty($arrayforcerecipient)) {
3656 $this->output .= 'Parameter forcerecipient is mandatory. Must be a list of values separated by ";" among an email, "thirdpartyemail", "internalfollowingcontact" or "salesrepresentative"';
3657 return 0;
3658 }
3659 $forcerecipient = implode(';', $arrayforcerecipient);
3660
3661 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3662 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3663 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3664 $formmail = new FormMail($this->db);
3665
3666 $now = dol_now();
3667 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
3668
3669 $tmpinvoice = new FactureFournisseur($this->db);
3670
3671 // Label of the event recorded once a reminder is sent. It is also used to not send the same reminder twice the same day.
3672 $labelreminderok = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
3673
3674 dol_syslog(__METHOD__." start", LOG_INFO);
3675
3676 // Select all action comm reminder
3677 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture_fourn as f";
3678 if (!empty($paymentmode) && $paymentmode != 'all') {
3679 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
3680 }
3681 $sql .= " WHERE f.paye = 0"; // Only unpaid
3682 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
3683 if ($datetouse == 'invoicedate') {
3684 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
3685 } else {
3686 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
3687 }
3688 $sql .= " AND f.entity IN (".getEntity('supplier_invoice', 0).")"; // One batch process only one company (no sharing)
3689 if (!empty($paymentmode) && $paymentmode != 'all') {
3690 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
3691 }
3692 $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // A credit note is not something to pay
3693 $sql .= " AND f.total_ttc > 0";
3694 // Exclude invoices for which the same reminder was already sent today
3695 $sql .= " AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX."actioncomm as a";
3696 $sql .= " WHERE a.elementtype = 'invoice_supplier' AND a.fk_element = f.rowid AND a.code = 'AC_EMAIL'";
3697 $sql .= " AND a.label = '".$this->db->escape($labelreminderok)."'";
3698 $sql .= " AND a.datep >= '".$this->db->idate(dol_get_first_hour($now))."')";
3699 if ($datetouse == 'invoicedate') {
3700 $sql .= $this->db->order("datef", "ASC");
3701 } else {
3702 $sql .= $this->db->order("date_lim_reglement", "ASC");
3703 }
3704
3705 $resql = $this->db->query($sql);
3706
3707 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
3708 if ($datetouse == 'invoicedate') {
3709 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedSupplierInvoicesWithDate", $stmpidate);
3710 } else {
3711 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidSupplierInvoicesWithDueDate", $stmpidate);
3712 }
3713 if (!empty($paymentmode) && $paymentmode != 'all') {
3714 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
3715 }
3716 $this->output .= '<br>';
3717
3718 if ($resql) {
3719 while ($obj = $this->db->fetch_object($resql)) {
3720 $errorforinvoice = 0; // An error on one invoice must not prevent to process the next ones
3721 // Load event
3722 $res = $tmpinvoice->fetch($obj->id);
3723 if ($res > 0) {
3724 $tmpinvoice->fetch_thirdparty();
3725
3726 $outputlangs = new Translate('', $conf);
3727 if ($tmpinvoice->thirdparty->default_lang) {
3728 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
3729 $outputlangs->loadLangs(array("main", "suppliers"));
3730 } else {
3731 $outputlangs = $langs;
3732 }
3733
3734 // Select email template according to language of recipient
3735 $templateId = 0;
3736 $templateLabel = '';
3737 if (empty($template) || $template == 'EmailTemplateCode') {
3738 $templateLabel = '(SendingReminderEmailOnUnpaidSupplierInvoice)';
3739 } else {
3740 if (is_numeric($template)) {
3741 $templateId = $template;
3742 } else {
3743 $templateLabel = $template;
3744 }
3745 }
3746
3747 $arraymessage = $formmail->getEMailTemplate($this->db, 'invoice_supplier_send', $user, $outputlangs, $templateId, 1, $templateLabel);
3748 if (is_numeric($arraymessage) && $arraymessage <= 0) {
3749 $langs->load("errors");
3750 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
3751 return 0;
3752 }
3753
3754 // PREPARE EMAIL
3755 $errormesg = '';
3756
3757 // Make substitution in email content
3758 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $tmpinvoice);
3759
3760 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
3761
3762 // Topic
3763 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
3764
3765 // Content
3766 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
3767
3768 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
3769
3770 // Recipient
3771 $to = array();
3772 $res = $tmpinvoice->fetch_thirdparty();
3773 $recipient = $tmpinvoice->thirdparty;
3774 if ($res > 0) {
3775 foreach ($arrayforcerecipient as $tmpforcerecipient) {
3776 if ($tmpforcerecipient == 'thirdpartyemail') {
3777 if (!empty($recipient->email)) {
3778 $to[] = $recipient->email;
3779 }
3780 } elseif ($tmpforcerecipient == 'internalfollowingcontact') {
3781 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'internal', 0, 'SALESREPFOLL');
3782 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
3783 foreach ($tmparraycontact as $data_email) {
3784 if (!empty($data_email['email'])) {
3785 $to[] = $data_email['email'];
3786 }
3787 }
3788 }
3789 } elseif ($tmpforcerecipient == 'salesrepresentative') {
3790 $tmparraysalesrep = $recipient->getSalesRepresentatives($user);
3791 if (is_array($tmparraysalesrep)) {
3792 foreach ($tmparraysalesrep as $salesrep) {
3793 if (!empty($salesrep['email']) && !empty($salesrep['status'])) {
3794 $to[] = $salesrep['email'];
3795 }
3796 }
3797 }
3798 } else { // A fixed email
3799 $to[] = $tmpforcerecipient;
3800 }
3801 }
3802 $to = array_values(array_unique(array_filter($to)));
3803 if (empty($to)) {
3804 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email found for recipients ".$forcerecipient.".";
3805 $error++;
3806 $errorforinvoice++;
3807 }
3808 } else {
3809 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
3810 $error++;
3811 $errorforinvoice++;
3812 }
3813
3814 // Sender
3815 $email_from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
3816 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
3817 $email_from = (string) $arraymessage->email_from;
3818 }
3819 if (empty($email_from)) {
3820 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
3821 $error++;
3822 $errorforinvoice++;
3823 }
3824
3825 if (!$errorforinvoice && !empty($to)) {
3826 $this->db->begin();
3827
3828 $to = implode(',', $to);
3829 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
3830 $to = $to.','.$arraymessage->email_to;
3831 }
3832
3833 // Errors Recipient
3834 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
3835
3836 $trackid = 'inv'.$tmpinvoice->id;
3837 $sendcontext = 'standard';
3838
3839 $email_tocc = '';
3840 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
3841 $email_tocc = (string) $arraymessage->email_tocc;
3842 }
3843
3844 $email_tobcc = '';
3845 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
3846 $email_tobcc = (string) $arraymessage->email_tobcc;
3847 }
3848
3849 // Mail Creation
3850 $cMailFile = new CMailFile($sendTopic, $to, $email_from, $sendContent, array(), array(), array(), $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
3851
3852 // Sending Mail
3853 if ($cMailFile->sendfile()) {
3854 $nbMailSend++;
3855
3856 // Add a line into event table
3857 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3858
3859 // Insert record of emails sent
3860 $actioncomm = new ActionComm($this->db);
3861
3862 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
3863 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
3864 $actioncomm->contact_id = 0;
3865
3866 $actioncomm->code = 'AC_EMAIL';
3867 $actioncomm->label = $labelreminderok;
3868 $actioncomm->note_private = $sendContent;
3869 $actioncomm->fk_project = $tmpinvoice->fk_project;
3870 $actioncomm->datep = dol_now();
3871 $actioncomm->datef = $actioncomm->datep;
3872 $actioncomm->percentage = -1; // Not applicable
3873 $actioncomm->authorid = $user->id; // User saving action
3874 $actioncomm->userownerid = $user->id; // Owner of action
3875 // Fields when action is an email (content should be added into note)
3876 $actioncomm->email_msgid = $cMailFile->msgid;
3877 $actioncomm->email_subject = $sendTopic;
3878 $actioncomm->email_from = $email_from;
3879 $actioncomm->email_sender = '';
3880 $actioncomm->email_to = $to;
3881 //$actioncomm->email_tocc = $sendtocc;
3882 //$actioncomm->email_tobcc = $sendtobcc;
3883 //$actioncomm->email_subject = $subject;
3884 $actioncomm->errors_to = $errors_to;
3885
3886 $actioncomm->elementtype = 'invoice_supplier';
3887 $actioncomm->elementid = $tmpinvoice->id;
3888 $actioncomm->fk_element = $tmpinvoice->id;
3889
3890 //$actioncomm->extraparams = $extraparams;
3891
3892 $actioncomm->create($user);
3893 } else {
3894 $errormesg = $cMailFile->error.' : '.$to;
3895 $error++;
3896 $errorforinvoice++;
3897
3898 // Add a line into event table
3899 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3900
3901 // Insert record of emails sent
3902 $actioncomm = new ActionComm($this->db);
3903
3904 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
3905 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
3906 $actioncomm->contact_id = 0;
3907
3908 $actioncomm->code = 'AC_EMAIL';
3909 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
3910 $actioncomm->note_private = $errormesg;
3911 $actioncomm->fk_project = $tmpinvoice->fk_project;
3912 $actioncomm->datep = dol_now();
3913 $actioncomm->datef = $actioncomm->datep;
3914 $actioncomm->percentage = -1; // Not applicable
3915 $actioncomm->authorid = $user->id; // User saving action
3916 $actioncomm->userownerid = $user->id; // Owner of action
3917 // Fields when action is an email (content should be added into note)
3918 $actioncomm->email_msgid = $cMailFile->msgid;
3919 $actioncomm->email_from = $email_from;
3920 $actioncomm->email_sender = '';
3921 $actioncomm->email_to = $to;
3922 //$actioncomm->email_tocc = $sendtocc;
3923 //$actioncomm->email_tobcc = $sendtobcc;
3924 //$actioncomm->email_subject = $subject;
3925 $actioncomm->errors_to = $errors_to;
3926
3927 //$actioncomm->extraparams = $extraparams;
3928
3929 $actioncomm->create($user);
3930 }
3931
3932 $this->db->commit(); // We always commit
3933 }
3934
3935 if ($errormesg) {
3936 $errorsMsg[] = $errormesg;
3937 }
3938 } else {
3939 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
3940 $error++;
3941 }
3942 }
3943 } else {
3944 $error++;
3945 }
3946
3947 if (!$error) {
3948 $this->output .= 'Nb of emails sent : '.$nbMailSend;
3949
3950 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
3951
3952 return 0;
3953 } else {
3954 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(empty($errorsMsg) ? $error : implode(', ', $errorsMsg));
3955
3956 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
3957
3958 return $error;
3959 }
3960 }
3961}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
checkPointOfTaxNotChanged()
Check that the point of tax date of a validated invoice is not changed by an update.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage suppliers invoices.
const TYPE_DEPOSIT
Deposit invoice.
create($user)
Create supplier invoice into database.
list_qualified_avoir_supplier_invoices($socid=0)
Return list of qualifying invoices for correction by credit note Invoices that respect the following ...
list_replacable_supplier_invoices($socid=0)
Return list of replaceable invoices Status valid or abandoned for other reason + not paid + no paymen...
deleteLine($rowid, $notrigger=0)
Delete a detail line from database.
set_unpaid($user)
Tag the invoice as not fully paid + trigger call BILL_UNPAYED Function used when a direct debit payme...
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
fetch($id=0, $ref='', $ref_ext='')
Load object in memory from database.
setCategories($categories)
Sets object to given categories.
info($id)
Loads the info order information into the invoice object.
const TYPE_CREDIT_NOTE
Credit note invoice.
isCreditNoteUsed()
Is credit note used.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card before printObjectLines() and formAdd...
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0)
Return clickable name (with optional picto)
getTooltipContentArray($params)
getTooltipContentArray
setPaid($user, $close_code='', $close_note='')
Tag invoice as a paid invoice.
update($user=null, $notrigger=0)
Update database.
addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start=0, $date_end=0, $fk_code_ventilation=0, $info_bits=0, $price_base_type='HT', $type=0, $rang=-1, $notrigger=0, $array_options=[], $fk_unit=null, $origin_id=0, $pu_devise=0, $ref_supplier='', $special_code=0, $fk_parent_line=0, $fk_remise_except=0, $origin_type='')
Adds an invoice line (associated with no predefined product/service) The parameters are already suppo...
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
const TYPE_REPLACEMENT
Replacement invoice.
sendEmailsRemindersOnSupplierInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='internalfollowingcontact')
Send reminders by emails for supplier invoices validated that are due.
setUnpaid($user)
Tag the invoice as not fully paid + trigger call BILL_UNPAYED Function used when a direct debit payme...
const STATUS_VALIDATED
Validated (need to be paid)
setDraft($user, $idwarehouse=-1, $notrigger=0)
Set draft status.
getNextNumRef($soc, $mode='next')
Return next reference of supplier invoice not already used (or last reference) according to numbering...
updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=0, $date_start='', $date_end='', $array_options=[], $fk_unit=null, $pu_devise=0, $ref_supplier='', $rang=0)
Update a line detail in the database.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
initAsSpecimen($option='')
Initialise an instance with random values.
const TYPE_STANDARD
Standard invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
Tag invoice as validated + call trigger BILL_VALIDATE.
set_paid($user, $close_code='', $close_note='')
Tag invoice as a paid invoice.
createFromClone(User $user, $fromid, $invertdetail=0)
Load an object from its id and create a new one in database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template model.
const STATUS_ABANDONED
Classified abandoned and no payment done.
hasDelay()
Is the payment of the supplier invoice having a delay?
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
hasUserPermission(User $user, $mode='write')
Check if user has a permission on supplier invoices.
const STATUS_CLOSED
Classified paid.
setVATReverseCharge($vatreversecharge)
Change the option VAT reverse charge.
Class to manage invoice templates.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage "other" html components Only common components are here.
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage line invoices.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:686
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492