dolibarr 25.0.0-alpha
product.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6 * Copyright (C) 2007-2011 Jean Heimburger <jean@tiaris.info>
7 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
8 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
9 * Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
10 * Copyright (C) 2013-2016 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2011-2021 Open-DSI <support@open-dsi.fr>
12 * Copyright (C) 2014 Henry Florian <florian.henry@open-concept.pro>
13 * Copyright (C) 2014-2016 Philippe Grand <philippe.grand@atoo-net.com>
14 * Copyright (C) 2014 Ion agorria <ion@agorria.com>
15 * Copyright (C) 2016-2024 Ferran Marcet <fmarcet@2byte.es>
16 * Copyright (C) 2017 Gustavo Novaro
17 * Copyright (C) 2019-2026 Frédéric France <frederic.france@free.fr>
18 * Copyright (C) 2023 Benjamin Falière <benjamin.faliere@altairis.fr>
19 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
20 * Copyright (C) 2025 Lenin Rivas <lenin.rivas777@gmail.com>
21 * Copyright (C) 2026 Anthony Berton <anthony.berton@bb2a.fr>
22 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
23 * Copyright (C) 2026 Mélina Joum <melina.joum@altairis.fr>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 */
38
44require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
46require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
47require_once DOL_DOCUMENT_ROOT.'/product/class/productlang.class.php';
48require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
49require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
50
54class Product extends CommonObject
55{
60 const SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY = 1;
61 const SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY = 2;
62 const SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT = 3;
63
68 public $TRIGGER_PREFIX = 'PRODUCT';
69
73 public $element = 'product';
74
78 public $table_element = 'product';
79
83 public $fk_element = 'fk_product';
84
88 protected $childtables = array(
89 'supplier_proposaldet' => array('name' => 'SupplierProposal', 'parent' => 'supplier_proposal', 'parentkey' => 'fk_supplier_proposal'),
90 'propaldet' => array('name' => 'Proposal', 'parent' => 'propal', 'parentkey' => 'fk_propal'),
91 'commandedet' => array('name' => 'Order', 'parent' => 'commande', 'parentkey' => 'fk_commande'),
92 'facturedet' => array('name' => 'Invoice', 'parent' => 'facture', 'parentkey' => 'fk_facture'),
93 'contratdet' => array('name' => 'Contract', 'parent' => 'contrat', 'parentkey' => 'fk_contrat'),
94 'facture_fourn_det' => array('name' => 'SupplierInvoice', 'parent' => 'facture_fourn', 'parentkey' => 'fk_facture_fourn'),
95 'commande_fournisseurdet' => array('name' => 'SupplierOrder', 'parent' => 'commande_fournisseur', 'parentkey' => 'fk_commande'),
96 'mrp_production' => array('name' => 'Mo', 'parent' => 'mrp_mo', 'parentkey' => 'fk_mo', 'enabled' => 'isModEnabled("mrp")'),
97 'bom_bom' => array('name' => 'BOM', 'enabled' => 'isModEnabled("bom")'),
98 'bom_bomline' => array('name' => 'BOMLine', 'parent' => 'bom_bom', 'parentkey' => 'fk_bom', 'enabled' => 'isModEnabled("bom")'),
99 );
100
106 public $picto = 'product';
107
111 protected $table_ref_field = 'ref';
112
117 public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm|\.avif';
118
124 public $ref;
125
131 public $libelle;
132
138 public $label;
139
145 public $description;
146
152 public $other;
153
159 public $type = self::TYPE_PRODUCT;
160
166 public $price;
167
171 public $price_formated; // used by takepos/ajax/ajax.php
172
178 public $price_ttc;
179
183 public $price_ttc_formated; // used by takepos/ajax/ajax.php
184
190 public $price_min;
191
197 public $price_min_ttc;
198
203 public $price_base_type;
207 public $price_label;
208
210
213 public $multiprices = array();
217 public $multiprices_ttc = array();
221 public $multiprices_base_type = array();
225 public $multiprices_default_vat_code = array();
229 public $multiprices_min = array();
233 public $multiprices_min_ttc = array();
237 public $multiprices_tva_tx = array();
241 public $multiprices_recuperableonly = array();
242
244
247 public $price_by_qty;
251 public $prices_by_qty = array();
255 public $prices_by_qty_id = array();
259 public $prices_by_qty_list = array();
260
264 public $level;
265
269 public $multilangs = array();
270
274 public $default_vat_code;
275
279 public $tva_tx;
280
284 public $tva_npr = 0;
285
289 public $remise_percent;
290
294 public $localtax1_tx;
298 public $localtax2_tx;
302 public $localtax1_type;
306 public $localtax2_type;
307
308 // Properties set by get_buyprice() for return
309
313 public $desc_supplier;
317 public $vatrate_supplier;
321 public $default_vat_code_supplier;
322
326 public $fourn_multicurrency_price;
327
331 public $fourn_multicurrency_unitprice;
335 public $fourn_multicurrency_tx;
339 public $fourn_multicurrency_id;
343 public $fourn_multicurrency_code;
344
348 public $packaging;
349
350
357 public $lifetime;
358
365 public $qc_frequency;
366
372 public $stock_reel = 0;
373
379 public $stock_theorique;
380
386 public $cost_price;
387
393 public $pmp;
394
400 public $seuil_stock_alerte = 0;
401
405 public $desiredstock = 0;
406
410 public $duration_value;
414 public $duration_unit;
418 public $duration;
419
423 public $fk_default_workstation;
424
430 public $status = 0;
431
438 public $tosell;
439
445 public $status_buy = 0;
446
453 public $tobuy;
454
460 public $finished;
461
467 public $fk_default_bom;
468
474 public $product_fourn_price_id;
475
481 public $buyprice;
482
488 public $tobatch;
489
490
496 public $status_batch = 0;
497
503 public $sell_or_eat_by_mandatory = 0;
504
510 public $batch_mask = '';
511
517 public $customcode;
518
524 public $url;
525
527
530 public $weight;
531
535 public $weight_units; // scale -3, 0, 3, 6
539 public $length;
543 public $length_units; // scale -3, 0, 3, 6
547 public $width;
551 public $width_units; // scale -3, 0, 3, 6
555 public $height;
559 public $height_units; // scale -3, 0, 3, 6
563 public $surface;
567 public $surface_units; // scale -3, 0, 3, 6
571 public $volume;
575 public $volume_units; // scale -3, 0, 3, 6
576
580 public $net_measure;
584 public $net_measure_units; // scale -3, 0, 3, 6
585
589 public $accountancy_code_sell;
593 public $accountancy_code_sell_intra;
597 public $accountancy_code_sell_export;
601 public $accountancy_code_buy;
605 public $accountancy_code_buy_intra;
609 public $accountancy_code_buy_export;
610
614 public $barcode;
615
619 public $barcode_type;
620
624 public $barcode_type_code;
625
629 public $stats_propale = array();
630
634 public $stats_commande = array();
635
639 public $stats_contrat = array();
640
644 public $stats_facture = array();
645
649 public $stats_proposal_supplier = array();
650
654 public $stats_commande_fournisseur = array();
655
659 public $stats_expedition = array();
660
664 public $stats_reception = array();
665
669 public $stats_mo = array();
670
674 public $stats_bom = array();
675
679 public $stats_mrptoconsume = array();
680
684 public $stats_mrptoproduce = array();
685
689 public $stats_facturerec = array();
690
694 public $stats_facture_fournisseur = array();
695
699 public $stats_facturefournrec = array();
700
704 public $imgWidth;
708 public $imgHeight;
709
714 public $product_fourn_id;
715
720 public $product_id_already_linked;
721
726 public $nbphoto = 0;
727
731 public $stock_warehouse = array();
732
736 public $fk_default_warehouse;
737
741 public $fk_price_expression;
742
747 public $fourn_qty;
748
753 public $fourn_pu;
754
759 public $fourn_price_base_type;
760
764 public $fourn_socid;
765
771 public $ref_fourn;
772
776 public $ref_supplier;
777
783 public $fk_unit;
784
790 public $price_autogen = 0;
791
797 public $sousprods = array();
798
802 public $res;
803
804
810 public $is_object_used;
811
821 public $is_sousproduit_qty;
822
833 public $is_sousproduit_incdec;
834
838 public $mandatory_period;
839
845 public $stockable_product = 1;
846
875 public $fields = array(
876 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
877 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 5),
878 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1, 'comment' => 'Reference of object'),
879 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 2, 'position' => 11, 'csslist' => 'tdoverflowmax250'),
880 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 'isModEnabled("barcode")', 'position' => 20, 'visible' => -1, 'showoncombobox' => 3, 'cssview' => 'tdwordbreak', 'csslist' => 'tdoverflowmax125'),
881 'fk_barcode_type' => array('type' => 'integer', 'label' => 'BarcodeType', 'enabled' => 1, 'position' => 21, 'notnull' => 0, 'visible' => -1,),
882 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 61, 'uieditable' => 1),
883 'note' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 62),
884 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 500),
885 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 501),
886 //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
887 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 510, 'foreignkey' => 'llx_user.rowid'),
888 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 511),
889 //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
890 'localtax1_tx' => array('type' => 'double(6,3)', 'label' => 'Localtax1tx', 'enabled' => 1, 'position' => 150, 'notnull' => 0, 'visible' => -1,),
891 'localtax1_type' => array('type' => 'varchar(10)', 'label' => 'Localtax1type', 'enabled' => 1, 'position' => 155, 'notnull' => 1, 'visible' => -1,),
892 'localtax2_tx' => array('type' => 'double(6,3)', 'label' => 'Localtax2tx', 'enabled' => 1, 'position' => 160, 'notnull' => 0, 'visible' => -1,),
893 'localtax2_type' => array('type' => 'varchar(10)', 'label' => 'Localtax2type', 'enabled' => 1, 'position' => 165, 'notnull' => 1, 'visible' => -1,),
894 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 170),
895 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'index' => 0, 'position' => 1000),
896 //'tosell' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>'0', 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
897 //'tobuy' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>'0', 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
898 'mandatory_period' => array('type' => 'integer', 'label' => 'mandatoryperiod', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'default' => '0', 'index' => 1, 'position' => 1000),
899 'stockable_product' => array('type' => 'integer', 'label' => 'stockable_product', 'enabled' => 1, 'visible' => 1, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 502),
900 );
901
905 const TYPE_PRODUCT = 0;
909 const TYPE_SERVICE = 1;
910
914 const DISABLED_STOCK = 0;
915 const ENABLED_STOCK = 1;
916
922 public function __construct($db)
923 {
924 $this->db = $db;
925
926 $this->ismultientitymanaged = 1;
927 $this->isextrafieldmanaged = 1;
928
929 $this->canvas = '';
930 }
931
937 public function check()
938 {
939 if (getDolGlobalInt('MAIN_SECURITY_ALLOW_UNSECURED_REF_LABELS')) {
940 $this->ref = trim((string) $this->ref);
941 } else {
942 $this->ref = dol_sanitizeFileName(stripslashes($this->ref));
943 }
944
945 $err = 0;
946 if (dol_strlen(trim((string) $this->ref)) == 0) {
947 $err++;
948 }
949
950 if (dol_strlen(trim((string) $this->label)) == 0) {
951 $err++;
952 }
953
954 if ($err > 0) {
955 return 0;
956 } else {
957 return 1;
958 }
959 }
960
968 public function create($user, $notrigger = 0)
969 {
970 global $conf, $langs;
971
972 $error = 0;
973
974 // Clean parameters
975 if (getDolGlobalInt('MAIN_SECURITY_ALLOW_UNSECURED_REF_LABELS')) {
976 $this->ref = trim((string) $this->ref);
977 } else {
978 $this->ref = dol_sanitizeFileName(dol_string_nospecial(trim((string) $this->ref)));
979 }
980 $this->label = trim((string) $this->label);
981 $this->price_ttc = (float) price2num($this->price_ttc);
982 $this->price = (float) price2num($this->price);
983 $this->price_min_ttc = (float) price2num($this->price_min_ttc);
984 $this->price_min = (float) price2num($this->price_min);
985 $this->price_label = trim((string) $this->price_label);
986 if (empty($this->tva_tx)) {
987 $this->tva_tx = 0;
988 }
989 if (empty($this->tva_npr)) {
990 $this->tva_npr = 0;
991 }
992 // Local taxes
993 if (empty($this->localtax1_tx)) {
994 $this->localtax1_tx = 0;
995 }
996 if (empty($this->localtax2_tx)) {
997 $this->localtax2_tx = 0;
998 }
999 if (empty($this->localtax1_type)) {
1000 $this->localtax1_type = '0';
1001 }
1002 if (empty($this->localtax2_type)) {
1003 $this->localtax2_type = '0';
1004 }
1005 // Price
1006 if (empty($this->price_base_type) && getDolGlobalString('PRODUCT_PRICE_BASE_TYPE')) {
1007 $this->price_base_type = getDolGlobalString('PRODUCT_PRICE_BASE_TYPE');
1008 }
1009 if (empty($this->price)) {
1010 $this->price = 0;
1011 }
1012 if (empty($this->price_min)) {
1013 $this->price_min = 0;
1014 }
1015 // Price by quantity
1016 if (empty($this->price_by_qty)) {
1017 $this->price_by_qty = 0;
1018 }
1019
1020 if (empty($this->status)) {
1021 $this->status = 0;
1022 }
1023 if (empty($this->status_buy)) {
1024 $this->status_buy = 0;
1025 }
1026 if (empty($this->stockable_product)) {
1027 $this->stockable_product = 0;
1028 }
1029
1030 $price_ht = 0;
1031 $price_ttc = 0;
1032 $price_min_ht = 0;
1033 $price_min_ttc = 0;
1034
1035 //
1036 if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
1037 $price_ttc = price2num($this->price_ttc, 'MU');
1038 $price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
1039 }
1040
1041 //
1042 if ($this->price_base_type != 'TTC' && $this->price > 0) {
1043 $price_ht = price2num($this->price, 'MU');
1044 $price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
1045 }
1046
1047 //
1048 if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
1049 $price_min_ttc = price2num($this->price_min_ttc, 'MU');
1050 $price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
1051 }
1052
1053 //
1054 if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
1055 $price_min_ht = price2num($this->price_min, 'MU');
1056 $price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
1057 }
1058
1059 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1060 $this->accountancy_code_buy_intra = trim((string) $this->accountancy_code_buy_intra);
1061 $this->accountancy_code_buy_export = trim((string) $this->accountancy_code_buy_export);
1062 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1063 $this->accountancy_code_sell_intra = trim((string) $this->accountancy_code_sell_intra);
1064 $this->accountancy_code_sell_export = trim((string) $this->accountancy_code_sell_export);
1065
1066 // Normalize the accountancy codes the way the admin dropdown does it, so an API client that
1067 // sends '606111000' ends up with the same '606111' value the GUI stores (see issue #32343).
1068 // When ACCOUNTING_MANAGE_ZERO is on, trailing zeros are part of the code and must be kept.
1069 if (!getDolGlobalString('ACCOUNTING_MANAGE_ZERO')) {
1070 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1071 $this->accountancy_code_buy = clean_account($this->accountancy_code_buy);
1072 $this->accountancy_code_buy_intra = clean_account($this->accountancy_code_buy_intra);
1073 $this->accountancy_code_buy_export = clean_account($this->accountancy_code_buy_export);
1074 $this->accountancy_code_sell = clean_account($this->accountancy_code_sell);
1075 $this->accountancy_code_sell_intra = clean_account($this->accountancy_code_sell_intra);
1076 $this->accountancy_code_sell_export = clean_account($this->accountancy_code_sell_export);
1077 }
1078
1079 // Barcode value
1080 $this->barcode = trim((string) $this->barcode);
1081 $this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
1082 // Check parameters
1083 if (empty($this->label)) {
1084 $langs->load('errors');
1085 $this->errors[] = $langs->trans('ErrorMandatoryParametersNotProvided');
1086 return -1;
1087 }
1088
1089 if (empty($this->ref) || $this->ref == 'auto') {
1090 // Load object modCodeProduct
1091 $module = getDolGlobalString('PRODUCT_CODEPRODUCT_ADDON', 'mod_codeproduct_leopard');
1092 if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
1093 if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
1094 $module = substr($module, 0, dol_strlen($module) - 4);
1095 }
1096 dol_include_once('/core/modules/product/'.$module.'.php');
1097 $modCodeProduct = new $module();
1098 '@phan-var-force ModeleProductCode $modCodeProduct';
1099 if (!empty($modCodeProduct->code_auto)) {
1100 $this->ref = $modCodeProduct->getNextValue($this, $this->type);
1101 }
1102 unset($modCodeProduct);
1103 }
1104
1105 if (empty($this->ref)) {
1106 $this->error = 'ProductModuleNotSetupForAutoRef';
1107 return -2;
1108 }
1109 }
1110
1111 dol_syslog(get_class($this)."::create ref=".$this->ref." price=".$this->price." price_ttc=".$this->price_ttc." tva_tx=".$this->tva_tx." price_base_type=".$this->price_base_type, LOG_DEBUG);
1112
1113 $now = dol_now();
1114
1115 if (empty($this->date_creation)) {
1116 $this->date_creation = $now;
1117 }
1118
1119 $this->db->begin();
1120
1121 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1122 if ($this->barcode == '-1' || $this->barcode == 'auto') {
1123 $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
1124 }
1125
1126 // Check more parameters
1127 // If error, this->errors[] is filled
1128 $result = $this->verify();
1129
1130 if ($result >= 0) {
1131 $sql = "SELECT count(*) as nb";
1132 $sql .= " FROM ".$this->db->prefix()."product";
1133 $sql .= " WHERE entity IN (".getEntity('product').")";
1134 $sql .= " AND ref = '".$this->db->escape($this->ref)."'";
1135
1136 $result = $this->db->query($sql);
1137 if ($result) {
1138 $obj = $this->db->fetch_object($result);
1139 if ($obj->nb == 0) {
1140 // Insert new product, no previous one found
1141 $sql = "INSERT INTO ".$this->db->prefix()."product (";
1142 $sql .= "datec";
1143 $sql .= ", entity";
1144 $sql .= ", ref";
1145 $sql .= ", ref_ext";
1146 $sql .= ", price_min";
1147 $sql .= ", price_min_ttc";
1148 $sql .= ", label";
1149 $sql .= ", fk_user_author";
1150 $sql .= ", fk_product_type";
1151 $sql .= ", price";
1152 $sql .= ", price_ttc";
1153 $sql .= ", price_base_type";
1154 $sql .= ", price_label";
1155 $sql .= ", tobuy";
1156 $sql .= ", tosell";
1157 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1158 $sql .= ", accountancy_code_buy";
1159 $sql .= ", accountancy_code_buy_intra";
1160 $sql .= ", accountancy_code_buy_export";
1161 $sql .= ", accountancy_code_sell";
1162 $sql .= ", accountancy_code_sell_intra";
1163 $sql .= ", accountancy_code_sell_export";
1164 }
1165 $sql .= ", canvas";
1166 $sql .= ", finished";
1167 $sql .= ", tobatch";
1168 $sql .= ", sell_or_eat_by_mandatory";
1169 $sql .= ", batch_mask";
1170 $sql .= ", fk_unit";
1171 $sql .= ", mandatory_period";
1172 $sql .= ", stockable_product";
1173 if (!empty($this->default_vat_code)) {
1174 $sql .= ", default_vat_code";
1175 }
1176 $sql .= ") VALUES (";
1177 $sql .= "'".$this->db->idate($this->date_creation)."'";
1178 $sql .= ", ".(!empty($this->entity) ? (int) $this->entity : (int) $conf->entity);
1179 $sql .= ", '".$this->db->escape($this->ref)."'";
1180 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1181 $sql .= ", ".price2num($price_min_ht);
1182 $sql .= ", ".price2num($price_min_ttc);
1183 $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
1184 $sql .= ", ".((int) $user->id);
1185 $sql .= ", ".((int) $this->type);
1186 $sql .= ", ".price2num($price_ht, 'MT');
1187 $sql .= ", ".price2num($price_ttc, 'MT');
1188 $sql .= ", '".$this->db->escape($this->price_base_type)."'";
1189 $sql .= ", ".(!empty($this->price_label) ? "'".$this->db->escape($this->price_label)."'" : "null");
1190 $sql .= ", ".((int) $this->status);
1191 $sql .= ", ".((int) $this->status_buy);
1192 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1193 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1194 $sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
1195 $sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
1196 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1197 $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
1198 $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
1199 }
1200 $sql .= ", '".$this->db->escape($this->canvas)."'";
1201 $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
1202 $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
1203 $sql .= ", ".((empty($this->sell_or_eat_by_mandatory) || $this->sell_or_eat_by_mandatory < 0) ? 0 : ((int) $this->sell_or_eat_by_mandatory));
1204 $sql .= ", '".$this->db->escape($this->batch_mask)."'";
1205 $sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
1206 $sql .= ", '".$this->db->escape((string) $this->mandatory_period)."'";
1207 $sql .= ", ".((int) $this->stockable_product);
1208 if (!empty($this->default_vat_code)) {
1209 $sql .= ", '".$this->db->escape($this->default_vat_code)."'";
1210 }
1211 $sql .= ")";
1212 dol_syslog(get_class($this)."::Create", LOG_DEBUG);
1213
1214 $result = $this->db->query($sql);
1215 if ($result) {
1216 $id = $this->db->last_insert_id($this->db->prefix()."product");
1217
1218 if ($id > 0) {
1219 $this->id = $id;
1220 $this->price = $price_ht;
1221 $this->price_ttc = $price_ttc;
1222 $this->price_min = $price_min_ht;
1223 $this->price_min_ttc = $price_min_ttc;
1224
1225 $result = $this->_log_price($user);
1226 if ($result > 0) {
1227 if ($this->update($id, $user, 1, 'add') <= 0) {
1228 $error++;
1229 }
1230 } else {
1231 $error++;
1232 $this->error = $this->db->lasterror();
1233 }
1234
1235 // update accountancy for this entity
1236 if (!$error && getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1237 $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
1238
1239 $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
1240 $sql .= " fk_product";
1241 $sql .= ", entity";
1242 $sql .= ", accountancy_code_buy";
1243 $sql .= ", accountancy_code_buy_intra";
1244 $sql .= ", accountancy_code_buy_export";
1245 $sql .= ", accountancy_code_sell";
1246 $sql .= ", accountancy_code_sell_intra";
1247 $sql .= ", accountancy_code_sell_export";
1248 $sql .= ") VALUES (";
1249 $sql .= ((int) $this->id);
1250 $sql .= ", " . ((int) $conf->entity);
1251 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1252 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1253 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1254 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1255 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1256 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1257 $sql .= ")";
1258 $result = $this->db->query($sql);
1259 if (!$result) {
1260 $error++;
1261 $this->error = 'ErrorFailedToInsertAccountancyForEntity';
1262 }
1263 }
1264 } else {
1265 $error++;
1266 $this->error = 'ErrorFailedToGetInsertedId';
1267 }
1268 } else {
1269 $error++;
1270 $this->error = $this->db->lasterror();
1271 }
1272 } else {
1273 // Product already exists with this ref
1274 $langs->load("products");
1275 $error++;
1276 $this->error = "ErrorProductAlreadyExists";
1277 dol_syslog(get_class($this)."::Create fails, ref ".$this->ref." already exists");
1278 }
1279 } else {
1280 $error++;
1281 $this->error = $this->db->lasterror();
1282 }
1283
1284 if (!$error && !$notrigger) {
1285 // Call trigger
1286 $result = $this->call_trigger('PRODUCT_CREATE', $user);
1287 if ($result < 0) {
1288 $error++;
1289 }
1290 // End call triggers
1291 }
1292
1293 if (!$error) {
1294 $this->db->commit();
1295 return $this->id;
1296 } else {
1297 $this->db->rollback();
1298 return -$error;
1299 }
1300 } else {
1301 $this->db->rollback();
1302 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1303 return -3;
1304 }
1305 }
1306
1307
1314 public function verify()
1315 {
1316 global $langs;
1317
1318 $this->errors = array();
1319
1320 $result = 0;
1321 $this->ref = trim((string) $this->ref);
1322
1323 if (!$this->ref) {
1324 $this->errors[] = 'ErrorBadRef';
1325 $result = -2;
1326 }
1327
1328 $arrayofnonnegativevalue = array('weight' => 'Weight', 'width' => 'Width', 'height' => 'Height', 'length' => 'Length', 'surface' => 'Surface', 'volume' => 'Volume');
1329 foreach ($arrayofnonnegativevalue as $key => $value) {
1330 if (property_exists($this, $key) && !empty($this->$key) && ($this->$key < 0)) {
1331 $langs->loadLangs(array("main", "other"));
1332 $this->error = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
1333 $this->errors[] = $this->error;
1334 $result = -4;
1335 }
1336 }
1337
1338 $rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
1339 if ($rescode) {
1340 if ($rescode == -1) {
1341 $this->errors[] = 'ErrorBadBarCodeSyntax';
1342 } elseif ($rescode == -2) {
1343 $this->errors[] = 'ErrorBarCodeRequired';
1344 } elseif ($rescode == -3) {
1345 // Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
1346 $this->errors[] = 'ErrorBarCodeAlreadyUsed';
1347 }
1348
1349 $result = -3;
1350 }
1351
1352 return $result;
1353 }
1354
1355 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1366 public function check_barcode($valuetotest, $typefortest)
1367 {
1368 // phpcs:enable
1369 global $conf;
1370
1371 if (isModEnabled('barcode') && getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM')) {
1372 $module = strtolower(getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM'));
1373
1374 $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
1375 foreach ($dirsociete as $dirroot) {
1376 $res = dol_include_once($dirroot.$module.'.php');
1377 if ($res) {
1378 break;
1379 }
1380 }
1381
1382 $mod = new $module();
1383 '@phan-var-force ModeleNumRefBarCode $mod';
1386 dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
1387 $result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
1388 return $result;
1389 } else {
1390 return 0;
1391 }
1392 }
1393
1405 public function update($id, $user, $notrigger = 0, $action = 'update', $updatetype = false)
1406 {
1407 global $langs, $conf, $hookmanager;
1408
1409 $error = 0;
1410
1411 // Check parameters
1412 if (!$this->label) {
1413 $this->label = 'MISSING LABEL';
1414 }
1415
1416 // Clean parameters
1417 if (getDolGlobalInt('MAIN_SECURITY_ALLOW_UNSECURED_REF_LABELS')) {
1418 $this->ref = trim((string) $this->ref);
1419 } else {
1420 $this->ref = dol_string_nospecial(trim((string) $this->ref));
1421 }
1422 $this->label = trim((string) $this->label);
1423 $this->description = trim((string) $this->description);
1424 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : null);
1425 $this->note_public = (isset($this->note_public) ? trim($this->note_public) : null);
1426 $this->net_measure = price2num($this->net_measure);
1427 $this->net_measure_units = (!is_numeric($this->net_measure_units) ? null : (int) $this->net_measure_units);
1428 $this->weight = price2num($this->weight);
1429 $this->weight_units = (!is_numeric($this->weight_units) ? null : (int) $this->weight_units);
1430 $this->length = price2num($this->length);
1431 $this->length_units = (!is_numeric($this->length_units) ? null : (int) $this->length_units);
1432 $this->width = price2num($this->width);
1433 $this->width_units = (!is_numeric($this->width_units) ? null : (int) $this->width_units);
1434 $this->height = price2num($this->height);
1435 $this->height_units = (!is_numeric($this->height_units) ? null : (int) $this->height_units);
1436 $this->surface = price2num($this->surface);
1437 $this->surface_units = (!is_numeric($this->surface_units) ? null : (int) $this->surface_units);
1438 $this->volume = price2num($this->volume);
1439 $this->volume_units = (!is_numeric($this->volume_units) ? null : (int) $this->volume_units);
1440
1441 // set unit not defined
1442 if (is_numeric($this->length_units)) {
1443 $this->width_units = $this->length_units; // Not used yet
1444 }
1445 if (is_numeric($this->length_units)) {
1446 $this->height_units = $this->length_units; // Not used yet
1447 }
1448
1449 // Automated compute surface and volume if not filled
1450 if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
1451 $this->surface = (float) $this->length * (float) $this->width;
1452 $this->surface_units = measuring_units_squared((int) $this->length_units);
1453 }
1454 if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
1455 $this->volume = $this->surface * (float) $this->height;
1456 $this->volume_units = measuring_units_cubed((int) $this->height_units);
1457 }
1458
1459 if (empty($this->tva_tx)) {
1460 $this->tva_tx = 0;
1461 }
1462 if (empty($this->tva_npr)) {
1463 $this->tva_npr = 0;
1464 }
1465 if (empty($this->localtax1_tx)) {
1466 $this->localtax1_tx = 0;
1467 }
1468 if (empty($this->localtax2_tx)) {
1469 $this->localtax2_tx = 0;
1470 }
1471 if (empty($this->localtax1_type)) {
1472 $this->localtax1_type = '0';
1473 }
1474 if (empty($this->localtax2_type)) {
1475 $this->localtax2_type = '0';
1476 }
1477 if (empty($this->status)) {
1478 $this->status = 0;
1479 }
1480 if (empty($this->status_buy)) {
1481 $this->status_buy = 0;
1482 }
1483
1484 if (empty($this->country_id)) {
1485 $this->country_id = 0;
1486 }
1487 if (empty($this->country_id) && !empty($this->country_code)) {
1488 $country_id = getCountry($this->country_code, '3');
1489 $this->country_id = is_int($country_id) ? $country_id : 0;
1490 }
1491
1492 if (empty($this->state_id)) {
1493 $this->state_id = 0;
1494 }
1495
1496 if (empty($this->stockable_product)) {
1497 $this->stockable_product = 0;
1498 }
1499
1500 // For automatic creation during update action (not used by Dolibarr GUI, can be used by scripts)
1501 if ($this->barcode == '-1' || $this->barcode == 'auto') {
1502 $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
1503 }
1504
1505 // Barcode value
1506 $this->barcode = (empty($this->barcode) ? '' : trim($this->barcode));
1507
1508 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1509 $this->accountancy_code_buy_intra = (!empty($this->accountancy_code_buy_intra) ? trim($this->accountancy_code_buy_intra) : '');
1510 $this->accountancy_code_buy_export = trim((string) $this->accountancy_code_buy_export);
1511 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1512 $this->accountancy_code_sell_intra = trim((string) $this->accountancy_code_sell_intra);
1513 $this->accountancy_code_sell_export = trim((string) $this->accountancy_code_sell_export);
1514
1515 // Normalize the accountancy codes the way the admin dropdown does it, so an API client that
1516 // sends '606111000' ends up with the same '606111' value the GUI stores (see issue #32343).
1517 // When ACCOUNTING_MANAGE_ZERO is on, trailing zeros are part of the code and must be kept.
1518 if (!getDolGlobalString('ACCOUNTING_MANAGE_ZERO')) {
1519 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1520 $this->accountancy_code_buy = clean_account($this->accountancy_code_buy);
1521 $this->accountancy_code_buy_intra = clean_account($this->accountancy_code_buy_intra);
1522 $this->accountancy_code_buy_export = clean_account($this->accountancy_code_buy_export);
1523 $this->accountancy_code_sell = clean_account($this->accountancy_code_sell);
1524 $this->accountancy_code_sell_intra = clean_account($this->accountancy_code_sell_intra);
1525 $this->accountancy_code_sell_export = clean_account($this->accountancy_code_sell_export);
1526 }
1527
1528 $this->db->begin();
1529
1530 $result = 0;
1531 // Check name is required and codes are ok or unique. If error, this->errors[] is filled
1532 if ($action != 'add') {
1533 $result = $this->verify(); // We don't check when update called during a create because verify was already done
1534 } else {
1535 // we can continue
1536 $result = 0;
1537 }
1538
1539 if ($result >= 0) {
1540 // $this->oldcopy should have been set by the caller of update (here properties were already modified)
1541 // Note that this->oldcopy must be a Product instance (not stdClass), otherwise the method
1542 // hasbatch() called below will fatal. Callers may set oldcopy via dol_clone($obj, 2) (which
1543 // returns a stdClass with scalar properties only) and then we cannot call methods on it,
1544 // so re-clone with native=1 in that case (see issues #38663, #38638).
1545 if (is_null($this->oldcopy) || (is_object($this->oldcopy) && empty($this->oldcopy->id)) || !($this->oldcopy instanceof Product)) {
1546 $this->oldcopy = dol_clone($this, 1); // 1 to clone with methods to avoid fatal error with $this->oldcopy->hasbatch()
1547 }
1548 // Test if batch management is activated on existing product
1549 // If yes, we create missing entries into product_batch
1550 if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
1551 //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
1552 $valueforundefinedlot = '000000';
1553 if (getDolGlobalString('STOCK_DEFAULT_BATCH')) {
1554 $valueforundefinedlot = getDolGlobalString('STOCK_DEFAULT_BATCH');
1555 }
1556
1557 dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
1558
1559 $this->load_stock();
1560 foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
1561 $qty_batch = 0;
1562 foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
1563 if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
1564 // We discard this line, we will create it later
1565 $sqlclean = "DELETE FROM ".$this->db->prefix()."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".((int) $ObjW->id);
1566 $result = $this->db->query($sqlclean);
1567 if (!$result) {
1568 dol_print_error($this->db);
1569 exit;
1570 }
1571 continue;
1572 }
1573
1574 $qty_batch += $detail->qty;
1575 }
1576 // Quantities in batch details are not same as stock quantity,
1577 // so we add a default batch record to complete and get same qty in parent and child table
1578 if ($ObjW->real != $qty_batch) {
1579 $ObjBatch = new Productbatch($this->db);
1580 $ObjBatch->batch = $valueforundefinedlot;
1581 $ObjBatch->qty = ($ObjW->real - $qty_batch);
1582 $ObjBatch->fk_product_stock = (int) $ObjW->id;
1583
1584 if ($ObjBatch->create($user, 1) < 0) {
1585 $error++;
1586 $this->errors = $ObjBatch->errors;
1587 } else {
1588 // we also add lot record if not exist
1589 $ObjLot = new Productlot($this->db);
1590 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1591 if ($ObjLot->fetch(0, $this->id, $valueforundefinedlot) == 0) {
1592 $ObjLot->fk_product = $this->id;
1593 $ObjLot->entity = (int) $this->entity;
1594 $ObjLot->fk_user_creat = $user->id;
1595 $ObjLot->batch = $valueforundefinedlot;
1596 if ($ObjLot->create($user, 1) < 0) {
1597 $error++;
1598 $this->errors = $ObjLot->errors;
1599 }
1600 }
1601 }
1602 }
1603 }
1604 }
1605
1606 $sql = "UPDATE ".$this->db->prefix()."product";
1607 $sql .= " SET label = '".$this->db->escape($this->label)."'";
1608
1609 if ($updatetype && ($this->isProduct() || $this->isService())) {
1610 $sql .= ", fk_product_type = ".((int) $this->type);
1611 }
1612
1613 $sql .= ", ref = '".$this->db->escape($this->ref)."'";
1614 $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1615 $sql .= ", default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null");
1616 $sql .= ", tva_tx = ".((float) $this->tva_tx);
1617 $sql .= ", recuperableonly = ".((int) $this->tva_npr);
1618 $sql .= ", localtax1_tx = ".((float) $this->localtax1_tx);
1619 $sql .= ", localtax2_tx = ".((float) $this->localtax2_tx);
1620 $sql .= ", localtax1_type = ".($this->localtax1_type != '' ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'");
1621 $sql .= ", localtax2_type = ".($this->localtax2_type != '' ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'");
1622
1623 $sql .= ", barcode = ".(empty($this->barcode) ? "null" : "'".$this->db->escape($this->barcode)."'");
1624 $sql .= ", fk_barcode_type = ".(empty($this->barcode_type) ? "null" : ((int) $this->barcode_type));
1625
1626 $sql .= ", tosell = ".(int) $this->status;
1627 $sql .= ", tobuy = ".(int) $this->status_buy;
1628 $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch);
1629 $sql .= ", sell_or_eat_by_mandatory = ".((empty($this->sell_or_eat_by_mandatory) || $this->sell_or_eat_by_mandatory < 0) ? 0 : (int) $this->sell_or_eat_by_mandatory);
1630 $sql .= ", batch_mask = '".$this->db->escape($this->batch_mask)."'";
1631
1632 $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished === '') ? "null" : (int) $this->finished);
1633 $sql .= ", fk_default_bom = ".((!isset($this->fk_default_bom) || $this->fk_default_bom < 0 || $this->fk_default_bom == '') ? "null" : (int) $this->fk_default_bom);
1634 $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null');
1635 $sql .= ", net_measure_units = ".((string) $this->net_measure_units != '' ? ((int) $this->net_measure_units) : 'null');
1636 $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null');
1637 $sql .= ", weight_units = ".((string) $this->weight_units != '' ? ((int) $this->weight_units) : 'null');
1638 $sql .= ", length = ".($this->length != '' ? "'".$this->db->escape($this->length)."'" : 'null');
1639 $sql .= ", length_units = ".((string) $this->length_units != '' ? ((int) $this->length_units) : 'null');
1640 $sql .= ", width= ".($this->width != '' ? "'".$this->db->escape($this->width)."'" : 'null');
1641 $sql .= ", width_units = ".((string) $this->width_units != '' ? ((int) $this->width_units) : 'null');
1642 $sql .= ", height = ".($this->height != '' ? "'".$this->db->escape($this->height)."'" : 'null');
1643 $sql .= ", height_units = ".((string) $this->height_units != '' ? ((int) $this->height_units) : 'null');
1644 $sql .= ", surface = ".($this->surface != '' ? "'".$this->db->escape($this->surface)."'" : 'null');
1645 $sql .= ", surface_units = ".((string) $this->surface_units != '' ? ((int) $this->surface_units) : 'null');
1646 $sql .= ", volume = ".($this->volume != '' ? "'".$this->db->escape($this->volume)."'" : 'null');
1647 $sql .= ", volume_units = ".((string) $this->volume_units != '' ? ((int) $this->volume_units) : 'null');
1648 $sql .= ", fk_default_warehouse = ".($this->fk_default_warehouse > 0 ? ((int) $this->fk_default_warehouse) : 'null');
1649 $sql .= ", fk_default_workstation = ".($this->fk_default_workstation > 0 ? ((int) $this->fk_default_workstation) : 'null');
1650 $sql .= ", seuil_stock_alerte = ".((isset($this->seuil_stock_alerte) && is_numeric($this->seuil_stock_alerte)) ? (float) $this->seuil_stock_alerte : 'null');
1651 $sql .= ", description = '".$this->db->escape($this->description)."'";
1652 $sql .= ", url = ".($this->url ? "'".$this->db->escape($this->url)."'" : 'null');
1653 $sql .= ", customcode = '".$this->db->escape($this->customcode)."'";
1654 $sql .= ", fk_country = ".($this->country_id > 0 ? (int) $this->country_id : 'null');
1655 $sql .= ", fk_state = ".($this->state_id > 0 ? (int) $this->state_id : 'null');
1656 $sql .= ", lifetime = ".($this->lifetime > 0 ? (int) $this->lifetime : 'null');
1657 $sql .= ", qc_frequency = ".($this->qc_frequency > 0 ? (int) $this->qc_frequency : 'null');
1658 $sql .= ", note = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : 'null');
1659 $sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : 'null');
1660 $sql .= ", duration = '".$this->db->escape($this->duration_value.$this->duration_unit)."'";
1661 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1662 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1663 $sql .= ", accountancy_code_buy_intra = '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1664 $sql .= ", accountancy_code_buy_export = '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1665 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1666 $sql .= ", accountancy_code_sell_intra= '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1667 $sql .= ", accountancy_code_sell_export= '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1668 }
1669 $sql .= ", desiredstock = ".((isset($this->desiredstock) && is_numeric($this->desiredstock)) ? (float) $this->desiredstock : "null");
1670 $sql .= ", cost_price = ".($this->cost_price != '' ? ((float) $this->cost_price) : 'null');
1671 $sql .= ", fk_unit= ".(!$this->fk_unit ? 'NULL' : (int) $this->fk_unit);
1672 $sql .= ", price_autogen = ".(!$this->price_autogen ? 0 : 1);
1673 $sql .= ", fk_price_expression = ".($this->fk_price_expression != 0 ? (int) $this->fk_price_expression : 'NULL');
1674 $sql .= ", fk_user_modif = ".($user->id > 0 ? (int) $user->id : 'NULL');
1675 $sql .= ", mandatory_period = ".((int) $this->mandatory_period);
1676 $sql .= ", stockable_product = ".(int) $this->stockable_product;
1677 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1678 $sql .= ", packaging = ".(float) $this->packaging;
1679 }
1680
1681 // stock field is not here because it is a denormalized value from product_stock.
1682 $sql .= " WHERE rowid = ".((int) $id);
1683
1684 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1685
1686 $resql = $this->db->query($sql);
1687 if ($resql) {
1688 $this->id = $id;
1689
1690 // Multilangs
1691 if (getDolGlobalInt('MAIN_MULTILANGS')) {
1692 if ($this->setMultiLangs($user, $notrigger) < 0) {
1693 $this->db->rollback();
1694 return -2;
1695 }
1696 }
1697
1698 $action = 'update';
1699
1700 // update accountancy for this entity
1701 if (!$error && getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1702 $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " . ((int) $this->id) . " AND entity = " . ((int) $conf->entity));
1703
1704 $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
1705 $sql .= " fk_product";
1706 $sql .= ", entity";
1707 $sql .= ", accountancy_code_buy";
1708 $sql .= ", accountancy_code_buy_intra";
1709 $sql .= ", accountancy_code_buy_export";
1710 $sql .= ", accountancy_code_sell";
1711 $sql .= ", accountancy_code_sell_intra";
1712 $sql .= ", accountancy_code_sell_export";
1713 $sql .= ") VALUES (";
1714 $sql .= ((int) $this->id);
1715 $sql .= ", " . ((int) $conf->entity);
1716 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1717 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1718 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1719 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1720 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1721 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1722 $sql .= ")";
1723 $result = $this->db->query($sql);
1724 if (!$result) {
1725 $error++;
1726 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1727 }
1728 }
1729
1730 if (!$this->hasbatch() && $this->oldcopy->hasbatch()) {
1731 // Selection of all product stock movements that contains batchs
1732 $sql = 'SELECT pb.qty, ps.fk_entrepot, pb.batch FROM '.MAIN_DB_PREFIX.'product_batch as pb';
1733 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_stock as ps ON (ps.rowid = pb.fk_product_stock)';
1734 $sql .= ' WHERE ps.fk_product = '.(int) $this->id;
1735
1736 $resql = $this->db->query($sql);
1737 if ($resql) {
1738 $inventorycode = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
1739
1740 while ($obj = $this->db->fetch_object($resql)) {
1741 $value = $obj->qty;
1742 $fk_entrepot = $obj->fk_entrepot;
1743 $price = 0;
1744 $dlc = '';
1745 $dluo = '';
1746 $batch = $obj->batch;
1747
1748 // To know how to revert stockMouvement (add or remove)
1749 $addOremove = $value > 0 ? 1 : 0; // 1 if remove, 0 if add
1750 $label = $langs->trans('BatchStockMouvementAddInGlobal');
1751 $res = $this->correct_stock_batch($user, $fk_entrepot, abs($value), $addOremove, $label, $price, $dlc, $dluo, $batch, $inventorycode, '', null, 0, null, true);
1752
1753 if ($res > 0) {
1754 $label = $langs->trans('BatchStockMouvementAddInGlobal');
1755 $res = $this->correct_stock($user, $fk_entrepot, abs($value), (int) empty($addOremove), $label, $price, $inventorycode, '', null, 0);
1756 if ($res < 0) {
1757 $error++;
1758 }
1759 } else {
1760 $error++;
1761 }
1762 }
1763 }
1764 }
1765
1766 // Actions on extra fields
1767 if (!$error) {
1768 $result = $this->insertExtraFields();
1769 if ($result < 0) {
1770 $error++;
1771 }
1772 }
1773
1774 if (!$error && !$notrigger) {
1775 // Call trigger
1776 $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1777 if ($result < 0) {
1778 $error++;
1779 }
1780 // End call triggers
1781 }
1782
1783 if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
1784 // We remove directory
1785 if ($conf->product->dir_output) {
1786 $olddir = $conf->product->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
1787 $newdir = $conf->product->dir_output."/".dol_sanitizeFileName($this->ref);
1788 if (file_exists($olddir)) {
1789 // include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1790 // $res = dol_move($olddir, $newdir);
1791 // do not use dol_move with directory
1792 $res = @rename($olddir, $newdir);
1793 if (!$res) {
1794 $langs->load("errors");
1795 $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
1796 $error++;
1797 } else {
1798 // to keep old entries with the new dir
1799 require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
1800 $ecmfiles = new EcmFiles($this->db);
1801 $ecmfiles->updateAfterRename("produit/".dol_sanitizeFileName($this->oldcopy->ref), "produit/".dol_sanitizeFileName($this->ref));
1802 }
1803 }
1804 }
1805 }
1806
1807 if (!$error) {
1808 if (isModEnabled('variants')) {
1809 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1810
1811 $comb = new ProductCombination($this->db);
1812
1813 foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) {
1814 $currcomb->updateProperties($this, $user);
1815 }
1816 }
1817
1818 $this->db->commit();
1819 return 1;
1820 } else {
1821 $this->db->rollback();
1822 return -$error;
1823 }
1824 } else {
1825 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1826 $langs->load("errors");
1827 if (empty($conf->barcode->enabled) || empty($this->barcode)) {
1828 $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref);
1829 } else {
1830 $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode);
1831 }
1832 $this->errors[] = $this->error;
1833 $this->db->rollback();
1834 return -1;
1835 } else {
1836 $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1837 $this->errors[] = $this->error;
1838 $this->db->rollback();
1839 return -2;
1840 }
1841 }
1842 } else {
1843 $this->db->rollback();
1844 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1845 return -3;
1846 }
1847 }
1848
1856 public function delete(User $user, $notrigger = 0)
1857 {
1858 global $conf;
1859 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1860
1861 $error = 0;
1862
1863 // Check parameters
1864 if (empty($this->id)) {
1865 $this->error = "Object must be fetched before calling delete";
1866 return -1;
1867 }
1868 if (($this->isProduct() && !$user->hasRight('produit', 'supprimer')) || ($this->isService() && !$user->hasRight('service', 'supprimer'))) {
1869 $this->error = "ErrorForbidden";
1870 return 0;
1871 }
1872
1873 $objectisused = $this->isObjectUsed($this->id);
1874 if (empty($objectisused)) {
1875 $this->db->begin();
1876
1877 if (empty($notrigger)) {
1878 // Call trigger
1879 $result = $this->call_trigger('PRODUCT_DELETE', $user);
1880 if ($result < 0) {
1881 $error++;
1882 }
1883 // End call triggers
1884 }
1885
1886 // Delete from product_batch on product delete
1887 if (!$error) {
1888 $sql = "DELETE FROM ".$this->db->prefix().'product_batch';
1889 $sql .= " WHERE fk_product_stock IN (";
1890 $sql .= "SELECT rowid FROM ".$this->db->prefix().'product_stock';
1891 $sql .= " WHERE fk_product = ".((int) $this->id).")";
1892
1893 $result = $this->db->query($sql);
1894 if (!$result) {
1895 $error++;
1896 $this->errors[] = $this->db->lasterror();
1897 }
1898 }
1899
1900 // Delete pricelogs so we don't have any orphan rows, see #38383
1901 if (!$error) {
1902 $sql = "DELETE FROM " . $this->db->prefix() . "product_fournisseur_price_log";
1903 $sql .= " WHERE fk_product_fournisseur IN (";
1904 $sql .= " SELECT rowid FROM " . $this->db->prefix() . "product_fournisseur_price";
1905 $sql .= " WHERE fk_product = " . ((int) $this->id);
1906 $sql .= " )";
1907
1908 $resql = $this->db->query($sql);
1909 if (!$resql) {
1910 $error++;
1911 $this->errors[] = $this->db->lasterror();
1912 }
1913 }
1914
1915 // Delete the extrafields of the translations (llx_product_lang_extrafields has no foreign key)
1916 if (!$error) {
1917 $sql = "DELETE FROM ".$this->db->prefix()."product_lang_extrafields";
1918 $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."product_lang WHERE fk_product = ".((int) $this->id).")";
1919 $result = $this->db->query($sql);
1920 if (!$result) {
1921 $error++;
1922 $this->errors[] = $this->db->lasterror();
1923 }
1924 }
1925
1926 // Delete all child tables
1927 if (!$error) {
1928 $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
1929 foreach ($elements as $table) {
1930 if (!$error) {
1931 $sql = "DELETE FROM ".$this->db->prefix().$table;
1932 $sql .= " WHERE fk_product = ".(int) $this->id;
1933
1934 $result = $this->db->query($sql);
1935 if (!$result) {
1936 $error++;
1937 $this->errors[] = $this->db->lasterror();
1938 }
1939 }
1940 }
1941 }
1942
1943 if (!$error && isModEnabled('variants')) {
1944 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1945 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
1946
1947 // If it is a parent product, then we remove the association with child products
1948 $prodcomb = new ProductCombination($this->db);
1949
1950 if ($prodcomb->deleteByFkProductParent($user, $this->id) < 0) {
1951 $error++;
1952 $this->errors[] = 'Error deleting combinations';
1953 }
1954
1955 // We also check if it is a child product
1956 if (!$error && ($prodcomb->fetchByFkProductChild($this->id) > 0) && ($prodcomb->delete($user) < 0)) {
1957 $error++;
1958 $this->errors[] = 'Error deleting child combination';
1959 }
1960 }
1961
1962 // Rows may survive the deactivation of the module, and the foreign key on
1963 // fk_product_parent would then refuse to delete the product. Only the links are
1964 // removed here, never a product: deleting variant products silently is the job of the
1965 // block above, which runs when the user can actually see them. Missing tables are
1966 // tolerated by deleteLinksByProduct(): they only exist once the module was enabled.
1967 if (!$error) {
1968 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1969
1970 $prodcomb = new ProductCombination($this->db);
1971 if ($prodcomb->deleteLinksByProduct($this->id) < 0) {
1972 $error++;
1973 $this->errors[] = $prodcomb->error;
1974 }
1975 }
1976
1977 // Delete from product_association
1978 if (!$error) {
1979 $sql = "DELETE FROM ".$this->db->prefix()."product_association";
1980 $sql .= " WHERE fk_product_pere = ".(int) $this->id." OR fk_product_fils = ".(int) $this->id;
1981
1982 $result = $this->db->query($sql);
1983 if (!$result) {
1984 $error++;
1985 $this->errors[] = $this->db->lasterror();
1986 }
1987 }
1988
1989 // Remove extrafields
1990 if (!$error) {
1991 $result = $this->deleteExtraFields();
1992 if ($result < 0) {
1993 $error++;
1994 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1995 }
1996 }
1997
1998 // Delete product
1999 if (!$error) {
2000 $sqlz = "DELETE FROM ".$this->db->prefix()."product";
2001 $sqlz .= " WHERE rowid = ".(int) $this->id;
2002
2003 $resultz = $this->db->query($sqlz);
2004 if (!$resultz) {
2005 $error++;
2006 $this->errors[] = $this->db->lasterror();
2007 }
2008 }
2009
2010 // Delete record into ECM index and physically
2011 if (!$error) {
2012 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2013 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2014 if (!$res) {
2015 $error++;
2016 }
2017 }
2018
2019 if (!$error) {
2020 // We remove directory
2021 $ref = dol_sanitizeFileName($this->ref);
2022 if ($conf->product->dir_output) {
2023 $dir = $conf->product->dir_output."/".$ref;
2024 if (file_exists($dir)) {
2025 $res = @dol_delete_dir_recursive($dir);
2026 if (!$res) {
2027 $this->errors[] = 'ErrorFailToDeleteDir';
2028 $error++;
2029 }
2030 }
2031 }
2032 }
2033
2034 if (!$error) {
2035 $this->db->commit();
2036 return 1;
2037 } else {
2038 foreach ($this->errors as $errmsg) {
2039 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
2040 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2041 }
2042 $this->db->rollback();
2043 return -$error;
2044 }
2045 } else {
2046 $this->error = "ErrorRecordIsUsedCantDelete";
2047 return 0;
2048 }
2049 }
2050
2056 public static function getSellOrEatByMandatoryList()
2057 {
2058 global $langs;
2059
2060 $sellByLabel = $langs->trans('SellByDate');
2061 $eatByLabel = $langs->trans('EatByDate');
2062 return array(
2063 self::SELL_OR_EAT_BY_MANDATORY_ID_NONE => $langs->trans('BatchSellOrEatByMandatoryNone'),
2064 self::SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY => $sellByLabel,
2065 self::SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY => $eatByLabel,
2066 self::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT => $langs->trans('BatchSellOrEatByMandatoryAll', $sellByLabel, $eatByLabel),
2067 );
2068 }
2069
2076 {
2077 $sellOrEatByMandatoryLabel = '';
2078
2079 $sellOrEatByMandatoryList = self::getSellOrEatByMandatoryList();
2080 if (isset($sellOrEatByMandatoryList[$this->sell_or_eat_by_mandatory])) {
2081 $sellOrEatByMandatoryLabel = $sellOrEatByMandatoryList[$this->sell_or_eat_by_mandatory];
2082 }
2083
2084 return $sellOrEatByMandatoryLabel;
2085 }
2086
2094 public function setMultiLangs($user, $notrigger = 0)
2095 {
2096 global $langs;
2097
2098 $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
2099 $current_lang = $langs->getDefaultLang();
2100
2101 foreach ($langs_available as $key => $value) {
2102 if ($key == $current_lang) {
2103 $sql = "SELECT rowid";
2104 $sql .= " FROM ".$this->db->prefix()."product_lang";
2105 $sql .= " WHERE fk_product = ".((int) $this->id);
2106 $sql .= " AND lang = '".$this->db->escape($key)."'";
2107
2108 $result = $this->db->query($sql);
2109 $objlang = ($result ? $this->db->fetch_object($result) : null);
2110 $rowidlang = ($objlang ? (int) $objlang->rowid : 0);
2111
2112 if ($objlang) { // if there is already a description line for this language
2113 $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
2114 $sql2 .= " SET ";
2115 $sql2 .= " label='".$this->db->escape($this->label)."',";
2116 $sql2 .= " description='".$this->db->escape($this->description)."'";
2117 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2118 $sql2 .= ", note='".$this->db->escape($this->other)."'";
2119 }
2120 $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
2121 } else {
2122 $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
2123 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2124 $sql2 .= ", note";
2125 }
2126 $sql2 .= ")";
2127 $sql2 .= " VALUES(".((int) $this->id).",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
2128 $sql2 .= " '".$this->db->escape($this->description)."'";
2129 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2130 $sql2 .= ", '".$this->db->escape($this->other)."'";
2131 }
2132 $sql2 .= ")";
2133 }
2134 dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
2135 if (!$this->db->query($sql2)) {
2136 $this->error = $this->db->lasterror();
2137 return -1;
2138 }
2139 if (empty($rowidlang)) {
2140 $rowidlang = (int) $this->db->last_insert_id($this->db->prefix()."product_lang");
2141 }
2142 if ($this->setMultiLangsExtrafields($key, $rowidlang) < 0) {
2143 return -1;
2144 }
2145 } elseif (isset($this->multilangs[$key])) {
2146 if (empty($this->multilangs[$key]["label"])) {
2147 $this->errors[] = $key . ' : ' . $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
2148 return -1;
2149 }
2150
2151 $sql = "SELECT rowid";
2152 $sql .= " FROM ".$this->db->prefix()."product_lang";
2153 $sql .= " WHERE fk_product = ".((int) $this->id);
2154 $sql .= " AND lang = '".$this->db->escape($key)."'";
2155
2156 $result = $this->db->query($sql);
2157 $objlang = ($result ? $this->db->fetch_object($result) : null);
2158 $rowidlang = ($objlang ? (int) $objlang->rowid : 0);
2159
2160 if ($objlang) { // if there is already a description line for this language
2161 $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
2162 $sql2 .= " SET ";
2163 $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
2164 $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
2165 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2166 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2167 $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
2168 }
2169 $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
2170 } else {
2171 $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
2172 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2173 $sql2 .= ", note";
2174 }
2175 $sql2 .= ")";
2176 $sql2 .= " VALUES(".((int) $this->id).",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
2177 $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
2178 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2179 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2180 $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
2181 }
2182 $sql2 .= ")";
2183 }
2184
2185 // We do not save if main fields are empty
2186 if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
2187 if (!$this->db->query($sql2)) {
2188 $this->error = $this->db->lasterror();
2189 return -1;
2190 }
2191 if (empty($rowidlang)) {
2192 $rowidlang = (int) $this->db->last_insert_id($this->db->prefix()."product_lang");
2193 }
2194 if ($this->setMultiLangsExtrafields($key, $rowidlang) < 0) {
2195 return -1;
2196 }
2197 }
2198 } else {
2199 // language is not current language and we didn't provide a multilang description for this language
2200 }
2201 }
2202
2203 if (empty($notrigger)) {
2204 // Call trigger
2205 $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
2206 if ($result < 0) {
2207 $this->error = $this->db->lasterror();
2208 return -1;
2209 }
2210 // End call triggers
2211 }
2212
2213 return 1;
2214 }
2215
2224 protected function setMultiLangsExtrafields($langcode, $rowidlang)
2225 {
2226 if (empty($rowidlang) || !isset($this->multilangs[$langcode]['array_options']) || !is_array($this->multilangs[$langcode]['array_options'])) {
2227 return 0;
2228 }
2229
2230 $productlang = new ProductLang($this->db);
2231 $productlang->id = $rowidlang;
2232 $productlang->array_options = $this->multilangs[$langcode]['array_options'];
2233 $result = $productlang->insertExtraFields();
2234 if ($result < 0) {
2235 $this->error = $productlang->error;
2236 $this->errors = array_merge($this->errors, $productlang->errors);
2237 dol_syslog(get_class($this).'::setMultiLangsExtrafields error='.$this->error, LOG_ERR);
2238 return -1;
2239 }
2240
2241 return 1;
2242 }
2243
2253 public function delMultiLangs($langtodelete, $user, $notrigger = 0)
2254 {
2255 dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
2256
2257 // Delete the extrafields of the translation first (llx_product_lang_extrafields has no foreign key)
2258 $sql = "DELETE FROM ".$this->db->prefix()."product_lang_extrafields";
2259 $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."product_lang";
2260 $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."')";
2261 $result = $this->db->query($sql);
2262 if (!$result) {
2263 $this->error = $this->db->lasterror();
2264 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2265 return -1;
2266 }
2267
2268 $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
2269 $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
2270
2271 $result = $this->db->query($sql);
2272 if ($result) {
2273 if (empty($notrigger)) {
2274 // Call trigger
2275 $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
2276 if ($result < 0) {
2277 $this->error = $this->db->lasterror();
2278 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2279 return -1;
2280 }
2281 // End call triggers
2282 }
2283 unset($this->multilangs[$langtodelete]);
2284 return 1;
2285 } else {
2286 $this->error = $this->db->lasterror();
2287 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2288 return -1;
2289 }
2290 }
2291
2300 public function setAccountancyCode($type, $value)
2301 {
2302 global $user;
2303
2304 $error = 0;
2305
2306 $this->db->begin();
2307
2308 if ($type == 'buy') {
2309 $field = 'accountancy_code_buy';
2310 } elseif ($type == 'buy_intra') {
2311 $field = 'accountancy_code_buy_intra';
2312 } elseif ($type == 'buy_export') {
2313 $field = 'accountancy_code_buy_export';
2314 } elseif ($type == 'sell') {
2315 $field = 'accountancy_code_sell';
2316 } elseif ($type == 'sell_intra') {
2317 $field = 'accountancy_code_sell_intra';
2318 } elseif ($type == 'sell_export') {
2319 $field = 'accountancy_code_sell_export';
2320 } else {
2321 return -1;
2322 }
2323
2324 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
2325 $sql .= "$field = '".$this->db->escape($value)."'";
2326 $sql .= " WHERE rowid = ".((int) $this->id);
2327
2328 dol_syslog(__METHOD__, LOG_DEBUG);
2329 $resql = $this->db->query($sql);
2330
2331 if ($resql) {
2332 // Call trigger
2333 $result = $this->call_trigger('PRODUCT_MODIFY', $user);
2334 if ($result < 0) {
2335 $error++;
2336 }
2337 // End call triggers
2338
2339 if ($error) {
2340 $this->db->rollback();
2341 return -1;
2342 }
2343
2344 $this->$field = $value;
2345
2346 $this->db->commit();
2347 return 1;
2348 } else {
2349 $this->error = $this->db->lasterror();
2350 $this->db->rollback();
2351 return -1;
2352 }
2353 }
2354
2361 public function getMultiLangs($loadextrafields = 0)
2362 {
2363 global $langs;
2364
2365 $current_lang = '';
2366 if ($langs instanceOf Translate) {
2367 $current_lang = $langs->getDefaultLang();
2368 }
2369
2370 $sql = "SELECT rowid, lang, label, description, note as other";
2371 $sql .= " FROM ".$this->db->prefix()."product_lang";
2372 $sql .= " WHERE fk_product = ".((int) $this->id);
2373
2374 $result = $this->db->query($sql);
2375 if ($result) {
2376 while ($obj = $this->db->fetch_object($result)) {
2377 //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
2378 if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
2379 $this->label = $obj->label;
2380 $this->description = $obj->description;
2381 $this->other = $obj->other;
2382 }
2383 $this->multilangs[(string) $obj->lang]["rowid"] = (int) $obj->rowid;
2384 $this->multilangs[(string) $obj->lang]["label"] = $obj->label;
2385 $this->multilangs[(string) $obj->lang]["description"] = $obj->description;
2386 $this->multilangs[(string) $obj->lang]["other"] = $obj->other;
2387 }
2388
2389 // Load the extrafields of each translation, only when asked, because this method is called by fetch()
2390 if ($loadextrafields && !empty($this->multilangs)) {
2391 $extrafields = new ExtraFields($this->db);
2392 $extrafields->fetch_name_optionals_label('product_lang');
2393 if (!empty($extrafields->attributes['product_lang']['count'])) {
2394 $productlang = new ProductLang($this->db);
2395 foreach ($this->multilangs as $langcode => $value) {
2396 $productlang->id = $value['rowid'];
2397 $productlang->array_options = array();
2398 $productlang->fetch_optionals();
2399 $this->multilangs[$langcode]['array_options'] = $productlang->array_options;
2400 }
2401 }
2402 }
2403
2404 return 1;
2405 } else {
2406 $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
2407 return -1;
2408 }
2409 }
2410
2417 private function getArrayForPriceCompare($level = 0)
2418 {
2419 $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
2420
2421 foreach ($testExit as $field) {
2422 if (!isset($this->$field)) {
2423 return array();
2424 }
2425 $tmparray = $this->$field;
2426 if (!isset($tmparray[$level])) {
2427 return array();
2428 }
2429 }
2430
2431 $lastPrice = array(
2432 'level' => $level ? $level : 1,
2433 'multiprices' => (float) $this->multiprices[$level],
2434 'multiprices_ttc' => (float) $this->multiprices_ttc[$level],
2435 'multiprices_base_type' => $this->multiprices_base_type[$level],
2436 'multiprices_min' => (float) $this->multiprices_min[$level],
2437 'multiprices_min_ttc' => (float) $this->multiprices_min_ttc[$level],
2438 'multiprices_tva_tx' => (float) $this->multiprices_tva_tx[$level],
2439 'multiprices_recuperableonly' => (float) $this->multiprices_recuperableonly[$level],
2440 );
2441
2442 return $lastPrice;
2443 }
2444
2445
2446 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2454 private function _log_price($user, $level = 0)
2455 {
2456 // phpcs:enable
2457 global $conf;
2458
2459 $now = dol_now();
2460
2461 // Clean parameters
2462 if (empty($this->price_by_qty)) {
2463 $this->price_by_qty = 0;
2464 }
2465
2466 // Add new price
2467 $sql = "INSERT INTO ".$this->db->prefix()."product_price(price_level,date_price, fk_product, fk_user_author, price_label, price, price_ttc, price_base_type,tosell, tva_tx, default_vat_code, recuperableonly,";
2468 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
2469 $sql .= " VALUES(".($level ? ((int) $level) : 1).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $user->id).", ".(empty($this->price_label) ? "null" : "'".$this->db->escape($this->price_label)."'").",";
2470 $sql .= " ".((float) price2num($this->price)).", ".((float) price2num($this->price_ttc)).",'".$this->db->escape($this->price_base_type)."',".((int) $this->status).", ".((float) price2num($this->tva_tx)).",";
2471 $sql .= " ".($this->default_vat_code ? ("'".$this->db->escape($this->default_vat_code)."'") : "null").", ".((int) $this->tva_npr).",";
2472 $sql .= " ".price2num($this->localtax1_tx).", ".price2num($this->localtax2_tx).", '".$this->db->escape($this->localtax1_type)."', '".$this->db->escape($this->localtax2_type)."', ".price2num($this->price_min).", ".price2num($this->price_min_ttc).", ".price2num($this->price_by_qty).", ".((int) $conf->entity).",".($this->fk_price_expression > 0 ? ((int) $this->fk_price_expression) : 'null');
2473 $sql .= ")";
2474
2475 dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
2476 $resql = $this->db->query($sql);
2477 if (!$resql) {
2478 $this->error = $this->db->lasterror();
2479 dol_print_error($this->db);
2480 return -1;
2481 } else {
2482 return 1;
2483 }
2484 }
2485
2486
2487 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2495 public function log_price_delete($user, $rowid)
2496 {
2497 // phpcs:enable
2498 $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
2499 $sql .= " WHERE fk_product_price = ".((int) $rowid);
2500 $sql .= " AND fk_product_price IN (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = ".((int) $this->id).")";
2501 $resql = $this->db->query($sql);
2502
2503 $sql = "DELETE FROM ".$this->db->prefix()."product_price_extrafields";
2504 $sql .= " WHERE fk_object = ".((int) $rowid);
2505 $resql = $this->db->query($sql);
2506
2507 $sql = "DELETE FROM ".$this->db->prefix()."product_price";
2508 $sql .= " WHERE rowid = ".((int) $rowid);
2509 $sql .= " AND fk_product = ".((int) $this->id);
2510 $resql = $this->db->query($sql);
2511 if ($resql) {
2512 return 1;
2513 } else {
2514 $this->error = $this->db->lasterror();
2515 return -1;
2516 }
2517 }
2518
2527 public function fetchAllPriceLogs($id)
2528 {
2529 dol_syslog(__METHOD__, LOG_DEBUG);
2530
2531 $logs = array();
2532
2533 $sql = "SELECT";
2534 $sql .= " pl.rowid as log_rowid,";
2535 $sql .= " pl.datec,";
2536 $sql .= " pl.price,";
2537 $sql .= " pl.quantity,";
2538 $sql .= " pl.fk_user,";
2539 $sql .= " pl.multicurrency_code,";
2540 $sql .= " pl.multicurrency_price,";
2541 // Supplier info
2542 $sql .= " pp.fk_soc as supplier_id,";
2543 $sql .= " pp.ref_fourn as supplier_ref,";
2544 $sql .= " pp.entity as entity";
2545
2546 $sql .= " FROM " . $this->db->prefix() . "product_fournisseur_price_log as pl";
2547 $sql .= " INNER JOIN " . $this->db->prefix() . "product_fournisseur_price as pp ON pl.fk_product_fournisseur = pp.rowid";
2548
2549 $sql .= " WHERE pp.fk_product = " . ((int) $id);
2550 $sql .= " AND pp.entity IN (" . getEntity('product') . ")";
2551 $sql .= " ORDER BY pl.datec DESC";
2552
2553 $resql = $this->db->query($sql);
2554 if ($resql) {
2555 while ($obj = $this->db->fetch_object($resql)) {
2556 if (is_string($obj->datec)) {
2557 $obj->datec = strtotime($obj->datec);
2558 }
2559 $logs[] = $obj;
2560 }
2561 $this->db->free($resql);
2562 } else {
2563 $this->error = $this->db->lasterror();
2564 }
2565
2566 return $logs;
2567 }
2568
2578 public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
2579 {
2580 global $hookmanager, $action;
2581
2582 // Call hook if any
2583 if (is_object($hookmanager)) {
2584 $parameters = array('thirdparty_seller' => $thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
2585 // Note that $action and $object may have been modified by some hooks
2586 $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
2587 if ($reshook > 0) {
2588 return $hookmanager->resArray;
2589 }
2590 }
2591
2592 // Update if prices fields are defined
2593 $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
2594 $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
2595 if (empty($tva_tx)) {
2596 $tva_npr = 0;
2597 }
2598
2599 $pu_ht = $this->price;
2600 $pu_ttc = $this->price_ttc;
2601 $price_min = $this->price_min;
2602 $price_min_ttc = $this->price_min_ttc;
2603 $price_base_type = (empty($this->price_base_type) ? 'HT' : $this->price_base_type);
2604
2605 // if price by customer / level
2606 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
2607 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
2608
2609 $prodcustprice = new ProductCustomerPrice($this->db);
2610
2611 $filter = array('t.fk_product' => (string) $this->id, 't.fk_soc' => (string) $thirdparty_buyer->id);
2612
2613 // If a price per customer exist
2614 $pricebycustomerexist = false;
2615 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
2616 if ($result) {
2617 if (count($prodcustprice->lines) > 0) {
2618 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
2619 foreach ($prodcustprice->lines as $k => $custprice_line) {
2620 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
2621 $pricebycustomerexist = true;
2622 $pu_ht = price($custprice_line->price);
2623 $price_min = price($custprice_line->price_min);
2624 $price_min_ttc = price($custprice_line->price_min_ttc);
2625 $pu_ttc = price($custprice_line->price_ttc);
2626 $price_base_type = $custprice_line->price_base_type;
2627 $tva_tx = $custprice_line->tva_tx;
2628 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
2629 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
2630 }
2631 $tva_npr = $custprice_line->recuperableonly;
2632 if (empty($tva_tx)) {
2633 $tva_npr = 0;
2634 }
2635 break;
2636 }
2637 }
2638 }
2639 }
2640
2641 if (!$pricebycustomerexist && !empty($thirdparty_buyer->price_level)) {
2642 $pu_ht = isset($this->multiprices[$thirdparty_buyer->price_level]) ? $this->multiprices[$thirdparty_buyer->price_level] : 0;
2643 $pu_ttc = isset($this->multiprices_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_ttc[$thirdparty_buyer->price_level] : 0;
2644 $price_min = isset($this->multiprices_min[$thirdparty_buyer->price_level]) ? $this->multiprices_min[$thirdparty_buyer->price_level] : 0;
2645 $price_min_ttc = isset($this->multiprices_min_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_min_ttc[$thirdparty_buyer->price_level] : 0;
2646 $price_base_type = isset($this->multiprices_base_type[$thirdparty_buyer->price_level]) ? $this->multiprices_base_type[$thirdparty_buyer->price_level] : 'HT';
2647 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
2648 // using this option is a bug. kept for backward compatibility
2649 if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
2650 $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
2651 }
2652 if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
2653 $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
2654 }
2655 if (empty($tva_tx)) {
2656 $tva_npr = 0;
2657 }
2658 }
2659 }
2660 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES') && !empty($thirdparty_buyer->price_level)) { // // If price per segment
2661 $pu_ht = isset($this->multiprices[$thirdparty_buyer->price_level]) ? $this->multiprices[$thirdparty_buyer->price_level] : 0;
2662 $pu_ttc = isset($this->multiprices_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_ttc[$thirdparty_buyer->price_level] : 0;
2663 $price_min = isset($this->multiprices_min[$thirdparty_buyer->price_level]) ? $this->multiprices_min[$thirdparty_buyer->price_level] : 0;
2664 $price_min_ttc = isset($this->multiprices_min_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_min_ttc[$thirdparty_buyer->price_level] : 0;
2665 $price_base_type = isset($this->multiprices_base_type[$thirdparty_buyer->price_level]) ? $this->multiprices_base_type[$thirdparty_buyer->price_level] : 'HT';
2666 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
2667 // using this option is a bug. kept for backward compatibility
2668 if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
2669 $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
2670 }
2671 if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
2672 $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
2673 }
2674 if (empty($tva_tx)) {
2675 $tva_npr = 0;
2676 }
2677 }
2678 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
2679 // If price per customer
2680 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
2681
2682 $prodcustprice = new ProductCustomerPrice($this->db);
2683
2684 $filter = array('t.fk_product' => (string) $this->id, 't.fk_soc' => (string) $thirdparty_buyer->id);
2685
2686 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
2687 if ($result) {
2688 if (count($prodcustprice->lines) > 0) {
2689 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
2690 foreach ($prodcustprice->lines as $k => $custprice_line) {
2691 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
2692 $pu_ht = price($custprice_line->price);
2693 $price_min = price($custprice_line->price_min);
2694 $price_min_ttc = price($custprice_line->price_min_ttc);
2695 $pu_ttc = price($custprice_line->price_ttc);
2696 $price_base_type = $custprice_line->price_base_type;
2697 $tva_tx = $custprice_line->tva_tx;
2698 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
2699 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
2700 }
2701 $tva_npr = $custprice_line->recuperableonly;
2702 if (empty($tva_tx)) {
2703 $tva_npr = 0;
2704 }
2705 break;
2706 }
2707 }
2708 }
2709 }
2710 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
2711 // If price per quantity
2712 if (!empty($this->prices_by_qty[0])) {
2713 // yes, this product has some prices per quantity
2714 // Search price into product_price_by_qty from $this->id
2715 foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
2716 if ($priceforthequantityarray['rowid'] != $pqp) {
2717 continue;
2718 }
2719 // We found the price
2720 if ($priceforthequantityarray['price_base_type'] == 'HT') {
2721 $pu_ht = $priceforthequantityarray['unitprice'];
2722 } else {
2723 $pu_ttc = $priceforthequantityarray['unitprice'];
2724 }
2725 break;
2726 }
2727 }
2728 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
2729 // If price per quantity and customer
2730 if (!empty($thirdparty_buyer->price_level)) {
2731 // The price of the level of the customer is the price to use when no price per quantity is selected
2732 $pu_ht = isset($this->multiprices[$thirdparty_buyer->price_level]) ? $this->multiprices[$thirdparty_buyer->price_level] : 0;
2733 $pu_ttc = isset($this->multiprices_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_ttc[$thirdparty_buyer->price_level] : 0;
2734 $price_min = isset($this->multiprices_min[$thirdparty_buyer->price_level]) ? $this->multiprices_min[$thirdparty_buyer->price_level] : 0;
2735 $price_min_ttc = isset($this->multiprices_min_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_min_ttc[$thirdparty_buyer->price_level] : 0;
2736 $price_base_type = empty($this->multiprices_base_type[$thirdparty_buyer->price_level]) ? 'HT' : $this->multiprices_base_type[$thirdparty_buyer->price_level];
2737 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
2738 // using this option is a bug. kept for backward compatibility
2739 if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
2740 $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
2741 }
2742 if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
2743 $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
2744 }
2745 if (empty($tva_tx)) {
2746 $tva_npr = 0;
2747 }
2748 }
2749 }
2750 if (!empty($thirdparty_buyer->price_level) && !empty($this->prices_by_qty[$thirdparty_buyer->price_level])) {
2751 // yes, this product has some prices per quantity
2752 // Search price into product_price_by_qty from $this->id
2753 foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
2754 if ($priceforthequantityarray['rowid'] != $pqp) {
2755 continue;
2756 }
2757 // We found the price
2758 if ($priceforthequantityarray['price_base_type'] == 'HT') {
2759 $pu_ht = $priceforthequantityarray['unitprice'];
2760 } else {
2761 $pu_ttc = $priceforthequantityarray['unitprice'];
2762 }
2763 break;
2764 }
2765 }
2766 }
2767
2768 $localtax1 = get_localtax((string) $tva_tx, 1, $thirdparty_buyer, $thirdparty_seller, $tva_npr);
2769 $localtax2 = get_localtax((string) $tva_tx, 2, $thirdparty_buyer, $thirdparty_seller, $tva_npr);
2770
2771 return array('pu_ht' => $pu_ht, 'pu_ttc' => $pu_ttc, 'price_min' => $price_min, 'price_min_ttc' => $price_min_ttc, 'price_base_type' => $price_base_type, 'tva_tx' => $tva_tx, 'tva_npr' => $tva_npr, 'localtax1' => $localtax1, 'localtax2' => $localtax2);
2772 }
2773
2774 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2788 public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
2789 {
2790 // phpcs:enable
2791 global $action, $hookmanager;
2792
2793 // Call hook if any
2794 if (is_object($hookmanager)) {
2795 $parameters = array(
2796 'prodfournprice' => $prodfournprice,
2797 'qty' => $qty,
2798 'product_id' => $product_id,
2799 'fourn_ref' => $fourn_ref,
2800 'fk_soc' => $fk_soc,
2801 );
2802 // Note that $action and $object may have been modified by some hooks
2803 $reshook = $hookmanager->executeHooks('getBuyPrice', $parameters, $this, $action);
2804 if ($reshook > 0) {
2805 return $hookmanager->resArray;
2806 }
2807 }
2808
2809 $result = 0;
2810
2811 // We do a first search with a select by searching with couple prodfournprice and qty only (later we will search on triplet qty/product_id/fourn_ref)
2812 $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
2813 $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.default_vat_code, pfp.fk_supplier_price_expression,";
2814 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
2815 $sql .= " pfp.packaging";
2816 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
2817 $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
2818 if ($qty > 0) {
2819 $sql .= " AND pfp.quantity <= ".((float) $qty);
2820 }
2821 $sql .= " ORDER BY pfp.quantity DESC";
2822
2823 dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
2824 $resql = $this->db->query($sql);
2825 if ($resql) {
2826 $obj = $this->db->fetch_object($resql);
2827 if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
2828 if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
2829 $prod_supplier = new ProductFournisseur($this->db);
2830 $prod_supplier->product_fourn_price_id = $obj->rowid;
2831 $prod_supplier->id = $obj->fk_product;
2832 $prod_supplier->fourn_qty = $obj->quantity;
2833 $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2834 $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2835
2836 include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2837 $priceparser = new PriceParser($this->db);
2838 $price_result = $priceparser->parseProductSupplier($prod_supplier);
2839 if ($price_result >= 0) {
2840 $obj->price = $price_result;
2841 }
2842 }
2843 $this->product_fourn_price_id = $obj->rowid;
2844 $this->buyprice = $obj->price; // deprecated
2845 $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
2846 $this->fourn_price_base_type = 'HT'; // Price base type
2847 $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2848 $this->ref_fourn = $obj->ref_supplier; // deprecated
2849 $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2850 $this->desc_supplier = $obj->desc_supplier; // desc supplier
2851 $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2852 $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2853 $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
2854 $this->fourn_multicurrency_price = $obj->multicurrency_price;
2855 $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2856 $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2857 $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2858 $this->fourn_multicurrency_code = $obj->multicurrency_code;
2859 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2860 $this->packaging = (float) $obj->packaging;
2861 }
2862 // Expose the supplier minimum purchase quantity so callers can enforce qty_min
2863 // on top of packaging-multiple rounding (#38783). pfp.quantity is the lowest
2864 // qty for which this price line is valid; for "below-min" callers this is the
2865 // floor they must round up to.
2866 $this->fourn_qty = $obj->quantity;
2867 $result = $obj->fk_product;
2868 return $result;
2869 } else { // If not found
2870 // We do a second search by doing a select again but searching with less reliable criteria: couple qty/id product, and if set fourn_ref or fk_soc.
2871 $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
2872 $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.default_vat_code, pfp.fk_supplier_price_expression,";
2873 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
2874 $sql .= " pfp.packaging";
2875 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
2876 $sql .= " WHERE 1 = 1";
2877 if ($product_id > 0) {
2878 $sql .= " AND pfp.fk_product = ".((int) $product_id);
2879 }
2880 if ($fourn_ref != 'none') {
2881 $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
2882 }
2883 if ($fk_soc > 0) {
2884 $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
2885 }
2886 if ($qty > 0) {
2887 $sql .= " AND pfp.quantity <= ".((float) $qty);
2888 }
2889 $sql .= " ORDER BY pfp.quantity DESC";
2890 $sql .= " LIMIT 1";
2891
2892 dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
2893 $resql = $this->db->query($sql);
2894 if ($resql) {
2895 $obj = $this->db->fetch_object($resql);
2896 if ($obj && $obj->quantity > 0) { // If found
2897 if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
2898 $prod_supplier = new ProductFournisseur($this->db);
2899 $prod_supplier->product_fourn_price_id = $obj->rowid;
2900 $prod_supplier->id = $obj->fk_product;
2901 $prod_supplier->fourn_qty = $obj->quantity;
2902 $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2903 $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2904
2905 include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2906 $priceparser = new PriceParser($this->db);
2907 $price_result = $priceparser->parseProductSupplier($prod_supplier);
2908 if ($price_result >= 0) {
2909 $obj->price = $price_result;
2910 }
2911 }
2912 $this->product_fourn_price_id = $obj->rowid;
2913 $this->buyprice = $obj->price; // deprecated
2914 $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
2915 $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
2916 $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
2917 $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2918 $this->ref_fourn = $obj->ref_supplier; // deprecated
2919 $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2920 $this->desc_supplier = $obj->desc_supplier; // desc supplier
2921 $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2922 $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2923 $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
2924 $this->fourn_multicurrency_price = $obj->multicurrency_price;
2925 $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2926 $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2927 $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2928 $this->fourn_multicurrency_code = $obj->multicurrency_code;
2929 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2930 $this->packaging = (float) $obj->packaging;
2931 }
2932 // Expose pfp.quantity so callers can enforce qty_min on top of packaging
2933 // rounding (#38783).
2934 $this->fourn_qty = $obj->quantity;
2935 $result = $obj->fk_product;
2936 return $result;
2937 } else {
2938 return -1; // This product does not exist with this supplier price ID, or it exists but with insufficient quantity; nor does it exist for the product/supplier ref pair in the required quantity.
2939 }
2940 } else {
2941 $this->error = $this->db->lasterror();
2942 return -3;
2943 }
2944 }
2945 } else {
2946 $this->error = $this->db->lasterror();
2947 return -2;
2948 }
2949 }
2950
2951
2970 public function updatePrice($newprice, $newpricebase, $user, $newvat = null, $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '', $price_label = '', $notrigger = 0)
2971 {
2972 $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
2973
2974 $id = $this->id;
2975
2976 dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
2977
2978 // Clean parameters
2979 if (empty($this->tva_tx)) {
2980 $this->tva_tx = 0.0;
2981 }
2982 if (empty($newnpr)) {
2983 $newnpr = 0.0;
2984 }
2985 if (empty($newminprice)) {
2986 $newminprice = 0.0;
2987 }
2988
2989 // Check parameters
2990 if ($newvat === null || $newvat == '') { // Maintain '' for backwards compatibility
2991 $newvat = (float) $this->tva_tx;
2992 }
2993
2994 $localtaxtype1 = '';
2995 $localtaxtype2 = '';
2996
2997 // If multiprices are enabled, then we check if the current product is subject to price autogeneration
2998 // Price will be modified ONLY when the first one is the one that is being modified
2999 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
3000 return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
3001 }
3002
3003 if (!empty($newminprice) && ($newminprice > $newprice)) {
3004 $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
3005 return -1;
3006 }
3007
3008 if ($newprice === 0 || $newprice !== '') {
3009 if ($newpricebase == 'TTC') {
3010 $price_ttc = (float) price2num($newprice, 'MU');
3011 $price = (float) price2num($newprice) / (1 + ((float) $newvat / 100));
3012 $price = (float) price2num($price, 'MU');
3013
3014 if ((string) $newminprice != '0') {
3015 $price_min_ttc = (float) price2num($newminprice, 'MU');
3016 $price_min = (float) price2num($newminprice) / (1 + ($newvat / 100));
3017 $price_min = (float) price2num($price_min, 'MU');
3018 } else {
3019 $price_min = 0.0;
3020 $price_min_ttc = 0.0;
3021 }
3022 } else {
3023 $price = (float) price2num($newprice, 'MU');
3024 $price_ttc = ($newnpr != 1) ? (float) price2num($newprice) * (1 + ($newvat / 100)) : $price;
3025 $price_ttc = (float) price2num($price_ttc, 'MU');
3026
3027 if ((string) $newminprice != '0') {
3028 $price_min = (float) price2num($newminprice, 'MU');
3029 $price_min_ttc = (float) price2num($newminprice) * (1 + ($newvat / 100));
3030 $price_min_ttc = (float) price2num($price_min_ttc, 'MU');
3031 //print 'X'.$newminprice.'-'.$price_min;
3032 } else {
3033 $price_min = 0.0;
3034 $price_min_ttc = 0.0;
3035 }
3036 }
3037 //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
3038 if (count($localtaxes_array) > 0) {
3039 $localtaxtype1 = $localtaxes_array['0'];
3040 $localtax1 = $localtaxes_array['1'];
3041 $localtaxtype2 = $localtaxes_array['2'];
3042 $localtax2 = $localtaxes_array['3'];
3043 } else {
3044 // if array empty, we try to use the vat code
3045 if (!empty($newdefaultvatcode)) {
3046 global $mysoc;
3047 // Get record from code
3048 $sql = "SELECT t.rowid, t.code, t.recuperableonly as tva_npr, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
3049 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3050 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($mysoc->country_code)."'";
3051 $sql .= " AND t.taux = ".((float) $newdefaultvatcode)." AND t.active = 1";
3052 $sql .= " AND t.code = '".$this->db->escape($newdefaultvatcode)."'";
3053 $resql = $this->db->query($sql);
3054 if ($resql) {
3055 $obj = $this->db->fetch_object($resql);
3056 if ($obj) {
3057 $npr = $obj->tva_npr;
3058 $localtax1 = $obj->localtax1;
3059 $localtax2 = $obj->localtax2;
3060 $localtaxtype1 = $obj->localtax1_type;
3061 $localtaxtype2 = $obj->localtax2_type;
3062 }
3063 }
3064 } else {
3065 // old method. deprecated because we can't retrieve type
3066 $localtaxtype1 = '0';
3067 $localtax1 = get_localtax($newvat, 1);
3068 $localtaxtype2 = '0';
3069 $localtax2 = get_localtax($newvat, 2);
3070 }
3071 }
3072 if (empty($localtax1)) {
3073 $localtax1 = 0; // If = '' then = 0
3074 }
3075 if (empty($localtax2)) {
3076 $localtax2 = 0; // If = '' then = 0
3077 }
3078
3079 $this->db->begin();
3080
3081 // The price columns of the table product hold the default price of the product, that is the price of the level 1
3082 // when multiprices are enabled (level is 0 when they are not). So they must not be overwritten by another level.
3083 // The vat columns are however shared by all levels, so they are always updated.
3084 $updatedefaultprice = (empty($level) || $level == 1);
3085
3086 // Don't put quotes here on decimal numbers.
3087 // This causes storage with base rounding instead of exact values.
3088 $sql = "UPDATE ".$this->db->prefix()."product SET";
3089 if ($updatedefaultprice) {
3090 $sql .= " price_base_type = '".$this->db->escape($newpricebase)."',";
3091 $sql .= " price = ".(float) $price.",";
3092 $sql .= " price_ttc = ".(float) $price_ttc.",";
3093 $sql .= " price_min = ".(float) $price_min.",";
3094 $sql .= " price_min_ttc = ".(float) $price_min_ttc.",";
3095 $sql .= " price_label = ".(!empty($price_label) ? "'".$this->db->escape($price_label)."'" : "null").",";
3096 }
3097 $sql .= " localtax1_tx = ".($localtax1 >= 0 ? (float) $localtax1 : 'NULL').",";
3098 $sql .= " localtax2_tx = ".($localtax2 >= 0 ? (float) $localtax2 : 'NULL').",";
3099 $sql .= " localtax1_type = ".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
3100 $sql .= " localtax2_type = ".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
3101 $sql .= " default_vat_code = ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
3102 $sql .= " tva_tx = ".(float) price2num($newvat).",";
3103 $sql .= " recuperableonly = '".$this->db->escape((string) $newnpr)."'";
3104 $sql .= " WHERE rowid = ".((int) $id);
3105
3106 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3107 $resql = $this->db->query($sql);
3108 if ($resql) {
3109 $this->multiprices[$level] = $price;
3110 $this->multiprices_ttc[$level] = $price_ttc;
3111 $this->multiprices_min[$level] = $price_min;
3112 $this->multiprices_min_ttc[$level] = $price_min_ttc;
3113 $this->multiprices_base_type[$level] = $newpricebase;
3114 $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
3115 $this->multiprices_tva_tx[$level] = $newvat;
3116 $this->multiprices_recuperableonly[$level] = $newnpr;
3117
3118 // Save the default price of the product to restore it after the log if we are updating another level
3119 // (_log_price() reads the price into the properties of the object to save the price of the level).
3120 $savdefaultprice = array($this->price, $this->price_label, $this->price_ttc, $this->price_min, $this->price_min_ttc, $this->price_base_type);
3121
3122 $this->price = $price;
3123 $this->price_label = $price_label;
3124 $this->price_ttc = $price_ttc;
3125 $this->price_min = $price_min;
3126 $this->price_min_ttc = $price_min_ttc;
3127 $this->price_base_type = $newpricebase;
3128 $this->default_vat_code = $newdefaultvatcode;
3129 $this->tva_tx = $newvat;
3130 $this->tva_npr = $newnpr;
3131
3132 //Local taxes
3133 $this->localtax1_tx = $localtax1;
3134 $this->localtax2_tx = $localtax2;
3135 $this->localtax1_type = $localtaxtype1;
3136 $this->localtax2_type = $localtaxtype2;
3137
3138 // Price by quantity
3139 // Each change of price adds a new line into product_price and the prices by quantity are attached to one line.
3140 // So when they stay enabled, we must find the current line to move its prices by quantity to the new one.
3141 $oldpriceid = 0;
3142 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3143 // Same selection of the current price line as in fetch()
3144 $sqlpbq = "SELECT rowid, price_by_qty FROM ".$this->db->prefix()."product_price";
3145 $sqlpbq .= " WHERE fk_product = ".((int) $id);
3146 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3147 $sqlpbq .= " AND entity IN (".getEntity('productprice').")";
3148 $sqlpbq .= " AND price_level = ".((int) ($level ? $level : 1));
3149 }
3150 $sqlpbq .= " ORDER BY date_price DESC, rowid DESC";
3151 $sqlpbq .= " LIMIT 1";
3152 $resqlpbq = $this->db->query($sqlpbq);
3153 if ($resqlpbq) {
3154 $objpbq = $this->db->fetch_object($resqlpbq);
3155 if ($objpbq) {
3156 $oldpriceid = (int) $objpbq->rowid;
3157 if (empty($newpbq)) {
3158 $newpbq = (int) $objpbq->price_by_qty; // Keep the current state
3159 }
3160 }
3161 }
3162 }
3163 if ($newpbq < 0) {
3164 $newpbq = 0;
3165 }
3166 $this->price_by_qty = $newpbq;
3167
3168 // check if price have really change before log
3169 $newPriceData = $this->getArrayForPriceCompare($level);
3170 if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || (!getDolGlobalString('PRODUIT_MULTIPRICES') && !getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
3171 $this->_log_price($user, $level); // Save price for level into table product_price
3172
3173 // Move the prices by quantity of the previous price line to the new one, else they are lost
3174 if ($newpbq == 1 && $oldpriceid > 0) {
3175 $newpriceid = (int) $this->db->last_insert_id($this->db->prefix()."product_price");
3176 if ($newpriceid > 0 && $newpriceid != $oldpriceid) {
3177 $sqlpbq = "UPDATE ".$this->db->prefix()."product_price_by_qty";
3178 $sqlpbq .= " SET fk_product_price = ".((int) $newpriceid);
3179 $sqlpbq .= " WHERE fk_product_price = ".((int) $oldpriceid);
3180 if (!$this->db->query($sqlpbq)) {
3181 $this->error = $this->db->lasterror();
3182 $this->db->rollback();
3183 return -1;
3184 }
3185 }
3186 }
3187 }
3188
3189 if (!$updatedefaultprice) {
3190 // The price of the level is now saved, so we can restore the default price of the product
3191 list($this->price, $this->price_label, $this->price_ttc, $this->price_min, $this->price_min_ttc, $this->price_base_type) = $savdefaultprice;
3192 }
3193
3194 $this->level = $level; // Store level of price edited for trigger
3195
3196 // Call trigger
3197 if (!$notrigger) {
3198 $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
3199 if ($result < 0) {
3200 $this->db->rollback();
3201 return -1;
3202 }
3203 }
3204 // End call triggers
3205
3206 $this->db->commit();
3207 } else {
3208 $this->db->rollback();
3209 $this->error = $this->db->lasterror();
3210 return -1;
3211 }
3212 }
3213
3214 return 1;
3215 }
3216
3224 public function setPriceExpression($expression_id)
3225 {
3226 global $user;
3227
3228 $this->fk_price_expression = $expression_id;
3229
3230 return $this->update($this->id, $user);
3231 }
3232
3245 public function fetch($id = 0, $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
3246 {
3247 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3248
3249 global $conf;
3250
3251 dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
3252
3253 // Check parameters
3254 if (!$id && !$ref && !$ref_ext && !$barcode) {
3255 $this->error = 'ErrorWrongParameters';
3256 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
3257 return -1;
3258 }
3259
3260 $sql = "SELECT p.rowid, p.ref, p.ref_ext, p.label, p.description, p.url, p.note_public, p.note as note_private, p.customcode, p.fk_country, p.fk_state, p.lifetime, p.qc_frequency, p.price, p.price_ttc,";
3261 $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly as tva_npr, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
3262 $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.fk_default_workstation, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
3263 $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.last_main_doc,";
3264 $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished, p.fk_default_bom, p.mandatory_period, p.packaging,";
3265 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
3266 $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
3267 } else {
3268 $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
3269 }
3270
3271 // For MultiCompany
3272 // PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
3273 $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
3274 $separatedStock = false; // Set to true will count stock from subtable llx_product_stock. It is slower than using denormalized field 'stock', but it is required when using multientity and shared warehouses.
3275 $visibleWarehousesEntities = $conf->entity;
3276 if (getDolGlobalString('MULTICOMPANY_PRODUCT_SHARING_ENABLED')) {
3277 if (getDolGlobalString('MULTICOMPANY_PMP_PER_ENTITY_ENABLED')) {
3278 $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
3279 if ($this->db->num_rows($checkPMPPerEntity) > 0) {
3280 $separatedEntityPMP = true;
3281 }
3282 }
3283 global $mc;
3284 $separatedStock = true;
3285 if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
3286 $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
3287 }
3288 }
3289 if ($separatedEntityPMP) {
3290 $sql .= " ppe.pmp,";
3291 } else {
3292 $sql .= " p.pmp,";
3293 }
3294 $sql .= " p.datec, GREATEST(p.tms, COALESCE(pef.tms, p.tms)) AS tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.sell_or_eat_by_mandatory, p.batch_mask, p.fk_unit,";
3295 $sql .= " p.fk_price_expression, p.price_autogen, p.stockable_product, p.model_pdf,";
3296 $sql .= " p.price_label,";
3297 if ($separatedStock) {
3298 $sql .= " SUM(sp.reel) as stock";
3299 } else {
3300 $sql .= " p.stock";
3301 }
3302 $sql .= " FROM ".$this->db->prefix()."product as p";
3303 $sql .= " LEFT JOIN ".$this->db->prefix()."product_extrafields as pef ON pef.fk_object=p.rowid";
3304 if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') || $separatedEntityPMP) {
3305 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
3306 }
3307 if ($separatedStock) {
3308 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as sp ON sp.fk_product = p.rowid AND sp.fk_entrepot IN (SELECT rowid FROM ".$this->db->prefix()."entrepot WHERE entity IN (".$this->db->sanitize($visibleWarehousesEntities)."))";
3309 }
3310
3311 if ($id) {
3312 $sql .= " WHERE p.rowid = ".((int) $id);
3313 } else {
3314 $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
3315 if ($ref) {
3316 $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
3317 } elseif ($ref_ext) {
3318 $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
3319 } elseif ($barcode) {
3320 $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
3321 }
3322 }
3323 if ($separatedStock) {
3324 $sql .= " GROUP BY p.rowid, p.ref, p.ref_ext, p.label, p.description, p.url, p.note_public, p.note, p.customcode, p.fk_country, p.fk_state, p.lifetime, p.qc_frequency, p.price, p.price_ttc,";
3325 $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
3326 $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.fk_default_workstation, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
3327 $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
3328 $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished, p.fk_default_bom, p.mandatory_period, p.packaging,";
3329 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
3330 $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
3331 } else {
3332 $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
3333 }
3334 if ($separatedEntityPMP) {
3335 $sql .= " ppe.pmp,";
3336 } else {
3337 $sql .= " p.pmp,";
3338 }
3339 $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.sell_or_eat_by_mandatory, p.batch_mask, p.fk_unit,";
3340 $sql .= " p.fk_price_expression, p.price_autogen, p.stockable_product, p.model_pdf,";
3341 $sql .= " p.price_label";
3342 // can't be false TODO fix
3343 // if (!$separatedStock) {
3344 // $sql .= ", p.stock";
3345 // }
3346 }
3347
3348 $resql = $this->db->query($sql);
3349 if ($resql) {
3350 unset($this->oldcopy);
3351
3352 if ($this->db->num_rows($resql) > 0) {
3353 $obj = $this->db->fetch_object($resql);
3354
3355 $this->id = $obj->rowid;
3356 $this->ref = $obj->ref;
3357 $this->ref_ext = $obj->ref_ext;
3358 $this->label = $obj->label;
3359 $this->description = $obj->description;
3360 $this->url = $obj->url;
3361 $this->note_public = $obj->note_public;
3362 $this->note_private = $obj->note_private;
3363 $this->note = $obj->note_private; // deprecated
3364
3365 $this->type = $obj->fk_product_type;
3366 $this->price_label = $obj->price_label;
3367 $this->status = $obj->tosell;
3368 $this->status_buy = $obj->tobuy;
3369 $this->status_batch = $obj->tobatch;
3370 $this->sell_or_eat_by_mandatory = $obj->sell_or_eat_by_mandatory;
3371 $this->batch_mask = $obj->batch_mask;
3372
3373 $this->customcode = $obj->customcode;
3374 $this->country_id = $obj->fk_country;
3375 $this->country_code = getCountry($this->country_id, '2', $this->db);
3376 $this->state_id = $obj->fk_state;
3377 $this->lifetime = $obj->lifetime;
3378 $this->qc_frequency = $obj->qc_frequency;
3379 $this->price = $obj->price;
3380 $this->price_ttc = $obj->price_ttc;
3381 $this->price_min = $obj->price_min;
3382 $this->price_min_ttc = $obj->price_min_ttc;
3383 $this->price_base_type = (empty($obj->price_base_type) ? 'HT' : $obj->price_base_type);
3384 $this->cost_price = isset($obj->cost_price) ? (float) $obj->cost_price : null;
3385 $this->default_vat_code = $obj->default_vat_code;
3386 $this->tva_tx = $obj->tva_tx;
3388 $this->tva_npr = $obj->tva_npr;
3390 $this->localtax1_tx = $obj->localtax1_tx;
3391 $this->localtax2_tx = $obj->localtax2_tx;
3392 $this->localtax1_type = $obj->localtax1_type;
3393 $this->localtax2_type = $obj->localtax2_type;
3394
3395 $this->finished = $obj->finished;
3396 $this->fk_default_bom = $obj->fk_default_bom;
3397
3398 $this->duration = $obj->duration;
3399 $matches = [];
3400 preg_match('/([\d.]+)(\w+)/', $obj->duration, $matches);
3401 $this->duration_value = !empty($matches[1]) ? (float) $matches[1] : 0;
3402 $this->duration_unit = !empty($matches[2]) ? (string) $matches[2] : null;
3403 $this->canvas = $obj->canvas;
3404 $this->net_measure = $obj->net_measure;
3405 $this->net_measure_units = $obj->net_measure_units;
3406 $this->weight = $obj->weight;
3407 $this->weight_units = (is_null($obj->weight_units) ? 0 : $obj->weight_units);
3408 $this->length = $obj->length;
3409 $this->length_units = (is_null($obj->length_units) ? 0 : $obj->length_units);
3410 $this->width = $obj->width;
3411 $this->width_units = (is_null($obj->width_units) ? 0 : $obj->width_units);
3412 $this->height = $obj->height;
3413 $this->height_units = (is_null($obj->height_units) ? 0 : $obj->height_units);
3414
3415 $this->surface = $obj->surface;
3416 $this->surface_units = (is_null($obj->surface_units) ? 0 : $obj->surface_units);
3417 $this->volume = $obj->volume;
3418 $this->volume_units = (is_null($obj->volume_units) ? 0 : $obj->volume_units);
3419 $this->barcode = $obj->barcode;
3420 $this->barcode_type = $obj->fk_barcode_type;
3421
3422 $this->accountancy_code_buy = $obj->accountancy_code_buy;
3423 $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
3424 $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
3425 $this->accountancy_code_sell = $obj->accountancy_code_sell;
3426 $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
3427 $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
3428
3429 $this->fk_default_warehouse = $obj->fk_default_warehouse;
3430 $this->fk_default_workstation = $obj->fk_default_workstation;
3431 $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
3432 $this->desiredstock = $obj->desiredstock;
3433 $this->stock_reel = $obj->stock;
3434 $this->stockable_product = $obj->stockable_product;
3435 $this->pmp = $obj->pmp;
3436
3437 $this->date_creation = $this->db->jdate($obj->datec);
3438 $this->date_modification = $this->db->jdate($obj->tms);
3439
3440 $this->import_key = $obj->import_key;
3441 $this->entity = $obj->entity;
3442
3443 $this->ref_ext = $obj->ref_ext;
3444 $this->fk_price_expression = $obj->fk_price_expression;
3445 $this->fk_unit = $obj->fk_unit;
3446 $this->price_autogen = $obj->price_autogen;
3447 $this->model_pdf = $obj->model_pdf;
3448 $this->last_main_doc = $obj->last_main_doc;
3449
3450 $this->mandatory_period = $obj->mandatory_period;
3451
3452 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
3453 $this->packaging = (float) $obj->packaging;
3454 }
3455
3456 $this->db->free($resql);
3457
3458 // fetch optionals attributes and labels
3459 $this->fetch_optionals();
3460
3461 // Multilangs
3462 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($ignore_lang_load)) {
3463 $this->getMultiLangs();
3464 }
3465
3466 // Load multiprices array
3467 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($ignore_price_load)) { // prices per segment
3468 $produit_multiprices_limit = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
3469 for ($i = 1; $i <= $produit_multiprices_limit; $i++) {
3470 $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
3471 $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
3472 $sql .= " ,price_label";
3473 $sql .= " FROM ".$this->db->prefix()."product_price";
3474 $sql .= " WHERE entity IN (".getEntity('productprice').")";
3475 $sql .= " AND price_level=".((int) $i);
3476 $sql .= " AND fk_product = ".((int) $this->id);
3477 $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
3478 $sql .= " LIMIT 1"; // Only the first one
3479 $resql = $this->db->query($sql);
3480 if ($resql) {
3481 $result = $this->db->fetch_array($resql);
3482
3483 $this->multiprices[$i] = $result ? $result["price"] : null;
3484 $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
3485 $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
3486 $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
3487 $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
3488 // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
3489 $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].(!empty($result['default_vat_code']) ? ' ('.$result['default_vat_code'].')' : '') : null;
3490 $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
3491
3492 // Price by quantity
3493 /*
3494 $this->prices_by_qty[$i]=$result["price_by_qty"];
3495 $this->prices_by_qty_id[$i]=$result["rowid"];
3496 // Get the pricelist according to the qty if flag is set
3497 if ($this->prices_by_qty[$i] == 1)
3498 {
3499 $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
3500 $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
3501 $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
3502 $sql.= " ORDER BY quantity ASC";
3503
3504 $resql = $this->db->query($sql);
3505 if ($resql)
3506 {
3507 $resultat=array();
3508 $ii=0;
3509 while ($result= $this->db->fetch_array($resql)) {
3510 $resultat[$ii]=array();
3511 $resultat[$ii]["rowid"]=$result["rowid"];
3512 $resultat[$ii]["price"]= $result["price"];
3513 $resultat[$ii]["unitprice"]= $result["unitprice"];
3514 $resultat[$ii]["quantity"]= $result["quantity"];
3515 $resultat[$ii]["remise_percent"]= $result["remise_percent"];
3516 $resultat[$ii]["remise"]= $result["remise"]; // deprecated
3517 $resultat[$ii]["price_base_type"]= $result["price_base_type"];
3518 $ii++;
3519 }
3520 $this->prices_by_qty_list[$i]=$resultat;
3521 }
3522 else
3523 {
3524 dol_print_error($this->db);
3525 return -1;
3526 }
3527 }*/
3528 } else {
3529 $this->error = $this->db->lasterror;
3530 return -1;
3531 }
3532 }
3533 } elseif ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($ignore_price_load)) { // prices per customers
3534 // Nothing loaded by default. List may be very long.
3535 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') && empty($ignore_price_load)) { // prices per quantity
3536 $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
3537 $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
3538 $sql .= " FROM ".$this->db->prefix()."product_price";
3539 $sql .= " WHERE fk_product = ".((int) $this->id);
3540 $sql .= " ORDER BY date_price DESC, rowid DESC";
3541 $sql .= " LIMIT 1";
3542
3543 $resql = $this->db->query($sql);
3544 if ($resql) {
3545 $result = $this->db->fetch_array($resql);
3546
3547 if ($result) {
3548 // Price by quantity
3549 $this->prices_by_qty[0] = $result["price_by_qty"];
3550 $this->prices_by_qty_id[0] = $result["rowid"];
3551 // Get the pricelist according to the qty if flag is set
3552 if ($this->prices_by_qty[0] == 1) {
3553 $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
3554 $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
3555 $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
3556 $sql .= " ORDER BY quantity ASC";
3557
3558 $resql = $this->db->query($sql);
3559 if ($resql) {
3560 $resultat = array();
3561 $ii = 0;
3562 while ($result = $this->db->fetch_array($resql)) {
3563 $resultat[$ii] = array();
3564 $resultat[$ii]["rowid"] = $result["rowid"];
3565 $resultat[$ii]["price"] = $result["price"];
3566 $resultat[$ii]["unitprice"] = $result["unitprice"];
3567 $resultat[$ii]["quantity"] = $result["quantity"];
3568 $resultat[$ii]["remise_percent"] = $result["remise_percent"];
3569 //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
3570 $resultat[$ii]["price_base_type"] = $result["price_base_type"];
3571 $ii++;
3572 }
3573 $this->prices_by_qty_list[0] = $resultat;
3574 } else {
3575 $this->error = $this->db->lasterror;
3576 return -1;
3577 }
3578 }
3579 }
3580 } else {
3581 $this->error = $this->db->lasterror;
3582 return -1;
3583 }
3584 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') && empty($ignore_price_load)) { // prices per customer and quantity
3585 $produit_multiprices_limit = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
3586 for ($i = 1; $i <= $produit_multiprices_limit; $i++) {
3587 $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
3588 $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
3589 $sql .= " FROM ".$this->db->prefix()."product_price";
3590 $sql .= " WHERE entity IN (".getEntity('productprice').")";
3591 $sql .= " AND price_level=".((int) $i);
3592 $sql .= " AND fk_product = ".((int) $this->id);
3593 $sql .= " ORDER BY date_price DESC, rowid DESC";
3594 $sql .= " LIMIT 1";
3595 $resql = $this->db->query($sql);
3596 if (!$resql) {
3597 $this->error = $this->db->lasterror;
3598 return -1;
3599 } else {
3600 $result = $this->db->fetch_array($resql);
3601 $this->multiprices[$i] = (!empty($result["price"]) ? $result["price"] : 0);
3602 $this->multiprices_ttc[$i] = (!empty($result["price_ttc"]) ? $result["price_ttc"] : 0);
3603 $this->multiprices_min[$i] = (!empty($result["price_min"]) ? $result["price_min"] : 0);
3604 $this->multiprices_min_ttc[$i] = (!empty($result["price_min_ttc"]) ? $result["price_min_ttc"] : 0);
3605 $this->multiprices_base_type[$i] = (!empty($result["price_base_type"]) ? $result["price_base_type"] : '');
3606 // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
3607 $this->multiprices_tva_tx[$i] = (!empty($result["tva_tx"]) ? $result["tva_tx"] : 0); // TODO Add ' ('.$result['default_vat_code'].')'
3608 $this->multiprices_recuperableonly[$i] = (!empty($result["recuperableonly"]) ? $result["recuperableonly"] : 0);
3609
3610 // Price by quantity
3611 $this->prices_by_qty[$i] = (!empty($result["price_by_qty"]) ? $result["price_by_qty"] : 0);
3612 $this->prices_by_qty_id[$i] = (!empty($result["rowid"]) ? $result["rowid"] : 0);
3613 // Get the pricelist according to the qty if flag is set
3614 if ($this->prices_by_qty[$i] == 1) {
3615 $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
3616 $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
3617 $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
3618 $sql .= " ORDER BY quantity ASC";
3619
3620 $resql = $this->db->query($sql);
3621 if ($resql) {
3622 $resultat = array();
3623 $ii = 0;
3624 while ($result = $this->db->fetch_array($resql)) {
3625 $resultat[$ii] = array();
3626 $resultat[$ii]["rowid"] = $result["rowid"];
3627 $resultat[$ii]["price"] = $result["price"];
3628 $resultat[$ii]["unitprice"] = $result["unitprice"];
3629 $resultat[$ii]["quantity"] = $result["quantity"];
3630 $resultat[$ii]["remise_percent"] = $result["remise_percent"];
3631 $resultat[$ii]["remise"] = $result["remise"]; // deprecated
3632 $resultat[$ii]["price_base_type"] = $result["price_base_type"];
3633 $ii++;
3634 }
3635 $this->prices_by_qty_list[$i] = $resultat;
3636 } else {
3637 $this->error = $this->db->lasterror;
3638 return -1;
3639 }
3640 }
3641 }
3642 }
3643 }
3644
3645 if (isModEnabled('dynamicprices') && !empty($this->fk_price_expression) && empty($ignore_expression)) {
3646 include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
3647 $priceparser = new PriceParser($this->db);
3648 $price_result = $priceparser->parseProduct($this);
3649 if ($price_result >= 0) {
3650 $this->price = $price_result;
3651 // Calculate the VAT
3652 $this->price_ttc = (float) price2num($this->price) * (1 + ($this->tva_tx / 100));
3653 $this->price_ttc = (float) price2num($this->price_ttc, 'MU');
3654 }
3655 }
3656
3657 // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
3658 // Instead we just init the stock_warehouse array
3659 $this->stock_warehouse = array();
3660
3661 return 1;
3662 } else {
3663 return 0;
3664 }
3665 } else {
3666 $this->error = $this->db->lasterror();
3667 return -1;
3668 }
3669 }
3670
3671 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3678 public function load_stats_mo($socid = 0)
3679 {
3680 // phpcs:enable
3681 global $user, $hookmanager, $action;
3682
3683 $error = 0;
3684
3685 foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
3686 $this->stats_mo['customers_'.$role] = 0;
3687 $this->stats_mo['nb_'.$role] = 0;
3688 $this->stats_mo['qty_'.$role] = 0;
3689
3690 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3691 $sql .= " SUM(mp.qty) as qty";
3692 $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
3693 $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
3694 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
3695 $sql .= " INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $user->id);
3696 }
3697 $sql .= " WHERE ";
3698 $sql .= " c.entity IN (".getEntity('mo').")";
3699
3700 $sql .= " AND mp.fk_product = ".((int) $this->id);
3701 $sql .= " AND mp.role ='".$this->db->escape($role)."'";
3702 if ($socid > 0) {
3703 $sql .= " AND c.fk_soc = ".((int) $socid);
3704 }
3705
3706 $result = $this->db->query($sql);
3707 if ($result) {
3708 $obj = $this->db->fetch_object($result);
3709 $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
3710 $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
3711 $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
3712 } else {
3713 $this->error = $this->db->error();
3714 $error++;
3715 }
3716 }
3717
3718 if (!empty($error)) {
3719 return -1;
3720 }
3721
3722 $parameters = array('socid' => $socid);
3723 $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
3724 if ($reshook > 0) {
3725 $this->stats_mo = $hookmanager->resArray['stats_mo'];
3726 }
3727
3728 return 1;
3729 }
3730
3731 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3738 public function load_stats_bom($socid = 0)
3739 {
3740 // phpcs:enable
3741 global $hookmanager, $action;
3742
3743 $error = 0;
3744
3745 $this->stats_bom['nb_toproduce'] = 0;
3746 $this->stats_bom['nb_toconsume'] = 0;
3747 $this->stats_bom['qty_toproduce'] = 0;
3748 $this->stats_bom['qty_toconsume'] = 0;
3749
3750 $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
3751 $sql .= " SUM(b.qty) as qty_toproduce";
3752 $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
3753 $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom = b.rowid";
3754 $sql .= " WHERE ";
3755 $sql .= " b.entity IN (".getEntity('bom').")";
3756 $sql .= " AND b.fk_product =".((int) $this->id);
3757 $sql .= " GROUP BY b.rowid";
3758
3759 $result = $this->db->query($sql);
3760 if ($result) {
3761 $obj = $this->db->fetch_object($result);
3762 $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
3763 $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
3764 } else {
3765 $this->error = $this->db->error();
3766 $error++;
3767 }
3768
3769 $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
3770 $sql .= " SUM(bl.qty) as qty_toconsume";
3771 $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
3772 $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
3773 $sql .= " WHERE ";
3774 $sql .= " b.entity IN (".getEntity('bom').")";
3775 $sql .= " AND bl.fk_product =".((int) $this->id);
3776
3777 $result = $this->db->query($sql);
3778 if ($result) {
3779 $obj = $this->db->fetch_object($result);
3780 $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
3781 $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
3782 } else {
3783 $this->error = $this->db->error();
3784 $error++;
3785 }
3786
3787 if (!empty($error)) {
3788 return -1;
3789 }
3790
3791 $parameters = array('socid' => $socid);
3792 $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
3793 if ($reshook > 0) {
3794 $this->stats_bom = $hookmanager->resArray['stats_bom'];
3795 }
3796
3797 return 1;
3798 }
3799
3800 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3807 public function load_stats_propale($socid = 0)
3808 {
3809 // phpcs:enable
3810 global $user, $hookmanager, $action;
3811
3812 $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
3813 $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
3814 $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
3815 $sql .= ", ".$this->db->prefix()."propal as p";
3816 $sql .= ", ".$this->db->prefix()."societe as s";
3817 $sql .= " WHERE p.rowid = pd.fk_propal";
3818 $sql .= " AND p.fk_soc = s.rowid";
3819 $sql .= " AND p.entity IN (".getEntity('propal').")";
3820 $sql .= " AND pd.fk_product = ".((int) $this->id);
3821 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
3822 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = ".((int) $user->id).")";
3823 }
3824 //$sql.= " AND pr.fk_statut != 0";
3825 if ($socid > 0) {
3826 $sql .= " AND p.fk_soc = ".((int) $socid);
3827 }
3828 // Add where from hooks
3829 $parameters = array('socid' => $socid, 'type_element' => 'propal');
3830 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3831 $sql .= $hookmanager->resPrint;
3832 $result = $this->db->query($sql);
3833 if ($result) {
3834 $obj = $this->db->fetch_object($result);
3835 $this->stats_propale['customers'] = (int) $obj->nb_customers;
3836 $this->stats_propale['nb'] = (int) $obj->nb;
3837 $this->stats_propale['rows'] = (int) $obj->nb_rows;
3838 $this->stats_propale['qty'] = $obj->qty ? (float) $obj->qty : 0;
3839
3840 // if it's a virtual product, maybe it is in proposal by extension
3841 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
3842 $TFather = $this->getFather();
3843 if (is_array($TFather) && !empty($TFather)) {
3844 foreach ($TFather as &$fatherData) {
3845 $pFather = new Product($this->db);
3846 $pFather->id = (int) $fatherData['id'];
3847 $qtyCoef = $fatherData['qty'];
3848
3849 if ($fatherData['incdec']) {
3850 $pFather->load_stats_propale($socid);
3851
3852 if (!empty($pFather->stats_propale)) {
3853 $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
3854 $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
3855 $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
3856 $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
3857 }
3858 }
3859 }
3860 }
3861 }
3862
3863 $parameters = array('socid' => $socid);
3864 $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
3865 if ($reshook > 0) {
3866 $this->stats_propale = $hookmanager->resArray['stats_propale'];
3867 }
3868
3869 return 1;
3870 } else {
3871 $this->error = $this->db->error();
3872 return -1;
3873 }
3874 }
3875
3876
3877 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3884 public function load_stats_proposal_supplier($socid = 0)
3885 {
3886 // phpcs:enable
3887 global $user, $hookmanager, $action;
3888
3889 $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
3890 $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
3891 $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
3892 $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
3893 $sql .= ", ".$this->db->prefix()."societe as s";
3894 $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
3895 $sql .= " AND p.fk_soc = s.rowid";
3896 $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
3897 $sql .= " AND pd.fk_product = ".((int) $this->id);
3898 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
3899 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = ".((int) $user->id).")";
3900 }
3901 //$sql.= " AND pr.fk_statut != 0";
3902 if ($socid > 0) {
3903 $sql .= " AND p.fk_soc = ".((int) $socid);
3904 }
3905
3906 $result = $this->db->query($sql);
3907 if ($result) {
3908 $obj = $this->db->fetch_object($result);
3909 $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
3910 $this->stats_proposal_supplier['nb'] = $obj->nb;
3911 $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
3912 $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
3913
3914 $parameters = array('socid' => $socid);
3915 $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
3916 if ($reshook > 0) {
3917 $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
3918 }
3919
3920 return 1;
3921 } else {
3922 $this->error = $this->db->error();
3923 return -1;
3924 }
3925 }
3926
3927
3928 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3937 public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3938 {
3939 // phpcs:enable
3940 global $user, $hookmanager, $action;
3941
3942
3943 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3944 $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3945 $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
3946 $sql .= ", ".$this->db->prefix()."commande as c";
3947 $sql .= ", ".$this->db->prefix()."societe as s";
3948 $sql .= " WHERE c.rowid = cd.fk_commande";
3949 $sql .= " AND c.fk_soc = s.rowid";
3950 $sql .= " AND c.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'commande').")";
3951 $sql .= " AND cd.fk_product = ".((int) $this->id);
3952 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
3953 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $user->id).")";
3954 }
3955 if ($socid > 0) {
3956 $sql .= " AND c.fk_soc = ".((int) $socid);
3957 }
3958 if ($filtrestatut != '') {
3959 $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3960 }
3961 // Add where from hooks
3962 $parameters = array('socid' => $socid, 'type_element' => 'order');
3963 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3964 $sql .= $hookmanager->resPrint;
3965 $result = $this->db->query($sql);
3966 if ($result) {
3967 $obj = $this->db->fetch_object($result);
3968 $this->stats_commande['customers'] = (int) $obj->nb_customers;
3969 $this->stats_commande['nb'] = (int) $obj->nb;
3970 $this->stats_commande['rows'] = (int) $obj->nb_rows;
3971 $this->stats_commande['qty'] = $obj->qty ? (float) $obj->qty : 0;
3972
3973 // if it's a virtual product, maybe it is in order by extension
3974 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
3975 $TFather = $this->getFather();
3976 if (is_array($TFather) && !empty($TFather)) {
3977 foreach ($TFather as &$fatherData) {
3978 $pFather = new Product($this->db);
3979 $pFather->id = $fatherData['id'];
3980 $qtyCoef = $fatherData['qty'];
3981
3982 if ($fatherData['incdec']) {
3983 $pFather->load_stats_commande($socid, $filtrestatut);
3984
3985 $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
3986 $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
3987 $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
3988 $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
3989 }
3990 }
3991 }
3992 }
3993
3994 // If stock decrease is on invoice validation, the theoretical stock continue to
3995 // count the orders lines containing product in theoretical stock when some are already removed by invoice validation.
3996 if ($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
3997 // Do the request using an UNION instead of a OR in the JOIN that is very slow
3998 if (getDolGlobalString('DECREASE_ONLY_UNINVOICEDPRODUCTS')) {
3999 // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation but only if order not yet invoice.
4000 $adeduire = 0;
4001 $sql = "SELECT SUM(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
4002 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
4003 //$sql .= " JOIN ".$this->db->prefix()."element_element as el ON ((el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande') OR (el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture'))";
4004 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande' ";
4005 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_source = c.rowid";
4006 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
4007 $sql .= " AND EXISTS (SELECT cd.fk_product FROM ".$this->db->prefix()."commandedet as cd WHERE cd.fk_product = fd.fk_product AND cd.fk_commande = c.rowid)"; // We check that the product is in order lines
4008
4009 $sql .= " UNION ";
4010
4011 $sql .= "SELECT SUM(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
4012 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
4013 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture' ";
4014 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_target = c.rowid";
4015 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
4016 $sql .= " AND EXISTS (SELECT cd.fk_product FROM ".$this->db->prefix()."commandedet as cd WHERE cd.fk_product = fd.fk_product AND cd.fk_commande = c.rowid)"; // We check that the product is in order lines
4017 // Add where from hooks
4018 $parameters = array('socid' => $socid, 'type_element' => 'order');
4019 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
4020 $sql .= $hookmanager->resPrint;
4021 $resql = $this->db->query($sql);
4022 if ($resql) {
4023 while ($obj = $this->db->fetch_object($resql)) {
4024 $adeduire += (float) $obj->count;
4025 }
4026 }
4027
4028 $this->stats_commande['qty'] -= $adeduire;
4029 } else {
4030 // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is off, we make a compensation with lines of invoices linked to the order
4031 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4032
4033 // For every order having invoice already validated we need to decrease stock cause it's in physical stock
4034 $adeduire = 0;
4035 $sql = "SELECT sum(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
4036 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
4037 //$sql .= " JOIN ".$this->db->prefix()."element_element as el ON ((el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande') OR (el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture'))";
4038 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande' ";
4039 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_source = c.rowid";
4040 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND f.fk_statut > ".Facture::STATUS_DRAFT." AND fd.fk_product = ".((int) $this->id);
4041 $sql .= " AND EXISTS (SELECT cd.fk_product FROM ".$this->db->prefix()."commandedet as cd WHERE cd.fk_product = fd.fk_product AND cd.fk_commande = c.rowid)"; // We check that the product is in order lines
4042
4043 $sql .= " UNION ALL ";
4044
4045 $sql .= "SELECT sum(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
4046 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
4047 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture' ";
4048 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_target = c.rowid";
4049 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND f.fk_statut > ".Facture::STATUS_DRAFT." AND fd.fk_product = ".((int) $this->id);
4050 $sql .= " AND EXISTS (SELECT cd.fk_product FROM ".$this->db->prefix()."commandedet as cd WHERE cd.fk_product = fd.fk_product AND cd.fk_commande = c.rowid)"; // We check that the product is in order lines
4051
4052 dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
4053 // Add where from hooks
4054 $parameters = array('socid' => $socid, 'type_element' => 'order');
4055 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
4056 $sql .= $hookmanager->resPrint;
4057 $resql = $this->db->query($sql);
4058 if ($resql) {
4059 while ($obj = $this->db->fetch_object($resql)) {
4060 $adeduire += (float) $obj->count;
4061 }
4062 } else {
4063 $this->error = $this->db->error();
4064 return -1;
4065 }
4066
4067 $this->stats_commande['qty'] -= $adeduire;
4068 }
4069 }
4070
4071 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
4072 $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
4073 if ($reshook > 0) {
4074 $this->stats_commande = $hookmanager->resArray['stats_commande'];
4075 }
4076 return 1;
4077 } else {
4078 $this->error = $this->db->error();
4079 return -1;
4080 }
4081 }
4082
4083 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4094 public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null, $dateofvirtualstockmin = null)
4095 {
4096 // phpcs:enable
4097 global $user, $hookmanager, $action;
4098
4099 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
4100 $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
4101 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
4102 $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
4103 $sql .= ", ".$this->db->prefix()."societe as s";
4104 $sql .= " WHERE c.rowid = cd.fk_commande";
4105 $sql .= " AND c.fk_soc = s.rowid";
4106 $sql .= " AND c.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'supplier_order').")";
4107 $sql .= " AND cd.fk_product = ".((int) $this->id);
4108 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4109 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4110 }
4111 if ($socid > 0) {
4112 $sql .= " AND c.fk_soc = ".((int) $socid);
4113 }
4114 if ($filtrestatut != '') {
4115 $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
4116 }
4117 if (!empty($dateofvirtualstock)) {
4118 // Window of the horizon. The lower bound, when set, drops the orders that did not arrive as planned: their date has
4119 // passed, so they are no longer a credible supply. Orders with no planned delivery date fall outside the window as
4120 // well, since their arrival is unknown, unless the option says to keep them.
4121 $sqlwindow = "c.date_livraison <= '".$this->db->idate($dateofvirtualstock)."'";
4122 if (!empty($dateofvirtualstockmin)) {
4123 $sqlwindow = "c.date_livraison >= '".$this->db->idate($dateofvirtualstockmin)."' AND ".$sqlwindow;
4124 }
4125 if (getDolGlobalInt('STOCK_VIRTUAL_HORIZON_INCLUDE_UNDATED_ORDERS')) {
4126 $sqlwindow .= " OR c.date_livraison IS NULL";
4127 }
4128 $sql .= " AND (".$sqlwindow.")";
4129 }
4130
4131 $result = $this->db->query($sql);
4132 if ($result) {
4133 $obj = $this->db->fetch_object($result);
4134 $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
4135 $this->stats_commande_fournisseur['nb'] = $obj->nb;
4136 $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
4137 $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
4138
4139 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
4140 $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
4141 if ($reshook > 0) {
4142 $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
4143 }
4144
4145 return 1;
4146 } else {
4147 $this->error = $this->db->error().' sql='.$sql;
4148 return -1;
4149 }
4150 }
4151
4152 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4162 public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
4163 {
4164 // phpcs:enable
4165 global $user, $hookmanager, $action;
4166
4167 $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
4168 $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
4169 $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
4170 $sql .= ", ".$this->db->prefix()."commandedet as cd";
4171 $sql .= ", ".$this->db->prefix()."commande as c";
4172 $sql .= ", ".$this->db->prefix()."expedition as e";
4173 $sql .= ", ".$this->db->prefix()."societe as s";
4174 $sql .= " WHERE e.rowid = ed.fk_expedition";
4175 $sql .= " AND c.rowid = cd.fk_commande";
4176 $sql .= " AND e.fk_soc = s.rowid";
4177 $sql .= " AND e.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'expedition').")";
4178 $sql .= " AND ed.fk_elementdet = cd.rowid";
4179 $sql .= " AND cd.fk_product = ".((int) $this->id);
4180 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4181 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = e.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4182 }
4183 if ($socid > 0) {
4184 $sql .= " AND e.fk_soc = ".((int) $socid);
4185 }
4186 if ($filtrestatut != '') {
4187 $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
4188 }
4189 if (!empty($filterShipmentStatus)) {
4190 $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
4191 }
4192
4193 $result = $this->db->query($sql);
4194 if ($result) {
4195 $obj = $this->db->fetch_object($result);
4196 $this->stats_expedition['customers'] = (int) $obj->nb_customers;
4197 $this->stats_expedition['nb'] = (int) $obj->nb;
4198 $this->stats_expedition['rows'] = (int) $obj->nb_rows;
4199 $this->stats_expedition['qty'] = $obj->qty ? (float) $obj->qty : 0;
4200
4201 // if it's a virtual product, maybe it is in sending by extension
4202 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4203 $TFather = $this->getFather();
4204 if (is_array($TFather) && !empty($TFather)) {
4205 foreach ($TFather as &$fatherData) {
4206 $pFather = new Product($this->db);
4207 $pFather->id = $fatherData['id'];
4208 $qtyCoef = $fatherData['qty'];
4209
4210 if ($fatherData['incdec']) {
4211 $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
4212
4213 if (!empty($pFather->stats_expedition)) {
4214 $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
4215 $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
4216 $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
4217 $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
4218 }
4219 }
4220 }
4221 }
4222 }
4223
4224 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
4225 $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
4226 if ($reshook > 0) {
4227 $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
4228 }
4229
4230 return 1;
4231 } else {
4232 $this->error = $this->db->error();
4233 return -1;
4234 }
4235 }
4236
4237 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4248 public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null, $dateofvirtualstockmin = null)
4249 {
4250 // phpcs:enable
4251 global $user, $hookmanager, $action;
4252
4253 $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
4254 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4255 $sql .= " FROM ".$this->db->prefix()."receptiondet_batch as fd";
4256 $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
4257 $sql .= ", ".$this->db->prefix()."societe as s";
4258 $sql .= " WHERE cf.rowid = fd.fk_element";
4259 $sql .= " AND cf.fk_soc = s.rowid";
4260 $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'supplier_order').")";
4261 $sql .= " AND fd.fk_product = ".((int) $this->id);
4262 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4263 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = cf.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4264 }
4265 if ($socid > 0) {
4266 $sql .= " AND cf.fk_soc = ".((int) $socid);
4267 }
4268 if ($filtrestatut != '') {
4269 $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
4270 }
4271 if (!empty($dateofvirtualstock)) {
4272 $sql .= " AND fd.datec <= '".$this->db->idate($dateofvirtualstock)."'";
4273 }
4274 if (!empty($dateofvirtualstockmin)) {
4275 // Same window as the supplier order side: both halves of the subtraction must always run on the same population of
4276 // orders, otherwise an order dropped from one half while its receptions are still subtracted in the other one would
4277 // push the theoretical stock below the real stock.
4278 $sqlwindow = "cf.date_livraison >= '".$this->db->idate($dateofvirtualstockmin)."' AND cf.date_livraison <= '".$this->db->idate($dateofvirtualstock)."'";
4279 if (getDolGlobalInt('STOCK_VIRTUAL_HORIZON_INCLUDE_UNDATED_ORDERS')) {
4280 $sqlwindow .= " OR cf.date_livraison IS NULL";
4281 }
4282 $sql .= " AND (".$sqlwindow.")";
4283 }
4284
4285 $result = $this->db->query($sql);
4286 if ($result) {
4287 $obj = $this->db->fetch_object($result);
4288 $this->stats_reception['suppliers'] = $obj->nb_suppliers;
4289 $this->stats_reception['nb'] = $obj->nb;
4290 $this->stats_reception['rows'] = $obj->nb_rows;
4291 $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
4292
4293 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
4294 $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
4295 if ($reshook > 0) {
4296 $this->stats_reception = $hookmanager->resArray['stats_reception'];
4297 }
4298
4299 return 1;
4300 } else {
4301 $this->error = $this->db->error();
4302 return -1;
4303 }
4304 }
4305
4306 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4318 public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null, $warehouseid = 0, $dateofvirtualstockmin = null)
4319 {
4320 // phpcs:enable
4321 global $user, $hookmanager, $action;
4322
4323 $serviceStockIsEnabled = isModEnabled("service") && getDolGlobalString('STOCK_SUPPORTS_SERVICES');
4324
4325 $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
4326 $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
4327 $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
4328 $sql .= ", ".$this->db->prefix()."mrp_mo as m";
4329 $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
4330 $sql .= " WHERE m.rowid = mp.fk_mo";
4331 $sql .= " AND m.entity IN (".getEntity(($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE')) ? 'stock' : 'mrp').")";
4332 $sql .= " AND mp.fk_product = ".((int) $this->id);
4333 $sql .= " AND (mp.disable_stock_change IN (0) OR mp.disable_stock_change IS NULL)";
4334 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4335 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = m.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4336 }
4337 if ($socid > 0) {
4338 $sql .= " AND m.fk_soc = ".((int) $socid);
4339 }
4340 if ($filtrestatut != '') {
4341 $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
4342 }
4343 if (!empty($dateofvirtualstockmin)) {
4344 // Window of the horizon. Here the relevant date is the planned end of production, not the validation date: a
4345 // manufacturing order validated months ago but never completed is no longer a credible source of goods, and its
4346 // components are no longer a credible consumption either. The validation date is kept as a fallback for the
4347 // orders that carry no planned end date.
4348 $sql .= " AND COALESCE(m.date_end_planned, m.date_valid) >= '".$this->db->idate($dateofvirtualstockmin)."'";
4349 $sql .= " AND COALESCE(m.date_end_planned, m.date_valid) <= '".$this->db->idate($dateofvirtualstock)."'";
4350 } elseif (!empty($dateofvirtualstock)) {
4351 $sql .= " AND m.date_valid <= '".$this->db->idate($dateofvirtualstock)."'"; // better date to code ? end of production ?
4352 }
4353 if (!$serviceStockIsEnabled) {
4354 $sql .= "AND EXISTS (SELECT p.rowid FROM ".$this->db->prefix()."product AS p WHERE p.rowid = ".((int) $this->id)." AND p.fk_product_type IN (0))";
4355 }
4356 if (!empty($warehouseid)) {
4357 $sql .= " AND m.fk_warehouse = ".((int) $warehouseid);
4358 }
4359 $sql .= " GROUP BY role";
4360
4361 if ($warehouseid) {
4362 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] = 0;
4363 } else {
4364 $this->stats_mrptoconsume['customers'] = 0;
4365 $this->stats_mrptoconsume['nb'] = 0;
4366 $this->stats_mrptoconsume['rows'] = 0;
4367 $this->stats_mrptoconsume['qty'] = 0.0;
4368 $this->stats_mrptoproduce['customers'] = 0;
4369 $this->stats_mrptoproduce['nb'] = 0;
4370 $this->stats_mrptoproduce['rows'] = 0;
4371 $this->stats_mrptoproduce['qty'] = 0.0;
4372 }
4373
4374 $result = $this->db->query($sql);
4375 if ($result) {
4376 while ($obj = $this->db->fetch_object($result)) {
4377 if ($obj->role == 'toconsume' && empty($warehouseid)) {
4378 $this->stats_mrptoconsume['customers'] += (int) $obj->nb_customers;
4379 $this->stats_mrptoconsume['nb'] += (int) $obj->nb;
4380 $this->stats_mrptoconsume['rows'] += (int) $obj->nb_rows;
4381 $this->stats_mrptoconsume['qty'] += ($obj->qty ? (float) $obj->qty : 0.0);
4382 }
4383 if ($obj->role == 'consumed' && empty($warehouseid)) {
4384 //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
4385 //$this->stats_mrptoconsume['nb'] += $obj->nb;
4386 //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
4387 $this->stats_mrptoconsume['qty'] -= ($obj->qty ? (float) $obj->qty : 0.0);
4388 }
4389 if ($obj->role == 'toproduce') {
4390 if ($warehouseid) {
4391 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] += ($obj->qty ? (float) $obj->qty : 0.0);
4392 } else {
4393 $this->stats_mrptoproduce['customers'] += (int) $obj->nb_customers;
4394 $this->stats_mrptoproduce['nb'] += (int) $obj->nb;
4395 $this->stats_mrptoproduce['rows'] += (int) $obj->nb_rows;
4396 $this->stats_mrptoproduce['qty'] += ($obj->qty ? (float) $obj->qty : 0.0);
4397 }
4398 }
4399 if ($obj->role == 'produced') {
4400 //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
4401 //$this->stats_mrptoproduce['nb'] += $obj->nb;
4402 //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
4403 if ($warehouseid) {
4404 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
4405 } else {
4406 $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
4407 }
4408 }
4409 }
4410
4411 // Clean data
4412 if ($warehouseid) {
4413 if ($this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] < 0) {
4414 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] = 0;
4415 }
4416 } else {
4417 if ($this->stats_mrptoconsume['qty'] < 0) {
4418 $this->stats_mrptoconsume['qty'] = 0;
4419 }
4420 if ($this->stats_mrptoproduce['qty'] < 0) {
4421 $this->stats_mrptoproduce['qty'] = 0;
4422 }
4423 }
4424
4425 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
4426 $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
4427 if ($reshook > 0) {
4428 $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
4429 }
4430
4431 return 1;
4432 } else {
4433 $this->error = $this->db->error();
4434 return -1;
4435 }
4436 }
4437
4438 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4445 public function load_stats_contrat($socid = 0)
4446 {
4447 // phpcs:enable
4448 global $user, $hookmanager, $action;
4449
4450 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
4451 $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
4452 $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
4453 $sql .= ", ".$this->db->prefix()."contrat as c";
4454 $sql .= ", ".$this->db->prefix()."societe as s";
4455 $sql .= " WHERE c.rowid = cd.fk_contrat";
4456 $sql .= " AND c.fk_soc = s.rowid";
4457 $sql .= " AND c.entity IN (".getEntity('contract').")";
4458 $sql .= " AND cd.fk_product = ".((int) $this->id);
4459 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4460 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4461 }
4462 //$sql.= " AND c.statut != 0";
4463 if ($socid > 0) {
4464 $sql .= " AND c.fk_soc = ".((int) $socid);
4465 }
4466
4467 $result = $this->db->query($sql);
4468 if ($result) {
4469 $obj = $this->db->fetch_object($result);
4470 $this->stats_contrat['customers'] = (int) $obj->nb_customers;
4471 $this->stats_contrat['nb'] = (int) $obj->nb;
4472 $this->stats_contrat['rows'] = (int) $obj->nb_rows;
4473 $this->stats_contrat['qty'] = $obj->qty ? (float) $obj->qty : 0;
4474
4475 // if it's a virtual product, maybe it is in contract by extension
4476 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4477 $TFather = $this->getFather();
4478 if (is_array($TFather) && !empty($TFather)) {
4479 foreach ($TFather as &$fatherData) {
4480 $pFather = new Product($this->db);
4481 $pFather->id = $fatherData['id'];
4482 $qtyCoef = $fatherData['qty'];
4483
4484 if ($fatherData['incdec']) {
4485 $pFather->load_stats_contrat($socid);
4486
4487 if (!empty($pFather->stats_contrat)) {
4488 $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
4489 $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
4490 $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
4491 $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
4492 }
4493 }
4494 }
4495 }
4496 }
4497
4498 $parameters = array('socid' => $socid);
4499 $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
4500 if ($reshook > 0) {
4501 $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
4502 }
4503
4504 return 1;
4505 } else {
4506 $this->error = $this->db->error().' sql='.$sql;
4507 return -1;
4508 }
4509 }
4510
4511 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4518 public function load_stats_facture($socid = 0)
4519 {
4520 // phpcs:enable
4521 global $user, $hookmanager, $action;
4522
4523 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
4524 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
4525 $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
4526 $sql .= ", ".$this->db->prefix()."facture as f";
4527 $sql .= ", ".$this->db->prefix()."societe as s";
4528 $sql .= " WHERE f.rowid = fd.fk_facture";
4529 $sql .= " AND f.fk_soc = s.rowid";
4530 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4531 $sql .= " AND fd.fk_product = ".((int) $this->id);
4532 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4533 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4534 }
4535 //$sql.= " AND f.fk_statut != 0";
4536 if ($socid > 0) {
4537 $sql .= " AND f.fk_soc = ".((int) $socid);
4538 }
4539
4540 $result = $this->db->query($sql);
4541 if ($result) {
4542 $obj = $this->db->fetch_object($result);
4543 $this->stats_facture['customers'] = (int) $obj->nb_customers;
4544 $this->stats_facture['nb'] = (int) $obj->nb;
4545 $this->stats_facture['rows'] = (int) $obj->nb_rows;
4546 $this->stats_facture['qty'] = $obj->qty ? (float) $obj->qty : 0;
4547
4548 // if it's a virtual product, maybe it is in invoice by extension
4549 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4550 $TFather = $this->getFather();
4551 if (is_array($TFather) && !empty($TFather)) {
4552 foreach ($TFather as &$fatherData) {
4553 $pFather = new Product($this->db);
4554 $pFather->id = $fatherData['id'];
4555 $qtyCoef = $fatherData['qty'];
4556
4557 if ($fatherData['incdec']) {
4558 $pFather->load_stats_facture($socid);
4559
4560 if (!empty($pFather->stats_facture)) {
4561 $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
4562 $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
4563 $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
4564 $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
4565 }
4566 }
4567 }
4568 }
4569 }
4570
4571 $parameters = array('socid' => $socid);
4572 $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
4573 if ($reshook > 0) {
4574 $this->stats_facture = $hookmanager->resArray['stats_facture'];
4575 }
4576
4577 return 1;
4578 } else {
4579 $this->error = $this->db->error();
4580 return -1;
4581 }
4582 }
4583
4584
4585 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4592 public function load_stats_facturerec($socid = 0)
4593 {
4594 // phpcs:enable
4595 global $user, $hookmanager, $action;
4596
4597 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
4598 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4599 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_rec as fd";
4600 $sql .= ", ".MAIN_DB_PREFIX."facture_rec as f";
4601 $sql .= ", ".MAIN_DB_PREFIX."societe as s";
4602 $sql .= " WHERE f.rowid = fd.fk_facture";
4603 $sql .= " AND f.fk_soc = s.rowid";
4604 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4605 $sql .= " AND fd.fk_product = ".((int) $this->id);
4606 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4607 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4608 }
4609 //$sql.= " AND f.fk_statut != 0";
4610 if ($socid > 0) {
4611 $sql .= " AND f.fk_soc = ".((int) $socid);
4612 }
4613
4614 $result = $this->db->query($sql);
4615 if ($result) {
4616 $obj = $this->db->fetch_object($result);
4617 $this->stats_facturerec['customers'] = (int) $obj->nb_customers;
4618 $this->stats_facturerec['nb'] = (int) $obj->nb;
4619 $this->stats_facturerec['rows'] = (int) $obj->nb_rows;
4620 $this->stats_facturerec['qty'] = $obj->qty ? (float) $obj->qty : 0.0;
4621
4622 // if it's a virtual product, maybe it is in invoice by extension
4623 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4624 $TFather = $this->getFather();
4625 if (is_array($TFather) && !empty($TFather)) {
4626 foreach ($TFather as &$fatherData) {
4627 $pFather = new Product($this->db);
4628 $pFather->id = $fatherData['id'];
4629 $qtyCoef = $fatherData['qty'];
4630
4631 if ($fatherData['incdec']) {
4632 $pFather->load_stats_facture($socid);
4633
4634 $this->stats_facturerec['customers'] += $pFather->stats_facturerec['customers'];
4635 $this->stats_facturerec['nb'] += $pFather->stats_facturerec['nb'];
4636 $this->stats_facturerec['rows'] += $pFather->stats_facturerec['rows'];
4637 $this->stats_facturerec['qty'] += $pFather->stats_facturerec['qty'] * $qtyCoef;
4638 }
4639 }
4640 }
4641 }
4642
4643 $parameters = array('socid' => $socid);
4644 $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoiceRec', $parameters, $this, $action);
4645 if ($reshook > 0) {
4646 $this->stats_facturerec = $hookmanager->resArray['stats_facturerec'];
4647 }
4648
4649 return 1;
4650 } else {
4651 $this->error = $this->db->error();
4652 return -1;
4653 }
4654 }
4655
4656 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4663 public function load_stats_facture_fournisseur($socid = 0)
4664 {
4665 // phpcs:enable
4666 global $user, $hookmanager, $action;
4667
4668 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
4669 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4670 $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
4671 $sql .= ", ".$this->db->prefix()."facture_fourn as f";
4672 $sql .= ", ".$this->db->prefix()."societe as s";
4673 $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
4674 $sql .= " AND f.fk_soc = s.rowid";
4675 $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
4676 $sql .= " AND fd.fk_product = ".((int) $this->id);
4677 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4678 $sql .= " AND EXISTS (SELECT 1 FROM ".$this->db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $user->id).")";
4679 }
4680 //$sql.= " AND f.fk_statut != 0";
4681 if ($socid > 0) {
4682 $sql .= " AND f.fk_soc = ".((int) $socid);
4683 }
4684
4685 $result = $this->db->query($sql);
4686 if ($result) {
4687 $obj = $this->db->fetch_object($result);
4688 $this->stats_facture_fournisseur['suppliers'] = (int) $obj->nb_suppliers;
4689 $this->stats_facture_fournisseur['nb'] = (int) $obj->nb;
4690 $this->stats_facture_fournisseur['rows'] = (int) $obj->nb_rows;
4691 $this->stats_facture_fournisseur['qty'] = $obj->qty ? (float) $obj->qty : 0.0;
4692
4693 $parameters = array('socid' => $socid);
4694 $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
4695 if ($reshook > 0) {
4696 $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
4697 }
4698
4699 return 1;
4700 } else {
4701 $this->error = $this->db->error();
4702 return -1;
4703 }
4704 }
4705
4706 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4713 public function load_stats_facturefournrec($socid = 0)
4714 {
4715 // phpcs:enable
4716 global $user, $hookmanager, $action;
4717
4718 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
4719 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4720 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det_rec as fd";
4721 $sql .= ", ".MAIN_DB_PREFIX."facture_fourn_rec as f";
4722 $sql .= ", ".MAIN_DB_PREFIX."societe as s";
4723 if (!$user->hasRight('societe', 'client', 'voir')) {
4724 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
4725 }
4726 $sql .= " WHERE f.rowid = fd.fk_facture";
4727 $sql .= " AND f.fk_soc = s.rowid";
4728 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4729 $sql .= " AND fd.fk_product = ".((int) $this->id);
4730 if (!$user->hasRight('societe', 'client', 'voir')) {
4731 $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4732 }
4733 //$sql.= " AND f.fk_statut != 0";
4734 if ($socid > 0) {
4735 $sql .= " AND f.fk_soc = ".((int) $socid);
4736 }
4737
4738 $result = $this->db->query($sql);
4739 if ($result) {
4740 $obj = $this->db->fetch_object($result);
4741 $this->stats_facturefournrec['suppliers'] = (int) $obj->nb_suppliers;
4742 $this->stats_facturefournrec['nb'] = (int) $obj->nb;
4743 $this->stats_facturefournrec['rows'] = (int) $obj->nb_rows;
4744 $this->stats_facturefournrec['qty'] = $obj->qty ? (float) $obj->qty : 0.0;
4745
4746 $parameters = array('socid' => $socid);
4747 $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoiceRec', $parameters, $this, $action);
4748 if ($reshook > 0) {
4749 $this->stats_facturefournrec = $hookmanager->resArray['stats_facturefournrec'];
4750 }
4751
4752 return 1;
4753 } else {
4754 $this->error = $this->db->error();
4755 return -1;
4756 }
4757 }
4758
4759 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4768 private function _get_stats($sql, $mode, $year = 0)
4769 {
4770 // phpcs:enable
4771 $tab = array();
4772
4773 $resql = $this->db->query($sql);
4774 if ($resql) {
4775 $num = $this->db->num_rows($resql);
4776 $i = 0;
4777 while ($i < $num) {
4778 $arr = $this->db->fetch_array($resql);
4779 if (is_array($arr)) {
4780 $keyfortab = (string) $arr[1];
4781 if ($year == -1) {
4782 $keyfortab = substr($keyfortab, -2);
4783 }
4784
4785 if ($mode == 'byunit') {
4786 $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
4787 } elseif ($mode == 'bynumber') {
4788 $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
4789 } elseif ($mode == 'byamount') {
4790 $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
4791 } else {
4792 // Bad value for $mode
4793 return -1;
4794 }
4795 }
4796 $i++;
4797 }
4798 } else {
4799 $this->error = $this->db->error().' sql='.$sql;
4800 return -1;
4801 }
4802
4803 if (empty($year)) {
4804 $year = dol_print_date(dol_now(), '%Y');
4805 $month = dol_print_date(dol_now(), '%m');
4806 } elseif ($year == -1) {
4807 $year = '';
4808 $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
4809 } else {
4810 $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
4811 }
4812
4813 $result = array();
4814
4815 for ($j = 0; $j < 12; $j++) {
4816 // $idx is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
4817 $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
4818
4819 // print $idx.'-'.$year.'-'.$month.'<br>';
4820 $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
4821 // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
4822
4823 $month = "0".($month - 1);
4824 if (dol_strlen($month) == 3) {
4825 $month = substr($month, 1);
4826 }
4827 if ($month == 0) {
4828 $month = 12;
4829 if ($year !== '') { // $year is '' when we want stats for all years
4830 $year -= 1;
4831 }
4832 }
4833 }
4834
4835 return array_reverse($result);
4836 }
4837
4838
4839 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4850 public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4851 {
4852 // phpcs:enable
4853 global $user;
4854
4855 $sql = "SELECT sum(d.qty) as qty, date_format(f.datef, '%Y%m')";
4856 if ($mode == 'bynumber') {
4857 $sql .= ", count(DISTINCT f.rowid)";
4858 }
4859 $sql .= ", sum(d.total_ht) as total_ht";
4860 $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
4861 if ($filteronproducttype >= 0) {
4862 $sql .= ", ".$this->db->prefix()."product as p";
4863 }
4864 if (!$user->hasRight('societe', 'client', 'voir')) {
4865 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4866 }
4867 $sql .= " WHERE f.rowid = d.fk_facture";
4868 if ($this->id > 0) {
4869 $sql .= " AND d.fk_product = ".((int) $this->id);
4870 } else {
4871 $sql .= " AND d.fk_product > 0";
4872 }
4873 if ($filteronproducttype >= 0) {
4874 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4875 }
4876 $sql .= " AND f.fk_soc = s.rowid";
4877 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4878 if (!$user->hasRight('societe', 'client', 'voir')) {
4879 $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4880 }
4881 if ($socid > 0) {
4882 $sql .= " AND f.fk_soc = ".((int) $socid);
4883 }
4884 $sql .= $morefilter;
4885 $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
4886 $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
4887
4888 return $this->_get_stats($sql, $mode, $year);
4889 }
4890
4891
4892 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4903 public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4904 {
4905 // phpcs:enable
4906 global $user;
4907
4908 $sql = "SELECT sum(d.qty) as qty, date_format(f.datef, '%Y%m')";
4909 if ($mode == 'bynumber') {
4910 $sql .= ", count(DISTINCT f.rowid)";
4911 }
4912 $sql .= ", sum(d.total_ht) as total_ht";
4913 $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
4914 if ($filteronproducttype >= 0) {
4915 $sql .= ", ".$this->db->prefix()."product as p";
4916 }
4917 if (!$user->hasRight('societe', 'client', 'voir')) {
4918 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4919 }
4920 $sql .= " WHERE f.rowid = d.fk_facture_fourn";
4921 if ($this->id > 0) {
4922 $sql .= " AND d.fk_product = ".((int) $this->id);
4923 } else {
4924 $sql .= " AND d.fk_product > 0";
4925 }
4926 if ($filteronproducttype >= 0) {
4927 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4928 }
4929 $sql .= " AND f.fk_soc = s.rowid";
4930 $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
4931 if (!$user->hasRight('societe', 'client', 'voir')) {
4932 $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4933 }
4934 if ($socid > 0) {
4935 $sql .= " AND f.fk_soc = ".((int) $socid);
4936 }
4937 $sql .= $morefilter;
4938 $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
4939 $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
4940
4941 return $this->_get_stats($sql, $mode, $year);
4942 }
4943
4944 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4955 public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4956 {
4957 // phpcs:enable
4958 global $user, $hookmanager;
4959
4960 $sql = "SELECT sum(d.qty) as qty, date_format(p.datep, '%Y%m')";
4961 if ($mode == 'bynumber') {
4962 $sql .= ", count(DISTINCT p.rowid)";
4963 }
4964 $sql .= ", sum(d.total_ht) as total_ht";
4965 $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
4966 if ($filteronproducttype >= 0) {
4967 $sql .= ", ".$this->db->prefix()."product as prod";
4968 }
4969 if (!$user->hasRight('societe', 'client', 'voir')) {
4970 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4971 }
4972 $sql .= " WHERE p.rowid = d.fk_propal";
4973 if ($this->id > 0) {
4974 $sql .= " AND d.fk_product = ".((int) $this->id);
4975 } else {
4976 $sql .= " AND d.fk_product > 0";
4977 }
4978 if ($filteronproducttype >= 0) {
4979 $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
4980 }
4981 $sql .= " AND p.fk_soc = s.rowid";
4982 $sql .= " AND p.entity IN (".getEntity('propal').")";
4983 if (!$user->hasRight('societe', 'client', 'voir')) {
4984 $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4985 }
4986 if ($socid > 0) {
4987 $sql .= " AND p.fk_soc = ".((int) $socid);
4988 }
4989 $sql .= $morefilter;
4990 $parameters = array('socid' => $user->socid);
4991 $hookmanager->executeHooks('productGetNbPropal', $parameters, $this); // Note that $action and $object may have been modified by hook
4992 $sql .= $hookmanager->resPrint;
4993 $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
4994 $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
4995 return $this->_get_stats($sql, $mode, $year);
4996 }
4997
4998 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5009 public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
5010 {
5011 // phpcs:enable
5012 global $user;
5013
5014 $sql = "SELECT sum(d.qty) as qty, date_format(p.date_valid, '%Y%m')";
5015 if ($mode == 'bynumber') {
5016 $sql .= ", count(DISTINCT p.rowid)";
5017 }
5018 $sql .= ", sum(d.total_ht) as total_ht";
5019 $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
5020 if ($filteronproducttype >= 0) {
5021 $sql .= ", ".$this->db->prefix()."product as prod";
5022 }
5023 if (!$user->hasRight('societe', 'client', 'voir')) {
5024 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5025 }
5026 $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
5027 if ($this->id > 0) {
5028 $sql .= " AND d.fk_product = ".((int) $this->id);
5029 } else {
5030 $sql .= " AND d.fk_product > 0";
5031 }
5032 if ($filteronproducttype >= 0) {
5033 $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
5034 }
5035 $sql .= " AND p.fk_soc = s.rowid";
5036 $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
5037 if (!$user->hasRight('societe', 'client', 'voir')) {
5038 $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5039 }
5040 if ($socid > 0) {
5041 $sql .= " AND p.fk_soc = ".((int) $socid);
5042 }
5043 $sql .= $morefilter;
5044 $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
5045 $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
5046
5047 return $this->_get_stats($sql, $mode, $year);
5048 }
5049
5050 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5061 public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
5062 {
5063 // phpcs:enable
5064 global $user, $hookmanager;
5065
5066 $sql = "SELECT sum(d.qty) as qty, date_format(c.date_commande, '%Y%m')";
5067 if ($mode == 'bynumber') {
5068 $sql .= ", count(DISTINCT c.rowid)";
5069 }
5070 $sql .= ", sum(d.total_ht) as total_ht";
5071 $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
5072 if ($filteronproducttype >= 0) {
5073 $sql .= ", ".$this->db->prefix()."product as p";
5074 }
5075 if (!$user->hasRight('societe', 'client', 'voir')) {
5076 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5077 }
5078 $sql .= " WHERE c.rowid = d.fk_commande";
5079 if ($this->id > 0) {
5080 $sql .= " AND d.fk_product = ".((int) $this->id);
5081 } else {
5082 $sql .= " AND d.fk_product > 0";
5083 }
5084 if ($filteronproducttype >= 0) {
5085 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
5086 }
5087 $sql .= " AND c.fk_soc = s.rowid";
5088 $sql .= " AND c.entity IN (".getEntity('commande').")";
5089 if (!$user->hasRight('societe', 'client', 'voir')) {
5090 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5091 }
5092 if ($socid > 0) {
5093 $sql .= " AND c.fk_soc = ".((int) $socid);
5094 }
5095 $sql .= $morefilter;
5096 $parameters = array('socid' => $user->socid);
5097 $hookmanager->executeHooks('productGetNbOrder', $parameters, $this); // Note that $action and $object may have been modified by hook
5098 $sql .= $hookmanager->resPrint;
5099 $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
5100 $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
5101
5102 return $this->_get_stats($sql, $mode, $year);
5103 }
5104
5105 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5116 public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
5117 {
5118 // phpcs:enable
5119 global $user;
5120
5121 $sql = "SELECT sum(d.qty) as qty, date_format(c.date_commande, '%Y%m')";
5122 if ($mode == 'bynumber') {
5123 $sql .= ", count(DISTINCT c.rowid)";
5124 }
5125 $sql .= ", sum(d.total_ht) as total_ht";
5126 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
5127 if ($filteronproducttype >= 0) {
5128 $sql .= ", ".$this->db->prefix()."product as p";
5129 }
5130 if (!$user->hasRight('societe', 'client', 'voir')) {
5131 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5132 }
5133 $sql .= " WHERE c.rowid = d.fk_commande";
5134 if ($this->id > 0) {
5135 $sql .= " AND d.fk_product = ".((int) $this->id);
5136 } else {
5137 $sql .= " AND d.fk_product > 0";
5138 }
5139 if ($filteronproducttype >= 0) {
5140 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
5141 }
5142 $sql .= " AND c.fk_soc = s.rowid";
5143 $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
5144 if (!$user->hasRight('societe', 'client', 'voir')) {
5145 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5146 }
5147 if ($socid > 0) {
5148 $sql .= " AND c.fk_soc = ".((int) $socid);
5149 }
5150 $sql .= $morefilter;
5151 $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
5152 $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
5153
5154 return $this->_get_stats($sql, $mode, $year);
5155 }
5156
5157 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5168 public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
5169 {
5170 // phpcs:enable
5171 global $user;
5172
5173 $sql = "SELECT sum(d.qty) as qty, date_format(c.date_contrat, '%Y%m')";
5174 if ($mode == 'bynumber') {
5175 $sql .= ", count(DISTINCT c.rowid)";
5176 }
5177 $sql .= ", sum(d.total_ht) as total_ht";
5178 $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
5179 if ($filteronproducttype >= 0) {
5180 $sql .= ", ".$this->db->prefix()."product as p";
5181 }
5182 if (!$user->hasRight('societe', 'client', 'voir')) {
5183 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5184 }
5185 $sql .= " WHERE c.entity IN (".getEntity('contract').")";
5186 $sql .= " AND c.rowid = d.fk_contrat";
5187
5188 if ($this->id > 0) {
5189 $sql .= " AND d.fk_product = ".((int) $this->id);
5190 } else {
5191 $sql .= " AND d.fk_product > 0";
5192 }
5193 if ($filteronproducttype >= 0) {
5194 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
5195 }
5196 $sql .= " AND c.fk_soc = s.rowid";
5197
5198 if (!$user->hasRight('societe', 'client', 'voir')) {
5199 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5200 }
5201 if ($socid > 0) {
5202 $sql .= " AND c.fk_soc = ".((int) $socid);
5203 }
5204 $sql .= $morefilter;
5205 $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
5206 $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
5207
5208 return $this->_get_stats($sql, $mode, $year);
5209 }
5210
5211 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5222 public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
5223 {
5224 // phpcs:enable
5225 global $user;
5226
5227 $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
5228 if ($mode == 'bynumber') {
5229 $sql .= ", count(DISTINCT d.rowid)";
5230 }
5231 $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
5232 if ($filteronproducttype >= 0) {
5233 $sql .= ", ".$this->db->prefix()."product as p";
5234 }
5235 if (!$user->hasRight('societe', 'client', 'voir')) {
5236 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5237 }
5238
5239 $sql .= " WHERE d.entity IN (".getEntity('mo').")";
5240 $sql .= " AND d.status > 0";
5241
5242 if ($this->id > 0) {
5243 $sql .= " AND d.fk_product = ".((int) $this->id);
5244 } else {
5245 $sql .= " AND d.fk_product > 0";
5246 }
5247 if ($filteronproducttype >= 0) {
5248 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
5249 }
5250
5251 if (!$user->hasRight('societe', 'client', 'voir')) {
5252 $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5253 }
5254 if ($socid > 0) {
5255 $sql .= " AND d.fk_soc = ".((int) $socid);
5256 }
5257 $sql .= $morefilter;
5258 $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
5259 $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
5260
5261 return $this->_get_stats($sql, $mode, $year);
5262 }
5263
5264 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5275 public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1, $notrigger = 0)
5276 {
5277 // phpcs:enable
5278 global $user;
5279
5280 // Clean parameters
5281 if (!is_numeric($id_pere)) {
5282 $id_pere = 0;
5283 }
5284 if (!is_numeric($id_fils)) {
5285 $id_fils = 0;
5286 }
5287 if (!is_numeric($incdec)) {
5288 $incdec = 0;
5289 }
5290
5291 $result = $this->del_sousproduit($id_pere, $id_fils);
5292 if ($result < 0) {
5293 return $result;
5294 }
5295
5296 // Check not already father of id_pere (to avoid father -> child -> father links)
5297 $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
5298 $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
5299 if (!$this->db->query($sql)) {
5300 dol_print_error($this->db);
5301 return -1;
5302 } else {
5303 //Selection of the highest row
5304 $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
5305 $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
5306 $resql = $this->db->query($sql);
5307 if ($resql) {
5308 $obj = $this->db->fetch_object($resql);
5309 $rank = $obj->max_rank + 1;
5310 //Addition of a product with the highest rank +1
5311 $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
5312 $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".((int) $incdec).", ".((int) $rank).")";
5313 if (! $this->db->query($sql)) {
5314 dol_print_error($this->db);
5315 return -1;
5316 } else {
5317 if (!$notrigger) {
5318 // Call trigger
5319 $result = $this->call_trigger('PRODUCT_SUBPRODUCT_ADD', $user);
5320 if ($result < 0) {
5321 $this->error = $this->db->lasterror();
5322 dol_syslog(get_class($this).'::addSubproduct error='.$this->error, LOG_ERR);
5323 return -1;
5324 }
5325 }
5326 // End call triggers
5327
5328 return 1;
5329 }
5330 } else {
5331 dol_print_error($this->db);
5332 return -1;
5333 }
5334 }
5335 }
5336
5337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5348 public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1, $notrigger = 0)
5349 {
5350 // phpcs:enable
5351 global $user;
5352
5353 // Clean parameters
5354 if (!is_numeric($id_pere)) {
5355 $id_pere = 0;
5356 }
5357 if (!is_numeric($id_fils)) {
5358 $id_fils = 0;
5359 }
5360 if (!is_numeric($incdec)) {
5361 $incdec = 1;
5362 }
5363 if (!is_numeric($qty)) {
5364 $qty = 1;
5365 }
5366
5367 $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
5368 $sql .= 'qty = '.price2num($qty, 'MS');
5369 $sql .= ',incdec = '.((int) $incdec);
5370 $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
5371
5372 if (!$this->db->query($sql)) {
5373 dol_print_error($this->db);
5374 return -1;
5375 } else {
5376 if (!$notrigger) {
5377 // Call trigger
5378 $result = $this->call_trigger('PRODUCT_SUBPRODUCT_UPDATE', $user);
5379 if ($result < 0) {
5380 $this->error = $this->db->lasterror();
5381 dol_syslog(get_class($this).'::updateSubproduct error='.$this->error, LOG_ERR);
5382 return -1;
5383 }
5384 // End call triggers
5385 }
5386
5387 return 1;
5388 }
5389 }
5390
5391 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5400 public function del_sousproduit($fk_parent, $fk_child, $notrigger = 0)
5401 {
5402 // phpcs:enable
5403 global $user;
5404
5405 if (!is_numeric($fk_parent)) {
5406 $fk_parent = 0;
5407 }
5408 if (!is_numeric($fk_child)) {
5409 $fk_child = 0;
5410 }
5411
5412 $sql = "DELETE FROM ".$this->db->prefix()."product_association";
5413 $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
5414 $sql .= " AND fk_product_fils = ".((int) $fk_child);
5415
5416 dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
5417 if (!$this->db->query($sql)) {
5418 dol_print_error($this->db);
5419 return -1;
5420 }
5421
5422 // Updated ranks so that none are missing
5423 $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
5424 $sqlrank .= " WHERE fk_product_pere = ".((int) $fk_parent);
5425 $sqlrank .= " ORDER BY rang";
5426 $resqlrank = $this->db->query($sqlrank);
5427 if ($resqlrank) {
5428 $cpt = 0;
5429 while ($objrank = $this->db->fetch_object($resqlrank)) {
5430 $cpt++;
5431 $sql = "UPDATE ".$this->db->prefix()."product_association";
5432 $sql .= " SET rang = ".((int) $cpt);
5433 $sql .= " WHERE rowid = ".((int) $objrank->rowid);
5434 if (! $this->db->query($sql)) {
5435 dol_print_error($this->db);
5436 return -1;
5437 }
5438 }
5439 }
5440
5441 if (!$notrigger) {
5442 // Call trigger
5443 $result = $this->call_trigger('PRODUCT_SUBPRODUCT_DELETE', $user);
5444 if ($result < 0) {
5445 $this->error = $this->db->lasterror();
5446 dol_syslog(get_class($this).'::delSubproduct error='.$this->error, LOG_ERR);
5447 return -1;
5448 }
5449 // End call triggers
5450 }
5451
5452 return 1;
5453 }
5454
5455 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5463 public function is_sousproduit($fk_parent, $fk_child)
5464 {
5465 // phpcs:enable
5466 $sql = "SELECT fk_product_pere, qty, incdec";
5467 $sql .= " FROM ".$this->db->prefix()."product_association";
5468 $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
5469 $sql .= " AND fk_product_fils = ".((int) $fk_child);
5470
5471 $result = $this->db->query($sql);
5472 if ($result) {
5473 $num = $this->db->num_rows($result);
5474
5475 if ($num > 0) {
5476 $obj = $this->db->fetch_object($result);
5477
5478 $this->is_sousproduit_qty = $obj->qty;
5479 $this->is_sousproduit_incdec = $obj->incdec;
5480
5481 return 1;
5482 } else {
5483 return 0;
5484 }
5485 } else {
5486 dol_print_error($this->db);
5487 return -1;
5488 }
5489 }
5490
5491
5492 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5503 public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
5504 {
5505 // phpcs:enable
5506 global $conf;
5507
5508 $now = dol_now();
5509
5510 dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
5511
5512 // Clean parameters
5513 $quantity = price2num($quantity, 'MS');
5514
5515 if ($ref_fourn) {
5516 // Check if ref is not already used
5517 $sql = "SELECT rowid, fk_product";
5518 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
5519 $sql .= " WHERE fk_soc = ".((int) $id_fourn);
5520 $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
5521 $sql .= " AND fk_product <> ".((int) $this->id);
5522 $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
5523
5524 $resql = $this->db->query($sql);
5525 if ($resql) {
5526 $obj = $this->db->fetch_object($resql);
5527 if ($obj) {
5528 // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
5529 $this->product_id_already_linked = $obj->fk_product;
5530 return -3;
5531 }
5532 $this->db->free($resql);
5533 }
5534 }
5535
5536 $sql = "SELECT rowid";
5537 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
5538 $sql .= " WHERE fk_soc = ".((int) $id_fourn);
5539 if ($ref_fourn) {
5540 $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
5541 } else {
5542 $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
5543 }
5544 $sql .= " AND quantity = ".((float) $quantity);
5545 $sql .= " AND fk_product = ".((int) $this->id);
5546 $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
5547
5548 $resql = $this->db->query($sql);
5549 if ($resql) {
5550 $obj = $this->db->fetch_object($resql);
5551
5552 // The reference supplier does not exist, we create it for this product.
5553 if (empty($obj)) {
5554 $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
5555 $sql .= "datec";
5556 $sql .= ", entity";
5557 $sql .= ", fk_product";
5558 $sql .= ", fk_soc";
5559 $sql .= ", ref_fourn";
5560 $sql .= ", quantity";
5561 $sql .= ", fk_user";
5562 $sql .= ", tva_tx";
5563 $sql .= ") VALUES (";
5564 $sql .= "'".$this->db->idate($now)."'";
5565 $sql .= ", ".((int) $conf->entity);
5566 $sql .= ", ".((int) $this->id);
5567 $sql .= ", ".((int) $id_fourn);
5568 $sql .= ", '".$this->db->escape($ref_fourn)."'";
5569 $sql .= ", ".((float) $quantity);
5570 $sql .= ", ".((int) $user->id);
5571 $sql .= ", 0";
5572 $sql .= ")";
5573
5574 if ($this->db->query($sql)) {
5575 $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
5576 return 1;
5577 } else {
5578 $this->error = $this->db->lasterror();
5579 return -1;
5580 }
5581 } else {
5582 // If the supplier price already exists for this product and quantity
5583 $this->product_fourn_price_id = $obj->rowid;
5584 return 0;
5585 }
5586 } else {
5587 $this->error = $this->db->lasterror();
5588 return -2;
5589 }
5590 }
5591
5592
5593 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5599 public function list_suppliers()
5600 {
5601 // phpcs:enable
5602 global $conf;
5603
5604 $list = array();
5605
5606 $sql = "SELECT DISTINCT p.fk_soc";
5607 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
5608 $sql .= " WHERE p.fk_product = ".((int) $this->id);
5609 $sql .= " AND p.entity = ".((int) $conf->entity);
5610
5611 $result = $this->db->query($sql);
5612 if ($result) {
5613 $num = $this->db->num_rows($result);
5614 $i = 0;
5615 while ($i < $num) {
5616 $obj = $this->db->fetch_object($result);
5617 $list[$i] = $obj->fk_soc;
5618 $i++;
5619 }
5620 }
5621
5622 return $list;
5623 }
5624
5625 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5633 public function clone_price($fromId, $toId)
5634 {
5635 // phpcs:enable
5636 global $user;
5637
5638 $now = dol_now();
5639
5640 $this->db->begin();
5641
5642 // Default selling price and price levels
5643 $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
5644 $sql .= " entity";
5645 $sql .= ", fk_product";
5646 $sql .= ", date_price";
5647 $sql .= ", price_level";
5648 $sql .= ", price";
5649 $sql .= ", price_ttc";
5650 $sql .= ", price_min";
5651 $sql .= ", price_min_ttc";
5652 $sql .= ", price_base_type";
5653 $sql .= ", price_label";
5654 $sql .= ", default_vat_code";
5655 $sql .= ", tva_tx";
5656 $sql .= ", recuperableonly";
5657 $sql .= ", localtax1_tx";
5658 $sql .= ", localtax1_type";
5659 $sql .= ", localtax2_tx";
5660 $sql .= ", localtax2_type";
5661 $sql .= ", fk_user_author";
5662 $sql .= ", tosell";
5663 $sql .= ", price_by_qty";
5664 $sql .= ", fk_price_expression";
5665 $sql .= ", fk_multicurrency";
5666 $sql .= ", multicurrency_code";
5667 $sql .= ", multicurrency_tx";
5668 $sql .= ", multicurrency_price";
5669 $sql .= ", multicurrency_price_ttc";
5670 $sql .= ")";
5671 $sql .= " SELECT";
5672 $sql .= " entity";
5673 $sql .= ", ".((int) $toId);
5674 $sql .= ", '".$this->db->idate($now)."'";
5675 $sql .= ", price_level";
5676 $sql .= ", price";
5677 $sql .= ", price_ttc";
5678 $sql .= ", price_min";
5679 $sql .= ", price_min_ttc";
5680 $sql .= ", price_base_type";
5681 $sql .= ", price_label";
5682 $sql .= ", default_vat_code";
5683 $sql .= ", tva_tx";
5684 $sql .= ", recuperableonly";
5685 $sql .= ", localtax1_tx";
5686 $sql .= ", localtax1_type";
5687 $sql .= ", localtax2_tx";
5688 $sql .= ", localtax2_type";
5689 $sql .= ", ".((int) $user->id);
5690 $sql .= ", tosell";
5691 $sql .= ", price_by_qty";
5692 $sql .= ", fk_price_expression";
5693 $sql .= ", fk_multicurrency";
5694 $sql .= ", multicurrency_code";
5695 $sql .= ", multicurrency_tx";
5696 $sql .= ", multicurrency_price";
5697 $sql .= ", multicurrency_price_ttc";
5698 $sql .= " FROM ".$this->db->prefix()."product_price as ps";
5699 $sql .= " WHERE ps.fk_product = ".((int) $fromId);
5700 $sql .= " AND ps.date_price IN (SELECT MAX(pd.date_price) FROM ".$this->db->prefix()."product_price as pd WHERE pd.fk_product = ".((int) $fromId)." AND pd.price_level = ps.price_level)";
5701 $sql .= " ORDER BY ps.date_price DESC";
5702
5703 dol_syslog(__METHOD__, LOG_DEBUG);
5704 $resql = $this->db->query($sql);
5705 if (!$resql) {
5706 $this->db->rollback();
5707 return -1;
5708 }
5709 $this->db->free($resql);
5710
5711 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
5712 $this->cloneMultipriceExtra($fromId, $toId); // Add of level price extrafields
5713 }
5714 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
5715 $this->cloneCustomerPriceAndExtra($fromId, $toId); // Price per customer
5716 }
5717 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
5718 // Add of level price extrafields and price per customer
5719 $this->cloneMultipriceExtra($fromId, $toId); // Add of level price extrafields
5720 $this->cloneCustomerPriceAndExtra($fromId, $toId); // Price per customer
5721 }
5722
5723 $this->db->commit();
5724 return 1;
5725 }
5726
5727 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5735 public function clone_associations($fromId, $toId)
5736 {
5737 // phpcs:enable
5738 $this->db->begin();
5739
5740 $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty, incdec)';
5741 $sql .= " SELECT ".((int) $toId).", fk_product_fils, qty, incdec FROM ".$this->db->prefix()."product_association";
5742 $sql .= " WHERE fk_product_pere = ".((int) $fromId);
5743
5744 dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
5745 if (!$this->db->query($sql)) {
5746 $this->db->rollback();
5747 return -1;
5748 }
5749
5750 $this->db->commit();
5751 return 1;
5752 }
5753
5754 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5762 public function clone_fournisseurs($fromId, $toId)
5763 {
5764 // phpcs:enable
5765 $this->db->begin();
5766
5767 $now = dol_now();
5768
5769 // les fournisseurs
5770 /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
5771 . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
5772 . " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, ref_fourn, fk_user_author"
5773 . " FROM ".$this->db->prefix()."product_fournisseur"
5774 . " WHERE fk_product = ".((int) $fromId);
5775
5776 if ( ! $this->db->query($sql ) )
5777 {
5778 $this->db->rollback();
5779 return -1;
5780 }*/
5781
5782 // les prix de fournisseurs.
5783 // All the columns describing the price must be copied, not only the five historical ones:
5784 // unitprice defaults to 0 in the table and find_min_price_product_fournisseur() reads it
5785 // directly, so a partial copy makes the best buying price of the new product evaluate to 0.
5786 // entity defaults to 1 as well, which would move the rows out of their company.
5787 // ref_fourn and barcode are deliberately left empty: the unique keys
5788 // uk_product_fournisseur_price_ref (ref_fourn, fk_soc, quantity, entity) and
5789 // uk_product_barcode (barcode, fk_barcode_type, entity) do not contain fk_product, so
5790 // copying either value would collide with the row of the source product.
5791 $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
5792 $sql .= " datec, fk_product, entity, fk_soc, desc_fourn, fk_availability, price, quantity,";
5793 $sql .= " remise_percent, remise, unitprice, charges, default_vat_code, tva_tx,";
5794 $sql .= " localtax1_tx, localtax1_type, localtax2_tx, localtax2_type, info_bits, fk_user,";
5795 $sql .= " fk_supplier_price_expression, delivery_time_days, supplier_reputation, packaging,";
5796 $sql .= " fk_multicurrency, multicurrency_code, multicurrency_tx, multicurrency_unitprice,";
5797 $sql .= " multicurrency_price, status)";
5798 $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", entity, fk_soc, desc_fourn, fk_availability, price, quantity,";
5799 $sql .= " remise_percent, remise, unitprice, charges, default_vat_code, tva_tx,";
5800 $sql .= " localtax1_tx, localtax1_type, localtax2_tx, localtax2_type, info_bits, fk_user,";
5801 $sql .= " fk_supplier_price_expression, delivery_time_days, supplier_reputation, packaging,";
5802 $sql .= " fk_multicurrency, multicurrency_code, multicurrency_tx, multicurrency_unitprice,";
5803 $sql .= " multicurrency_price, status";
5804 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
5805 $sql .= " WHERE fk_product = ".((int) $fromId);
5806
5807 dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
5808 $resql = $this->db->query($sql);
5809 if (!$resql) {
5810 $this->db->rollback();
5811 return -1;
5812 } else {
5813 $this->db->commit();
5814 return 1;
5815 }
5816 }
5817
5818 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5831 public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
5832 {
5833 // phpcs:enable
5834 $tmpproduct = null;
5835
5836 if ($multiply < 1) {
5837 dol_syslog(get_class($this).'::'.__FUNCTION__.' Product quantity rounded up to 1 from '.$multiply.'. May result in unexpected end quantity for product children of '.$id_parent, LOG_WARNING);
5838 $multiply = 1;
5839 }
5840
5841 foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
5842 if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
5843 $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
5844 $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
5845 $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
5846 $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
5847 $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
5848
5849 //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
5850 if (is_null($tmpproduct)) {
5851 $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
5852 }
5853 $tmpproduct->fetch($id); // Load product to get ->ref
5854
5855 if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
5856 $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
5857 }
5858
5859 $this->res[] = array(
5860 'id' => $id, // Id product
5861 'id_parent' => $id_parent,
5862 'ref' => $tmpproduct->ref, // Ref product
5863 'nb' => $nb, // Nb of units that compose parent product
5864 'nb_total' => $nb * $multiply, // Nb of units for all nb of product
5865 'stock' => $tmpproduct->stock_reel, // Stock
5866 'stock_alert' => $tmpproduct->seuil_stock_alerte, // Stock alert
5867 'label' => $label,
5868 'fullpath' => $compl_path.$label, // Label
5869 'type' => $type, // Nb of units that compose parent product
5870 'desiredstock' => $tmpproduct->desiredstock,
5871 'level' => $level,
5872 'incdec' => $incdec,
5873 'entity' => $tmpproduct->entity
5874 );
5875
5876 // Recursive call if there child has children of its own
5877 if (isset($desc_pere['childs']) && is_array($desc_pere['childs'])) {
5878 if (!is_int($desc_pere[1] * $multiply)) {
5879 dol_syslog(get_class($this).'::'.__FUNCTION__.' Source product quantity and multiplier may result in unexpected end quantity for '.$label.'/'.$multiply.' Child product:'.json_encode($desc_pere), LOG_WARNING);
5880 }
5881
5882 //print 'YYY We go down for '.$desc_pere[3]." -> \n";
5883 $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", (int) ceil($desc_pere[1] * $multiply), $level + 1, $id, $ignore_stock_load);
5884 }
5885 }
5886 }
5887 }
5888
5889 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5898 public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
5899 {
5900 // phpcs:enable
5901 $this->res = array();
5902 if (isset($this->sousprods) && is_array($this->sousprods)) {
5903 foreach ($this->sousprods as $prod_name => $desc_product) {
5904 if (is_array($desc_product)) {
5905 $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load); // This set $this->res
5906 }
5907 }
5908 }
5909 return $this->res;
5910 }
5911
5919 public function hasFatherOrChild($mode = 0)
5920 {
5921 $nb = 0;
5922
5923 $sql = "SELECT COUNT(pa.rowid) as nb";
5924 $sql .= " FROM ".$this->db->prefix()."product_association as pa";
5925 if ($mode == 0) {
5926 $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
5927 } elseif ($mode == -1) {
5928 $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id); // We are a child, so we found lines that link to parents (can have several parents)
5929 } elseif ($mode == 1) {
5930 $sql .= " WHERE pa.fk_product_pere = ".((int) $this->id); // We are a parent, so we found lines that link to children (can have several children)
5931 }
5932
5933 $resql = $this->db->query($sql);
5934 if ($resql) {
5935 $obj = $this->db->fetch_object($resql);
5936 if ($obj) {
5937 $nb = (int) $obj->nb;
5938 }
5939 } else {
5940 return -1;
5941 }
5942
5943 return $nb;
5944 }
5945
5951 public function hasVariants()
5952 {
5953 $nb = 0;
5954 if (!isModEnabled('variants')) {
5955 return $nb;
5956 }
5957 $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
5958 $sql .= " AND entity IN (".getEntity('product').")";
5959
5960 $resql = $this->db->query($sql);
5961 if ($resql) {
5962 $obj = $this->db->fetch_object($resql);
5963 if ($obj) {
5964 $nb = (int) $obj->nb;
5965 }
5966 }
5967
5968 return $nb;
5969 }
5970
5971
5977 public function isVariant()
5978 {
5979 if (isModEnabled('variants')) {
5980 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
5981
5982 $query = $this->db->query($sql);
5983
5984 if ($query) {
5985 if (!$this->db->num_rows($query)) {
5986 return false;
5987 }
5988 return true;
5989 } else {
5990 dol_print_error($this->db);
5991 return -1;
5992 }
5993 } else {
5994 return false;
5995 }
5996 }
5997
6004 public function getFather()
6005 {
6006 $sql = "SELECT p.rowid, p.label as label, p.ref as ref, pa.fk_product_pere as id, p.fk_product_type, pa.qty, pa.incdec, p.entity";
6007 $sql .= ", p.tosell as status, p.tobuy as status_buy";
6008 $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
6009 $sql .= " ".$this->db->prefix()."product as p";
6010 $sql .= " WHERE p.rowid = pa.fk_product_pere";
6011 $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
6012
6013 $res = $this->db->query($sql);
6014 if ($res) {
6015 $prods = array();
6016 while ($record = $this->db->fetch_array($res)) {
6017 // $record['id'] = $record['rowid'] = id of father
6018 $prods[$record['id']] = array();
6019 $prods[$record['id']]['id'] = $record['rowid'];
6020 $prods[$record['id']]['ref'] = $record['ref'];
6021 $prods[$record['id']]['label'] = $record['label'];
6022 $prods[$record['id']]['qty'] = $record['qty'];
6023 $prods[$record['id']]['incdec'] = $record['incdec'];
6024 $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
6025 $prods[$record['id']]['entity'] = $record['entity'];
6026 $prods[$record['id']]['status'] = $record['status'];
6027 $prods[$record['id']]['status_buy'] = $record['status_buy'];
6028 }
6029 return $prods;
6030 } else {
6031 dol_print_error($this->db);
6032 return -1;
6033 }
6034 }
6035
6036
6046 public function getChildsArbo($id, $firstlevelonly = 0, $level = 1, $parents = array())
6047 {
6048 if (empty($id)) {
6049 return array();
6050 }
6051
6052 $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
6053 $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
6054 $sql .= " pa.rowid as fk_association, pa.rang";
6055 $sql .= " FROM ".$this->db->prefix()."product as p,";
6056 $sql .= " ".$this->db->prefix()."product_association as pa";
6057 $sql .= " WHERE p.rowid = pa.fk_product_fils";
6058 $sql .= " AND pa.fk_product_pere = ".((int) $id);
6059 $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
6060 $sql .= " ORDER BY pa.rang";
6061
6062 dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level. ' parents='.(is_array($parents) ? implode(',', $parents) : $parents), LOG_DEBUG);
6063
6064 // Protection against infinite loop
6065 if ($level > 30) {
6066 return array();
6067 }
6068
6069 $res = $this->db->query($sql);
6070 if ($res) {
6071 $prods = array();
6072 if ($this->db->num_rows($res) > 0) {
6073 $parents[] = $id;
6074 }
6075
6076 while ($rec = $this->db->fetch_array($res)) {
6077 if (in_array($rec['id'], $parents)) {
6078 dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING);
6079 continue; // We discard this child if it is already found at a higher level in tree in the same branch.
6080 }
6081
6082 $prods[$rec['rowid']] = array(
6083 0 => $rec['rowid'],
6084 1 => $rec['qty'],
6085 2 => $rec['fk_product_type'],
6086 3 => $this->db->escape($rec['label']),
6087 4 => $rec['incdec'],
6088 5 => $rec['ref'],
6089 6 => $rec['fk_association'],
6090 7 => $rec['rang']
6091 );
6092 //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
6093 //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
6094 if (empty($firstlevelonly)) {
6095 $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1, $parents);
6096 foreach ($listofchilds as $keyChild => $valueChild) {
6097 $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
6098 }
6099 }
6100 }
6101
6102 return $prods;
6103 } else {
6104 dol_print_error($this->db);
6105 return -1;
6106 }
6107 }
6108
6109 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6116 public function get_sousproduits_arbo()
6117 {
6118 // phpcs:enable
6119 $parent = array();
6120
6121 foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
6122 $parent[$this->label][$keyChild] = $valueChild;
6123 }
6124 foreach ($parent as $key => $value) { // key=label, value is array of children
6125 $this->sousprods[$key] = $value; // @phan-suppress-current-line PhanTypeMismatchProperty
6126 }
6127 }
6128
6136 public function getTooltipContentArray($params)
6137 {
6138 global $conf, $langs, $user;
6139
6140 $langs->loadLangs(array('products', 'other'));
6141
6142 $datas = array();
6143 $nofetch = !empty($params['nofetch']);
6144
6145 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
6146 return ['optimize' => $langs->trans("ShowProduct")];
6147 }
6148
6149 // Does user has permission to read product/service
6150 $permissiontoreadproduct = 0;
6151 if ($this->type == self::TYPE_PRODUCT && $user->hasRight('product', 'read')) {
6152 $permissiontoreadproduct = 1;
6153 }
6154 if ($this->type == self::TYPE_SERVICE && $user->hasRight('service', 'read')) {
6155 $permissiontoreadproduct = 1;
6156 }
6157
6158 if (!empty($this->entity) && $permissiontoreadproduct) {
6159 $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80, 0, 0, 0, 0, '1');
6160 if ($this->nbphoto > 0) {
6161 $datas['photo'] = '<div class="photointooltip floatright">'."\n" . $tmpphoto . '</div>';
6162 }
6163 }
6164
6165 if ($this->isProduct()) {
6166 $datas['picto'] = img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
6167 } elseif ($this->isService()) {
6168 $datas['picto'] = img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
6169 }
6170 if (isset($this->status) && isset($this->status_buy)) {
6171 $datas['status'] = ' '.$this->getLibStatut(5, 0) . ' '.$this->getLibStatut(5, 1);
6172 }
6173
6174 if (!empty($this->ref)) {
6175 $datas['ref'] = '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
6176 }
6177 if (!empty($this->label)) {
6178 $datas['label'] = '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label.'<br>';
6179 }
6180
6181 if ($permissiontoreadproduct) {
6182 if (!empty($this->description) && getDolGlobalString('PRODUCT_SHOW_DESCRIPTION_IN_TOOLTIP')) {
6183 $datas['description'] = '<br><b>'.$langs->trans('ProductDescription').':</b> '.dolGetFirstLineOfText($this->description, 5);
6184 }
6185
6186 $datas['stockmanaged'] = "<br><b>".$langs->trans("StockableProduct").'</b>: '.yn($this->isStockManaged());
6187
6188 if ($this->isStockManaged()) {
6189 if (isModEnabled('productbatch')) {
6190 $langs->load("productbatch");
6191 $datas['batchstatus'] = "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
6192 if ($this->status_batch) {
6193 $datas['batchdlc'] = "<br><b>".$langs->trans("BatchSellOrEatByMandatoryList", $langs->transnoentitiesnoconv("SellByDate"), $langs->transnoentitiesnoconv("EatByDate")).'</b>: '.$this->getSellOrEatByMandatoryLabel();
6194 }
6195 }
6196 }
6197 if (isModEnabled('barcode')) {
6198 $datas['barcode'] = '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
6199 }
6200
6201 if ($this->isProduct()) {
6202 if ($this->weight) {
6203 $datas['weight'] = "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
6204 }
6205 $labelsize = "";
6206 if ($this->length) {
6207 $labelsize .= "<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
6208 }
6209 if ($this->width) {
6210 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
6211 }
6212 if ($this->height) {
6213 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
6214 }
6215 if ($labelsize) {
6216 $datas['size'] = "<br>".$labelsize;
6217 }
6218
6219 $labelsurfacevolume = "";
6220 if ($this->surface) {
6221 $labelsurfacevolume .= "<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
6222 }
6223 if ($this->volume) {
6224 $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
6225 }
6226 if ($labelsurfacevolume) {
6227 $datas['surface'] = "<br>" . $labelsurfacevolume;
6228 }
6229 }
6230 if ($this->isService() && !empty($this->duration_value)) {
6231 // Duration
6232 $datas['duration'] = '<br><b>'.$langs->trans("Duration").':</b> '.$this->duration_value;
6233 if ($this->duration_value > 1) {
6234 $dur = array("i" => $langs->trans("Minutes"), "h" => $langs->trans("Hours"), "d" => $langs->trans("Days"), "w" => $langs->trans("Weeks"), "m" => $langs->trans("Months"), "y" => $langs->trans("Years"));
6235 } elseif ($this->duration_value > 0) {
6236 $dur = array("i" => $langs->trans("Minute"), "h" => $langs->trans("Hour"), "d" => $langs->trans("Day"), "w" => $langs->trans("Week"), "m" => $langs->trans("Month"), "y" => $langs->trans("Year"));
6237 }
6238 $datas['duration'] .= (!empty($this->duration_unit) && isset($dur[$this->duration_unit]) ? "&nbsp;".$langs->trans($dur[$this->duration_unit]) : '');
6239 }
6240 if (empty($user->socid)) {
6241 if ($this->isStockManaged() && isset($this->pmp) && $this->pmp) {
6242 $datas['pmp'] = "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
6243 }
6244
6245 if (isModEnabled('accounting')) {
6246 if ($this->status && isset($this->accountancy_code_sell)) {
6247 include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
6248 $selllabel = '<br>';
6249 $selllabel .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
6250 $selllabel .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
6251 $selllabel .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
6252 $datas['accountancysell'] = $selllabel;
6253 }
6254 if ($this->status_buy && isset($this->accountancy_code_buy)) {
6255 include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
6256 $buylabel = '';
6257 if (empty($this->status)) {
6258 $buylabel .= '<br>';
6259 }
6260 $buylabel .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
6261 $buylabel .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
6262 $buylabel .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
6263 $datas['accountancybuy'] = $buylabel;
6264 }
6265 }
6266 }
6267 // show categories for this record only in ajax to not overload lists
6268 if (isModEnabled('category') && !$nofetch) {
6269 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
6270 $form = new Form($this->db);
6271 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_PRODUCT, 1);
6272 }
6273 }
6274
6275 return $datas;
6276 }
6277
6292 public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ', $addlinktonotes = 0)
6293 {
6294 global $langs, $hookmanager, $user;
6295
6296 include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
6297
6298 $result = '';
6299
6300 $newref = (string) $this->ref;
6301 if ($maxlength) {
6302 $newref = dol_trunc($newref, $maxlength, 'middle');
6303 }
6304 $params = [
6305 'id' => $this->id,
6306 'objecttype' => ($this->type == 1 ? 'service' : 'product'),
6307 'option' => $option,
6308 'nofetch' => 1,
6309 ];
6310 $classfortooltip = 'classfortooltip';
6311 $dataparams = '';
6312 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
6313 $classfortooltip = 'classforajaxtooltip';
6314 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
6315 $label = '';
6316 } else {
6317 $label = implode($this->getTooltipContentArray($params));
6318 }
6319
6320 $linkclose = '';
6321 if (empty($notooltip)) {
6322 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
6323 $label = $langs->trans("ShowProduct");
6324 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1, 1).'"';
6325 }
6326 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1, 1).'"' : ' title="tocomplete"');
6327 $linkclose .= $dataparams.' class="nowraponall '.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
6328 } else {
6329 $linkclose = ' class="nowraponall'.($morecss ? ' '.$morecss : '').'"';
6330 }
6331
6332 if ($option == 'supplier' || $option == 'category') {
6333 $baseurl = DOL_URL_ROOT.'/product/price_suppliers.php';
6334 } elseif ($option == 'stock') {
6335 $baseurl = DOL_URL_ROOT.'/product/stock/product.php';
6336 } elseif ($option == 'composition') {
6337 $baseurl = DOL_URL_ROOT.'/product/composition/card.php';
6338 } else {
6339 $baseurl = DOL_URL_ROOT.'/product/card.php';
6340 }
6341 $query = ['id' => $this->id];
6342
6343 if ($option !== 'nolink') {
6344 // Add param to save lastsearch_values or not
6345 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
6346 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
6347 $add_save_lastsearch_values = 1;
6348 }
6349 if ($add_save_lastsearch_values) {
6350 $query = array_merge($query, ['save_lastsearch_values' => 1]);
6351 }
6352 }
6353 $url = dolBuildUrl($baseurl, $query);
6354
6355 $linkstart = '<a href="'.$url.'"';
6356 $linkstart .= $linkclose.'>';
6357 $linkend = '</a>';
6358
6359 $result .= $linkstart;
6360 if ($withpicto) {
6361 if ($this->isProduct()) {
6362 $result .= (img_object(($notooltip ? '' : $label), 'product', 'class="paddingright"', 0, 0, $notooltip ? 0 : 1));
6363 }
6364 if ($this->isService()) {
6365 $result .= (img_object(($notooltip ? '' : $label), 'service', 'class="paddingright"', 0, 0, $notooltip ? 0 : 1));
6366 }
6367 }
6368 $result .= '<span class="aaa">'.dol_escape_htmltag($newref).'</span>';
6369 $result .= $linkend;
6370 if ($withpicto != 2) {
6371 $result .= (($add_label && $this->label) ? $sep.dol_trunc($this->label, ($add_label > 1 ? $add_label : 0)) : '');
6372 }
6373
6374 if ($addlinktonotes) {
6375 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
6376 if ($txttoshow) {
6377 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
6378 $result .= ' <span class="note inline-block">';
6379 $result .= '<a href="'.DOL_URL_ROOT.'/product/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
6380 $result .= img_picto('', 'note');
6381 $result .= '</a>';
6382 $result .= '</span>';
6383 }
6384 }
6385
6386 global $action;
6387 $hookmanager->initHooks(array('productdao'));
6388 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'label' => &$label);
6389 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6390 if ($reshook > 0) {
6391 $result = $hookmanager->resPrint;
6392 } else {
6393 $result .= $hookmanager->resPrint;
6394 }
6395
6396 return $result;
6397 }
6398
6399
6410 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
6411 {
6412 global $langs;
6413
6414 $langs->load("products");
6415 $outputlangs->load("products");
6416
6417 // Set the model to the name of the model to use
6418 if (!dol_strlen($modele)) {
6419 $modele = ''; // No doc template/generation by default
6420
6421 if (!empty($this->model_pdf)) {
6422 $modele = $this->model_pdf;
6423 } elseif (getDolGlobalString('PRODUCT_ADDON_PDF')) {
6424 $modele = getDolGlobalString('PRODUCT_ADDON_PDF');
6425 }
6426 }
6427
6428 if (empty($modele)) {
6429 return 0;
6430 } else {
6431 $modelpath = "core/modules/product/doc/";
6432 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
6433 }
6434 }
6435
6443 public function getLibStatut($mode = 0, $type = 0)
6444 {
6445 switch ($type) {
6446 case 0:
6447 return $this->LibStatut($this->status, $mode, $type);
6448 case 1:
6449 return $this->LibStatut($this->status_buy, $mode, $type);
6450 case 2:
6451 return $this->LibStatut($this->status_batch, $mode, $type);
6452 default:
6453 //Simulate previous behavior but should return an error string
6454 return $this->LibStatut($this->status_buy, $mode, $type);
6455 }
6456 }
6457
6458 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6467 public function LibStatut($status, $mode = 0, $type = 0)
6468 {
6469 // phpcs:enable
6470 global $langs;
6471
6472 $labelStatus = $labelStatusShort = '';
6473
6474 $langs->load('products');
6475 if (isModEnabled('productbatch')) {
6476 $langs->load("productbatch");
6477 }
6478
6479 if ($type == 2) {
6480 switch ($mode) {
6481 case 0:
6482 $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
6483 return dolGetStatus($label);
6484 case 1:
6485 $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
6486 return dolGetStatus($label);
6487 case 2:
6488 return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
6489 case 3:
6490 return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
6491 case 4:
6492 return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
6493 case 5:
6494 return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
6495 default:
6496 return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
6497 }
6498 }
6499
6500 $statuttrans = empty($status) ? 'status5' : 'status4';
6501
6502 if ($status == 0) {
6503 // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
6504 if ($type == 0) {
6505 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
6506 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
6507 } elseif ($type == 1) {
6508 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
6509 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
6510 } elseif ($type == 2) {
6511 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
6512 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
6513 }
6514 } elseif ($status == 1) {
6515 // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
6516 if ($type == 0) {
6517 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
6518 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
6519 } elseif ($type == 1) {
6520 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
6521 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
6522 } elseif ($type == 2) {
6523 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBatch');
6524 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBatchShort');
6525 }
6526 } elseif ($type == 2 && $status == 2) {
6527 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
6528 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
6529 }
6530
6531 if ($mode > 6) {
6532 return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
6533 } else {
6534 return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
6535 }
6536 }
6537
6538
6544 public function getLibFinished()
6545 {
6546 global $langs;
6547
6548 $langs->load('products');
6549 $label = '';
6550
6551 if (isset($this->finished) && $this->finished >= 0) {
6552 $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
6553 $resql = $this->db->query($sql);
6554 if (!$resql) {
6555 $this->error = $this->db->error().' sql='.$sql;
6556 dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
6557 return -1;
6558 } elseif ($this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
6559 $label = $langs->trans($res['label']);
6560 }
6561 $this->db->free($resql);
6562 }
6563
6564 return $label;
6565 }
6566
6567
6568 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6585 public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
6586 {
6587 // phpcs:enable
6588 if ($id_entrepot) {
6589 $this->db->begin();
6590
6591 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
6592
6593 // Ensure $nbpiece is a number and positive
6594 $nbpiece = (float) $nbpiece;
6595 if ($nbpiece < 0) {
6596 if (!$movement) {
6597 $movement = 1;
6598 }
6599 $nbpiece = abs($nbpiece);
6600 }
6601 $op = array();
6602 $op[0] = $nbpiece;
6603 $op[1] = -$nbpiece;
6604
6605 $movementstock = new MouvementStock($this->db);
6606 $movementstock->setOrigin($origin_element, (int) $origin_id); // Set ->origin_type and ->origin_id
6607 $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
6608
6609 if ($result >= 0) {
6610 if ($extrafields) {
6611 $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
6612 $movementstock->array_options = $array_options;
6613 $movementstock->insertExtraFields();
6614 }
6615 $this->db->commit();
6616 return 1;
6617 } else {
6618 $this->setErrorsFromObject($movementstock);
6619
6620 $this->db->rollback();
6621 return -1;
6622 }
6623 }
6624
6625 return -1;
6626 }
6627
6628 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6649 public function correct_stock_batch($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $dlc = '', $dluo = '', $lot = '', $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null, $force_update_batch = false)
6650 {
6651 // phpcs:enable
6652 if ($id_entrepot) {
6653 $this->db->begin();
6654
6655 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
6656
6657 // Ensure $nbpiece is a number and positive
6658 $nbpiece = (float) $nbpiece;
6659 if ($nbpiece < 0) {
6660 if (!$movement) {
6661 $movement = 1;
6662 }
6663 $nbpiece = abs($nbpiece);
6664 }
6665
6666 $op = array();
6667 $op[0] = $nbpiece;
6668 $op[1] = -$nbpiece;
6669
6670 $movementstock = new MouvementStock($this->db);
6671 $movementstock->setOrigin($origin_element, (int) $origin_id); // Set ->origin_type and ->fk_origin
6672 $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct, 0, $force_update_batch);
6673
6674 if ($result >= 0) {
6675 if ($extrafields) {
6676 $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
6677 $movementstock->array_options = $array_options;
6678 $movementstock->insertExtraFields();
6679 }
6680 $this->db->commit();
6681 return 1;
6682 } else {
6683 $this->error = $movementstock->error;
6684 $this->errors = $movementstock->errors;
6685
6686 $this->db->rollback();
6687 return -1;
6688 }
6689 }
6690 return -1;
6691 }
6692
6693 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6706 public function load_stock($option = '', $includedraftpoforvirtual = null, $dateofvirtualstock = null)
6707 {
6708 // phpcs:enable
6709 $this->stock_reel = 0;
6710 $this->stock_warehouse = array();
6711 $this->stock_theorique = 0;
6712
6713 // Set filter on warehouse status
6714 $warehouseStatus = array();
6715 if (preg_match('/warehouseclosed/', $option)) {
6717 }
6718 if (preg_match('/warehouseopen/', $option)) {
6720 }
6721 if (preg_match('/warehouseinternal/', $option)) {
6722 if (getDolGlobalString('ENTREPOT_EXTRA_STATUS')) {
6724 } else {
6726 }
6727 }
6728
6729 $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
6730 $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
6731 $sql .= ", ".$this->db->prefix()."entrepot as w";
6732 $sql .= " WHERE w.entity IN (".getEntity('stock').")";
6733 $sql .= " AND w.rowid = ps.fk_entrepot";
6734 $sql .= " AND ps.fk_product = ".((int) $this->id);
6735 if (count($warehouseStatus)) {
6736 $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
6737 }
6738
6739 $sql .= " ORDER BY ps.reel ".(getDolGlobalString('DO_NOT_TRY_TO_DEFRAGMENT_STOCKS_WAREHOUSE') ? 'DESC' : 'ASC'); // Note : qty ASC is important for expedition card, to avoid stock fragmentation;
6740
6741 dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
6742 $result = $this->db->query($sql);
6743 if ($result) {
6744 $num = $this->db->num_rows($result);
6745 $i = 0;
6746 if ($num > 0) {
6747 while ($i < $num) {
6748 $row = $this->db->fetch_object($result);
6749 $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
6750 $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
6751 $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
6752 if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
6753 $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
6754 }
6755 $this->stock_reel += $row->reel;
6756 $i++;
6757 }
6758 $this->stock_reel = (float) price2num($this->stock_reel, 'MS');
6759 }
6760 $this->db->free($result);
6761
6762 if (!preg_match('/novirtual/', $option)) {
6763 $this->load_virtual_stock($includedraftpoforvirtual, $dateofvirtualstock); // This load stock_theorique and also load all arrays stats_xxx...
6764 }
6765
6766 return 1;
6767 } else {
6768 $this->error = $this->db->lasterror();
6769 return -1;
6770 }
6771 }
6772
6773
6774 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6784 public function load_virtual_stock($includedraftpoforvirtual = null, $dateofvirtualstock = null)
6785 {
6786 // phpcs:enable
6787 global $hookmanager, $action;
6788
6789 $stock_commande_client = 0;
6790 $stock_commande_fournisseur = 0;
6791 $stock_sending_client = 0;
6792 $stock_reception_fournisseur = 0;
6793 $stock_inproduction = 0;
6794
6795 //dol_syslog("load_virtual_stock");
6796
6797 // If the caller did not provide a date, apply the virtual stock horizon (option STOCK_VIRTUAL_HORIZON_IN_DAYS):
6798 // incoming supply expected after this horizon is ignored, so the theoretical stock does not promise goods that are still far away.
6799 // An empty option means no horizon at all (default). A value of 0 is a valid horizon: only supply already due is counted.
6800 $horizoninDays = getDolGlobalString('STOCK_VIRTUAL_HORIZON_IN_DAYS');
6801 $dateofvirtualstockmin = 0;
6802 if (empty($dateofvirtualstock) && $horizoninDays !== '') {
6803 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // dol_time_plus_duree/dol_get_first_hour are not loaded in CLI/webservice contexts
6804 $dateofvirtualstock = dol_time_plus_duree(dol_now(), max(0, (int) $horizoninDays), 'd');
6805 $dateofvirtualstockmin = dol_get_first_hour(dol_now()); // The horizon is a window: supply expected before today did not arrive as planned
6806 }
6807
6808 if (isModEnabled('order')) {
6809 $result = $this->load_stats_commande(0, '1,2', 1);
6810 if ($result < 0) {
6811 dol_print_error($this->db, $this->error);
6812 }
6813 $stock_commande_client = $this->stats_commande['qty'];
6814 }
6815 if (isModEnabled("shipping")) {
6816 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
6817 $filterShipmentStatus = '';
6818 if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT')) {
6819 $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
6820 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
6821 $filterShipmentStatus = Expedition::STATUS_CLOSED;
6822 }
6823 $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
6824 if ($result < 0) {
6825 dol_print_error($this->db, $this->error);
6826 }
6827 $stock_sending_client = $this->stats_expedition['qty'];
6828 }
6829 // Include supplier order lines
6830 if (isModEnabled("supplier_order")) {
6831 $filterStatus = getDolGlobalString('SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK', '3,4');
6832 if (isset($includedraftpoforvirtual)) {
6833 $filterStatus = '0,1,2,'.$filterStatus; // 1,2 may have already been inside $filterStatus but it is better to have twice than missing $filterStatus does not include them
6834 }
6835 $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1, $dateofvirtualstock, $dateofvirtualstockmin);
6836 if ($result < 0) {
6837 dol_print_error($this->db, $this->error);
6838 }
6839 $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
6840 }
6841 // Include reception lines
6842 if (isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) {
6843 $filterStatus = getDolGlobalString('SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK', '4');
6844 if (isset($includedraftpoforvirtual)) {
6845 $filterStatus = '0,'.$filterStatus;
6846 }
6847 $result = $this->load_stats_reception(0, $filterStatus, 1, $dateofvirtualstock, $dateofvirtualstockmin);
6848 if ($result < 0) {
6849 dol_print_error($this->db, $this->error);
6850 }
6851 $stock_reception_fournisseur = $this->stats_reception['qty'];
6852 }
6853 // Include manufacturing
6854 if (isModEnabled('mrp')) {
6855 $filterStatus = getDolGlobalString('MO_STATUS_FOR_VIRTUAL_STOCK', '1,2');
6856 $result = $this->load_stats_inproduction(0, $filterStatus, 1, $dateofvirtualstock, 0, $dateofvirtualstockmin);
6857 if ($result < 0) {
6858 dol_print_error($this->db, $this->error);
6859 }
6860 $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
6861 }
6862
6863 $this->stock_theorique = $this->stock_reel + $stock_inproduction;
6864
6865 // $weBillOrderOrShipmentReception is set to 'order' or 'shipmentreception'. it will be used to know how to make virtual stock
6866 // calculation when we have a stock increase or decrease on billing. Do we have to count orders to bill or shipment/reception to bill ?
6867 $weBillOrderOrShipmentReception = getDolGlobalString('STOCK_DO_WE_BILL_ORDER_OR_SHIPMENTECEPTION_FOR_VIRTUALSTOCK', 'order');
6868
6869 // Stock decrease mode
6870 if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
6871 $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
6872 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER')) {
6873 if (getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER_INCLUDE_DRAFT')) { // By default, draft means "does not exist", so we do not include them by default, except if option is on
6874 $tmpnewprod = dol_clone($this, 1);
6875 $result = $tmpnewprod->load_stats_commande(0, '0', 1); // Get qty in draft orders
6876 $this->stock_theorique += $tmpnewprod->stats_commande['qty'];
6877 }
6878 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $weBillOrderOrShipmentReception == 'order') {
6879 $this->stock_theorique -= $stock_commande_client;
6880 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $weBillOrderOrShipmentReception == 'shipmentreception') {
6881 $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
6882 }
6883
6884 // Stock Increase mode
6885 if (getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE')) {
6886 $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
6887 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER')) { // This option is similar to STOCK_CALCULATE_ON_RECEPTION_CLOSE but when module Reception is not enabled
6888 $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
6889 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER')) { // Warning: stock change "on approval", not on validation !
6890 if (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER_INCLUDE_DRAFT')) { // By default, draft means "does not exist", so we do not include them by default, except if option is on
6891 $tmpnewprod = dol_clone($this, 1);
6892 $result = $tmpnewprod->load_stats_commande_fournisseur(0, '0', 1); // Get qty in draft orders
6893 $this->stock_theorique += $this->stats_commande_fournisseur['qty'];
6894 }
6895 $this->stock_theorique -= $stock_reception_fournisseur;
6896 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $weBillOrderOrShipmentReception == 'order') {
6897 $this->stock_theorique += $stock_commande_fournisseur;
6898 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $weBillOrderOrShipmentReception == 'shipmentreception') {
6899 $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
6900 }
6901
6902 $parameters = array('id' => $this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
6903 // Note that $action and $object may have been modified by some hooks
6904 $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
6905 if ($reshook > 0) {
6906 $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
6907 } elseif ($reshook == 0 && isset($hookmanager->resArray['stock_stats_hook'])) {
6908 $this->stock_theorique += $hookmanager->resArray['stock_stats_hook'];
6909 }
6910
6911 //Virtual Stock by Warehouse
6912 if (!empty($this->stock_warehouse) && getDolGlobalString('STOCK_ALLOW_VIRTUAL_STOCK_PER_WAREHOUSE')) {
6913 foreach ($this->stock_warehouse as $warehouseid => $stockwarehouse) {
6914 if (isModEnabled('mrp')) {
6915 $result = $this->load_stats_inproduction(0, getDolGlobalString('MO_STATUS_FOR_VIRTUAL_STOCK', '1,2'), 1, $dateofvirtualstock, $warehouseid, $dateofvirtualstockmin);
6916 if ($result < 0) {
6917 dol_print_error($this->db, $this->error);
6918 }
6919 }
6920
6921 if ($this->fk_default_warehouse == $warehouseid) {
6922 $this->stock_warehouse[$warehouseid]->virtual = $this->stock_warehouse[$warehouseid]->real + $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] + $this->stats_commande_fournisseur['qty'] - ($this->stats_commande['qty'] + $this->stats_mrptoconsume['qty']);
6923 } else {
6924 $this->stock_warehouse[$warehouseid]->virtual = $this->stock_warehouse[$warehouseid]->real + $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'];
6925 }
6926 }
6927 }
6928
6929 return 1;
6930 }
6931
6939 public function loadStockForVirtualProduct($option = '', $qtyWish = 1)
6940 {
6941 $this->stock_warehouse = array();
6942 $error = 0;
6943
6944 $this->get_sousproduits_arbo();
6945 $prods_arbo = $this->get_arbo_each_prod($qtyWish, 1);
6946 if (count($prods_arbo) > 0) {
6947 $productCachedList = array();
6948 $stockByComponentList = array();
6949
6950 foreach ($prods_arbo as $componentArr) {
6951 $componentId = $componentArr['id'];
6952 // only component whose manage stock
6953 if ($componentArr['incdec'] == 1) {
6954 if (!isset($productCachedList[$componentId])) {
6955 $componentStatic = new self($this->db);
6956 $componentStatic->fetch($componentId);
6957 // check if it's a sub-kit
6958 $childrenNb = $componentStatic->hasFatherOrChild(1);
6959 if ($childrenNb == 0) {
6960 $componentStatic->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
6961 if (!isset($stockByComponentList[$componentId])) {
6962 $stockByComponentList[$componentId] = array(
6963 'qty_need' => 0
6964 );
6965 }
6966 $stockByComponentList[$componentId]['qty_need'] += $componentArr['nb_total'];
6967 }
6968 $productCachedList[$componentId] = $componentStatic;
6969 }
6970 }
6971 }
6972
6973 if (!empty($stockByComponentList)) {
6974 foreach ($stockByComponentList as $componentId => $stockByComponentArr) {
6975 if (!isset($productCachedList[$componentId])) {
6976 $componentStatic = new self($this->db);
6977 $componentStatic->fetch($componentId);
6978 $componentStatic->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
6979 $productCachedList[$componentId] = $componentStatic;
6980 }
6981 $component = $productCachedList[$componentId];
6982
6983
6984 if ($component->stock_reel < $stockByComponentArr['qty_need']) {
6985 // not enough stock for this component to assemble this virtual product
6986 $error++;
6987 $this->error = 'Not enough component [id='.$componentId.'] in stock, real='.$component->stock_reel.' and need='.$stockByComponentArr['qty_need'];
6988 $this->errors[] = $this->error;
6989 dol_syslog(__METHOD__.' : '.$this->error, LOG_ERR);
6990 } else {
6991 if (!empty($component->stock_warehouse)) {
6992 foreach ($component->stock_warehouse as $warehouseId => $warehouseObj) {
6993 $kitWarehouseAvailable = new stdClass();
6994 $kitWarehouseAvailable->id = $warehouseObj->id;
6995 $kitWarehouseAvailable->real = $qtyWish;
6996 $this->stock_warehouse[$warehouseId] = $kitWarehouseAvailable;
6997 }
6998 }
6999 }
7000
7001 if ($error) {
7002 break;
7003 }
7004 }
7005 } elseif (getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE') && empty($productCachedList)) {
7006 // if all sub product are not stock managed when use parent stock
7007 $this->load_stock('warehouseopen');
7008 }
7009 }
7010
7011 if ($error) {
7012 return -1;
7013 } else {
7014 return 1;
7015 }
7016 }
7017
7025 public function loadBatchInfo($batch)
7026 {
7027 $result = array();
7028
7029 // The dates of the lot are read from llx_product_lot (eatby and sellby of llx_product_batch are deprecated and not updated when the lot is modified)
7030 $sql = "SELECT pb.batch, pl.eatby, pl.sellby, SUM(pb.qty) AS qty FROM ".$this->db->prefix()."product_batch as pb";
7031 $sql .= " INNER JOIN ".$this->db->prefix()."product_stock as ps ON pb.fk_product_stock = ps.rowid";
7032 $sql .= " LEFT JOIN ".$this->db->prefix()."product_lot as pl ON pl.fk_product = ps.fk_product AND pl.batch = pb.batch";
7033 $sql .= " WHERE ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
7034 $sql .= " GROUP BY pb.batch, pl.eatby, pl.sellby";
7035 dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
7036 $resql = $this->db->query($sql);
7037 if ($resql) {
7038 $num = $this->db->num_rows($resql);
7039 $i = 0;
7040 while ($i < $num) {
7041 $obj = $this->db->fetch_object($resql);
7042 $result[] = array('batch' => $batch, 'eatby' => $this->db->jdate($obj->eatby), 'sellby' => $this->db->jdate($obj->sellby), 'qty' => $obj->qty);
7043 $i++;
7044 }
7045 return $result;
7046 } else {
7047 dol_print_error($this->db);
7048 $this->db->rollback();
7049 return array();
7050 }
7051 }
7052
7053 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7062 public function add_photo($sdir, $file)
7063 {
7064 // phpcs:enable
7065 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
7066
7067 $result = 0;
7068
7069 $dir = $sdir;
7070 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
7071 $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
7072 } else {
7073 $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
7074 }
7075
7076 dol_mkdir($dir);
7077
7078 $dir_osencoded = $dir;
7079
7080 if (is_dir($dir_osencoded)) {
7081 $originImage = $dir.'/'.$file['name'];
7082
7083 // Cree fichier en taille origine
7084 $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
7085
7086 if (file_exists(dol_osencode($originImage))) {
7087 // Create thumbs
7088 $this->addThumbs($originImage);
7089 }
7090 }
7091
7092 if (is_numeric($result) && $result > 0) {
7093 return 1;
7094 } else {
7095 return -1;
7096 }
7097 }
7098
7099 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7106 public function is_photo_available($sdir)
7107 {
7108 // phpcs:enable
7109 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
7110 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
7111
7112 $dir = $sdir;
7113 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
7114 $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
7115 } else {
7116 $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
7117 }
7118
7119 $dir_osencoded = dol_osencode($dir);
7120 if (file_exists($dir_osencoded)) {
7121 $handle = opendir($dir_osencoded);
7122 if (is_resource($handle)) {
7123 while (($file = readdir($handle)) !== false) {
7124 if (!utf8_check($file)) {
7125 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
7126 }
7127 if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
7128 return true;
7129 }
7130 }
7131 }
7132 }
7133
7134 return false;
7135 }
7136
7137 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7145 public function liste_photos($dir, $nbmax = 0)
7146 {
7147 // phpcs:enable
7148 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
7149 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
7150
7151 $nbphoto = 0;
7152 $tabobj = array();
7153
7154 $dir_osencoded = dol_osencode($dir);
7155 $handle = @opendir($dir_osencoded);
7156 if (is_resource($handle)) {
7157 while (($file = readdir($handle)) !== false) {
7158 if (!utf8_check($file)) {
7159 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // readdir returns ISO
7160 }
7161 if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
7162 $nbphoto++;
7163
7164 // We forge name of thumb.
7165 $photo = $file;
7166 $photo_vignette = '';
7167 $regs = array();
7168 if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
7169 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
7170 }
7171
7172 $dirthumb = $dir.'thumbs/';
7173
7174 // Object
7175 $obj = array();
7176 $obj['photo'] = $photo;
7177 if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
7178 $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
7179 } else {
7180 $obj['photo_vignette'] = "";
7181 }
7182
7183 $tabobj[$nbphoto - 1] = $obj;
7184
7185 // Do we have to continue with next photo ?
7186 if ($nbmax && $nbphoto >= $nbmax) {
7187 break;
7188 }
7189 }
7190 }
7191
7192 closedir($handle);
7193 }
7194
7195 return $tabobj;
7196 }
7197
7198 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7205 public function delete_photo($file)
7206 {
7207 // phpcs:enable
7208 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
7209 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
7210
7211 $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
7212 $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
7213 $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
7214
7215 // On efface l'image d'origine
7216 dol_delete_file($file, 0, 0, 0, $this); // For triggers
7217
7218 // Si elle existe, on efface la vignette
7219 if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
7220 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
7221 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
7222 dol_delete_file($dirthumb.$photo_vignette);
7223 }
7224
7225 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
7226 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
7227 dol_delete_file($dirthumb.$photo_vignette);
7228 }
7229 }
7230 }
7231
7232 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7239 public function get_image_size($file)
7240 {
7241 // phpcs:enable
7242 $file_osencoded = dol_osencode($file);
7243 $infoImg = getimagesize($file_osencoded); // Get information on image
7244 $this->imgWidth = $infoImg[0]; // Largeur de l'image
7245 $this->imgHeight = $infoImg[1]; // Hauteur de l'image
7246 }
7247
7253 public function loadStateBoard()
7254 {
7255 global $hookmanager;
7256
7257 $this->nb = array();
7258
7259 $sql = "SELECT count(p.rowid) as nb, fk_product_type";
7260 $sql .= " FROM ".$this->db->prefix()."product as p";
7261 $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
7262 // Add where from hooks
7263 if (is_object($hookmanager)) {
7264 $parameters = array();
7265 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
7266 $sql .= $hookmanager->resPrint;
7267 }
7268 $sql .= ' GROUP BY fk_product_type';
7269
7270 $resql = $this->db->query($sql);
7271 if ($resql) {
7272 while ($obj = $this->db->fetch_object($resql)) {
7273 if ($obj->fk_product_type == 1) {
7274 $this->nb["services"] = $obj->nb;
7275 } else {
7276 $this->nb["products"] = $obj->nb;
7277 }
7278 }
7279 $this->db->free($resql);
7280 return 1;
7281 } else {
7282 dol_print_error($this->db);
7283 $this->error = $this->db->error();
7284 return -1;
7285 }
7286 }
7287
7293 public function isProduct()
7294 {
7295 return $this->type == Product::TYPE_PRODUCT;
7296 }
7297
7303 public function isService()
7304 {
7305 return $this->type == Product::TYPE_SERVICE;
7306 }
7307
7313 public function isStockManaged()
7314 {
7315 return (($this->isProduct() || ($this->isService() && getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) && ($this->stockable_product > 0));
7316 }
7317
7323 public function isMandatoryPeriod()
7324 {
7325 return $this->mandatory_period == 1;
7326 }
7327
7333 public function hasbatch()
7334 {
7335 return $this->status_batch > 0;
7336 }
7337
7338
7339 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7348 public function get_barcode($object, $type = '')
7349 {
7350 // phpcs:enable
7351 global $conf;
7352
7353 $result = '';
7354 if (getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM')) {
7355 $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
7356 foreach ($dirsociete as $dirroot) {
7357 $res = dol_include_once($dirroot . getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM').'.php');
7358 if ($res) {
7359 break;
7360 }
7361 }
7362 $var = getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM');
7363 $mod = new $var();
7364 '@phan-var-force ModeleNumRefBarCode $mod';
7365
7366 $result = $mod->getNextValue($object, $type);
7367
7368 dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
7369 }
7370 return $result;
7371 }
7372
7380 public function initAsSpecimen()
7381 {
7382 $now = dol_now();
7383
7384 // Initialize parameters
7385 $this->specimen = 1;
7386 $this->id = 0;
7387 $this->ref = 'PRODUCT_SPEC';
7388 $this->label = 'PRODUCT SPECIMEN';
7389 $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
7390 $this->specimen = 1;
7391 $this->country_id = 1;
7392 $this->status = 1;
7393 $this->status_buy = 1;
7394 $this->tobatch = 0;
7395 $this->sell_or_eat_by_mandatory = 0;
7396 $this->note_private = 'This is a comment (private)';
7397 $this->note_public = 'This is a comment (public)';
7398 $this->date_creation = $now;
7399 $this->date_modification = $now;
7400
7401 $this->weight = 4;
7402 $this->weight_units = 3;
7403
7404 $this->length = 5;
7405 $this->length_units = 1;
7406 $this->width = 6;
7407 $this->width_units = 0;
7408 $this->height = null;
7409 $this->height_units = null;
7410
7411 $this->surface = 30;
7412 $this->surface_units = 0;
7413 $this->volume = 300;
7414 $this->volume_units = 0;
7415
7416 $this->barcode = -1; // Create barcode automatically
7417
7418 return 1;
7419 }
7420
7430 public function getLabelOfUnit($type = 'long', $outputlangs = null, $noentities = 0)
7431 {
7432 global $langs;
7433
7434 if (empty($this->fk_unit)) {
7435 return '';
7436 }
7437 if (empty($outputlangs)) {
7438 $outputlangs = $langs;
7439 }
7440
7441 $outputlangs->load('products');
7442 $label = '';
7443
7444 $sql = "SELECT code, label, short_label FROM ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
7445
7446 $resql = $this->db->query($sql);
7447 if (!$resql) {
7448 $this->error = $this->db->error();
7449 dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
7450 return -1;
7451 } elseif ($this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
7452 if ($type == 'short') {
7453 if ($noentities) {
7454 $label = $outputlangs->transnoentitiesnoconv($res['short_label']);
7455 } else {
7456 $label = $outputlangs->trans($res['short_label']);
7457 }
7458 } elseif ($type == 'code') {
7459 $label = $res['code'];
7460 } else {
7461 if ($outputlangs->trans('unit'.$res['code']) == 'unit'.$res['code']) {
7462 // No translation available
7463 $label = $res['label'];
7464 } else {
7465 // Return the translated value
7466 if ($noentities) {
7467 $label = $outputlangs->transnoentitiesnoconv('unit'.$res['code']);
7468 } else {
7469 $label = $outputlangs->trans('unit'.$res['code']);
7470 }
7471 }
7472 }
7473 }
7474 $this->db->free($resql);
7475
7476 return $label;
7477 }
7478
7479 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7485 public function min_recommended_price()
7486 {
7487 // phpcs:enable
7488 $maxpricesupplier = 0;
7489
7490 if (getDolGlobalString('PRODUCT_MINIMUM_RECOMMENDED_PRICE')) {
7491 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
7492 $product_fourn = new ProductFournisseur($this->db);
7493 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
7494
7495 if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
7496 foreach ($product_fourn_list as $productfourn) {
7497 if ($productfourn->fourn_unitprice > $maxpricesupplier) {
7498 $maxpricesupplier = $productfourn->fourn_unitprice;
7499 }
7500 }
7501
7502 $maxpricesupplier *= getDolGlobalString('PRODUCT_MINIMUM_RECOMMENDED_PRICE');
7503 }
7504 }
7505
7506 return $maxpricesupplier;
7507 }
7508
7509
7520 public function setCategories($categories)
7521 {
7522 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7523 return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
7524 }
7525
7536 public function mergeProduct($product_origin_id)
7537 {
7538 global $conf, $langs, $hookmanager, $user, $action;
7539
7540 $error = 0;
7541 $productOrigin = new Product($this->db); // The product that we will delete
7542
7543 dol_syslog("mergeProduct merge product id=".$product_origin_id." (will be deleted) into the product id=".$this->id);
7544
7545 if ($productOrigin->fetch($product_origin_id) < 1) {
7546 $this->error = $langs->trans('ErrorRecordNotFound');
7547 $error++;
7548 }
7549
7550 // Stock of origin product would be lost when it is deleted, so we refuse the merge
7551 if (!$error) {
7552 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix()."product_stock";
7553 $sql .= " WHERE fk_product = ".((int) $productOrigin->id)." AND reel <> 0";
7554 $resql = $this->db->query($sql);
7555 if (!$resql) {
7556 $this->error = $this->db->lasterror();
7557 $error++;
7558 } else {
7559 $obj = $this->db->fetch_object($resql);
7560 if ($obj && $obj->nb > 0) {
7561 $langs->load("errors");
7562 $this->error = $langs->trans('ErrorMergeOriginProductHasStock', $productOrigin->ref);
7563 $error++;
7564 }
7565 $this->db->free($resql);
7566 }
7567 }
7568
7569 if (!$error) {
7570 $this->db->begin();
7571
7572 // Recopy some data
7573 $listofproperties = array(
7574 'ref',
7575 'ref_ext',
7576 'label',
7577 'description',
7578 'url',
7579 'barcode',
7580 'fk_barcode_type',
7581 'import_key',
7582 'mandatory_period',
7583 'accountancy_code_buy',
7584 'accountancy_code_buy_intra',
7585 'accountancy_code_buy_export',
7586 'accountancy_code_sell',
7587 'accountancy_code_sell_intra',
7588 'accountancy_code_sell_export'
7589 );
7590 foreach ($listofproperties as $property) {
7591 if (empty($this->$property)) {
7592 $this->$property = $productOrigin->$property;
7593 }
7594 }
7595 // Concat some data
7596 $listofproperties = array(
7597 'note_public', 'note_private'
7598 );
7599 foreach ($listofproperties as $property) {
7600 $this->$property = dol_concatdesc($this->$property, $productOrigin->$property);
7601 }
7602
7603 // Merge extrafields
7604 if (is_array($productOrigin->array_options)) {
7605 foreach ($productOrigin->array_options as $key => $val) {
7606 if (empty($this->array_options[$key])) {
7607 $this->array_options[$key] = $val;
7608 }
7609 }
7610 }
7611
7612 // Merge categories
7613 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7614 $static_cat = new Categorie($this->db);
7615 $custcats_ori = $static_cat->containing($productOrigin->id, 'product', 'id');
7616 $custcats = $static_cat->containing($this->id, 'product', 'id');
7617 $custcats = array_merge($custcats, $custcats_ori);
7618 $this->setCategories($custcats);
7619
7620 // If product has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
7621 if ($productOrigin->barcode == $this->barcode) {
7622 dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
7623 $productOrigin->barcode = '';
7624 //$productOrigin->update($productOrigin->id, $user, 0, 'merge');
7625 }
7626
7627 // Update
7628 $result = $this->update($this->id, $user, 0, 'merge');
7629 if ($result <= 0) {
7630 $error++;
7631 }
7632
7633 // Move links
7634 if (!$error) {
7635 // TODO add this functionality into the api_products.class.php
7636 $objects = array(
7637 'ActionComm' => '/comm/action/class/actioncomm.class.php',
7638 // do not use Categorie, it cause foreign key error, merge is done before
7639 //'Categorie' => '/categories/class/categorie.class.php',
7640 'Commande' => '/commande/class/commande.class.php',
7641 'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
7642 'Contrat' => '/contrat/class/contrat.class.php',
7643 'Delivery' => '/delivery/class/delivery.class.php',
7644 'Expedition' => '/expedition/class/expedition.class.php',
7645 'Facture' => '/compta/facture/class/facture.class.php',
7646 'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
7647 'FactureRec' => '/compta/facture/class/facture-rec.class.php',
7648 'FichinterRec' => '/fichinter/class/fichinterrec.class.php',
7649 'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
7650 'Propal' => '/comm/propal/class/propal.class.php',
7651 'Reception' => '/reception/class/reception.class.php',
7652 'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
7653 'TimeSpent' => '/core/class/timespent.class.php',
7654 );
7655 // Tables of these modules exist only if module was enabled once
7656 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'bom_bom')) {
7657 $objects['Bom'] = '/bom/class/bom.class.php';
7658 }
7659 if ($this->db->DDLListTables((string) $conf->db->name, $this->db->prefix().'mrp_mo')) {
7660 $objects['Mo'] = '/mrp/class/mo.class.php';
7661 }
7662
7663 // First, all core objects must update their tables
7664 foreach ($objects as $object_name => $object_file) {
7665 require_once DOL_DOCUMENT_ROOT.$object_file;
7666
7667 if (!$object_name::replaceProduct($this->db, $productOrigin->id, $this->id)) {
7668 $error++;
7669 $this->error = $this->db->lasterror();
7670 break;
7671 }
7672 }
7673 }
7674
7675 // External modules should update their ones too
7676 if (!$error) {
7677 $parameters = array('soc_origin' => $productOrigin->id, 'soc_dest' => $this->id);
7678 $reshook = $hookmanager->executeHooks('replaceProduct', $parameters, $this, $action);
7679
7680 if ($reshook < 0) {
7681 $this->error = $hookmanager->error;
7682 $this->errors = $hookmanager->errors;
7683 $error++;
7684 }
7685 }
7686
7687
7688 if (!$error) {
7689 $this->context = array('merge' => 1, 'mergefromid' => $productOrigin->id);
7690
7691 // Call trigger
7692 $result = $this->call_trigger('PRODUCT_MODIFY', $user);
7693 if ($result < 0) {
7694 $error++;
7695 }
7696 // End call triggers
7697 }
7698
7699 if (!$error) {
7700 // Move files from the dir of the product being deleted into the dir of the product kept.
7701 // This must happen on success only: the filesystem is not part of the transaction, so
7702 // moving the files on the failing path stripped the origin product of its documents
7703 // while the database was rolled back, and left them orphaned on the successful one.
7704 if (!empty($conf->product->multidir_output[$productOrigin->entity ?? $conf->entity])) {
7705 $srcdir = $conf->product->multidir_output[$productOrigin->entity ?? $conf->entity]."/".$productOrigin->ref;
7706 $destdir = $conf->product->multidir_output[$this->entity ?? $conf->entity]."/".$this->ref;
7707
7708 if (dol_is_dir($srcdir)) {
7709 $dirlist = dol_dir_list($srcdir, 'files', 1);
7710 foreach ($dirlist as $filetomove) {
7711 $destfile = $destdir.'/'.$filetomove['relativename'];
7712 // dol_move() does not create the target directory, which may not exist yet
7713 dol_mkdir(dirname($destfile));
7714 dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
7715 }
7716 //exit;
7717 }
7718 }
7719
7720 // dol_move() updated the path of moved files into ecm index, but they must also be linked to the kept product,
7721 // otherwise the delete of origin product removes their index entries.
7722 $sql = "UPDATE ".$this->db->prefix()."ecm_files SET src_object_id = ".((int) $this->id);
7723 $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element)."' AND src_object_id = ".((int) $productOrigin->id);
7724 if (!$this->db->query($sql)) {
7725 $this->error = $this->db->lasterror();
7726 $error++;
7727 }
7728 }
7729
7730 if (!$error) {
7731 // Delete the product
7732 if ($productOrigin->delete($user) < 1) {
7733 $this->error = $productOrigin->error;
7734 $this->errors = $productOrigin->errors;
7735 $error++;
7736 }
7737 }
7738
7739 if (!$error) {
7740 $this->db->commit();
7741 return 0;
7742 } else {
7743 $langs->load("errors");
7744 $this->error = $langs->trans('ErrorsProductsMerge').' '.$this->error;
7745 $this->db->rollback();
7746 return -1;
7747 }
7748 }
7749
7750 return -1;
7751 }
7752
7761 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
7762 {
7763 /* we firstly delete origin product prices existing in destination before update */
7764 $sql = " DELETE FROM ".$dbs->prefix()."product_customer_price";
7765 $sql .= " WHERE fk_soc = ".(int) $origin_id;
7766 $sql .= " AND fk_product IN (SELECT fk_product FROM (SELECT fk_product FROM ".$dbs->prefix()."product_customer_price WHERE fk_soc = ".(int) $dest_id.") AS tmp)";
7767 //$sql .= ' AND EXISTS (SELECT 1 FROM '.$dbs->prefix().'product_customer_price p_new WHERE p_new.fk_product = p_old.fk_product AND p_new.fk_soc = '.(int) $dest_id.')';
7768
7769 if (!$dbs->query($sql)) {
7770 return false;
7771 }
7772
7773 $tables = array(
7774 'product_customer_price',
7775 'product_customer_price_log'
7776 );
7777
7778 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
7779 }
7780
7792 public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
7793 {
7794 $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
7795 $query = $this->db->query($sql);
7796
7797 $rules = array();
7798
7799 while ($result = $this->db->fetch_object($query)) {
7800 $rules[$result->level] = $result;
7801 }
7802
7803 //Because prices can be based on other level's prices, we temporarily store them
7804 $prices = array(
7805 1 => $baseprice
7806 );
7807
7808 $nbofproducts = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
7809 for ($i = 1; $i <= $nbofproducts; $i++) {
7810 $price = $baseprice;
7811 $price_min = $baseprice;
7812
7813 //We have to make sure it does exist and it is > 0
7814 //First price level only allows changing min_price
7815 if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
7816 $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
7817 }
7818
7819 $prices[$i] = $price;
7820
7821 //We have to make sure it does exist and it is > 0
7822 if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
7823 $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
7824 }
7825
7826 //Little check to make sure the price is modified before triggering generation
7827 $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
7828 $check_type = ($baseprice == $this->multiprices_base_type[$i]);
7829
7830 if ($check_amount && $check_type) {
7831 continue;
7832 }
7833
7834 if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, 1) < 0) {
7835 return -1;
7836 }
7837 }
7838
7839 return 1;
7840 }
7841
7849 public function hasUserPermission(User $user, $mode = 'write')
7850 {
7851 $module = $this->isProduct() ? 'produit' : 'service';
7852 if ($mode == 'create') {
7853 $mode = 'write';
7854 }
7855 if (!in_array($mode, array('read', 'write', 'delete'))) {
7856 return false;
7857 }
7858
7859 return (bool) $user->hasRight($module, $mode);
7860 }
7861
7868 public function info($id)
7869 {
7870 $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, GREATEST(p.tms, COALESCE(pef.tms, p.tms)) as date_modification,";
7871 $sql .= " p.fk_user_author, p.fk_user_modif";
7872 $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
7873 $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as pef ON pef.fk_object=p.rowid";
7874 $sql .= " WHERE p.rowid = ".((int) $id);
7875
7876 $result = $this->db->query($sql);
7877 if ($result) {
7878 if ($this->db->num_rows($result)) {
7879 $obj = $this->db->fetch_object($result);
7880
7881 $this->id = $obj->rowid;
7882 $this->ref = $obj->ref;
7883
7884 $this->user_creation_id = $obj->fk_user_author;
7885 $this->user_modification_id = $obj->fk_user_modif;
7886
7887 $this->date_creation = $this->db->jdate($obj->date_creation);
7888 $this->date_modification = $this->db->jdate($obj->date_modification);
7889 }
7890
7891 $this->db->free($result);
7892 } else {
7893 dol_print_error($this->db);
7894 }
7895 }
7896
7897
7903 public function getProductDurationHours()
7904 {
7905 if (empty($this->duration_value)) {
7906 $this->errors[] = 'ErrorDurationForServiceNotDefinedCantCalculateHourlyPrice';
7907 return -1;
7908 }
7909 if ($this->duration_unit == 's') {
7910 $prodDurationHours = 1. / 3600;
7911 } elseif ($this->duration_unit == 'i' || $this->duration_unit == 'mn' || $this->duration_unit == 'min') {
7912 $prodDurationHours = 1. / 60;
7913 } elseif ($this->duration_unit == 'h') {
7914 $prodDurationHours = 1.;
7915 } elseif ($this->duration_unit == 'd') {
7916 $prodDurationHours = 24.;
7917 } elseif ($this->duration_unit == 'w') {
7918 $prodDurationHours = 24. * 7;
7919 } elseif ($this->duration_unit == 'm') {
7920 $prodDurationHours = 24. * 30;
7921 } elseif ($this->duration_unit == 'y') {
7922 $prodDurationHours = 24. * 365;
7923 } else {
7924 // Unknown unit: the duration cannot be converted. Returning 0 silently made callers
7925 // compute a zero duration, and time.php divides by this value (#40805).
7926 $this->errors[] = 'ErrorDurationForServiceNotDefinedCantCalculateHourlyPrice';
7927 return -1;
7928 }
7929 $prodDurationHours *= $this->duration_value;
7930
7931 return $prodDurationHours;
7932 }
7933
7934
7942 public function getKanbanView($option = '', $arraydata = null)
7943 {
7944 global $langs, $conf;
7945
7946 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
7947
7948 $return = '<div class="box-flex-item box-flex-grow-zero">';
7949 $return .= '<div class="info-box info-box-sm">';
7950 $return .= '<div class="info-box-img">';
7951 $label = '';
7952 if ($this->entity !== null && $this->is_photo_available($conf->product->multidir_output[$this->entity])) {
7953 $label .= $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 120, 160, 0, 0, 0, '', 'photoref photokanban');
7954 $return .= $label;
7955 } else {
7956 if ($this->isProduct()) {
7957 $label .= img_picto('', 'product');
7958 } elseif ($this->isService()) {
7959 $label .= img_picto('', 'service');
7960 }
7961 $return .= $label;
7962 }
7963 $return .= '</div>';
7964 $return .= '<div class="info-box-content">';
7965 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
7966 if ($selected >= 0) {
7967 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
7968 }
7969 $return .= '<br><span class="info-box-label opacitymedium inline-block tdoverflowmax150 valignmiddle" title="'.dol_escape_htmltag($this->label).'">'.dol_escape_htmltag($this->label).'</span>';
7970 if ($this->price_base_type == 'TTC') {
7971 $return .= '<br><span class="info-box-status amount">'.price($this->price_ttc).' '.$langs->trans("TTC").'</span>';
7972 } else {
7973 if ($this->status) {
7974 $return .= '<br><span class="info-box-status amount">'.price($this->price).' '.$langs->trans("HT").'</span>';
7975 }
7976 }
7977 $br = 1;
7978 if ($this->isProduct()) {
7979 $return .= '<br><div class="info-box-status opacitymedium inline-block valignmiddle">'.img_picto($langs->trans('PhysicalStock'), 'stock').'</div><div class="inline-block valignmiddle paddingleft" title="'.$langs->trans('PhysicalStock').'">'.$this->stock_reel.'</div>';
7980 $br = 0;
7981 }
7982 if ($br) {
7983 $return .= '<br>';
7984 $return .= '<div class="info-box-status inline-block valignmiddle">'.$this->getLibStatut(3, 1).' '.$this->getLibStatut(3, 0).'</div>';
7985 } else {
7986 $return .= '<div class="info-box-status inline-block valignmiddle marginleftonly paddingleft">'.$this->getLibStatut(3, 1).' '.$this->getLibStatut(3, 0).'</div>';
7987 }
7988 $return .= '</div>';
7989 $return .= '</div>';
7990 $return .= '</div>';
7991 return $return;
7992 }
7993
8001 private function cloneCustomerPriceAndExtra($fromId, $toId)
8002 {
8003 global $user;
8004
8005 $now = dol_now();
8006
8007 // Price per customer
8008 $sql = "SELECT";
8009 $sql .= " entity";
8010 $sql .= ", fk_soc";
8011 $sql .= ", datec";
8012 $sql .= ", price";
8013 $sql .= ", price_ttc";
8014 $sql .= ", price_min";
8015 $sql .= ", price_min_ttc";
8016 $sql .= ", price_base_type";
8017 $sql .= ", default_vat_code";
8018 $sql .= ", tva_tx";
8019 $sql .= ", recuperableonly";
8020 $sql .= ", localtax1_tx";
8021 $sql .= ", localtax1_type";
8022 $sql .= ", localtax2_tx";
8023 $sql .= ", localtax2_type";
8024 $sql .= ", fk_user";
8025 $sql .= ", ref_customer";
8026 $sql .= ", discount_percent";
8027 $sql .= ", date_begin";
8028 $sql .= ", date_end";
8029 $sql .= ", price_label";
8030 $sql .= ", import_key";
8031 $sql .= ", rowid";
8032 $sql .= " FROM ".$this->db->prefix()."product_customer_price";
8033 $sql .= " WHERE fk_product = ".((int) $fromId);
8034 $sql .= " ORDER BY rowid ASC";
8035 dol_syslog(__METHOD__.' - '.$sql, LOG_DEBUG);
8036
8037 $resql = $this->db->query($sql);
8038 if (!$resql) {
8039 $this->db->rollback();
8040 return -1;
8041 }
8042
8043 // Add of customer price extrafields
8044 // Retrieving the list of extrafields
8045 $sql_fields = "SHOW COLUMNS FROM ".$this->db->prefix()."product_customer_price_extrafields";
8046 $resql_fields = $this->db->query($sql_fields);
8047 if (!$resql_fields) {
8048 $this->db->rollback();
8049 return -1;
8050 }
8051 $fields = array();
8052 while ($field = $this->db->fetch_object($resql_fields)) {
8053 if (!in_array($field->Field, array('rowid', 'tms', 'fk_object'))) {
8054 $fields[] = $field->Field;
8055 }
8056 }
8057 $this->db->free($resql_fields);
8058
8059 while ($oldPrice = $this->db->fetch_object($resql)) {
8060 // Entering the customer price for the new product
8061 $sql_insert = "INSERT INTO ".$this->db->prefix()."product_customer_price (";
8062 $sql_insert .= "entity";
8063 $sql_insert .= ", datec";
8064 $sql_insert .= ", fk_product";
8065 $sql_insert .= ", fk_soc";
8066 $sql_insert .= ", ref_customer";
8067 $sql_insert .= ", price";
8068 $sql_insert .= ", price_ttc";
8069 $sql_insert .= ", price_min";
8070 $sql_insert .= ", price_min_ttc";
8071 $sql_insert .= ", price_base_type";
8072 $sql_insert .= ", default_vat_code";
8073 $sql_insert .= ", tva_tx";
8074 $sql_insert .= ", recuperableonly";
8075 $sql_insert .= ", localtax1_type";
8076 $sql_insert .= ", localtax1_tx";
8077 $sql_insert .= ", localtax2_type";
8078 $sql_insert .= ", localtax2_tx";
8079 $sql_insert .= ", discount_percent";
8080 $sql_insert .= ", date_begin";
8081 $sql_insert .= ", date_end";
8082 $sql_insert .= ", fk_user";
8083 $sql_insert .= ", price_label";
8084 $sql_insert .= ", import_key";
8085 $sql_insert .= ") VALUES (";
8086 $sql_insert .= ((int) $oldPrice->entity);
8087 $sql_insert .= ", '".$this->db->idate($now)."'";
8088 $sql_insert .= ", ".((int) $toId);
8089 $sql_insert .= ", ".((int) $oldPrice->fk_soc);
8090 $sql_insert .= ", ".(!isset($oldPrice->ref_customer) ? "NULL" : "'".$this->db->escape($oldPrice->ref_customer)."'");
8091 $sql_insert .= ", ".(is_null($oldPrice->price) ? "NULL" : price2num($oldPrice->price));
8092 $sql_insert .= ", ".(is_null($oldPrice->price_ttc) ? "NULL" : price2num($oldPrice->price_ttc));
8093 $sql_insert .= ", ".(is_null($oldPrice->price_min) ? "NULL" : price2num($oldPrice->price_min));
8094 $sql_insert .= ", ".(is_null($oldPrice->price_min_ttc) ? "NULL" : price2num($oldPrice->price_min_ttc));
8095 $sql_insert .= ", ".(!isset($oldPrice->price_base_type) ? "NULL" : "'".$this->db->escape($oldPrice->price_base_type)."'");
8096 $sql_insert .= ", ".(is_null($oldPrice->default_vat_code) ? "NULL" : "'".$this->db->escape($oldPrice->default_vat_code)."'");
8097 $sql_insert .= ", ".(is_null($oldPrice->tva_tx) ? "NULL" : price2num($oldPrice->tva_tx));
8098 $sql_insert .= ", ".((int) $oldPrice->recuperableonly);
8099 $sql_insert .= ", ".(is_null($oldPrice->localtax1_type) ? "NULL" : "'".$this->db->escape($oldPrice->localtax1_type)."'");
8100 $sql_insert .= ", ".(is_null($oldPrice->localtax1_tx) ? "NULL" : price2num($oldPrice->localtax1_tx));
8101 $sql_insert .= ", ".(is_null($oldPrice->localtax2_type) ? "NULL" : "'".$this->db->escape($oldPrice->localtax2_type)."'");
8102 $sql_insert .= ", ".(is_null($oldPrice->localtax2_tx) ? "NULL" : price2num($oldPrice->localtax2_tx));
8103 $sql_insert .= ", ".(is_null($oldPrice->discount_percent) ? "0" : price2num($oldPrice->discount_percent));
8104 $sql_insert .= ", ".(empty($oldPrice->date_begin) ? "NULL" : "'".$this->db->idate($oldPrice->date_begin)."'");
8105 $sql_insert .= ", ".(empty($oldPrice->date_end) ? "NULL" : "'".$this->db->idate($oldPrice->date_end)."'");
8106 $sql_insert .= ", ".((int) $user->id);
8107 $sql_insert .= ", ".(is_null($oldPrice->price_label) ? "NULL" : "'".$this->db->escape($oldPrice->price_label)."'");
8108 $sql_insert .= ", ".(is_null($oldPrice->import_key) ? "NULL" : "'".$this->db->escape($oldPrice->import_key)."'");
8109 $sql_insert .= ")";
8110
8111 $resql_insert = $this->db->query($sql_insert);
8112
8113 if (!$resql_insert) {
8114 $this->db->rollback();
8115 return -1;
8116 }
8117
8118 // Retrieval of the new customer price ID
8119 $newPriceId = $this->db->last_insert_id($this->db->prefix()."product_customer_price");
8120 // Copy of extrafields
8121 // Add of customer price extrafields
8122 if (!empty($fields)) {
8123 $sql_copy = "INSERT INTO ".$this->db->prefix()."product_customer_price_extrafields";
8124 $sql_copy .= " (fk_object";
8125 foreach ($fields as $field) {
8126 $sql_copy .= ",".$field;
8127 }
8128 $sql_copy .= ")";
8129 $sql_copy .= " SELECT ";
8130 $sql_copy .= ((int) $newPriceId);
8131
8132 foreach ($fields as $field) {
8133 $sql_copy .= ",".$field;
8134 }
8135 $sql_copy .= " FROM ".$this->db->prefix()."product_customer_price_extrafields";
8136 $sql_copy .= " WHERE fk_object = ".((int) $oldPrice->rowid);
8137 $resql_copy = $this->db->query($sql_copy);
8138 if (!$resql_copy) {
8139 $this->db->rollback();
8140 return -1;
8141 }
8142 }
8143 }
8144
8145 $this->db->free($resql);
8146
8147 return 1;
8148 }
8149
8157 private function cloneMultipriceExtra($fromId, $toId)
8158 {
8159 global $user;
8160
8161 $now = dol_now();
8162
8163 // Retrieving the list of extrafields
8164 $sql_fields = "SHOW COLUMNS FROM ".MAIN_DB_PREFIX."product_price_extrafields";
8165 $resql_fields = $this->db->query($sql_fields);
8166 if (!$resql_fields) {
8167 $this->db->rollback();
8168 return -1;
8169 }
8170 $fields = array();
8171 while ($field = $this->db->fetch_object($resql_fields)) {
8172 if (!in_array($field->Field, array('rowid', 'tms', 'fk_object'))) {
8173 $fields[] = $field->Field;
8174 }
8175 }
8176 if (!empty($fields)) {
8177 // Matching old price, new price
8178 $sql = "SELECT oldp.rowid AS old_price_id, oldp.date_price, oldp.price_level,";
8179 $sql .= " newp.rowid AS new_price_id, newp.price_level";
8180 $sql .= " FROM ".$this->db->prefix()."product_price AS oldp";
8181 $sql .= " INNER JOIN ".$this->db->prefix()."product_price AS newp ON newp.price_level = oldp.price_level";
8182 $sql .= " WHERE oldp.fk_product = ".((int) $fromId);
8183 $sql .= " AND newp.fk_product = ".((int) $toId);
8184 $sql .= " ORDER BY oldp.date_price DESC";
8185 $resql = $this->db->query($sql);
8186 if (!$resql) {
8187 $this->db->rollback();
8188 return -1;
8189 }
8190 // Copy of extrafields
8191 while ($obj = $this->db->fetch_object($resql)) {
8192 $sql_copy = "INSERT INTO ".$this->db->prefix()."product_price_extrafields";
8193 $sql_copy .= " (fk_object";
8194 foreach ($fields as $field) {
8195 $sql_copy .= ",".$field;
8196 }
8197 $sql_copy .= ")";
8198 $sql_copy .= " SELECT ";
8199 $sql_copy .= ((int) $obj->new_price_id);
8200 foreach ($fields as $field) {
8201 $sql_copy .= ",".$field;
8202 }
8203 $sql_copy .= " FROM ".$this->db->prefix()."product_price_extrafields";
8204 $sql_copy .= " WHERE fk_object = ".((int) $obj->old_price_id);
8205 $resql_copy = $this->db->query($sql_copy);
8206 if (!$resql_copy) {
8207 $this->db->rollback();
8208 return -1;
8209 }
8210 }
8211
8212 $this->db->free($resql);
8213 }
8214
8215 $this->db->free($resql_fields);
8216
8217 return 1;
8218 }
8219}
8220
8226{
8227 public $picto = 'service';
8228}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
clean_account($account)
Return accounting account without zero on the right.
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage categories.
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...
deleteEcmFiles($mode=0)
Delete related files of object in database.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
addThumbs($file, $quality=50)
Build thumb.
Class to manage Dolibarr database access.
Class to manage ECM files.
const STATUS_OPEN_INTERNAL
Warehouse open and only operations for stock transfers/corrections allowed (not for customer shipping...
const STATUS_OPEN_ALL
Warehouse open and any operations are allowed (customer shipping, supplier dispatch,...
const STATUS_CLOSED
Warehouse closed, inactive.
const STATUS_CLOSED
Closed status -> parcel was received by customer / end of process prev status : validated or shipment...
const STATUS_VALIDATED
Validated status -> parcel is ready to be sent prev status : draft next status : closed or shipment_i...
Class to manage standard extra fields.
const STATUS_DRAFT
Draft status.
Class to manage generation of HTML components Only common components must be here.
Class to manage stock movements.
Class to parse product price expressions.
Class ProductCombination Used to represent the relation between a product and one of its variants.
File of class to manage predefined price products or services by customer.
Class to manage predefined suppliers products.
Class to manage products or services.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
get_nb_achat($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units or supplier invoices in which product is included.
getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp=0)
Return price of sell of a product for a seller/buyer/product.
__construct($db)
Constructor.
is_sousproduit($fk_parent, $fk_child)
Check if it is a sub-product into a kit.
const DISABLED_STOCK
Stockable product.
const SELL_OR_EAT_BY_MANDATORY_ID_NONE
Const sell or eat by mandatory id.
isStockManaged()
Return if the object is managed in stock.
setPriceExpression($expression_id)
Sets the supplier price expression.
getArrayForPriceCompare($level=0)
used to check if price have really change to avoid log pollution
get_arbo_each_prod($multiply=1, $ignore_stock_load=0)
Build the tree of subproducts and return it.
load_stats_inproduction($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null, $warehouseid=0, $dateofvirtualstockmin=null)
Charge tableau des stats production pour le produit/service.
list_suppliers()
Return list of suppliers providing the product or service.
load_stats_mo($socid=0)
Charge tableau des stats OF pour le produit/service.
isVariant()
Return if loaded product is a variant.
updatePrice($newprice, $newpricebase, $user, $newvat=null, $newminprice=0, $level=0, $newnpr=0, $newpbq=0, $ignore_autogen=0, $localtaxes_array=array(), $newdefaultvatcode='', $price_label='', $notrigger=0)
Modify customer price of a product/Service for a given level.
hasVariants()
Return if a product has variants or not.
load_stats_proposal_supplier($socid=0)
Charge tableau des stats propale pour le produit/service.
getLibFinished()
Retour label of nature of product.
add_sousproduit($id_pere, $id_fils, $qty, $incdec=1, $notrigger=0)
Link a product/service to a parent product/service.
add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
Add a supplier price for the product.
setMultiLangs($user, $notrigger=0)
Update or add a translation for a product.
hasFatherOrChild($mode=0)
Count all parent and children products for current product (first level only)
load_stats_facturerec($socid=0)
Load array of statistics for recurring invoice for product/service.
get_nb_propalsupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in proposals in which product is included.
load_stats_facturefournrec($socid=0)
Load array of statistics for recurring supplier invoice for product/service.
get_nb_contract($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
load_stats_facture_fournisseur($socid=0)
Load array of statistics for vendor invoice for product/service.
get_nb_ordersupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
get_nb_mos($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
clone_associations($fromId, $toId)
Clone links between products.
load_stats_reception($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null, $dateofvirtualstockmin=null)
Loads supplier reception statistics table for given product or service.
create($user, $notrigger=0)
Insert product into database.
load_stats_contrat($socid=0)
Charge tableau des stats contrat pour le produit/service.
isService()
Return if the object is a service.
loadBatchInfo($batch)
Load existing information about a serial.
load_stock($option='', $includedraftpoforvirtual=null, $dateofvirtualstock=null)
Load information about stock of a product into ->stock_reel, ->stock_warehouse[] (including stock_war...
getProductDurationHours()
Return the duration of a service in hours (for a service based on duration fields)
get_buyprice($prodfournprice, $qty, $product_id=0, $fourn_ref='', $fk_soc=0)
Read price used by a provider.
clone_fournisseurs($fromId, $toId)
Copies the suppliers and supplier pricing of a product/service onto another one.
const TYPE_PRODUCT
Regular product.
fetchAllPriceLogs($id)
Get all price change logs for a product, enriched with supplier info.
mergeProduct($product_origin_id)
Merge a product with current one, deleting the given product $product_origin_id.
add_photo($sdir, $file)
Move an uploaded file described into $file array into target directory $sdir.
log_price_delete($user, $rowid)
Delete a price line of this product.
info($id)
Load information for tab info.
correct_stock($user, $id_entrepot, $nbpiece, $movement, $label='', $price=0, $inventorycode='', $origin_element='', $origin_id=null, $disablestockchangeforsubproduct=0, $extrafields=null)
Adjust stock in a warehouse for product.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create a document onto disk according to template module.
static getSellOrEatByMandatoryList()
Get the array of labels of Sell by or Eat by all mandatory flags for each status.
getChildsArbo($id, $firstlevelonly=0, $level=1, $parents=array())
Return children of product $id.
load_virtual_stock($includedraftpoforvirtual=null, $dateofvirtualstock=null)
Load value ->stock_theorique of a product.
load_stats_propale($socid=0)
Charge tableau des stats propale pour le produit/service.
get_barcode($object, $type='')
Get a barcode from the module to generate barcode values.
setAccountancyCode($type, $value)
Sets an accountancy code for a product.
load_stats_commande_fournisseur($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null, $dateofvirtualstockmin=null)
Charge tableau des stats commande fournisseur pour le produit/service.
load_stats_facture($socid=0)
Charge tableau des stats facture pour le produit/service.
setCategories($categories)
Sets object to supplied categories.
get_nb_propal($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in proposals in which product is included.
update($id, $user, $notrigger=0, $action='update', $updatetype=false)
Update a record into database.
correct_stock_batch($user, $id_entrepot, $nbpiece, $movement, $label='', $price=0, $dlc='', $dluo='', $lot='', $inventorycode='', $origin_element='', $origin_id=null, $disablestockchangeforsubproduct=0, $extrafields=null, $force_update_batch=false)
Adjust stock in a warehouse for product with batch number.
load_stats_bom($socid=0)
Charge tableau des stats OF pour le produit/service.
hasbatch()
Return if the object has a batch management.
getNomUrl($withpicto=0, $option='', $maxlength=0, $save_lastsearch_value=-1, $notooltip=0, $morecss='', $add_label=0, $sep=' - ', $addlinktonotes=0)
Return clickable link of object (with eventually picto)
cloneMultipriceExtra($fromId, $toId)
Clone price level extrafields.
hasUserPermission(User $user, $mode='write')
Check if user has a permission on this type of product (product or service)
del_sousproduit($fk_parent, $fk_child, $notrigger=0)
Remove a link between a subproduct and a parent product/service.
fetch($id=0, $ref='', $ref_ext='', $barcode='', $ignore_expression=0, $ignore_price_load=0, $ignore_lang_load=0)
Load a product in memory from database.
update_sousproduit($id_pere, $id_fils, $qty, $incdec=1, $notrigger=0)
Modify composed product.
load_stats_commande($socid=0, $filtrestatut='', $forVirtualStock=0)
Charge tableau des stats commande client pour le produit/service.
delete_photo($file)
Delete a photo and its thumbs.
fetch_prod_arbo($prod, $compl_path='', $multiply=1, $level=1, $id_parent=0, $ignore_stock_load=0)
Function recursive, used only by get_arbo_each_prod(), to build tree of subproducts into ->res Define...
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
getLibStatut($mode=0, $type=0)
Return label of status of object.
load_stats_sending($socid=0, $filtrestatut='', $forVirtualStock=0, $filterShipmentStatus='')
Charge tableau des stats expedition client pour le produit/service.
clone_price($fromId, $toId)
Recopie les prix d'un produit/service sur un autre.
delMultiLangs($langtodelete, $user, $notrigger=0)
Delete a language for this product.
check()
Check that ref and label are ok.
initAsSpecimen()
Initialise an instance with random values.
liste_photos($dir, $nbmax=0)
Return an array with all photos of product found on disk.
loadStateBoard()
Load indicators this->nb for the dashboard.
getFather()
Return all parent products for current product (first level only)
getSellOrEatByMandatoryLabel()
Get the label for sell by or eat by mandatory flag of the current product.
verify()
Check properties of product are ok (like name, barcode, ...).
get_sousproduits_arbo()
get_nb_order($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
loadStockForVirtualProduct($option='', $qtyWish=1)
Load stock for components of virtual product (first level only)
setMultiLangsExtrafields($langcode, $rowidlang)
Save the extrafields of a translation of the product (table llx_product_lang_extrafields).
min_recommended_price()
Return minimum product recommended price.
cloneCustomerPriceAndExtra($fromId, $toId)
Clone customer prices using extra fields.
_log_price($user, $level=0)
Insert a track that we changed a customer price.
getLabelOfUnit($type='long', $outputlangs=null, $noentities=0)
Reads the units dictionary to return the translation code of a unit (if type='code'),...
_get_stats($sql, $mode, $year=0)
Return an array formatted for showing graphs.
isMandatoryPeriod()
Return if the object has a constraint on mandatory_period.
isProduct()
Return if the object is a product.
generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
Generates prices for a product based on product multiprice generation rules.
LibStatut($status, $mode=0, $type=0)
Return label of a given status.
const TYPE_SERVICE
Service.
is_photo_available($sdir)
Return if at least one photo is available.
getMultiLangs($loadextrafields=0)
Load array this->multilangs.
get_image_size($file)
Load size of image file.
get_nb_vente($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units or customers invoices in which product is included.
getTooltipContentArray($params)
getTooltipContentArray
Class of a translation of a product (a row of llx_product_lang).
Class to manage products or services.
Manage record for batch number management.
static findAll($dbs, $fk_product_stock, $with_qty=0, $fk_product=0)
Return all batch detail records for a given product and warehouse.
Class with list of lots and properties.
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
global $mysoc
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:686
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
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_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_is_dir($folder)
Test if filename is a directory.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
utf8_check($str)
Check if a string is in UTF8.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
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_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
measuring_units_squared($unitscale)
Transform a given unit scale into the square of that unit, if known.
measuringUnitString($unitid, $measuring_style='', $unitscale=null, $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
measuring_units_cubed($unit)
Transform a given unit scale into the cube of that unit, if known.