dolibarr 21.0.0-alpha
fournisseur.commande.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
6 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2010-2018 Philippe Grand <philippe.grand@atoo-net.com>
8 * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
9 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10 * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
11 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
12 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
13 * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2021 Josep Lluís Amador <joseplluis@lliuretic.cat>
15 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
16 * Copyright (C) 2024 Solution Libre SAS <contact@solution-libre.fr>
17 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
18 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
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/commonorder.class.php';
41require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
42require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.orderline.class.php';
43require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
44if (isModEnabled('productbatch')) {
45 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
46}
47
48
53{
57 public $element = 'order_supplier';
58
62 public $table_element = 'commande_fournisseur';
63
67 public $table_element_line = 'commande_fournisseurdet';
68
72 public $class_element_line = 'CommandeFournisseurLigne';
73
77 public $fk_element = 'fk_commande';
78
82 public $picto = 'supplier_order';
83
88 public $restrictiononfksoc = 1;
89
93 protected $table_ref_field = 'ref';
94
98 public $id;
99
103 public $ref;
104
108 public $ref_supplier;
109
115 public $ref_fourn;
116
120 public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process running -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
121 // -> 7=Canceled/Never received -> (reopen) 3=Process running
122 // -> 6=Canceled -> (reopen) 2=Approved
123 // -> 9=Refused -> (reopen) 1=Validated
124 // Note: billed or not is on another field "billed"
125
126 public $billed;
127
131 public $socid;
132
136 public $fourn_id;
137
141 public $date;
142
146 public $date_valid;
147
151 public $date_approve;
152
157 public $date_approve2;
158
162 public $date_commande;
163
164 //For backward compatibility
165 public $remise_percent;
166 public $methode_commande_id;
167 public $methode_commande;
168
172 public $delivery_date;
173
177 public $total_ht;
178
182 public $total_tva;
183
187 public $total_localtax1;
188
192 public $total_localtax2;
193
197 public $total_ttc;
198
199 public $source;
200
204 public $fk_project;
205
209 public $cond_reglement_id;
210
214 public $cond_reglement_code;
215
219 public $cond_reglement_label;
220
224 public $cond_reglement_doc;
225
229 public $fk_account;
230
234 public $mode_reglement_id;
235
239 public $mode_reglement_code;
240
244 public $mode_reglement;
245
249 public $user_author_id;
250
254 public $user_approve_id;
255
260 public $user_approve_id2;
261
262 public $refuse_note;
263
267 public $extraparams = array();
268
272 public $lines = array();
273
277 public $line;
278
279 // Add for supplier_proposal
280 public $origin;
281 public $origin_id;
282 public $linked_objects = array();
283
287 public $date_lim_reglement;
288 public $receptions = array();
289
290 // Multicurrency
294 public $fk_multicurrency;
295
299 public $multicurrency_code;
300
304 public $multicurrency_tx;
305
309 public $multicurrency_total_ht;
310
314 public $multicurrency_total_tva;
315
319 public $multicurrency_total_ttc;
320
348 public $fields = array(
349 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 10),
350 'ref' => array('type' => 'varchar(255)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'showoncombobox' => 1, 'position' => 25, 'searchall' => 1),
351 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'Ref ext', 'enabled' => 1, 'visible' => 0, 'position' => 35),
352 'ref_supplier' => array('type' => 'varchar(255)', 'label' => 'RefOrderSupplierShort', 'enabled' => 1, 'visible' => 1, 'position' => 40, 'searchall' => 1),
353 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 45),
354 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 710),
355 'date_approve' => array('type' => 'datetime', 'label' => 'DateApprove', 'enabled' => 1, 'visible' => -1, 'position' => 720),
356 'date_approve2' => array('type' => 'datetime', 'label' => 'DateApprove2', 'enabled' => 1, 'visible' => 3, 'position' => 725),
357 'date_commande' => array('type' => 'date', 'label' => 'OrderDateShort', 'enabled' => 1, 'visible' => 1, 'position' => 70),
358 'date_livraison' => array('type' => 'datetime', 'label' => 'DeliveryDate', 'enabled' => 'empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)', 'visible' => 1, 'position' => 74),
359 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => 3, 'position' => 41),
360 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => 3, 'notnull' => -1, 'position' => 80),
361 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => 3, 'position' => 711),
362 'fk_user_approve' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserApproval', 'enabled' => 1, 'visible' => 3, 'position' => 721),
363 'fk_user_approve2' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserApproval2', 'enabled' => 1, 'visible' => 3, 'position' => 726),
364 'source' => array('type' => 'smallint(6)', 'label' => 'Source', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 100),
365 'billed' => array('type' => 'smallint(6)', 'label' => 'Billed', 'enabled' => 1, 'visible' => 1, 'position' => 710),
366 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
367 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => 1, 'position' => 135, 'isameasure' => 1),
368 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => 3, 'position' => 140, 'isameasure' => 1),
369 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => 3, 'position' => 145, 'isameasure' => 1),
370 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => -1, 'position' => 150, 'isameasure' => 1),
371 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 750, 'searchall' => 1),
372 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 760, 'searchall' => 1),
373 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPDF', 'enabled' => 1, 'visible' => 0, 'position' => 165),
374 'fk_input_method' => array('type' => 'integer', 'label' => 'OrderMode', 'enabled' => 1, 'visible' => 3, 'position' => 170),
375 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => 3, 'position' => 175),
376 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => 3, 'position' => 180),
377 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => 0, 'position' => 190),
378 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => 3, 'position' => 200),
379 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 1, 'visible' => 3, 'position' => 205),
380 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLocation', 'enabled' => 1, 'visible' => 3, 'position' => 210),
381 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => 0, 'position' => 215),
382 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 220),
383 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 225),
384 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 230),
385 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 235),
386 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
387 'date_creation' => array('type' => 'datetime', 'label' => 'Date creation', 'enabled' => 1, 'visible' => -1, 'position' => 500),
388 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => 1, 'notnull' => 1, 'position' => 50),
389 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 1000, 'index' => 1),
390 'tms' => array('type' => 'datetime', 'label' => "DateModificationShort", 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 501),
391 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => 0, 'position' => 700),
392 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => 1, 'position' => 701),
393 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => 0, 'position' => 900),
394 );
395
396
400 const STATUS_DRAFT = 0;
401
406
411
416
421
426
431
436
440 const STATUS_REFUSED = 9;
441
442
447
453 public function __construct($db)
454 {
455 $this->db = $db;
456
457 $this->ismultientitymanaged = 1;
458 }
459
460
468 public function fetch($id, $ref = '')
469 {
470 // Check parameters
471 if (empty($id) && empty($ref)) {
472 return -1;
473 }
474
475 $sql = "SELECT c.rowid, c.entity, c.ref, ref_supplier, c.fk_soc, c.fk_statut as status, c.amount_ht, c.total_ht, c.total_ttc, c.total_tva,";
476 $sql .= " c.localtax1, c.localtax2, ";
477 $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
478 $sql .= " c.fk_user_author as user_author_id, c.fk_user_valid as user_validation_id, c.fk_user_approve as user_approve_id, c.fk_user_approve2 as user_approve_id2,";
479 $sql .= " c.date_commande as date_commande, c.date_livraison as delivery_date, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
480 $sql .= " c.fk_account,";
481 $sql .= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
482 $sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
483 $sql .= " cm.libelle as methode_commande,";
484 $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,";
485 $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
486 $sql .= ', c.fk_incoterms, c.location_incoterms';
487 $sql .= ', i.libelle as label_incoterms';
488 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as c";
489 $sql .= " LEFT JOIN ".$this->db->prefix()."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid";
490 $sql .= " LEFT JOIN ".$this->db->prefix()."c_paiement as p ON c.fk_mode_reglement = p.id";
491 $sql .= " LEFT JOIN ".$this->db->prefix()."c_input_method as cm ON cm.rowid = c.fk_input_method";
492 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_incoterms as i ON c.fk_incoterms = i.rowid';
493
494 if (empty($id)) {
495 $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")";
496 } else {
497 $sql .= " WHERE c.rowid=".((int) $id);
498 }
499
500 if ($ref) {
501 $sql .= " AND c.ref='".$this->db->escape($ref)."'";
502 }
503
504 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
505 $resql = $this->db->query($sql);
506 if ($resql) {
507 $obj = $this->db->fetch_object($resql);
508 if (!$obj) {
509 $this->error = 'Bill with id '.$id.' not found';
510 dol_syslog(get_class($this).'::fetch '.$this->error);
511 return 0;
512 }
513
514 $this->id = $obj->rowid;
515 $this->entity = $obj->entity;
516
517 $this->ref = $obj->ref;
518 $this->ref_supplier = $obj->ref_supplier;
519 $this->socid = $obj->fk_soc;
520 $this->fourn_id = $obj->fk_soc;
521 $this->statut = $obj->status; // deprecated
522 $this->status = $obj->status;
523 $this->billed = $obj->billed;
524 $this->user_author_id = $obj->user_author_id;
525 $this->user_validation_id = $obj->user_validation_id;
526 $this->user_approve_id = $obj->user_approve_id;
527 $this->user_approve_id2 = $obj->user_approve_id2;
528 $this->total_ht = $obj->total_ht;
529 $this->total_tva = $obj->total_tva;
530 $this->total_localtax1 = $obj->localtax1;
531 $this->total_localtax2 = $obj->localtax2;
532 $this->total_ttc = $obj->total_ttc;
533 $this->date_creation = $this->db->jdate($obj->date_creation);
534 $this->date_valid = $this->db->jdate($obj->date_valid);
535 $this->date_approve = $this->db->jdate($obj->date_approve);
536 $this->date_approve2 = $this->db->jdate($obj->date_approve2);
537 $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier
538 if (isset($obj->date_commande)) {
539 $this->date = $this->date_commande;
540 } else {
541 $this->date = $this->date_creation;
542 }
543 $this->delivery_date = $this->db->jdate($obj->delivery_date);
544 $this->remise_percent = $obj->remise_percent;
545 $this->methode_commande_id = $obj->fk_input_method;
546 $this->methode_commande = $obj->methode_commande;
547
548 $this->source = $obj->source;
549 $this->fk_project = $obj->fk_project;
550 $this->cond_reglement_id = $obj->fk_cond_reglement;
551 $this->cond_reglement_code = $obj->cond_reglement_code;
552 $this->cond_reglement = $obj->cond_reglement_label; // deprecated
553 $this->cond_reglement_label = $obj->cond_reglement_label;
554 $this->cond_reglement_doc = $obj->cond_reglement_doc;
555 $this->fk_account = $obj->fk_account;
556 $this->mode_reglement_id = $obj->fk_mode_reglement;
557 $this->mode_reglement_code = $obj->mode_reglement_code;
558 $this->mode_reglement = $obj->mode_reglement_libelle;
559 $this->note = $obj->note_private; // deprecated
560 $this->note_private = $obj->note_private;
561 $this->note_public = $obj->note_public;
562 $this->model_pdf = $obj->model_pdf;
563
564 //Incoterms
565 $this->fk_incoterms = $obj->fk_incoterms;
566 $this->location_incoterms = $obj->location_incoterms;
567 $this->label_incoterms = $obj->label_incoterms;
568
569 // Multicurrency
570 $this->fk_multicurrency = $obj->fk_multicurrency;
571 $this->multicurrency_code = $obj->multicurrency_code;
572 $this->multicurrency_tx = $obj->multicurrency_tx;
573 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
574 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
575 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
576
577 $this->extraparams = isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
578
579 $this->db->free($resql);
580
581 // Retrieve all extrafield
582 // fetch optionals attributes and labels
583 $this->fetch_optionals();
584
585 // Lines
586 $result = $this->fetch_lines();
587
588 if ($result < 0) {
589 return -1;
590 } else {
591 return 1;
592 }
593 } else {
594 $this->error = $this->db->error()." sql=".$sql;
595 return -1;
596 }
597 }
598
599 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
606 public function fetch_lines($only_product = 0)
607 {
608 // phpcs:enable
609
610 $this->lines = array();
611
612 $sql = "SELECT l.rowid, l.fk_commande, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
613 $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
614 $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
615 $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.info_bits, l.special_code, l.fk_parent_line, l.rang,";
616 $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc, p.tobatch as product_tobatch, p.barcode as product_barcode,";
617 $sql .= " l.fk_unit,";
618 $sql .= " l.date_start, l.date_end,";
619 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
620 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as l";
621 $sql .= ' LEFT JOIN '.$this->db->prefix().'product as p ON l.fk_product = p.rowid';
622 $sql .= " WHERE l.fk_commande = ".((int) $this->id);
623 if ($only_product) {
624 $sql .= ' AND p.fk_product_type = 0';
625 }
626 $sql .= " ORDER BY l.rang, l.rowid";
627 //print $sql;
628
629 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
630
631 $result = $this->db->query($sql);
632 if ($result) {
633 $num = $this->db->num_rows($result);
634 $i = 0;
635
636 while ($i < $num) {
637 $objp = $this->db->fetch_object($result);
638
639 $line = new CommandeFournisseurLigne($this->db);
640
641 $line->id = $objp->rowid;
642 $line->fk_commande = $objp->fk_commande;
643 $line->desc = $objp->description;
644 $line->description = $objp->description;
645 $line->qty = $objp->qty;
646 $line->tva_tx = $objp->tva_tx;
647 $line->localtax1_tx = $objp->localtax1_tx;
648 $line->localtax2_tx = $objp->localtax2_tx;
649 $line->localtax1_type = $objp->localtax1_type;
650 $line->localtax2_type = $objp->localtax2_type;
651 $line->subprice = $objp->subprice;
652 $line->pu_ht = $objp->subprice;
653 $line->remise_percent = $objp->remise_percent;
654
655 $line->vat_src_code = $objp->vat_src_code;
656 $line->total_ht = $objp->total_ht;
657 $line->total_tva = $objp->total_tva;
658 $line->total_localtax1 = $objp->total_localtax1;
659 $line->total_localtax2 = $objp->total_localtax2;
660 $line->total_ttc = $objp->total_ttc;
661 $line->product_type = $objp->product_type;
662
663 $line->fk_product = $objp->fk_product;
664
665 $line->libelle = $objp->product_label; // deprecated
666 $line->product_label = $objp->product_label;
667 $line->product_desc = $objp->product_desc;
668 $line->product_tobatch = $objp->product_tobatch;
669 $line->product_barcode = $objp->product_barcode;
670
671 $line->ref = $objp->product_ref; // Ref of product
672 $line->product_ref = $objp->product_ref; // Ref of product
673 $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
674 $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
675
676 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
677 // TODO We should not fetch this properties into the fetch_lines. This is NOT properties of a line.
678 // Move this into another method and call it when required.
679
680 // Take better packaging for $objp->qty (first supplier ref quantity <= $objp->qty)
681 $sqlsearchpackage = 'SELECT rowid, packaging FROM '.$this->db->prefix()."product_fournisseur_price";
682 $sqlsearchpackage .= ' WHERE entity IN ('.getEntity('product_fournisseur_price').")";
683 $sqlsearchpackage .= " AND fk_product = ".((int) $objp->fk_product);
684 $sqlsearchpackage .= " AND ref_fourn = '".$this->db->escape($objp->ref_supplier)."'";
685 $sqlsearchpackage .= " AND quantity <= ".((float) $objp->qty); // required to be qualified
686 $sqlsearchpackage .= " AND (packaging IS NULL OR packaging = 0 OR packaging <= ".((float) $objp->qty).")"; // required to be qualified
687 $sqlsearchpackage .= " AND fk_soc = ".((int) $this->socid);
688 $sqlsearchpackage .= " ORDER BY packaging ASC"; // Take the smaller package first
689 $sqlsearchpackage .= " LIMIT 1";
690
691 $resqlsearchpackage = $this->db->query($sqlsearchpackage);
692 if ($resqlsearchpackage) {
693 $objsearchpackage = $this->db->fetch_object($resqlsearchpackage);
694 if ($objsearchpackage) {
695 $line->fk_fournprice = $objsearchpackage->rowid;
696 $line->packaging = $objsearchpackage->packaging;
697 }
698 } else {
699 $this->error = $this->db->lasterror();
700 return -1;
701 }
702 }
703
704 $line->date_start = $this->db->jdate($objp->date_start);
705 $line->date_end = $this->db->jdate($objp->date_end);
706 $line->fk_unit = $objp->fk_unit;
707
708 // Multicurrency
709 $line->fk_multicurrency = $objp->fk_multicurrency;
710 $line->multicurrency_code = $objp->multicurrency_code;
711 $line->multicurrency_subprice = $objp->multicurrency_subprice;
712 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
713 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
714 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
715
716 $line->info_bits = $objp->info_bits;
717 $line->special_code = $objp->special_code;
718 $line->fk_parent_line = $objp->fk_parent_line;
719
720 $line->rang = $objp->rang;
721
722 // Retrieve all extrafield
723 // fetch optionals attributes and labels
724 $line->fetch_optionals();
725
726 $this->lines[$i] = $line;
727
728 $i++;
729 }
730 $this->db->free($result);
731
732 return $num;
733 } else {
734 $this->error = $this->db->error()." sql=".$sql;
735 return -1;
736 }
737 }
738
747 public function valid($user, $idwarehouse = 0, $notrigger = 0)
748 {
749 global $conf;
750 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
751
752 $error = 0;
753
754 dol_syslog(get_class($this)."::valid");
755 $result = 0;
756 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")))
757 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight("fournisseur", "supplier_order_advance", "validate"))) {
758 $this->db->begin();
759
760 // Definition of supplier order numbering model name
761 $soc = new Societe($this->db);
762 $soc->fetch($this->fourn_id);
763
764 // Check if object has a temporary ref
765 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
766 $num = $this->getNextNumRef($soc);
767 } else {
768 $num = $this->ref;
769 }
770 $this->newref = dol_sanitizeFileName($num);
771
772 $sql = 'UPDATE '.$this->db->prefix()."commande_fournisseur";
773 $sql .= " SET ref='".$this->db->escape($num)."',";
774 $sql .= " fk_statut = ".((int) self::STATUS_VALIDATED).",";
775 $sql .= " date_valid='".$this->db->idate(dol_now())."',";
776 $sql .= " fk_user_valid = ".((int) $user->id);
777 $sql .= " WHERE rowid = ".((int) $this->id);
778 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
779
780 $resql = $this->db->query($sql);
781 if (!$resql) {
782 dol_print_error($this->db);
783 $error++;
784 }
785
786 if (!$error && !$notrigger) {
787 // Call trigger
788 $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user);
789 if ($result < 0) {
790 $error++;
791 }
792 // End call triggers
793 }
794
795 if (!$error) {
796 $this->oldref = $this->ref;
797
798 // Rename directory if dir was a temporary ref
799 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
800 // Now we rename also files into index
801 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
802 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
803 $resql = $this->db->query($sql);
804 if (!$resql) {
805 $error++;
806 $this->error = $this->db->lasterror();
807 }
808 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
809 $sql .= " WHERE filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
810 $resql = $this->db->query($sql);
811 if (!$resql) {
812 $error++;
813 $this->error = $this->db->lasterror();
814 }
815
816 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
817 $oldref = dol_sanitizeFileName($this->ref);
818 $newref = dol_sanitizeFileName($num);
819 $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref;
820 $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
821 if (!$error && file_exists($dirsource)) {
822 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
823
824 if (@rename($dirsource, $dirdest)) {
825 dol_syslog("Rename ok");
826 // Rename docs starting with $oldref with $newref
827 $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
828 foreach ($listoffiles as $fileentry) {
829 $dirsource = $fileentry['name'];
830 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
831 $dirsource = $fileentry['path'].'/'.$dirsource;
832 $dirdest = $fileentry['path'].'/'.$dirdest;
833 @rename($dirsource, $dirdest);
834 }
835 }
836 }
837 }
838 }
839
840 if (!$error) {
841 $result = 1;
843 $this->statut = self::STATUS_VALIDATED; // deprecated
844 $this->ref = $num;
845 }
846
847 if (!$error) {
848 $this->db->commit();
849 return 1;
850 } else {
851 $this->db->rollback();
852 return -1;
853 }
854 } else {
855 $this->error = 'NotAuthorized';
856 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
857 return -1;
858 }
859 }
860
867 public function getLibStatut($mode = 0)
868 {
869 return $this->LibStatut($this->statut, $mode, $this->billed);
870 }
871
872 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
881 public function LibStatut($status, $mode = 0, $billed = 0)
882 {
883 // phpcs:enable
884 global $langs, $hookmanager;
885
886 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
887 $langs->load('orders');
888
889 $this->labelStatus[0] = 'StatusSupplierOrderDraft';
890 $this->labelStatus[1] = 'StatusSupplierOrderValidated';
891 $this->labelStatus[2] = 'StatusSupplierOrderApproved';
892 if (!getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
893 $this->labelStatus[3] = 'StatusSupplierOrderOnProcess';
894 } else {
895 $this->labelStatus[3] = 'StatusSupplierOrderOnProcessWithValidation';
896 }
897 $this->labelStatus[4] = 'StatusSupplierOrderReceivedPartially';
898 $this->labelStatus[5] = 'StatusSupplierOrderReceivedAll';
899 $this->labelStatus[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled
900 $this->labelStatus[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled
901 $this->labelStatus[9] = 'StatusSupplierOrderRefused';
902
903 // List of language codes for status
904 $this->labelStatusShort[0] = 'StatusSupplierOrderDraftShort';
905 $this->labelStatusShort[1] = 'StatusSupplierOrderValidatedShort';
906 $this->labelStatusShort[2] = 'StatusSupplierOrderApprovedShort';
907 $this->labelStatusShort[3] = 'StatusSupplierOrderOnProcessShort';
908 $this->labelStatusShort[4] = 'StatusSupplierOrderReceivedPartiallyShort';
909 $this->labelStatusShort[5] = 'StatusSupplierOrderReceivedAllShort';
910 $this->labelStatusShort[6] = 'StatusSupplierOrderCanceledShort';
911 $this->labelStatusShort[7] = 'StatusSupplierOrderCanceledShort';
912 $this->labelStatusShort[9] = 'StatusSupplierOrderRefusedShort';
913 }
914
915 $statustrans = array(
916 0 => 'status0',
917 1 => 'status1b',
918 2 => 'status1',
919 3 => 'status4',
920 4 => 'status4b',
921 5 => 'status6',
922 6 => 'status9',
923 7 => 'status9',
924 9 => 'status9',
925 );
926
927 $statusClass = 'status0';
928 if (!empty($statustrans[$status])) {
929 $statusClass = $statustrans[$status];
930 }
931
932 $billedtext = '';
933 if ($billed) {
934 $billedtext = ' - '.$langs->trans("Billed");
935 }
936 if ($status == 5 && $billed) {
937 $statusClass = 'status6';
938 }
939
940 $statusLong = $langs->transnoentitiesnoconv($this->labelStatus[$status]).$billedtext;
941 $statusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
942
943 $parameters = array('status' => $status, 'mode' => $mode, 'billed' => $billed);
944 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
945 if ($reshook > 0) {
946 return $hookmanager->resPrint;
947 }
948
949 return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode);
950 }
951
958 public function getTooltipContentArray($params)
959 {
960 global $conf, $langs, $user;
961
962 $langs->loadLangs(['bills', 'orders']);
963
964 $datas = [];
965 $nofetch = !empty($params['nofetch']);
966
967 if ($user->hasRight("fournisseur", "commande", "read")) {
968 $datas['picto'] = '<u class="paddingrightonly">'.$langs->trans("SupplierOrder").'</u>';
969 if (isset($this->statut)) {
970 $datas['picto'] .= ' '.$this->getLibStatut(5);
971 }
972 if (!empty($this->ref)) {
973 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
974 }
975 if (!empty($this->ref_supplier)) {
976 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
977 }
978 if (!$nofetch) {
979 $langs->load('companies');
980 if (empty($this->thirdparty)) {
981 $this->fetch_thirdparty();
982 }
983 $datas['supplier'] = '<br><b>'.$langs->trans('Supplier').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
984 }
985 if (!empty($this->total_ht)) {
986 $datas['totalht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
987 }
988 if (!empty($this->total_tva)) {
989 $datas['totaltva'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
990 }
991 if (!empty($this->total_ttc)) {
992 $datas['totalttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
993 }
994 if (!empty($this->date)) {
995 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
996 }
997 if (!empty($this->delivery_date)) {
998 $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
999 }
1000 }
1001 return $datas;
1002 }
1003
1014 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
1015 {
1016 global $langs, $user, $hookmanager;
1017
1018 $result = '';
1019 $params = [
1020 'id' => $this->id,
1021 'objecttype' => $this->element,
1022 'option' => $option,
1023 'nofetch' => 1
1024 ];
1025 $classfortooltip = 'classfortooltip';
1026 $dataparams = '';
1027 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1028 $classfortooltip = 'classforajaxtooltip';
1029 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1030 $label = '';
1031 } else {
1032 $label = implode($this->getTooltipContentArray($params));
1033 }
1034
1035 $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
1036
1037 if ($option !== 'nolink') {
1038 // Add param to save lastsearch_values or not
1039 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1040 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1041 $add_save_lastsearch_values = 1;
1042 }
1043 if ($add_save_lastsearch_values) {
1044 $url .= '&save_lastsearch_values=1';
1045 }
1046 }
1047
1048 $linkclose = '';
1049 if (empty($notooltip)) {
1050 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1051 $label = $langs->trans("ShowOrder");
1052 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1053 }
1054 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
1055 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
1056 }
1057
1058 $linkstart = '<a href="'.$url.'"';
1059 $linkstart .= $linkclose.'>';
1060 $linkend = '</a>';
1061
1062 $result .= $linkstart;
1063 if ($withpicto) {
1064 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1065 }
1066 if ($withpicto != 2) {
1067 $result .= $this->ref;
1068 }
1069 $result .= $linkend;
1070
1071 if ($addlinktonotes) {
1072 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1073 if ($txttoshow) {
1074 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1075 $result .= ' <span class="note inline-block">';
1076 $result .= '<a href="'.DOL_URL_ROOT.'/fourn/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
1077 $result .= img_picto('', 'note');
1078 $result .= '</a>';
1079 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1080 //$result.='</a>';
1081 $result .= '</span>';
1082 }
1083 }
1084
1085 global $action;
1086 $hookmanager->initHooks(array($this->element . 'dao'));
1087 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1088 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1089 if ($reshook > 0) {
1090 $result = $hookmanager->resPrint;
1091 } else {
1092 $result .= $hookmanager->resPrint;
1093 }
1094 return $result;
1095 }
1096
1097
1105 public function getNextNumRef($soc)
1106 {
1107 global $langs, $conf;
1108 $langs->load("orders");
1109
1110 if (getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER')) {
1111 $mybool = false;
1112
1113 $file = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER').'.php';
1114 $classname = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER');
1115
1116 // Include file with class
1117 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1118
1119 foreach ($dirmodels as $reldir) {
1120 $dir = dol_buildpath($reldir."core/modules/supplier_order/");
1121
1122 // Load file with numbering class (if found)
1123 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1124 }
1125
1126 if (!$mybool) {
1127 dol_print_error(null, "Failed to include file ".$file);
1128 return '';
1129 }
1130
1131 $obj = new $classname();
1132 '@phan-var-force ModeleNumRefSuppliersOrders $obj';
1133 $numref = $obj->getNextValue($soc, $this);
1134
1135 if ($numref != "") {
1136 return $numref;
1137 } else {
1138 $this->error = $obj->error;
1139 return -1;
1140 }
1141 } else {
1142 $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
1143 return -2;
1144 }
1145 }
1152 public function classifyBilled(User $user)
1153 {
1154 $error = 0;
1155
1156 if ($this->billed) {
1157 return 0;
1158 }
1159
1160 $this->db->begin();
1161
1162 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur SET billed = 1';
1163 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
1164
1165 if ($this->db->query($sql)) {
1166 if (!$error) {
1167 // Call trigger
1168 $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
1169 if ($result < 0) {
1170 $error++;
1171 }
1172 // End call triggers
1173 }
1174
1175 if (!$error) {
1176 $this->billed = 1;
1177
1178 $this->db->commit();
1179 return 1;
1180 } else {
1181 $this->db->rollback();
1182 return -1;
1183 }
1184 } else {
1185 dol_print_error($this->db);
1186
1187 $this->db->rollback();
1188 return -1;
1189 }
1190 }
1191
1192
1199 public function classifyUnBilled(User $user)
1200 {
1201 if (empty($this->billed)) {
1202 return 0;
1203 }
1204
1205 $this->db->begin();
1206
1207 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur SET billed = 0';
1208 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
1209 ;
1210
1211 if (!$this->db->query($sql)) {
1212 dol_print_error($this->db);
1213 $this->db->rollback();
1214 return -1;
1215 }
1216
1217 // Call trigger
1218 $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_UNBILLED', $user);
1219 if ($result < 0) {
1220 $this->db->rollback();
1221 return -1;
1222 }
1223 // End call triggers
1224
1225 $this->billed = 1;
1226 $this->db->commit();
1227 return 1;
1228 }
1229
1230
1239 public function approve($user, $idwarehouse = 0, $secondlevel = 0)
1240 {
1241 global $langs, $conf;
1242 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1243
1244 $error = 0;
1245
1246 dol_syslog(get_class($this)."::approve");
1247
1248 if ($user->hasRight("fournisseur", "commande", "approuver")) {
1249 $now = dol_now();
1250
1251 $this->db->begin();
1252
1253 // Definition of order numbering model name
1254 $soc = new Societe($this->db);
1255 $soc->fetch($this->fourn_id);
1256
1257 // Check if object has a temporary ref
1258 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1259 $num = $this->getNextNumRef($soc);
1260 } else {
1261 $num = $this->ref;
1262 }
1263 $this->newref = dol_sanitizeFileName($num);
1264
1265 // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
1266 $movetoapprovestatus = true;
1267 $comment = '';
1268
1269 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1270 $sql .= " SET ref='".$this->db->escape($num)."',";
1271 if (empty($secondlevel)) { // standard or first level approval
1272 $sql .= " date_approve='".$this->db->idate($now)."',";
1273 $sql .= " fk_user_approve = ".$user->id;
1274 if (getDolGlobalString('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED') && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) {
1275 if (empty($this->user_approve_id2)) {
1276 $movetoapprovestatus = false; // second level approval not done
1277 $comment = ' (first level)';
1278 }
1279 }
1280 } else { // request a second level approval
1281 $sql .= " date_approve2='".$this->db->idate($now)."',";
1282 $sql .= " fk_user_approve2 = ".((int) $user->id);
1283 if (empty($this->user_approve_id)) {
1284 $movetoapprovestatus = false; // first level approval not done
1285 }
1286 $comment = ' (second level)';
1287 }
1288 // If double approval is required and first approval, we keep status to 1 = validated
1289 if ($movetoapprovestatus) {
1290 $sql .= ", fk_statut = ".self::STATUS_ACCEPTED;
1291 } else {
1292 $sql .= ", fk_statut = ".self::STATUS_VALIDATED;
1293 }
1294 $sql .= " WHERE rowid = ".((int) $this->id);
1295 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1296
1297 if ($this->db->query($sql)) {
1298 if (getDolGlobalString('SUPPLIER_ORDER_AUTOADD_USER_CONTACT')) {
1299 $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
1300 if ($result < 0 && $result != -2) { // -2 means already exists
1301 $error++;
1302 }
1303 }
1304
1305 // If stock is incremented on validate order, we must increment it
1306 if (!$error && $movetoapprovestatus && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER')) {
1307 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1308 $langs->load("agenda");
1309
1310 $cpt = count($this->lines);
1311 for ($i = 0; $i < $cpt; $i++) {
1312 // Product with reference
1313 if ($this->lines[$i]->fk_product > 0) {
1314 $this->line = $this->lines[$i];
1315 $mouvP = new MouvementStock($this->db);
1316 $mouvP->origin = &$this;
1317 $mouvP->setOrigin($this->element, $this->id);
1318 // We decrement stock of product (and sub-products)
1319 $up_ht_disc = $this->lines[$i]->subprice;
1320 if (!empty($this->lines[$i]->remise_percent) && !getDolGlobalString('STOCK_EXCLUDE_DISCOUNT_FOR_PMP')) {
1321 $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1322 }
1323 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref));
1324 if ($result < 0) {
1325 $error++;
1326 }
1327 unset($this->line);
1328 }
1329 }
1330 }
1331
1332 if (!$error) {
1333 // Call trigger
1334 $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user);
1335 if ($result < 0) {
1336 $error++;
1337 }
1338 // End call triggers
1339 }
1340
1341 if (!$error) {
1342 $this->ref = $this->newref;
1343
1344 if ($movetoapprovestatus) {
1345 $this->statut = self::STATUS_ACCEPTED;
1346 } else {
1347 $this->statut = self::STATUS_VALIDATED;
1348 }
1349 if (empty($secondlevel)) { // standard or first level approval
1350 $this->date_approve = $now;
1351 $this->user_approve_id = $user->id;
1352 } else { // request a second level approval
1353 $this->date_approve2 = $now;
1354 $this->user_approve_id2 = $user->id;
1355 }
1356
1357 $this->db->commit();
1358 return 1;
1359 } else {
1360 $this->db->rollback();
1361 return -1;
1362 }
1363 } else {
1364 $this->db->rollback();
1365 $this->error = $this->db->lasterror();
1366 return -1;
1367 }
1368 } else {
1369 dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
1370 }
1371 return -1;
1372 }
1373
1380 public function refuse($user)
1381 {
1382 global $conf, $langs;
1383
1384 $error = 0;
1385
1386 dol_syslog(get_class($this)."::refuse");
1387 $result = 0;
1388 if ($user->hasRight("fournisseur", "commande", "approuver")) {
1389 $this->db->begin();
1390
1391 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
1392 $sql .= " WHERE rowid = ".((int) $this->id);
1393
1394 if ($this->db->query($sql)) {
1395 $result = 0;
1396
1397 if ($error == 0) {
1398 // Call trigger
1399 $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user);
1400 if ($result < 0) {
1401 $error++;
1402 $this->db->rollback();
1403 } else {
1404 $this->db->commit();
1405 }
1406 // End call triggers
1407 }
1408 } else {
1409 $this->db->rollback();
1410 $this->error = $this->db->lasterror();
1411 dol_syslog(get_class($this)."::refuse Error -1");
1412 $result = -1;
1413 }
1414 } else {
1415 dol_syslog(get_class($this)."::refuse Not Authorized");
1416 }
1417 return $result;
1418 }
1419
1420 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1429 public function Cancel($user, $idwarehouse = -1)
1430 {
1431 // phpcs:enable
1432 global $langs, $conf;
1433
1434 $error = 0;
1435
1436 //dol_syslog("CommandeFournisseur::Cancel");
1437 $result = 0;
1438 if ($user->hasRight("fournisseur", "commande", "commander")) {
1439 $statut = self::STATUS_CANCELED;
1440
1441 $this->db->begin();
1442
1443 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur SET fk_statut = ".((int) $statut);
1444 $sql .= " WHERE rowid = ".((int) $this->id);
1445 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
1446 if ($this->db->query($sql)) {
1447 $result = 0;
1448
1449 // Call trigger
1450 $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user);
1451 if ($result < 0) {
1452 $error++;
1453 }
1454 // End call triggers
1455
1456 if ($error == 0) {
1457 $this->db->commit();
1458 return 1;
1459 } else {
1460 $this->db->rollback();
1461 return -1;
1462 }
1463 } else {
1464 $this->db->rollback();
1465 $this->error = $this->db->lasterror();
1466 dol_syslog(get_class($this)."::cancel ".$this->error);
1467 return -1;
1468 }
1469 } else {
1470 dol_syslog(get_class($this)."::cancel Not Authorized");
1471 return -1;
1472 }
1473 }
1474
1484 public function commande($user, $date, $methode, $comment = '')
1485 {
1486 global $langs;
1487 dol_syslog(get_class($this)."::commande");
1488 $error = 0;
1489 if ($user->hasRight("fournisseur", "commande", "commander")) {
1490 $this->db->begin();
1491
1492 $newnoteprivate = $this->note_private;
1493 if ($comment) {
1494 $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment);
1495 }
1496
1497 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1498 $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', ";
1499 $sql .= " note_private='".$this->db->escape($newnoteprivate)."'";
1500 $sql .= " WHERE rowid=".((int) $this->id);
1501
1502 dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1503 if ($this->db->query($sql)) {
1504 $this->statut = self::STATUS_ORDERSENT;
1505 $this->methode_commande_id = $methode;
1506 $this->date_commande = $date;
1507 $this->context = array('comments' => $comment);
1508
1509 // Call trigger
1510 $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
1511 if ($result < 0) {
1512 $error++;
1513 }
1514 // End call triggers
1515 } else {
1516 $error++;
1517 $this->error = $this->db->lasterror();
1518 $this->errors[] = $this->db->lasterror();
1519 }
1520
1521 if (!$error) {
1522 $this->db->commit();
1523 } else {
1524 $this->db->rollback();
1525 }
1526 } else {
1527 $error++;
1528 $this->error = $langs->trans('NotAuthorized');
1529 $this->errors[] = $langs->trans('NotAuthorized');
1530 dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1531 }
1532
1533 return ($error ? -1 : 1);
1534 }
1535
1543 public function create($user, $notrigger = 0)
1544 {
1545 global $langs, $conf, $hookmanager;
1546
1547 $this->db->begin();
1548
1549 $error = 0;
1550 $now = dol_now();
1551
1552 // set tmp vars
1553 $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set
1554 if (empty($date)) {
1555 $date = $now;
1556 }
1557 $delivery_date = $this->delivery_date;
1558
1559 // Clean parameters
1560 if (empty($this->source)) {
1561 $this->source = 0;
1562 }
1563
1564 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1565 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1566 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
1567 } else {
1568 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1569 }
1570 if (empty($this->fk_multicurrency)) {
1571 $this->multicurrency_code = $conf->currency;
1572 $this->fk_multicurrency = 0;
1573 $this->multicurrency_tx = 1;
1574 }
1575
1576 $this->statut = self::STATUS_DRAFT; // deprecated
1577 $this->status = self::STATUS_DRAFT;
1578
1579 $sql = "INSERT INTO ".$this->db->prefix()."commande_fournisseur (";
1580 $sql .= "ref";
1581 $sql .= ", ref_supplier";
1582 $sql .= ", note_private";
1583 $sql .= ", note_public";
1584 $sql .= ", entity";
1585 $sql .= ", fk_soc";
1586 $sql .= ", fk_projet";
1587 $sql .= ", date_creation";
1588 $sql .= ", date_livraison";
1589 $sql .= ", fk_user_author";
1590 $sql .= ", fk_statut";
1591 $sql .= ", source";
1592 $sql .= ", model_pdf";
1593 $sql .= ", fk_mode_reglement";
1594 $sql .= ", fk_cond_reglement";
1595 $sql .= ", fk_account";
1596 $sql .= ", fk_incoterms, location_incoterms";
1597 $sql .= ", fk_multicurrency";
1598 $sql .= ", multicurrency_code";
1599 $sql .= ", multicurrency_tx";
1600 $sql .= ") ";
1601 $sql .= " VALUES (";
1602 $sql .= "'(PROV)'";
1603 $sql .= ", ".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "NULL");
1604 $sql .= ", '".$this->db->escape($this->note_private)."'";
1605 $sql .= ", '".$this->db->escape($this->note_public)."'";
1606 $sql .= ", ".setEntity($this);
1607 $sql .= ", ".((int) $this->socid);
1608 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1609 $sql .= ", '".$this->db->idate($date)."'";
1610 $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1611 $sql .= ", ".((int) $user->id);
1612 $sql .= ", ".self::STATUS_DRAFT;
1613 $sql .= ", ".((int) $this->source);
1614 $sql .= ", '".$this->db->escape(getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF'))."'";
1615 $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1616 $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1617 $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
1618 $sql .= ", ".(int) $this->fk_incoterms;
1619 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1620 $sql .= ", ".(int) $this->fk_multicurrency;
1621 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1622 $sql .= ", ".(float) $this->multicurrency_tx;
1623 $sql .= ")";
1624
1625 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1626 if ($this->db->query($sql)) {
1627 $this->id = $this->db->last_insert_id($this->db->prefix()."commande_fournisseur");
1628
1629 if ($this->id) {
1630 $num = count($this->lines);
1631
1632 // insert products details into database
1633 for ($i = 0; $i < $num; $i++) {
1634 $line = $this->lines[$i];
1635 if (!is_object($line)) {
1636 $line = (object) $line;
1637 }
1638
1639 //$this->special_code = $line->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
1640
1641 // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1642 $result = $this->addline(
1643 $line->desc,
1644 $line->subprice,
1645 $line->qty,
1646 $line->tva_tx,
1647 $line->localtax1_tx,
1648 $line->localtax2_tx,
1649 $line->fk_product,
1650 0,
1651 $line->ref_fourn, // $line->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1652 $line->remise_percent,
1653 'HT',
1654 0,
1655 $line->product_type,
1656 $line->info_bits,
1657 0,
1658 $line->date_start,
1659 $line->date_end,
1660 $line->array_options,
1661 $line->fk_unit,
1662 $line->multicurrency_subprice, // pu_ht_devise
1663 $line->origin, // origin
1664 $line->origin_id, // origin_id
1665 $line->rang, // rang
1666 $line->special_code
1667 );
1668 if ($result < 0) {
1669 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functional error
1670 $this->db->rollback();
1671 return -1;
1672 }
1673 }
1674
1675 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1676 $sql .= " SET ref='(PROV".$this->id.")'";
1677 $sql .= " WHERE rowid=".((int) $this->id);
1678
1679 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1680 if ($this->db->query($sql)) {
1681 // Add link with price request and supplier order
1682 if ($this->id) {
1683 $this->ref = "(PROV".$this->id.")";
1684
1685 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1686 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1687 }
1688
1689 // Add object linked
1690 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1691 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1692 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, ...))
1693 foreach ($tmp_origin_id as $origin_id) {
1694 $ret = $this->add_object_linked($origin, $origin_id);
1695 if (!$ret) {
1696 dol_print_error($this->db);
1697 $error++;
1698 }
1699 }
1700 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1701 $origin_id = $tmp_origin_id;
1702 $ret = $this->add_object_linked($origin, $origin_id);
1703 if (!$ret) {
1704 dol_print_error($this->db);
1705 $error++;
1706 }
1707 }
1708 }
1709 }
1710 }
1711
1712 if (!$error) {
1713 $result = $this->insertExtraFields();
1714 if ($result < 0) {
1715 $error++;
1716 }
1717 }
1718
1719 if (!$error && !$notrigger) {
1720 // Call trigger
1721 $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user);
1722 if ($result < 0) {
1723 $this->db->rollback();
1724
1725 return -1;
1726 }
1727 // End call triggers
1728 }
1729
1730 $this->db->commit();
1731 return $this->id;
1732 } else {
1733 $this->error = $this->db->lasterror();
1734 $this->db->rollback();
1735
1736 return -2;
1737 }
1738 } else {
1739 $this->error = 'Failed to get ID of inserted line';
1740
1741 return -1;
1742 }
1743 } else {
1744 $this->error = $this->db->lasterror();
1745 $this->db->rollback();
1746
1747 return -1;
1748 }
1749 }
1750
1758 public function update(User $user, $notrigger = 0)
1759 {
1760 global $conf;
1761
1762 $error = 0;
1763
1764 // Clean parameters
1765 if (isset($this->ref)) {
1766 $this->ref = trim($this->ref);
1767 }
1768 if (isset($this->ref_supplier)) {
1769 $this->ref_supplier = trim($this->ref_supplier);
1770 }
1771 if (isset($this->note_private)) {
1772 $this->note_private = trim($this->note_private);
1773 }
1774 if (isset($this->note_public)) {
1775 $this->note_public = trim($this->note_public);
1776 }
1777 if (isset($this->model_pdf)) {
1778 $this->model_pdf = trim($this->model_pdf);
1779 }
1780 if (isset($this->import_key)) {
1781 $this->import_key = trim($this->import_key);
1782 }
1783
1784 // Update request
1785 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET";
1786
1787 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1788 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1789 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1790 $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
1791 $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
1792 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1793 $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
1794 $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
1795 $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
1796 $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
1797 $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
1798 $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
1799 $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
1800 $sql .= " fk_user_valid=".(isset($this->user_validation_id) && $this->user_validation_id > 0 ? $this->user_validation_id : "null").",";
1801 $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
1802 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
1803 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
1804 $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
1805 //$sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").",";
1806 $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").",";
1807 //$sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").",";
1808 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1809 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1810 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1811 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1812
1813 $sql .= " WHERE rowid=".((int) $this->id);
1814
1815 $this->db->begin();
1816
1817 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1818 $resql = $this->db->query($sql);
1819 if (!$resql) {
1820 $error++;
1821 $this->errors[] = "Error ".$this->db->lasterror();
1822 }
1823
1824 if (!$error) {
1825 $result = $this->insertExtraFields();
1826 if ($result < 0) {
1827 $error++;
1828 }
1829 }
1830
1831 if (!$error && !$notrigger) {
1832 // Call trigger
1833 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
1834 if ($result < 0) {
1835 $error++;
1836 }
1837 // End call triggers
1838 }
1839
1840 // Commit or rollback
1841 if ($error) {
1842 foreach ($this->errors as $errmsg) {
1843 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1844 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1845 }
1846 $this->db->rollback();
1847 return -1 * $error;
1848 } else {
1849 $this->db->commit();
1850 return 1;
1851 }
1852 }
1853
1862 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
1863 {
1864 global $conf, $user, $hookmanager;
1865
1866 $error = 0;
1867
1868 $this->db->begin();
1869
1870 // get extrafields so they will be clone
1871 foreach ($this->lines as $line) {
1872 $line->fetch_optionals();
1873 }
1874
1875 // Load source object
1876 $objFrom = clone $this;
1877
1878 // Change socid if needed
1879 if (!empty($socid) && $socid != $this->socid) {
1880 $objsoc = new Societe($this->db);
1881
1882 if ($objsoc->fetch($socid) > 0) {
1883 $this->socid = $objsoc->id;
1884 $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1885 $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1886 $this->fk_project = 0;
1887 $this->fk_delivery_address = 0;
1888 }
1889
1890 // TODO Change product price if multi-prices
1891 }
1892
1893 $this->id = 0;
1894 $this->statut = self::STATUS_DRAFT;
1895
1896 // Clear fields
1897 $this->user_author_id = $user->id;
1898 $this->user_validation_id = 0;
1899
1900 $this->date = dol_now();
1901 $this->date_creation = 0;
1902 $this->date_validation = 0;
1903 $this->date_commande = 0;
1904 $this->ref_supplier = '';
1905 $this->user_approve_id = 0;
1906 $this->user_approve_id2 = 0;
1907 $this->date_approve = 0;
1908 $this->date_approve2 = 0;
1909
1910 // Create clone
1911 $this->context['createfromclone'] = 'createfromclone';
1912 $result = $this->create($user, $notrigger);
1913 if ($result < 0) {
1914 $error++;
1915 }
1916
1917 if (!$error) {
1918 // Hook of thirdparty module
1919 if (is_object($hookmanager)) {
1920 $parameters = array('objFrom' => $objFrom);
1921 $action = '';
1922 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1923 if ($reshook < 0) {
1924 $this->setErrorsFromObject($hookmanager);
1925 $error++;
1926 }
1927 }
1928 }
1929
1930 unset($this->context['createfromclone']);
1931
1932 // End
1933 if (!$error) {
1934 $this->db->commit();
1935 return $this->id;
1936 } else {
1937 $this->db->rollback();
1938 return -1;
1939 }
1940 }
1941
1971 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $fk_prod_fourn_price = 0, $ref_supplier = '', $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $type = 0, $info_bits = 0, $notrigger = 0, $date_start = null, $date_end = null, $array_options = [], $fk_unit = null, $pu_ht_devise = 0, $origin = '', $origin_id = 0, $rang = -1, $special_code = 0)
1972 {
1973 global $langs, $mysoc, $conf;
1974
1975 dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, $info_bits, $notrigger, $date_start, $date_end, $fk_unit, $pu_ht_devise, $origin, $origin_id");
1976 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1977
1978 if ($this->statut == self::STATUS_DRAFT) {
1979 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1980
1981 // Clean parameters
1982 if (empty($qty)) {
1983 $qty = 0;
1984 }
1985 if (!$info_bits) {
1986 $info_bits = 0;
1987 }
1988 if (empty($txtva)) {
1989 $txtva = 0;
1990 }
1991 if (empty($rang)) {
1992 $rang = 0;
1993 }
1994 if (empty($txlocaltax1)) {
1995 $txlocaltax1 = 0;
1996 }
1997 if (empty($txlocaltax2)) {
1998 $txlocaltax2 = 0;
1999 }
2000 if (empty($remise_percent)) {
2001 $remise_percent = 0;
2002 }
2003
2004 $remise_percent = price2num($remise_percent);
2005 $qty = price2num($qty);
2006 $pu_ht = price2num($pu_ht);
2007 $pu_ht_devise = price2num($pu_ht_devise);
2008 $pu_ttc = price2num($pu_ttc);
2009 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
2010 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
2011 }
2012 $txlocaltax1 = price2num($txlocaltax1);
2013 $txlocaltax2 = price2num($txlocaltax2);
2014 if ($price_base_type == 'HT') {
2015 $pu = $pu_ht;
2016 } else {
2017 $pu = $pu_ttc;
2018 }
2019 $desc = trim($desc);
2020
2021 // Check parameters
2022 if ($qty < 0 && !$fk_product) {
2023 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product"));
2024 return -1;
2025 }
2026 if ($type < 0) {
2027 return -1;
2028 }
2029 if ($date_start && $date_end && $date_start > $date_end) {
2030 $langs->load("errors");
2031 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2032 return -1;
2033 }
2034
2035
2036 $this->db->begin();
2037
2038 $product_type = $type;
2039 $label = ''; // deprecated
2040
2041 if ($fk_product > 0) {
2042 if (getDolGlobalString('SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY')) { // Not the common case
2043 // Check quantity is enough
2044 dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." ref_supplier=".$ref_supplier);
2045 $prod = new ProductFournisseur($this->db);
2046 if ($prod->fetch($fk_product) > 0) {
2047 $product_type = $prod->type;
2048 $label = $prod->label;
2049
2050 // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
2051 // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
2052 $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', (isset($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
2053
2054 // If supplier order created from sales order, we take best supplier price
2055 // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price
2056 if ($result > 0 && ($origin == 'commande' || $pu === '')) {
2057 $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
2058 $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
2059 // is remise percent not keyed but present for the product we add it
2060 if ($remise_percent == 0 && $prod->remise_percent != 0) {
2061 $remise_percent = $prod->remise_percent;
2062 }
2063 }
2064 if ($result == 0) { // If result == 0, we failed to found the supplier reference price
2065 $langs->load("errors");
2066 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2067 $this->db->rollback();
2068 dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
2069 //$pu = $prod->fourn_pu; // We do not overwrite unit price
2070 //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
2071 return -1;
2072 }
2073 if ($result == -1) {
2074 $langs->load("errors");
2075 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2076 $this->db->rollback();
2077 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
2078 return -1;
2079 }
2080 if ($result < -1) {
2081 $this->error = $prod->error;
2082 $this->db->rollback();
2083 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
2084 return -1;
2085 }
2086 } else {
2087 $this->error = $prod->error;
2088 $this->db->rollback();
2089 return -1;
2090 }
2091 }
2092
2093 // Predefine quantity according to packaging
2094 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2095 $prod = new Product($this->db);
2096 $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', (empty($this->fk_soc) ? $this->socid : $this->fk_soc));
2097
2098 if ($qty < $prod->packaging) {
2099 $qty = $prod->packaging;
2100 } else {
2101 if (!empty($prod->packaging) && (fmod((float) $qty, $prod->packaging) > 0.000001)) {
2102 $coeff = intval((float) $qty / $prod->packaging) + 1;
2103 $qty = (float) $prod->packaging * $coeff;
2104 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'mesgs');
2105 }
2106 }
2107 }
2108 }
2109
2110 if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
2111 $pu = 0;
2112 }
2113
2114 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2115
2116 // Clean vat code
2117 $reg = array();
2118 $vat_src_code = '';
2119 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
2120 $vat_src_code = $reg[1];
2121 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
2122 }
2123
2124 // Calcul du total TTC et de la TVA pour la ligne a partir de
2125 // qty, pu, remise_percent et txtva
2126 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2127 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2128
2129 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2130
2131 $total_ht = $tabprice[0];
2132 $total_tva = $tabprice[1];
2133 $total_ttc = $tabprice[2];
2134 $total_localtax1 = $tabprice[9];
2135 $total_localtax2 = $tabprice[10];
2136 $pu = $pu_ht = $tabprice[3];
2137
2138 // MultiCurrency
2139 $multicurrency_total_ht = $tabprice[16];
2140 $multicurrency_total_tva = $tabprice[17];
2141 $multicurrency_total_ttc = $tabprice[18];
2142 $pu_ht_devise = $tabprice[19];
2143
2144 $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
2145 $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
2146
2147 if ($rang < 0) {
2148 $rangmax = $this->line_max();
2149 $rang = $rangmax + 1;
2150 }
2151
2152 // Insert line
2153 $this->line = new CommandeFournisseurLigne($this->db);
2154
2155 $this->line->context = $this->context;
2156
2157 $this->line->fk_commande = $this->id;
2158 $this->line->label = $label;
2159 $this->line->ref_fourn = $ref_supplier;
2160 $this->line->ref_supplier = $ref_supplier;
2161 $this->line->desc = $desc;
2162 $this->line->qty = $qty;
2163 $this->line->tva_tx = $txtva;
2164 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
2165 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
2166 $this->line->localtax1_type = $localtax1_type;
2167 $this->line->localtax2_type = $localtax2_type;
2168 $this->line->fk_product = $fk_product;
2169 $this->line->product_type = $product_type;
2170 $this->line->remise_percent = $remise_percent;
2171 $this->line->subprice = $pu_ht;
2172 $this->line->rang = $rang;
2173 $this->line->info_bits = $info_bits;
2174
2175 $this->line->vat_src_code = $vat_src_code;
2176 $this->line->total_ht = $total_ht;
2177 $this->line->total_tva = $total_tva;
2178 $this->line->total_localtax1 = $total_localtax1;
2179 $this->line->total_localtax2 = $total_localtax2;
2180 $this->line->total_ttc = $total_ttc;
2181 $this->line->product_type = $type;
2182 $this->line->special_code = (!empty($special_code) ? $special_code : 0);
2183 $this->line->origin = $origin;
2184 $this->line->origin_id = $origin_id;
2185 $this->line->fk_unit = $fk_unit;
2186
2187 $this->line->date_start = $date_start;
2188 $this->line->date_end = $date_end;
2189
2190 // Multicurrency
2191 $this->line->fk_multicurrency = $this->fk_multicurrency;
2192 $this->line->multicurrency_code = $this->multicurrency_code;
2193 $this->line->multicurrency_subprice = $pu_ht_devise;
2194 $this->line->multicurrency_total_ht = $multicurrency_total_ht;
2195 $this->line->multicurrency_total_tva = $multicurrency_total_tva;
2196 $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
2197
2198 $this->line->subprice = $pu_ht;
2199 $this->line->price = $this->line->subprice;
2200
2201 $this->line->remise_percent = $remise_percent;
2202
2203 if (is_array($array_options) && count($array_options) > 0) {
2204 $this->line->array_options = $array_options;
2205 }
2206
2207 $result = $this->line->insert($notrigger);
2208 if ($result > 0) {
2209 // Reorder if child line
2210 if (!empty($this->line->fk_parent_line)) {
2211 $this->line_order(true, 'DESC');
2212 } elseif ($rang > 0 && $rang <= count($this->lines)) { // Update all rank of all other lines
2213 $linecount = count($this->lines);
2214 for ($ii = $rang; $ii <= $linecount; $ii++) {
2215 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2216 }
2217 }
2218
2219 // Mise a jour information denormalisees au niveau de la commande meme
2220 $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
2221 if ($result > 0) {
2222 $this->db->commit();
2223 return $this->line->id;
2224 } else {
2225 $this->db->rollback();
2226 return -1;
2227 }
2228 } else {
2229 $this->error = $this->line->error;
2230 $this->errors = $this->line->errors;
2231 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
2232 $this->db->rollback();
2233 return -1;
2234 }
2235 }
2236 return -1;
2237 }
2238
2239
2257 public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0, $fk_reception = 0)
2258 {
2259 global $conf, $langs;
2260
2261 $error = 0;
2262 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2263
2264 // Check parameters (if test are wrong here, there is bug into caller)
2265 if ($entrepot <= 0) {
2266 $this->error = 'ErrorBadValueForParameterWarehouse';
2267 return -1;
2268 }
2269 if ($qty == 0) {
2270 $this->error = 'ErrorBadValueForParameterQty';
2271 return -1;
2272 }
2273
2274 $dispatchstatus = 1;
2275 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
2276 $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
2277 }
2278
2279 $now = dol_now();
2280
2281 $inventorycode = dol_print_date(dol_now(), 'dayhourlog');
2282
2283 if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) {
2284 $this->db->begin();
2285
2286 $sql = "INSERT INTO ".$this->db->prefix()."receptiondet_batch";
2287 $sql .= " (fk_element, fk_product, qty, fk_entrepot, fk_user, datec, fk_elementdet, status, comment, eatby, sellby, batch, fk_reception) VALUES";
2288 $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
2289 $sql .= ($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ".($batch ? "'".$this->db->escape($batch)."'" : "null").", ".($fk_reception > 0 ? "'".$this->db->escape($fk_reception)."'" : "null");
2290 $sql .= ")";
2291
2292 dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
2293 $resql = $this->db->query($sql);
2294 if ($resql) {
2295 if (!$notrigger) {
2296 global $conf, $langs, $user;
2297 // Call trigger
2298 $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user);
2299 if ($result < 0) {
2300 $error++;
2301 }
2302 // End call triggers
2303 }
2304 } else {
2305 $this->error = $this->db->lasterror();
2306 $error++;
2307 }
2308
2309 // If module stock is enabled and the stock increase is done on purchase order dispatching
2310 if (!$error && $entrepot > 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER')) {
2311 $mouv = new MouvementStock($this->db);
2312 if ($product > 0) {
2313 // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
2314 $mouv->origin = &$this;
2315 $mouv->setOrigin($this->element, $this->id);
2316
2317 // Method change if qty < 0
2318 if (getDolGlobalString('SUPPLIER_ORDER_ALLOW_NEGATIVE_QTY_FOR_SUPPLIER_ORDER_RETURN') && $qty < 0) {
2319 $result = $mouv->livraison($user, $product, $entrepot, $qty * (-1), $price, $comment, $now, $eatby, $sellby, $batch, 0, $inventorycode);
2320 } else {
2321 $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch, '', 0, $inventorycode);
2322 }
2323
2324 if ($result < 0) {
2325 $this->error = $mouv->error;
2326 $this->errors = $mouv->errors;
2327 dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".implode(',', $this->errors), LOG_ERR);
2328 $error++;
2329 }
2330 }
2331 }
2332
2333 if ($error == 0) {
2334 $this->db->commit();
2335 return 1;
2336 } else {
2337 $this->db->rollback();
2338 return -1;
2339 }
2340 } else {
2341 $this->error = 'BadStatusForObject';
2342 return -2;
2343 }
2344 }
2345
2353 public function deleteLine($idline, $notrigger = 0)
2354 {
2355 global $user;
2356
2357 if ($this->statut == 0) {
2358 $line = new CommandeFournisseurLigne($this->db);
2359
2360 if ($line->fetch($idline) <= 0) {
2361 return 0;
2362 }
2363
2364 // check if not yet received
2365 $dispatchedLines = $this->getDispachedLines();
2366 foreach ($dispatchedLines as $dispatchLine) {
2367 if ($dispatchLine['orderlineid'] == $idline) {
2368 $this->error = "LineAlreadyDispatched";
2369 $this->errors[] = $this->error;
2370 return -3;
2371 }
2372 }
2373
2374 if ($line->delete($user, $notrigger) > 0) {
2375 $this->update_price(1);
2376 return 1;
2377 } else {
2378 $this->setErrorsFromObject($line);
2379 return -1;
2380 }
2381 } else {
2382 return -2;
2383 }
2384 }
2385
2393 public function delete(User $user, $notrigger = 0)
2394 {
2395 global $langs, $conf;
2396 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2397
2398 $error = 0;
2399
2400 $this->db->begin();
2401
2402 if (empty($notrigger)) {
2403 // Call trigger
2404 $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user);
2405 if ($result < 0) {
2406 $this->errors[] = 'ErrorWhenRunningTrigger';
2407 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2408 $this->db->rollback();
2409 return -1;
2410 }
2411 // End call triggers
2412 }
2413
2414 // Test we can delete
2415 $this->fetchObjectLinked(null, 'order_supplier');
2416 if (!empty($this->linkedObjects) && array_key_exists('reception', $this->linkedObjects)) {
2417 foreach ($this->linkedObjects['reception'] as $element) {
2418 if ($element->statut >= 0) {
2419 $this->errors[] = $langs->trans('ReceptionExist');
2420 $error++;
2421 break;
2422 }
2423 }
2424 }
2425
2426 $main = $this->db->prefix().'commande_fournisseurdet';
2427 $ef = $main."_extrafields";
2428 $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_commande = ".((int) $this->id).")";
2429 dol_syslog(get_class($this)."::delete extrafields lines", LOG_DEBUG);
2430 if (!$this->db->query($sql)) {
2431 $this->error = $this->db->lasterror();
2432 $this->errors[] = $this->db->lasterror();
2433 $error++;
2434 }
2435
2436 $sql = "DELETE FROM ".$this->db->prefix()."commande_fournisseurdet WHERE fk_commande =".((int) $this->id);
2437 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2438 if (!$this->db->query($sql)) {
2439 $this->error = $this->db->lasterror();
2440 $this->errors[] = $this->db->lasterror();
2441 $error++;
2442 }
2443
2444 $sql = "DELETE FROM ".$this->db->prefix()."commande_fournisseur WHERE rowid =".((int) $this->id);
2445 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2446 if ($resql = $this->db->query($sql)) {
2447 if ($this->db->affected_rows($resql) < 1) {
2448 $this->error = $this->db->lasterror();
2449 $this->errors[] = $this->db->lasterror();
2450 $error++;
2451 }
2452 } else {
2453 $this->error = $this->db->lasterror();
2454 $this->errors[] = $this->db->lasterror();
2455 $error++;
2456 }
2457
2458 // Remove extrafields
2459 if (!$error) {
2460 $result = $this->deleteExtraFields();
2461 if ($result < 0) {
2462 $this->error = 'FailToDeleteExtraFields';
2463 $this->errors[] = 'FailToDeleteExtraFields';
2464 $error++;
2465 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
2466 }
2467 }
2468
2469 // Delete linked object
2470 $res = $this->deleteObjectLinked();
2471 if ($res < 0) {
2472 $this->error = 'FailToDeleteObjectLinked';
2473 $this->errors[] = 'FailToDeleteObjectLinked';
2474 $error++;
2475 }
2476
2477 if (!$error) {
2478 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2479 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2480 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2481
2482 // We remove directory
2483 $ref = dol_sanitizeFileName($this->ref);
2484 if ($conf->fournisseur->commande->dir_output) {
2485 $dir = $conf->fournisseur->commande->dir_output."/".$ref;
2486 $file = $dir."/".$ref.".pdf";
2487 if (file_exists($file)) {
2488 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2489 $this->error = 'ErrorFailToDeleteFile';
2490 $this->errors[] = 'ErrorFailToDeleteFile';
2491 $error++;
2492 }
2493 }
2494 if (file_exists($dir)) {
2495 $res = @dol_delete_dir_recursive($dir);
2496 if (!$res) {
2497 $this->error = 'ErrorFailToDeleteDir';
2498 $this->errors[] = 'ErrorFailToDeleteDir';
2499 $error++;
2500 }
2501 }
2502 }
2503 }
2504
2505 if (!$error) {
2506 dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
2507 $this->db->commit();
2508 return 1;
2509 } else {
2510 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2511 $this->db->rollback();
2512 return -$error;
2513 }
2514 }
2515
2516
2525 public function getDispachedLines($status = -1)
2526 {
2527 $ret = array();
2528
2529 // List of already dispatched lines
2530 $sql = "SELECT p.ref, p.label,";
2531 $sql .= " e.rowid as warehouse_id, e.ref as entrepot,";
2532 $sql .= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status, cfd.fk_elementdet";
2533 $sql .= " FROM ".$this->db->prefix()."product as p,";
2534 $sql .= " ".$this->db->prefix()."receptiondet_batch as cfd";
2535 $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e ON cfd.fk_entrepot = e.rowid";
2536 $sql .= " WHERE cfd.fk_element = ".((int) $this->id);
2537 $sql .= " AND cfd.fk_product = p.rowid";
2538 if ($status >= 0) {
2539 $sql .= " AND cfd.status = ".((int) $status);
2540 }
2541 $sql .= " ORDER BY cfd.rowid ASC";
2542
2543 $resql = $this->db->query($sql);
2544 if ($resql) {
2545 $num = $this->db->num_rows($resql);
2546 $i = 0;
2547
2548 while ($i < $num) {
2549 $objp = $this->db->fetch_object($resql);
2550 if ($objp) {
2551 $ret[] = array(
2552 'id' => $objp->dispatchedlineid,
2553 'productid' => $objp->fk_product,
2554 'warehouseid' => $objp->warehouse_id,
2555 'qty' => $objp->qty,
2556 'orderlineid' => $objp->fk_elementdet
2557 );
2558 }
2559
2560 $i++;
2561 }
2562 } else {
2563 dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
2564 }
2565
2566 return $ret;
2567 }
2568
2569 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2579 public function Livraison($user, $date, $type, $comment)
2580 {
2581 // phpcs:enable
2582 global $conf, $langs;
2583
2584 $result = 0;
2585 $error = 0;
2586
2587 dol_syslog(get_class($this)."::Livraison");
2588
2589 $usercanreceive = 0;
2590 if (!isModEnabled('reception')) {
2591 $usercanreceive = $user->hasRight("fournisseur", "commande", "receptionner");
2592 } else {
2593 $usercanreceive = $user->hasRight("reception", "creer");
2594 }
2595
2596 if ($usercanreceive) {
2597 // Define the new status
2598 if ($type == 'par') {
2600 } elseif ($type == 'tot') {
2602 } elseif ($type == 'nev') {
2604 } elseif ($type == 'can') {
2606 } else {
2607 $error++;
2608 dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
2609 return -2;
2610 }
2611
2612 // Some checks to accept the record
2613 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
2614 // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
2615 if (!$error && ($type == 'tot')) {
2616 $dispatchedlinearray = $this->getDispachedLines(0);
2617 if (count($dispatchedlinearray) > 0) {
2618 $result = -1;
2619 $error++;
2620 $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
2621 dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
2622 }
2623 }
2624 if (!$error && getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE') && ($type == 'tot')) { // Accept to move to reception done, only if status of all line are ok (refuse denied)
2625 $dispatcheddenied = $this->getDispachedLines(2);
2626 if (count($dispatchedlinearray) > 0) {
2627 $result = -1;
2628 $error++;
2629 $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
2630 dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
2631 }
2632 }
2633 }
2634
2635 // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
2636
2637 if (empty($error)) {
2638 $this->db->begin();
2639
2640 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2641 $sql .= " SET fk_statut = ".((int) $statut);
2642 $sql .= " WHERE rowid = ".((int) $this->id);
2643 $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received
2644
2645 dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2646 $resql = $this->db->query($sql);
2647 if ($resql) {
2648 $result = 1;
2649 $old_statut = $this->statut;
2650 $this->statut = $statut;
2651 $this->context['actionmsg2'] = $comment;
2652
2653 // Call trigger
2654 $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
2655 if ($result_trigger < 0) {
2656 $error++;
2657 }
2658 // End call triggers
2659
2660 if (empty($error)) {
2661 $this->db->commit();
2662 } else {
2663 $this->statut = $old_statut;
2664 $this->db->rollback();
2665 $this->error = $this->db->lasterror();
2666 $result = -1;
2667 }
2668 } else {
2669 $this->db->rollback();
2670 $this->error = $this->db->lasterror();
2671 $result = -1;
2672 }
2673 }
2674 } else {
2675 $this->error = $langs->trans('NotAuthorized');
2676 $this->errors[] = $langs->trans('NotAuthorized');
2677 dol_syslog(get_class($this)."::Livraison Not Authorized");
2678 $result = -3;
2679 }
2680 return $result;
2681 }
2682
2683 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2693 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2694 {
2695 // phpcs:enable
2696 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2697 }
2698
2707 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2708 {
2709 if ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")) {
2710 $error = 0;
2711
2712 $this->db->begin();
2713
2714 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2715 $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2716 $sql .= " WHERE rowid = ".((int) $this->id);
2717
2718 dol_syslog(__METHOD__, LOG_DEBUG);
2719 $resql = $this->db->query($sql);
2720 if (!$resql) {
2721 $this->errors[] = $this->db->error();
2722 $error++;
2723 }
2724
2725 if (!$error) {
2726 $this->oldcopy = clone $this;
2727 $this->delivery_date = $delivery_date;
2728 }
2729
2730 if (!$notrigger && empty($error)) {
2731 // Call trigger
2732 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2733 if ($result < 0) {
2734 $error++;
2735 }
2736 // End call triggers
2737 }
2738
2739 if (!$error) {
2740 $this->db->commit();
2741 return 1;
2742 } else {
2743 foreach ($this->errors as $errmsg) {
2744 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2745 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2746 }
2747 $this->db->rollback();
2748 return -1 * $error;
2749 }
2750 } else {
2751 return -2;
2752 }
2753 }
2754
2755 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2764 public function set_id_projet($user, $id_projet, $notrigger = 0)
2765 {
2766 // phpcs:enable
2767 if ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")) {
2768 $error = 0;
2769
2770 $this->db->begin();
2771
2772 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2773 $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2774 $sql .= " WHERE rowid = ".((int) $this->id);
2775
2776 dol_syslog(__METHOD__, LOG_DEBUG);
2777 $resql = $this->db->query($sql);
2778 if (!$resql) {
2779 $this->errors[] = $this->db->error();
2780 $error++;
2781 }
2782
2783 if (!$error) {
2784 $this->oldcopy = clone $this;
2785 $this->fk_projet = $id_projet;
2786 $this->fk_project = $id_projet;
2787 }
2788
2789 if (!$notrigger && empty($error)) {
2790 // Call trigger
2791 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2792 if ($result < 0) {
2793 $error++;
2794 }
2795 // End call triggers
2796 }
2797
2798 if (!$error) {
2799 $this->db->commit();
2800 return 1;
2801 } else {
2802 foreach ($this->errors as $errmsg) {
2803 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2804 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2805 }
2806 $this->db->rollback();
2807 return -1 * $error;
2808 }
2809 } else {
2810 return -2;
2811 }
2812 }
2813
2822 public function updateFromCommandeClient($user, $idc, $comclientid)
2823 {
2824 $comclient = new Commande($this->db);
2825 $comclient->fetch($comclientid);
2826
2827 $this->id = $idc;
2828
2829 $this->lines = array();
2830
2831 $num = count($comclient->lines);
2832 for ($i = 0; $i < $num; $i++) {
2833 $prod = new Product($this->db);
2834 $label = '';
2835 $ref = '';
2836 if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) {
2837 $label = $prod->label;
2838 $ref = $prod->ref;
2839 }
2840
2841 $sql = "INSERT INTO ".$this->db->prefix()."commande_fournisseurdet";
2842 $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2843 $sql .= " VALUES (".((int) $idc).", '".$this->db->escape($label)."', '".$this->db->escape($comclient->lines[$i]->desc)."'";
2844 $sql .= ",".$comclient->lines[$i]->fk_product.", ".price2num($comclient->lines[$i]->price, 'MU');
2845 $sql .= ", ".price2num($comclient->lines[$i]->qty, 'MS').", ".price2num($comclient->lines[$i]->tva_tx, 5).", ".price2num($comclient->lines[$i]->localtax1_tx, 5).", ".price2num($comclient->lines[$i]->localtax2_tx, 5).", ".price2num($comclient->lines[$i]->remise_percent, 3);
2846 $sql .= ", '".price2num($comclient->lines[$i]->subprice, 'MT')."','0', '".$this->db->escape($ref)."');";
2847 if ($this->db->query($sql)) {
2848 $this->update_price(1);
2849 }
2850 }
2851
2852 return 1;
2853 }
2854
2862 public function setStatus($user, $status)
2863 {
2864 global $conf, $langs;
2865 $error = 0;
2866
2867 $this->db->begin();
2868
2869 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur';
2870 $sql .= " SET fk_statut = ".$status;
2871 $sql .= " WHERE rowid = ".((int) $this->id);
2872
2873 dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
2874 $resql = $this->db->query($sql);
2875 if ($resql) {
2876 // Trigger names for each status
2877 $triggerName = array();
2878 $triggerName[0] = 'DRAFT';
2879 $triggerName[1] = 'VALIDATED';
2880 $triggerName[2] = 'APPROVED';
2881 $triggerName[3] = 'ORDERED'; // Ordered
2882 $triggerName[4] = 'RECEIVED_PARTIALLY';
2883 $triggerName[5] = 'RECEIVED_COMPLETELY';
2884 $triggerName[6] = 'CANCELED';
2885 $triggerName[7] = 'CANCELED';
2886 $triggerName[9] = 'REFUSED';
2887
2888 // Call trigger
2889 $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user);
2890 if ($result < 0) {
2891 $error++;
2892 }
2893 // End call triggers
2894 } else {
2895 $error++;
2896 $this->error = $this->db->lasterror();
2897 dol_syslog(get_class($this)."::setStatus ".$this->error);
2898 }
2899
2900 if (!$error) {
2901 $this->statut = $status;
2902 $this->db->commit();
2903 return 1;
2904 } else {
2905 $this->db->rollback();
2906 return -1;
2907 }
2908 }
2909
2933 public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $notrigger = 0, $date_start = 0, $date_end = 0, $array_options = [], $fk_unit = null, $pu_ht_devise = 0, $ref_supplier = '')
2934 {
2935 global $mysoc, $conf, $langs;
2936 dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
2937 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2938
2939 $error = 0;
2940
2941 if ($this->statut == self::STATUS_DRAFT) {
2942 // Clean parameters
2943 if (empty($qty)) {
2944 $qty = 0;
2945 }
2946 if (empty($info_bits)) {
2947 $info_bits = 0;
2948 }
2949 if (empty($txtva)) {
2950 $txtva = 0;
2951 }
2952 if (empty($txlocaltax1)) {
2953 $txlocaltax1 = 0;
2954 }
2955 if (empty($txlocaltax2)) {
2956 $txlocaltax2 = 0;
2957 }
2958 if (empty($remise_percent)) {
2959 $remise_percent = 0;
2960 }
2961
2962 $remise_percent = (float) price2num($remise_percent);
2963 $qty = price2num($qty);
2964 if (!$qty) {
2965 $qty = 1;
2966 }
2967 $pu = price2num($pu);
2968 $pu_ht_devise = price2num($pu_ht_devise);
2969 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
2970 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
2971 }
2972 $txlocaltax1 = (float) price2num($txlocaltax1);
2973 $txlocaltax2 = (float) price2num($txlocaltax2);
2974
2975 // Check parameters
2976 if ($type < 0) {
2977 return -1;
2978 }
2979 if ($date_start && $date_end && $date_start > $date_end) {
2980 $langs->load("errors");
2981 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2982 return -1;
2983 }
2984
2985 $this->db->begin();
2986
2987 // Calcul du total TTC et de la TVA pour la ligne a partir de
2988 // qty, pu, remise_percent et txtva
2989 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2990 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2991
2992 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2993
2994 // Clean vat code
2995 $reg = array();
2996 $vat_src_code = '';
2997 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
2998 $vat_src_code = $reg[1];
2999 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3000 }
3001
3002 $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_ht_devise);
3003 $total_ht = $tabprice[0];
3004 $total_tva = $tabprice[1];
3005 $total_ttc = $tabprice[2];
3006 $total_localtax1 = $tabprice[9];
3007 $total_localtax2 = $tabprice[10];
3008 $pu_ht = $tabprice[3];
3009 $pu_tva = $tabprice[4];
3010 $pu_ttc = $tabprice[5];
3011
3012 // MultiCurrency
3013 $multicurrency_total_ht = $tabprice[16];
3014 $multicurrency_total_tva = $tabprice[17];
3015 $multicurrency_total_ttc = $tabprice[18];
3016 $pu_ht_devise = $tabprice[19];
3017
3018 $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3019 $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3020
3021 //Fetch current line from the database and then clone the object and set it in $oldline property
3022 $this->line = new CommandeFournisseurLigne($this->db);
3023 $this->line->fetch($rowid);
3024
3025 $oldline = clone $this->line;
3026 $this->line->oldline = $oldline;
3027
3028 $this->line->context = $this->context;
3029
3030 $this->line->fk_commande = $this->id;
3031 //$this->line->label=$label;
3032 $this->line->desc = $desc;
3033
3034 // redefine quantity according to packaging
3035 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
3036 if ($qty < $this->line->packaging) {
3037 $qty = $this->line->packaging;
3038 } else {
3039 if (!empty($this->line->packaging) && ($qty % $this->line->packaging) > 0) {
3040 $coeff = intval($qty / $this->line->packaging) + 1;
3041 $qty = $this->line->packaging * $coeff;
3042 setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs');
3043 }
3044 }
3045 }
3046
3047 $this->line->qty = $qty;
3048 $this->line->ref_supplier = $ref_supplier;
3049
3050 $this->line->vat_src_code = $vat_src_code;
3051 $this->line->tva_tx = $txtva;
3052 $this->line->localtax1_tx = $txlocaltax1;
3053 $this->line->localtax2_tx = $txlocaltax2;
3054 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3055 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3056 $this->line->remise_percent = $remise_percent;
3057 $this->line->subprice = $pu_ht;
3058 $this->line->info_bits = $info_bits;
3059 $this->line->total_ht = $total_ht;
3060 $this->line->total_tva = $total_tva;
3061 $this->line->total_localtax1 = $total_localtax1;
3062 $this->line->total_localtax2 = $total_localtax2;
3063 $this->line->total_ttc = $total_ttc;
3064 $this->line->product_type = $type;
3065 $this->line->special_code = $oldline->special_code;
3066 $this->line->rang = $oldline->rang;
3067 $this->line->origin = $this->origin;
3068 $this->line->fk_unit = $fk_unit;
3069
3070 $this->line->date_start = $date_start;
3071 $this->line->date_end = $date_end;
3072
3073 // Multicurrency
3074 $this->line->fk_multicurrency = $this->fk_multicurrency;
3075 $this->line->multicurrency_code = $this->multicurrency_code;
3076 $this->line->multicurrency_subprice = $pu_ht_devise;
3077 $this->line->multicurrency_total_ht = $multicurrency_total_ht;
3078 $this->line->multicurrency_total_tva = $multicurrency_total_tva;
3079 $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
3080
3081 $this->line->subprice = $pu_ht;
3082 $this->line->price = $this->line->subprice;
3083
3084 $this->line->remise_percent = $remise_percent;
3085
3086 if (is_array($array_options) && count($array_options) > 0) {
3087 // We replace values in this->line->array_options only for entries defined into $array_options
3088 foreach ($array_options as $key => $value) {
3089 $this->line->array_options[$key] = $array_options[$key];
3090 }
3091 }
3092
3093 $result = $this->line->update($notrigger);
3094
3095
3096 // Mise a jour info denormalisees au niveau facture
3097 if ($result >= 0) {
3098 $this->update_price('1', 'auto');
3099 $this->db->commit();
3100 return $result;
3101 } else {
3102 $this->error = $this->db->lasterror();
3103 $this->db->rollback();
3104 return -1;
3105 }
3106 } else {
3107 $this->error = "Order status makes operation forbidden";
3108 dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
3109 return -2;
3110 }
3111 }
3112
3113
3121 public function initAsSpecimen()
3122 {
3123 global $user, $langs, $conf;
3124
3125 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
3126
3127 dol_syslog(get_class($this)."::initAsSpecimen");
3128
3129 $now = dol_now();
3130
3131 // Find first product
3132 $prodid = 0;
3133 $product = new ProductFournisseur($this->db);
3134 $sql = "SELECT rowid";
3135 $sql .= " FROM ".$this->db->prefix()."product";
3136 $sql .= " WHERE entity IN (".getEntity('product').")";
3137 $sql .= $this->db->order("rowid", "ASC");
3138 $sql .= $this->db->plimit(1);
3139 $resql = $this->db->query($sql);
3140 if ($resql) {
3141 $obj = $this->db->fetch_object($resql);
3142 $prodid = $obj->rowid;
3143 }
3144
3145 // Initialise parameters
3146 $this->id = 0;
3147 $this->ref = 'SPECIMEN';
3148 $this->specimen = 1;
3149 $this->socid = 1;
3150 $this->date = $now;
3151 $this->date_commande = $now;
3152 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
3153 $this->cond_reglement_code = 'RECEP';
3154 $this->mode_reglement_code = 'CHQ';
3155
3156 $this->note_public = 'This is a comment (public)';
3157 $this->note_private = 'This is a comment (private)';
3158
3159 $this->multicurrency_tx = 1;
3160 $this->multicurrency_code = $conf->currency;
3161
3162 $this->statut = 0;
3163
3164 // Lines
3165 $nbp = 5;
3166 $xnbp = 0;
3167 while ($xnbp < $nbp) {
3168 $line = new CommandeFournisseurLigne($this->db);
3169 $line->desc = $langs->trans("Description")." ".$xnbp;
3170 $line->qty = 1;
3171 $line->subprice = 100;
3172 $line->tva_tx = 19.6;
3173 $line->localtax1_tx = 0;
3174 $line->localtax2_tx = 0;
3175 if ($xnbp == 2) {
3176 $line->total_ht = 50;
3177 $line->total_ttc = 59.8;
3178 $line->total_tva = 9.8;
3179 $line->remise_percent = 50;
3180 } else {
3181 $line->total_ht = 100;
3182 $line->total_ttc = 119.6;
3183 $line->total_tva = 19.6;
3184 $line->remise_percent = 00;
3185 }
3186 $line->fk_product = $prodid;
3187
3188 $this->lines[$xnbp] = $line;
3189
3190 $this->total_ht += $line->total_ht;
3191 $this->total_tva += $line->total_tva;
3192 $this->total_ttc += $line->total_ttc;
3193
3194 $xnbp++;
3195 }
3196
3197 return 1;
3198 }
3199
3206 public function info($id)
3207 {
3208 $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
3209 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
3210 $sql .= ' FROM '.$this->db->prefix().'commande_fournisseur as c';
3211 $sql .= ' WHERE c.rowid = '.((int) $id);
3212
3213 $result = $this->db->query($sql);
3214 if ($result) {
3215 if ($this->db->num_rows($result)) {
3216 $obj = $this->db->fetch_object($result);
3217
3218 $this->id = $obj->rowid;
3219
3220 $this->user_creation_id = $obj->fk_user_author;
3221 $this->user_validation_id = $obj->fk_user_valid;
3222 $this->user_modification_id = $obj->fk_user_modif;
3223 $this->user_approve_id = $obj->fk_user_approve;
3224 $this->user_approve_id2 = $obj->fk_user_approve2;
3225
3226 $this->date_creation = $this->db->jdate($obj->datec);
3227 $this->date_modification = $this->db->jdate($obj->datem);
3228 $this->date_approve = $this->db->jdate($obj->datea);
3229 $this->date_approve2 = $this->db->jdate($obj->datea2);
3230 $this->date_validation = $this->db->jdate($obj->date_validation);
3231 }
3232 $this->db->free($result);
3233 } else {
3234 dol_print_error($this->db);
3235 }
3236 }
3237
3243 public function loadStateBoard()
3244 {
3245 global $conf, $user;
3246
3247 $this->nb = array();
3248 $clause = "WHERE";
3249
3250 $sql = "SELECT count(co.rowid) as nb";
3251 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as co";
3252 $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON co.fk_soc = s.rowid";
3253 if (!$user->hasRight("societe", "client", "voir") && !$user->socid) {
3254 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3255 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3256 $clause = "AND";
3257 }
3258 $sql .= " ".$clause." co.entity IN (".getEntity('supplier_order').")";
3259
3260 $resql = $this->db->query($sql);
3261 if ($resql) {
3262 while ($obj = $this->db->fetch_object($resql)) {
3263 $this->nb["supplier_orders"] = $obj->nb;
3264 }
3265 $this->db->free($resql);
3266 return 1;
3267 } else {
3268 dol_print_error($this->db);
3269 $this->error = $this->db->error();
3270 return -1;
3271 }
3272 }
3273
3274 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3282 public function load_board($user, $mode = 'opened')
3283 {
3284 // phpcs:enable
3285 global $conf, $langs;
3286
3287 $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date, c.total_ht";
3288 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as c";
3289 if (!$user->hasRight("societe", "client", "voir") && !$user->socid) {
3290 $sql .= " JOIN ".$this->db->prefix()."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3291 }
3292 $sql .= " WHERE c.entity = ".$conf->entity;
3293 if ($mode === 'awaiting') {
3294 $sql .= " AND c.fk_statut IN (".self::STATUS_ORDERSENT.", ".self::STATUS_RECEIVED_PARTIALLY.")";
3295 } else {
3296 $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
3297 }
3298 if ($user->socid) {
3299 $sql .= " AND c.fk_soc = ".((int) $user->socid);
3300 }
3301
3302 $resql = $this->db->query($sql);
3303 if ($resql) {
3304 $commandestatic = new CommandeFournisseur($this->db);
3305
3306 $response = new WorkboardResponse();
3307 $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24;
3308 $response->label = $langs->trans("SuppliersOrdersToProcess");
3309 $response->labelShort = $langs->trans("Opened");
3310 $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=1,2&mainmenu=commercial&leftmenu=orders_suppliers';
3311 $response->url_late = DOL_URL_ROOT.'/fourn/commande/list.php?mainmenu=commercial&leftmenu=orders_suppliers&search_option=late';
3312 $response->img = img_object('', "order");
3313
3314 if ($mode === 'awaiting') {
3315 $response->label = $langs->trans("SuppliersOrdersAwaitingReception");
3316 $response->labelShort = $langs->trans("AwaitingReception");
3317 $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=3,4&mainmenu=commercial&leftmenu=orders_suppliers';
3318 }
3319
3320 while ($obj = $this->db->fetch_object($resql)) {
3321 $commandestatic->delivery_date = $this->db->jdate($obj->delivery_date);
3322 $commandestatic->date_commande = $this->db->jdate($obj->date_commande);
3323 $commandestatic->statut = $obj->fk_statut;
3324
3325 $response->nbtodo++;
3326 $response->total += $obj->total_ht;
3327
3328 if ($commandestatic->hasDelay()) {
3329 $response->nbtodolate++;
3330 }
3331 }
3332
3333 return $response;
3334 } else {
3335 $this->error = $this->db->error();
3336 return -1;
3337 }
3338 }
3339
3346 public function getInputMethod()
3347 {
3348 global $langs;
3349
3350 if ($this->methode_commande_id > 0) {
3351 $sql = "SELECT rowid, code, libelle as label";
3352 $sql .= " FROM ".$this->db->prefix().'c_input_method';
3353 $sql .= " WHERE active=1 AND rowid = ".((int) $this->methode_commande_id);
3354
3355 $resql = $this->db->query($sql);
3356 if ($resql) {
3357 if ($this->db->num_rows($resql)) {
3358 $obj = $this->db->fetch_object($resql);
3359
3360 $string = $langs->trans($obj->code);
3361 if ($string == $obj->code) {
3362 $string = $obj->label != '-' ? $obj->label : '';
3363 }
3364 return $string;
3365 }
3366 } else {
3367 dol_print_error($this->db);
3368 }
3369 }
3370
3371 return '';
3372 }
3373
3385 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3386 {
3387 global $conf, $langs;
3388
3389 if (!dol_strlen($modele)) {
3390 $modele = ''; // No doc template/generation by default
3391
3392 if (!empty($this->model_pdf)) {
3393 $modele = $this->model_pdf;
3394 } elseif (getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF')) {
3395 $modele = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF');
3396 }
3397 }
3398
3399 if (empty($modele)) {
3400 return 0;
3401 } else {
3402 $langs->load("suppliers");
3403 $outputlangs->load("products");
3404
3405 $modelpath = "core/modules/supplier_order/doc/";
3406 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3407 return $result;
3408 }
3409 }
3410
3417 public function getMaxDeliveryTimeDay($langs)
3418 {
3419 if (empty($this->lines)) {
3420 return '';
3421 }
3422
3423 $tmpproductfourn = new ProductFournisseur($this->db);
3424
3425 $nb = 0;
3426 foreach ($this->lines as $line) {
3427 if ($line->fk_product > 0) {
3428 // Load delivery_time_days, return id into product_fournisseur_price
3429 $idp = $tmpproductfourn->find_min_price_product_fournisseur($line->fk_product, $line->qty, $this->thirdparty->id);
3430 if ($idp > 0) {
3431 //$tmpproductfourn->fetch_product_fournisseur_price($idp);
3432 if ($tmpproductfourn->delivery_time_days > $nb) {
3433 $nb = $tmpproductfourn->delivery_time_days;
3434 }
3435 }
3436 }
3437 }
3438
3439 if ($nb === 0) {
3440 return '';
3441 } else {
3442 return $nb.' '.$langs->trans('days');
3443 }
3444 }
3445
3450 public function getRights()
3451 {
3452 global $user;
3453
3454 return $user->hasRight("fournisseur", "commande");
3455 }
3456
3457
3466 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3467 {
3468 $tables = array(
3469 'commande_fournisseur'
3470 );
3471
3472 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3473 }
3474
3483 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
3484 {
3485 $tables = array(
3486 'commande_fournisseurdet'
3487 );
3488
3489 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
3490 }
3491
3499 public function hasDelay()
3500 {
3501 global $conf;
3502
3503 if ($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY) {
3504 $now = dol_now();
3505 if (!empty($this->delivery_date)) {
3506 $date_to_test = $this->delivery_date;
3507 return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3508 } else {
3509 //$date_to_test = $this->date_commande;
3510 //return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3511 return false;
3512 }
3513 } else {
3514 $now = dol_now();
3515 $date_to_test = $this->date_commande;
3516
3517 return ($this->statut > 0 && $this->statut < 5) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3518 }
3519 }
3520
3528 public function showDelay()
3529 {
3530 global $conf, $langs;
3531
3532 $langs->load('orders');
3533
3534 $text = '';
3535
3536 if ($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY) {
3537 if (!empty($this->delivery_date)) {
3538 $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
3539 } else {
3540 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3541 }
3542 } else {
3543 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3544 }
3545 if ($text) {
3546 $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3547 }
3548
3549 return $text;
3550 }
3551
3552
3561 public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '')
3562 {
3563 if (isModEnabled("supplier_order")) {
3564 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
3565
3566 $qtydelivered = array();
3567 $qtywished = array();
3568
3569 $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
3570
3571 $filter = array('t.fk_element' => $this->id);
3572 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
3573 $filter['t.status'] = 1; // Restrict to lines with status validated
3574 }
3575
3576 $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
3577 if ($ret < 0) {
3578 $this->error = $supplierorderdispatch->error;
3579 $this->errors = $supplierorderdispatch->errors;
3580 return $ret;
3581 } else {
3582 if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) {
3583 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3584 $date_liv = dol_now();
3585
3586 // Build array with quantity deliverd by product
3587 foreach ($supplierorderdispatch->lines as $line) {
3588 $qtydelivered[$line->fk_product] += $line->qty;
3589 }
3590 foreach ($this->lines as $line) {
3591 // Exclude lines not qualified for shipment, similar code is found into interface_20_modWrokflow for customers
3592 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES') && $line->product_type > 0) {
3593 continue;
3594 }
3595 $qtywished[$line->fk_product] += $line->qty;
3596 }
3597
3598 //Compare array
3599 $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys.
3600 $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys
3601 $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys
3602 //var_dump(array_keys($qtydelivered));
3603 //var_dump(array_keys($qtywished));
3604 //var_dump($diff_array);
3605 //var_dump($keysinwishednotindelivered);
3606 //var_dump($keysindeliverednotinwished);
3607 //exit;
3608
3609 if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) { //No diff => mean everything is received
3610 if ($closeopenorder) {
3611 //$ret=$this->setStatus($user,5);
3612 $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // $type is 'tot', 'par', 'nev', 'can'
3613 if ($ret < 0) {
3614 return -1;
3615 }
3616 return 5;
3617 } else {
3618 //Diff => received partially
3619 //$ret=$this->setStatus($user,4);
3620 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3621 if ($ret < 0) {
3622 return -1;
3623 }
3624 return 4;
3625 }
3626 } elseif (getDolGlobalString('SUPPLIER_ORDER_MORE_THAN_WISHED')) {
3627 //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...)
3628
3629 $close = 0;
3630
3631 if (count($diff_array) > 0) {
3632 //there are some difference between the two arrays
3633
3634 //scan the array of results
3635 foreach ($diff_array as $key => $value) {
3636 //if the quantity delivered is greater or equal to wish quantity @phan-suppress-next-line PhanTypeInvalidDimOffset
3637 if ($qtydelivered[$key] >= $qtywished[$key]) {
3638 $close++;
3639 }
3640 }
3641 }
3642
3643
3644 if ($close == count($diff_array)) {
3645 //all the products are received equal or more than the wished quantity
3646 if ($closeopenorder) {
3647 $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // $type is 'tot', 'par', 'nev', 'can'
3648 if ($ret < 0) {
3649 return -1;
3650 }
3651 return 5;
3652 } else {
3653 //Diff => received partially
3654 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3655 if ($ret < 0) {
3656 return -1;
3657 }
3658 return 4;
3659 }
3660 } else {
3661 //all the products are not received
3662 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3663 if ($ret < 0) {
3664 return -1;
3665 }
3666 return 4;
3667 }
3668 } else {
3669 //Diff => received partially
3670 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3671 if ($ret < 0) {
3672 return -1;
3673 }
3674 return 4;
3675 }
3676 }
3677 return 1;
3678 }
3679 }
3680 return 0;
3681 }
3682
3690 public function loadReceptions($filtre_statut = -1)
3691 {
3692 $this->receptions = array();
3693
3694 dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG);
3695
3696 $sql = 'SELECT cd.rowid, cd.fk_product,';
3697 $sql .= ' sum(cfd.qty) as qty';
3698 $sql .= ' FROM '.$this->db->prefix().'receptiondet_batch as cfd,';
3699 if ($filtre_statut >= 0) {
3700 $sql .= ' '.$this->db->prefix().'reception as e,';
3701 }
3702 $sql .= ' '.$this->db->prefix().'commande_fournisseurdet as cd';
3703 $sql .= ' WHERE';
3704 if ($filtre_statut >= 0) {
3705 $sql .= ' cfd.fk_reception = e.rowid AND';
3706 }
3707 $sql .= ' cfd.fk_elementdet = cd.rowid';
3708 $sql .= ' AND cd.fk_commande ='.((int) $this->id);
3709 if (isset($this->fk_product) && !empty($this->fk_product) > 0) {
3710 $sql .= ' AND cd.fk_product = '.((int) $this->fk_product);
3711 }
3712 if ($filtre_statut >= 0) {
3713 $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
3714 }
3715 $sql .= ' GROUP BY cd.rowid, cd.fk_product';
3716
3717 $resql = $this->db->query($sql);
3718 if ($resql) {
3719 $num = $this->db->num_rows($resql);
3720 $i = 0;
3721 while ($i < $num) {
3722 $obj = $this->db->fetch_object($resql);
3723 empty($this->receptions[$obj->rowid]) ? $this->receptions[$obj->rowid] = $obj->qty : $this->receptions[$obj->rowid] += $obj->qty;
3724 $i++;
3725 }
3726 $this->db->free($resql);
3727
3728 return $num;
3729 } else {
3730 $this->error = $this->db->lasterror();
3731 return -1;
3732 }
3733 }
3734
3742 public function getKanbanView($option = '', $arraydata = null)
3743 {
3744 global $langs;
3745
3746 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3747
3748 $return = '<div class="box-flex-item box-flex-grow-zero">';
3749 $return .= '<div class="info-box info-box-sm">';
3750 $return .= '<span class="info-box-icon bg-infobox-action">';
3751 $return .= img_picto('', $this->picto);
3752 $return .= '</span>';
3753 $return .= '<div class="info-box-content">';
3754 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
3755 if ($selected >= 0) {
3756 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3757 }
3758 if (property_exists($this, 'socid') || property_exists($this, 'total_tva')) {
3759 $return .= '<br><span class="info-box-label amount">'.$this->socid.'</span>';
3760 }
3761 if (property_exists($this, 'billed')) {
3762 $return .= '<br><span class="opacitymedium">'.$langs->trans("Billed").' : </span><span class="info-box-label">'.yn($this->billed).'</span>';
3763 }
3764 if (method_exists($this, 'getLibStatut')) {
3765 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3766 }
3767 $return .= '</div>';
3768 $return .= '</div>';
3769 $return .= '</div>';
3770 return $return;
3771 }
3772}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:640
$object ref
Definition info.php:79
Class to manage table ReceptionLineBatch.
Class to manage predefined suppliers products.
const STATUS_CANCELED_AFTER_ORDER
Order canceled/never received.
const STATUS_RECEIVED_PARTIALLY
Received partially.
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set the planned delivery date.
updateFromCommandeClient($user, $idc, $comclientid)
Update a supplier order from a sales order.
getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0)
Return clickable name (with picto eventually)
loadReceptions($filtre_statut=-1)
Load array this->receptions of lines of shipments with nb of products sent for each order line Note: ...
static replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a product id with another one.
$fields
'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortf...
set_date_livraison($user, $delivery_date, $notrigger=0)
Set delivery date.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
info($id)
Charge les information d'ordre info dans l'objet facture.
const STATUS_CANCELED
Order canceled.
getNextNumRef($soc)
Returns the next order reference not used, based on the numbering model defined within COMMANDE_SUPPL...
fetch_lines($only_product=0)
Load array lines.
getInputMethod()
Returns the translated input method of object (defined if $this->methode_commande_id > 0).
const STATUS_VALIDATED
Validated status.
const STATUS_RECEIVED_COMPLETELY
Received completely.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $ref_supplier='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=0, $date_start=null, $date_end=null, $array_options=[], $fk_unit=null, $pu_ht_devise=0, $origin='', $origin_id=0, $rang=-1, $special_code=0)
Add order line.
loadStateBoard()
Load the indicators this->nb for the state board.
calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
Calc status regarding to dispatched stock.
set_id_projet($user, $id_projet, $notrigger=0)
Set the id projet.
showDelay()
Show the customer delayed info.
getTooltipContentArray($params)
getTooltipContentArray
classifyUnBilled(User $user)
Classify not billed.
approve($user, $idwarehouse=0, $secondlevel=0)
Approve a supplier order.
Cancel($user, $idwarehouse=-1)
Cancel an approved order.
dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0, $fk_reception=0)
Save a receiving into the tracking table of receiving (receptiondet_batch) and add product into stock...
valid($user, $idwarehouse=0, $notrigger=0)
Validate an order.
create($user, $notrigger=0)
Create order with draft status.
update(User $user, $notrigger=0)
Update Supplier Order.
createFromClone(User $user, $socid=0, $notrigger=0)
Load an object from its id and create a new one in database.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=0, $date_start=0, $date_end=0, $array_options=[], $fk_unit=null, $pu_ht_devise=0, $ref_supplier='')
Update line.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template model.
const STATUS_ORDERSENT
Order sent, shipment on process.
commande($user, $date, $methode, $comment='')
Submit a supplier order to supplier.
getRights()
Returns the rights used for this class.
load_board($user, $mode='opened')
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
deleteLine($idline, $notrigger=0)
Delete line.
getMaxDeliveryTimeDay($langs)
Return the max number delivery delay in day.
fetch($id, $ref='')
Get object and lines from database.
Livraison($user, $date, $type, $comment)
Set a delivery in database for this supplier order.
getDispachedLines($status=-1)
Return array of dispatched lines waiting to be approved for this order.
classifyBilled(User $user)
Class invoiced the supplier order.
initAsSpecimen()
Initialise an instance with random values.
const SOURCE_ID_REPLENISHMENT
The constant used into source field to track the order was generated by the replenishement feature.
setStatus($user, $status)
Tag order with a particular status.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getLibStatut($mode=0)
Return label of the status of object.
hasDelay()
Is the supplier order delayed? We suppose a purchase ordered as late if a the purchase order has been...
LibStatut($status, $mode=0, $billed=0)
Return label of a status.
Class to manage line orders.
Class to manage customers orders.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Superclass for orders classes.
Class to manage Dolibarr database access.
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 third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
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)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session 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)
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
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 '.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
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...
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...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_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...
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:88