dolibarr 25.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-2025 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-2026 MDW <mdeweerd@users.noreply.github.com>
18 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
19 * Copyright (C) 2025 Noé Cendrier <noe.cendrier@altairis.fr>
20 * Copyright (C) 2026 Pierre Ardoin <developpeur@lesmetiersdubatiment.fr>
21 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
22 * Copyright (C) 2026 Nick Fragoulis
23 *
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation; either version 3 of the License, or
27 * (at your option) any later version.
28 *
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
33 *
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <https://www.gnu.org/licenses/>.
36 */
37
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
45require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
46require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.orderline.class.php';
47require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
48require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
49if (isModEnabled('productbatch')) {
50 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
51}
52
53
58{
59 use CommonSubtotal;
60
64 public $element = 'order_supplier';
65
69 public $table_element = 'commande_fournisseur';
70
74 public $table_element_line = 'commande_fournisseurdet';
75
79 public $class_element_line = 'CommandeFournisseurLigne';
80
84 public $fk_element = 'fk_commande';
85
89 public $picto = 'supplier_order';
90
95 public $restrictiononfksoc = 1;
96
100 protected $table_ref_field = 'ref';
101
105 public $id;
106
110 public $ref;
111
115 public $ref_supplier;
116
122 public $ref_fourn;
123
129 public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process running -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
130 // -> 7=Canceled/Never received -> (reopen) 3=Process running
131 // -> 6=Canceled -> (reopen) 2=Approved
132 // -> 9=Refused -> (reopen) 1=Validated
133 // Note: billed or not is on another field "billed"
134
138 public $billed;
139
143 public $socid;
144
148 public $fourn_id;
149
153 public $date;
154
158 public $date_valid;
159
163 public $date_approve;
164
169 public $date_approve2;
170
174 public $date_commande;
175
180 public $remise_percent;
184 public $methode_commande_id;
188 public $methode_commande;
189
193 public $delivery_date;
194
198 public $fk_warehouse;
199
203 public $total_ht;
204
208 public $total_tva;
209
213 public $total_localtax1;
214
218 public $total_localtax2;
219
223 public $total_ttc;
224
228 public $source;
229
233 public $cond_reglement_id;
234
238 public $cond_reglement_code;
239
243 public $cond_reglement_label;
244
248 public $cond_reglement_doc;
249
254 public $deposit_percent;
255
259 public $fk_account;
260
264 public $mode_reglement_id;
265
269 public $mode_reglement_code;
270
274 public $mode_reglement;
275
279 public $user_author_id;
280
284 public $user_approve_id;
285
290 public $user_approve_id2;
291
295 public $refuse_note;
296
300 public $cancel_note;
301
305 public $extraparams = array();
306
310 public $lines = array();
311
315 public $line;
316
320 public $origin;
321
325 public $origin_id;
326
330 public $date_lim_reglement;
331
335 public $receptions = array();
336
337 // Multicurrency
341 public $fk_multicurrency;
342
346 public $multicurrency_code;
347
351 public $multicurrency_tx;
352
356 public $multicurrency_total_ht;
357
361 public $multicurrency_total_tva;
362
366 public $multicurrency_total_ttc;
367
395 public $fields = array(
396 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 10),
397 'ref' => array('type' => 'varchar(255)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'showoncombobox' => 1, 'position' => 25, 'searchall' => 1),
398 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 35),
399 'ref_supplier' => array('type' => 'varchar(255)', 'label' => 'RefOrderSupplierShort', 'enabled' => 1, 'visible' => 1, 'position' => 40, 'searchall' => 1),
400 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 45),
401 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 710),
402 'date_approve' => array('type' => 'datetime', 'label' => 'DateApprove', 'enabled' => 1, 'visible' => -1, 'position' => 720),
403 'date_approve2' => array('type' => 'datetime', 'label' => 'DateApprove2', 'enabled' => 1, 'visible' => 3, 'position' => 725),
404 'date_commande' => array('type' => 'date', 'label' => 'OrderDateShort', 'enabled' => 1, 'visible' => 1, 'position' => 70),
405 'date_livraison' => array('type' => 'datetime', 'label' => 'DeliveryDate', 'enabled' => 'getDolGlobalInt("ORDER_DISABLE_DELIVERY_DATE") ? 0 : 1', 'visible' => 1, 'position' => 74),
406 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'DefaultWarehouse', 'enabled' => 'isModEnabled("stock")', 'visible' => -1, 'position' => 75, 'nodepth' => 1),
407 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => 3, 'position' => 41),
408 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => 3, 'notnull' => -1, 'position' => 80),
409 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => 3, 'position' => 711),
410 'fk_user_approve' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserApproval', 'enabled' => 1, 'visible' => 3, 'position' => 721),
411 'fk_user_approve2' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserApproval2', 'enabled' => 1, 'visible' => 3, 'position' => 726),
412 'source' => array('type' => 'smallint(6)', 'label' => 'Source', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 100),
413 'billed' => array('type' => 'smallint(6)', 'label' => 'Billed', 'enabled' => 1, 'visible' => 1, 'position' => 710),
414 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
415 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => 1, 'position' => 135, 'isameasure' => 1),
416 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => 3, 'position' => 140, 'isameasure' => 1),
417 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => 3, 'position' => 145, 'isameasure' => 1),
418 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => -1, 'position' => 150, 'isameasure' => 1),
419 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 750, 'searchall' => 1),
420 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 760, 'searchall' => 1),
421 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPDF', 'enabled' => 1, 'visible' => 0, 'position' => 165),
422 'fk_input_method' => array('type' => 'integer', 'label' => 'OrderMode', 'enabled' => 1, 'visible' => 3, 'position' => 170),
423 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => 3, 'position' => 175),
424 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 176),
425 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => 3, 'position' => 180),
426 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => 0, 'position' => 190),
427 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => 3, 'position' => 200),
428 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 1, 'visible' => 3, 'position' => 205),
429 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLocation', 'enabled' => 1, 'visible' => 3, 'position' => 210),
430 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Currency', 'enabled' => 1, 'visible' => 0, 'position' => 215),
431 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 220),
432 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 225),
433 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 230),
434 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 235),
435 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
436 'date_creation' => array('type' => 'datetime', 'label' => 'Date creation', 'enabled' => 1, 'visible' => -1, 'position' => 500),
437 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => 1, 'notnull' => 1, 'position' => 50),
438 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 1000, 'index' => 1),
439 'tms' => array('type' => 'datetime', 'label' => "DateModificationShort", 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 501),
440 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => 0, 'position' => 700),
441 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => 1, 'position' => 701),
442 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => 0, 'position' => 900),
443 );
444
445
449 const STATUS_DRAFT = 0;
450
455
460
465
470
475
480
485
489 const STATUS_REFUSED = 9;
490
491
496
502 public function __construct($db)
503 {
504 $this->db = $db;
505
506 $this->ismultientitymanaged = 1;
507 }
508
509
517 public function fetch($id, $ref = '')
518 {
519 // Check parameters
520 if (empty($id) && empty($ref)) {
521 return -1;
522 }
523
524 $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,";
525 $sql .= " c.localtax1, c.localtax2, ";
526 $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
527 $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,";
528 $sql .= " c.date_commande as date_commande, c.date_livraison as delivery_date, c.fk_warehouse, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
529 $sql .= " c.fk_account,";
530 $sql .= " c.note_private, c.note_public, c.model_pdf, c.last_main_doc, c.extraparams, c.billed,";
531 $sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
532 $sql .= " cm.libelle as methode_commande,";
533 $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc, c.deposit_percent,";
534 $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
535 $sql .= ', c.fk_incoterms, c.location_incoterms';
536 $sql .= ', c.last_main_doc';
537 $sql .= ', i.libelle as label_incoterms';
538 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as c";
539 $sql .= " LEFT JOIN ".$this->db->prefix()."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid";
540 $sql .= " LEFT JOIN ".$this->db->prefix()."c_paiement as p ON c.fk_mode_reglement = p.id";
541 $sql .= " LEFT JOIN ".$this->db->prefix()."c_input_method as cm ON cm.rowid = c.fk_input_method";
542 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_incoterms as i ON c.fk_incoterms = i.rowid';
543
544 if (empty($id)) {
545 $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")";
546 } else {
547 $sql .= " WHERE c.rowid=".((int) $id);
548 }
549
550 if ($ref) {
551 $sql .= " AND c.ref='".$this->db->escape($ref)."'";
552 }
553
554 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
555 $resql = $this->db->query($sql);
556 if ($resql) {
557 $obj = $this->db->fetch_object($resql);
558 if (!$obj) {
559 $this->error = 'Bill with id '.$id.' not found';
560 dol_syslog(get_class($this).'::fetch '.$this->error);
561 return 0;
562 }
563
564 $this->id = $obj->rowid;
565 $this->entity = $obj->entity;
566
567 $this->ref = $obj->ref;
568 $this->ref_supplier = $obj->ref_supplier;
569
570 $this->socid = $obj->fk_soc;
571 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
572
573 $this->fourn_id = $obj->fk_soc;
574 $this->statut = $obj->status; // deprecated
575 $this->status = $obj->status;
576 $this->billed = $obj->billed;
577 $this->last_main_doc = $obj->last_main_doc;
578 $this->user_author_id = $obj->user_author_id;
579 $this->user_validation_id = $obj->user_validation_id;
580 $this->user_approve_id = $obj->user_approve_id;
581 $this->user_approve_id2 = $obj->user_approve_id2;
582 $this->total_ht = $obj->total_ht;
583 $this->total_tva = $obj->total_tva;
584 $this->total_localtax1 = $obj->localtax1;
585 $this->total_localtax2 = $obj->localtax2;
586 $this->total_ttc = $obj->total_ttc;
587 $this->date_creation = $this->db->jdate($obj->date_creation);
588 $this->date_valid = $this->db->jdate($obj->date_valid);
589 $this->date_approve = $this->db->jdate($obj->date_approve);
590 $this->date_approve2 = $this->db->jdate($obj->date_approve2);
591 $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier
592 if (isset($obj->date_commande)) {
593 $this->date = $this->date_commande;
594 } else {
595 $this->date = $this->date_creation;
596 }
597 $this->delivery_date = $this->db->jdate($obj->delivery_date);
598 $this->fk_warehouse = $obj->fk_warehouse;
599 $this->remise_percent = $obj->remise_percent;
600 $this->methode_commande_id = $obj->fk_input_method;
601 $this->methode_commande = $obj->methode_commande;
602
603 $this->source = $obj->source;
604 $this->fk_project = $obj->fk_project;
605 $this->cond_reglement_id = $obj->fk_cond_reglement;
606 $this->cond_reglement_code = $obj->cond_reglement_code;
607 $this->cond_reglement_label = $obj->cond_reglement_label;
608 $this->cond_reglement_doc = $obj->cond_reglement_doc;
609 $this->deposit_percent = $obj->deposit_percent;
610 $this->fk_account = $obj->fk_account;
611 $this->mode_reglement_id = $obj->fk_mode_reglement;
612 $this->mode_reglement_code = $obj->mode_reglement_code;
613 $this->mode_reglement = $obj->mode_reglement_libelle;
614 $this->note = $obj->note_private; // deprecated
615 $this->note_private = $obj->note_private;
616 $this->note_public = $obj->note_public;
617 $this->model_pdf = $obj->model_pdf;
618 $this->last_main_doc = $obj->last_main_doc;
619
620 //Incoterms
621 $this->fk_incoterms = $obj->fk_incoterms;
622 $this->location_incoterms = $obj->location_incoterms;
623 $this->label_incoterms = $obj->label_incoterms;
624
625 // Multicurrency
626 $this->fk_multicurrency = $obj->fk_multicurrency;
627 $this->multicurrency_code = $obj->multicurrency_code;
628 $this->multicurrency_tx = $obj->multicurrency_tx;
629 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
630 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
631 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
632
633 $this->extraparams = isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
634
635 $this->db->free($resql);
636
637 // Retrieve all extrafield
638 // fetch optionals attributes and labels
639 $this->fetch_optionals();
640
641 // Lines
642 $result = $this->fetch_lines();
643
644 if ($result < 0) {
645 return -1;
646 } else {
647 return 1;
648 }
649 } else {
650 $this->error = $this->db->error()." sql=".$sql;
651 return -1;
652 }
653 }
654
655 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
662 public function fetch_lines($only_product = 0)
663 {
664 // phpcs:enable
665
666 $this->lines = array();
667
668 $sql = "SELECT l.rowid, l.fk_commande, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
669 $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice, l.subprice_ttc,";
670 $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
671 $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.info_bits, l.special_code, l.fk_parent_line, l.rang,";
672 $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, p.stockable_product,";
673 $sql .= " l.fk_unit, l.extraparams,";
674 $sql .= " l.date_start, l.date_end,";
675 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_subprice_ttc, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
676 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as l";
677 $sql .= ' LEFT JOIN '.$this->db->prefix().'product as p ON l.fk_product = p.rowid';
678 $sql .= " WHERE l.fk_commande = ".((int) $this->id);
679 if ($only_product) {
680 $sql .= ' AND p.fk_product_type = 0';
681 }
682 $sql .= " ORDER BY l.rang, l.rowid";
683 //print $sql;
684
685 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
686
687 $result = $this->db->query($sql);
688 if ($result) {
689 $num = $this->db->num_rows($result);
690 $i = 0;
691
692 while ($i < $num) {
693 $objp = $this->db->fetch_object($result);
694
695 $line = new CommandeFournisseurLigne($this->db);
696
697 $line->id = $objp->rowid;
698 $line->fk_commande = $objp->fk_commande;
699 $line->desc = $objp->description;
700 $line->description = $objp->description;
701 $line->qty = $objp->qty;
702 $line->tva_tx = $objp->tva_tx;
703 $line->localtax1_tx = $objp->localtax1_tx;
704 $line->localtax2_tx = $objp->localtax2_tx;
705 $line->localtax1_type = $objp->localtax1_type;
706 $line->localtax2_type = $objp->localtax2_type;
707 $line->subprice = $objp->subprice;
708 $line->pu_ht = $objp->subprice; // deprecated
709 $line->subprice_ttc = $objp->subprice_ttc;
710 $line->pu_ttc = $objp->subprice_ttc; // deprecated
711 $line->remise_percent = $objp->remise_percent;
712
713 $line->vat_src_code = $objp->vat_src_code;
714 $line->total_ht = $objp->total_ht;
715 $line->total_tva = $objp->total_tva;
716 $line->total_localtax1 = $objp->total_localtax1;
717 $line->total_localtax2 = $objp->total_localtax2;
718 $line->total_ttc = $objp->total_ttc;
719 $line->product_type = $objp->product_type;
720
721 $line->fk_product = $objp->fk_product;
722
723 $line->libelle = $objp->product_label; // deprecated
724 $line->product_label = $objp->product_label;
725 $line->product_desc = $objp->product_desc;
726 $line->product_tobatch = $objp->product_tobatch;
727 $line->product_barcode = $objp->product_barcode;
728 $line->stockable_product = $objp->stockable_product;
729
730 $line->ref = $objp->product_ref; // Ref of product
731 $line->product_ref = $objp->product_ref; // Ref of product
732 $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
733 $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
734
735 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
736 // TODO We should not fetch this properties into the fetch_lines. This is NOT properties of a line.
737 // Move this into another method and call it when required.
738
739 // Take better packaging for $objp->qty (first supplier ref quantity <= $objp->qty)
740 $sqlsearchpackage = 'SELECT rowid, packaging FROM '.$this->db->prefix()."product_fournisseur_price";
741 $sqlsearchpackage .= ' WHERE entity IN ('.getEntity('productsupplierprice').")";
742 $sqlsearchpackage .= " AND fk_product = ".((int) $objp->fk_product);
743 $sqlsearchpackage .= " AND ref_fourn = '".$this->db->escape($objp->ref_supplier)."'";
744 $sqlsearchpackage .= " AND quantity <= ".abs((float) $objp->qty); // required to be qualified
745 $sqlsearchpackage .= " AND (packaging IS NULL OR packaging = 0 OR packaging <= ".abs((float) $objp->qty).")"; // required to be qualified
746 $sqlsearchpackage .= " AND fk_soc = ".((int) $this->socid);
747 $sqlsearchpackage .= " ORDER BY packaging ASC"; // Take the smaller package first
748 $sqlsearchpackage .= " LIMIT 1";
749
750 $resqlsearchpackage = $this->db->query($sqlsearchpackage);
751 if ($resqlsearchpackage) {
752 $objsearchpackage = $this->db->fetch_object($resqlsearchpackage);
753 if ($objsearchpackage) {
754 $line->fk_fournprice = $objsearchpackage->rowid;
755 $line->packaging = (float) $objsearchpackage->packaging;
756 }
757 } else {
758 $this->error = $this->db->lasterror();
759 return -1;
760 }
761 }
762
763 $line->date_start = $this->db->jdate($objp->date_start);
764 $line->date_end = $this->db->jdate($objp->date_end);
765 $line->fk_unit = $objp->fk_unit;
766
767 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
768
769 // Multicurrency
770 $line->fk_multicurrency = $objp->fk_multicurrency;
771 $line->multicurrency_code = $objp->multicurrency_code;
772 $line->multicurrency_subprice = $objp->multicurrency_subprice;
773 $line->multicurrency_subprice_ttc = $objp->multicurrency_subprice_ttc;
774 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
775 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
776 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
777
778 $line->info_bits = $objp->info_bits;
779 $line->special_code = $objp->special_code;
780 $line->fk_parent_line = $objp->fk_parent_line;
781
782 $line->rang = $objp->rang;
783
784 // Retrieve all extrafield
785 // fetch optionals attributes and labels
786 $line->fetch_optionals();
787
788 $this->lines[$i] = $line;
789
790 $i++;
791 }
792 $this->db->free($result);
793
794 return $num;
795 } else {
796 $this->error = $this->db->error()." sql=".$sql;
797 return -1;
798 }
799 }
800
809 public function valid($user, $idwarehouse = 0, $notrigger = 0)
810 {
811 global $conf;
812 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
813
814 $error = 0;
815
816 dol_syslog(get_class($this)."::valid");
817 $result = 0;
818 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")))
819 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight("fournisseur", "supplier_order_advance", "validate"))) {
820 $this->db->begin();
821
822 if (!getDolGlobalBool('SUPPLIER_ORDER_NOCHECK_ONBUY_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines('onbuy')) {
823 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
824 return -1;
825 }
826 // Definition of supplier order numbering model name
827 $soc = new Societe($this->db);
828 $soc->fetch((int) $this->fourn_id);
829
830 // Check if object has a temporary ref
831 if (preg_match('/^[\‍(]?PROV/i', (string) $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
832 $num = $this->getNextNumRef($soc);
833 } else {
834 $num = (string) $this->ref;
835 }
836 $this->newref = dol_sanitizeFileName($num);
837
838 $sql = 'UPDATE '.$this->db->prefix()."commande_fournisseur";
839 $sql .= " SET ref='".$this->db->escape($num)."',";
840 $sql .= " fk_statut = ".((int) self::STATUS_VALIDATED).",";
841 $sql .= " date_valid='".$this->db->idate(dol_now())."',";
842 $sql .= " fk_user_valid = ".((int) $user->id);
843 $sql .= " WHERE rowid = ".((int) $this->id);
844 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
845
846 $resql = $this->db->query($sql);
847 if (!$resql) {
848 dol_print_error($this->db);
849 $error++;
850 }
851
852 if (!$error && !$notrigger) {
853 // Call trigger
854 $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user);
855 if ($result < 0) {
856 $error++;
857 }
858 // End call triggers
859 }
860
861 if (!$error) {
862 $this->oldref = $this->ref;
863
864 // Rename directory if dir was a temporary ref
865 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
866 // Now we rename also files into index
867 $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)."'";
868 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
869 $resql = $this->db->query($sql);
870 if (!$resql) {
871 $error++;
872 $this->error = $this->db->lasterror();
873 }
874 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
875 $sql .= " WHERE filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
876 $resql = $this->db->query($sql);
877 if (!$resql) {
878 $error++;
879 $this->error = $this->db->lasterror();
880 }
881
882 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
883 $oldref = dol_sanitizeFileName($this->ref);
884 $newref = dol_sanitizeFileName($num);
885 $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref;
886 $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
887 if (!$error && file_exists($dirsource)) {
888 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
889
890 if (@rename($dirsource, $dirdest)) {
891 dol_syslog("Rename ok");
892 // Rename docs starting with $oldref with $newref
893 $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
894 foreach ($listoffiles as $fileentry) {
895 $dirsource = $fileentry['name'];
896 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
897 $dirsource = $fileentry['path'].'/'.$dirsource;
898 $dirdest = $fileentry['path'].'/'.$dirdest;
899 @rename($dirsource, $dirdest);
900 }
901 }
902 }
903 }
904 }
905
906 if (!$error) {
907 $result = 1;
909 $this->statut = self::STATUS_VALIDATED; // deprecated
910 $this->ref = $num;
911 }
912
913 if (!$error) {
914 $this->db->commit();
915 return 1;
916 } else {
917 $this->db->rollback();
918 return -1;
919 }
920 } else {
921 $this->error = 'NotAuthorized';
922 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
923 return -1;
924 }
925 }
926
933 public function getLibStatut($mode = 0)
934 {
935 return $this->LibStatut(isset($this->status) ? $this->status : $this->statut, $mode, $this->billed);
936 }
937
938 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
947 public function LibStatut($status, $mode = 0, $billed = 0)
948 {
949 // phpcs:enable
950 global $langs, $hookmanager;
951
952 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
953 $langs->load('orders');
954
955 $this->labelStatus[0] = 'StatusSupplierOrderDraft';
956 $this->labelStatus[1] = 'StatusSupplierOrderValidated';
957 $this->labelStatus[2] = 'StatusSupplierOrderApproved';
958 if (!getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
959 $this->labelStatus[3] = 'StatusSupplierOrderOnProcess';
960 } else {
961 $this->labelStatus[3] = 'StatusSupplierOrderOnProcessWithValidation';
962 }
963 $this->labelStatus[4] = 'StatusSupplierOrderReceivedPartially';
964 $this->labelStatus[5] = 'StatusSupplierOrderReceivedAll';
965 $this->labelStatus[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled
966 $this->labelStatus[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled
967 $this->labelStatus[9] = 'StatusSupplierOrderRefused';
968
969 // List of language codes for status
970 $this->labelStatusShort[0] = 'StatusSupplierOrderDraftShort';
971 $this->labelStatusShort[1] = 'StatusSupplierOrderValidatedShort';
972 $this->labelStatusShort[2] = 'StatusSupplierOrderApprovedShort';
973 $this->labelStatusShort[3] = 'StatusSupplierOrderOnProcessShort';
974 $this->labelStatusShort[4] = 'StatusSupplierOrderReceivedPartiallyShort';
975 $this->labelStatusShort[5] = 'StatusSupplierOrderReceivedAllShort';
976 $this->labelStatusShort[6] = 'StatusSupplierOrderCanceledShort';
977 $this->labelStatusShort[7] = 'StatusSupplierOrderCanceledShort';
978 $this->labelStatusShort[9] = 'StatusSupplierOrderRefusedShort';
979 }
980
981 $statustrans = array(
982 0 => 'status0',
983 1 => 'status1b',
984 2 => 'status1',
985 3 => 'status4',
986 4 => 'status4b',
987 5 => 'status6',
988 6 => 'status9',
989 7 => 'status9',
990 9 => 'status9',
991 );
992
993 $statusClass = 'status0';
994 if (!empty($statustrans[$status])) {
995 $statusClass = $statustrans[$status];
996 }
997
998 $billedtext = '';
999 if ($billed) {
1000 $billedtext = ' - '.$langs->trans("Billed");
1001 }
1002 if ($status == 5 && $billed) {
1003 $statusClass = 'status6';
1004 }
1005
1006 $statusLong = $langs->transnoentitiesnoconv($this->labelStatus[$status]).$billedtext;
1007 $statusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
1008
1009 $parameters = array('status' => $status, 'mode' => $mode, 'billed' => $billed);
1010 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
1011 if ($reshook > 0) {
1012 return $hookmanager->resPrint;
1013 }
1014
1015 return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode);
1016 }
1017
1024 public function getTooltipContentArray($params)
1025 {
1026 global $conf, $langs, $user;
1027
1028 $langs->loadLangs(['bills', 'orders']);
1029
1030 $datas = [];
1031 $nofetch = !empty($params['nofetch']);
1032
1033 if ($user->hasRight("fournisseur", "commande", "read")) {
1034 $datas['picto'] = '<u class="paddingrightonly">'.$langs->trans("SupplierOrder").'</u>';
1035 if ($this->status) {
1036 $datas['picto'] .= ' '.$this->getLibStatut(5);
1037 }
1038 if (!empty($this->ref)) {
1039 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1040 }
1041 if (!empty($this->ref_supplier)) {
1042 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
1043 }
1044 if (!$nofetch) {
1045 $langs->load('companies');
1046 if (empty($this->thirdparty)) {
1047 $this->fetch_thirdparty();
1048 }
1049 $datas['supplier'] = '<br><b>'.$langs->trans('Supplier').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
1050 }
1051 if (!empty($this->total_ht)) {
1052 $datas['totalht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1053 }
1054 if (!empty($this->total_tva)) {
1055 $datas['totaltva'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1056 }
1057 if (!empty($this->total_ttc)) {
1058 $datas['totalttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1059 }
1060 if (!empty($this->date)) {
1061 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1062 }
1063 if (!empty($this->delivery_date)) {
1064 $langs->load("sendings");
1065 $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
1066 }
1067 }
1068 return $datas;
1069 }
1070
1078 {
1079 global $mysoc;
1080
1081 $context = parent::getObjectLinesDisplayContext();
1082 // The supplier is the seller, an empty third party is used if it is not loaded (same as a failed fetch in the card)
1083 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1084 $context['seller'] = (is_object($this->thirdparty) ? $this->thirdparty : new Societe($this->db));
1085 $context['buyer'] = $mysoc;
1086 $context['forceall'] = 1;
1087 $context['inputalsopricewithtax'] = 1;
1088 // 2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum
1089 $context['senderissupplier'] = (getDolGlobalInt('SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY') ? getDolGlobalInt('SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY') : 2);
1090
1091 return $context;
1092 }
1093
1104 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
1105 {
1106 global $langs, $user, $hookmanager;
1107
1108 $result = '';
1109 $params = [
1110 'id' => $this->id,
1111 'objecttype' => $this->element,
1112 'option' => $option,
1113 'nofetch' => 1
1114 ];
1115 $classfortooltip = 'classfortooltip';
1116 $dataparams = '';
1117 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1118 $classfortooltip = 'classforajaxtooltip';
1119 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1120 $label = '';
1121 } else {
1122 $label = $this->getTooltipContent($params);
1123 }
1124
1125 $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
1126
1127 if ($option !== 'nolink') {
1128 // Add param to save lastsearch_values or not
1129 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1130 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1131 $add_save_lastsearch_values = 1;
1132 }
1133 if ($add_save_lastsearch_values) {
1134 $url .= '&save_lastsearch_values=1';
1135 }
1136 }
1137
1138 $linkclose = '';
1139 if (empty($notooltip)) {
1140 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1141 $label = $langs->trans("ShowOrder");
1142 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1143 }
1144 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1145 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
1146 }
1147
1148 $linkstart = '<a href="'.$url.'"';
1149 $linkstart .= $linkclose.'>';
1150 $linkend = '</a>';
1151
1152 $result .= $linkstart;
1153 if ($withpicto) {
1154 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1155 }
1156 if ($withpicto != 2) {
1157 $result .= $this->ref;
1158 }
1159 $result .= $linkend;
1160
1161 if ($addlinktonotes) {
1162 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1163 if ($txttoshow) {
1164 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1165 $result .= ' <span class="note inline-block">';
1166 $result .= '<a href="'.DOL_URL_ROOT.'/fourn/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
1167 $result .= img_picto('', 'note');
1168 $result .= '</a>';
1169 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1170 //$result.='</a>';
1171 $result .= '</span>';
1172 }
1173 }
1174
1175 global $action;
1176 $hookmanager->initHooks(array($this->element . 'dao'));
1177 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1178 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1179 if ($reshook > 0) {
1180 $result = $hookmanager->resPrint;
1181 } else {
1182 $result .= $hookmanager->resPrint;
1183 }
1184 return $result;
1185 }
1186
1187
1195 public function getNextNumRef($soc)
1196 {
1197 global $langs, $conf;
1198 $langs->load("orders");
1199
1200 if (getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER')) {
1201 $mybool = false;
1202
1203 $file = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER').'.php';
1204 $classname = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER');
1205
1206 // Include file with class
1207 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1208
1209 foreach ($dirmodels as $reldir) {
1210 $dir = dol_buildpath($reldir."core/modules/supplier_order/");
1211
1212 // Load file with numbering class (if found)
1213 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1214 }
1215
1216 if (!$mybool) {
1217 dol_print_error(null, "Failed to include file ".$file);
1218 return '';
1219 }
1220
1221 $obj = new $classname();
1222 '@phan-var-force ModeleNumRefSuppliersOrders $obj';
1224 $numref = $obj->getNextValue($soc, $this);
1225
1226 if ($numref != "") {
1227 return $numref;
1228 } else {
1229 $this->error = $obj->error;
1230 return -1;
1231 }
1232 } else {
1233 $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
1234 return -2;
1235 }
1236 }
1237
1244 public function classifyBilled(User $user)
1245 {
1246 $error = 0;
1247
1248 if ($this->billed) {
1249 return 0;
1250 }
1251
1252 $this->db->begin();
1253
1254 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur SET billed = 1';
1255 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
1256
1257 if ($this->db->query($sql)) {
1258 // Call trigger
1259 $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
1260 if ($result < 0) {
1261 $error++;
1262 }
1263 // End call triggers
1264
1265 if (!$error) {
1266 $this->billed = 1;
1267
1268 $this->db->commit();
1269 return 1;
1270 } else {
1271 $this->db->rollback();
1272 return -1;
1273 }
1274 } else {
1275 dol_print_error($this->db);
1276
1277 $this->db->rollback();
1278 return -1;
1279 }
1280 }
1281
1282
1289 public function classifyUnBilled(User $user)
1290 {
1291 if (empty($this->billed)) {
1292 return 0;
1293 }
1294
1295 $this->db->begin();
1296
1297 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur SET billed = 0';
1298 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
1299 ;
1300
1301 if (!$this->db->query($sql)) {
1302 dol_print_error($this->db);
1303 $this->db->rollback();
1304 return -1;
1305 }
1306
1307 // Call trigger
1308 $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_UNBILLED', $user);
1309 if ($result < 0) {
1310 $this->db->rollback();
1311 return -1;
1312 }
1313 // End call triggers
1314
1315 $this->billed = 1;
1316 $this->db->commit();
1317 return 1;
1318 }
1319
1320
1329 public function approve($user, $idwarehouse = 0, $secondlevel = 0)
1330 {
1331 global $langs;
1332
1333 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1334
1335 $error = 0;
1336
1337 dol_syslog(get_class($this)."::approve");
1338
1339 if ($user->hasRight("fournisseur", "commande", "approuver")) {
1340 $now = dol_now();
1341
1342 $this->db->begin();
1343
1344 // Definition of order numbering model name
1345 $soc = new Societe($this->db);
1346 $soc->fetch((int) $this->fourn_id);
1347
1348 // Check if object has a temporary ref
1349 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1350 $num = $this->getNextNumRef($soc);
1351 } else {
1352 $num = (string) $this->ref;
1353 }
1354 $this->newref = dol_sanitizeFileName($num);
1355
1356 // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
1357 $movetoapprovestatus = true;
1358 $comment = '';
1359
1360 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1361 $sql .= " SET ref='".$this->db->escape($num)."',";
1362 if (empty($secondlevel)) { // standard or first level approval
1363 $sql .= " date_approve='".$this->db->idate($now)."',";
1364 $sql .= " fk_user_approve = ".((int) $user->id);
1365 if (getDolGlobalString('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED') && $this->total_ht >= getDolGlobalFloat('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED')) {
1366 if (empty($this->user_approve_id2)) {
1367 $movetoapprovestatus = false; // second level approval not done
1368 $comment = ' (first level)';
1369 }
1370 }
1371 } else { // request a second level approval
1372 $sql .= " date_approve2='".$this->db->idate($now)."',";
1373 $sql .= " fk_user_approve2 = ".((int) $user->id);
1374 if (empty($this->user_approve_id)) {
1375 $movetoapprovestatus = false; // first level approval not done
1376 }
1377 $comment = ' (second level)';
1378 }
1379 // If double approval is required and first approval, we keep status to 1 = validated
1380 if ($movetoapprovestatus) {
1381 $sql .= ", fk_statut = ".self::STATUS_ACCEPTED;
1382 } else {
1383 $sql .= ", fk_statut = ".self::STATUS_VALIDATED;
1384 }
1385 $sql .= " WHERE rowid = ".((int) $this->id);
1386 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1387
1388 if ($this->db->query($sql)) {
1389 if (getDolGlobalString('SUPPLIER_ORDER_AUTOADD_USER_CONTACT')) {
1390 $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
1391 if ($result < 0 && $result != -2) { // -2 means already exists
1392 $error++;
1393 }
1394 }
1395
1396 // If stock is incremented on validate order, we must increment it
1397 if (!$error && $movetoapprovestatus && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER')) {
1398 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1399 $langs->load("agenda");
1400
1401 $cpt = count($this->lines);
1402 for ($i = 0; $i < $cpt; $i++) {
1403 // Product with reference
1404 if ($this->lines[$i]->fk_product > 0) {
1405 $this->line = $this->lines[$i];
1406 $mouvP = new MouvementStock($this->db);
1407 $mouvP->origin = &$this;
1408 $mouvP->setOrigin($this->element, $this->id);
1409 // We decrement stock of product (and sub-products)
1410 $up_ht_disc = $this->lines[$i]->subprice;
1411 if (!empty($this->lines[$i]->remise_percent) && !getDolGlobalString('STOCK_EXCLUDE_DISCOUNT_FOR_PMP')) {
1412 $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1413 }
1414 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->transnoentitiesnoconv("OrderApprovedInDolibarr", $this->ref));
1415 if ($result < 0) {
1416 $error++;
1417 }
1418 unset($this->line);
1419 }
1420 }
1421 }
1422
1423 if (!$error) {
1424 // Call trigger
1425 $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user);
1426 if ($result < 0) {
1427 $error++;
1428 }
1429 // End call triggers
1430 }
1431
1432 if (!$error) {
1433 $this->ref = $this->newref;
1434
1435 if ($movetoapprovestatus) {
1436 $this->statut = self::STATUS_ACCEPTED; // deprecated
1438 } else {
1439 $this->statut = self::STATUS_VALIDATED; // deprecated
1441 }
1442 if (empty($secondlevel)) { // standard or first level approval
1443 $this->date_approve = $now;
1444 $this->user_approve_id = $user->id;
1445 } else { // request a second level approval
1446 $this->date_approve2 = $now;
1447 $this->user_approve_id2 = $user->id;
1448 }
1449
1450 $this->db->commit();
1451 return 1;
1452 } else {
1453 $this->db->rollback();
1454 return -1;
1455 }
1456 } else {
1457 $this->db->rollback();
1458 $this->error = $this->db->lasterror();
1459 return -1;
1460 }
1461 } else {
1462 dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
1463 }
1464 return -1;
1465 }
1466
1473 public function refuse($user)
1474 {
1475 $error = 0;
1476
1477 dol_syslog(get_class($this)."::refuse");
1478 $result = 0;
1479 if ($user->hasRight("fournisseur", "commande", "approuver")) {
1480 $this->db->begin();
1481
1482 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
1483 $sql .= " WHERE rowid = ".((int) $this->id);
1484
1485 if ($this->db->query($sql)) {
1486 $result = 0;
1487
1488 if ($error == 0) {
1489 // Call trigger
1490 $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user);
1491 if ($result < 0) {
1492 $error++;
1493 $this->db->rollback();
1494 } else {
1495 $this->db->commit();
1496 }
1497 // End call triggers
1498 }
1499 } else {
1500 $this->db->rollback();
1501 $this->error = $this->db->lasterror();
1502 dol_syslog(get_class($this)."::refuse Error -1");
1503 $result = -1;
1504 }
1505 } else {
1506 dol_syslog(get_class($this)."::refuse Not Authorized");
1507 }
1508 return $result;
1509 }
1510
1511 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1520 public function cancel($user, $idwarehouse = -1)
1521 {
1522 // phpcs:enable
1523 $error = 0;
1524
1525 //dol_syslog("CommandeFournisseur::Cancel");
1526 $result = 0;
1527 if ($user->hasRight("fournisseur", "commande", "commander")) {
1528 $statut = self::STATUS_CANCELED;
1529
1530 $this->db->begin();
1531
1532 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur SET fk_statut = ".((int) $statut);
1533 $sql .= " WHERE rowid = ".((int) $this->id);
1534 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
1535 if ($this->db->query($sql)) {
1536 $result = 0;
1537
1538 // Call trigger
1539 $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user);
1540 if ($result < 0) {
1541 $error++;
1542 }
1543 // End call triggers
1544
1545 if ($error == 0) {
1546 $this->db->commit();
1547 return 1;
1548 } else {
1549 $this->db->rollback();
1550 return -1;
1551 }
1552 } else {
1553 $this->db->rollback();
1554 $this->error = $this->db->lasterror();
1555 dol_syslog(get_class($this)."::cancel ".$this->error);
1556 return -1;
1557 }
1558 } else {
1559 dol_syslog(get_class($this)."::cancel Not Authorized");
1560 return -1;
1561 }
1562 }
1563
1573 public function commande($user, $date, $methode, $comment = '')
1574 {
1575 global $langs;
1576 dol_syslog(get_class($this)."::commande");
1577 $error = 0;
1578 if ($user->hasRight("fournisseur", "commande", "commander")) {
1579 $this->db->begin();
1580
1581 $newnoteprivate = $this->note_private;
1582 if ($comment) {
1583 $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment);
1584 }
1585
1586 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1587 $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".((int) $methode).", date_commande='".$this->db->idate($date)."', ";
1588 $sql .= " note_private='".$this->db->escape((string) $newnoteprivate)."'";
1589 $sql .= " WHERE rowid=".((int) $this->id);
1590
1591 dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1592 if ($this->db->query($sql)) {
1593 $this->statut = self::STATUS_ORDERSENT; // deprecated
1595 $this->methode_commande_id = $methode;
1596 $this->date_commande = $date;
1597 $this->context['comments'] = $comment;
1598
1599 // Call trigger
1600 $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
1601 if ($result < 0) {
1602 $error++;
1603 }
1604 // End call triggers
1605 } else {
1606 $error++;
1607 $this->error = $this->db->lasterror();
1608 $this->errors[] = $this->db->lasterror();
1609 }
1610
1611 if (!$error) {
1612 $this->db->commit();
1613 } else {
1614 $this->db->rollback();
1615 }
1616 } else {
1617 $error++;
1618 $this->error = $langs->trans('NotAuthorized');
1619 $this->errors[] = $langs->trans('NotAuthorized');
1620 dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1621 }
1622
1623 return ($error ? -1 : 1);
1624 }
1625
1632 public function updateProductBuyPrices($user)
1633 {
1634 if (empty($this->thirdparty)) {
1635 $this->fetch_thirdparty();
1636 }
1637
1638 // Same rights as the buying prices tab of the product card
1639 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1640 $canproduct = $canservice = $user->hasRight('product', 'product_advance', 'write_supplier_prices');
1641 } else {
1642 $canproduct = $user->hasRight('produit', 'creer');
1643 $canservice = $user->hasRight('service', 'creer');
1644 }
1645
1646 // Products for which the supplier already has a price, whatever its ref
1647 $withprice = array();
1648 $productids = array(0);
1649 foreach ($this->lines as $line) {
1650 $productids[] = (int) $line->fk_product;
1651 }
1652 $sql = "SELECT DISTINCT fk_product FROM ".$this->db->prefix()."product_fournisseur_price";
1653 $sql .= " WHERE fk_soc = ".((int) $this->socid)." AND entity IN (".getEntity('productsupplierprice').") AND fk_product IN (".$this->db->sanitize(implode(',', $productids)).")";
1654 $resql = $this->db->query($sql);
1655 while ($resql && $obj = $this->db->fetch_object($resql)) {
1656 $withprice[(int) $obj->fk_product] = 1;
1657 }
1658
1659 $nbupdated = 0;
1660 foreach ($this->lines as $line) {
1661 if ($line->fk_product <= 0 || $line->qty <= 0 || $line->subprice <= 0 || ($line->product_type == Product::TYPE_SERVICE ? !$canservice : !$canproduct)) {
1662 continue;
1663 }
1664
1665 // Supplier price. History and triggers are managed by update_buyprice(). Nothing to update if no price line exists for this supplier ref.
1666 $productsupplier = new ProductFournisseur($this->db);
1667 if ($productsupplier->get_buyprice(0, $line->qty, $line->fk_product, $line->ref_supplier, (int) $this->socid) > 0
1668 && $productsupplier->fetch_product_fournisseur_price($productsupplier->product_fourn_price_id) > 0
1669 && (price2num($productsupplier->fourn_unitprice, 'MU') != price2num($line->subprice, 'MU') || (float) $productsupplier->fourn_remise_percent != (float) $line->remise_percent)) {
1670 $qty = $productsupplier->fourn_qty;
1671 $productsupplier->product_fourn_packaging = $productsupplier->packaging; // Keep the packaging of the price line
1672 $mcsubprice = (empty($line->multicurrency_subprice) ? $line->subprice : $line->multicurrency_subprice);
1673 $result = $productsupplier->update_buyprice($qty, $line->subprice * $qty, $user, 'HT', $this->thirdparty, $productsupplier->fk_availability, $productsupplier->ref_supplier, (float) $productsupplier->fourn_tva_tx, (float) $productsupplier->fourn_charges, $line->remise_percent, $productsupplier->fourn_remise, $productsupplier->fourn_tva_npr, $productsupplier->delivery_time_days, $productsupplier->supplier_reputation, array(), $productsupplier->default_vat_code, $mcsubprice * $qty, 'HT', (float) $this->multicurrency_tx, $this->multicurrency_code, $productsupplier->desc_supplier, $productsupplier->supplier_barcode, (int) $productsupplier->supplier_fk_barcode_type);
1674 if ($result < 0) {
1675 $this->setErrorsFromObject($productsupplier);
1676 return -1;
1677 }
1678 $nbupdated++;
1679 }
1680
1681 // The supplier has no price for this product: create it for the quantity 1, like the buying prices tab of the product does.
1682 // The supplier ref is the one of the line or else the ref of the product, as it must be unique for a supplier and a quantity.
1683 $newprice = new ProductFournisseur($this->db);
1684 if (empty($productsupplier->product_fourn_price_id) && empty($withprice[$line->fk_product]) && $newprice->fetch($line->fk_product) > 0) {
1685 $ref = ($line->ref_supplier ? (string) $line->ref_supplier : $newprice->ref);
1686 $result = $newprice->add_fournisseur($user, (int) $this->socid, $ref, 1); // -3 if this supplier ref is used by another product
1687 if ($result > 0) {
1688 $withprice[$line->fk_product] = 1;
1689 $result = $newprice->update_buyprice(1, (float) $line->subprice, $user, 'HT', $this->thirdparty, 0, $ref, (float) $line->tva_tx, 0, $line->remise_percent, 0, 0, 0, '', array(), (string) $line->vat_src_code, (float) ($line->multicurrency_subprice ?: $line->subprice), 'HT', (float) $this->multicurrency_tx, $this->multicurrency_code);
1690 $nbupdated++;
1691 }
1692 if ($result < 0 && $result != -3) {
1693 $this->setErrorsFromObject($newprice);
1694 return -1;
1695 }
1696 }
1697
1698 // Cost price (net unit price of the line)
1699 $costprice = price2num($line->subprice * (1 - $line->remise_percent / 100), 'MU');
1700 $product = new Product($this->db);
1701 if ($product->fetch($line->fk_product) > 0 && price2num($product->cost_price, 'MU') != $costprice) {
1702 $result = $product->setValueFrom('cost_price', $costprice, '', null, 'text', '', $user, 'PRODUCT_MODIFY');
1703 if ($result < 0) {
1704 $this->setErrorsFromObject($product);
1705 return -1;
1706 }
1707 $nbupdated++;
1708 }
1709 }
1710
1711 return $nbupdated;
1712 }
1713
1721 public function create($user, $notrigger = 0)
1722 {
1723 global $conf;
1724
1725 $this->db->begin();
1726
1727 $error = 0;
1728 $now = dol_now();
1729
1730 // set tmp vars
1731 $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set
1732 if (empty($date)) {
1733 $date = $now;
1734 }
1735 $delivery_date = $this->delivery_date;
1736
1737 // Clean parameters
1738 if (empty($this->source)) {
1739 $this->source = 0;
1740 }
1741
1742 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1743 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1744 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
1745 } else {
1746 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1747 }
1748 if (empty($this->fk_multicurrency)) {
1749 $this->multicurrency_code = $conf->currency;
1750 $this->fk_multicurrency = 0;
1751 $this->multicurrency_tx = 1;
1752 }
1753 $this->entity = setEntity($this);
1754
1755 // We set order into draft status
1756 $this->statut = self::STATUS_DRAFT; // deprecated
1757 $this->status = self::STATUS_DRAFT;
1758
1759 $sql = "INSERT INTO ".$this->db->prefix()."commande_fournisseur (";
1760 $sql .= "ref";
1761 $sql .= ", ref_supplier";
1762 $sql .= ", note_private";
1763 $sql .= ", note_public";
1764 $sql .= ", entity";
1765 $sql .= ", fk_soc";
1766 $sql .= ", fk_projet";
1767 $sql .= ", date_creation";
1768 $sql .= ", date_livraison";
1769 $sql .= ", fk_warehouse";
1770 $sql .= ", fk_user_author";
1771 $sql .= ", fk_statut";
1772 $sql .= ", source";
1773 $sql .= ", model_pdf";
1774 $sql .= ", fk_mode_reglement";
1775 $sql .= ", deposit_percent";
1776 $sql .= ", fk_cond_reglement";
1777 $sql .= ", fk_account";
1778 $sql .= ", fk_incoterms, location_incoterms";
1779 $sql .= ", fk_multicurrency";
1780 $sql .= ", multicurrency_code";
1781 $sql .= ", multicurrency_tx";
1782 $sql .= ") ";
1783 $sql .= " VALUES (";
1784 $sql .= "'(PROV)'";
1785 $sql .= ", ".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "NULL");
1786 $sql .= ", '".$this->db->escape((string) $this->note_private)."'";
1787 $sql .= ", '".$this->db->escape((string) $this->note_public)."'";
1788 $sql .= ", ".((int) $this->entity);
1789 $sql .= ", ".((int) $this->socid);
1790 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1791 $sql .= ", '".$this->db->idate($date)."'";
1792 $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1793 $sql .= ", ".($this->fk_warehouse > 0 ? ((int) $this->fk_warehouse) : "null");
1794 $sql .= ", ".((int) $user->id);
1795 $sql .= ", ".self::STATUS_DRAFT;
1796 $sql .= ", ".((int) $this->source);
1797 $sql .= ", '".$this->db->escape(getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF'))."'";
1798 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'null');
1799 $sql .= ", ".(!empty($this->deposit_percent) ? "'" . $this->db->escape($this->deposit_percent) . "'" : "null");
1800 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'null');
1801 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1802 $sql .= ", ".(int) $this->fk_incoterms;
1803 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1804 $sql .= ", ".(int) $this->fk_multicurrency;
1805 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1806 $sql .= ", ".(float) $this->multicurrency_tx;
1807 $sql .= ")";
1808
1809 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1810 if ($this->db->query($sql)) {
1811 $this->id = $this->db->last_insert_id($this->db->prefix()."commande_fournisseur");
1812
1813 if ($this->id) {
1814 $num = count($this->lines);
1815
1816 // insert products details into database
1817 for ($i = 0; $i < $num; $i++) {
1818 $line = $this->lines[$i];
1819 if (!is_object($line)) {
1820 // Build a real line object: the loop below calls methods on it
1821 // (getPriceBaseType), which a cast to stdClass cannot answer.
1822 $lineobj = new CommandeFournisseurLigne($this->db);
1823 foreach ($line as $key => $val) {
1824 $lineobj->$key = $val;
1825 }
1826 $line = $lineobj;
1827 $this->lines[$i] = $line;
1828 }
1829
1830 //$this->special_code = $line->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
1831
1832 // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1833 // Preserve the original entry mode of the line so the total is computed from the typed value (no rounding drift).
1834 // In TTC mode, do not forward the HT currency price as pu_ht_devise: under multicurrency it would
1835 // reset the local price and recompute from the HT currency amount (read as TTC) -> 0.01 drift.
1836 // Like SupplierProposal (which does not pass it), the currency price is re-derived from the local price.
1837 $line_price_base_type = $line->getPriceBaseType();
1838 $line_pu_devise = ($line_price_base_type === 'TTC') ? 0 : (float) $line->multicurrency_subprice;
1839 $result = $this->addline(
1840 (string) $line->desc,
1841 (float) $line->subprice,
1842 (float) $line->qty,
1843 $line->tva_tx,
1844 (float) $line->localtax1_tx,
1845 (float) $line->localtax2_tx,
1846 (int) $line->fk_product,
1847 0,
1848 (string) ($line->ref_supplier ? $line->ref_supplier : $line->ref_fourn), // $line->ref_fourn comes from field ref into table of lines. Value may be a ref that does not exists anymore, so we first try with value of product
1849 (float) $line->remise_percent,
1850 $line_price_base_type,
1851 (float) $line->subprice_ttc,
1852 (int) $line->product_type,
1853 (int) $line->info_bits,
1854 0,
1855 $line->date_start ?? null,
1856 $line->date_end ?? null,
1857 $line->array_options,
1858 $line->fk_unit ?? null,
1859 $line_pu_devise, // pu_ht_devise
1860 (string) $line->origin, // origin
1861 (int) $line->origin_id, // origin_id
1862 (int) ($line->rang > 0 ? $line->rang : -1), // rang
1863 (int) $line->special_code,
1864 isset($line->product_label) ? $line->product_label : ''
1865 );
1866 if ($result < 0) {
1867 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functional error
1868 $this->db->rollback();
1869 return -1;
1870 }
1871 }
1872
1873 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1874 $sql .= " SET ref='(PROV".((int) $this->id).")'";
1875 $sql .= " WHERE rowid=".((int) $this->id);
1876
1877 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1878 if ($this->db->query($sql)) {
1879 // Add link with price request and supplier order
1880 if ($this->id) {
1881 $this->ref = "(PROV".$this->id.")";
1882
1883 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1884 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1885 }
1886
1887 // Add object linked
1888 if (!empty($this->linked_objects) && is_array($this->linked_objects)) {
1889 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1890 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, ...))
1891 foreach ($tmp_origin_id as $origin_id) {
1892 $ret = $this->add_object_linked($origin, $origin_id);
1893 if (!$ret) {
1894 dol_print_error($this->db);
1895 $error++;
1896 }
1897 }
1898 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1899 $origin_id = $tmp_origin_id;
1900 $ret = $this->add_object_linked($origin, $origin_id);
1901 if (!$ret) {
1902 dol_print_error($this->db);
1903 $error++;
1904 }
1905 }
1906 }
1907 }
1908 }
1909
1910 if (!$error) {
1911 $result = $this->insertExtraFields();
1912 if ($result < 0) {
1913 $error++;
1914 }
1915 }
1916
1917 if (!$error && !$notrigger) {
1918 // Call trigger
1919 $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user);
1920 if ($result < 0) {
1921 $this->db->rollback();
1922
1923 return -1;
1924 }
1925 // End call triggers
1926 }
1927
1928 $this->db->commit();
1929 return $this->id;
1930 } else {
1931 $this->error = $this->db->lasterror();
1932 $this->db->rollback();
1933
1934 return -2;
1935 }
1936 } else {
1937 $this->error = 'Failed to get ID of inserted line';
1938
1939 return -1;
1940 }
1941 } else {
1942 $this->error = $this->db->lasterror();
1943 $this->db->rollback();
1944
1945 return -1;
1946 }
1947 }
1948
1956 public function update(User $user, $notrigger = 0)
1957 {
1958 $error = 0;
1959
1960 // Clean parameters
1961 if (isset($this->ref)) {
1962 $this->ref = trim($this->ref);
1963 }
1964 if (isset($this->ref_supplier)) {
1965 $this->ref_supplier = trim($this->ref_supplier);
1966 }
1967 if (isset($this->note_private)) {
1968 $this->note_private = trim($this->note_private);
1969 }
1970 if (isset($this->note_public)) {
1971 $this->note_public = trim($this->note_public);
1972 }
1973 if (isset($this->model_pdf)) {
1974 $this->model_pdf = trim($this->model_pdf);
1975 }
1976 if (isset($this->import_key)) {
1977 $this->import_key = trim($this->import_key);
1978 }
1979
1980 // Update request
1981 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET";
1982
1983 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1984 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1985 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1986 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
1987 $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
1988 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1989 $sql .= " fk_warehouse=".($this->fk_warehouse > 0 ? ((int) $this->fk_warehouse) : "null").",";
1990 $sql .= " total_tva=".(isset($this->total_tva) ? ((float) $this->total_tva) : "null").",";
1991 $sql .= " localtax1=".(isset($this->total_localtax1) ? ((float) $this->total_localtax1) : "null").",";
1992 $sql .= " localtax2=".(isset($this->total_localtax2) ? ((float) $this->total_localtax2) : "null").",";
1993 $sql .= " total_ht=".(isset($this->total_ht) ? ((float) $this->total_ht) : "null").",";
1994 $sql .= " total_ttc=".(isset($this->total_ttc) ? ((float) $this->total_ttc) : "null").",";
1995 $sql .= " fk_statut=".(isset($this->status) ? ((int) $this->status) : "null").",";
1996 $sql .= " fk_user_author=".(isset($this->user_author_id) ? ((int) $this->user_author_id) : "null").",";
1997 $sql .= " fk_user_valid=".(isset($this->user_validation_id) && $this->user_validation_id > 0 ? ((int) $this->user_validation_id) : "null").",";
1998 $sql .= " fk_projet=".((!empty($this->fk_project) && $this->fk_project > 0) ? ((int) $this->fk_project) : "null").",";
1999 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? ((int) $this->cond_reglement_id) : "null").",";
2000 $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
2001 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? ((int) $this->mode_reglement_id) : "null").",";
2002 $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
2003 //$sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").",";
2004 $sql .= " fk_account=".($this->fk_account > 0 ? ((int) $this->fk_account) : "null").",";
2005 //$sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").",";
2006 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
2007 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
2008 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
2009 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
2010
2011 $sql .= " WHERE rowid=".((int) $this->id);
2012
2013 $this->db->begin();
2014
2015 dol_syslog(get_class($this)."::update", LOG_DEBUG);
2016 $resql = $this->db->query($sql);
2017 if (!$resql) {
2018 $error++;
2019 $this->errors[] = "Error ".$this->db->lasterror();
2020 }
2021
2022 if (!$error) {
2023 $result = $this->insertExtraFields();
2024 if ($result < 0) {
2025 $error++;
2026 }
2027 }
2028
2029 if (!$error && !$notrigger) {
2030 // Call trigger
2031 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2032 if ($result < 0) {
2033 $error++;
2034 }
2035 // End call triggers
2036 }
2037
2038 // Commit or rollback
2039 if ($error) {
2040 foreach ($this->errors as $errmsg) {
2041 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2042 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2043 }
2044 $this->db->rollback();
2045 return -1 * $error;
2046 } else {
2047 $this->db->commit();
2048 return 1;
2049 }
2050 }
2051
2060 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
2061 {
2062 global $conf, $user, $hookmanager;
2063
2064 $error = 0;
2065
2066 $this->db->begin();
2067
2068 // get extrafields so they will be clone
2069 foreach ($this->lines as $line) {
2070 $line->fetch_optionals();
2071 }
2072
2073 // Load source object
2074 $objFrom = clone $this;
2075
2076 // Change socid if needed
2077 if (!empty($socid) && $socid != $this->socid) {
2078 $objsoc = new Societe($this->db);
2079
2080 if ($objsoc->fetch($socid) > 0) {
2081 $this->socid = $objsoc->id;
2082 $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
2083 $this->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : '0');
2084 $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
2085 $this->fk_project = 0;
2086 $this->fk_delivery_address = 0;
2087 }
2088
2089 // TODO Change product price if multi-prices
2090 }
2091
2092 $this->id = 0;
2093 $this->statut = self::STATUS_DRAFT; // deprecated
2094 $this->status = self::STATUS_DRAFT;
2095
2096 // Clear fields
2097 $this->user_author_id = $user->id;
2098 $this->user_validation_id = 0;
2099
2100 $this->date = dol_now();
2101 $this->date_creation = 0;
2102 $this->date_validation = 0;
2103 $this->date_commande = null;
2104 $this->ref_supplier = '';
2105 $this->user_approve_id = 0;
2106 $this->user_approve_id2 = 0;
2107 $this->date_approve = 0;
2108 $this->date_approve2 = 0;
2109
2110 // Create clone
2111 $this->context['createfromclone'] = 'createfromclone';
2112 $result = $this->create($user, $notrigger);
2113 if ($result < 0) {
2114 $error++;
2115 }
2116
2117 if (!$error) {
2118 // Hook of thirdparty module
2119 if (is_object($hookmanager)) {
2120 $parameters = array('objFrom' => $objFrom);
2121 $action = '';
2122 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2123 if ($reshook < 0) {
2124 $this->setErrorsFromObject($hookmanager);
2125 $error++;
2126 }
2127 }
2128 }
2129
2130 unset($this->context['createfromclone']);
2131
2132 // End
2133 if (!$error) {
2134 $this->db->commit();
2135 return $this->id;
2136 } else {
2137 $this->db->rollback();
2138 return -1;
2139 }
2140 }
2141
2172 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, $label = '')
2173 {
2174 global $langs, $mysoc;
2175
2176 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");
2177 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2178
2179 if ($this->status == self::STATUS_DRAFT) {
2180 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2181
2182 // Clean parameters
2183 if (empty($qty)) {
2184 $qty = 0;
2185 }
2186 if (!$info_bits) {
2187 $info_bits = 0;
2188 }
2189 if (empty($txtva)) {
2190 $txtva = 0;
2191 }
2192 if (empty($rang)) {
2193 $rang = 0;
2194 }
2195 if (empty($txlocaltax1)) {
2196 $txlocaltax1 = 0;
2197 }
2198 if (empty($txlocaltax2)) {
2199 $txlocaltax2 = 0;
2200 }
2201 if (empty($remise_percent)) {
2202 $remise_percent = 0;
2203 }
2204
2205 $remise_percent = price2num($remise_percent);
2206 $qty = price2num($qty);
2207 $pu_ht = price2num($pu_ht);
2208 $pu_ht_devise = price2num($pu_ht_devise);
2209 $pu_ttc = price2num($pu_ttc);
2210 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
2211 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
2212 }
2213 $txlocaltax1 = price2num($txlocaltax1);
2214 $txlocaltax2 = price2num($txlocaltax2);
2215 if ($price_base_type == 'HT') {
2216 $pu = $pu_ht;
2217 } else {
2218 $pu = $pu_ttc;
2219 }
2220
2221 $label = trim((string) $label);
2222 $desc = trim((string) $desc);
2223 if ($desc === '' && $label !== '') {
2224 $desc = $label;
2225 }
2226
2227 // Check parameters
2228 if ($qty < 0 && !$fk_product) {
2229 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product"));
2230 return -1;
2231 }
2232 if ($type < 0) {
2233 return -1;
2234 }
2235 if ($date_start && $date_end && $date_start > $date_end) {
2236 $langs->load("errors");
2237 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2238 return -1;
2239 }
2240
2241
2242 $this->db->begin();
2243
2244 $product_type = $type;
2245 $label = ''; // deprecated
2246
2247 if ($fk_product > 0) {
2248 if (getDolGlobalInt('SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY') == 1) { // Not the common case
2249 // Check quantity is enough
2250 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);
2251 $prod = new ProductFournisseur($this->db);
2252 if ($prod->fetch($fk_product) > 0) {
2253 $product_type = $prod->type;
2254 $label = $prod->label;
2255
2256 // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
2257 // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
2258 $result = $prod->get_buyprice($fk_prod_fourn_price, (float) $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
2259
2260 // If supplier order created from sales order, we take best supplier price
2261 // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price
2262 if ($result > 0 && ($origin == 'commande' || $pu === '')) {
2263 $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
2264 $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
2265 // is remise percent not keyed but present for the product we add it
2266 if ($remise_percent == 0 && $prod->remise_percent != 0) {
2267 $remise_percent = $prod->remise_percent;
2268 }
2269 }
2270 if ($result == 0) { // If result == 0, we failed to found the supplier reference price
2271 $langs->load("errors");
2272 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2273 $this->db->rollback();
2274 dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
2275 //$pu = $prod->fourn_pu; // We do not overwrite unit price
2276 //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
2277 return -1;
2278 }
2279 if ($result == -1) {
2280 $langs->load("errors");
2281 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2282 $this->db->rollback();
2283 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
2284 return -1;
2285 }
2286 if ($result < -1) {
2287 $this->error = $prod->error;
2288 $this->db->rollback();
2289 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
2290 return -1;
2291 }
2292 } else {
2293 $this->error = $prod->error;
2294 $this->db->rollback();
2295 return -1;
2296 }
2297 }
2298
2299 // Predefine quantity according to packaging
2300 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2301 $prod = new Product($this->db);
2302 $prod->get_buyprice($fk_prod_fourn_price, (float) $qty, $fk_product, 'none', (empty($this->fk_soc) ? $this->socid : $this->fk_soc));
2303
2304 // Align messaging, type and float-safety with the customer-order path at commande.class.php:1720
2305 // (#38782 bugs 1, 2, 6).
2306 $newqty = $this->roundQtyToPackaging($qty, $prod->packaging);
2307 if ($newqty != $qty) {
2308 $qty = $newqty;
2309 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
2310 }
2311
2312 // Enforce the supplier minimum purchase quantity on top of packaging
2313 // rounding. The packaging block above only ensures qty is a packaging
2314 // multiple, not that it satisfies pfp.quantity (=qty_min). If the line
2315 // is below the supplier minimum, round qty_min itself up to the next
2316 // packaging multiple so we end up with the smallest valid order qty (#38783).
2317 if (!empty($prod->fourn_qty) && (float) $qty > 0 && (float) $qty < (float) $prod->fourn_qty) { // A negative quantity (return) is not concerned by the minimum purchase quantity
2318 if (!empty($prod->packaging) && (float) price2num(fmod((float) $prod->fourn_qty, (float) $prod->packaging), 'MS')) {
2319 $coeff = intval((float) $prod->fourn_qty / (float) $prod->packaging) + 1;
2320 $qty = (float) price2num((float) $prod->packaging * $coeff, 'MS');
2321 } else {
2322 $qty = (float) $prod->fourn_qty;
2323 }
2324 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'mesgs');
2325 }
2326 }
2327 }
2328
2329 if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
2330 $pu = 0;
2331 }
2332
2333 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2334
2335 // Clean vat code
2336 $reg = array();
2337 $vat_src_code = '';
2338 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
2339 $vat_src_code = $reg[1];
2340 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
2341 }
2342
2343 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
2344 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
2345 // and this is done at the line level, which has its own VAT rate
2346
2347 $tabprice = calcul_price_total((float) $qty, $pu, (float) $remise_percent, $txtva, (float) $txlocaltax1, (float) $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise, $this->multicurrency_code);
2348
2349 $total_ht = $tabprice[0];
2350 $total_tva = $tabprice[1];
2351 $total_ttc = $tabprice[2];
2352 $total_localtax1 = $tabprice[9];
2353 $total_localtax2 = $tabprice[10];
2354 $pu = $pu_ht = $tabprice[3];
2355 $pu_tva = $tabprice[4];
2356 $pu_ttc = $tabprice[5];
2357
2358 // MultiCurrency
2359 $multicurrency_total_ht = $tabprice[16];
2360 $multicurrency_total_tva = $tabprice[17];
2361 $multicurrency_total_ttc = $tabprice[18];
2362 $pu_ht_devise = $tabprice[19];
2363 $multicurrency_pu_ttc = $tabprice[21];
2364
2365 $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
2366 $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
2367
2368 if ($rang < 0) {
2369 $rangmax = $this->line_max();
2370 $rang = $rangmax + 1;
2371 }
2372
2373 // Insert line
2374 $this->line = new CommandeFournisseurLigne($this->db);
2375
2376 $this->line->context = $this->context;
2377
2378 $this->line->fk_commande = $this->id;
2379 $this->line->label = $label;
2380 $this->line->ref_fourn = $ref_supplier;
2381 $this->line->ref_supplier = $ref_supplier;
2382 $this->line->desc = $desc;
2383 $this->line->qty = $qty;
2384 $this->line->tva_tx = $txtva;
2385 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
2386 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
2387 $this->line->localtax1_type = $localtax1_type;
2388 $this->line->localtax2_type = $localtax2_type;
2389 $this->line->fk_product = $fk_product;
2390 $this->line->product_type = $product_type;
2391 $this->line->remise_percent = $remise_percent;
2392 $this->line->subprice = (float) $pu_ht;
2393 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
2394
2395 $this->line->rang = $rang;
2396 $this->line->info_bits = $info_bits;
2397
2398 $this->line->vat_src_code = $vat_src_code;
2399 $this->line->total_ht = (float) $total_ht;
2400 $this->line->total_tva = (float) $total_tva;
2401 $this->line->total_localtax1 = (float) $total_localtax1;
2402 $this->line->total_localtax2 = (float) $total_localtax2;
2403 $this->line->total_ttc = (float) $total_ttc;
2404 $this->line->product_type = $type;
2405 $this->line->special_code = (!empty($special_code) ? $special_code : 0);
2406 $this->line->origin = $origin;
2407 $this->line->origin_type = $origin;
2408 $this->line->origin_id = $origin_id;
2409 $this->line->fk_unit = $fk_unit;
2410
2411 $this->line->date_start = $date_start;
2412 $this->line->date_end = $date_end;
2413
2414 // Multicurrency
2415 $this->line->fk_multicurrency = $this->fk_multicurrency;
2416 $this->line->multicurrency_code = $this->multicurrency_code;
2417 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
2418 $this->line->multicurrency_subprice_ttc = (float) $multicurrency_pu_ttc;
2419 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
2420 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
2421 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
2422
2423 $this->line->subprice = (float) $pu_ht;
2424 $this->line->price = $this->line->subprice;
2425
2426 $this->line->remise_percent = $remise_percent;
2427
2428 if (is_array($array_options) && count($array_options) > 0) {
2429 $this->line->array_options = $array_options;
2430 }
2431
2432 $result = $this->line->insert($notrigger);
2433 if ($result > 0) {
2434 // Update denormalized fields at the order level
2435 $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.
2436
2437 if ($result > 0) {
2438 if (!isset($this->context['createfromclone'])) {
2439 if (!empty($this->line->fk_parent_line)) {
2440 // Always reorder if child line
2441 $this->line_order(true, 'DESC');
2442 } elseif ($rang > 0 && $rang <= count($this->lines)) {
2443 // Update all rank of all other lines starting from the same $ranktouse
2444 $linecount = count($this->lines);
2445 for ($ii = $rang; $ii <= $linecount; $ii++) {
2446 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2447 }
2448 }
2449
2450 $this->lines[] = $this->line;
2451 } else {
2452 foreach ($this->lines as $line) {
2453 if ($line->id == $origin_id) {
2454 $this->line->extraparams = $line->extraparams;
2455 $this->line->setExtraParameters();
2456 }
2457 }
2458 }
2459
2460 $this->db->commit();
2461 return $this->line->id;
2462 } else {
2463 $this->db->rollback();
2464 return -1;
2465 }
2466 } else {
2467 $this->setErrorsFromObject($this->line);
2468 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
2469 $this->db->rollback();
2470 return -1;
2471 }
2472 }
2473 return -1;
2474 }
2475
2476
2494 public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0, $fk_reception = 0)
2495 {
2496 global $conf, $langs;
2497
2498 $error = 0;
2499 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2500
2501 // Check parameters (if test are wrong here, there is bug into caller)
2502 if ($entrepot <= 0) {
2503 $this->error = 'ErrorBadValueForParameterWarehouse';
2504 return -1;
2505 }
2506 if ($qty == 0) {
2507 $this->error = 'ErrorBadValueForParameterQty';
2508 return -1;
2509 }
2510
2511 $dispatchstatus = 1;
2512 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
2513 $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
2514 }
2515
2516 $now = dol_now();
2517
2518 $inventorycode = dol_print_date(dol_now(), 'dayhourlog');
2519
2520 if (($this->status == self::STATUS_ORDERSENT || $this->status == self::STATUS_RECEIVED_PARTIALLY || $this->status == self::STATUS_RECEIVED_COMPLETELY)) {
2521 $this->db->begin();
2522
2523 $sql = "INSERT INTO ".$this->db->prefix()."receptiondet_batch";
2524 $sql .= " (fk_element, fk_product, qty, fk_entrepot, fk_user, datec, fk_elementdet, status, comment, eatby, sellby, batch, fk_reception) VALUES";
2525 $sql .= " ('".((int) $this->id)."','".((int) $product)."','".((float) $qty)."',".($entrepot > 0 ? "'".((int) $entrepot)."'" : "null").",'".((int) $user->id)."','".$this->db->idate($now)."','".((int) $fk_commandefourndet)."', ".((int) $dispatchstatus).", '".$this->db->escape($comment)."', ";
2526 $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((string) $fk_reception)."'" : "null");
2527 $sql .= ")";
2528
2529 dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
2530 $resql = $this->db->query($sql);
2531 if ($resql) {
2532 if (!$notrigger) {
2533 global $conf, $langs, $user;
2534 // Call trigger
2535 $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user);
2536 if ($result < 0) {
2537 $error++;
2538 }
2539 // End call triggers
2540 }
2541 } else {
2542 $this->error = $this->db->lasterror();
2543 $error++;
2544 }
2545
2546 // If module stock is enabled and the stock increase is done on purchase order dispatching
2547 if (!$error && $entrepot > 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER')) {
2548 $mouv = new MouvementStock($this->db);
2549 if ($product > 0) {
2550 // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
2551 $mouv->origin = &$this;
2552 $mouv->setOrigin($this->element, $this->id);
2553
2554 // Method change if qty < 0
2555 if (getDolGlobalString('SUPPLIER_ORDER_ALLOW_NEGATIVE_QTY_FOR_SUPPLIER_ORDER_RETURN') && $qty < 0) {
2556 $result = $mouv->livraison($user, $product, $entrepot, $qty * (-1), $price, $comment, $now, $eatby, $sellby, $batch, 0, $inventorycode);
2557 } else {
2558 $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch, '', 0, $inventorycode);
2559 }
2560
2561 if ($result < 0) {
2562 $this->error = $mouv->error;
2563 $this->errors = $mouv->errors;
2564 dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".implode(',', $this->errors), LOG_ERR);
2565 $error++;
2566 }
2567 }
2568 }
2569
2570 if ($error == 0) {
2571 $this->db->commit();
2572 return 1;
2573 } else {
2574 $this->db->rollback();
2575 return -1;
2576 }
2577 } else {
2578 $this->error = 'BadStatusForObject';
2579 return -2;
2580 }
2581 }
2582
2590 public function deleteLine($idline, $notrigger = 0)
2591 {
2592 global $user;
2593
2594 if ($this->status == 0) {
2595 $line = new CommandeFournisseurLigne($this->db);
2596
2597 if ($line->fetch($idline) <= 0) {
2598 return 0;
2599 }
2600 if ($this->id > 0 && (int) $line->fk_commande !== (int) $this->id) {
2601 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2602 return -1;
2603 }
2604
2605 // check if not yet received
2606 $dispatchedLines = $this->getDispachedLines();
2607 foreach ($dispatchedLines as $dispatchLine) {
2608 if ($dispatchLine['orderlineid'] == $idline) {
2609 $this->error = "LineAlreadyDispatched";
2610 $this->errors[] = $this->error;
2611 return -3;
2612 }
2613 }
2614
2615 if ($line->delete($user, $notrigger) > 0) {
2616 $this->update_price(1);
2617 return 1;
2618 } else {
2619 $this->setErrorsFromObject($line);
2620 return -1;
2621 }
2622 } else {
2623 return -2;
2624 }
2625 }
2626
2634 public function delete(User $user, $notrigger = 0)
2635 {
2636 global $langs, $conf;
2637 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2638
2639 $error = 0;
2640
2641 $this->db->begin();
2642
2643 if (empty($notrigger)) {
2644 // Call trigger
2645 $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user);
2646 if ($result < 0) {
2647 $this->errors[] = 'ErrorWhenRunningTrigger';
2648 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2649 $this->db->rollback();
2650 return -1;
2651 }
2652 // End call triggers
2653 }
2654
2655 // Test we can delete
2656 $this->fetchObjectLinked(null, 'order_supplier');
2657 if (!empty($this->linkedObjects) && array_key_exists('reception', $this->linkedObjects)) {
2658 foreach ($this->linkedObjects['reception'] as $element) {
2659 if ($element->statut >= 0) {
2660 $this->errors[] = $langs->trans('ReceptionExist');
2661 $error++;
2662 break;
2663 }
2664 }
2665 }
2666
2667 // Remove linked categories.
2668 if (!$error) {
2669 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_supplier_order";
2670 $sql .= " WHERE fk_supplier_order = ".((int) $this->id);
2671
2672 $result = $this->db->query($sql);
2673 if (!$result) {
2674 $error++;
2675 $this->errors[] = $this->db->lasterror();
2676 }
2677 }
2678
2679 $main = $this->db->prefix().'commande_fournisseurdet';
2680
2681 if (!$error) {
2682 $sql1 = "UPDATE ".$this->db->prefix()."commandedet SET fk_commandefourndet = NULL WHERE fk_commandefourndet IN (SELECT rowid FROM ".$this->db->sanitize($main)." WHERE fk_commande = ".((int) $this->id).")";
2683 dol_syslog(__METHOD__." linked order lines", LOG_DEBUG);
2684 if (!$this->db->query($sql1)) {
2685 $error++;
2686 $this->error = $this->db->lasterror();
2687 $this->errors[] = $this->db->lasterror();
2688 }
2689 }
2690
2691 if (!$error) {
2692 $ef = $main."_extrafields";
2693 $sql = "DELETE FROM ".$this->db->sanitize($ef)." WHERE fk_object IN (SELECT rowid FROM ".$this->db->sanitize($main)." WHERE fk_commande = ".((int) $this->id).")";
2694 dol_syslog(get_class($this)."::delete extrafields lines", LOG_DEBUG);
2695 if (!$this->db->query($sql)) {
2696 $this->error = $this->db->lasterror();
2697 $this->errors[] = $this->db->lasterror();
2698 $error++;
2699 }
2700 }
2701
2702 if (!$error) {
2703 $sql = "DELETE FROM ".$this->db->prefix()."commande_fournisseurdet WHERE fk_commande = ".((int) $this->id);
2704 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2705 if (!$this->db->query($sql)) {
2706 $this->error = $this->db->lasterror();
2707 $this->errors[] = $this->db->lasterror();
2708 $error++;
2709 }
2710 }
2711
2712 if (!$error) {
2713 $sql = "DELETE FROM ".$this->db->prefix()."commande_fournisseur WHERE rowid = ".((int) $this->id);
2714 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2715 if ($resql = $this->db->query($sql)) {
2716 if ($this->db->affected_rows($resql) < 1) {
2717 $this->error = $this->db->lasterror();
2718 $this->errors[] = $this->db->lasterror();
2719 $error++;
2720 }
2721 } else {
2722 $this->error = $this->db->lasterror();
2723 $this->errors[] = $this->db->lasterror();
2724 $error++;
2725 }
2726 }
2727
2728 // Remove extrafields
2729 if (!$error) {
2730 $result = $this->deleteExtraFields();
2731 if ($result < 0) {
2732 $this->error = 'FailToDeleteExtraFields';
2733 $this->errors[] = 'FailToDeleteExtraFields';
2734 $error++;
2735 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
2736 }
2737 }
2738
2739 // Delete linked object
2740 $res = $this->deleteObjectLinked();
2741 if ($res < 0) {
2742 $this->error = 'FailToDeleteObjectLinked';
2743 $this->errors[] = 'FailToDeleteObjectLinked';
2744 $error++;
2745 }
2746
2747 if (!$error) {
2748 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2749 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2750 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2751
2752 // We remove directory
2753 $ref = dol_sanitizeFileName($this->ref);
2754 if ($conf->fournisseur->commande->dir_output && !empty($ref)) {
2755 $dir = $conf->fournisseur->commande->dir_output."/".$ref;
2756 $file = $dir."/".$ref.".pdf";
2757 if (file_exists($file)) {
2758 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2759 $this->error = 'ErrorFailToDeleteFile';
2760 $this->errors[] = 'ErrorFailToDeleteFile';
2761 $error++;
2762 }
2763 }
2764 if (file_exists($dir)) {
2765 $res = @dol_delete_dir_recursive($dir);
2766 if (!$res) {
2767 $this->error = 'ErrorFailToDeleteDir';
2768 $this->errors[] = 'ErrorFailToDeleteDir';
2769 $error++;
2770 }
2771 }
2772 }
2773 }
2774
2775 if (!$error) {
2776 dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
2777 $this->db->commit();
2778 return 1;
2779 } else {
2780 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2781 $this->db->rollback();
2782 return -$error;
2783 }
2784 }
2785
2786
2795 public function getDispachedLines($status = -1)
2796 {
2797 $ret = array();
2798
2799 // List of already dispatched lines
2800 $sql = "SELECT p.ref, p.label,";
2801 $sql .= " e.rowid as warehouse_id, e.ref as entrepot,";
2802 $sql .= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status, cfd.fk_elementdet";
2803 $sql .= " FROM ".$this->db->prefix()."product as p,";
2804 $sql .= " ".$this->db->prefix()."receptiondet_batch as cfd";
2805 $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e ON cfd.fk_entrepot = e.rowid";
2806 $sql .= " WHERE cfd.fk_element = ".((int) $this->id);
2807 $sql .= " AND cfd.fk_product = p.rowid";
2808 if ($status >= 0) {
2809 $sql .= " AND cfd.status = ".((int) $status);
2810 }
2811 $sql .= " ORDER BY cfd.rowid ASC";
2812
2813 $resql = $this->db->query($sql);
2814 if ($resql) {
2815 $num = $this->db->num_rows($resql);
2816 $i = 0;
2817
2818 while ($i < $num) {
2819 $objp = $this->db->fetch_object($resql);
2820 if ($objp) {
2821 $ret[] = array(
2822 'id' => $objp->dispatchedlineid,
2823 'productid' => $objp->fk_product,
2824 'warehouseid' => $objp->warehouse_id,
2825 'qty' => $objp->qty,
2826 'orderlineid' => $objp->fk_elementdet
2827 );
2828 }
2829
2830 $i++;
2831 }
2832 } else {
2833 dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
2834 }
2835
2836 return $ret;
2837 }
2838
2839 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2849 public function Livraison($user, $date, $type, $comment)
2850 {
2851 // phpcs:enable
2852 global $langs;
2853
2854 $result = 0;
2855 $error = 0;
2856 $dispatchedlinearray = array();
2857
2858 dol_syslog(get_class($this)."::Livraison");
2859
2860 $usercanreceive = 0;
2861 if (!isModEnabled('reception')) {
2862 $usercanreceive = $user->hasRight("fournisseur", "commande", "receptionner");
2863 } else {
2864 $usercanreceive = $user->hasRight("reception", "creer");
2865 }
2866
2867 if ($usercanreceive) {
2868 // Define the new status
2869 if ($type == 'par') {
2871 } elseif ($type == 'tot') {
2873 } elseif ($type == 'nev') {
2875 } elseif ($type == 'can') {
2877 } else {
2878 $error++;
2879 dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
2880 return -2;
2881 }
2882
2883 // Some checks to accept the record
2884 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
2885 // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
2886 if ($type == 'tot') {
2887 $dispatchedlinearray = $this->getDispachedLines(0);
2888 if (count($dispatchedlinearray) > 0) {
2889 $result = -1;
2890 $error++;
2891 $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
2892 dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
2893 }
2894 }
2895 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)
2896 $dispatcheddenied = $this->getDispachedLines(2);
2897 if (count($dispatcheddenied) > 0) {
2898 $result = -1;
2899 $error++;
2900 $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
2901 dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
2902 }
2903 }
2904 }
2905
2906 // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
2907
2908 if (empty($error)) {
2909 $this->db->begin();
2910
2911 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2912 $sql .= " SET fk_statut = ".((int) $statut);
2913 $sql .= " WHERE rowid = ".((int) $this->id);
2914 $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received
2915
2916 dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2917 $resql = $this->db->query($sql);
2918 if ($resql) {
2919 $result = 1;
2920 $old_statut = $this->status;
2921 $this->status = $statut;
2922 $this->context['actionmsg2'] = $comment;
2923
2924 // Call trigger
2925 $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
2926 if ($result_trigger < 0) {
2927 $error++;
2928 }
2929 // End call triggers
2930
2931 if (empty($error)) {
2932 $this->db->commit();
2933 } else {
2934 $this->status = $old_statut;
2935 $this->db->rollback();
2936 $this->error = $this->db->lasterror();
2937 $result = -1;
2938 }
2939 } else {
2940 $this->db->rollback();
2941 $this->error = $this->db->lasterror();
2942 $result = -1;
2943 }
2944 }
2945 } else {
2946 $this->error = $langs->trans('NotAuthorized');
2947 $this->errors[] = $langs->trans('NotAuthorized');
2948 dol_syslog(get_class($this)."::Livraison Not Authorized");
2949 $result = -3;
2950 }
2951 return $result;
2952 }
2953
2954 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2964 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2965 {
2966 // phpcs:enable
2967 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2968 }
2969
2978 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2979 {
2980 if ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")) {
2981 $error = 0;
2982
2983 $this->db->begin();
2984
2985 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2986 $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2987 $sql .= " WHERE rowid = ".((int) $this->id);
2988
2989 dol_syslog(__METHOD__, LOG_DEBUG);
2990 $resql = $this->db->query($sql);
2991 if (!$resql) {
2992 $this->errors[] = $this->db->error();
2993 $error++;
2994 }
2995
2996 if (!$error) {
2997 $this->oldcopy = clone $this;
2998 $this->delivery_date = $delivery_date;
2999 }
3000
3001 if (!$notrigger && empty($error)) {
3002 // Call trigger
3003 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
3004 if ($result < 0) {
3005 $error++;
3006 }
3007 // End call triggers
3008 }
3009
3010 if (!$error) {
3011 $this->db->commit();
3012 return 1;
3013 } else {
3014 foreach ($this->errors as $errmsg) {
3015 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3016 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3017 }
3018 $this->db->rollback();
3019 return -1 * $error;
3020 }
3021 } else {
3022 return -2;
3023 }
3024 }
3025
3032 public function setReopen(User $user): int
3033 {
3034 if (in_array($this->status, [1, 2, 3, 4, 5, 6, 7, 9])) {
3035 if ($this->status == 1) {
3036 $newStatus = 0; // Validated->Draft
3037 } elseif ($this->status == 2) {
3038 $newStatus = 0; // Approved->Draft
3039 } elseif ($this->status == 3) {
3040 $newStatus = 2; // Ordered->Approved
3041 } elseif ($this->status == 4) {
3042 $newStatus = 3;
3043 } elseif ($this->status == 5) {
3044 //$newstatus=2; // Ordered
3045 // TODO Can we set it to submitted ?
3046 //$newstatus=3; // Submitted
3047 // TODO If there is at least one reception, we can set to Received->Received partially
3048 $newStatus = 4; // Received partially
3049 } elseif ($this->status == 6) {
3050 $newStatus = 2; // Canceled->Approved
3051 } elseif ($this->status == 7) {
3052 $newStatus = 3; // Canceled->Process running
3053 } elseif ($this->status == 9) {
3054 $newStatus = 1; // Refused->Validated
3055 } else {
3056 $newStatus = 2;
3057 }
3058
3059 $this->db->begin();
3060
3061 $result = $this->setStatus($user, $newStatus);
3062 if ($result > 0) {
3063 if ($newStatus == 0) {
3064 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur';
3065 $sql .= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null';
3066 $sql .= ' WHERE rowid = '.((int) $this->id);
3067
3068 $this->db->query($sql);
3069 }
3070
3071 $this->db->commit();
3072
3073 return 1;
3074 } else {
3075 $this->db->rollback();
3076
3077 return -1;
3078 }
3079 }
3080
3081 return 0;
3082 }
3083
3084 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3093 public function set_id_projet($user, $id_projet, $notrigger = 0)
3094 {
3095 // phpcs:enable
3096 if ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")) {
3097 $error = 0;
3098
3099 $this->db->begin();
3100
3101 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
3102 $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
3103 $sql .= " WHERE rowid = ".((int) $this->id);
3104
3105 dol_syslog(__METHOD__, LOG_DEBUG);
3106 $resql = $this->db->query($sql);
3107 if (!$resql) {
3108 $this->errors[] = $this->db->error();
3109 $error++;
3110 }
3111
3112 if (!$error) {
3113 $this->oldcopy = clone $this;
3114 $this->fk_projet = $id_projet;
3115 $this->fk_project = $id_projet;
3116 }
3117
3118 if (!$notrigger && empty($error)) {
3119 // Call trigger
3120 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
3121 if ($result < 0) {
3122 $error++;
3123 }
3124 // End call triggers
3125 }
3126
3127 if (!$error) {
3128 $this->db->commit();
3129 return 1;
3130 } else {
3131 foreach ($this->errors as $errmsg) {
3132 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3133 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3134 }
3135 $this->db->rollback();
3136 return -1 * $error;
3137 }
3138 } else {
3139 return -2;
3140 }
3141 }
3142
3151 public function updateFromCommandeClient($user, $idc, $comclientid)
3152 {
3153 $comclient = new Commande($this->db);
3154 $comclient->fetch($comclientid);
3155
3156 $this->id = $idc;
3157
3158 $this->lines = array();
3159
3160 $num = count($comclient->lines);
3161 for ($i = 0; $i < $num; $i++) {
3162 $prod = new Product($this->db);
3163 $label = '';
3164 $ref = '';
3165 if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) {
3166 $label = $prod->label;
3167 $ref = (string) $prod->ref;
3168 }
3169
3170 $sql = "INSERT INTO ".$this->db->prefix()."commande_fournisseurdet";
3171 $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
3172 $sql .= " VALUES (".((int) $idc).", '".$this->db->escape($label)."', '".$this->db->escape($comclient->lines[$i]->desc)."'";
3173 $sql .= ",".((int) $comclient->lines[$i]->fk_product).", ".price2num($comclient->lines[$i]->price, 'MU');
3174 $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);
3175 $sql .= ", '".price2num($comclient->lines[$i]->subprice, 'MT')."','0', '".$this->db->escape($ref)."');";
3176 if ($this->db->query($sql)) {
3177 $this->update_price(1);
3178 }
3179 }
3180
3181 return 1;
3182 }
3183
3191 public function setStatus($user, $status)
3192 {
3193 $error = 0;
3194
3195 $this->db->begin();
3196
3197 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur';
3198 $sql .= " SET fk_statut = ".((int) $status);
3199 $sql .= " WHERE rowid = ".((int) $this->id);
3200
3201 dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
3202 $resql = $this->db->query($sql);
3203 if ($resql) {
3204 // Trigger names for each status
3205 $triggerName = array();
3206 $triggerName[0] = 'DRAFT';
3207 $triggerName[1] = 'VALIDATED';
3208 $triggerName[2] = 'APPROVED';
3209 $triggerName[3] = 'ORDERED'; // Ordered
3210 $triggerName[4] = 'RECEIVED_PARTIALLY';
3211 $triggerName[5] = 'RECEIVED_COMPLETELY';
3212 $triggerName[6] = 'CANCELED';
3213 $triggerName[7] = 'CANCELED';
3214 $triggerName[9] = 'REFUSED';
3215
3216 // Call trigger
3217 $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user);
3218 if ($result < 0) {
3219 $error++;
3220 }
3221 // End call triggers
3222 } else {
3223 $error++;
3224 $this->error = $this->db->lasterror();
3225 dol_syslog(get_class($this)."::setStatus ".$this->error);
3226 }
3227
3228 if (!$error) {
3229 $this->status = $status;
3230 $this->db->commit();
3231 return 1;
3232 } else {
3233 $this->db->rollback();
3234 return -1;
3235 }
3236 }
3237
3249 public function setCategories($categories)
3250 {
3251 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3252 return parent::setCategoriesCommon($categories, Categorie::TYPE_SUPPLIER_ORDER);
3253 }
3254
3278 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 = '')
3279 {
3280 global $mysoc, $conf, $langs;
3281
3282 if (!$this->isLineOfObject($rowid)) {
3283 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
3284 return -1;
3285 }
3286
3287 dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
3288 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3289
3290 $error = 0;
3291
3292 if ($this->status == self::STATUS_DRAFT) {
3293 // Clean parameters
3294 if (empty($qty)) {
3295 $qty = 0;
3296 }
3297 if (empty($info_bits)) {
3298 $info_bits = 0;
3299 }
3300 if (empty($txtva)) {
3301 $txtva = 0;
3302 }
3303 if (empty($txlocaltax1)) {
3304 $txlocaltax1 = 0;
3305 }
3306 if (empty($txlocaltax2)) {
3307 $txlocaltax2 = 0;
3308 }
3309 if (empty($remise_percent)) {
3310 $remise_percent = 0;
3311 }
3312
3313 $remise_percent = (float) price2num($remise_percent);
3314 $qty = price2num($qty);
3315 if (!$qty) {
3316 $qty = 1;
3317 }
3318 $pu = price2num($pu);
3319 $pu_ht_devise = price2num($pu_ht_devise);
3320 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3321 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3322 }
3323 $txlocaltax1 = (float) price2num($txlocaltax1);
3324 $txlocaltax2 = (float) price2num($txlocaltax2);
3325
3326 // Check parameters
3327 if ($type < 0) {
3328 return -1;
3329 }
3330 if ($date_start && $date_end && $date_start > $date_end) {
3331 $langs->load("errors");
3332 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3333 return -1;
3334 }
3335
3336 $this->db->begin();
3337
3338 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
3339 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
3340 // and this is done at the line level, which has its own VAT rate
3341
3342 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
3343
3344 // Clean vat code
3345 $reg = array();
3346 $vat_src_code = '';
3347 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3348 $vat_src_code = $reg[1];
3349 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3350 }
3351
3352 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
3353 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
3354 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
3355 $tmpline = new CommandeFournisseurLigne($this->db);
3356 if ($tmpline->fetch($rowid) > 0) {
3357 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
3358 if ($newqty != $qty) {
3359 $qty = $newqty;
3360 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
3361 }
3362 }
3363 }
3364
3365 $tabprice = calcul_price_total($qty, (float) $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, (float) $this->multicurrency_tx, (float) $pu_ht_devise, $this->multicurrency_code);
3366 $total_ht = $tabprice[0];
3367 $total_tva = $tabprice[1];
3368 $total_ttc = $tabprice[2];
3369 $total_localtax1 = $tabprice[9];
3370 $total_localtax2 = $tabprice[10];
3371 $pu_ht = $tabprice[3];
3372 $pu_tva = $tabprice[4];
3373 $pu_ttc = $tabprice[5];
3374
3375 // MultiCurrency
3376 $multicurrency_total_ht = $tabprice[16];
3377 $multicurrency_total_tva = $tabprice[17];
3378 $multicurrency_total_ttc = $tabprice[18];
3379 $pu_ht_devise = $tabprice[19];
3380 $multicurrency_pu_ttc = $tabprice[21];
3381
3382 $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3383 $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3384
3385 // Fetch current line from the database and then clone the object and set it in $oldline property
3386 $this->line = new CommandeFournisseurLigne($this->db);
3387 $this->line->fetch($rowid);
3388
3389 $oldline = clone $this->line;
3390 $this->line->oldline = $oldline;
3391
3392 $this->line->context = $this->context;
3393
3394 $this->line->fk_commande = $this->id;
3395 //$this->line->label=$label;
3396 $this->line->desc = $desc;
3397
3398
3399 $this->line->qty = $qty;
3400 $this->line->ref_supplier = $ref_supplier;
3401
3402 $this->line->vat_src_code = $vat_src_code;
3403 $this->line->tva_tx = $txtva;
3404 $this->line->localtax1_tx = $txlocaltax1;
3405 $this->line->localtax2_tx = $txlocaltax2;
3406 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3407 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3408 $this->line->remise_percent = $remise_percent;
3409 $this->line->subprice = (float) $pu_ht;
3410 $this->line->subprice_ttc = (float) $pu_ttc;
3411 $this->line->info_bits = $info_bits;
3412 $this->line->total_ht = (float) $total_ht;
3413 $this->line->total_tva = (float) $total_tva;
3414 $this->line->total_localtax1 = (float) $total_localtax1;
3415 $this->line->total_localtax2 = (float) $total_localtax2;
3416 $this->line->total_ttc = (float) $total_ttc;
3417 $this->line->product_type = $type;
3418 $this->line->special_code = $oldline->special_code;
3419 $this->line->rang = $oldline->rang;
3420 $this->line->origin = $this->origin;
3421 $this->line->fk_unit = $fk_unit;
3422
3423 $this->line->date_start = $date_start;
3424 $this->line->date_end = $date_end;
3425
3426 // Multicurrency
3427 $this->line->fk_multicurrency = $this->fk_multicurrency;
3428 $this->line->multicurrency_code = $this->multicurrency_code;
3429 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
3430 $this->line->multicurrency_subprice_ttc = (float) $multicurrency_pu_ttc;
3431 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
3432 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
3433 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
3434
3435 $this->line->subprice = (float) $pu_ht;
3436 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
3437 $this->line->price = $this->line->subprice;
3438
3439 $this->line->remise_percent = $remise_percent;
3440
3441 if (is_array($array_options) && count($array_options) > 0) {
3442 // We replace values in this->line->array_options only for entries defined into $array_options
3443 foreach ($array_options as $key => $value) {
3444 $this->line->array_options[$key] = $array_options[$key];
3445 }
3446 }
3447
3448 $result = $this->line->update($notrigger);
3449
3450
3451 // Update denormalized information at the invoice level
3452 if ($result >= 0) {
3453 $this->update_price(1, 'auto');
3454 $this->db->commit();
3455 return $result;
3456 } else {
3457 $this->errors[] = $this->line->error;
3458 $this->errors = array_merge($this->errors, $this->line->errors);
3459 $this->error = $this->db->lasterror();
3460 $this->db->rollback();
3461 return -1;
3462 }
3463 } else {
3464 $this->error = "Order status makes operation forbidden";
3465 dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
3466 return -2;
3467 }
3468 }
3469
3470
3478 public function initAsSpecimen()
3479 {
3480 global $user, $langs, $conf;
3481
3482 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
3483
3484 dol_syslog(get_class($this)."::initAsSpecimen");
3485
3486 $now = dol_now();
3487
3488 // Find first product
3489 $prodid = 0;
3490 $product = new ProductFournisseur($this->db);
3491 $sql = "SELECT rowid";
3492 $sql .= " FROM ".$this->db->prefix()."product";
3493 $sql .= " WHERE entity IN (".getEntity('product').")";
3494 $sql .= $this->db->order("rowid", "ASC");
3495 $sql .= $this->db->plimit(1);
3496 $resql = $this->db->query($sql);
3497 if ($resql && $this->db->num_rows($resql)) {
3498 $obj = $this->db->fetch_object($resql);
3499 $prodid = $obj->rowid;
3500 }
3501
3502 // Initialise parameters
3503 $this->id = 0;
3504 $this->ref = 'SPECIMEN';
3505 $this->specimen = 1;
3506 $this->socid = 1;
3507 $this->date = $now;
3508 $this->date_commande = $now;
3509 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
3510 $this->cond_reglement_code = 'RECEP';
3511 $this->mode_reglement_code = 'CHQ';
3512
3513 $this->note_public = 'This is a comment (public)';
3514 $this->note_private = 'This is a comment (private)';
3515
3516 $this->multicurrency_tx = 1;
3517 $this->multicurrency_code = $conf->currency;
3518
3519 $this->statut = 0; // deprecated
3520 $this->status = 0;
3521
3522 // Lines
3523 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
3524 $xnbp = 0;
3525 while ($xnbp < $nbp) {
3526 $line = new CommandeFournisseurLigne($this->db);
3527 $line->desc = $langs->trans("Description")." ".$xnbp;
3528 $line->qty = 1;
3529 $line->subprice = 100;
3530 $line->tva_tx = 19.6;
3531 $line->localtax1_tx = 0;
3532 $line->localtax2_tx = 0;
3533 if ($xnbp == 2) {
3534 $line->total_ht = 50;
3535 $line->total_ttc = 59.8;
3536 $line->total_tva = 9.8;
3537 $line->remise_percent = 50;
3538 } else {
3539 $line->total_ht = 100;
3540 $line->total_ttc = 119.6;
3541 $line->total_tva = 19.6;
3542 $line->remise_percent = 00;
3543 }
3544 $line->fk_product = $prodid;
3545
3546 $this->lines[$xnbp] = $line;
3547
3548 $this->total_ht += $line->total_ht;
3549 $this->total_tva += $line->total_tva;
3550 $this->total_ttc += $line->total_ttc;
3551
3552 $xnbp++;
3553 }
3554
3555 return 1;
3556 }
3557
3564 public function info($id)
3565 {
3566 $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
3567 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
3568 $sql .= ' FROM '.$this->db->prefix().'commande_fournisseur as c';
3569 $sql .= ' WHERE c.rowid = '.((int) $id);
3570
3571 $result = $this->db->query($sql);
3572 if ($result) {
3573 if ($this->db->num_rows($result)) {
3574 $obj = $this->db->fetch_object($result);
3575
3576 $this->id = $obj->rowid;
3577
3578 $this->user_creation_id = $obj->fk_user_author;
3579 $this->user_validation_id = $obj->fk_user_valid;
3580 $this->user_modification_id = $obj->fk_user_modif;
3581 $this->user_approve_id = $obj->fk_user_approve;
3582 $this->user_approve_id2 = $obj->fk_user_approve2;
3583
3584 $this->date_creation = $this->db->jdate($obj->datec);
3585 $this->date_modification = $this->db->jdate($obj->datem);
3586 $this->date_approve = $this->db->jdate($obj->datea);
3587 $this->date_approve2 = $this->db->jdate($obj->datea2);
3588 $this->date_validation = $this->db->jdate($obj->date_validation);
3589 }
3590 $this->db->free($result);
3591 } else {
3592 dol_print_error($this->db);
3593 }
3594 }
3595
3601 public function loadStateBoard()
3602 {
3603 global $user;
3604
3605 $this->nb = array();
3606 $sanitizedclause = "WHERE";
3607
3608 $sql = "SELECT count(co.rowid) as nb";
3609 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as co";
3610 $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON co.fk_soc = s.rowid";
3611 if (empty($user->socid) && !$user->hasRight("societe", "client", "voir") && !$user->socid) {
3612 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3613 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3614 $sanitizedclause = "AND";
3615 }
3616 $sql .= " ".$sanitizedclause." co.entity IN (".getEntity('supplier_order').")";
3617
3618 $resql = $this->db->query($sql);
3619 if ($resql) {
3620 while ($obj = $this->db->fetch_object($resql)) {
3621 $this->nb["supplier_orders"] = $obj->nb;
3622 }
3623 $this->db->free($resql);
3624 return 1;
3625 } else {
3626 dol_print_error($this->db);
3627 $this->error = $this->db->error();
3628 return -1;
3629 }
3630 }
3631
3632 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3640 public function load_board($user, $mode = 'opened')
3641 {
3642 // phpcs:enable
3643 global $conf, $langs;
3644
3645 $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date, c.total_ht";
3646 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as c";
3647 if (empty($user->socid) && !$user->hasRight("societe", "client", "voir") && !$user->socid) {
3648 $sql .= " JOIN ".$this->db->prefix()."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3649 }
3650 $sql .= " WHERE c.entity = ".((int) $conf->entity);
3651 if ($mode === 'awaiting') {
3652 $sql .= " AND c.fk_statut IN (".self::STATUS_ORDERSENT.", ".self::STATUS_RECEIVED_PARTIALLY.")";
3653 } else {
3654 $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
3655 }
3656 if ($user->socid) {
3657 $sql .= " AND c.fk_soc = ".((int) $user->socid);
3658 }
3659
3660 $resql = $this->db->query($sql);
3661 if ($resql) {
3662 $commandestatic = new CommandeFournisseur($this->db);
3663
3664 $response = new WorkboardResponse();
3665 $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24;
3666 $response->label = $langs->trans("SuppliersOrdersToProcess");
3667 $response->labelShort = $langs->trans("Opened");
3668 $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=1,2&mainmenu=commercial&leftmenu=orders_suppliers';
3669 $response->url_late = DOL_URL_ROOT.'/fourn/commande/list.php?mainmenu=commercial&leftmenu=orders_suppliers&search_option=late';
3670 $response->img = img_object('', "order");
3671
3672 if ($mode === 'awaiting') {
3673 $response->label = $langs->trans("SuppliersOrdersAwaitingReception");
3674 $response->labelShort = $langs->trans("AwaitingReception");
3675 $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=3,4&mainmenu=commercial&leftmenu=orders_suppliers';
3676 $response->url_late = DOL_URL_ROOT.'/fourn/commande/list.php?mainmenu=commercial&leftmenu=orders_suppliers&search_option=recv_late';
3677 }
3678
3679 while ($obj = $this->db->fetch_object($resql)) {
3680 $commandestatic->delivery_date = $this->db->jdate($obj->delivery_date);
3681 $commandestatic->date_commande = $this->db->jdate($obj->date_commande);
3682 $commandestatic->statut = $obj->fk_statut; // deprecated
3683 $commandestatic->status = $obj->fk_statut;
3684
3685 $response->nbtodo++;
3686 $response->total += $obj->total_ht;
3687
3688 if ($commandestatic->hasDelay()) {
3689 $response->nbtodolate++;
3690 }
3691 }
3692
3693 return $response;
3694 } else {
3695 $this->error = $this->db->error();
3696 return -1;
3697 }
3698 }
3699
3706 public function getInputMethod()
3707 {
3708 global $langs;
3709
3710 if ($this->methode_commande_id > 0) {
3711 $sql = "SELECT rowid, code, libelle as label";
3712 $sql .= " FROM ".$this->db->prefix().'c_input_method';
3713 $sql .= " WHERE active=1 AND rowid = ".((int) $this->methode_commande_id);
3714
3715 $resql = $this->db->query($sql);
3716 if ($resql) {
3717 if ($this->db->num_rows($resql)) {
3718 $obj = $this->db->fetch_object($resql);
3719
3720 $string = $langs->trans($obj->code);
3721 if ($string == $obj->code) {
3722 $string = $obj->label != '-' ? $obj->label : '';
3723 }
3724 return $string;
3725 }
3726 } else {
3727 dol_print_error($this->db);
3728 }
3729 }
3730
3731 return '';
3732 }
3733
3745 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3746 {
3747 global $langs;
3748
3749 if (!dol_strlen($modele)) {
3750 $modele = ''; // No doc template/generation by default
3751
3752 if (!empty($this->model_pdf)) {
3753 $modele = $this->model_pdf;
3754 } elseif (getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF')) {
3755 $modele = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF');
3756 }
3757 }
3758
3759 if (empty($modele)) {
3760 return 0;
3761 } else {
3762 $langs->load("suppliers");
3763 $outputlangs->load("products");
3764
3765 $modelpath = "core/modules/supplier_order/doc/";
3766 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3767 return $result;
3768 }
3769 }
3770
3777 public function getMaxDeliveryTimeDay($langs)
3778 {
3779 if (empty($this->lines)) {
3780 return '';
3781 }
3782
3783 $tmpproductfourn = new ProductFournisseur($this->db);
3784
3785 $nb = 0;
3786 foreach ($this->lines as $line) {
3787 if ($line->fk_product > 0) {
3788 // Load delivery_time_days, return id into product_fournisseur_price
3789 $idp = $tmpproductfourn->find_min_price_product_fournisseur($line->fk_product, $line->qty, $this->thirdparty->id);
3790 if ($idp > 0) {
3791 //$tmpproductfourn->fetch_product_fournisseur_price($idp);
3792 if ($tmpproductfourn->delivery_time_days > $nb) {
3793 $nb = $tmpproductfourn->delivery_time_days;
3794 }
3795 }
3796 }
3797 }
3798
3799 if ($nb === 0) {
3800 return '';
3801 } else {
3802 return $nb.' '.$langs->trans('days');
3803 }
3804 }
3805
3813 public function hasUserPermission(User $user, $mode = 'write')
3814 {
3815 if ($mode == 'create') {
3816 $mode = 'write';
3817 }
3818 if (!in_array($mode, array('read', 'write', 'delete'))) {
3819 return false;
3820 }
3821
3822 return (bool) $user->hasRight("fournisseur", "commande", $mode);
3823 }
3824
3825
3834 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3835 {
3836 $tables = array(
3837 'commande_fournisseur'
3838 );
3839
3840 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3841 }
3842
3851 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
3852 {
3853 $tables = array(
3854 'commande_fournisseurdet'
3855 );
3856
3857 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
3858 }
3859
3867 public function hasDelay()
3868 {
3869 global $conf;
3870
3871 if ($this->status == self::STATUS_ORDERSENT || $this->status == self::STATUS_RECEIVED_PARTIALLY) {
3872 $now = dol_now();
3873 if (!empty($this->delivery_date)) {
3874 $date_to_test = $this->delivery_date;
3875 return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3876 } else {
3877 //$date_to_test = $this->date_commande;
3878 //return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3879 return false;
3880 }
3881 } else {
3882 $now = dol_now();
3883 $date_to_test = $this->date_commande;
3884
3885 return ($this->status > 0 && $this->status < 5) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3886 }
3887 }
3888
3896 public function showDelay()
3897 {
3898 global $conf, $langs;
3899
3900 $langs->load('orders');
3901
3902 $text = '';
3903
3904 if ($this->status == self::STATUS_ORDERSENT || $this->status == self::STATUS_RECEIVED_PARTIALLY) {
3905 if (!empty($this->delivery_date)) {
3906 $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
3907 } else {
3908 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3909 }
3910 } else {
3911 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3912 }
3913 if ($text) {
3914 $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3915 }
3916
3917 return $text;
3918 }
3919
3920
3929 public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '')
3930 {
3931 if (isModEnabled("supplier_order")) {
3932 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
3933
3934 $qtydelivered = array();
3935 $qtywished = array();
3936
3937 $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
3938
3939 $filter = array('t.fk_element' => $this->id);
3940 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
3941 $filter['t.status'] = 1; // Restrict to lines with status validated
3942 }
3943
3944 $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
3945 if ($ret < 0) {
3946 $this->error = $supplierorderdispatch->error;
3947 $this->errors = $supplierorderdispatch->errors;
3948 return $ret;
3949 } else {
3950 if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) {
3951 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3952 $date_liv = dol_now();
3953
3954 // Build array with quantity deliverd by product
3955 foreach ($supplierorderdispatch->lines as $line) {
3956 if (array_key_exists($line->fk_product, $qtydelivered)) {
3957 $qtydelivered[$line->fk_product] += $line->qty;
3958 } else {
3959 $qtydelivered[$line->fk_product] = $line->qty;
3960 }
3961 }
3962 foreach ($this->lines as $line) {
3963 // Free lines have no product and cannot be dispatched to stock.
3964 if (empty($line->fk_product)) {
3965 continue;
3966 }
3967 // Exclude lines not qualified for shipment, similar code is found into interface_20_modWrokflow for customers
3968 if ($line->product_type > 0 && (!getDolGlobalString('STOCK_SUPPORTS_SERVICES') || empty($line->stockable_product))) {
3969 continue;
3970 }
3971 if (array_key_exists($line->fk_product, $qtywished)) {
3972 $qtywished[$line->fk_product] += $line->qty;
3973 } else {
3974 $qtywished[$line->fk_product] = $line->qty;
3975 }
3976 }
3977
3978 //Compare array
3979 $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys.
3980 $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys
3981 $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys
3982 //var_dump(array_keys($qtydelivered));
3983 //var_dump(array_keys($qtywished));
3984 //var_dump($diff_array);
3985 //var_dump($keysinwishednotindelivered);
3986 //var_dump($keysindeliverednotinwished);
3987 //exit;
3988
3989 if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) { //No diff => mean everything is received
3990 if ($closeopenorder) {
3991 //$ret=$this->setStatus($user,5);
3992 $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // $type is 'tot', 'par', 'nev', 'can'
3993 if ($ret < 0) {
3994 return -1;
3995 }
3996 return 5;
3997 } else {
3998 //Diff => received partially
3999 //$ret=$this->setStatus($user,4);
4000 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
4001 if ($ret < 0) {
4002 return -1;
4003 }
4004 return 4;
4005 }
4006 } elseif (getDolGlobalString('SUPPLIER_ORDER_MORE_THAN_WISHED')) {
4007 //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...)
4008
4009 $close = 0;
4010
4011 if (count($diff_array) > 0) {
4012 //there are some difference between the two arrays
4013
4014 //scan the array of results
4015 foreach ($diff_array as $key => $value) {
4016 //if the quantity delivered is greater or equal to wish quantity @phan-suppress-next-line PhanTypeInvalidDimOffset
4017 if ($qtydelivered[$key] >= $qtywished[$key]) {
4018 $close++;
4019 }
4020 }
4021 }
4022
4023
4024 if ($close == count($diff_array)) {
4025 //all the products are received equal or more than the wished quantity
4026 if ($closeopenorder) {
4027 $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // $type is 'tot', 'par', 'nev', 'can'
4028 if ($ret < 0) {
4029 return -1;
4030 }
4031 return 5;
4032 } else {
4033 //Diff => received partially
4034 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
4035 if ($ret < 0) {
4036 return -1;
4037 }
4038 return 4;
4039 }
4040 } else {
4041 //all the products are not received
4042 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
4043 if ($ret < 0) {
4044 return -1;
4045 }
4046 return 4;
4047 }
4048 } else {
4049 //Diff => received partially
4050 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
4051 if ($ret < 0) {
4052 return -1;
4053 }
4054 return 4;
4055 }
4056 }
4057 return 1;
4058 }
4059 }
4060 return 0;
4061 }
4062
4070 public function loadReceptions($filtre_statut = -1)
4071 {
4072 $this->receptions = array();
4073
4074 dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG);
4075
4076 $sql = 'SELECT cd.rowid, cd.fk_product,';
4077 $sql .= ' sum(cfd.qty) as qty';
4078 $sql .= ' FROM '.$this->db->prefix().'receptiondet_batch as cfd,';
4079 if ($filtre_statut >= 0) {
4080 $sql .= ' '.$this->db->prefix().'reception as e,';
4081 }
4082 $sql .= ' '.$this->db->prefix().'commande_fournisseurdet as cd';
4083 $sql .= ' WHERE';
4084 if ($filtre_statut >= 0) {
4085 $sql .= ' cfd.fk_reception = e.rowid AND';
4086 }
4087 $sql .= ' cfd.fk_elementdet = cd.rowid';
4088 $sql .= ' AND cd.fk_commande ='.((int) $this->id);
4089 if ($filtre_statut >= 0) {
4090 $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
4091 }
4092 $sql .= ' GROUP BY cd.rowid, cd.fk_product';
4093
4094 $resql = $this->db->query($sql);
4095 if ($resql) {
4096 $num = $this->db->num_rows($resql);
4097 $i = 0;
4098 while ($i < $num) {
4099 $obj = $this->db->fetch_object($resql);
4100 if (empty($this->receptions[$obj->rowid])) {
4101 $this->receptions[$obj->rowid] = (float) $obj->qty;
4102 } else {
4103 $this->receptions[$obj->rowid] += (float) $obj->qty;
4104 }
4105 $i++;
4106 }
4107 $this->db->free($resql);
4108
4109 return $num;
4110 } else {
4111 $this->error = $this->db->lasterror();
4112 return -1;
4113 }
4114 }
4115
4123 public function getKanbanView($option = '', $arraydata = null)
4124 {
4125 global $langs;
4126
4127 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
4128
4129 $return = '<div class="box-flex-item box-flex-grow-zero">';
4130 $return .= '<div class="info-box info-box-sm">';
4131 $return .= '<span class="info-box-icon bg-infobox-action">';
4132 $return .= img_picto('', $this->picto);
4133 $return .= '</span>';
4134 $return .= '<div class="info-box-content">';
4135 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
4136 if ($selected >= 0) {
4137 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
4138 }
4139 if (!empty($arraydata['thirdparty'])) {
4140 $return .= '<br><span class="info-box-label">'.$arraydata['thirdparty'].'</span>';
4141 }
4142 if (!empty($this->date)) {
4143 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date, 'day').'</span>';
4144 }
4145 if (!empty($this->total_ht)) {
4146 $return .= ' &nbsp; <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans("AmountHT")).'">'.price($this->total_ht);
4147 $return .= ' '.$langs->trans("HT");
4148 $return .= '</span>';
4149 }
4150 if (method_exists($this, 'getLibStatut')) {
4151 $return .= '<br><span class="info-box-status">'.$this->getLibStatut(3).'</span>';
4152 }
4153 if (property_exists($this, 'billed')) {
4154 $return .= ' &nbsp; <span class="opacitymedium">'.$langs->trans("Billed").': </span><span class="info-box-label">'.yn($this->billed).'</span>';
4155 }
4156 $return .= '</div>';
4157 $return .= '</div>';
4158 $return .= '</div>';
4159 return $return;
4160 }
4161
4180 public function sendReminderForLateSupplierDeliveries($daysbeforeendlist = '0')
4181 {
4182 global $conf, $langs, $user;
4183
4184 $error = 0;
4185 $this->output = '';
4186 $this->error = '';
4187
4188 $blockingerrormsg = '';
4189
4190 if (!isModEnabled('supplier_order')) { // Should not happen. If module disabled, cron job should not be visible.
4191 $langs->load("agenda");
4192 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("SupplierOrder"));
4193 return 0;
4194 }
4195
4196 $langs->loadLangs(array('main', 'orders'));
4197
4198 $now = dol_now();
4199 $nbok = 0;
4200 $nbko = 0;
4201
4202 $listofordersok = array();
4203 $listofordersko = array();
4204
4205 $arraydaysbeforeend = explode(';', $daysbeforeendlist);
4206 foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
4207 dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG);
4208
4209 if (!is_numeric($daysbeforeend)) {
4210 $blockingerrormsg = "Value for delta is not a numeric value";
4211 $nbko++;
4212 break;
4213 }
4214
4215 // Label of the event recorded once a reminder is sent for a given delay. Also used to not send the same reminder twice the same day.
4216 $labelreminderok = 'sendReminderForLateSupplierDeliveriesOK (daysbeforeend='.$daysbeforeend.')';
4217
4218 $tmp = dol_getdate($now);
4219 $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
4220 $datetosearchforend = dol_time_plus_duree(dol_mktime(23, 59, 59, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
4221
4222 $sql = "SELECT c.rowid";
4223 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
4224 $sql .= " WHERE c.entity = ".((int) $conf->entity); // Do not use getEntity('supplier_order') here, we want the batch to be on its entity only
4225 $sql .= " AND c.fk_statut IN (".self::STATUS_ORDERSENT.", ".self::STATUS_RECEIVED_PARTIALLY.")"; // Sent to supplier or partially received, so still awaiting delivery
4226 $sql .= " AND c.date_livraison >= '".$this->db->idate($datetosearchfor)."'";
4227 $sql .= " AND c.date_livraison <= '".$this->db->idate($datetosearchforend)."'";
4228 $sql .= " AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX."actioncomm as a";
4229 $sql .= " WHERE a.elementtype = 'order_supplier' AND a.fk_element = c.rowid AND a.code = 'AC_EMAIL'";
4230 $sql .= " AND a.label = '".$this->db->escape($labelreminderok)."'";
4231 $sql .= " AND a.datep >= '".$this->db->idate(dol_get_first_hour($now))."')";
4232
4233 $resql = $this->db->query($sql);
4234 if ($resql) {
4235 $num_rows = $this->db->num_rows($resql);
4236
4237 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
4238 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4239 $formmail = new FormMail($this->db);
4240
4241 $i = 0;
4242 while ($i < $num_rows) {
4243 $obj = $this->db->fetch_object($resql);
4244
4245 $orderstatic = new CommandeFournisseur($this->db);
4246 $orderstatic->fetch($obj->rowid);
4247
4248 $recipient = new User($this->db);
4249 $recipientres = (!empty($orderstatic->user_author_id)) ? $recipient->fetch($orderstatic->user_author_id) : -1;
4250
4251 if ($recipientres <= 0 || empty($recipient->email)) {
4252 $nbko++;
4253 $listofordersko[$orderstatic->id] = $orderstatic->id;
4254 } else {
4255 $orderstatic->fetch_thirdparty();
4256
4257 $arraydefaultmessage = null;
4258 $labeltouse = getDolGlobalString('SUPPLIER_ORDER_EMAIL_TEMPLATE_REMIND_LATE_DELIVERY');
4259
4260 if (!empty($labeltouse)) {
4261 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'order_supplier', $user, $langs, 0, 1, $labeltouse);
4262 }
4263
4264 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
4265 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $orderstatic);
4266 complete_substitutions_array($substitutionarray, $langs, $orderstatic);
4267 $substitutionarray['__SUPPLIER_ORDER_DELIVERY_DATE__'] = dol_print_date($orderstatic->delivery_date, 'day', 'tzuserrel', $langs);
4268 $substitutionarray['__SUPPLIER_ORDER_SUPPLIER_NAME__'] = (is_object($orderstatic->thirdparty) ? $orderstatic->thirdparty->name : '');
4269 $substitutionarray['__SUPPLIER_ORDER_URL__'] = DOL_MAIN_URL_ROOT.'/fourn/commande/card.php?id='.$orderstatic->id;
4270
4271 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $langs);
4272 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $langs);
4273 $email_from = getDolGlobalString('SUPPLIER_ORDER_MAIL_FROM', $conf->email_from);
4274 $to = (string) $recipient->email;
4275
4276 $trackid = 'ord'.$orderstatic->id;
4277 $moreinheader = 'X-Dolibarr-Info: sendReminderForLateSupplierDeliveries'."\r\n";
4278
4279 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
4280 $cmail = new CMailFile($subject, $to, $email_from, $msg, array(), array(), array(), '', '', 0, 1, '', '', $trackid, $moreinheader);
4281 $result = $cmail->sendfile();
4282 if (!$result) {
4283 $error++;
4284 $this->error .= $cmail->error.' ';
4285 if (!is_null($cmail->errors)) {
4286 $this->errors = array_merge($this->errors, $cmail->errors);
4287 }
4288 $nbko++;
4289 $listofordersko[$orderstatic->id] = $orderstatic->id;
4290 } else {
4291 $nbok++;
4292 $listofordersok[$orderstatic->id] = $orderstatic->id;
4293
4294 // Insert record of email sent, as an agenda event on the order (same convention as other automated reminder emails)
4295 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
4296
4297 $actioncomm = new ActionComm($this->db);
4298 $actioncomm->type_code = 'AC_OTH_AUTO';
4299 $actioncomm->code = 'AC_EMAIL';
4300 $actioncomm->label = $labelreminderok;
4301 $actioncomm->note_private = $msg;
4302 $actioncomm->fk_project = $orderstatic->fk_project;
4303 $actioncomm->datep = $now;
4304 $actioncomm->datef = $now;
4305 $actioncomm->percentage = -1; // Not applicable
4306 $actioncomm->socid = (is_object($orderstatic->thirdparty) ? $orderstatic->thirdparty->id : 0);
4307 $actioncomm->contact_id = 0;
4308 $actioncomm->authorid = $user->id;
4309 $actioncomm->userownerid = $user->id;
4310 $actioncomm->email_msgid = $cmail->msgid;
4311 $actioncomm->email_from = $email_from;
4312 $actioncomm->email_sender = '';
4313 $actioncomm->email_to = $to;
4314 $actioncomm->email_subject = $subject;
4315
4316 $actioncomm->fk_element = $orderstatic->id;
4317 $actioncomm->elementid = $orderstatic->id;
4318 $actioncomm->elementtype = $orderstatic->element;
4319
4320 $actioncomm->create($user);
4321 }
4322 } else {
4323 $error++;
4324 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
4325
4326 $nbko++;
4327 $listofordersko[$orderstatic->id] = $orderstatic->id;
4328
4329 // Do not break here: a template issue for one order (ex: template not found) must not
4330 // prevent the reminder from being sent for the other orders due the same day.
4331 }
4332 }
4333
4334 $i++;
4335 }
4336 } else {
4337 $this->error = $this->db->lasterror();
4338 return 1;
4339 }
4340 }
4341
4342 if ($blockingerrormsg) {
4343 $this->error = $blockingerrormsg;
4344 return 1;
4345 } else {
4346 $this->output = 'Found '.($nbok + $nbko).' orders to send reminder for.';
4347 $this->output .= ' Sent email successfully for '.$nbok.' orders';
4348 if ($nbko) {
4349 $this->output .= ' - Canceled for '.$nbko.' order(s) (no email for the order author, missing template, or send error)';
4350 }
4351 }
4352
4353 if ($error) {
4354 return 1;
4355 }
4356 return 0;
4357 }
4358}
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
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.
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.
sendReminderForLateSupplierDeliveries($daysbeforeendlist='0')
Send an internal reminder by email when a supplier order's expected delivery date has passed and the ...
const STATUS_RECEIVED_COMPLETELY
Received completely.
cancel($user, $idwarehouse=-1)
Cancel an approved order.
setReopen(User $user)
Reopen supplier order.
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.
updateProductBuyPrices($user)
Save the price of the predefined product lines as supplier price (with its history,...
getTooltipContentArray($params)
getTooltipContentArray
classifyUnBilled(User $user)
Classify not billed.
approve($user, $idwarehouse=0, $secondlevel=0)
Approve a supplier order.
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, $label='')
Add order line.
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.
hasUserPermission(User $user, $mode='write')
Check if user has a permission on supplier orders.
load_board($user, $mode='opened')
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
deleteLine($idline, $notrigger=0)
Delete line.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card before printObjectLines() and formAdd...
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.
setCategories($categories)
Sets object to given categories.
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.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
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.
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 a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_SERVICE
Service.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:686
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
getDolGlobalFloat($key, $default=0)
Return a Dolibarr global constant float value.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492