dolibarr 21.0.0-beta
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-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
14 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
15 * Copyright (C) 2018-2024 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 MDW <mdeweerd@users.noreply.github.com>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
41require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
42require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.ligne.class.php';
43require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
44
45if (isModEnabled('accounting')) {
46 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
47 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
48}
49
54{
58 public $element = 'invoice_supplier';
59
63 public $table_element = 'facture_fourn';
64
68 public $table_element_line = 'facture_fourn_det';
69
73 public $class_element_line = 'SupplierInvoiceLine';
77 public $fk_element = 'fk_facture_fourn';
78
82 public $picto = 'supplier_invoice';
83
88 public $restrictiononfksoc = 1;
89
93 protected $table_ref_field = 'ref';
94
98 public $rowid;
99
103 public $ref;
104
108 public $ref_supplier;
109
114 public $libelle;
118 public $label;
119
120 //Check constants for types
121 public $type = self::TYPE_STANDARD;
122
129 public $statut;
130
136 public $status;
137
144 public $fk_statut;
145
151 public $paye;
156 public $paid;
157
162 public $author;
163
169 public $datec;
170
176 public $date_echeance;
177
182 public $amount = 0;
187 public $remise = 0;
188
193 public $tva;
194
195 // Warning: Do not set default value into property definition. it must stay null.
196 // For example to avoid to have substitution done when object is generic and not yet defined.
198 public $localtax1;
200 public $localtax2;
202 public $total_ht;
204 public $total_tva;
206 public $total_localtax1;
208 public $total_localtax2;
210 public $total_ttc;
211
217 public $note;
219 public $note_private;
221 public $note_public;
223 public $propalid;
224
228 public $fk_account; // default bank account
229
233 public $transport_mode_id;
234
238 public $vat_reverse_charge;
239
243 public $extraparams = array();
244
249 public $lines = array();
250
255 public $fournisseur;
256
258
261 public $fk_facture_source;
262
264 public $fac_rec;
266 public $fk_fac_rec_source;
267
268 public $fields = array(
269 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
270 'ref' => array('type' => 'varchar(255)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 15),
271 'ref_supplier' => array('type' => 'varchar(255)', 'label' => 'RefSupplier', 'enabled' => 1, 'visible' => -1, 'position' => 20),
272 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 25, 'index' => 1),
273 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 30),
274 'type' => array('type' => 'smallint(6)', 'label' => 'Type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 35),
275 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 36),
276 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 40),
277 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 45),
278 'datef' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => -1, 'position' => 50),
279 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 55),
280 'libelle' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => -1, 'position' => 60),
281 'paye' => array('type' => 'smallint(6)', 'label' => 'Paye', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 65),
282 'amount' => array('type' => 'double(24,8)', 'label' => 'Amount', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 70),
283 'remise' => array('type' => 'double(24,8)', 'label' => 'Discount', 'enabled' => 1, 'visible' => -1, 'position' => 75),
284 'close_code' => array('type' => 'varchar(16)', 'label' => 'CloseCode', 'enabled' => 1, 'visible' => -1, 'position' => 80),
285 'close_note' => array('type' => 'varchar(128)', 'label' => 'CloseNote', 'enabled' => 1, 'visible' => -1, 'position' => 85),
286 'tva' => array('type' => 'double(24,8)', 'label' => 'Tva', 'enabled' => 1, 'visible' => -1, 'position' => 90),
287 'localtax1' => array('type' => 'double(24,8)', 'label' => 'Localtax1', 'enabled' => 1, 'visible' => -1, 'position' => 95),
288 'localtax2' => array('type' => 'double(24,8)', 'label' => 'Localtax2', 'enabled' => 1, 'visible' => -1, 'position' => 100),
289 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 105),
290 'total_tva' => array('type' => 'double(24,8)', 'label' => 'TotalVAT', 'enabled' => 1, 'visible' => -1, 'position' => 110),
291 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 115),
292 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 125),
293 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 130),
294 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 135),
295 'fk_facture_source' => array('type' => 'integer', 'label' => 'Fk facture source', 'enabled' => 1, 'visible' => -1, 'position' => 140),
296 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 145),
297 'fk_account' => array('type' => 'integer', 'label' => 'Account', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 150),
298 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 155),
299 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 160),
300 'date_lim_reglement' => array('type' => 'date', 'label' => 'DateLimReglement', 'enabled' => 1, 'visible' => -1, 'position' => 165),
301 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 170),
302 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 175),
303 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPdf', 'enabled' => 1, 'visible' => 0, 'position' => 180),
304 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 190),
305 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 1, 'visible' => -1, 'position' => 195),
306 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLocation', 'enabled' => 1, 'visible' => -1, 'position' => 200),
307 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyId', 'enabled' => 1, 'visible' => -1, 'position' => 205),
308 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCode', 'enabled' => 1, 'visible' => -1, 'position' => 210),
309 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 1, 'visible' => -1, 'position' => 215),
310 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyTotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 220),
311 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyTotalVAT', 'enabled' => 1, 'visible' => -1, 'position' => 225),
312 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyTotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 230),
313 'date_pointoftax' => array('type' => 'date', 'label' => 'Date pointoftax', 'enabled' => 1, 'visible' => -1, 'position' => 235),
314 'date_valid' => array('type' => 'date', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 240),
315 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'Last main doc', 'enabled' => 1, 'visible' => -1, 'position' => 245),
316 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500),
317 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
318 );
319
320
324 public $fk_user_valid;
325
329 const TYPE_STANDARD = 0;
330
335
340
344 const TYPE_DEPOSIT = 3;
345
349 const STATUS_DRAFT = 0;
350
355
363 const STATUS_CLOSED = 2;
364
373
374 const CLOSECODE_DISCOUNTVAT = 'discount_vat';
375 const CLOSECODE_BADCREDIT = 'badsupplier';
376 const CLOSECODE_ABANDONED = 'abandon';
377 const CLOSECODE_REPLACED = 'replaced';
378
384 public function __construct($db)
385 {
386 $this->db = $db;
387
388 $this->ismultientitymanaged = 1;
389 }
390
397 public function create($user)
398 {
399 global $langs, $conf, $hookmanager;
400
401 $error = 0;
402 $now = dol_now();
403
404 // Clean parameters
405 if (isset($this->ref_supplier)) {
406 $this->ref_supplier = trim($this->ref_supplier);
407 }
408 if (empty($this->type)) {
409 $this->type = self::TYPE_STANDARD;
410 }
411 if (empty($this->date)) {
412 $this->date = $now;
413 }
414
415 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
416 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
417 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
418 } else {
419 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
420 }
421 if (empty($this->fk_multicurrency)) {
422 $this->multicurrency_code = $conf->currency;
423 $this->fk_multicurrency = 0;
424 $this->multicurrency_tx = 1;
425 }
426 $this->entity = setEntity($this);
427
428 $this->db->begin();
429
430 // Defaults
431 $originaldatewhen = 0;
432 $nextdatewhen = 0;
433 $previousdaynextdatewhen = 0;
434 $_facrec = null;
435
436 // Create invoice from a template recurring invoice
437 if ($this->fac_rec > 0) {
438 $this->fk_fac_rec_source = $this->fac_rec;
439
440 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture-rec.class.php';
441 $_facrec = new FactureFournisseurRec($this->db);
442 $result = $_facrec->fetch($this->fac_rec);
443 $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
444
445 // Define some dates
446 if (!empty($_facrec->frequency)) {
447 $originaldatewhen = $_facrec->date_when;
448 $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
449 $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
450 $this->socid = $_facrec->socid;
451 }
452
453 $this->entity = $_facrec->entity; // Invoice created in same entity than template
454
455 // Fields coming from GUI
456 // @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
457 // set by posted page with $object->xxx = ... and this section should be removed.
458 $this->fk_project = GETPOSTINT('projectid') > 0 ? (GETPOSTINT('projectid')) : $_facrec->fk_project;
459 $this->note_public = GETPOST('note_public', 'restricthtml') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
460 $this->note_private = GETPOST('note_private', 'restricthtml') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
461 $this->model_pdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
462 $this->cond_reglement_id = GETPOSTINT('cond_reglement_id') > 0 ? (GETPOSTINT('cond_reglement_id')) : $_facrec->cond_reglement_id;
463 $this->mode_reglement_id = GETPOSTINT('mode_reglement_id') > 0 ? (GETPOSTINT('mode_reglement_id')) : $_facrec->mode_reglement_id;
464 $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
465
466 // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
467 $this->total_ht = $_facrec->total_ht;
468 $this->total_ttc = $_facrec->total_ttc;
469
470 // Fields always coming from template
471 $this->fk_incoterms = $_facrec->fk_incoterms;
472 $this->location_incoterms = $_facrec->location_incoterms;
473
474 // Clean parameters
475 if (! $this->type) {
476 $this->type = self::TYPE_STANDARD;
477 }
478 $this->note_public = trim($this->note_public);
479 $this->note_private = trim($this->note_private);
480 $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->title));
481
482 $this->array_options = $_facrec->array_options;
483
484 if (! $this->mode_reglement_id) {
485 $this->mode_reglement_id = 0;
486 }
487 $this->status = self::STATUS_DRAFT;
488 $this->statut = self::STATUS_DRAFT; // deprecated
489
490 $this->linked_objects = $_facrec->linkedObjectsIds;
491 // We do not add link to template invoice or next invoice will be linked to all generated invoices
492 //$this->linked_objects['facturerec'][0] = $this->fac_rec;
493
494 $forceduedate = $this->calculate_date_lim_reglement();
495
496 // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
497 if ($_facrec->frequency > 0) {
498 $this->ref_supplier = trim($this->ref_supplier . '_' . ($_facrec->nb_gen_done + 1));
499 dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
500 if (empty($_facrec->date_when)) {
501 $_facrec->date_when = $now;
502 }
503 $next_date = $_facrec->getNextDate(); // Calculate next date
504 $result = $_facrec->setValueFrom('date_last_gen', $now, '', 0, 'date', '', $user, '');
505 //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
506 $result = $_facrec->setNextDate($next_date, 1);
507 }
508
509 // Define lang of customer
510 $outputlangs = $langs;
511 $newlang = '';
512
513 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
514 $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
515 }
516 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($this, 'default_lang') && isset($this->default_lang)) { // @phan-suppress-current-line PhanUndeclaredProperty
517 $newlang = $this->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
518 }
519 if (!empty($newlang)) {
520 $outputlangs = new Translate("", $conf);
521 $outputlangs->setDefaultLang($newlang);
522 } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
523 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
524 $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
525 $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
526 $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
527 $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
528 $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
529 $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
530 $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
531 $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
532 $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'); // Only for template invoice
533 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $originaldatewhen ? dol_print_date($originaldatewhen, 'dayhour') : '';
534 $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $nextdatewhen ? dol_print_date($nextdatewhen, 'dayhour') : '';
535 $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = $previousdaynextdatewhen ? dol_print_date($previousdaynextdatewhen, 'dayhour') : '';
536 $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
537 $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
538
539 complete_substitutions_array($substitutionarray, $outputlangs);
540
541 $this->note_public = make_substitutions($this->note_public, $substitutionarray);
542 $this->note_private = make_substitutions($this->note_private, $substitutionarray);
543 }
544
545 // Define due date if not already defined
546 if (!empty($forceduedate)) {
547 $this->date_echeance = $forceduedate;
548 }
549
550 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
551 $sql .= "ref";
552 $sql .= ", ref_supplier";
553 $sql .= ", ref_ext";
554 $sql .= ", entity";
555 $sql .= ", type";
556 $sql .= ", subtype";
557 $sql .= ", libelle";
558 $sql .= ", fk_soc";
559 $sql .= ", datec";
560 $sql .= ", datef";
561 $sql .= ", vat_reverse_charge";
562 $sql .= ", fk_projet";
563 $sql .= ", fk_cond_reglement";
564 $sql .= ", fk_mode_reglement";
565 $sql .= ", fk_account";
566 $sql .= ", note_private";
567 $sql .= ", note_public";
568 $sql .= ", fk_user_author";
569 $sql .= ", date_lim_reglement";
570 $sql .= ", fk_incoterms, location_incoterms";
571 $sql .= ", fk_multicurrency";
572 $sql .= ", multicurrency_code";
573 $sql .= ", multicurrency_tx";
574 $sql .= ", fk_facture_source";
575 $sql .= ", fk_fac_rec_source";
576 $sql .= ")";
577 $sql .= " VALUES (";
578 $sql .= "'(PROV)'";
579 $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
580 $sql .= ", '".$this->db->escape($this->ref_ext)."'";
581 $sql .= ", ".((int) $this->entity);
582 $sql .= ", '".$this->db->escape($this->type)."'";
583 $sql .= ", ".((int) $this->subtype);
584 $sql .= ", '".$this->db->escape(isset($this->label) ? $this->label : (isset($this->libelle) ? $this->libelle : ''))."'";
585 $sql .= ", ".((int) $this->socid);
586 $sql .= ", '".$this->db->idate($now)."'";
587 $sql .= ", '".$this->db->idate($this->date)."'";
588 $sql .= ", ".($this->vat_reverse_charge != '' ? ((int) $this->db->escape($this->vat_reverse_charge)) : 0);
589 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
590 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
591 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
592 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
593 $sql .= ", '".$this->db->escape($this->note_private)."'";
594 $sql .= ", '".$this->db->escape($this->note_public)."'";
595 $sql .= ", ".((int) $user->id).",";
596 $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null";
597 $sql .= ", ".(int) $this->fk_incoterms;
598 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
599 $sql .= ", ".(int) $this->fk_multicurrency;
600 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
601 $sql .= ", ".(float) $this->multicurrency_tx;
602 $sql .= ", ".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null");
603 $sql .= ", ".(isset($this->fk_fac_rec_source) ? $this->fk_fac_rec_source : "NULL");
604 $sql .= ")";
605
606 dol_syslog(get_class($this)."::create", LOG_DEBUG);
607 $resql = $this->db->query($sql);
608 if ($resql) {
609 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
610
611 // Update ref with new one
612 $this->ref = '(PROV'.$this->id.')';
613 $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
614
615 dol_syslog(get_class($this)."::create", LOG_DEBUG);
616 $resql = $this->db->query($sql);
617 if (!$resql) {
618 $error++;
619 }
620
621 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
622 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
623 }
624
625 // Add object linked
626 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
627 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
628 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, ...))
629 foreach ($tmp_origin_id as $origin_id) {
630 $ret = $this->add_object_linked($origin, $origin_id);
631 if (!$ret) {
632 dol_print_error($this->db);
633 $error++;
634 }
635 }
636 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
637 $origin_id = $tmp_origin_id;
638 $ret = $this->add_object_linked($origin, $origin_id);
639 if (!$ret) {
640 dol_print_error($this->db);
641 $error++;
642 }
643 }
644 }
645 }
646
647 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
648 dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
649 foreach ($this->lines as $i => $val) {
650 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code, fk_remise_except)';
651 $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').')';
652
653 $resql_insert = $this->db->query($sql);
654 if ($resql_insert) {
655 $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
656
657 $res = $this->updateline(
658 $idligne,
659 $this->lines[$i]->desc ? $this->lines[$i]->desc : $this->lines[$i]->description,
660 $this->lines[$i]->subprice,
661 $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''),
662 $this->lines[$i]->localtax1_tx,
663 $this->lines[$i]->localtax2_tx,
664 $this->lines[$i]->qty,
665 $this->lines[$i]->fk_product,
666 'HT',
667 (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''),
668 $this->lines[$i]->product_type,
669 $this->lines[$i]->remise_percent,
670 0,
671 $this->lines[$i]->date_start,
672 $this->lines[$i]->date_end,
673 $this->lines[$i]->array_options,
674 $this->lines[$i]->fk_unit,
675 $this->lines[$i]->multicurrency_subprice,
676 $this->lines[$i]->ref_supplier
677 );
678 } else {
679 $this->error = $this->db->lasterror();
680 $this->db->rollback();
681 return -5;
682 }
683 }
684 } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
685 dol_syslog("There is ".count($this->lines)." lines that are array lines");
686 foreach ($this->lines as $i => $val) {
687 $line = $this->lines[$i];
688
689 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
690 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
691 if (!is_object($line)) {
692 $line = (object) $line;
693 }
694
695 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code, fk_remise_except)';
696 $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').')';
697
698 $resql_insert = $this->db->query($sql);
699 if ($resql_insert) {
700 $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
701
702 $this->updateline(
703 $idligne,
704 $line->desc ? $line->desc : $line->description,
705 $line->subprice,
706 $line->tva_tx,
707 $line->localtax1_tx,
708 $line->localtax2_tx,
709 $line->qty,
710 $line->fk_product,
711 'HT',
712 (!empty($line->info_bits) ? $line->info_bits : ''),
713 $line->product_type,
714 $line->remise_percent,
715 0,
716 $line->date_start,
717 $line->date_end,
718 $line->array_options,
719 $line->fk_unit,
720 $line->multicurrency_subprice,
721 $line->ref_supplier
722 );
723 } else {
724 $this->error = $this->db->lasterror();
725 $this->db->rollback();
726 return -5;
727 }
728 }
729 }
730
731 /*
732 * Insert lines of template invoices
733 */
734 if (! $error && $this->fac_rec > 0 && $_facrec instanceof FactureFournisseurRec) {
735 foreach ($_facrec->lines as $i => $val) {
736 if ($_facrec->lines[$i]->fk_product) {
737 $prod = new Product($this->db);
738 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
739 }
740
741 // For line from template invoice, we use data from template invoice
742 /*
743 $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
744 $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
745 if (empty($tva_tx)) $tva_npr=0;
746 $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
747 $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
748 */
749 $tva_tx = $_facrec->lines[$i]->tva_tx . ($_facrec->lines[$i]->vat_src_code ? '(' . $_facrec->lines[$i]->vat_src_code . ')' : '');
750 $tva_npr = $_facrec->lines[$i]->info_bits;
751 if (empty($tva_tx)) {
752 $tva_npr = 0;
753 }
754 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
755 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
756
757 // $fk_product_fournisseur_price not used and does not exist on line
758 // $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
759 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
760
761 // If buyprice not defined from template invoice, we try to guess the best value
762 if (! $buyprice && $_facrec->lines[$i]->fk_product > 0) {
763 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
764 $producttmp = new ProductFournisseur($this->db);
765 $producttmp->fetch($_facrec->lines[$i]->fk_product);
766
767 // If margin module defined on costprice, we try the costprice
768 // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
769 // else we get the best supplier price
770 if (getDolGlobalString('MARGIN_TYPE') == 'costprice' && !empty($producttmp->cost_price)) {
771 $buyprice = $producttmp->cost_price;
772 } elseif (isModEnabled('stock') && (getDolGlobalString('MARGIN_TYPE') == 'costprice' || getDolGlobalString('MARGIN_TYPE') == 'pmp') && !empty($producttmp->pmp)) {
773 $buyprice = $producttmp->pmp;
774 } else {
775 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
776 if ($producttmp->product_fourn_price_id > 0) {
777 $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
778 }
779 }
780 }
781 }
782
783 $result_insert = $this->addline(
784 $_facrec->lines[$i]->desc ? $_facrec->lines[$i]->desc : $_facrec->lines[$i]->description,
785 $_facrec->lines[$i]->pu_ht,
786 $tva_tx,
787 $localtax1_tx,
788 $localtax2_tx,
789 $_facrec->lines[$i]->qty,
790 $_facrec->lines[$i]->fk_product,
791 $_facrec->lines[$i]->remise_percent,
792 ($_facrec->lines[$i]->date_start == 1 && $this->date) ? $this->date : '',
793 ($_facrec->lines[$i]->date_end == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
794 0,
795 $_facrec->lines[$i]->info_bits,
796 'HT',
797 0,
798 $_facrec->lines[$i]->rang,
799 0,
800 $_facrec->lines[$i]->array_options,
801 $_facrec->lines[$i]->fk_unit,
802 0,
803 0,
804 $_facrec->lines[$i]->ref_supplier,
805 $_facrec->lines[$i]->special_code,
806 0,
807 0
808 );
809 if ($result_insert < 0) {
810 $error++;
811 $this->error = $this->db->error();
812 break;
813 }
814 }
815 }
816
817
818 // Update total price
819 $result = $this->update_price(1);
820 if ($result > 0) {
821 // Actions on extra fields
822 if (!$error) {
823 $result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found
824 if ($result < 0) {
825 $error++;
826 }
827 }
828
829 if (!$error) {
830 // Call trigger
831 $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user);
832 if ($result < 0) {
833 $error++;
834 }
835 // End call triggers
836 }
837
838 if (!$error) {
839 $this->db->commit();
840 return $this->id;
841 } else {
842 $this->db->rollback();
843 return -4;
844 }
845 } else {
846 $this->error = $langs->trans('FailedToUpdatePrice');
847 $this->db->rollback();
848 return -3;
849 }
850 } else {
851 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
852 $this->error = $langs->trans('ErrorRefAlreadyExists');
853 $this->db->rollback();
854 return -1;
855 } else {
856 $this->error = $this->db->lasterror();
857 $this->db->rollback();
858 return -2;
859 }
860 }
861 }
862
871 public function fetch($id = 0, $ref = '', $ref_ext = '')
872 {
873 if (empty($id) && empty($ref) && empty($ref_ext)) {
874 return -1;
875 }
876
877 $sql = "SELECT";
878 $sql .= " t.rowid,";
879 $sql .= " t.ref,";
880 $sql .= " t.ref_supplier,";
881 $sql .= " t.ref_ext,";
882 $sql .= " t.entity,";
883 $sql .= " t.type,";
884 $sql .= " t.subtype,";
885 $sql .= " t.fk_soc,";
886 $sql .= " t.datec,";
887 $sql .= " t.datef,";
888 $sql .= " t.tms,";
889 $sql .= " t.libelle as label,";
890 $sql .= " t.paye,";
891 $sql .= " t.close_code,";
892 $sql .= " t.close_note,";
893 $sql .= " t.tva,";
894 $sql .= " t.localtax1,";
895 $sql .= " t.localtax2,";
896 $sql .= " t.total_ht,";
897 $sql .= " t.total_tva,";
898 $sql .= " t.total_ttc,";
899 $sql .= " t.fk_statut as status,";
900 $sql .= " t.fk_user_author,";
901 $sql .= " t.fk_user_valid,";
902 $sql .= " t.fk_facture_source,";
903 $sql .= " t.vat_reverse_charge,";
904 $sql .= " t.fk_fac_rec_source,";
905 $sql .= " t.fk_projet as fk_project,";
906 $sql .= " t.fk_cond_reglement,";
907 $sql .= " t.fk_account,";
908 $sql .= " t.fk_mode_reglement,";
909 $sql .= " t.date_lim_reglement,";
910 $sql .= " t.note_private,";
911 $sql .= " t.note_public,";
912 $sql .= " t.model_pdf,";
913 $sql .= " t.last_main_doc,";
914 $sql .= " t.import_key,";
915 $sql .= " t.extraparams,";
916 $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,";
917 $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_label,";
918 $sql .= ' s.nom as socnom, s.rowid as socid,';
919 $sql .= ' t.fk_incoterms, t.location_incoterms,';
920 $sql .= " i.libelle as label_incoterms,";
921 $sql .= ' t.fk_transport_mode,';
922 $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
923 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
924 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
925 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid";
926 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id";
927 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
928 if ($id) {
929 $sql .= " WHERE t.rowid = ".((int) $id);
930 } else {
931 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')'; // Don't use entity if you use rowid
932 if ($ref) {
933 $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
934 }
935 if ($ref_ext) {
936 $sql .= " AND t.ref_ext = '".$this->db->escape($ref_ext)."'";
937 }
938 }
939
940 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
941 $resql = $this->db->query($sql);
942 if ($resql) {
943 if ($this->db->num_rows($resql)) {
944 $obj = $this->db->fetch_object($resql);
945
946 $this->id = $obj->rowid;
947 $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility
948
949 $this->ref_supplier = $obj->ref_supplier;
950 $this->ref_ext = $obj->ref_ext;
951 $this->entity = $obj->entity;
952 $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type;
953 $this->subtype = (int) $obj->subtype;
954 $this->socid = $obj->fk_soc;
955 $this->datec = $this->db->jdate($obj->datec);
956 $this->date = $this->db->jdate($obj->datef);
957 //$this->datep = $this->db->jdate($obj->datef);
958 $this->tms = $this->db->jdate($obj->tms);
959 $this->libelle = $obj->label; // deprecated
960 $this->label = $obj->label;
961 $this->paye = $obj->paye;
962 $this->paid = $obj->paye;
963 $this->close_code = $obj->close_code;
964 $this->close_note = $obj->close_note;
965 $this->total_localtax1 = $obj->localtax1;
966 $this->total_localtax2 = $obj->localtax2;
967 $this->total_ht = $obj->total_ht;
968 $this->total_tva = $obj->total_tva;
969 $this->total_ttc = $obj->total_ttc;
970 $this->status = $obj->status;
971 $this->statut = $obj->status; // For backward compatibility
972 $this->fk_statut = $obj->status; // For backward compatibility
973 $this->user_creation_id = $obj->fk_user_author;
974 $this->author = $obj->fk_user_author; // deprecated
975 $this->user_validation_id = $obj->fk_user_valid;
976 $this->fk_facture_source = $obj->fk_facture_source;
977 $this->vat_reverse_charge = empty($obj->vat_reverse_charge) ? 0 : 1;
978 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
979 $this->fk_project = $obj->fk_project;
980 $this->cond_reglement_id = $obj->fk_cond_reglement;
981 $this->cond_reglement_code = $obj->cond_reglement_code;
982 $this->cond_reglement = $obj->cond_reglement_label; // deprecated
983 $this->cond_reglement_label = $obj->cond_reglement_label;
984 $this->cond_reglement_doc = $obj->cond_reglement_doc;
985 $this->fk_account = $obj->fk_account;
986 $this->mode_reglement_id = $obj->fk_mode_reglement;
987 $this->mode_reglement_code = $obj->mode_reglement_code;
988 $this->mode_reglement = $obj->mode_reglement_label;
989 $this->date_echeance = $this->db->jdate($obj->date_lim_reglement);
990 $this->note = $obj->note_private; // deprecated
991 $this->note_private = $obj->note_private;
992 $this->note_public = $obj->note_public;
993 $this->model_pdf = $obj->model_pdf;
994 $this->last_main_doc = $obj->last_main_doc;
995 $this->import_key = $obj->import_key;
996
997 //Incoterms
998 $this->fk_incoterms = $obj->fk_incoterms;
999 $this->location_incoterms = $obj->location_incoterms;
1000 $this->label_incoterms = $obj->label_incoterms;
1001 $this->transport_mode_id = $obj->fk_transport_mode;
1002
1003 // Multicurrency
1004 $this->fk_multicurrency = $obj->fk_multicurrency;
1005 $this->multicurrency_code = $obj->multicurrency_code;
1006 $this->multicurrency_tx = $obj->multicurrency_tx;
1007 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1008 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1009 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1010
1011 $this->extraparams = isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
1012
1013 $this->socid = $obj->socid;
1014
1015 // Retrieve all extrafield
1016 // fetch optionals attributes and labels
1017 $this->fetch_optionals();
1018
1019 $result = $this->fetch_lines();
1020 if ($result < 0) {
1021 $this->error = $this->db->lasterror();
1022 return -3;
1023 }
1024 } else {
1025 $this->error = 'Bill with id '.$id.' not found';
1026 dol_syslog(get_class($this).'::fetch '.$this->error);
1027 return 0;
1028 }
1029
1030 $this->db->free($resql);
1031 return 1;
1032 } else {
1033 $this->error = "Error ".$this->db->lasterror();
1034 return -1;
1035 }
1036 }
1037
1038
1039 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1045 public function fetch_lines()
1046 {
1047 // phpcs:enable
1048 $this->lines = array();
1049
1050 $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';
1051 $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';
1052 $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';
1053 $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';
1054 $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';
1055 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
1056 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
1057 $sql .= ' WHERE fk_facture_fourn='.((int) $this->id);
1058 $sql .= ' ORDER BY f.rang, f.rowid';
1059
1060 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1061
1062 $resql_rows = $this->db->query($sql);
1063 if ($resql_rows) {
1064 $num_rows = $this->db->num_rows($resql_rows);
1065 if ($num_rows) {
1066 $i = 0;
1067 while ($i < $num_rows) {
1068 $obj = $this->db->fetch_object($resql_rows);
1069
1070 $line = new SupplierInvoiceLine($this->db);
1071
1072 $line->id = $obj->rowid;
1073 $line->rowid = $obj->rowid;
1074 $line->description = $obj->line_desc;
1075 $line->desc = $obj->line_desc;
1076 $line->date_start = $obj->date_start;
1077 $line->date_end = $obj->date_end;
1078 $line->product_ref = $obj->product_ref;
1079 $line->ref = $obj->product_ref;
1080 $line->ref_supplier = $obj->ref_supplier;
1081 $line->libelle = $obj->label;
1082 $line->label = $obj->label;
1083 $line->product_barcode = $obj->product_barcode;
1084 $line->product_desc = $obj->product_desc;
1085 $line->subprice = $obj->pu_ht;
1086 $line->pu_ht = $obj->pu_ht;
1087 $line->pu_ttc = $obj->pu_ttc;
1088 $line->vat_src_code = $obj->vat_src_code;
1089 $line->tva_tx = $obj->tva_tx;
1090 $line->localtax1_tx = $obj->localtax1_tx;
1091 $line->localtax2_tx = $obj->localtax2_tx;
1092 $line->localtax1_type = $obj->localtax1_type;
1093 $line->localtax2_type = $obj->localtax2_type;
1094 $line->qty = $obj->qty;
1095 $line->remise_percent = $obj->remise_percent;
1096 $line->fk_remise_except = $obj->fk_remise_except;
1097 //$line->tva = $obj->total_tva; // deprecated
1098 $line->total_ht = $obj->total_ht;
1099 $line->total_ttc = $obj->total_ttc;
1100 $line->total_tva = $obj->total_tva;
1101 $line->total_localtax1 = $obj->total_localtax1;
1102 $line->total_localtax2 = $obj->total_localtax2;
1103 $line->fk_facture_fourn = $obj->fk_facture_fourn;
1104 $line->fk_product = $obj->fk_product;
1105 $line->product_type = $obj->product_type;
1106 $line->product_label = $obj->label;
1107 $line->info_bits = $obj->info_bits;
1108 $line->fk_parent_line = $obj->fk_parent_line;
1109 $line->special_code = $obj->special_code;
1110 $line->rang = $obj->rang;
1111 $line->fk_unit = $obj->fk_unit;
1112
1113 // Accountancy
1114 $line->fk_accounting_account = $obj->fk_code_ventilation;
1115
1116 // Multicurrency
1117 $line->fk_multicurrency = $obj->fk_multicurrency;
1118 $line->multicurrency_code = $obj->multicurrency_code;
1119 $line->multicurrency_subprice = $obj->multicurrency_subprice;
1120 $line->multicurrency_total_ht = $obj->multicurrency_total_ht;
1121 $line->multicurrency_total_tva = $obj->multicurrency_total_tva;
1122 $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1123
1124 // Extra fields
1125 $line->fetch_optionals();
1126
1127 $this->lines[$i] = $line;
1128
1129 $i++;
1130 }
1131 }
1132 $this->db->free($resql_rows);
1133 return 1;
1134 } else {
1135 $this->error = $this->db->error();
1136 dol_syslog(get_class($this)."::fetch_lines - No lines:{$this->error} Error:{$this->error}", LOG_DEBUG);
1137 return -3;
1138 }
1139 }
1140
1141
1149 public function update($user = null, $notrigger = 0)
1150 {
1151 global $langs;
1152 $error = 0;
1153
1154 // Clean parameters
1155 if (empty($this->type)) {
1156 $this->type = self::TYPE_STANDARD;
1157 }
1158 if (isset($this->ref)) {
1159 $this->ref = trim($this->ref);
1160 }
1161 if (isset($this->ref_supplier)) {
1162 $this->ref_supplier = trim($this->ref_supplier);
1163 }
1164 if (isset($this->ref_ext)) {
1165 $this->ref_ext = trim($this->ref_ext);
1166 }
1167 if (isset($this->entity)) {
1168 $this->entity = (int) $this->entity;
1169 }
1170 if (isset($this->type)) {
1171 $this->type = (int) $this->type;
1172 }
1173 if (isset($this->subtype)) {
1174 $this->subtype = (int) $this->subtype;
1175 }
1176 if (isset($this->socid)) {
1177 $this->socid = (int) $this->socid;
1178 }
1179 if (isset($this->label)) {
1180 $this->label = trim($this->label);
1181 }
1182 if (isset($this->paid)) {
1183 $this->paid = (int) (bool) $this->paye;
1184 $this->paye = $this->paid;
1185 } elseif (isset($this->paye)) {
1186 $this->paid = (int) (bool) $this->paye;
1187 $this->paye = $this->paid;
1188 }
1189 if (isset($this->close_code)) {
1190 $this->close_code = trim($this->close_code);
1191 }
1192 if (isset($this->close_note)) {
1193 $this->close_note = trim($this->close_note);
1194 }
1195 if (empty($this->total_ht)) {
1196 $this->total_ht = 0;
1197 }
1198 if (empty($this->total_tva)) {
1199 $this->total_tva = 0;
1200 }
1201 if (empty($this->total_localtax1)) {
1202 $this->total_localtax1 = 0;
1203 }
1204 if (empty($this->total_localtax2)) {
1205 $this->total_localtax2 = 0;
1206 }
1207 if (isset($this->total_ttc)) {
1208 $this->total_ttc = (float) $this->total_ttc;
1209 }
1210 if (isset($this->status)) {
1211 $this->status = (int) $this->status;
1212 $this->statut = $this->status;
1213 } elseif (isset($this->statut)) {
1214 $this->status = (int) $this->statut;
1215 $this->statut = $this->status;
1216 }
1217 if (isset($this->author)) { // TODO: user_creation_id?
1218 $this->author = (int) $this->author;
1219 }
1220 if (isset($this->fk_user_valid)) {
1221 $this->fk_user_valid = (int) $this->fk_user_valid;
1222 }
1223 if (isset($this->fk_facture_source)) {
1224 $this->fk_facture_source = (int) $this->fk_facture_source;
1225 }
1226 if (isset($this->fk_project)) {
1227 if (empty($this->fk_project)) {
1228 $this->fk_project = 0;
1229 } else {
1230 $this->fk_project = (int) $this->fk_project;
1231 }
1232 }
1233 if (isset($this->cond_reglement_id)) {
1234 $this->cond_reglement_id = (int) $this->cond_reglement_id;
1235 }
1236 if (isset($this->note_private)) {
1237 $this->note_private = trim($this->note_private);
1238 $this->note = $this->note_private;
1239 }
1240 if (isset($this->note_public)) {
1241 $this->note_public = trim($this->note_public);
1242 }
1243 if (isset($this->model_pdf)) {
1244 $this->model_pdf = trim($this->model_pdf);
1245 }
1246 if (isset($this->import_key)) {
1247 $this->import_key = trim($this->import_key);
1248 }
1249
1250
1251 // Check parameters
1252 // Put here code to add control on parameters values
1253
1254 // Update request
1255 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
1256 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1257 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1258 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1259 $sql .= " entity=".(isset($this->entity) ? ((int) $this->entity) : "null").",";
1260 $sql .= " type=".(isset($this->type) ? ((int) $this->type) : "null").",";
1261 $sql .= " subtype=".((int) $this->subtype).",";
1262 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
1263 $sql .= " datec=".(dol_strlen((string) $this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
1264 $sql .= " datef=".(dol_strlen((string) $this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
1265 if (dol_strlen((string) $this->tms) != 0) {
1266 $sql .= " tms=".(dol_strlen((string) $this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
1267 }
1268 $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
1269 $sql .= " paye=".(isset($this->paid) ? ((int) $this->paid) : "0").",";
1270 $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
1271 $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
1272 $sql .= " localtax1=".(isset($this->total_localtax1) ? ((float) $this->total_localtax1) : "null").",";
1273 $sql .= " localtax2=".(isset($this->total_localtax2) ? ((float) $this->total_localtax2) : "null").",";
1274 $sql .= " total_ht=".(isset($this->total_ht) ? ((float) $this->total_ht) : "null").",";
1275 $sql .= " total_tva=".(isset($this->total_tva) ? ((float) $this->total_tva) : "null").",";
1276 $sql .= " total_ttc=".(isset($this->total_ttc) ? ((float) $this->total_ttc) : "null").",";
1277 $sql .= " fk_statut=".(isset($this->status) ? ((int) $this->status) : (isset($this->statut) ? ((int) $this->statut) : "null")).",";
1278 $sql .= " fk_user_author=".(isset($this->author) ? ((int) $this->author) : "null").",";
1279 $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? ((int) $this->fk_user_valid) : "null").",";
1280 $sql .= " fk_facture_source=".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null").",";
1281 $sql .= " vat_reverse_charge = ".($this->vat_reverse_charge != '' ? ((int) $this->db->escape($this->vat_reverse_charge)) : 0).",";
1282 $sql .= " fk_projet=".(!empty($this->fk_project) ? ((int) $this->fk_project) : "null").",";
1283 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? ((int) $this->cond_reglement_id) : "null").",";
1284 $sql .= " date_lim_reglement=".(dol_strlen((string) $this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
1285 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1286 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1287 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1288 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1289 $sql .= " WHERE rowid=".((int) $this->id);
1290
1291 $this->db->begin();
1292
1293 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1294 $resql = $this->db->query($sql);
1295
1296 if (!$resql) {
1297 $error++;
1298
1299 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1300 $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
1301 } else {
1302 $this->errors[] = "Error ".$this->db->lasterror();
1303 }
1304 }
1305
1306 if (!$error) {
1307 $result = $this->insertExtraFields();
1308 if ($result < 0) {
1309 $error++;
1310 }
1311 }
1312
1313 if (!$error) {
1314 if (!$notrigger) {
1315 // Call trigger
1316 $result = $this->call_trigger('BILL_SUPPLIER_MODIFY', $user);
1317 if ($result < 0) {
1318 $error++;
1319 }
1320 // End call triggers
1321 }
1322 }
1323
1324 // Commit or rollback
1325 if ($error) {
1326 foreach ($this->errors as $errmsg) {
1327 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1328 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1329 }
1330 $this->db->rollback();
1331 return -1 * $error;
1332 } else {
1333 $this->db->commit();
1334 return 1;
1335 }
1336 }
1337
1338 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1345 public function insert_discount($idremise)
1346 {
1347 // phpcs:enable
1348 global $conf, $langs;
1349
1350 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1351 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1352
1353 $this->db->begin();
1354
1355 $remise = new DiscountAbsolute($this->db);
1356 $result = $remise->fetch($idremise);
1357
1358 if ($result > 0) {
1359 if ($remise->fk_invoice_supplier) { // Protection against multiple submission
1360 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
1361 $this->db->rollback();
1362 return -5;
1363 }
1364
1365 $facligne = new SupplierInvoiceLine($this->db);
1366 $facligne->fk_facture_fourn = $this->id;
1367 $facligne->fk_remise_except = $remise->id;
1368 $facligne->desc = $remise->description; // Description ligne
1369 $facligne->vat_src_code = $remise->vat_src_code;
1370 $facligne->tva_tx = $remise->tva_tx;
1371 $facligne->subprice = -(float) $remise->amount_ht;
1372 $facligne->fk_product = 0; // Id produit predefini
1373 $facligne->product_type = 0;
1374 $facligne->qty = 1;
1375 $facligne->remise_percent = 0;
1376 $facligne->rang = -1;
1377 $facligne->info_bits = 2;
1378
1379 if (getDolGlobalString('MAIN_ADD_LINE_AT_POSITION')) {
1380 $facligne->rang = 1;
1381 $linecount = count($this->lines);
1382 for ($ii = 1; $ii <= $linecount; $ii++) {
1383 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
1384 }
1385 }
1386
1387 // Get buy/cost price of invoice that is source of discount
1388 if ($remise->fk_invoice_supplier_source > 0) {
1389 $srcinvoice = new FactureFournisseur($this->db);
1390 $srcinvoice->fetch($remise->fk_invoice_supplier_source);
1391 $totalcostpriceofinvoice = 0;
1392 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
1393 $formmargin = new FormMargin($this->db);
1394 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
1395 $facligne->pa_ht = $arraytmp['pa_total'];
1396 }
1397
1398 $facligne->total_ht = -(float) $remise->amount_ht;
1399 $facligne->total_tva = -(float) $remise->amount_tva;
1400 $facligne->total_ttc = -(float) $remise->amount_ttc;
1401
1402 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
1403 $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht;
1404 $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva;
1405 $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc;
1406
1407 $lineid = $facligne->insert();
1408 if ($lineid > 0) {
1409 $result = $this->update_price(1);
1410 if ($result > 0) {
1411 // Create link between discount and invoice line
1412 $result = $remise->link_to_invoice($lineid, 0);
1413 if ($result < 0) {
1414 $this->error = $remise->error;
1415 $this->db->rollback();
1416 return -4;
1417 }
1418
1419 $this->db->commit();
1420 return 1;
1421 } else {
1422 $this->error = $facligne->error;
1423 $this->db->rollback();
1424 return -1;
1425 }
1426 } else {
1427 $this->error = $facligne->error;
1428 $this->db->rollback();
1429 return -2;
1430 }
1431 } else {
1432 $this->db->rollback();
1433 return -3;
1434 }
1435 }
1436
1437
1445 public function delete(User $user, $notrigger = 0)
1446 {
1447 global $conf;
1448
1449 $rowid = $this->id;
1450
1451 dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
1452
1453 // TODO Test if there is at least on payment. If yes, refuse to delete.
1454
1455 $error = 0;
1456 $this->db->begin();
1457
1458 if (!$error && !$notrigger) {
1459 // Call trigger
1460 $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user);
1461 if ($result < 0) {
1462 $this->db->rollback();
1463 return -1;
1464 }
1465 // Fin appel triggers
1466 }
1467
1468 if (!$error) {
1469 // If invoice was converted into a discount not yet consumed, we remove discount
1470 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
1471 $sql .= ' WHERE fk_invoice_supplier_source = '.((int) $rowid);
1472 $sql .= ' AND fk_invoice_supplier_line IS NULL';
1473 $resql = $this->db->query($sql);
1474
1475 // If invoice has consumned discounts
1476 $this->fetch_lines();
1477 $list_rowid_det = array();
1478 foreach ($this->lines as $key => $invoiceline) {
1479 $list_rowid_det[] = $invoiceline->id;
1480 }
1481
1482 // Consumned discounts are freed
1483 if (count($list_rowid_det)) {
1484 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
1485 $sql .= ' SET fk_invoice_supplier = NULL, fk_invoice_supplier_line = NULL';
1486 $sql .= ' WHERE fk_invoice_supplier_line IN ('.$this->db->sanitize(implode(',', $list_rowid_det)).')';
1487
1488 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1489 if (!$this->db->query($sql)) {
1490 $error++;
1491 }
1492 }
1493 }
1494
1495 if (!$error) {
1496 $main = MAIN_DB_PREFIX.'facture_fourn_det';
1497 $ef = $main."_extrafields";
1498 $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture_fourn = ".((int) $rowid).")";
1499 $resqlef = $this->db->query($sqlef);
1500 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.((int) $rowid);
1501 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1502 $resql = $this->db->query($sql);
1503 if ($resqlef && $resql) {
1504 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.((int) $rowid);
1505 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1506 $resql2 = $this->db->query($sql);
1507 if (!$resql2) {
1508 $error++;
1509 }
1510 } else {
1511 $error++;
1512 }
1513 }
1514
1515 if (!$error) {
1516 // Delete linked object
1517 $res = $this->deleteObjectLinked();
1518 if ($res < 0) {
1519 $error++;
1520 }
1521 }
1522
1523 if (!$error) {
1524 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
1525 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1526 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
1527
1528 // We remove directory
1529 if ($conf->fournisseur->facture->dir_output) {
1530 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1531
1532 $ref = dol_sanitizeFileName($this->ref);
1533 $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$ref;
1534 $file = $dir."/".$ref.".pdf";
1535 if (file_exists($file)) {
1536 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
1537 $this->error = 'ErrorFailToDeleteFile';
1538 $error++;
1539 }
1540 }
1541 if (file_exists($dir)) {
1542 $res = @dol_delete_dir_recursive($dir);
1543
1544 if (!$res) {
1545 $this->error = 'ErrorFailToDeleteDir';
1546 $error++;
1547 }
1548 }
1549 }
1550 }
1551
1552 // Remove extrafields
1553 if (!$error) {
1554 $result = $this->deleteExtraFields();
1555 if ($result < 0) {
1556 $error++;
1557 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1558 }
1559 }
1560
1561 if (!$error) {
1562 dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1563 $this->db->commit();
1564 return 1;
1565 } else {
1566 $this->error = $this->db->lasterror();
1567 $this->db->rollback();
1568 return -$error;
1569 }
1570 }
1571
1572
1573 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1584 public function set_paid($user, $close_code = '', $close_note = '')
1585 {
1586 // phpcs:enable
1587 dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
1588 return $this->setPaid($user, $close_code, $close_note);
1589 }
1590
1599 public function setPaid($user, $close_code = '', $close_note = '')
1600 {
1601 $error = 0;
1602
1603 if ($this->paid != 1) {
1604 $this->db->begin();
1605
1606 $now = dol_now();
1607
1608 dol_syslog("FactureFournisseur::setPaid", LOG_DEBUG);
1609
1610 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn SET';
1611 $sql .= ' fk_statut = '.self::STATUS_CLOSED;
1612 if (!$close_code) {
1613 $sql .= ', paye=1';
1614 }
1615 if ($close_code) {
1616 $sql .= ", close_code='".$this->db->escape($close_code)."'";
1617 }
1618 if ($close_note) {
1619 $sql .= ", close_note='".$this->db->escape($close_note)."'";
1620 }
1621 $sql .= ', fk_user_closing = '.((int) $user->id);
1622 $sql .= ", date_closing = '".$this->db->idate($now)."'";
1623 $sql .= ' WHERE rowid = '.((int) $this->id);
1624
1625 $resql = $this->db->query($sql);
1626 if ($resql) {
1627 // Call trigger
1628 $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user);
1629 if ($result < 0) {
1630 $error++;
1631 }
1632 // End call triggers
1633 } else {
1634 $error++;
1635 $this->error = $this->db->error();
1636 dol_print_error($this->db);
1637 }
1638
1639 if (!$error) {
1640 $this->db->commit();
1641 return 1;
1642 } else {
1643 $this->db->rollback();
1644 return -1;
1645 }
1646 } else {
1647 return 0;
1648 }
1649 }
1650
1651 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1662 public function set_unpaid($user)
1663 {
1664 // phpcs:enable
1665 dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
1666 return $this->setUnpaid($user);
1667 }
1668
1677 public function setUnpaid($user)
1678 {
1679 $error = 0;
1680
1681 $this->db->begin();
1682
1683 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
1684 $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
1685 $sql .= ' date_closing=null,';
1686 $sql .= ' fk_user_closing=null';
1687 $sql .= ' WHERE rowid = '.((int) $this->id);
1688
1689 dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
1690 $resql = $this->db->query($sql);
1691 if ($resql) {
1692 // Call trigger
1693 $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user);
1694 if ($result < 0) {
1695 $error++;
1696 }
1697 // End call triggers
1698 } else {
1699 $error++;
1700 $this->error = $this->db->error();
1701 dol_print_error($this->db);
1702 }
1703
1704 if (!$error) {
1705 $this->db->commit();
1706 return 1;
1707 } else {
1708 $this->db->rollback();
1709 return -1;
1710 }
1711 }
1712
1723 public function setCanceled($user, $close_code = '', $close_note = '')
1724 {
1725 dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
1726
1727 $this->db->begin();
1728
1729 $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn SET';
1730 $sql .= ' fk_statut='.self::STATUS_ABANDONED;
1731 if ($close_code) {
1732 $sql .= ", close_code='".$this->db->escape($close_code)."'";
1733 }
1734 if ($close_note) {
1735 $sql .= ", close_note='".$this->db->escape($close_note)."'";
1736 }
1737 $sql .= " WHERE rowid = ".((int) $this->id);
1738
1739 $resql = $this->db->query($sql);
1740 if ($resql) {
1741 // Bound discounts are deducted from the invoice
1742 // as they have not been used since the invoice is abandoned.
1743 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
1744 $sql .= ' SET fk_invoice_supplier = NULL';
1745 $sql .= ' WHERE fk_invoice_supplier = '.((int) $this->id);
1746
1747 $resql = $this->db->query($sql);
1748 if ($resql) {
1749 // Call trigger
1750 $result = $this->call_trigger('BILL_SUPPLIER_CANCEL', $user);
1751 if ($result < 0) {
1752 $this->db->rollback();
1753 return -1;
1754 }
1755 // End call triggers
1756
1757 $this->db->commit();
1758 return 1;
1759 } else {
1760 $this->error = $this->db->error()." sql=".$sql;
1761 $this->db->rollback();
1762 return -1;
1763 }
1764 } else {
1765 $this->error = $this->db->error()." sql=".$sql;
1766 $this->db->rollback();
1767 return -2;
1768 }
1769 }
1770
1780 public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1781 {
1782 global $mysoc, $conf, $langs;
1783
1784 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1785
1786 $now = dol_now();
1787
1788 $error = 0;
1789 dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
1790
1791 // Force to have object complete for checks
1792 $this->fetch_thirdparty();
1793 $this->fetch_lines();
1794
1795 // Check parameters
1796 if ($this->status > self::STATUS_DRAFT) { // This is to avoid to validate twice (avoid errors on logs and stock management)
1797 dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
1798 return 0;
1799 }
1800 if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier)) {
1801 $langs->load("errors");
1802 $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
1803 return -1;
1804 }
1805 if (count($this->lines) <= 0) {
1806 $langs->load("errors");
1807 $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
1808 return -1;
1809 }
1810
1811 // Check for mandatory fields in thirdparty (defined into setup)
1812 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
1813 $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'ACCOUNTANCY_CODE_SUPPLIER');
1814 foreach ($array_to_check as $key) {
1815 $keymin = strtolower($key);
1816 if ($keymin == 'accountancy_code_supplier') {
1817 $keymin = 'code_compta_fournisseur';
1818 }
1819 if (!property_exists($this->thirdparty, $keymin)) {
1820 continue;
1821 }
1822 $vallabel = $this->thirdparty->$keymin;
1823
1824 $i = (int) preg_replace('/[^0-9]/', '', $key);
1825 if ($i > 0) {
1826 if ($this->thirdparty->isACompany()) {
1827 // Check for mandatory prof id (but only if country is other than ours)
1828 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
1829 $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
1830 if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
1831 $langs->load("errors");
1832 $this->error = $langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $this->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
1833 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
1834 return -1;
1835 }
1836 }
1837 }
1838 } else {
1839 if ($key == 'EMAIL') {
1840 // Check for mandatory
1841 if (getDolGlobalString('SOCIETE_EMAIL_INVOICE_MANDATORY') && !isValidEmail($this->thirdparty->email)) {
1842 $langs->load("errors");
1843 $this->error = $langs->trans("ErrorBadEMail", $this->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").') ['.$langs->trans('Company').' : '.$this->thirdparty->name.']';
1844 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
1845 return -1;
1846 }
1847 } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') {
1848 // Check for mandatory
1849 if (getDolGlobalString('SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_fournisseur)) {
1850 $langs->load("errors");
1851 $this->error = $langs->trans("ErrorAccountancyCodeSupplierIsMandatory", $this->thirdparty->name).' ('.$langs->trans("ForbiddenBySetupRules").')';
1852 dol_syslog(__METHOD__.' '.$this->error, LOG_ERR);
1853 return -1;
1854 }
1855 }
1856 }
1857 }
1858 }
1859
1860 $this->db->begin();
1861
1862 // Define new ref
1863 if ($force_number) {
1864 $num = $force_number;
1865 } elseif (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1866 $num = $this->getNextNumRef($this->thirdparty);
1867 } else {
1868 $num = $this->ref;
1869 }
1870 $this->newref = dol_sanitizeFileName($num);
1871
1872 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
1873 $sql .= " SET ref='".$this->db->escape($num)."', fk_statut = 1, fk_user_valid = ".((int) $user->id).", date_valid = '".$this->db->idate($now)."'";
1874 $sql .= " WHERE rowid = ".((int) $this->id);
1875
1876 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
1877 $resql = $this->db->query($sql);
1878 if ($resql) {
1879 // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
1880 if (!$error && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
1881 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1882 $langs->load("agenda");
1883
1884 $cpt = count($this->lines);
1885 for ($i = 0; $i < $cpt; $i++) {
1886 if ($this->lines[$i]->fk_product > 0) {
1887 $mouvP = new MouvementStock($this->db);
1888 $mouvP->origin = &$this;
1889 $mouvP->setOrigin($this->element, $this->id);
1890 // We increase stock for product
1891 $up_ht_disc = $this->lines[$i]->subprice;
1892 if (!empty($this->lines[$i]->remise_percent) && !getDolGlobalString('STOCK_EXCLUDE_DISCOUNT_FOR_PMP')) {
1893 $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1894 }
1896 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
1897 } else {
1898 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
1899 }
1900 if ($result < 0) {
1901 $this->error = $mouvP->error;
1902 if (count($mouvP->errors)) {
1903 $this->errors = $mouvP->errors;
1904 }
1905 return -2;
1906 }
1907 }
1908 }
1909 }
1910
1911 // Triggers call
1912 if (!$error && empty($notrigger)) {
1913 // Call trigger
1914 $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user);
1915 if ($result < 0) {
1916 $error++;
1917 }
1918 // End call triggers
1919 }
1920
1921 if (!$error) {
1922 $this->oldref = $this->ref;
1923
1924 // Rename directory if dir was a temporary ref
1925 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1926 // Now we rename also files into index
1927 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'";
1928 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity;
1929 $resql = $this->db->query($sql);
1930 if (!$resql) {
1931 $error++;
1932 $this->error = $this->db->lasterror();
1933 }
1934 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'";
1935 $sql .= " WHERE filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity;
1936 $resql = $this->db->query($sql);
1937 if (!$resql) {
1938 $error++;
1939 $this->error = $this->db->lasterror();
1940 }
1941
1942 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1943 $oldref = dol_sanitizeFileName($this->ref);
1944 $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref;
1945 $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->newref;
1946 if (!$error && file_exists($dirsource)) {
1947 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
1948
1949 if (@rename($dirsource, $dirdest)) {
1950 dol_syslog("Rename ok");
1951 // Rename docs starting with $oldref with $this->newref
1952 $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, '/'));
1953 foreach ($listoffiles as $fileentry) {
1954 $dirsource = $fileentry['name'];
1955 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $this->newref, $dirsource);
1956 $dirsource = $fileentry['path'].'/'.$dirsource;
1957 $dirdest = $fileentry['path'].'/'.$dirdest;
1958 @rename($dirsource, $dirdest);
1959 }
1960 }
1961 }
1962 }
1963 }
1964
1965 // Set new ref and define current status
1966 if (!$error) {
1967 $this->ref = $this->newref;
1968 $this->statut = self::STATUS_VALIDATED;
1970 //$this->date_validation=$now; this is stored into log table
1971 }
1972
1973 if (!$error) {
1974 $this->db->commit();
1975 return 1;
1976 } else {
1977 $this->db->rollback();
1978 return -1;
1979 }
1980 } else {
1981 $this->error = $this->db->error();
1982 $this->db->rollback();
1983 return -1;
1984 }
1985 }
1986
1995 public function setDraft($user, $idwarehouse = -1, $notrigger = 0)
1996 {
1997 // phpcs:enable
1998 global $conf, $langs;
1999
2000 $error = 0;
2001
2002 if ($this->status == self::STATUS_DRAFT) {
2003 dol_syslog(__METHOD__." already draft status", LOG_WARNING);
2004 return 0;
2005 }
2006
2007 dol_syslog(__METHOD__, LOG_DEBUG);
2008
2009 $this->db->begin();
2010
2011 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
2012 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2013 $sql .= " WHERE rowid = ".((int) $this->id);
2014
2015 $result = $this->db->query($sql);
2016 if ($result) {
2017 if (!$error) {
2018 $this->oldcopy = clone $this;
2019 }
2020
2021 // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
2022 if ($result >= 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
2023 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2024 $langs->load("agenda");
2025
2026 $cpt = count($this->lines);
2027 for ($i = 0; $i < $cpt; $i++) {
2028 if ($this->lines[$i]->fk_product > 0) {
2029 $mouvP = new MouvementStock($this->db);
2030 $mouvP->origin = &$this;
2031 $mouvP->setOrigin($this->element, $this->id);
2032 // We increase stock for product
2034 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
2035 } else {
2036 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
2037 }
2038 }
2039 }
2040 }
2041 // Triggers call
2042 if (!$error && empty($notrigger)) {
2043 // Call trigger
2044 $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user);
2045 if ($result < 0) {
2046 $error++;
2047 }
2048 // End call triggers
2049 }
2050 if ($error == 0) {
2051 $this->db->commit();
2052 return 1;
2053 } else {
2054 $this->db->rollback();
2055 return -1;
2056 }
2057 } else {
2058 $this->error = $this->db->error();
2059 $this->db->rollback();
2060 return -1;
2061 }
2062 }
2063
2064
2098 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)
2099 {
2100 global $langs, $mysoc;
2101
2102 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);
2103 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2104
2105 if ($this->status == self::STATUS_DRAFT) {
2106 // Clean parameters
2107 if (empty($remise_percent)) {
2108 $remise_percent = 0;
2109 }
2110 if (empty($qty)) {
2111 $qty = 0;
2112 }
2113 if (empty($info_bits)) {
2114 $info_bits = 0;
2115 }
2116 if (empty($rang)) {
2117 $rang = 0;
2118 }
2119 if (empty($fk_code_ventilation)) {
2120 $fk_code_ventilation = 0;
2121 }
2122 if (empty($txtva)) {
2123 $txtva = 0;
2124 }
2125 if (empty($txlocaltax1)) {
2126 $txlocaltax1 = 0;
2127 }
2128 if (empty($txlocaltax2)) {
2129 $txlocaltax2 = 0;
2130 }
2131
2132 $remise_percent = price2num($remise_percent);
2133 $qty = price2num($qty);
2134 $pu = price2num($pu);
2135 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
2136 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
2137 }
2138 $txlocaltax1 = price2num($txlocaltax1);
2139 $txlocaltax2 = price2num($txlocaltax2);
2140
2141 if ($date_start && $date_end && $date_start > $date_end) {
2142 $langs->load("errors");
2143 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2144 return -1;
2145 }
2146
2147 $this->db->begin();
2148
2149 if ($fk_product > 0) {
2150 if (getDolGlobalInt('SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY') == 1) { // Not the common case
2151 // Check quantity is enough
2152 dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." qty=".$qty." ref_supplier=".$ref_supplier);
2153 $prod = new ProductFournisseur($this->db);
2154 if ($prod->fetch($fk_product) > 0) {
2155 $product_type = $prod->type;
2156 $label = $prod->label;
2157 $fk_prod_fourn_price = 0;
2158
2159 // We use 'none' instead of $ref_supplier, because $ref_supplier may not exists anymore. So we will take the first supplier price ok.
2160 // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
2161 $result = $prod->get_buyprice($fk_prod_fourn_price, $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
2162 if ($result > 0) {
2163 if (empty($pu)) {
2164 $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
2165 }
2166 $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
2167 // is remise percent not keyed but present for the product we add it
2168 if ($remise_percent == 0 && $prod->remise_percent != 0) {
2169 $remise_percent = $prod->remise_percent;
2170 }
2171 }
2172 if ($result == 0) { // If result == 0, we failed to found the supplier reference price
2173 $langs->load("errors");
2174 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2175 $this->db->rollback();
2176 dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
2177 //$pu = $prod->fourn_pu; // We do not overwrite unit price
2178 //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
2179 return -1;
2180 }
2181 if ($result == -1) {
2182 $langs->load("errors");
2183 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2184 $this->db->rollback();
2185 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
2186 return -1;
2187 }
2188 if ($result < -1) {
2189 $this->error = $prod->error;
2190 $this->db->rollback();
2191 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
2192 return -1;
2193 }
2194 } else {
2195 $this->error = $prod->error;
2196 $this->db->rollback();
2197 return -1;
2198 }
2199 }
2200 } else {
2201 $product_type = $type;
2202 }
2203
2204 if (isModEnabled("multicurrency") && $pu_devise > 0) {
2205 $pu = 0;
2206 }
2207
2208 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2209
2210 // Clean vat code
2211 $reg = array();
2212 $vat_src_code = '';
2213 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
2214 $vat_src_code = $reg[1];
2215 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
2216 }
2217
2218 // Calcul du total TTC et de la TVA pour la ligne a partir de
2219 // qty, pu, remise_percent et txtva
2220 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2221 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2222
2223 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_devise);
2224 $total_ht = $tabprice[0];
2225 $total_tva = $tabprice[1];
2226 $total_ttc = $tabprice[2];
2227 $total_localtax1 = $tabprice[9];
2228 $total_localtax2 = $tabprice[10];
2229 $pu_ht = $tabprice[3];
2230
2231 // MultiCurrency
2232 $multicurrency_total_ht = $tabprice[16];
2233 $multicurrency_total_tva = $tabprice[17];
2234 $multicurrency_total_ttc = $tabprice[18];
2235 $pu_ht_devise = $tabprice[19];
2236
2237 // Check parameters
2238 if ($type < 0) {
2239 return -1;
2240 }
2241
2242 if ($rang < 0) {
2243 $rangmax = $this->line_max();
2244 $rang = $rangmax + 1;
2245 }
2246
2247 // Insert line
2248 $supplierinvoiceline = new SupplierInvoiceLine($this->db);
2249
2250 $supplierinvoiceline->context = $this->context;
2251
2252 $supplierinvoiceline->fk_facture_fourn = $this->id;
2253 //$supplierinvoiceline->label=$label; // deprecated
2254 $supplierinvoiceline->desc = $desc;
2255 $supplierinvoiceline->ref_supplier = $ref_supplier;
2256
2257 $supplierinvoiceline->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : (float) $qty); // For credit note, quantity is always positive and unit price negative
2258 $supplierinvoiceline->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs((float) $pu_ht) : (float) $pu_ht); // For credit note, unit price always negative, always positive otherwise
2259
2260 $supplierinvoiceline->vat_src_code = $vat_src_code;
2261 $supplierinvoiceline->tva_tx = $txtva;
2262 $supplierinvoiceline->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
2263 $supplierinvoiceline->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
2264 $supplierinvoiceline->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
2265 $supplierinvoiceline->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
2266
2267 $supplierinvoiceline->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_ht) : (float) $total_ht); // For credit note and if qty is negative, total is negative
2268 $supplierinvoiceline->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva); // For credit note and if qty is negative, total is negative
2269 $supplierinvoiceline->total_localtax1 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_localtax1) : (float) $total_localtax1); // For credit note and if qty is negative, total is negative
2270 $supplierinvoiceline->total_localtax2 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_localtax2) : (float) $total_localtax2); // For credit note and if qty is negative, total is negative
2271 $supplierinvoiceline->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc); // For credit note and if qty is negative, total is negative
2272
2273 $supplierinvoiceline->fk_product = $fk_product;
2274 $supplierinvoiceline->product_type = $type;
2275 $supplierinvoiceline->remise_percent = $remise_percent;
2276 $supplierinvoiceline->date_start = $date_start;
2277 $supplierinvoiceline->date_end = $date_end;
2278 $supplierinvoiceline->fk_code_ventilation = $fk_code_ventilation;
2279 $supplierinvoiceline->rang = $rang;
2280 $supplierinvoiceline->info_bits = $info_bits;
2281 $supplierinvoiceline->fk_remise_except = $fk_remise_except;
2282
2283
2284 $supplierinvoiceline->special_code = (int) $special_code;
2285 $supplierinvoiceline->fk_parent_line = $fk_parent_line;
2286 $supplierinvoiceline->origin = $this->origin;
2287 $supplierinvoiceline->origin_id = $origin_id;
2288 $supplierinvoiceline->fk_unit = $fk_unit;
2289
2290 // Multicurrency
2291 $supplierinvoiceline->fk_multicurrency = $this->fk_multicurrency;
2292 $supplierinvoiceline->multicurrency_code = $this->multicurrency_code;
2293 $supplierinvoiceline->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs((float) $pu_ht_devise) : (float) $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
2294
2295 $supplierinvoiceline->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $multicurrency_total_ht) : (float) $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
2296 $supplierinvoiceline->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $multicurrency_total_tva) : (float) $multicurrency_total_tva); // For credit note and if qty is negative, total is negative
2297 $supplierinvoiceline->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc); // For credit note and if qty is negative, total is negative
2298
2299 if (is_array($array_options) && count($array_options) > 0) {
2300 $supplierinvoiceline->array_options = $array_options;
2301 }
2302
2303 $result = $supplierinvoiceline->insert($notrigger);
2304 if ($result > 0) {
2305 // Reorder if child line
2306 if (!empty($fk_parent_line)) {
2307 $this->line_order(true, 'DESC');
2308 } elseif ($rang > 0 && $rang <= count($this->lines)) { // Update all rank of all other lines
2309 $linecount = count($this->lines);
2310 for ($ii = $rang; $ii <= $linecount; $ii++) {
2311 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2312 }
2313 }
2314
2315 // Mise a jour information denormalisees au niveau de la facture meme
2316 $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.
2317 if ($result > 0) {
2318 $this->db->commit();
2319 return $supplierinvoiceline->id;
2320 } else {
2321 $this->error = $this->db->error();
2322 $this->db->rollback();
2323 return -1;
2324 }
2325 } else {
2326 $this->error = $supplierinvoiceline->error;
2327 $this->errors = $supplierinvoiceline->errors;
2328 $this->db->rollback();
2329 return -2;
2330 }
2331 } else {
2332 return 0;
2333 }
2334 }
2335
2361 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)
2362 {
2363 global $mysoc, $langs;
2364
2365 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);
2366 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2367
2368 $pu = price2num($pu);
2369 $qty = price2num($qty);
2370 $remise_percent = (float) price2num($remise_percent);
2371 $pu_devise = price2num($pu_devise);
2372
2373 // Check parameters
2374 //if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
2375 if ($type < 0) {
2376 return -1;
2377 }
2378
2379 if ($date_start && $date_end && $date_start > $date_end) {
2380 $langs->load("errors");
2381 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2382 return -1;
2383 }
2384
2385 // Clean parameters
2386 if (empty($vatrate)) {
2387 $vatrate = 0;
2388 }
2389 if (empty($txlocaltax1)) {
2390 $txlocaltax1 = 0;
2391 }
2392 if (empty($txlocaltax2)) {
2393 $txlocaltax2 = 0;
2394 }
2395
2396 $txlocaltax1 = (float) price2num($txlocaltax1);
2397 $txlocaltax2 = (float) price2num($txlocaltax2);
2398
2399 // Calcul du total TTC et de la TVA pour la ligne a partir de
2400 // qty, pu, remise_percent et txtva
2401 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2402 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2403
2404 $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty);
2405
2406 $reg = array();
2407
2408 // Clean vat code
2409 $vat_src_code = '';
2410 if (preg_match('/\‍((.*)\‍)/', (string) $vatrate, $reg)) {
2411 $vat_src_code = $reg[1];
2412 $vatrate = preg_replace('/\s*\‍(.*\‍)/', '', (string) $vatrate); // Remove code into vatrate.
2413 }
2414
2415 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_devise);
2416 $total_ht = $tabprice[0];
2417 $total_tva = $tabprice[1];
2418 $total_ttc = $tabprice[2];
2419 $pu_ht = $tabprice[3];
2420 $pu_tva = $tabprice[4];
2421 $pu_ttc = $tabprice[5];
2422 $total_localtax1 = $tabprice[9];
2423 $total_localtax2 = $tabprice[10];
2424
2425 // MultiCurrency
2426 $multicurrency_total_ht = $tabprice[16];
2427 $multicurrency_total_tva = $tabprice[17];
2428 $multicurrency_total_ttc = $tabprice[18];
2429 $pu_ht_devise = $tabprice[19];
2430
2431 if (empty($info_bits)) {
2432 $info_bits = 0;
2433 }
2434
2435 // Fetch current line from the database and then clone the object and set it in $oldline property
2436 $line = new SupplierInvoiceLine($this->db);
2437 $line->fetch($id);
2438 $line->fetch_optionals();
2439
2440 $staticline = clone $line;
2441
2442 if ($idproduct) {
2443 $product = new Product($this->db);
2444 $result = $product->fetch($idproduct);
2445 $product_type = $product->type;
2446 } else {
2447 $idproduct = $staticline->fk_product;
2448 $product_type = $type;
2449 }
2450
2451 $line->oldline = $staticline;
2452 $line->context = $this->context;
2453
2454 $line->description = $desc;
2455 $line->desc = $desc;
2456
2457 $line->qty = ($this->type == self::TYPE_CREDIT_NOTE ? abs((float) $qty) : (float) $qty); // For credit note, quantity is always positive and unit price negative
2458 $line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ? -abs((float) $pu_ht) : (float) $pu_ht); // For credit note, unit price always negative, always positive otherwise
2459 $line->pu_ht = $line->subprice; // deprecated
2460 $line->pu_ttc = ($this->type == self::TYPE_CREDIT_NOTE ? -abs((float) $pu_ttc) : (float) $pu_ttc); // For credit note, unit price always negative, always positive otherwise
2461
2462 $line->remise_percent = $remise_percent;
2463 $line->ref_supplier = $ref_supplier;
2464
2465 $line->date_start = $date_start;
2466 $line->date_end = $date_end;
2467
2468 $line->vat_src_code = $vat_src_code;
2469 $line->tva_tx = $vatrate;
2470 $line->localtax1_tx = $txlocaltax1;
2471 $line->localtax2_tx = $txlocaltax2;
2472 $line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
2473 $line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
2474
2475 $line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_ht) : (float) $total_ht);
2476 $line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_tva) : (float) $total_tva);
2477 $line->total_localtax1 = (float) $total_localtax1;
2478 $line->total_localtax2 = (float) $total_localtax2;
2479 $line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((float) $total_ttc) : (float) $total_ttc);
2480
2481 $line->fk_product = $idproduct;
2482 $line->product_type = $product_type;
2483 $line->info_bits = $info_bits;
2484 $line->fk_unit = $fk_unit;
2485 $line->rang = $rang;
2486
2487 if (is_array($array_options) && count($array_options) > 0) {
2488 // We replace values in this->line->array_options only for entries defined into $array_options
2489 foreach ($array_options as $key => $value) {
2490 $line->array_options[$key] = $array_options[$key];
2491 }
2492 }
2493
2494 // Multicurrency
2495 $line->multicurrency_subprice = (float) $pu_ht_devise;
2496 $line->multicurrency_total_ht = (float) $multicurrency_total_ht;
2497 $line->multicurrency_total_tva = (float) $multicurrency_total_tva;
2498 $line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
2499
2500 $res = $line->update($notrigger);
2501
2502 if ($res < 1) {
2503 $this->errors[] = $line->error;
2504 } else {
2505 // Update total price into invoice record
2506 $res = $this->update_price('1', 'auto', 0, $this->thirdparty);
2507 }
2508
2509 return $res;
2510 }
2511
2519 public function deleteLine($rowid, $notrigger = 0)
2520 {
2521 if (!$rowid) {
2522 $rowid = $this->id;
2523 }
2524
2525 $this->db->begin();
2526
2527 // Free the discount linked to a line of invoice
2528 $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
2529 $sql .= ' SET fk_invoice_supplier_line = NULL';
2530 $sql .= ' WHERE fk_invoice_supplier_line = '.((int) $rowid);
2531
2532 dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
2533 $result = $this->db->query($sql);
2534 if (!$result) {
2535 $this->error = $this->db->error();
2536 $this->db->rollback();
2537 return -2;
2538 }
2539
2540 $line = new SupplierInvoiceLine($this->db);
2541
2542 if ($line->fetch($rowid) < 1) {
2543 return -1;
2544 }
2545
2546 $res = $line->delete($notrigger);
2547
2548 if ($res < 1) {
2549 $this->errors[] = $line->error;
2550 $this->db->rollback();
2551 return -3;
2552 } else {
2553 $res = $this->update_price(1);
2554
2555 if ($res > 0) {
2556 $this->db->commit();
2557 return 1;
2558 } else {
2559 $this->db->rollback();
2560 $this->error = $this->db->lasterror();
2561 return -4;
2562 }
2563 }
2564 }
2565
2566
2573 public function info($id)
2574 {
2575 $sql = 'SELECT c.rowid, datec, tms as datem, ';
2576 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid';
2577 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
2578 $sql .= ' WHERE c.rowid = '.((int) $id);
2579
2580 $result = $this->db->query($sql);
2581 if ($result) {
2582 if ($this->db->num_rows($result)) {
2583 $obj = $this->db->fetch_object($result);
2584
2585 $this->id = $obj->rowid;
2586
2587 $this->user_creation_id = $obj->fk_user_author;
2588 $this->user_validation_id = $obj->fk_user_valid;
2589 $this->user_modification_id = $obj->fk_user_modif;
2590 $this->date_creation = $this->db->jdate($obj->datec);
2591 $this->date_modification = $this->db->jdate($obj->datem);
2592 //$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)
2593 }
2594 $this->db->free($result);
2595 } else {
2596 dol_print_error($this->db);
2597 }
2598 }
2599
2600 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2609 public function list_replacable_supplier_invoices($socid = 0)
2610 {
2611 // phpcs:enable
2612 global $conf;
2613
2614 $return = array();
2615
2616 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut,";
2617 $sql .= " ff.rowid as rowidnext";
2618 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2619 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
2620 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source";
2621 $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
2622 $sql .= " AND f.entity = ".$conf->entity;
2623 $sql .= " AND f.paye = 0"; // Pas classee payee completement
2624 $sql .= " AND pf.fk_paiementfourn IS NULL"; // Aucun paiement deja fait
2625 $sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de replacement
2626 if ($socid > 0) {
2627 $sql .= " AND f.fk_soc = ".((int) $socid);
2628 }
2629 $sql .= " ORDER BY f.ref";
2630
2631 dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG);
2632 $resql = $this->db->query($sql);
2633 if ($resql) {
2634 while ($obj = $this->db->fetch_object($resql)) {
2635 $return[$obj->rowid] = array(
2636 'id' => $obj->rowid,
2637 'ref' => $obj->ref,
2638 'status' => $obj->fk_statut
2639 );
2640 }
2641 //print_r($return);
2642 return $return;
2643 } else {
2644 $this->error = $this->db->error();
2645 return -1;
2646 }
2647 }
2648
2649 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2659 public function list_qualified_avoir_supplier_invoices($socid = 0)
2660 {
2661 // phpcs:enable
2662 global $conf;
2663
2664 $return = array();
2665
2666 $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiementfourn";
2667 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
2668 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn";
2669 $sql .= " WHERE f.entity = ".$conf->entity;
2670 $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
2671 $sql .= " AND NOT EXISTS (SELECT rowid from ".MAIN_DB_PREFIX."facture_fourn as ff WHERE f.rowid = ff.fk_facture_source";
2672 $sql .= " AND ff.type=".self::TYPE_REPLACEMENT.")";
2673 $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
2674 if ($socid > 0) {
2675 $sql .= " AND f.fk_soc = ".((int) $socid);
2676 }
2677 $sql .= " ORDER BY f.ref";
2678
2679 dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG);
2680 $resql = $this->db->query($sql);
2681 if ($resql) {
2682 while ($obj = $this->db->fetch_object($resql)) {
2683 $qualified = 0;
2684 if ($obj->fk_statut == self::STATUS_VALIDATED) {
2685 $qualified = 1;
2686 }
2687 if ($obj->fk_statut == self::STATUS_CLOSED) {
2688 $qualified = 1;
2689 }
2690 if ($qualified) {
2691 $paymentornot = ($obj->fk_paiementfourn ? 1 : 0);
2692 $return[$obj->rowid] = array('ref' => (string) $obj->ref, 'status' => (int) $obj->fk_statut, 'type' => (int) $obj->type, 'paye' => (int) $obj->paye, 'paymentornot' => (int) $paymentornot);
2693 }
2694 }
2695
2696 return $return;
2697 } else {
2698 $this->error = $this->db->error();
2699 return -1;
2700 }
2701 }
2702
2703 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2710 public function load_board($user)
2711 {
2712 // phpcs:enable
2713 global $conf, $langs;
2714
2715 $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut as status, ff.total_ht, ff.total_ttc';
2716 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
2717 if (!$user->hasRight("societe", "client", "voir") && !$user->socid) {
2718 $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ff.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2719 }
2720 $sql .= ' WHERE ff.paye = 0';
2721 $sql .= " AND ff.fk_statut IN (".self::STATUS_VALIDATED.")";
2722 $sql .= " AND ff.entity = ".$conf->entity;
2723 if ($user->socid) {
2724 $sql .= ' AND ff.fk_soc = '.((int) $user->socid);
2725 }
2726
2727 $resql = $this->db->query($sql);
2728 if ($resql) {
2729 $langs->load("bills");
2730 $now = dol_now();
2731
2732 $response = new WorkboardResponse();
2733 $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24;
2734 $response->label = $langs->trans("SupplierBillsToPay");
2735 $response->labelShort = $langs->trans("StatusToPay");
2736
2737 $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills';
2738 $response->img = img_object($langs->trans("Bills"), "bill");
2739
2740 $facturestatic = new FactureFournisseur($this->db);
2741
2742 while ($obj = $this->db->fetch_object($resql)) {
2743 $facturestatic->date_echeance = $this->db->jdate($obj->datefin);
2744 $facturestatic->statut = $obj->status; // For backward compatibility
2745 $facturestatic->status = $obj->status;
2746
2747 $response->nbtodo++;
2748 $response->total += $obj->total_ht;
2749
2750 if ($facturestatic->hasDelay()) {
2751 $response->nbtodolate++;
2752 $response->url_late = DOL_URL_ROOT.'/fourn/facture/list.php?search_option=late&mainmenu=billing&leftmenu=suppliers_bills';
2753 }
2754 }
2755
2756 $this->db->free($resql);
2757 return $response;
2758 } else {
2759 dol_print_error($this->db);
2760 $this->error = $this->db->error();
2761 return -1;
2762 }
2763 }
2764
2772 public function getTooltipContentArray($params)
2773 {
2774 global $conf, $langs, $mysoc;
2775
2776 $langs->load('bills');
2777
2778 $datas = [];
2779 $moretitle = $params['moretitle'] ?? '';
2780
2781 $picto = $this->picto;
2782 if ($this->type == self::TYPE_REPLACEMENT) {
2783 $picto .= 'r'; // Replacement invoice
2784 }
2785 if ($this->type == self::TYPE_CREDIT_NOTE) {
2786 $picto .= 'a'; // Credit note
2787 }
2788 if ($this->type == self::TYPE_DEPOSIT) {
2789 $picto .= 'd'; // Deposit invoice
2790 }
2791
2792 $datas['picto'] = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("SupplierInvoice").'</u>';
2793 if ($this->type == self::TYPE_REPLACEMENT) {
2794 $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplace").'</u>';
2795 } elseif ($this->type == self::TYPE_CREDIT_NOTE) {
2796 $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
2797 } elseif ($this->type == self::TYPE_DEPOSIT) {
2798 $datas['picto'] .= '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
2799 }
2800 if (isset($this->status)) {
2801 $alreadypaid = -1;
2802 if (isset($this->totalpaid)) {
2803 $alreadypaid = $this->totalpaid;
2804 }
2805
2806 $datas['picto'] .= ' '.$this->getLibStatut(5, $alreadypaid);
2807 }
2808 if ($moretitle) {
2809 $datas['picto'] .= ' - '.$moretitle;
2810 }
2811 if (!empty($this->ref)) {
2812 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2813 }
2814 if (!empty($this->ref_supplier)) {
2815 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
2816 }
2817 if (!empty($this->label)) {
2818 $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
2819 }
2820 if (!empty($this->date)) {
2821 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
2822 }
2823 if (!empty($this->date_echeance)) {
2824 $datas['date_echeance'] = '<br><b>'.$langs->trans('DateDue').':</b> '.dol_print_date($this->date_echeance, 'day');
2825 }
2826 if (!empty($this->total_ht)) {
2827 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2828 }
2829 if (!empty($this->total_tva)) {
2830 $datas['totaltva'] = '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2831 }
2832 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2833 // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
2834 $datas['amountlt1'] = '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2835 }
2836 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2837 $datas['amountlt2'] = '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2838 }
2839 if (!empty($this->revenuestamp)) {
2840 $datas['amountrevenustamp'] = '<br><b>'.$langs->trans('RevenueStamp').':</b> '.price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2841 }
2842 if (!empty($this->total_ttc)) {
2843 $datas['totalttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2844 }
2845 return $datas;
2846 }
2847
2861 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
2862 {
2863 global $langs, $conf, $user, $hookmanager;
2864
2865 $result = '';
2866
2867 if ($option == 'withdraw') {
2868 $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer';
2869 } elseif ($option == 'document') {
2870 $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id;
2871 } else {
2872 $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id;
2873 }
2874
2875 if ($short) {
2876 return $url;
2877 }
2878
2879 if ($option !== 'nolink') {
2880 // Add param to save lastsearch_values or not
2881 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2882 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2883 $add_save_lastsearch_values = 1;
2884 }
2885 if ($add_save_lastsearch_values) {
2886 $url .= '&save_lastsearch_values=1';
2887 }
2888 }
2889
2890 $picto = $this->picto;
2891 if ($this->type == self::TYPE_REPLACEMENT) {
2892 $picto .= 'r'; // Replacement invoice
2893 }
2894 if ($this->type == self::TYPE_CREDIT_NOTE) {
2895 $picto .= 'a'; // Credit note
2896 }
2897 if ($this->type == self::TYPE_DEPOSIT) {
2898 $picto .= 'd'; // Deposit invoice
2899 }
2900
2901 $params = [
2902 'id' => $this->id,
2903 'objecttype' => $this->element,
2904 'option' => $option,
2905 'moretitle' => $moretitle,
2906 ];
2907 $classfortooltip = 'classfortooltip';
2908 $dataparams = '';
2909 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2910 $classfortooltip = 'classforajaxtooltip';
2911 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2912 $label = '';
2913 } else {
2914 $label = implode($this->getTooltipContentArray($params));
2915 }
2916
2917 $ref = $this->ref;
2918 if (empty($ref)) {
2919 $ref = $this->id;
2920 }
2921
2922 $linkclose = '';
2923 if (empty($notooltip)) {
2924 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2925 $label = $langs->trans("ShowSupplierInvoice");
2926 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2927 }
2928 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
2929 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2930 }
2931
2932 $linkstart = '<a href="'.$url.'"';
2933 $linkstart .= $linkclose.'>';
2934 $linkend = '</a>';
2935
2936 $result .= $linkstart;
2937 if ($withpicto) {
2938 $result .= img_object(($notooltip ? '' : $label), ($picto ? $picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2939 }
2940 if ($withpicto != 2) {
2941 $result .= ($max ? dol_trunc($ref, $max) : $ref);
2942 }
2943 $result .= $linkend;
2944
2945 if ($addlinktonotes) {
2946 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2947 if ($txttoshow) {
2948 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
2949 $result .= ' <span class="note inline-block">';
2950 $result .= '<a href="'.DOL_URL_ROOT.'/fourn/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
2951 $result .= img_picto('', 'note');
2952 $result .= '</a>';
2953 $result .= '</span>';
2954 }
2955 }
2956 global $action;
2957 $hookmanager->initHooks(array($this->element . 'dao'));
2958 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2959 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2960 if ($reshook > 0) {
2961 $result = $hookmanager->resPrint;
2962 } else {
2963 $result .= $hookmanager->resPrint;
2964 }
2965 return $result;
2966 }
2967
2976 public function getNextNumRef($soc, $mode = 'next')
2977 {
2978 global $db, $langs, $conf;
2979 $langs->load("orders");
2980
2981 // Clean parameters (if not defined or using deprecated value)
2982 if (!getDolGlobalString('INVOICE_SUPPLIER_ADDON_NUMBER')) {
2983 $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus';
2984 }
2985
2986 $mybool = false;
2987
2988 $file = getDolGlobalString('INVOICE_SUPPLIER_ADDON_NUMBER') . ".php";
2989 $classname = getDolGlobalString('INVOICE_SUPPLIER_ADDON_NUMBER');
2990
2991 // Include file with class
2992 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2993
2994 foreach ($dirmodels as $reldir) {
2995 $dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
2996
2997 // Load file with numbering class (if found)
2998 $mybool = ((bool) @include_once $dir.$file) || $mybool;
2999 }
3000
3001 if (!$mybool) {
3002 dol_print_error(null, "Failed to include file ".$file);
3003 return '';
3004 }
3005
3006 $obj = new $classname();
3007 '@phan-var-force ModeleNumRefSuppliersInvoices $obj';
3008 $numref = "";
3009 $numref = $obj->getNextValue($soc, $this, $mode);
3010
3011 if ($numref != "") {
3012 return $numref;
3013 } else {
3014 $this->error = $obj->error;
3015 return -1;
3016 }
3017 }
3018
3019
3028 public function initAsSpecimen($option = '')
3029 {
3030 global $langs, $conf;
3031 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3032
3033 $now = dol_now();
3034
3035 // Load array of products prodids
3036 $num_prods = 0;
3037 $prodids = array();
3038
3039 $sql = "SELECT rowid";
3040 $sql .= " FROM ".MAIN_DB_PREFIX."product";
3041 $sql .= " WHERE entity IN (".getEntity('product').")";
3042 $sql .= $this->db->plimit(100);
3043
3044 $resql = $this->db->query($sql);
3045 if ($resql) {
3046 $num_prods = $this->db->num_rows($resql);
3047 $i = 0;
3048 while ($i < $num_prods) {
3049 $i++;
3050 $row = $this->db->fetch_row($resql);
3051 $prodids[$i] = $row[0];
3052 }
3053 }
3054
3055 // Initialise parameters
3056 $this->id = 0;
3057 $this->ref = 'SPECIMEN';
3058 $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
3059 $this->specimen = 1;
3060 $this->socid = 1;
3061 $this->date = $now;
3062 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
3063 $this->cond_reglement_code = 'RECEP';
3064 $this->mode_reglement_code = 'CHQ';
3065
3066 $this->note_public = 'This is a comment (public)';
3067 $this->note_private = 'This is a comment (private)';
3068
3069 $this->multicurrency_tx = 1;
3070 $this->multicurrency_code = $conf->currency;
3071
3072 $xnbp = 0;
3073 if (empty($option) || $option != 'nolines') {
3074 // Lines
3075 $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)
3076 while ($xnbp < $nbp) {
3077 $line = new SupplierInvoiceLine($this->db);
3078 $line->desc = $langs->trans("Description")." ".$xnbp;
3079 $line->qty = 1;
3080 $line->subprice = 100;
3081 $line->pu_ht = $line->subprice; // the canelle template use pu_ht and not subprice
3082 $line->price = 100;
3083 $line->tva_tx = 19.6;
3084 $line->localtax1_tx = 0;
3085 $line->localtax2_tx = 0;
3086 if ($xnbp == 2) {
3087 $line->total_ht = 50;
3088 $line->total_ttc = 59.8;
3089 $line->total_tva = 9.8;
3090 $line->remise_percent = 50;
3091 } else {
3092 $line->total_ht = 100;
3093 $line->total_ttc = 119.6;
3094 $line->total_tva = 19.6;
3095 $line->remise_percent = 0;
3096 }
3097
3098 if ($num_prods > 0) {
3099 $prodid = mt_rand(1, $num_prods);
3100 $line->fk_product = $prodids[$prodid];
3101 }
3102 $line->product_type = 0;
3103
3104 $this->lines[$xnbp] = $line;
3105
3106 $this->total_ht += $line->total_ht;
3107 $this->total_tva += $line->total_tva;
3108 $this->total_ttc += $line->total_ttc;
3109
3110 $xnbp++;
3111 }
3112 }
3113
3114 $this->total_ht = $xnbp * 100;
3115 $this->total_tva = $xnbp * 19.6;
3116 $this->total_ttc = $xnbp * 119.6;
3117
3118 return 1;
3119 }
3120
3126 public function loadStateBoard()
3127 {
3128 global $conf, $user;
3129
3130 $this->nb = array();
3131
3132 $clause = "WHERE";
3133
3134 $sql = "SELECT count(f.rowid) as nb";
3135 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
3136 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
3137 if (!$user->hasRight("societe", "client", "voir") && !$user->socid) {
3138 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3139 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3140 $clause = "AND";
3141 }
3142 $sql .= " ".$clause." f.entity = ".((int) $conf->entity);
3143
3144 $resql = $this->db->query($sql);
3145 if ($resql) {
3146 while ($obj = $this->db->fetch_object($resql)) {
3147 $this->nb["supplier_invoices"] = $obj->nb;
3148 }
3149 $this->db->free($resql);
3150 return 1;
3151 } else {
3152 dol_print_error($this->db);
3153 $this->error = $this->db->error();
3154 return -1;
3155 }
3156 }
3157
3166 public function createFromClone(User $user, $fromid, $invertdetail = 0)
3167 {
3168 global $conf, $langs;
3169
3170 $error = 0;
3171
3172 $object = new FactureFournisseur($this->db);
3173
3174 $this->db->begin();
3175
3176 // Load source object
3177 $object->fetch($fromid);
3178 $object->id = 0;
3179 $object->statut = self::STATUS_DRAFT; // For backward compatibility
3180 $object->status = self::STATUS_DRAFT;
3181
3182 $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor
3183
3184 // Clear fields
3185 $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier);
3186 $object->author = $user->id; // FIXME? user_validation_id is replacement for author
3187 $object->user_validation_id = 0; // FIXME? user_validation_id is replacement for author
3188 $object->fk_facture_source = 0;
3189 $object->date_creation = '';
3190 $object->date_validation = '';
3191 $object->date = (empty($this->date) ? dol_now() : $this->date);
3192 $object->ref_client = '';
3193 $object->close_code = '';
3194 $object->close_note = '';
3195 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
3196 $object->note_private = '';
3197 $object->note_public = '';
3198 }
3199
3200 $object->date_echeance = $object->calculate_date_lim_reglement();
3201
3202 // Loop on each line of new invoice
3203 foreach ($object->lines as $i => $line) {
3204 if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
3205 unset($object->lines[$i]);
3206 }
3207 }
3208
3209 // Create clone
3210 $object->context['createfromclone'] = 'createfromclone';
3211 $result = $object->create($user);
3212
3213 // Other options
3214 if ($result < 0) {
3215 $this->error = $object->error;
3216 $this->errors = $object->errors;
3217 $error++;
3218 }
3219
3220 if (!$error) {
3221 }
3222
3223 unset($object->context['createfromclone']);
3224
3225 // End
3226 if (!$error) {
3227 $this->db->commit();
3228 return $object->id;
3229 } else {
3230 $this->db->rollback();
3231 return -1;
3232 }
3233 }
3234
3246 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3247 {
3248 global $langs;
3249
3250 $langs->load("suppliers");
3251 $outputlangs->load("products");
3252
3253 // Set the model on the model name to use
3254 if (empty($modele)) {
3255 if (getDolGlobalString('INVOICE_SUPPLIER_ADDON_PDF')) {
3256 $modele = getDolGlobalString('INVOICE_SUPPLIER_ADDON_PDF');
3257 } else {
3258 $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation
3259 }
3260 }
3261
3262 if (empty($modele)) {
3263 return 0;
3264 } else {
3265 $modelpath = "core/modules/supplier_invoice/doc/";
3266
3267 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3268 }
3269 }
3270
3275 public function getRights()
3276 {
3277 global $user;
3278
3279 return $user->hasRight("fournisseur", "facture");
3280 }
3281
3290 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3291 {
3292 $tables = array(
3293 'facture_fourn'
3294 );
3295
3296 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3297 }
3298
3307 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
3308 {
3309 $tables = array(
3310 'facture_fourn_det'
3311 );
3312
3313 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
3314 }
3315
3321 public function hasDelay()
3322 {
3323 global $conf;
3324
3325 $now = dol_now();
3326
3327 if (!$this->date_echeance) {
3328 return false;
3329 }
3330
3331 $status = isset($this->status) ? $this->status : $this->statut;
3332
3333 return ($status == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay));
3334 }
3335
3341 public function isCreditNoteUsed()
3342 {
3343 $isUsed = false;
3344
3345 $sql = "SELECT fk_invoice_supplier FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_invoice_supplier_source = ".((int) $this->id);
3346 $resql = $this->db->query($sql);
3347 if (!empty($resql)) {
3348 $obj = $this->db->fetch_object($resql);
3349 if (!empty($obj->fk_invoice_supplier)) {
3350 $isUsed = true;
3351 }
3352 }
3353
3354 return $isUsed;
3355 }
3363 public function getKanbanView($option = '', $arraydata = null)
3364 {
3365 global $langs;
3366
3367 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3368
3369 $picto = $this->picto;
3370 if ($this->type == self::TYPE_REPLACEMENT) {
3371 $picto .= 'r'; // Replacement invoice
3372 }
3373 if ($this->type == self::TYPE_CREDIT_NOTE) {
3374 $picto .= 'a'; // Credit note
3375 }
3376 if ($this->type == self::TYPE_DEPOSIT) {
3377 $picto .= 'd'; // Deposit invoice
3378 }
3379
3380 $return = '<div class="box-flex-item box-flex-grow-zero">';
3381 $return .= '<div class="info-box info-box-sm">';
3382 $return .= '<span class="info-box-icon bg-infobox-action">';
3383 $return .= img_picto('', $picto);
3384 $return .= '</span>';
3385 $return .= '<div class="info-box-content">';
3386 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
3387 if ($selected >= 0) {
3388 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3389 }
3390 if (!empty($arraydata['thirdparty'])) {
3391 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
3392 }
3393 if (property_exists($this, 'date')) {
3394 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
3395 }
3396 if (property_exists($this, 'total_ht')) {
3397 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
3398 $return .= ' '.$langs->trans("HT");
3399 $return .= '</span>';
3400 }
3401 if (method_exists($this, 'getLibStatut')) {
3402 $alreadypaid = (empty($arraydata['alreadypaid']) ? 0 : $arraydata['alreadypaid']);
3403 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).'</div>';
3404 }
3405 $return .= '</div>';
3406 $return .= '</div>';
3407 $return .= '</div>';
3408 return $return;
3409 }
3410
3417 public function setVATReverseCharge($vatreversecharge)
3418 {
3419 if (!$this->table_element) {
3420 dol_syslog(get_class($this)."::setVATReverseCharge was called on object with property table_element not defined", LOG_ERR);
3421 return -1;
3422 }
3423
3424 dol_syslog(get_class($this).'::setVATReverseCharge('.$vatreversecharge.')');
3425
3426 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3427 $sql .= " SET vat_reverse_charge = ".((int) $vatreversecharge);
3428 $sql .= " WHERE rowid=".((int) $this->id);
3429
3430 if ($this->db->query($sql)) {
3431 $this->vat_reverse_charge = ($vatreversecharge == 0) ? 0 : 1;
3432 return 1;
3433 } else {
3434 dol_syslog(get_class($this).'::setVATReverseCharge Error ', LOG_DEBUG);
3435 $this->error = $this->db->error();
3436 return 0;
3437 }
3438 }
3439
3451 public function sendEmailsRemindersOnSupplierInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '', $datetouse = 'duedate', $forcerecipient = '')
3452 {
3453 global $conf, $langs, $user;
3454
3455 $this->output = '';
3456 $this->error = '';
3457 $nbMailSend = 0;
3458
3459 $error = 0;
3460 $errorsMsg = array();
3461
3462 $langs->load('bills');
3463
3464 if (!isModEnabled(empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) ? 'fournisseur' : 'supplier_invoice')) { // Should not happen. If module disabled, cron job should not be visible.
3465 $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv('Suppliers'));
3466 return 0;
3467 }
3468 if (!in_array($datetouse, array('duedate', 'invoicedate'))) {
3469 $this->output .= 'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
3470 return 0;
3471 }
3472
3473 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3474 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3475 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3476 $formmail = new FormMail($this->db);
3477
3478 $now = dol_now();
3479 $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
3480
3481 $tmpinvoice = new FactureFournisseur($this->db);
3482
3483 dol_syslog(__METHOD__." start", LOG_INFO);
3484
3485 // Select all action comm reminder
3486 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture_fourn as f";
3487 if (!empty($paymentmode) && $paymentmode != 'all') {
3488 $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
3489 }
3490 $sql .= " WHERE f.paye = 0"; // Only unpaid
3491 $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; // Only validated status
3492 if ($datetouse == 'invoicedate') {
3493 $sql .= " AND f.datef = '".$this->db->idate($tmpidate, 'gmt')."'";
3494 } else {
3495 $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
3496 }
3497 $sql .= " AND f.entity IN (".getEntity('supplier_invoice', 0).")"; // One batch process only one company (no sharing)
3498 if (!empty($paymentmode) && $paymentmode != 'all') {
3499 $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
3500 }
3501 // TODO Add a filter to check there is no payment started yet
3502 if ($datetouse == 'invoicedate') {
3503 $sql .= $this->db->order("datef", "ASC");
3504 } else {
3505 $sql .= $this->db->order("date_lim_reglement", "ASC");
3506 }
3507
3508 $resql = $this->db->query($sql);
3509
3510 $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
3511 if ($datetouse == 'invoicedate') {
3512 $this->output .= $langs->transnoentitiesnoconv("SearchValidatedSupplierInvoicesWithDate", $stmpidate);
3513 } else {
3514 $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidSupplierInvoicesWithDueDate", $stmpidate);
3515 }
3516 if (!empty($paymentmode) && $paymentmode != 'all') {
3517 $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
3518 }
3519 $this->output .= '<br>';
3520
3521 if ($resql) {
3522 while ($obj = $this->db->fetch_object($resql)) {
3523 if (!$error) {
3524 // Load event
3525 $res = $tmpinvoice->fetch($obj->id);
3526 if ($res > 0) {
3527 $tmpinvoice->fetch_thirdparty();
3528
3529 $outputlangs = new Translate('', $conf);
3530 if ($tmpinvoice->thirdparty->default_lang) {
3531 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
3532 $outputlangs->loadLangs(array("main", "suppliers"));
3533 } else {
3534 $outputlangs = $langs;
3535 }
3536
3537 // Select email template according to language of recipient
3538 $templateId = 0;
3539 $templateLabel = '';
3540 if (empty($template) || $template == 'EmailTemplateCode') {
3541 $templateLabel = '(SendingReminderEmailOnUnpaidSupplierInvoice)';
3542 } else {
3543 if (is_numeric($template)) {
3544 $templateId = $template;
3545 } else {
3546 $templateLabel = $template;
3547 }
3548 }
3549
3550 $arraymessage = $formmail->getEMailTemplate($this->db, 'invoice_supplier_send', $user, $outputlangs, $templateId, 1, $templateLabel);
3551 if (is_numeric($arraymessage) && $arraymessage <= 0) {
3552 $langs->load("errors");
3553 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
3554 return 0;
3555 }
3556
3557 // PREPARE EMAIL
3558 $errormesg = '';
3559
3560 // Make substitution in email content
3561 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $tmpinvoice);
3562
3563 complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
3564
3565 // Topic
3566 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
3567
3568 // Content
3569 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
3570
3571 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
3572
3573 // Recipient
3574 $to = array();
3575 if ($forcerecipient) { // If a recipient was forced
3576 $to = array($forcerecipient);
3577 } else {
3578 $res = $tmpinvoice->fetch_thirdparty();
3579 $recipient = $tmpinvoice->thirdparty;
3580 if ($res > 0) {
3581 $tmparraycontact = $tmpinvoice->liste_contact(-1, 'internal', 0, 'SALESREPFOLL');
3582 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
3583 foreach ($tmparraycontact as $data_email) {
3584 if (!empty($data_email['email'])) {
3585 $to[] = $data_email['email'];
3586 }
3587 }
3588 }
3589 if (empty($to) && !empty($recipient->email)) {
3590 $to[] = $recipient->email;
3591 }
3592 if (empty($to)) {
3593 $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->socid.". No email defined for supplier invoice or customer.";
3594 $error++;
3595 }
3596 } else {
3597 $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
3598 $error++;
3599 }
3600 }
3601
3602 // Sender
3603 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
3604 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
3605 $from = $arraymessage->email_from;
3606 }
3607 if (empty($from)) {
3608 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
3609 $error++;
3610 }
3611
3612 if (!$error && !empty($to)) {
3613 $this->db->begin();
3614
3615 $to = implode(',', $to);
3616 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
3617 $to = $to.','.$arraymessage->email_to;
3618 }
3619
3620 // Errors Recipient
3621 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
3622
3623 $trackid = 'inv'.$tmpinvoice->id;
3624 $sendcontext = 'standard';
3625
3626 $email_tocc = '';
3627 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
3628 $email_tocc = $arraymessage->email_tocc;
3629 }
3630
3631 $email_tobcc = '';
3632 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
3633 $email_tobcc = $arraymessage->email_tobcc;
3634 }
3635
3636 // Mail Creation
3637 $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
3638
3639 // Sending Mail
3640 if ($cMailFile->sendfile()) {
3641 $nbMailSend++;
3642
3643 // Add a line into event table
3644 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3645
3646 // Insert record of emails sent
3647 $actioncomm = new ActionComm($this->db);
3648
3649 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
3650 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
3651 $actioncomm->contact_id = 0;
3652
3653 $actioncomm->code = 'AC_EMAIL';
3654 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.' paymentmode='.$paymentmode.' template='.$template.' datetouse='.$datetouse.' forcerecipient='.$forcerecipient.')';
3655 $actioncomm->note_private = $sendContent;
3656 $actioncomm->fk_project = $tmpinvoice->fk_project;
3657 $actioncomm->datep = dol_now();
3658 $actioncomm->datef = $actioncomm->datep;
3659 $actioncomm->percentage = -1; // Not applicable
3660 $actioncomm->authorid = $user->id; // User saving action
3661 $actioncomm->userownerid = $user->id; // Owner of action
3662 // Fields when action is an email (content should be added into note)
3663 $actioncomm->email_msgid = $cMailFile->msgid;
3664 $actioncomm->email_subject = $sendTopic;
3665 $actioncomm->email_from = $from;
3666 $actioncomm->email_sender = '';
3667 $actioncomm->email_to = $to;
3668 //$actioncomm->email_tocc = $sendtocc;
3669 //$actioncomm->email_tobcc = $sendtobcc;
3670 //$actioncomm->email_subject = $subject;
3671 $actioncomm->errors_to = $errors_to;
3672
3673 $actioncomm->elementtype = 'invoice_supplier';
3674 $actioncomm->fk_element = $tmpinvoice->id;
3675
3676 //$actioncomm->extraparams = $extraparams;
3677
3678 $actioncomm->create($user);
3679 } else {
3680 $errormesg = $cMailFile->error.' : '.$to;
3681 $error++;
3682
3683 // Add a line into event table
3684 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3685
3686 // Insert record of emails sent
3687 $actioncomm = new ActionComm($this->db);
3688
3689 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
3690 $actioncomm->socid = $tmpinvoice->thirdparty->id; // To link to a company
3691 $actioncomm->contact_id = 0;
3692
3693 $actioncomm->code = 'AC_EMAIL';
3694 $actioncomm->label = 'sendEmailsRemindersOnInvoiceDueDateKO';
3695 $actioncomm->note_private = $errormesg;
3696 $actioncomm->fk_project = $tmpinvoice->fk_project;
3697 $actioncomm->datep = dol_now();
3698 $actioncomm->datef = $actioncomm->datep;
3699 $actioncomm->percentage = -1; // Not applicable
3700 $actioncomm->authorid = $user->id; // User saving action
3701 $actioncomm->userownerid = $user->id; // Owner of action
3702 // Fields when action is an email (content should be added into note)
3703 $actioncomm->email_msgid = $cMailFile->msgid;
3704 $actioncomm->email_from = $from;
3705 $actioncomm->email_sender = '';
3706 $actioncomm->email_to = $to;
3707 //$actioncomm->email_tocc = $sendtocc;
3708 //$actioncomm->email_tobcc = $sendtobcc;
3709 //$actioncomm->email_subject = $subject;
3710 $actioncomm->errors_to = $errors_to;
3711
3712 //$actioncomm->extraparams = $extraparams;
3713
3714 $actioncomm->create($user);
3715 }
3716
3717 $this->db->commit(); // We always commit
3718 }
3719
3720 if ($errormesg) {
3721 $errorsMsg[] = $errormesg;
3722 }
3723 } else {
3724 $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
3725 $error++;
3726 }
3727 }
3728 }
3729 } else {
3730 $error++;
3731 }
3732
3733 if (!$error) {
3734 $this->output .= 'Nb of emails sent : '.$nbMailSend;
3735
3736 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
3737
3738 return 0;
3739 } else {
3740 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(empty($errorsMsg) ? $error : implode(', ', $errorsMsg));
3741
3742 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
3743
3744 return $error;
3745 }
3746 }
3747}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
$object ref
Definition info.php:89
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
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.
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.
call_trigger($triggerName, $user)
Call trigger based on this instance.
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.
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)
Adds an invoice line (associated with no predefined product/service) The parameters are already suppo...
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)
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 picto eventually)
getTooltipContentArray($params)
getTooltipContentArray
setPaid($user, $close_code='', $close_note='')
Tag invoice as a paid invoice.
update($user=null, $notrigger=0)
Update database.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
const TYPE_REPLACEMENT
Replacement invoice.
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.
sendEmailsRemindersOnSupplierInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for supplier invoices validated that are due.
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.
getRights()
Returns the rights used for this class.
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)
const STATUS_CLOSED
Classified paid.
setVATReverseCharge($vatreversecharge)
Change the option VAT reverse charge.
Class to manage invoice templates.
Class permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
Class permettant la generation de composants html autre Only common components are here.
Class to manage stock movements.
static getIdFromCode($dbs, $code)
Get id of currency from code.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
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:171
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:660
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:149