dolibarr 22.0.5
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-2025 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 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 3 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <https://www.gnu.org/licenses/>.
33 */
34
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
42require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
43require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.orderline.class.php';
44require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
45if (isModEnabled('productbatch')) {
46 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
47}
48
49
54{
58 public $element = 'order_supplier';
59
63 public $table_element = 'commande_fournisseur';
64
68 public $table_element_line = 'commande_fournisseurdet';
69
73 public $class_element_line = 'CommandeFournisseurLigne';
74
78 public $fk_element = 'fk_commande';
79
83 public $picto = 'supplier_order';
84
89 public $restrictiononfksoc = 1;
90
94 protected $table_ref_field = 'ref';
95
99 public $id;
100
104 public $ref;
105
109 public $ref_supplier;
110
116 public $ref_fourn;
117
123 public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process running -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
124 // -> 7=Canceled/Never received -> (reopen) 3=Process running
125 // -> 6=Canceled -> (reopen) 2=Approved
126 // -> 9=Refused -> (reopen) 1=Validated
127 // Note: billed or not is on another field "billed"
128
132 public $billed;
133
137 public $socid;
138
142 public $fourn_id;
143
147 public $date;
148
152 public $date_valid;
153
157 public $date_approve;
158
163 public $date_approve2;
164
168 public $date_commande;
169
174 public $remise_percent;
178 public $methode_commande_id;
182 public $methode_commande;
183
187 public $delivery_date;
188
192 public $total_ht;
193
197 public $total_tva;
198
202 public $total_localtax1;
203
207 public $total_localtax2;
208
212 public $total_ttc;
213
217 public $source;
218
222 public $fk_project;
223
227 public $cond_reglement_id;
228
232 public $cond_reglement_code;
233
237 public $cond_reglement_label;
238
242 public $cond_reglement_doc;
243
247 public $fk_account;
248
252 public $mode_reglement_id;
253
257 public $mode_reglement_code;
258
262 public $mode_reglement;
263
267 public $user_author_id;
268
272 public $user_approve_id;
273
278 public $user_approve_id2;
279
283 public $refuse_note;
284
288 public $extraparams = array();
289
293 public $lines = array();
294
298 public $line;
299
303 public $origin;
307 public $origin_id;
308 public $linked_objects = array();
309
313 public $date_lim_reglement;
317 public $receptions = array();
318
319 // Multicurrency
323 public $fk_multicurrency;
324
328 public $multicurrency_code;
329
333 public $multicurrency_tx;
334
338 public $multicurrency_total_ht;
339
343 public $multicurrency_total_tva;
344
348 public $multicurrency_total_ttc;
349
377 public $fields = array(
378 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 10),
379 'ref' => array('type' => 'varchar(255)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'showoncombobox' => 1, 'position' => 25, 'searchall' => 1),
380 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 35),
381 'ref_supplier' => array('type' => 'varchar(255)', 'label' => 'RefOrderSupplierShort', 'enabled' => 1, 'visible' => 1, 'position' => 40, 'searchall' => 1),
382 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 45),
383 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 710),
384 'date_approve' => array('type' => 'datetime', 'label' => 'DateApprove', 'enabled' => 1, 'visible' => -1, 'position' => 720),
385 'date_approve2' => array('type' => 'datetime', 'label' => 'DateApprove2', 'enabled' => 1, 'visible' => 3, 'position' => 725),
386 'date_commande' => array('type' => 'date', 'label' => 'OrderDateShort', 'enabled' => 1, 'visible' => 1, 'position' => 70),
387 'date_livraison' => array('type' => 'datetime', 'label' => 'DeliveryDate', 'enabled' => 'empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)', 'visible' => 1, 'position' => 74),
388 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => 3, 'position' => 41),
389 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => 3, 'notnull' => -1, 'position' => 80),
390 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => 3, 'position' => 711),
391 'fk_user_approve' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserApproval', 'enabled' => 1, 'visible' => 3, 'position' => 721),
392 'fk_user_approve2' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserApproval2', 'enabled' => 1, 'visible' => 3, 'position' => 726),
393 'source' => array('type' => 'smallint(6)', 'label' => 'Source', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 100),
394 'billed' => array('type' => 'smallint(6)', 'label' => 'Billed', 'enabled' => 1, 'visible' => 1, 'position' => 710),
395 'total_ht' => array('type' => 'double(24,8)', 'label' => 'AmountHT', 'enabled' => 1, 'visible' => 1, 'position' => 130, 'isameasure' => 1),
396 'total_tva' => array('type' => 'double(24,8)', 'label' => 'AmountVAT', 'enabled' => 1, 'visible' => 1, 'position' => 135, 'isameasure' => 1),
397 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LT1', 'enabled' => 1, 'visible' => 3, 'position' => 140, 'isameasure' => 1),
398 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LT2', 'enabled' => 1, 'visible' => 3, 'position' => 145, 'isameasure' => 1),
399 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'AmountTTC', 'enabled' => 1, 'visible' => -1, 'position' => 150, 'isameasure' => 1),
400 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 750, 'searchall' => 1),
401 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 760, 'searchall' => 1),
402 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPDF', 'enabled' => 1, 'visible' => 0, 'position' => 165),
403 'fk_input_method' => array('type' => 'integer', 'label' => 'OrderMode', 'enabled' => 1, 'visible' => 3, 'position' => 170),
404 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => 3, 'position' => 175),
405 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => 3, 'position' => 180),
406 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => 0, 'position' => 190),
407 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => 3, 'position' => 200),
408 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 1, 'visible' => 3, 'position' => 205),
409 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLocation', 'enabled' => 1, 'visible' => 3, 'position' => 210),
410 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => 0, 'position' => 215),
411 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 220),
412 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'CurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 225),
413 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 230),
414 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 235),
415 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
416 'date_creation' => array('type' => 'datetime', 'label' => 'Date creation', 'enabled' => 1, 'visible' => -1, 'position' => 500),
417 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => 1, 'notnull' => 1, 'position' => 50),
418 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 1000, 'index' => 1),
419 'tms' => array('type' => 'datetime', 'label' => "DateModificationShort", 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 501),
420 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => 0, 'position' => 700),
421 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => 1, 'position' => 701),
422 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => 0, 'position' => 900),
423 );
424
425
429 const STATUS_DRAFT = 0;
430
435
440
445
450
455
460
465
469 const STATUS_REFUSED = 9;
470
471
476
482 public function __construct($db)
483 {
484 $this->db = $db;
485
486 $this->ismultientitymanaged = 1;
487 }
488
489
497 public function fetch($id, $ref = '')
498 {
499 // Check parameters
500 if (empty($id) && empty($ref)) {
501 return -1;
502 }
503
504 $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,";
505 $sql .= " c.localtax1, c.localtax2, ";
506 $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
507 $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,";
508 $sql .= " c.date_commande as date_commande, c.date_livraison as delivery_date, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
509 $sql .= " c.fk_account,";
510 $sql .= " c.note_private, c.note_public, c.model_pdf, c.last_main_doc, c.extraparams, c.billed,";
511 $sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
512 $sql .= " cm.libelle as methode_commande,";
513 $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,";
514 $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
515 $sql .= ', c.fk_incoterms, c.location_incoterms';
516 $sql .= ', c.last_main_doc';
517 $sql .= ', i.libelle as label_incoterms';
518 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as c";
519 $sql .= " LEFT JOIN ".$this->db->prefix()."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid";
520 $sql .= " LEFT JOIN ".$this->db->prefix()."c_paiement as p ON c.fk_mode_reglement = p.id";
521 $sql .= " LEFT JOIN ".$this->db->prefix()."c_input_method as cm ON cm.rowid = c.fk_input_method";
522 $sql .= ' LEFT JOIN '.$this->db->prefix().'c_incoterms as i ON c.fk_incoterms = i.rowid';
523
524 if (empty($id)) {
525 $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")";
526 } else {
527 $sql .= " WHERE c.rowid=".((int) $id);
528 }
529
530 if ($ref) {
531 $sql .= " AND c.ref='".$this->db->escape($ref)."'";
532 }
533
534 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
535 $resql = $this->db->query($sql);
536 if ($resql) {
537 $obj = $this->db->fetch_object($resql);
538 if (!$obj) {
539 $this->error = 'Bill with id '.$id.' not found';
540 dol_syslog(get_class($this).'::fetch '.$this->error);
541 return 0;
542 }
543
544 $this->id = $obj->rowid;
545 $this->entity = $obj->entity;
546
547 $this->ref = $obj->ref;
548 $this->ref_supplier = $obj->ref_supplier;
549
550 $this->socid = $obj->fk_soc;
551 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
552
553 $this->fourn_id = $obj->fk_soc;
554 $this->statut = $obj->status; // deprecated
555 $this->status = $obj->status;
556 $this->billed = $obj->billed;
557 $this->last_main_doc = $obj->last_main_doc;
558 $this->user_author_id = $obj->user_author_id;
559 $this->user_validation_id = $obj->user_validation_id;
560 $this->user_approve_id = $obj->user_approve_id;
561 $this->user_approve_id2 = $obj->user_approve_id2;
562 $this->total_ht = $obj->total_ht;
563 $this->total_tva = $obj->total_tva;
564 $this->total_localtax1 = $obj->localtax1;
565 $this->total_localtax2 = $obj->localtax2;
566 $this->total_ttc = $obj->total_ttc;
567 $this->date_creation = $this->db->jdate($obj->date_creation);
568 $this->date_valid = $this->db->jdate($obj->date_valid);
569 $this->date_approve = $this->db->jdate($obj->date_approve);
570 $this->date_approve2 = $this->db->jdate($obj->date_approve2);
571 $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier
572 if (isset($obj->date_commande)) {
573 $this->date = $this->date_commande;
574 } else {
575 $this->date = $this->date_creation;
576 }
577 $this->delivery_date = $this->db->jdate($obj->delivery_date);
578 $this->remise_percent = $obj->remise_percent;
579 $this->methode_commande_id = $obj->fk_input_method;
580 $this->methode_commande = $obj->methode_commande;
581
582 $this->source = $obj->source;
583 $this->fk_project = $obj->fk_project;
584 $this->cond_reglement_id = $obj->fk_cond_reglement;
585 $this->cond_reglement_code = $obj->cond_reglement_code;
586 $this->cond_reglement_label = $obj->cond_reglement_label;
587 $this->cond_reglement_doc = $obj->cond_reglement_doc;
588 $this->fk_account = $obj->fk_account;
589 $this->mode_reglement_id = $obj->fk_mode_reglement;
590 $this->mode_reglement_code = $obj->mode_reglement_code;
591 $this->mode_reglement = $obj->mode_reglement_libelle;
592 $this->note = $obj->note_private; // deprecated
593 $this->note_private = $obj->note_private;
594 $this->note_public = $obj->note_public;
595 $this->model_pdf = $obj->model_pdf;
596 $this->last_main_doc = $obj->last_main_doc;
597
598 //Incoterms
599 $this->fk_incoterms = $obj->fk_incoterms;
600 $this->location_incoterms = $obj->location_incoterms;
601 $this->label_incoterms = $obj->label_incoterms;
602
603 // Multicurrency
604 $this->fk_multicurrency = $obj->fk_multicurrency;
605 $this->multicurrency_code = $obj->multicurrency_code;
606 $this->multicurrency_tx = $obj->multicurrency_tx;
607 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
608 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
609 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
610
611 $this->extraparams = isset($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
612
613 $this->db->free($resql);
614
615 // Retrieve all extrafield
616 // fetch optionals attributes and labels
617 $this->fetch_optionals();
618
619 // Lines
620 $result = $this->fetch_lines();
621
622 if ($result < 0) {
623 return -1;
624 } else {
625 return 1;
626 }
627 } else {
628 $this->error = $this->db->error()." sql=".$sql;
629 return -1;
630 }
631 }
632
633 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
640 public function fetch_lines($only_product = 0)
641 {
642 // phpcs:enable
643
644 $this->lines = array();
645
646 $sql = "SELECT l.rowid, l.fk_commande, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
647 $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
648 $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
649 $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.info_bits, l.special_code, l.fk_parent_line, l.rang,";
650 $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,";
651 $sql .= " l.fk_unit, l.extraparams,";
652 $sql .= " l.date_start, l.date_end,";
653 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
654 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as l";
655 $sql .= ' LEFT JOIN '.$this->db->prefix().'product as p ON l.fk_product = p.rowid';
656 $sql .= " WHERE l.fk_commande = ".((int) $this->id);
657 if ($only_product) {
658 $sql .= ' AND p.fk_product_type = 0';
659 }
660 $sql .= " ORDER BY l.rang, l.rowid";
661 //print $sql;
662
663 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
664
665 $result = $this->db->query($sql);
666 if ($result) {
667 $num = $this->db->num_rows($result);
668 $i = 0;
669
670 while ($i < $num) {
671 $objp = $this->db->fetch_object($result);
672
673 $line = new CommandeFournisseurLigne($this->db);
674
675 $line->id = $objp->rowid;
676 $line->fk_commande = $objp->fk_commande;
677 $line->desc = $objp->description;
678 $line->description = $objp->description;
679 $line->qty = $objp->qty;
680 $line->tva_tx = $objp->tva_tx;
681 $line->localtax1_tx = $objp->localtax1_tx;
682 $line->localtax2_tx = $objp->localtax2_tx;
683 $line->localtax1_type = $objp->localtax1_type;
684 $line->localtax2_type = $objp->localtax2_type;
685 $line->subprice = $objp->subprice;
686 $line->pu_ht = $objp->subprice;
687 $line->remise_percent = $objp->remise_percent;
688
689 $line->vat_src_code = $objp->vat_src_code;
690 $line->total_ht = $objp->total_ht;
691 $line->total_tva = $objp->total_tva;
692 $line->total_localtax1 = $objp->total_localtax1;
693 $line->total_localtax2 = $objp->total_localtax2;
694 $line->total_ttc = $objp->total_ttc;
695 $line->product_type = $objp->product_type;
696
697 $line->fk_product = $objp->fk_product;
698
699 $line->libelle = $objp->product_label; // deprecated
700 $line->product_label = $objp->product_label;
701 $line->product_desc = $objp->product_desc;
702 $line->product_tobatch = $objp->product_tobatch;
703 $line->product_barcode = $objp->product_barcode;
704
705 $line->ref = $objp->product_ref; // Ref of product
706 $line->product_ref = $objp->product_ref; // Ref of product
707 $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
708 $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
709
710 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
711 // TODO We should not fetch this properties into the fetch_lines. This is NOT properties of a line.
712 // Move this into another method and call it when required.
713
714 // Take better packaging for $objp->qty (first supplier ref quantity <= $objp->qty)
715 $sqlsearchpackage = 'SELECT rowid, packaging FROM '.$this->db->prefix()."product_fournisseur_price";
716 $sqlsearchpackage .= ' WHERE entity IN ('.getEntity('product_fournisseur_price').")";
717 $sqlsearchpackage .= " AND fk_product = ".((int) $objp->fk_product);
718 $sqlsearchpackage .= " AND ref_fourn = '".$this->db->escape($objp->ref_supplier)."'";
719 $sqlsearchpackage .= " AND quantity <= ".abs((float) $objp->qty); // required to be qualified
720 $sqlsearchpackage .= " AND (packaging IS NULL OR packaging = 0 OR packaging <= ".abs((float) $objp->qty).")"; // required to be qualified
721 $sqlsearchpackage .= " AND fk_soc = ".((int) $this->socid);
722 $sqlsearchpackage .= " ORDER BY packaging ASC"; // Take the smaller package first
723 $sqlsearchpackage .= " LIMIT 1";
724
725 $resqlsearchpackage = $this->db->query($sqlsearchpackage);
726 if ($resqlsearchpackage) {
727 $objsearchpackage = $this->db->fetch_object($resqlsearchpackage);
728 if ($objsearchpackage) {
729 $line->fk_fournprice = $objsearchpackage->rowid;
730 $line->packaging = (float) $objsearchpackage->packaging;
731 }
732 } else {
733 $this->error = $this->db->lasterror();
734 return -1;
735 }
736 }
737
738 $line->date_start = $this->db->jdate($objp->date_start);
739 $line->date_end = $this->db->jdate($objp->date_end);
740 $line->fk_unit = $objp->fk_unit;
741
742 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
743
744 // Multicurrency
745 $line->fk_multicurrency = $objp->fk_multicurrency;
746 $line->multicurrency_code = $objp->multicurrency_code;
747 $line->multicurrency_subprice = $objp->multicurrency_subprice;
748 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
749 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
750 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
751
752 $line->info_bits = $objp->info_bits;
753 $line->special_code = $objp->special_code;
754 $line->fk_parent_line = $objp->fk_parent_line;
755
756 $line->rang = $objp->rang;
757
758 // Retrieve all extrafield
759 // fetch optionals attributes and labels
760 $line->fetch_optionals();
761
762 $this->lines[$i] = $line;
763
764 $i++;
765 }
766 $this->db->free($result);
767
768 return $num;
769 } else {
770 $this->error = $this->db->error()." sql=".$sql;
771 return -1;
772 }
773 }
774
783 public function valid($user, $idwarehouse = 0, $notrigger = 0)
784 {
785 global $conf;
786 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
787
788 $error = 0;
789
790 dol_syslog(get_class($this)."::valid");
791 $result = 0;
792 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")))
793 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight("fournisseur", "supplier_order_advance", "validate"))) {
794 $this->db->begin();
795
796 // Definition of supplier order numbering model name
797 $soc = new Societe($this->db);
798 $soc->fetch($this->fourn_id);
799
800 // Check if object has a temporary ref
801 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
802 $num = $this->getNextNumRef($soc);
803 } else {
804 $num = $this->ref;
805 }
806 $this->newref = dol_sanitizeFileName($num);
807
808 $sql = 'UPDATE '.$this->db->prefix()."commande_fournisseur";
809 $sql .= " SET ref='".$this->db->escape($num)."',";
810 $sql .= " fk_statut = ".((int) self::STATUS_VALIDATED).",";
811 $sql .= " date_valid='".$this->db->idate(dol_now())."',";
812 $sql .= " fk_user_valid = ".((int) $user->id);
813 $sql .= " WHERE rowid = ".((int) $this->id);
814 $sql .= " AND fk_statut = ".((int) self::STATUS_DRAFT);
815
816 $resql = $this->db->query($sql);
817 if (!$resql) {
818 dol_print_error($this->db);
819 $error++;
820 }
821
822 if (!$error && !$notrigger) {
823 // Call trigger
824 $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user);
825 if ($result < 0) {
826 $error++;
827 }
828 // End call triggers
829 }
830
831 if (!$error) {
832 $this->oldref = $this->ref;
833
834 // Rename directory if dir was a temporary ref
835 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
836 // Now we rename also files into index
837 $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)."'";
838 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
839 $resql = $this->db->query($sql);
840 if (!$resql) {
841 $error++;
842 $this->error = $this->db->lasterror();
843 }
844 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
845 $sql .= " WHERE filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
846 $resql = $this->db->query($sql);
847 if (!$resql) {
848 $error++;
849 $this->error = $this->db->lasterror();
850 }
851
852 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
853 $oldref = dol_sanitizeFileName($this->ref);
854 $newref = dol_sanitizeFileName($num);
855 $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref;
856 $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
857 if (!$error && file_exists($dirsource)) {
858 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
859
860 if (@rename($dirsource, $dirdest)) {
861 dol_syslog("Rename ok");
862 // Rename docs starting with $oldref with $newref
863 $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
864 foreach ($listoffiles as $fileentry) {
865 $dirsource = $fileentry['name'];
866 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
867 $dirsource = $fileentry['path'].'/'.$dirsource;
868 $dirdest = $fileentry['path'].'/'.$dirdest;
869 @rename($dirsource, $dirdest);
870 }
871 }
872 }
873 }
874 }
875
876 if (!$error) {
877 $result = 1;
879 $this->statut = self::STATUS_VALIDATED; // deprecated
880 $this->ref = $num;
881 }
882
883 if (!$error) {
884 $this->db->commit();
885 return 1;
886 } else {
887 $this->db->rollback();
888 return -1;
889 }
890 } else {
891 $this->error = 'NotAuthorized';
892 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
893 return -1;
894 }
895 }
896
903 public function getLibStatut($mode = 0)
904 {
905 return $this->LibStatut(isset($this->status) ? $this->status : $this->statut, $mode, $this->billed);
906 }
907
908 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
917 public function LibStatut($status, $mode = 0, $billed = 0)
918 {
919 // phpcs:enable
920 global $langs, $hookmanager;
921
922 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
923 $langs->load('orders');
924
925 $this->labelStatus[0] = 'StatusSupplierOrderDraft';
926 $this->labelStatus[1] = 'StatusSupplierOrderValidated';
927 $this->labelStatus[2] = 'StatusSupplierOrderApproved';
928 if (!getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
929 $this->labelStatus[3] = 'StatusSupplierOrderOnProcess';
930 } else {
931 $this->labelStatus[3] = 'StatusSupplierOrderOnProcessWithValidation';
932 }
933 $this->labelStatus[4] = 'StatusSupplierOrderReceivedPartially';
934 $this->labelStatus[5] = 'StatusSupplierOrderReceivedAll';
935 $this->labelStatus[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled
936 $this->labelStatus[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled
937 $this->labelStatus[9] = 'StatusSupplierOrderRefused';
938
939 // List of language codes for status
940 $this->labelStatusShort[0] = 'StatusSupplierOrderDraftShort';
941 $this->labelStatusShort[1] = 'StatusSupplierOrderValidatedShort';
942 $this->labelStatusShort[2] = 'StatusSupplierOrderApprovedShort';
943 $this->labelStatusShort[3] = 'StatusSupplierOrderOnProcessShort';
944 $this->labelStatusShort[4] = 'StatusSupplierOrderReceivedPartiallyShort';
945 $this->labelStatusShort[5] = 'StatusSupplierOrderReceivedAllShort';
946 $this->labelStatusShort[6] = 'StatusSupplierOrderCanceledShort';
947 $this->labelStatusShort[7] = 'StatusSupplierOrderCanceledShort';
948 $this->labelStatusShort[9] = 'StatusSupplierOrderRefusedShort';
949 }
950
951 $statustrans = array(
952 0 => 'status0',
953 1 => 'status1b',
954 2 => 'status1',
955 3 => 'status4',
956 4 => 'status4b',
957 5 => 'status6',
958 6 => 'status9',
959 7 => 'status9',
960 9 => 'status9',
961 );
962
963 $statusClass = 'status0';
964 if (!empty($statustrans[$status])) {
965 $statusClass = $statustrans[$status];
966 }
967
968 $billedtext = '';
969 if ($billed) {
970 $billedtext = ' - '.$langs->trans("Billed");
971 }
972 if ($status == 5 && $billed) {
973 $statusClass = 'status6';
974 }
975
976 $statusLong = $langs->transnoentitiesnoconv($this->labelStatus[$status]).$billedtext;
977 $statusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
978
979 $parameters = array('status' => $status, 'mode' => $mode, 'billed' => $billed);
980 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
981 if ($reshook > 0) {
982 return $hookmanager->resPrint;
983 }
984
985 return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode);
986 }
987
994 public function getTooltipContentArray($params)
995 {
996 global $conf, $langs, $user;
997
998 $langs->loadLangs(['bills', 'orders']);
999
1000 $datas = [];
1001 $nofetch = !empty($params['nofetch']);
1002
1003 if ($user->hasRight("fournisseur", "commande", "read")) {
1004 $datas['picto'] = '<u class="paddingrightonly">'.$langs->trans("SupplierOrder").'</u>';
1005 if ($this->status) {
1006 $datas['picto'] .= ' '.$this->getLibStatut(5);
1007 }
1008 if (!empty($this->ref)) {
1009 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1010 }
1011 if (!empty($this->ref_supplier)) {
1012 $datas['refsupplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
1013 }
1014 if (!$nofetch) {
1015 $langs->load('companies');
1016 if (empty($this->thirdparty)) {
1017 $this->fetch_thirdparty();
1018 }
1019 $datas['supplier'] = '<br><b>'.$langs->trans('Supplier').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
1020 }
1021 if (!empty($this->total_ht)) {
1022 $datas['totalht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1023 }
1024 if (!empty($this->total_tva)) {
1025 $datas['totaltva'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1026 }
1027 if (!empty($this->total_ttc)) {
1028 $datas['totalttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1029 }
1030 if (!empty($this->date)) {
1031 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
1032 }
1033 if (!empty($this->delivery_date)) {
1034 $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
1035 }
1036 }
1037 return $datas;
1038 }
1039
1050 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
1051 {
1052 global $langs, $user, $hookmanager;
1053
1054 $result = '';
1055 $params = [
1056 'id' => $this->id,
1057 'objecttype' => $this->element,
1058 'option' => $option,
1059 'nofetch' => 1
1060 ];
1061 $classfortooltip = 'classfortooltip';
1062 $dataparams = '';
1063 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1064 $classfortooltip = 'classforajaxtooltip';
1065 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1066 $label = '';
1067 } else {
1068 $label = implode($this->getTooltipContentArray($params));
1069 }
1070
1071 $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
1072
1073 if ($option !== 'nolink') {
1074 // Add param to save lastsearch_values or not
1075 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1076 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1077 $add_save_lastsearch_values = 1;
1078 }
1079 if ($add_save_lastsearch_values) {
1080 $url .= '&save_lastsearch_values=1';
1081 }
1082 }
1083
1084 $linkclose = '';
1085 if (empty($notooltip)) {
1086 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1087 $label = $langs->trans("ShowOrder");
1088 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1089 }
1090 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1091 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
1092 }
1093
1094 $linkstart = '<a href="'.$url.'"';
1095 $linkstart .= $linkclose.'>';
1096 $linkend = '</a>';
1097
1098 $result .= $linkstart;
1099 if ($withpicto) {
1100 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1101 }
1102 if ($withpicto != 2) {
1103 $result .= $this->ref;
1104 }
1105 $result .= $linkend;
1106
1107 if ($addlinktonotes) {
1108 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1109 if ($txttoshow) {
1110 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1111 $result .= ' <span class="note inline-block">';
1112 $result .= '<a href="'.DOL_URL_ROOT.'/fourn/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
1113 $result .= img_picto('', 'note');
1114 $result .= '</a>';
1115 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
1116 //$result.='</a>';
1117 $result .= '</span>';
1118 }
1119 }
1120
1121 global $action;
1122 $hookmanager->initHooks(array($this->element . 'dao'));
1123 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1124 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1125 if ($reshook > 0) {
1126 $result = $hookmanager->resPrint;
1127 } else {
1128 $result .= $hookmanager->resPrint;
1129 }
1130 return $result;
1131 }
1132
1133
1141 public function getNextNumRef($soc)
1142 {
1143 global $langs, $conf;
1144 $langs->load("orders");
1145
1146 if (getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER')) {
1147 $mybool = false;
1148
1149 $file = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER').'.php';
1150 $classname = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_NUMBER');
1151
1152 // Include file with class
1153 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1154
1155 foreach ($dirmodels as $reldir) {
1156 $dir = dol_buildpath($reldir."core/modules/supplier_order/");
1157
1158 // Load file with numbering class (if found)
1159 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1160 }
1161
1162 if (!$mybool) {
1163 dol_print_error(null, "Failed to include file ".$file);
1164 return '';
1165 }
1166
1167 $obj = new $classname();
1168 '@phan-var-force ModeleNumRefSuppliersOrders $obj';
1170 $numref = $obj->getNextValue($soc, $this);
1171
1172 if ($numref != "") {
1173 return $numref;
1174 } else {
1175 $this->error = $obj->error;
1176 return -1;
1177 }
1178 } else {
1179 $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
1180 return -2;
1181 }
1182 }
1183
1190 public function classifyBilled(User $user)
1191 {
1192 $error = 0;
1193
1194 if ($this->billed) {
1195 return 0;
1196 }
1197
1198 $this->db->begin();
1199
1200 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur SET billed = 1';
1201 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
1202
1203 if ($this->db->query($sql)) {
1204 if (!$error) {
1205 // Call trigger
1206 $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
1207 if ($result < 0) {
1208 $error++;
1209 }
1210 // End call triggers
1211 }
1212
1213 if (!$error) {
1214 $this->billed = 1;
1215
1216 $this->db->commit();
1217 return 1;
1218 } else {
1219 $this->db->rollback();
1220 return -1;
1221 }
1222 } else {
1223 dol_print_error($this->db);
1224
1225 $this->db->rollback();
1226 return -1;
1227 }
1228 }
1229
1230
1237 public function classifyUnBilled(User $user)
1238 {
1239 if (empty($this->billed)) {
1240 return 0;
1241 }
1242
1243 $this->db->begin();
1244
1245 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur SET billed = 0';
1246 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
1247 ;
1248
1249 if (!$this->db->query($sql)) {
1250 dol_print_error($this->db);
1251 $this->db->rollback();
1252 return -1;
1253 }
1254
1255 // Call trigger
1256 $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_UNBILLED', $user);
1257 if ($result < 0) {
1258 $this->db->rollback();
1259 return -1;
1260 }
1261 // End call triggers
1262
1263 $this->billed = 1;
1264 $this->db->commit();
1265 return 1;
1266 }
1267
1268
1277 public function approve($user, $idwarehouse = 0, $secondlevel = 0)
1278 {
1279 global $langs, $conf;
1280 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1281
1282 $error = 0;
1283
1284 dol_syslog(get_class($this)."::approve");
1285
1286 if ($user->hasRight("fournisseur", "commande", "approuver")) {
1287 $now = dol_now();
1288
1289 $this->db->begin();
1290
1291 // Definition of order numbering model name
1292 $soc = new Societe($this->db);
1293 $soc->fetch($this->fourn_id);
1294
1295 // Check if object has a temporary ref
1296 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1297 $num = $this->getNextNumRef($soc);
1298 } else {
1299 $num = $this->ref;
1300 }
1301 $this->newref = dol_sanitizeFileName($num);
1302
1303 // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
1304 $movetoapprovestatus = true;
1305 $comment = '';
1306
1307 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1308 $sql .= " SET ref='".$this->db->escape($num)."',";
1309 if (empty($secondlevel)) { // standard or first level approval
1310 $sql .= " date_approve='".$this->db->idate($now)."',";
1311 $sql .= " fk_user_approve = ".((int) $user->id);
1312 if (getDolGlobalString('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED') && $this->total_ht >= getDolGlobalFloat('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED')) {
1313 if (empty($this->user_approve_id2)) {
1314 $movetoapprovestatus = false; // second level approval not done
1315 $comment = ' (first level)';
1316 }
1317 }
1318 } else { // request a second level approval
1319 $sql .= " date_approve2='".$this->db->idate($now)."',";
1320 $sql .= " fk_user_approve2 = ".((int) $user->id);
1321 if (empty($this->user_approve_id)) {
1322 $movetoapprovestatus = false; // first level approval not done
1323 }
1324 $comment = ' (second level)';
1325 }
1326 // If double approval is required and first approval, we keep status to 1 = validated
1327 if ($movetoapprovestatus) {
1328 $sql .= ", fk_statut = ".self::STATUS_ACCEPTED;
1329 } else {
1330 $sql .= ", fk_statut = ".self::STATUS_VALIDATED;
1331 }
1332 $sql .= " WHERE rowid = ".((int) $this->id);
1333 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1334
1335 if ($this->db->query($sql)) {
1336 if (getDolGlobalString('SUPPLIER_ORDER_AUTOADD_USER_CONTACT')) {
1337 $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
1338 if ($result < 0 && $result != -2) { // -2 means already exists
1339 $error++;
1340 }
1341 }
1342
1343 // If stock is incremented on validate order, we must increment it
1344 if (!$error && $movetoapprovestatus && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER')) {
1345 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1346 $langs->load("agenda");
1347
1348 $cpt = count($this->lines);
1349 for ($i = 0; $i < $cpt; $i++) {
1350 // Product with reference
1351 if ($this->lines[$i]->fk_product > 0) {
1352 $this->line = $this->lines[$i];
1353 $mouvP = new MouvementStock($this->db);
1354 $mouvP->origin = &$this;
1355 $mouvP->setOrigin($this->element, $this->id);
1356 // We decrement stock of product (and sub-products)
1357 $up_ht_disc = $this->lines[$i]->subprice;
1358 if (!empty($this->lines[$i]->remise_percent) && !getDolGlobalString('STOCK_EXCLUDE_DISCOUNT_FOR_PMP')) {
1359 $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1360 }
1361 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref));
1362 if ($result < 0) {
1363 $error++;
1364 }
1365 unset($this->line);
1366 }
1367 }
1368 }
1369
1370 if (!$error) {
1371 // Call trigger
1372 $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user);
1373 if ($result < 0) {
1374 $error++;
1375 }
1376 // End call triggers
1377 }
1378
1379 if (!$error) {
1380 $this->ref = $this->newref;
1381
1382 if ($movetoapprovestatus) {
1383 $this->statut = self::STATUS_ACCEPTED; // deprecated
1385 } else {
1386 $this->statut = self::STATUS_VALIDATED; // deprecated
1388 }
1389 if (empty($secondlevel)) { // standard or first level approval
1390 $this->date_approve = $now;
1391 $this->user_approve_id = $user->id;
1392 } else { // request a second level approval
1393 $this->date_approve2 = $now;
1394 $this->user_approve_id2 = $user->id;
1395 }
1396
1397 $this->db->commit();
1398 return 1;
1399 } else {
1400 $this->db->rollback();
1401 return -1;
1402 }
1403 } else {
1404 $this->db->rollback();
1405 $this->error = $this->db->lasterror();
1406 return -1;
1407 }
1408 } else {
1409 dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
1410 }
1411 return -1;
1412 }
1413
1420 public function refuse($user)
1421 {
1422 global $conf, $langs;
1423
1424 $error = 0;
1425
1426 dol_syslog(get_class($this)."::refuse");
1427 $result = 0;
1428 if ($user->hasRight("fournisseur", "commande", "approuver")) {
1429 $this->db->begin();
1430
1431 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
1432 $sql .= " WHERE rowid = ".((int) $this->id);
1433
1434 if ($this->db->query($sql)) {
1435 $result = 0;
1436
1437 if ($error == 0) {
1438 // Call trigger
1439 $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user);
1440 if ($result < 0) {
1441 $error++;
1442 $this->db->rollback();
1443 } else {
1444 $this->db->commit();
1445 }
1446 // End call triggers
1447 }
1448 } else {
1449 $this->db->rollback();
1450 $this->error = $this->db->lasterror();
1451 dol_syslog(get_class($this)."::refuse Error -1");
1452 $result = -1;
1453 }
1454 } else {
1455 dol_syslog(get_class($this)."::refuse Not Authorized");
1456 }
1457 return $result;
1458 }
1459
1460 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1469 public function Cancel($user, $idwarehouse = -1)
1470 {
1471 // phpcs:enable
1472 global $langs, $conf;
1473
1474 $error = 0;
1475
1476 //dol_syslog("CommandeFournisseur::Cancel");
1477 $result = 0;
1478 if ($user->hasRight("fournisseur", "commande", "commander")) {
1479 $statut = self::STATUS_CANCELED;
1480
1481 $this->db->begin();
1482
1483 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur SET fk_statut = ".((int) $statut);
1484 $sql .= " WHERE rowid = ".((int) $this->id);
1485 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
1486 if ($this->db->query($sql)) {
1487 $result = 0;
1488
1489 // Call trigger
1490 $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user);
1491 if ($result < 0) {
1492 $error++;
1493 }
1494 // End call triggers
1495
1496 if ($error == 0) {
1497 $this->db->commit();
1498 return 1;
1499 } else {
1500 $this->db->rollback();
1501 return -1;
1502 }
1503 } else {
1504 $this->db->rollback();
1505 $this->error = $this->db->lasterror();
1506 dol_syslog(get_class($this)."::cancel ".$this->error);
1507 return -1;
1508 }
1509 } else {
1510 dol_syslog(get_class($this)."::cancel Not Authorized");
1511 return -1;
1512 }
1513 }
1514
1524 public function commande($user, $date, $methode, $comment = '')
1525 {
1526 global $langs;
1527 dol_syslog(get_class($this)."::commande");
1528 $error = 0;
1529 if ($user->hasRight("fournisseur", "commande", "commander")) {
1530 $this->db->begin();
1531
1532 $newnoteprivate = $this->note_private;
1533 if ($comment) {
1534 $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment);
1535 }
1536
1537 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1538 $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', ";
1539 $sql .= " note_private='".$this->db->escape((string) $newnoteprivate)."'";
1540 $sql .= " WHERE rowid=".((int) $this->id);
1541
1542 dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1543 if ($this->db->query($sql)) {
1544 $this->statut = self::STATUS_ORDERSENT; // deprecated
1546 $this->methode_commande_id = $methode;
1547 $this->date_commande = $date;
1548 $this->context['comments'] = $comment;
1549
1550 // Call trigger
1551 $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
1552 if ($result < 0) {
1553 $error++;
1554 }
1555 // End call triggers
1556 } else {
1557 $error++;
1558 $this->error = $this->db->lasterror();
1559 $this->errors[] = $this->db->lasterror();
1560 }
1561
1562 if (!$error) {
1563 $this->db->commit();
1564 } else {
1565 $this->db->rollback();
1566 }
1567 } else {
1568 $error++;
1569 $this->error = $langs->trans('NotAuthorized');
1570 $this->errors[] = $langs->trans('NotAuthorized');
1571 dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1572 }
1573
1574 return ($error ? -1 : 1);
1575 }
1576
1584 public function create($user, $notrigger = 0)
1585 {
1586 global $langs, $conf, $hookmanager;
1587
1588 $this->db->begin();
1589
1590 $error = 0;
1591 $now = dol_now();
1592
1593 // set tmp vars
1594 $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set
1595 if (empty($date)) {
1596 $date = $now;
1597 }
1598 $delivery_date = $this->delivery_date;
1599
1600 // Clean parameters
1601 if (empty($this->source)) {
1602 $this->source = 0;
1603 }
1604
1605 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1606 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1607 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
1608 } else {
1609 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1610 }
1611 if (empty($this->fk_multicurrency)) {
1612 $this->multicurrency_code = $conf->currency;
1613 $this->fk_multicurrency = 0;
1614 $this->multicurrency_tx = 1;
1615 }
1616 $this->entity = setEntity($this);
1617
1618 // We set order into draft status
1619 $this->statut = self::STATUS_DRAFT; // deprecated
1620 $this->status = self::STATUS_DRAFT;
1621
1622 $sql = "INSERT INTO ".$this->db->prefix()."commande_fournisseur (";
1623 $sql .= "ref";
1624 $sql .= ", ref_supplier";
1625 $sql .= ", note_private";
1626 $sql .= ", note_public";
1627 $sql .= ", entity";
1628 $sql .= ", fk_soc";
1629 $sql .= ", fk_projet";
1630 $sql .= ", date_creation";
1631 $sql .= ", date_livraison";
1632 $sql .= ", fk_user_author";
1633 $sql .= ", fk_statut";
1634 $sql .= ", source";
1635 $sql .= ", model_pdf";
1636 $sql .= ", fk_mode_reglement";
1637 $sql .= ", fk_cond_reglement";
1638 $sql .= ", fk_account";
1639 $sql .= ", fk_incoterms, location_incoterms";
1640 $sql .= ", fk_multicurrency";
1641 $sql .= ", multicurrency_code";
1642 $sql .= ", multicurrency_tx";
1643 $sql .= ") ";
1644 $sql .= " VALUES (";
1645 $sql .= "'(PROV)'";
1646 $sql .= ", ".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "NULL");
1647 $sql .= ", '".$this->db->escape($this->note_private)."'";
1648 $sql .= ", '".$this->db->escape($this->note_public)."'";
1649 $sql .= ", ".((int) $this->entity);
1650 $sql .= ", ".((int) $this->socid);
1651 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1652 $sql .= ", '".$this->db->idate($date)."'";
1653 $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1654 $sql .= ", ".((int) $user->id);
1655 $sql .= ", ".self::STATUS_DRAFT;
1656 $sql .= ", ".((int) $this->source);
1657 $sql .= ", '".$this->db->escape(getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF'))."'";
1658 $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1659 $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1660 $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
1661 $sql .= ", ".(int) $this->fk_incoterms;
1662 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1663 $sql .= ", ".(int) $this->fk_multicurrency;
1664 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1665 $sql .= ", ".(float) $this->multicurrency_tx;
1666 $sql .= ")";
1667
1668 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1669 if ($this->db->query($sql)) {
1670 $this->id = $this->db->last_insert_id($this->db->prefix()."commande_fournisseur");
1671
1672 if ($this->id) {
1673 $num = count($this->lines);
1674
1675 // insert products details into database
1676 for ($i = 0; $i < $num; $i++) {
1677 $line = $this->lines[$i];
1678 if (!is_object($line)) {
1679 $line = (object) $line;
1680 }
1681
1682 //$this->special_code = $line->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
1683
1684 // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1685 $result = $this->addline(
1686 $line->desc,
1687 $line->subprice,
1688 $line->qty,
1689 $line->tva_tx,
1690 $line->localtax1_tx ?? 0.0,
1691 $line->localtax2_tx ?? 0.0,
1692 $line->fk_product,
1693 0,
1694 $line->ref_fourn ?? '', // $line->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1695 $line->remise_percent,
1696 'HT',
1697 0,
1698 $line->product_type,
1699 $line->info_bits ?? 0,
1700 0,
1701 $line->date_start ?? null,
1702 $line->date_end ?? null,
1703 $line->array_options ?? [],
1704 $line->fk_unit ?? null,
1705 $line->multicurrency_subprice ?? 0, // pu_ht_devise
1706 $line->origin ?? '', // origin
1707 $line->origin_id ?? 0, // origin_id
1708 $line->rang ?? -1, // rang
1709 $line->special_code ?? 0
1710 );
1711 if ($result < 0) {
1712 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functional error
1713 $this->db->rollback();
1714 return -1;
1715 }
1716 }
1717
1718 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
1719 $sql .= " SET ref='(PROV".$this->id.")'";
1720 $sql .= " WHERE rowid=".((int) $this->id);
1721
1722 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1723 if ($this->db->query($sql)) {
1724 // Add link with price request and supplier order
1725 if ($this->id) {
1726 $this->ref = "(PROV".$this->id.")";
1727
1728 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1729 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1730 }
1731
1732 // Add object linked
1733 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1734 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1735 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, ...))
1736 foreach ($tmp_origin_id as $origin_id) {
1737 $ret = $this->add_object_linked($origin, $origin_id);
1738 if (!$ret) {
1739 dol_print_error($this->db);
1740 $error++;
1741 }
1742 }
1743 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1744 $origin_id = $tmp_origin_id;
1745 $ret = $this->add_object_linked($origin, $origin_id);
1746 if (!$ret) {
1747 dol_print_error($this->db);
1748 $error++;
1749 }
1750 }
1751 }
1752 }
1753 }
1754
1755 if (!$error) {
1756 $result = $this->insertExtraFields();
1757 if ($result < 0) {
1758 $error++;
1759 }
1760 }
1761
1762 if (!$error && !$notrigger) {
1763 // Call trigger
1764 $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user);
1765 if ($result < 0) {
1766 $this->db->rollback();
1767
1768 return -1;
1769 }
1770 // End call triggers
1771 }
1772
1773 $this->db->commit();
1774 return $this->id;
1775 } else {
1776 $this->error = $this->db->lasterror();
1777 $this->db->rollback();
1778
1779 return -2;
1780 }
1781 } else {
1782 $this->error = 'Failed to get ID of inserted line';
1783
1784 return -1;
1785 }
1786 } else {
1787 $this->error = $this->db->lasterror();
1788 $this->db->rollback();
1789
1790 return -1;
1791 }
1792 }
1793
1801 public function update(User $user, $notrigger = 0)
1802 {
1803 global $conf;
1804
1805 $error = 0;
1806
1807 // Clean parameters
1808 if (isset($this->ref)) {
1809 $this->ref = trim($this->ref);
1810 }
1811 if (isset($this->ref_supplier)) {
1812 $this->ref_supplier = trim($this->ref_supplier);
1813 }
1814 if (isset($this->note_private)) {
1815 $this->note_private = trim($this->note_private);
1816 }
1817 if (isset($this->note_public)) {
1818 $this->note_public = trim($this->note_public);
1819 }
1820 if (isset($this->model_pdf)) {
1821 $this->model_pdf = trim($this->model_pdf);
1822 }
1823 if (isset($this->import_key)) {
1824 $this->import_key = trim($this->import_key);
1825 }
1826
1827 // Update request
1828 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET";
1829
1830 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1831 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1832 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1833 $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
1834 $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
1835 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1836 $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
1837 $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
1838 $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
1839 $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
1840 $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
1841 $sql .= " fk_statut=".(isset($this->status) ? $this->status : "null").",";
1842 $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
1843 $sql .= " fk_user_valid=".(isset($this->user_validation_id) && $this->user_validation_id > 0 ? $this->user_validation_id : "null").",";
1844 $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
1845 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
1846 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
1847 $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
1848 //$sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").",";
1849 $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").",";
1850 //$sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").",";
1851 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1852 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1853 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1854 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1855
1856 $sql .= " WHERE rowid=".((int) $this->id);
1857
1858 $this->db->begin();
1859
1860 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1861 $resql = $this->db->query($sql);
1862 if (!$resql) {
1863 $error++;
1864 $this->errors[] = "Error ".$this->db->lasterror();
1865 }
1866
1867 if (!$error) {
1868 $result = $this->insertExtraFields();
1869 if ($result < 0) {
1870 $error++;
1871 }
1872 }
1873
1874 if (!$error && !$notrigger) {
1875 // Call trigger
1876 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
1877 if ($result < 0) {
1878 $error++;
1879 }
1880 // End call triggers
1881 }
1882
1883 // Commit or rollback
1884 if ($error) {
1885 foreach ($this->errors as $errmsg) {
1886 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1887 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1888 }
1889 $this->db->rollback();
1890 return -1 * $error;
1891 } else {
1892 $this->db->commit();
1893 return 1;
1894 }
1895 }
1896
1905 public function createFromClone(User $user, $socid = 0, $notrigger = 0)
1906 {
1907 global $conf, $user, $hookmanager;
1908
1909 $error = 0;
1910
1911 $this->db->begin();
1912
1913 // get extrafields so they will be clone
1914 foreach ($this->lines as $line) {
1915 $line->fetch_optionals();
1916 }
1917
1918 // Load source object
1919 $objFrom = clone $this;
1920
1921 // Change socid if needed
1922 if (!empty($socid) && $socid != $this->socid) {
1923 $objsoc = new Societe($this->db);
1924
1925 if ($objsoc->fetch($socid) > 0) {
1926 $this->socid = $objsoc->id;
1927 $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1928 $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1929 $this->fk_project = 0;
1930 $this->fk_delivery_address = 0;
1931 }
1932
1933 // TODO Change product price if multi-prices
1934 }
1935
1936 $this->id = 0;
1937 $this->statut = self::STATUS_DRAFT; // deprecated
1938 $this->status = self::STATUS_DRAFT;
1939
1940 // Clear fields
1941 $this->user_author_id = $user->id;
1942 $this->user_validation_id = 0;
1943
1944 $this->date = dol_now();
1945 $this->date_creation = 0;
1946 $this->date_validation = 0;
1947 $this->date_commande = null;
1948 $this->ref_supplier = '';
1949 $this->user_approve_id = 0;
1950 $this->user_approve_id2 = 0;
1951 $this->date_approve = 0;
1952 $this->date_approve2 = 0;
1953
1954 // Create clone
1955 $this->context['createfromclone'] = 'createfromclone';
1956 $result = $this->create($user, $notrigger);
1957 if ($result < 0) {
1958 $error++;
1959 }
1960
1961 if (!$error) {
1962 // Hook of thirdparty module
1963 if (is_object($hookmanager)) {
1964 $parameters = array('objFrom' => $objFrom);
1965 $action = '';
1966 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1967 if ($reshook < 0) {
1968 $this->setErrorsFromObject($hookmanager);
1969 $error++;
1970 }
1971 }
1972 }
1973
1974 unset($this->context['createfromclone']);
1975
1976 // End
1977 if (!$error) {
1978 $this->db->commit();
1979 return $this->id;
1980 } else {
1981 $this->db->rollback();
1982 return -1;
1983 }
1984 }
1985
2015 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)
2016 {
2017 global $langs, $mysoc;
2018
2019 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");
2020 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2021
2022 if ($this->status == self::STATUS_DRAFT) {
2023 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2024
2025 // Clean parameters
2026 if (empty($qty)) {
2027 $qty = 0;
2028 }
2029 if (!$info_bits) {
2030 $info_bits = 0;
2031 }
2032 if (empty($txtva)) {
2033 $txtva = 0;
2034 }
2035 if (empty($rang)) {
2036 $rang = 0;
2037 }
2038 if (empty($txlocaltax1)) {
2039 $txlocaltax1 = 0;
2040 }
2041 if (empty($txlocaltax2)) {
2042 $txlocaltax2 = 0;
2043 }
2044 if (empty($remise_percent)) {
2045 $remise_percent = 0;
2046 }
2047
2048 $remise_percent = price2num($remise_percent);
2049 $qty = price2num($qty);
2050 $pu_ht = price2num($pu_ht);
2051 $pu_ht_devise = price2num($pu_ht_devise);
2052 $pu_ttc = price2num($pu_ttc);
2053 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
2054 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
2055 }
2056 $txlocaltax1 = price2num($txlocaltax1);
2057 $txlocaltax2 = price2num($txlocaltax2);
2058 if ($price_base_type == 'HT') {
2059 $pu = $pu_ht;
2060 } else {
2061 $pu = $pu_ttc;
2062 }
2063 $desc = trim($desc);
2064
2065 // Check parameters
2066 if ($qty < 0 && !$fk_product) {
2067 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product"));
2068 return -1;
2069 }
2070 if ($type < 0) {
2071 return -1;
2072 }
2073 if ($date_start && $date_end && $date_start > $date_end) {
2074 $langs->load("errors");
2075 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2076 return -1;
2077 }
2078
2079
2080 $this->db->begin();
2081
2082 $product_type = $type;
2083 $label = ''; // deprecated
2084
2085 if ($fk_product > 0) {
2086 if (getDolGlobalInt('SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY') == 1) { // Not the common case
2087 // Check quantity is enough
2088 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);
2089 $prod = new ProductFournisseur($this->db);
2090 if ($prod->fetch($fk_product) > 0) {
2091 $product_type = $prod->type;
2092 $label = $prod->label;
2093
2094 // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
2095 // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
2096 $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
2097
2098 // If supplier order created from sales order, we take best supplier price
2099 // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price
2100 if ($result > 0 && ($origin == 'commande' || $pu === '')) {
2101 $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
2102 $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
2103 // is remise percent not keyed but present for the product we add it
2104 if ($remise_percent == 0 && $prod->remise_percent != 0) {
2105 $remise_percent = $prod->remise_percent;
2106 }
2107 }
2108 if ($result == 0) { // If result == 0, we failed to found the supplier reference price
2109 $langs->load("errors");
2110 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2111 $this->db->rollback();
2112 dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
2113 //$pu = $prod->fourn_pu; // We do not overwrite unit price
2114 //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
2115 return -1;
2116 }
2117 if ($result == -1) {
2118 $langs->load("errors");
2119 $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
2120 $this->db->rollback();
2121 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
2122 return -1;
2123 }
2124 if ($result < -1) {
2125 $this->error = $prod->error;
2126 $this->db->rollback();
2127 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
2128 return -1;
2129 }
2130 } else {
2131 $this->error = $prod->error;
2132 $this->db->rollback();
2133 return -1;
2134 }
2135 }
2136
2137 // Predefine quantity according to packaging
2138 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2139 $prod = new Product($this->db);
2140 $prod->get_buyprice($fk_prod_fourn_price, (float) $qty, $fk_product, 'none', (empty($this->fk_soc) ? $this->socid : $this->fk_soc));
2141
2142 $qtysign = ((float) $qty < 0 ? -1 : 1); // The rounding is done on the absolute value, the sign of the quantity is kept
2143 if (abs((float) $qty) < (float) $prod->packaging) {
2144 $qty = $qtysign * (float) $prod->packaging;
2145 } else {
2146 if (!empty($prod->packaging) && (float) price2num(abs((float) $qty) - round(abs((float) $qty) / (float) $prod->packaging) * (float) $prod->packaging, 'MS') != 0) {
2147 $coeff = intval(abs((float) $qty) / $prod->packaging) + 1;
2148 $qty = price2num($qtysign * (float) $prod->packaging * $coeff, 'MS');
2149 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'mesgs');
2150 }
2151 }
2152 }
2153 }
2154
2155 if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
2156 $pu = 0;
2157 }
2158
2159 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2160
2161 // Clean vat code
2162 $reg = array();
2163 $vat_src_code = '';
2164 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
2165 $vat_src_code = $reg[1];
2166 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
2167 }
2168
2169 // Calcul du total TTC et de la TVA pour la ligne a partir de
2170 // qty, pu, remise_percent et txtva
2171 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2172 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2173
2174 $tabprice = calcul_price_total((float) $qty, $pu, $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);
2175
2176 $total_ht = $tabprice[0];
2177 $total_tva = $tabprice[1];
2178 $total_ttc = $tabprice[2];
2179 $total_localtax1 = $tabprice[9];
2180 $total_localtax2 = $tabprice[10];
2181 $pu = $pu_ht = $tabprice[3];
2182
2183 // MultiCurrency
2184 $multicurrency_total_ht = $tabprice[16];
2185 $multicurrency_total_tva = $tabprice[17];
2186 $multicurrency_total_ttc = $tabprice[18];
2187 $pu_ht_devise = $tabprice[19];
2188
2189 $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
2190 $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
2191
2192 if ($rang < 0) {
2193 $rangmax = $this->line_max();
2194 $rang = $rangmax + 1;
2195 }
2196
2197 // Insert line
2198 $this->line = new CommandeFournisseurLigne($this->db);
2199
2200 $this->line->context = $this->context;
2201
2202 $this->line->fk_commande = $this->id;
2203 $this->line->label = $label;
2204 $this->line->ref_fourn = $ref_supplier;
2205 $this->line->ref_supplier = $ref_supplier;
2206 $this->line->desc = $desc;
2207 $this->line->qty = $qty;
2208 $this->line->tva_tx = $txtva;
2209 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
2210 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
2211 $this->line->localtax1_type = $localtax1_type;
2212 $this->line->localtax2_type = $localtax2_type;
2213 $this->line->fk_product = $fk_product;
2214 $this->line->product_type = $product_type;
2215 $this->line->remise_percent = $remise_percent;
2216 $this->line->subprice = (float) $pu_ht;
2217 $this->line->rang = $rang;
2218 $this->line->info_bits = $info_bits;
2219
2220 $this->line->vat_src_code = $vat_src_code;
2221 $this->line->total_ht = (float) $total_ht;
2222 $this->line->total_tva = (float) $total_tva;
2223 $this->line->total_localtax1 = (float) $total_localtax1;
2224 $this->line->total_localtax2 = (float) $total_localtax2;
2225 $this->line->total_ttc = (float) $total_ttc;
2226 $this->line->product_type = $type;
2227 $this->line->special_code = (!empty($special_code) ? $special_code : 0);
2228 $this->line->origin = $origin;
2229 $this->line->origin_type = $origin;
2230 $this->line->origin_id = $origin_id;
2231 $this->line->fk_unit = $fk_unit;
2232
2233 $this->line->date_start = $date_start;
2234 $this->line->date_end = $date_end;
2235
2236 // Multicurrency
2237 $this->line->fk_multicurrency = $this->fk_multicurrency;
2238 $this->line->multicurrency_code = $this->multicurrency_code;
2239 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
2240 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
2241 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
2242 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
2243
2244 $this->line->subprice = (float) $pu_ht;
2245 $this->line->price = $this->line->subprice;
2246
2247 $this->line->remise_percent = $remise_percent;
2248
2249 if (is_array($array_options) && count($array_options) > 0) {
2250 $this->line->array_options = $array_options;
2251 }
2252
2253 $result = $this->line->insert($notrigger);
2254 if ($result > 0) {
2255 // Update denormalized fields at the order level
2256 $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.
2257
2258 if ($result > 0) {
2259 if (!isset($this->context['createfromclone'])) {
2260 if (!empty($this->line->fk_parent_line)) {
2261 // Always reorder if child line
2262 $this->line_order(true, 'DESC');
2263 } elseif ($rang > 0 && $rang <= count($this->lines)) {
2264 // Update all rank of all other lines starting from the same $ranktouse
2265 $linecount = count($this->lines);
2266 for ($ii = $rang; $ii <= $linecount; $ii++) {
2267 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
2268 }
2269 }
2270
2271 $this->lines[] = $this->line;
2272 }
2273
2274 $this->db->commit();
2275 return $this->line->id;
2276 } else {
2277 $this->db->rollback();
2278 return -1;
2279 }
2280 } else {
2281 $this->setErrorsFromObject($this->line);
2282 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
2283 $this->db->rollback();
2284 return -1;
2285 }
2286 }
2287 return -1;
2288 }
2289
2290
2308 public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0, $fk_reception = 0)
2309 {
2310 global $conf, $langs;
2311
2312 $error = 0;
2313 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2314
2315 // Check parameters (if test are wrong here, there is bug into caller)
2316 if ($entrepot <= 0) {
2317 $this->error = 'ErrorBadValueForParameterWarehouse';
2318 return -1;
2319 }
2320 if ($qty == 0) {
2321 $this->error = 'ErrorBadValueForParameterQty';
2322 return -1;
2323 }
2324
2325 $dispatchstatus = 1;
2326 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
2327 $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
2328 }
2329
2330 $now = dol_now();
2331
2332 $inventorycode = dol_print_date(dol_now(), 'dayhourlog');
2333
2334 if (($this->status == self::STATUS_ORDERSENT || $this->status == self::STATUS_RECEIVED_PARTIALLY || $this->status == self::STATUS_RECEIVED_COMPLETELY)) {
2335 $this->db->begin();
2336
2337 $sql = "INSERT INTO ".$this->db->prefix()."receptiondet_batch";
2338 $sql .= " (fk_element, fk_product, qty, fk_entrepot, fk_user, datec, fk_elementdet, status, comment, eatby, sellby, batch, fk_reception) VALUES";
2339 $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
2340 $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");
2341 $sql .= ")";
2342
2343 dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
2344 $resql = $this->db->query($sql);
2345 if ($resql) {
2346 if (!$notrigger) {
2347 global $conf, $langs, $user;
2348 // Call trigger
2349 $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user);
2350 if ($result < 0) {
2351 $error++;
2352 }
2353 // End call triggers
2354 }
2355 } else {
2356 $this->error = $this->db->lasterror();
2357 $error++;
2358 }
2359
2360 // If module stock is enabled and the stock increase is done on purchase order dispatching
2361 if (!$error && $entrepot > 0 && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER')) {
2362 $mouv = new MouvementStock($this->db);
2363 if ($product > 0) {
2364 // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
2365 $mouv->origin = &$this;
2366 $mouv->setOrigin($this->element, $this->id);
2367
2368 // Method change if qty < 0
2369 if (getDolGlobalString('SUPPLIER_ORDER_ALLOW_NEGATIVE_QTY_FOR_SUPPLIER_ORDER_RETURN') && $qty < 0) {
2370 $result = $mouv->livraison($user, $product, $entrepot, $qty * (-1), $price, $comment, $now, $eatby, $sellby, $batch, 0, $inventorycode);
2371 } else {
2372 $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch, '', 0, $inventorycode);
2373 }
2374
2375 if ($result < 0) {
2376 $this->error = $mouv->error;
2377 $this->errors = $mouv->errors;
2378 dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".implode(',', $this->errors), LOG_ERR);
2379 $error++;
2380 }
2381 }
2382 }
2383
2384 if ($error == 0) {
2385 $this->db->commit();
2386 return 1;
2387 } else {
2388 $this->db->rollback();
2389 return -1;
2390 }
2391 } else {
2392 $this->error = 'BadStatusForObject';
2393 return -2;
2394 }
2395 }
2396
2404 public function deleteLine($idline, $notrigger = 0)
2405 {
2406 global $user;
2407
2408 if ($this->status == 0) {
2409 $line = new CommandeFournisseurLigne($this->db);
2410
2411 if ($line->fetch($idline) <= 0) {
2412 return 0;
2413 }
2414 if ($this->id > 0 && (int) $line->fk_commande !== (int) $this->id) {
2415 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2416 return -1;
2417 }
2418
2419 // check if not yet received
2420 $dispatchedLines = $this->getDispachedLines();
2421 foreach ($dispatchedLines as $dispatchLine) {
2422 if ($dispatchLine['orderlineid'] == $idline) {
2423 $this->error = "LineAlreadyDispatched";
2424 $this->errors[] = $this->error;
2425 return -3;
2426 }
2427 }
2428
2429 if ($line->delete($user, $notrigger) > 0) {
2430 $this->update_price(1);
2431 return 1;
2432 } else {
2433 $this->setErrorsFromObject($line);
2434 return -1;
2435 }
2436 } else {
2437 return -2;
2438 }
2439 }
2440
2448 public function delete(User $user, $notrigger = 0)
2449 {
2450 global $langs, $conf;
2451 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2452
2453 $error = 0;
2454
2455 $this->db->begin();
2456
2457 if (empty($notrigger)) {
2458 // Call trigger
2459 $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user);
2460 if ($result < 0) {
2461 $this->errors[] = 'ErrorWhenRunningTrigger';
2462 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2463 $this->db->rollback();
2464 return -1;
2465 }
2466 // End call triggers
2467 }
2468
2469 // Test we can delete
2470 $this->fetchObjectLinked(null, 'order_supplier');
2471 if (!empty($this->linkedObjects) && array_key_exists('reception', $this->linkedObjects)) {
2472 foreach ($this->linkedObjects['reception'] as $element) {
2473 if ($element->statut >= 0) {
2474 $this->errors[] = $langs->trans('ReceptionExist');
2475 $error++;
2476 break;
2477 }
2478 }
2479 }
2480
2481 // Remove linked categories.
2482 if (!$error) {
2483 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_supplier_order";
2484 $sql .= " WHERE fk_supplier_order = ".((int) $this->id);
2485
2486 $result = $this->db->query($sql);
2487 if (!$result) {
2488 $error++;
2489 $this->errors[] = $this->db->lasterror();
2490 }
2491 }
2492
2493 $main = $this->db->prefix().'commande_fournisseurdet';
2494
2495 if (!$error) {
2496 $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).")";
2497 dol_syslog(__METHOD__." linked order lines", LOG_DEBUG);
2498 if (!$this->db->query($sql1)) {
2499 $error++;
2500 $this->error = $this->db->lasterror();
2501 $this->errors[] = $this->db->lasterror();
2502 }
2503 }
2504
2505 if (!$error) {
2506 $ef = $main."_extrafields";
2507 $sql = "DELETE FROM ".$this->db->sanitize($ef)." WHERE fk_object IN (SELECT rowid FROM ".$this->db->sanitize($main)." WHERE fk_commande = ".((int) $this->id).")";
2508 dol_syslog(get_class($this)."::delete extrafields lines", LOG_DEBUG);
2509 if (!$this->db->query($sql)) {
2510 $this->error = $this->db->lasterror();
2511 $this->errors[] = $this->db->lasterror();
2512 $error++;
2513 }
2514 }
2515
2516 if (!$error) {
2517 $sql = "DELETE FROM ".$this->db->prefix()."commande_fournisseurdet WHERE fk_commande = ".((int) $this->id);
2518 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2519 if (!$this->db->query($sql)) {
2520 $this->error = $this->db->lasterror();
2521 $this->errors[] = $this->db->lasterror();
2522 $error++;
2523 }
2524 }
2525
2526 if (!$error) {
2527 $sql = "DELETE FROM ".$this->db->prefix()."commande_fournisseur WHERE rowid = ".((int) $this->id);
2528 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2529 if ($resql = $this->db->query($sql)) {
2530 if ($this->db->affected_rows($resql) < 1) {
2531 $this->error = $this->db->lasterror();
2532 $this->errors[] = $this->db->lasterror();
2533 $error++;
2534 }
2535 } else {
2536 $this->error = $this->db->lasterror();
2537 $this->errors[] = $this->db->lasterror();
2538 $error++;
2539 }
2540 }
2541
2542 // Remove extrafields
2543 if (!$error) {
2544 $result = $this->deleteExtraFields();
2545 if ($result < 0) {
2546 $this->error = 'FailToDeleteExtraFields';
2547 $this->errors[] = 'FailToDeleteExtraFields';
2548 $error++;
2549 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
2550 }
2551 }
2552
2553 // Delete linked object
2554 $res = $this->deleteObjectLinked();
2555 if ($res < 0) {
2556 $this->error = 'FailToDeleteObjectLinked';
2557 $this->errors[] = 'FailToDeleteObjectLinked';
2558 $error++;
2559 }
2560
2561 if (!$error) {
2562 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2563 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2564 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2565
2566 // We remove directory
2567 $ref = dol_sanitizeFileName($this->ref);
2568 if ($conf->fournisseur->commande->dir_output && !empty($ref)) {
2569 $dir = $conf->fournisseur->commande->dir_output."/".$ref;
2570 $file = $dir."/".$ref.".pdf";
2571 if (file_exists($file)) {
2572 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2573 $this->error = 'ErrorFailToDeleteFile';
2574 $this->errors[] = 'ErrorFailToDeleteFile';
2575 $error++;
2576 }
2577 }
2578 if (file_exists($dir)) {
2579 $res = @dol_delete_dir_recursive($dir);
2580 if (!$res) {
2581 $this->error = 'ErrorFailToDeleteDir';
2582 $this->errors[] = 'ErrorFailToDeleteDir';
2583 $error++;
2584 }
2585 }
2586 }
2587 }
2588
2589 if (!$error) {
2590 dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
2591 $this->db->commit();
2592 return 1;
2593 } else {
2594 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2595 $this->db->rollback();
2596 return -$error;
2597 }
2598 }
2599
2600
2609 public function getDispachedLines($status = -1)
2610 {
2611 $ret = array();
2612
2613 // List of already dispatched lines
2614 $sql = "SELECT p.ref, p.label,";
2615 $sql .= " e.rowid as warehouse_id, e.ref as entrepot,";
2616 $sql .= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status, cfd.fk_elementdet";
2617 $sql .= " FROM ".$this->db->prefix()."product as p,";
2618 $sql .= " ".$this->db->prefix()."receptiondet_batch as cfd";
2619 $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e ON cfd.fk_entrepot = e.rowid";
2620 $sql .= " WHERE cfd.fk_element = ".((int) $this->id);
2621 $sql .= " AND cfd.fk_product = p.rowid";
2622 if ($status >= 0) {
2623 $sql .= " AND cfd.status = ".((int) $status);
2624 }
2625 $sql .= " ORDER BY cfd.rowid ASC";
2626
2627 $resql = $this->db->query($sql);
2628 if ($resql) {
2629 $num = $this->db->num_rows($resql);
2630 $i = 0;
2631
2632 while ($i < $num) {
2633 $objp = $this->db->fetch_object($resql);
2634 if ($objp) {
2635 $ret[] = array(
2636 'id' => $objp->dispatchedlineid,
2637 'productid' => $objp->fk_product,
2638 'warehouseid' => $objp->warehouse_id,
2639 'qty' => $objp->qty,
2640 'orderlineid' => $objp->fk_elementdet
2641 );
2642 }
2643
2644 $i++;
2645 }
2646 } else {
2647 dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
2648 }
2649
2650 return $ret;
2651 }
2652
2653 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2663 public function Livraison($user, $date, $type, $comment)
2664 {
2665 // phpcs:enable
2666 global $conf, $langs;
2667
2668 $result = 0;
2669 $error = 0;
2670 $dispatchedlinearray = array();
2671
2672 dol_syslog(get_class($this)."::Livraison");
2673
2674 $usercanreceive = 0;
2675 if (!isModEnabled('reception')) {
2676 $usercanreceive = $user->hasRight("fournisseur", "commande", "receptionner");
2677 } else {
2678 $usercanreceive = $user->hasRight("reception", "creer");
2679 }
2680
2681 if ($usercanreceive) {
2682 // Define the new status
2683 if ($type == 'par') {
2685 } elseif ($type == 'tot') {
2687 } elseif ($type == 'nev') {
2689 } elseif ($type == 'can') {
2691 } else {
2692 $error++;
2693 dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
2694 return -2;
2695 }
2696
2697 // Some checks to accept the record
2698 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
2699 // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
2700 if (!$error && ($type == 'tot')) {
2701 $dispatchedlinearray = $this->getDispachedLines(0);
2702 if (count($dispatchedlinearray) > 0) {
2703 $result = -1;
2704 $error++;
2705 $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
2706 dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
2707 }
2708 }
2709 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)
2710 $dispatcheddenied = $this->getDispachedLines(2);
2711 if (count($dispatchedlinearray) > 0) {
2712 $result = -1;
2713 $error++;
2714 $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
2715 dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
2716 }
2717 }
2718 }
2719
2720 // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
2721
2722 if (empty($error)) {
2723 $this->db->begin();
2724
2725 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2726 $sql .= " SET fk_statut = ".((int) $statut);
2727 $sql .= " WHERE rowid = ".((int) $this->id);
2728 $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received
2729
2730 dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2731 $resql = $this->db->query($sql);
2732 if ($resql) {
2733 $result = 1;
2734 $old_statut = $this->status;
2735 $this->status = $statut;
2736 $this->context['actionmsg2'] = $comment;
2737
2738 // Call trigger
2739 $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
2740 if ($result_trigger < 0) {
2741 $error++;
2742 }
2743 // End call triggers
2744
2745 if (empty($error)) {
2746 $this->db->commit();
2747 } else {
2748 $this->status = $old_statut;
2749 $this->db->rollback();
2750 $this->error = $this->db->lasterror();
2751 $result = -1;
2752 }
2753 } else {
2754 $this->db->rollback();
2755 $this->error = $this->db->lasterror();
2756 $result = -1;
2757 }
2758 }
2759 } else {
2760 $this->error = $langs->trans('NotAuthorized');
2761 $this->errors[] = $langs->trans('NotAuthorized');
2762 dol_syslog(get_class($this)."::Livraison Not Authorized");
2763 $result = -3;
2764 }
2765 return $result;
2766 }
2767
2768 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2778 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2779 {
2780 // phpcs:enable
2781 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2782 }
2783
2792 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2793 {
2794 if ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")) {
2795 $error = 0;
2796
2797 $this->db->begin();
2798
2799 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2800 $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2801 $sql .= " WHERE rowid = ".((int) $this->id);
2802
2803 dol_syslog(__METHOD__, LOG_DEBUG);
2804 $resql = $this->db->query($sql);
2805 if (!$resql) {
2806 $this->errors[] = $this->db->error();
2807 $error++;
2808 }
2809
2810 if (!$error) {
2811 $this->oldcopy = clone $this;
2812 $this->delivery_date = $delivery_date;
2813 }
2814
2815 if (!$notrigger && empty($error)) {
2816 // Call trigger
2817 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2818 if ($result < 0) {
2819 $error++;
2820 }
2821 // End call triggers
2822 }
2823
2824 if (!$error) {
2825 $this->db->commit();
2826 return 1;
2827 } else {
2828 foreach ($this->errors as $errmsg) {
2829 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2830 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2831 }
2832 $this->db->rollback();
2833 return -1 * $error;
2834 }
2835 } else {
2836 return -2;
2837 }
2838 }
2839
2846 public function setReopen(User $user): int
2847 {
2848 if (in_array($this->status, [1, 2, 3, 4, 5, 6, 7, 9])) {
2849 if ($this->status == 1) {
2850 $newStatus = 0; // Validated->Draft
2851 } elseif ($this->status == 2) {
2852 $newStatus = 0; // Approved->Draft
2853 } elseif ($this->status == 3) {
2854 $newStatus = 2; // Ordered->Approved
2855 } elseif ($this->status == 4) {
2856 $newStatus = 3;
2857 } elseif ($this->status == 5) {
2858 //$newstatus=2; // Ordered
2859 // TODO Can we set it to submitted ?
2860 //$newstatus=3; // Submitted
2861 // TODO If there is at least one reception, we can set to Received->Received partially
2862 $newStatus = 4; // Received partially
2863 } elseif ($this->status == 6) {
2864 $newStatus = 2; // Canceled->Approved
2865 } elseif ($this->status == 7) {
2866 $newStatus = 3; // Canceled->Process running
2867 } elseif ($this->status == 9) {
2868 $newStatus = 1; // Refused->Validated
2869 } else {
2870 $newStatus = 2;
2871 }
2872
2873 $this->db->begin();
2874
2875 $result = $this->setStatus($user, $newStatus);
2876 if ($result > 0) {
2877 if ($newStatus == 0) {
2878 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur';
2879 $sql .= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null';
2880 $sql .= ' WHERE rowid = '.((int) $this->id);
2881
2882 $this->db->query($sql);
2883 }
2884
2885 $this->db->commit();
2886
2887 return 1;
2888 } else {
2889 $this->db->rollback();
2890
2891 return -1;
2892 }
2893 }
2894
2895 return 0;
2896 }
2897
2898 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2907 public function set_id_projet($user, $id_projet, $notrigger = 0)
2908 {
2909 // phpcs:enable
2910 if ($user->hasRight("fournisseur", "commande", "creer") || $user->hasRight("supplier_order", "creer")) {
2911 $error = 0;
2912
2913 $this->db->begin();
2914
2915 $sql = "UPDATE ".$this->db->prefix()."commande_fournisseur";
2916 $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2917 $sql .= " WHERE rowid = ".((int) $this->id);
2918
2919 dol_syslog(__METHOD__, LOG_DEBUG);
2920 $resql = $this->db->query($sql);
2921 if (!$resql) {
2922 $this->errors[] = $this->db->error();
2923 $error++;
2924 }
2925
2926 if (!$error) {
2927 $this->oldcopy = clone $this;
2928 $this->fk_projet = $id_projet;
2929 $this->fk_project = $id_projet;
2930 }
2931
2932 if (!$notrigger && empty($error)) {
2933 // Call trigger
2934 $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2935 if ($result < 0) {
2936 $error++;
2937 }
2938 // End call triggers
2939 }
2940
2941 if (!$error) {
2942 $this->db->commit();
2943 return 1;
2944 } else {
2945 foreach ($this->errors as $errmsg) {
2946 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2947 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2948 }
2949 $this->db->rollback();
2950 return -1 * $error;
2951 }
2952 } else {
2953 return -2;
2954 }
2955 }
2956
2965 public function updateFromCommandeClient($user, $idc, $comclientid)
2966 {
2967 $comclient = new Commande($this->db);
2968 $comclient->fetch($comclientid);
2969
2970 $this->id = $idc;
2971
2972 $this->lines = array();
2973
2974 $num = count($comclient->lines);
2975 for ($i = 0; $i < $num; $i++) {
2976 $prod = new Product($this->db);
2977 $label = '';
2978 $ref = '';
2979 if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) {
2980 $label = $prod->label;
2981 $ref = $prod->ref;
2982 }
2983
2984 $sql = "INSERT INTO ".$this->db->prefix()."commande_fournisseurdet";
2985 $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2986 $sql .= " VALUES (".((int) $idc).", '".$this->db->escape($label)."', '".$this->db->escape($comclient->lines[$i]->desc)."'";
2987 $sql .= ",".((int) $comclient->lines[$i]->fk_product).", ".price2num($comclient->lines[$i]->price, 'MU');
2988 $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);
2989 $sql .= ", '".price2num($comclient->lines[$i]->subprice, 'MT')."','0', '".$this->db->escape($ref)."');";
2990 if ($this->db->query($sql)) {
2991 $this->update_price(1);
2992 }
2993 }
2994
2995 return 1;
2996 }
2997
3005 public function setStatus($user, $status)
3006 {
3007 global $conf, $langs;
3008 $error = 0;
3009
3010 $this->db->begin();
3011
3012 $sql = 'UPDATE '.$this->db->prefix().'commande_fournisseur';
3013 $sql .= " SET fk_statut = ".$status;
3014 $sql .= " WHERE rowid = ".((int) $this->id);
3015
3016 dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
3017 $resql = $this->db->query($sql);
3018 if ($resql) {
3019 // Trigger names for each status
3020 $triggerName = array();
3021 $triggerName[0] = 'DRAFT';
3022 $triggerName[1] = 'VALIDATED';
3023 $triggerName[2] = 'APPROVED';
3024 $triggerName[3] = 'ORDERED'; // Ordered
3025 $triggerName[4] = 'RECEIVED_PARTIALLY';
3026 $triggerName[5] = 'RECEIVED_COMPLETELY';
3027 $triggerName[6] = 'CANCELED';
3028 $triggerName[7] = 'CANCELED';
3029 $triggerName[9] = 'REFUSED';
3030
3031 // Call trigger
3032 $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user);
3033 if ($result < 0) {
3034 $error++;
3035 }
3036 // End call triggers
3037 } else {
3038 $error++;
3039 $this->error = $this->db->lasterror();
3040 dol_syslog(get_class($this)."::setStatus ".$this->error);
3041 }
3042
3043 if (!$error) {
3044 $this->status = $status;
3045 $this->db->commit();
3046 return 1;
3047 } else {
3048 $this->db->rollback();
3049 return -1;
3050 }
3051 }
3052
3064 public function setCategories($categories)
3065 {
3066 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3067 return parent::setCategoriesCommon($categories, Categorie::TYPE_SUPPLIER_ORDER);
3068 }
3069
3093 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 = '')
3094 {
3095 global $mysoc, $conf, $langs;
3096 dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
3097 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3098
3099 $error = 0;
3100
3101 if ($this->status == self::STATUS_DRAFT) {
3102 // Clean parameters
3103 if (empty($qty)) {
3104 $qty = 0;
3105 }
3106 if (empty($info_bits)) {
3107 $info_bits = 0;
3108 }
3109 if (empty($txtva)) {
3110 $txtva = 0;
3111 }
3112 if (empty($txlocaltax1)) {
3113 $txlocaltax1 = 0;
3114 }
3115 if (empty($txlocaltax2)) {
3116 $txlocaltax2 = 0;
3117 }
3118 if (empty($remise_percent)) {
3119 $remise_percent = 0;
3120 }
3121
3122 $remise_percent = (float) price2num($remise_percent);
3123 $qty = price2num($qty);
3124 if (!$qty) {
3125 $qty = 1;
3126 }
3127 $pu = price2num($pu);
3128 $pu_ht_devise = price2num($pu_ht_devise);
3129 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3130 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3131 }
3132 $txlocaltax1 = (float) price2num($txlocaltax1);
3133 $txlocaltax2 = (float) price2num($txlocaltax2);
3134
3135 // Check parameters
3136 if ($type < 0) {
3137 return -1;
3138 }
3139 if ($date_start && $date_end && $date_start > $date_end) {
3140 $langs->load("errors");
3141 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3142 return -1;
3143 }
3144
3145 $this->db->begin();
3146
3147 // Calcul du total TTC et de la TVA pour la ligne a partir de
3148 // qty, pu, remise_percent et txtva
3149 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3150 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3151
3152 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
3153
3154 // Clean vat code
3155 $reg = array();
3156 $vat_src_code = '';
3157 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3158 $vat_src_code = $reg[1];
3159 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3160 }
3161
3162 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
3163 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
3164 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
3165 $tmpline = new CommandeFournisseurLigne($this->db);
3166 if ($tmpline->fetch($rowid) > 0) {
3167 $qtysign = ((float) $qty < 0 ? -1 : 1); // The rounding is done on the absolute value, the sign of the quantity is kept
3168 if (abs((float) $qty) < (float) $tmpline->packaging) {
3169 $qty = $qtysign * (float) $tmpline->packaging;
3170 } else {
3171 if (!empty($tmpline->packaging) && is_numeric($tmpline->packaging) && (float) $tmpline->packaging > 0 && (float) price2num(abs((float) $qty) - round(abs((float) $qty) / (float) $tmpline->packaging) * (float) $tmpline->packaging, 'MS') != 0) {
3172 $coeff = intval(abs((float) $qty) / $tmpline->packaging) + 1;
3173 $qty = price2num($qtysign * (float) $tmpline->packaging * $coeff, 'MS');
3174 setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs');
3175 }
3176 }
3177 }
3178 }
3179
3180 $tabprice = calcul_price_total($qty, (float) $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise);
3181 $total_ht = $tabprice[0];
3182 $total_tva = $tabprice[1];
3183 $total_ttc = $tabprice[2];
3184 $total_localtax1 = $tabprice[9];
3185 $total_localtax2 = $tabprice[10];
3186 $pu_ht = $tabprice[3];
3187 $pu_tva = $tabprice[4];
3188 $pu_ttc = $tabprice[5];
3189
3190 // MultiCurrency
3191 $multicurrency_total_ht = $tabprice[16];
3192 $multicurrency_total_tva = $tabprice[17];
3193 $multicurrency_total_ttc = $tabprice[18];
3194 $pu_ht_devise = $tabprice[19];
3195
3196 $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3197 $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3198
3199 // Fetch current line from the database and then clone the object and set it in $oldline property
3200 $this->line = new CommandeFournisseurLigne($this->db);
3201 $this->line->fetch($rowid);
3202
3203 $oldline = clone $this->line;
3204 $this->line->oldline = $oldline;
3205
3206 $this->line->context = $this->context;
3207
3208 $this->line->fk_commande = $this->id;
3209 //$this->line->label=$label;
3210 $this->line->desc = $desc;
3211
3212 $this->line->qty = $qty;
3213 $this->line->ref_supplier = $ref_supplier;
3214
3215 $this->line->vat_src_code = $vat_src_code;
3216 $this->line->tva_tx = $txtva;
3217 $this->line->localtax1_tx = $txlocaltax1;
3218 $this->line->localtax2_tx = $txlocaltax2;
3219 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3220 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3221 $this->line->remise_percent = $remise_percent;
3222 $this->line->subprice = (float) $pu_ht;
3223 $this->line->info_bits = $info_bits;
3224 $this->line->total_ht = (float) $total_ht;
3225 $this->line->total_tva = (float) $total_tva;
3226 $this->line->total_localtax1 = (float) $total_localtax1;
3227 $this->line->total_localtax2 = (float) $total_localtax2;
3228 $this->line->total_ttc = (float) $total_ttc;
3229 $this->line->product_type = $type;
3230 $this->line->special_code = $oldline->special_code;
3231 $this->line->rang = $oldline->rang;
3232 $this->line->origin = $this->origin;
3233 $this->line->fk_unit = $fk_unit;
3234
3235 $this->line->date_start = $date_start;
3236 $this->line->date_end = $date_end;
3237
3238 // Multicurrency
3239 $this->line->fk_multicurrency = $this->fk_multicurrency;
3240 $this->line->multicurrency_code = $this->multicurrency_code;
3241 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
3242 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
3243 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
3244 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
3245
3246 $this->line->subprice = (float) $pu_ht;
3247 $this->line->price = $this->line->subprice;
3248
3249 $this->line->remise_percent = $remise_percent;
3250
3251 if (is_array($array_options) && count($array_options) > 0) {
3252 // We replace values in this->line->array_options only for entries defined into $array_options
3253 foreach ($array_options as $key => $value) {
3254 $this->line->array_options[$key] = $array_options[$key];
3255 }
3256 }
3257
3258 $result = $this->line->update($notrigger);
3259
3260
3261 // Mise a jour info denormalisees au niveau facture
3262 if ($result >= 0) {
3263 $this->update_price(1, 'auto');
3264 $this->db->commit();
3265 return $result;
3266 } else {
3267 $this->errors[] = $this->line->error;
3268 $this->errors = array_merge($this->errors, $this->line->errors);
3269 $this->error = $this->db->lasterror();
3270 $this->db->rollback();
3271 return -1;
3272 }
3273 } else {
3274 $this->error = "Order status makes operation forbidden";
3275 dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
3276 return -2;
3277 }
3278 }
3279
3280
3288 public function initAsSpecimen()
3289 {
3290 global $user, $langs, $conf;
3291
3292 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
3293
3294 dol_syslog(get_class($this)."::initAsSpecimen");
3295
3296 $now = dol_now();
3297
3298 // Find first product
3299 $prodid = 0;
3300 $product = new ProductFournisseur($this->db);
3301 $sql = "SELECT rowid";
3302 $sql .= " FROM ".$this->db->prefix()."product";
3303 $sql .= " WHERE entity IN (".getEntity('product').")";
3304 $sql .= $this->db->order("rowid", "ASC");
3305 $sql .= $this->db->plimit(1);
3306 $resql = $this->db->query($sql);
3307 if ($resql && $this->db->num_rows($resql)) {
3308 $obj = $this->db->fetch_object($resql);
3309 $prodid = $obj->rowid;
3310 }
3311
3312 // Initialise parameters
3313 $this->id = 0;
3314 $this->ref = 'SPECIMEN';
3315 $this->specimen = 1;
3316 $this->socid = 1;
3317 $this->date = $now;
3318 $this->date_commande = $now;
3319 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
3320 $this->cond_reglement_code = 'RECEP';
3321 $this->mode_reglement_code = 'CHQ';
3322
3323 $this->note_public = 'This is a comment (public)';
3324 $this->note_private = 'This is a comment (private)';
3325
3326 $this->multicurrency_tx = 1;
3327 $this->multicurrency_code = $conf->currency;
3328
3329 $this->statut = 0; // deprecated
3330 $this->status = 0;
3331
3332 // Lines
3333 $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)
3334 $xnbp = 0;
3335 while ($xnbp < $nbp) {
3336 $line = new CommandeFournisseurLigne($this->db);
3337 $line->desc = $langs->trans("Description")." ".$xnbp;
3338 $line->qty = 1;
3339 $line->subprice = 100;
3340 $line->tva_tx = 19.6;
3341 $line->localtax1_tx = 0;
3342 $line->localtax2_tx = 0;
3343 if ($xnbp == 2) {
3344 $line->total_ht = 50;
3345 $line->total_ttc = 59.8;
3346 $line->total_tva = 9.8;
3347 $line->remise_percent = 50;
3348 } else {
3349 $line->total_ht = 100;
3350 $line->total_ttc = 119.6;
3351 $line->total_tva = 19.6;
3352 $line->remise_percent = 00;
3353 }
3354 $line->fk_product = $prodid;
3355
3356 $this->lines[$xnbp] = $line;
3357
3358 $this->total_ht += $line->total_ht;
3359 $this->total_tva += $line->total_tva;
3360 $this->total_ttc += $line->total_ttc;
3361
3362 $xnbp++;
3363 }
3364
3365 return 1;
3366 }
3367
3374 public function info($id)
3375 {
3376 $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
3377 $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
3378 $sql .= ' FROM '.$this->db->prefix().'commande_fournisseur as c';
3379 $sql .= ' WHERE c.rowid = '.((int) $id);
3380
3381 $result = $this->db->query($sql);
3382 if ($result) {
3383 if ($this->db->num_rows($result)) {
3384 $obj = $this->db->fetch_object($result);
3385
3386 $this->id = $obj->rowid;
3387
3388 $this->user_creation_id = $obj->fk_user_author;
3389 $this->user_validation_id = $obj->fk_user_valid;
3390 $this->user_modification_id = $obj->fk_user_modif;
3391 $this->user_approve_id = $obj->fk_user_approve;
3392 $this->user_approve_id2 = $obj->fk_user_approve2;
3393
3394 $this->date_creation = $this->db->jdate($obj->datec);
3395 $this->date_modification = $this->db->jdate($obj->datem);
3396 $this->date_approve = $this->db->jdate($obj->datea);
3397 $this->date_approve2 = $this->db->jdate($obj->datea2);
3398 $this->date_validation = $this->db->jdate($obj->date_validation);
3399 }
3400 $this->db->free($result);
3401 } else {
3402 dol_print_error($this->db);
3403 }
3404 }
3405
3411 public function loadStateBoard()
3412 {
3413 global $conf, $user;
3414
3415 $this->nb = array();
3416 $clause = "WHERE";
3417
3418 $sql = "SELECT count(co.rowid) as nb";
3419 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as co";
3420 $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON co.fk_soc = s.rowid";
3421 if (empty($user->socid) && !$user->hasRight("societe", "client", "voir") && !$user->socid) {
3422 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3423 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3424 $clause = "AND";
3425 }
3426 $sql .= " ".$clause." co.entity IN (".getEntity('supplier_order').")";
3427
3428 $resql = $this->db->query($sql);
3429 if ($resql) {
3430 while ($obj = $this->db->fetch_object($resql)) {
3431 $this->nb["supplier_orders"] = $obj->nb;
3432 }
3433 $this->db->free($resql);
3434 return 1;
3435 } else {
3436 dol_print_error($this->db);
3437 $this->error = $this->db->error();
3438 return -1;
3439 }
3440 }
3441
3442 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3450 public function load_board($user, $mode = 'opened')
3451 {
3452 // phpcs:enable
3453 global $conf, $langs;
3454
3455 $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date, c.total_ht";
3456 $sql .= " FROM ".$this->db->prefix()."commande_fournisseur as c";
3457 if (empty($user->socid) && !$user->hasRight("societe", "client", "voir") && !$user->socid) {
3458 $sql .= " JOIN ".$this->db->prefix()."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3459 }
3460 $sql .= " WHERE c.entity = ".$conf->entity;
3461 if ($mode === 'awaiting') {
3462 $sql .= " AND c.fk_statut IN (".self::STATUS_ORDERSENT.", ".self::STATUS_RECEIVED_PARTIALLY.")";
3463 } else {
3464 $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
3465 }
3466 if ($user->socid) {
3467 $sql .= " AND c.fk_soc = ".((int) $user->socid);
3468 }
3469
3470 $resql = $this->db->query($sql);
3471 if ($resql) {
3472 $commandestatic = new CommandeFournisseur($this->db);
3473
3474 $response = new WorkboardResponse();
3475 $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24;
3476 $response->label = $langs->trans("SuppliersOrdersToProcess");
3477 $response->labelShort = $langs->trans("Opened");
3478 $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=1,2&mainmenu=commercial&leftmenu=orders_suppliers';
3479 $response->url_late = DOL_URL_ROOT.'/fourn/commande/list.php?mainmenu=commercial&leftmenu=orders_suppliers&search_option=late';
3480 $response->img = img_object('', "order");
3481
3482 if ($mode === 'awaiting') {
3483 $response->label = $langs->trans("SuppliersOrdersAwaitingReception");
3484 $response->labelShort = $langs->trans("AwaitingReception");
3485 $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=3,4&mainmenu=commercial&leftmenu=orders_suppliers';
3486 $response->url_late = DOL_URL_ROOT.'/fourn/commande/list.php?mainmenu=commercial&leftmenu=orders_suppliers&search_option=recv_late';
3487 }
3488
3489 while ($obj = $this->db->fetch_object($resql)) {
3490 $commandestatic->delivery_date = $this->db->jdate($obj->delivery_date);
3491 $commandestatic->date_commande = $this->db->jdate($obj->date_commande);
3492 $commandestatic->statut = $obj->fk_statut; // deprecated
3493 $commandestatic->status = $obj->fk_statut;
3494
3495 $response->nbtodo++;
3496 $response->total += $obj->total_ht;
3497
3498 if ($commandestatic->hasDelay()) {
3499 $response->nbtodolate++;
3500 }
3501 }
3502
3503 return $response;
3504 } else {
3505 $this->error = $this->db->error();
3506 return -1;
3507 }
3508 }
3509
3516 public function getInputMethod()
3517 {
3518 global $langs;
3519
3520 if ($this->methode_commande_id > 0) {
3521 $sql = "SELECT rowid, code, libelle as label";
3522 $sql .= " FROM ".$this->db->prefix().'c_input_method';
3523 $sql .= " WHERE active=1 AND rowid = ".((int) $this->methode_commande_id);
3524
3525 $resql = $this->db->query($sql);
3526 if ($resql) {
3527 if ($this->db->num_rows($resql)) {
3528 $obj = $this->db->fetch_object($resql);
3529
3530 $string = $langs->trans($obj->code);
3531 if ($string == $obj->code) {
3532 $string = $obj->label != '-' ? $obj->label : '';
3533 }
3534 return $string;
3535 }
3536 } else {
3537 dol_print_error($this->db);
3538 }
3539 }
3540
3541 return '';
3542 }
3543
3555 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3556 {
3557 global $langs;
3558
3559 if (!dol_strlen($modele)) {
3560 $modele = ''; // No doc template/generation by default
3561
3562 if (!empty($this->model_pdf)) {
3563 $modele = $this->model_pdf;
3564 } elseif (getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF')) {
3565 $modele = getDolGlobalString('COMMANDE_SUPPLIER_ADDON_PDF');
3566 }
3567 }
3568
3569 if (empty($modele)) {
3570 return 0;
3571 } else {
3572 $langs->load("suppliers");
3573 $outputlangs->load("products");
3574
3575 $modelpath = "core/modules/supplier_order/doc/";
3576 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3577 return $result;
3578 }
3579 }
3580
3587 public function getMaxDeliveryTimeDay($langs)
3588 {
3589 if (empty($this->lines)) {
3590 return '';
3591 }
3592
3593 $tmpproductfourn = new ProductFournisseur($this->db);
3594
3595 $nb = 0;
3596 foreach ($this->lines as $line) {
3597 if ($line->fk_product > 0) {
3598 // Load delivery_time_days, return id into product_fournisseur_price
3599 $idp = $tmpproductfourn->find_min_price_product_fournisseur($line->fk_product, $line->qty, $this->thirdparty->id);
3600 if ($idp > 0) {
3601 //$tmpproductfourn->fetch_product_fournisseur_price($idp);
3602 if ($tmpproductfourn->delivery_time_days > $nb) {
3603 $nb = $tmpproductfourn->delivery_time_days;
3604 }
3605 }
3606 }
3607 }
3608
3609 if ($nb === 0) {
3610 return '';
3611 } else {
3612 return $nb.' '.$langs->trans('days');
3613 }
3614 }
3615
3621 public function getRights()
3622 {
3623 global $user;
3624
3625 return $user->hasRight("fournisseur", "commande");
3626 }
3627
3628
3637 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3638 {
3639 $tables = array(
3640 'commande_fournisseur'
3641 );
3642
3643 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3644 }
3645
3654 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
3655 {
3656 $tables = array(
3657 'commande_fournisseurdet'
3658 );
3659
3660 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
3661 }
3662
3670 public function hasDelay()
3671 {
3672 global $conf;
3673
3674 if ($this->status == self::STATUS_ORDERSENT || $this->status == self::STATUS_RECEIVED_PARTIALLY) {
3675 $now = dol_now();
3676 if (!empty($this->delivery_date)) {
3677 $date_to_test = $this->delivery_date;
3678 return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3679 } else {
3680 //$date_to_test = $this->date_commande;
3681 //return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3682 return false;
3683 }
3684 } else {
3685 $now = dol_now();
3686 $date_to_test = $this->date_commande;
3687
3688 return ($this->status > 0 && $this->status < 5) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3689 }
3690 }
3691
3699 public function showDelay()
3700 {
3701 global $conf, $langs;
3702
3703 $langs->load('orders');
3704
3705 $text = '';
3706
3707 if ($this->status == self::STATUS_ORDERSENT || $this->status == self::STATUS_RECEIVED_PARTIALLY) {
3708 if (!empty($this->delivery_date)) {
3709 $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
3710 } else {
3711 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3712 }
3713 } else {
3714 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3715 }
3716 if ($text) {
3717 $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3718 }
3719
3720 return $text;
3721 }
3722
3723
3732 public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '')
3733 {
3734 if (isModEnabled("supplier_order")) {
3735 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
3736
3737 $qtydelivered = array();
3738 $qtywished = array();
3739
3740 $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
3741
3742 $filter = array('t.fk_element' => $this->id);
3743 if (getDolGlobalString('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
3744 $filter['t.status'] = 1; // Restrict to lines with status validated
3745 }
3746
3747 $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
3748 if ($ret < 0) {
3749 $this->error = $supplierorderdispatch->error;
3750 $this->errors = $supplierorderdispatch->errors;
3751 return $ret;
3752 } else {
3753 if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) {
3754 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3755 $date_liv = dol_now();
3756
3757 // Build array with quantity deliverd by product
3758 foreach ($supplierorderdispatch->lines as $line) {
3759 if (array_key_exists($line->fk_product, $qtydelivered)) {
3760 $qtydelivered[$line->fk_product] += $line->qty;
3761 } else {
3762 $qtydelivered[$line->fk_product] = $line->qty;
3763 }
3764 }
3765 foreach ($this->lines as $line) {
3766 // Exclude lines not qualified for shipment, similar code is found into interface_20_modWrokflow for customers
3767 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES') && $line->product_type > 0) {
3768 continue;
3769 }
3770 if (array_key_exists($line->fk_product, $qtywished)) {
3771 $qtywished[$line->fk_product] += $line->qty;
3772 } else {
3773 $qtywished[$line->fk_product] = $line->qty;
3774 }
3775 }
3776
3777 //Compare array
3778 $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys.
3779 $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys
3780 $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys
3781 //var_dump(array_keys($qtydelivered));
3782 //var_dump(array_keys($qtywished));
3783 //var_dump($diff_array);
3784 //var_dump($keysinwishednotindelivered);
3785 //var_dump($keysindeliverednotinwished);
3786 //exit;
3787
3788 if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) { //No diff => mean everything is received
3789 if ($closeopenorder) {
3790 //$ret=$this->setStatus($user,5);
3791 $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // $type is 'tot', 'par', 'nev', 'can'
3792 if ($ret < 0) {
3793 return -1;
3794 }
3795 return 5;
3796 } else {
3797 //Diff => received partially
3798 //$ret=$this->setStatus($user,4);
3799 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3800 if ($ret < 0) {
3801 return -1;
3802 }
3803 return 4;
3804 }
3805 } elseif (getDolGlobalString('SUPPLIER_ORDER_MORE_THAN_WISHED')) {
3806 //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...)
3807
3808 $close = 0;
3809
3810 if (count($diff_array) > 0) {
3811 //there are some difference between the two arrays
3812
3813 //scan the array of results
3814 foreach ($diff_array as $key => $value) {
3815 //if the quantity delivered is greater or equal to wish quantity @phan-suppress-next-line PhanTypeInvalidDimOffset
3816 if ($qtydelivered[$key] >= $qtywished[$key]) {
3817 $close++;
3818 }
3819 }
3820 }
3821
3822
3823 if ($close == count($diff_array)) {
3824 //all the products are received equal or more than the wished quantity
3825 if ($closeopenorder) {
3826 $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // $type is 'tot', 'par', 'nev', 'can'
3827 if ($ret < 0) {
3828 return -1;
3829 }
3830 return 5;
3831 } else {
3832 //Diff => received partially
3833 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3834 if ($ret < 0) {
3835 return -1;
3836 }
3837 return 4;
3838 }
3839 } else {
3840 //all the products are not received
3841 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3842 if ($ret < 0) {
3843 return -1;
3844 }
3845 return 4;
3846 }
3847 } else {
3848 //Diff => received partially
3849 $ret = $this->Livraison($user, $date_liv, 'par', $comment); // $type is 'tot', 'par', 'nev', 'can'
3850 if ($ret < 0) {
3851 return -1;
3852 }
3853 return 4;
3854 }
3855 }
3856 return 1;
3857 }
3858 }
3859 return 0;
3860 }
3861
3869 public function loadReceptions($filtre_statut = -1)
3870 {
3871 $this->receptions = array();
3872
3873 dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG);
3874
3875 $sql = 'SELECT cd.rowid, cd.fk_product,';
3876 $sql .= ' sum(cfd.qty) as qty';
3877 $sql .= ' FROM '.$this->db->prefix().'receptiondet_batch as cfd,';
3878 if ($filtre_statut >= 0) {
3879 $sql .= ' '.$this->db->prefix().'reception as e,';
3880 }
3881 $sql .= ' '.$this->db->prefix().'commande_fournisseurdet as cd';
3882 $sql .= ' WHERE';
3883 if ($filtre_statut >= 0) {
3884 $sql .= ' cfd.fk_reception = e.rowid AND';
3885 }
3886 $sql .= ' cfd.fk_elementdet = cd.rowid';
3887 $sql .= ' AND cd.fk_commande ='.((int) $this->id);
3888 if (isset($this->fk_product) && !empty($this->fk_product) > 0) {
3889 $sql .= ' AND cd.fk_product = '.((int) $this->fk_product);
3890 }
3891 if ($filtre_statut >= 0) {
3892 $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
3893 }
3894 $sql .= ' GROUP BY cd.rowid, cd.fk_product';
3895
3896 $resql = $this->db->query($sql);
3897 if ($resql) {
3898 $num = $this->db->num_rows($resql);
3899 $i = 0;
3900 while ($i < $num) {
3901 $obj = $this->db->fetch_object($resql);
3902 empty($this->receptions[$obj->rowid]) ? $this->receptions[$obj->rowid] = $obj->qty : $this->receptions[$obj->rowid] += $obj->qty;
3903 $i++;
3904 }
3905 $this->db->free($resql);
3906
3907 return $num;
3908 } else {
3909 $this->error = $this->db->lasterror();
3910 return -1;
3911 }
3912 }
3913
3921 public function getKanbanView($option = '', $arraydata = null)
3922 {
3923 global $langs;
3924
3925 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3926
3927 $return = '<div class="box-flex-item box-flex-grow-zero">';
3928 $return .= '<div class="info-box info-box-sm">';
3929 $return .= '<span class="info-box-icon bg-infobox-action">';
3930 $return .= img_picto('', $this->picto);
3931 $return .= '</span>';
3932 $return .= '<div class="info-box-content">';
3933 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
3934 if ($selected >= 0) {
3935 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3936 }
3937 if (property_exists($this, 'socid') || property_exists($this, 'total_tva')) {
3938 $return .= '<br><span class="info-box-label amount">'.$this->socid.'</span>';
3939 }
3940 if (property_exists($this, 'billed')) {
3941 $return .= '<br><span class="opacitymedium">'.$langs->trans("Billed").' : </span><span class="info-box-label">'.yn($this->billed).'</span>';
3942 }
3943 if (method_exists($this, 'getLibStatut')) {
3944 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
3945 }
3946 $return .= '</div>';
3947 $return .= '</div>';
3948 $return .= '</div>';
3949 return $return;
3950 }
3951}
$object ref
Definition info.php:90
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.
const STATUS_RECEIVED_COMPLETELY
Received completely.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $ref_supplier='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=0, $date_start=null, $date_end=null, $array_options=[], $fk_unit=null, $pu_ht_devise=0, $origin='', $origin_id=0, $rang=-1, $special_code=0)
Add order line.
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.
getTooltipContentArray($params)
getTooltipContentArray
classifyUnBilled(User $user)
Classify not billed.
approve($user, $idwarehouse=0, $secondlevel=0)
Approve a supplier order.
Cancel($user, $idwarehouse=-1)
Cancel an approved order.
dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0, $fk_reception=0)
Save a receiving into the tracking table of receiving (receptiondet_batch) and add product into stock...
valid($user, $idwarehouse=0, $notrigger=0)
Validate an order.
create($user, $notrigger=0)
Create order with draft status.
update(User $user, $notrigger=0)
Update Supplier Order.
createFromClone(User $user, $socid=0, $notrigger=0)
Load an object from its id and create a new one in database.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=0, $date_start=0, $date_end=0, $array_options=[], $fk_unit=null, $pu_ht_devise=0, $ref_supplier='')
Update line.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template model.
const STATUS_ORDERSENT
Order sent, shipment on process.
commande($user, $date, $methode, $comment='')
Submit a supplier order to supplier.
getRights()
Returns the rights used for this class.
load_board($user, $mode='opened')
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
deleteLine($idline, $notrigger=0)
Delete line.
getMaxDeliveryTimeDay($langs)
Return the max number delivery delay in day.
fetch($id, $ref='')
Get object and lines from database.
Livraison($user, $date, $type, $comment)
Set a delivery in database for this supplier order.
getDispachedLines($status=-1)
Return array of dispatched lines waiting to be approved for this order.
classifyBilled(User $user)
Class invoiced the supplier order.
initAsSpecimen()
Initialise an instance with random values.
const SOURCE_ID_REPLENISHMENT
The constant used into source field to track the order was generated by the replenishement feature.
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.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Superclass for orders classes.
Class to manage Dolibarr database access.
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
dol_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:63
getDolGlobalFloat($key, $default=0)
Return a Dolibarr global constant float value.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller=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