dolibarr 24.0.3
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 *
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 3 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <https://www.gnu.org/licenses/>.
35 */
36
42require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
44require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
45require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
46require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
47
51class Product extends CommonObject
52{
57 const SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY = 1;
58 const SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY = 2;
59 const SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT = 3;
60
65 public $TRIGGER_PREFIX = 'PRODUCT';
66
70 public $element = 'product';
71
75 public $table_element = 'product';
76
80 public $fk_element = 'fk_product';
81
85 protected $childtables = array(
86 'supplier_proposaldet' => array('name' => 'SupplierProposal', 'parent' => 'supplier_proposal', 'parentkey' => 'fk_supplier_proposal'),
87 'propaldet' => array('name' => 'Proposal', 'parent' => 'propal', 'parentkey' => 'fk_propal'),
88 'commandedet' => array('name' => 'Order', 'parent' => 'commande', 'parentkey' => 'fk_commande'),
89 'facturedet' => array('name' => 'Invoice', 'parent' => 'facture', 'parentkey' => 'fk_facture'),
90 'contratdet' => array('name' => 'Contract', 'parent' => 'contrat', 'parentkey' => 'fk_contrat'),
91 'facture_fourn_det' => array('name' => 'SupplierInvoice', 'parent' => 'facture_fourn', 'parentkey' => 'fk_facture_fourn'),
92 'commande_fournisseurdet' => array('name' => 'SupplierOrder', 'parent' => 'commande_fournisseur', 'parentkey' => 'fk_commande'),
93 'mrp_production' => array('name' => 'Mo', 'parent' => 'mrp_mo', 'parentkey' => 'fk_mo', 'enabled' => 'isModEnabled("mrp")'),
94 'bom_bom' => array('name' => 'BOM', 'enabled' => 'isModEnabled("bom")'),
95 'bom_bomline' => array('name' => 'BOMLine', 'parent' => 'bom_bom', 'parentkey' => 'fk_bom', 'enabled' => 'isModEnabled("bom")'),
96 );
97
103 public $picto = 'product';
104
108 protected $table_ref_field = 'ref';
109
114 public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm|\.avif';
115
121 public $ref;
122
128 public $libelle;
129
135 public $label;
136
142 public $description;
143
149 public $other;
150
156 public $type = self::TYPE_PRODUCT;
157
163 public $price;
164
168 public $price_formated; // used by takepos/ajax/ajax.php
169
175 public $price_ttc;
176
180 public $price_ttc_formated; // used by takepos/ajax/ajax.php
181
187 public $price_min;
188
194 public $price_min_ttc;
195
200 public $price_base_type;
204 public $price_label;
205
207
210 public $multiprices = array();
214 public $multiprices_ttc = array();
218 public $multiprices_base_type = array();
222 public $multiprices_default_vat_code = array();
226 public $multiprices_min = array();
230 public $multiprices_min_ttc = array();
234 public $multiprices_tva_tx = array();
238 public $multiprices_recuperableonly = array();
239
241
244 public $price_by_qty;
248 public $prices_by_qty = array();
252 public $prices_by_qty_id = array();
256 public $prices_by_qty_list = array();
257
261 public $level;
262
266 public $multilangs = array();
267
271 public $default_vat_code;
272
276 public $tva_tx;
277
281 public $tva_npr = 0;
282
286 public $remise_percent;
287
291 public $localtax1_tx;
295 public $localtax2_tx;
299 public $localtax1_type;
303 public $localtax2_type;
304
305 // Properties set by get_buyprice() for return
306
310 public $desc_supplier;
314 public $vatrate_supplier;
318 public $default_vat_code_supplier;
319
323 public $fourn_multicurrency_price;
324
328 public $fourn_multicurrency_unitprice;
332 public $fourn_multicurrency_tx;
336 public $fourn_multicurrency_id;
340 public $fourn_multicurrency_code;
341
345 public $packaging;
346
347
354 public $lifetime;
355
362 public $qc_frequency;
363
369 public $stock_reel = 0;
370
376 public $stock_theorique;
377
383 public $cost_price;
384
390 public $pmp;
391
397 public $seuil_stock_alerte = 0;
398
402 public $desiredstock = 0;
403
407 public $duration_value;
411 public $duration_unit;
415 public $duration;
416
420 public $fk_default_workstation;
421
427 public $status = 0;
428
435 public $tosell;
436
442 public $status_buy = 0;
443
450 public $tobuy;
451
457 public $finished;
458
464 public $fk_default_bom;
465
471 public $product_fourn_price_id;
472
478 public $buyprice;
479
485 public $tobatch;
486
487
493 public $status_batch = 0;
494
500 public $sell_or_eat_by_mandatory = 0;
501
507 public $batch_mask = '';
508
514 public $customcode;
515
521 public $url;
522
524
527 public $weight;
528
532 public $weight_units; // scale -3, 0, 3, 6
536 public $length;
540 public $length_units; // scale -3, 0, 3, 6
544 public $width;
548 public $width_units; // scale -3, 0, 3, 6
552 public $height;
556 public $height_units; // scale -3, 0, 3, 6
560 public $surface;
564 public $surface_units; // scale -3, 0, 3, 6
568 public $volume;
572 public $volume_units; // scale -3, 0, 3, 6
573
577 public $net_measure;
581 public $net_measure_units; // scale -3, 0, 3, 6
582
586 public $accountancy_code_sell;
590 public $accountancy_code_sell_intra;
594 public $accountancy_code_sell_export;
598 public $accountancy_code_buy;
602 public $accountancy_code_buy_intra;
606 public $accountancy_code_buy_export;
607
611 public $barcode;
612
616 public $barcode_type;
617
621 public $barcode_type_code;
622
626 public $stats_propale = array();
627
631 public $stats_commande = array();
632
636 public $stats_contrat = array();
637
641 public $stats_facture = array();
642
646 public $stats_proposal_supplier = array();
647
651 public $stats_commande_fournisseur = array();
652
656 public $stats_expedition = array();
657
661 public $stats_reception = array();
662
666 public $stats_mo = array();
667
671 public $stats_bom = array();
672
676 public $stats_mrptoconsume = array();
677
681 public $stats_mrptoproduce = array();
682
686 public $stats_facturerec = array();
687
691 public $stats_facture_fournisseur = array();
692
696 public $stats_facturefournrec = array();
697
701 public $imgWidth;
705 public $imgHeight;
706
711 public $product_fourn_id;
712
717 public $product_id_already_linked;
718
723 public $nbphoto = 0;
724
728 public $stock_warehouse = array();
729
733 public $fk_default_warehouse;
734
738 public $fk_price_expression;
739
744 public $fourn_qty;
745
750 public $fourn_pu;
751
756 public $fourn_price_base_type;
757
761 public $fourn_socid;
762
768 public $ref_fourn;
769
773 public $ref_supplier;
774
780 public $fk_unit;
781
787 public $price_autogen = 0;
788
794 public $sousprods = array();
795
799 public $res;
800
801
807 public $is_object_used;
808
818 public $is_sousproduit_qty;
819
830 public $is_sousproduit_incdec;
831
835 public $mandatory_period;
836
842 public $stockable_product = 1;
843
872 public $fields = array(
873 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
874 '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'),
875 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 5),
876 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 2, 'position' => 15, 'csslist' => 'tdoverflowmax250'),
877 'barcode' => array('type' => 'varchar(255)', 'label' => 'Barcode', 'enabled' => 'isModEnabled("barcode")', 'position' => 20, 'visible' => -1, 'showoncombobox' => 3, 'cssview' => 'tdwordbreak', 'csslist' => 'tdoverflowmax125'),
878 'fk_barcode_type' => array('type' => 'integer', 'label' => 'BarcodeType', 'enabled' => 1, 'position' => 21, 'notnull' => 0, 'visible' => -1,),
879 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 61),
880 'note' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 62),
881 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 500),
882 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 501),
883 //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
884 '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'),
885 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 511),
886 //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
887 'localtax1_tx' => array('type' => 'double(6,3)', 'label' => 'Localtax1tx', 'enabled' => 1, 'position' => 150, 'notnull' => 0, 'visible' => -1,),
888 'localtax1_type' => array('type' => 'varchar(10)', 'label' => 'Localtax1type', 'enabled' => 1, 'position' => 155, 'notnull' => 1, 'visible' => -1,),
889 'localtax2_tx' => array('type' => 'double(6,3)', 'label' => 'Localtax2tx', 'enabled' => 1, 'position' => 160, 'notnull' => 0, 'visible' => -1,),
890 'localtax2_type' => array('type' => 'varchar(10)', 'label' => 'Localtax2type', 'enabled' => 1, 'position' => 165, 'notnull' => 1, 'visible' => -1,),
891 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 170),
892 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'index' => 0, 'position' => 1000),
893 //'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')),
894 //'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')),
895 'mandatory_period' => array('type' => 'integer', 'label' => 'mandatoryperiod', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'default' => '0', 'index' => 1, 'position' => 1000),
896 'stockable_product' => array('type' => 'integer', 'label' => 'stockable_product', 'enabled' => 1, 'visible' => 1, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 502),
897 );
898
902 const TYPE_PRODUCT = 0;
906 const TYPE_SERVICE = 1;
907
911 const DISABLED_STOCK = 0;
912 const ENABLED_STOCK = 1;
913
919 public function __construct($db)
920 {
921 $this->db = $db;
922
923 $this->ismultientitymanaged = 1;
924 $this->isextrafieldmanaged = 1;
925
926 $this->canvas = '';
927 }
928
934 public function check()
935 {
936 if (getDolGlobalInt('MAIN_SECURITY_ALLOW_UNSECURED_REF_LABELS')) {
937 $this->ref = trim($this->ref);
938 } else {
939 $this->ref = dol_sanitizeFileName(stripslashes($this->ref));
940 }
941
942 $err = 0;
943 if (dol_strlen(trim($this->ref)) == 0) {
944 $err++;
945 }
946
947 if (dol_strlen(trim($this->label)) == 0) {
948 $err++;
949 }
950
951 if ($err > 0) {
952 return 0;
953 } else {
954 return 1;
955 }
956 }
957
965 public function create($user, $notrigger = 0)
966 {
967 global $conf, $langs;
968
969 $error = 0;
970
971 // Clean parameters
972 if (getDolGlobalInt('MAIN_SECURITY_ALLOW_UNSECURED_REF_LABELS')) {
973 $this->ref = trim($this->ref);
974 } else {
975 $this->ref = dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)));
976 }
977 $this->label = trim($this->label);
978 $this->price_ttc = (float) price2num($this->price_ttc);
979 $this->price = (float) price2num($this->price);
980 $this->price_min_ttc = (float) price2num($this->price_min_ttc);
981 $this->price_min = (float) price2num($this->price_min);
982 $this->price_label = trim($this->price_label);
983 if (empty($this->tva_tx)) {
984 $this->tva_tx = 0;
985 }
986 if (empty($this->tva_npr)) {
987 $this->tva_npr = 0;
988 }
989 // Local taxes
990 if (empty($this->localtax1_tx)) {
991 $this->localtax1_tx = 0;
992 }
993 if (empty($this->localtax2_tx)) {
994 $this->localtax2_tx = 0;
995 }
996 if (empty($this->localtax1_type)) {
997 $this->localtax1_type = '0';
998 }
999 if (empty($this->localtax2_type)) {
1000 $this->localtax2_type = '0';
1001 }
1002 // Price
1003 if (empty($this->price_base_type) && getDolGlobalString('PRODUCT_PRICE_BASE_TYPE')) {
1004 $this->price_base_type = getDolGlobalString('PRODUCT_PRICE_BASE_TYPE');
1005 }
1006 if (empty($this->price)) {
1007 $this->price = 0;
1008 }
1009 if (empty($this->price_min)) {
1010 $this->price_min = 0;
1011 }
1012 // Price by quantity
1013 if (empty($this->price_by_qty)) {
1014 $this->price_by_qty = 0;
1015 }
1016
1017 if (empty($this->status)) {
1018 $this->status = 0;
1019 }
1020 if (empty($this->status_buy)) {
1021 $this->status_buy = 0;
1022 }
1023 if (empty($this->stockable_product)) {
1024 $this->stockable_product = 0;
1025 }
1026
1027 $price_ht = 0;
1028 $price_ttc = 0;
1029 $price_min_ht = 0;
1030 $price_min_ttc = 0;
1031
1032 //
1033 if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
1034 $price_ttc = price2num($this->price_ttc, 'MU');
1035 $price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
1036 }
1037
1038 //
1039 if ($this->price_base_type != 'TTC' && $this->price > 0) {
1040 $price_ht = price2num($this->price, 'MU');
1041 $price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
1042 }
1043
1044 //
1045 if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
1046 $price_min_ttc = price2num($this->price_min_ttc, 'MU');
1047 $price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
1048 }
1049
1050 //
1051 if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
1052 $price_min_ht = price2num($this->price_min, 'MU');
1053 $price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
1054 }
1055
1056 $this->accountancy_code_buy = trim((string) $this->accountancy_code_buy);
1057 $this->accountancy_code_buy_intra = trim((string) $this->accountancy_code_buy_intra);
1058 $this->accountancy_code_buy_export = trim((string) $this->accountancy_code_buy_export);
1059 $this->accountancy_code_sell = trim((string) $this->accountancy_code_sell);
1060 $this->accountancy_code_sell_intra = trim((string) $this->accountancy_code_sell_intra);
1061 $this->accountancy_code_sell_export = trim((string) $this->accountancy_code_sell_export);
1062
1063 // Normalize the accountancy codes the way the admin dropdown does it, so an API client that
1064 // sends '606111000' ends up with the same '606111' value the GUI stores (see issue #32343).
1065 // When ACCOUNTING_MANAGE_ZERO is on, trailing zeros are part of the code and must be kept.
1066 if (!getDolGlobalString('ACCOUNTING_MANAGE_ZERO')) {
1067 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1068 $this->accountancy_code_buy = clean_account($this->accountancy_code_buy);
1069 $this->accountancy_code_buy_intra = clean_account($this->accountancy_code_buy_intra);
1070 $this->accountancy_code_buy_export = clean_account($this->accountancy_code_buy_export);
1071 $this->accountancy_code_sell = clean_account($this->accountancy_code_sell);
1072 $this->accountancy_code_sell_intra = clean_account($this->accountancy_code_sell_intra);
1073 $this->accountancy_code_sell_export = clean_account($this->accountancy_code_sell_export);
1074 }
1075
1076 // Barcode value
1077 $this->barcode = trim($this->barcode);
1078 $this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
1079 // Check parameters
1080 if (empty($this->label)) {
1081 $langs->load('errors');
1082 $this->errors[] = $langs->trans('ErrorMandatoryParametersNotProvided');
1083 return -1;
1084 }
1085
1086 if (empty($this->ref) || $this->ref == 'auto') {
1087 // Load object modCodeProduct
1088 $module = getDolGlobalString('PRODUCT_CODEPRODUCT_ADDON', 'mod_codeproduct_leopard');
1089 if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
1090 if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
1091 $module = substr($module, 0, dol_strlen($module) - 4);
1092 }
1093 dol_include_once('/core/modules/product/'.$module.'.php');
1094 $modCodeProduct = new $module();
1095 '@phan-var-force ModeleProductCode $modCodeProduct';
1096 if (!empty($modCodeProduct->code_auto)) {
1097 $this->ref = $modCodeProduct->getNextValue($this, $this->type);
1098 }
1099 unset($modCodeProduct);
1100 }
1101
1102 if (empty($this->ref)) {
1103 $this->error = 'ProductModuleNotSetupForAutoRef';
1104 return -2;
1105 }
1106 }
1107
1108 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);
1109
1110 $now = dol_now();
1111
1112 if (empty($this->date_creation)) {
1113 $this->date_creation = $now;
1114 }
1115
1116 $this->db->begin();
1117
1118 // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
1119 if ($this->barcode == '-1' || $this->barcode == 'auto') {
1120 $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
1121 }
1122
1123 // Check more parameters
1124 // If error, this->errors[] is filled
1125 $result = $this->verify();
1126
1127 if ($result >= 0) {
1128 $sql = "SELECT count(*) as nb";
1129 $sql .= " FROM ".$this->db->prefix()."product";
1130 $sql .= " WHERE entity IN (".getEntity('product').")";
1131 $sql .= " AND ref = '".$this->db->escape($this->ref)."'";
1132
1133 $result = $this->db->query($sql);
1134 if ($result) {
1135 $obj = $this->db->fetch_object($result);
1136 if ($obj->nb == 0) {
1137 // Insert new product, no previous one found
1138 $sql = "INSERT INTO ".$this->db->prefix()."product (";
1139 $sql .= "datec";
1140 $sql .= ", entity";
1141 $sql .= ", ref";
1142 $sql .= ", ref_ext";
1143 $sql .= ", price_min";
1144 $sql .= ", price_min_ttc";
1145 $sql .= ", label";
1146 $sql .= ", fk_user_author";
1147 $sql .= ", fk_product_type";
1148 $sql .= ", price";
1149 $sql .= ", price_ttc";
1150 $sql .= ", price_base_type";
1151 $sql .= ", price_label";
1152 $sql .= ", tobuy";
1153 $sql .= ", tosell";
1154 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1155 $sql .= ", accountancy_code_buy";
1156 $sql .= ", accountancy_code_buy_intra";
1157 $sql .= ", accountancy_code_buy_export";
1158 $sql .= ", accountancy_code_sell";
1159 $sql .= ", accountancy_code_sell_intra";
1160 $sql .= ", accountancy_code_sell_export";
1161 }
1162 $sql .= ", canvas";
1163 $sql .= ", finished";
1164 $sql .= ", tobatch";
1165 $sql .= ", sell_or_eat_by_mandatory";
1166 $sql .= ", batch_mask";
1167 $sql .= ", fk_unit";
1168 $sql .= ", mandatory_period";
1169 $sql .= ", stockable_product";
1170 if (!empty($this->default_vat_code)) {
1171 $sql .= ", default_vat_code";
1172 }
1173 $sql .= ") VALUES (";
1174 $sql .= "'".$this->db->idate($this->date_creation)."'";
1175 $sql .= ", ".(!empty($this->entity) ? (int) $this->entity : (int) $conf->entity);
1176 $sql .= ", '".$this->db->escape($this->ref)."'";
1177 $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1178 $sql .= ", ".price2num($price_min_ht);
1179 $sql .= ", ".price2num($price_min_ttc);
1180 $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
1181 $sql .= ", ".((int) $user->id);
1182 $sql .= ", ".((int) $this->type);
1183 $sql .= ", ".price2num($price_ht, 'MT');
1184 $sql .= ", ".price2num($price_ttc, 'MT');
1185 $sql .= ", '".$this->db->escape($this->price_base_type)."'";
1186 $sql .= ", ".(!empty($this->price_label) ? "'".$this->db->escape($this->price_label)."'" : "null");
1187 $sql .= ", ".((int) $this->status);
1188 $sql .= ", ".((int) $this->status_buy);
1189 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1190 $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
1191 $sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
1192 $sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
1193 $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
1194 $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
1195 $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
1196 }
1197 $sql .= ", '".$this->db->escape($this->canvas)."'";
1198 $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
1199 $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
1200 $sql .= ", ".((empty($this->sell_or_eat_by_mandatory) || $this->sell_or_eat_by_mandatory < 0) ? 0 : ((int) $this->sell_or_eat_by_mandatory));
1201 $sql .= ", '".$this->db->escape($this->batch_mask)."'";
1202 $sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
1203 $sql .= ", '".$this->db->escape((string) $this->mandatory_period)."'";
1204 $sql .= ", ".((int) $this->stockable_product);
1205 if (!empty($this->default_vat_code)) {
1206 $sql .= ", '".$this->db->escape($this->default_vat_code)."'";
1207 }
1208 $sql .= ")";
1209 dol_syslog(get_class($this)."::Create", LOG_DEBUG);
1210
1211 $result = $this->db->query($sql);
1212 if ($result) {
1213 $id = $this->db->last_insert_id($this->db->prefix()."product");
1214
1215 if ($id > 0) {
1216 $this->id = $id;
1217 $this->price = $price_ht;
1218 $this->price_ttc = $price_ttc;
1219 $this->price_min = $price_min_ht;
1220 $this->price_min_ttc = $price_min_ttc;
1221
1222 $result = $this->_log_price($user);
1223 if ($result > 0) {
1224 if ($this->update($id, $user, 1, 'add') <= 0) {
1225 $error++;
1226 }
1227 } else {
1228 $error++;
1229 $this->error = $this->db->lasterror();
1230 }
1231
1232 // update accountancy for this entity
1233 if (!$error && getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1234 $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
1235
1236 $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
1237 $sql .= " fk_product";
1238 $sql .= ", entity";
1239 $sql .= ", accountancy_code_buy";
1240 $sql .= ", accountancy_code_buy_intra";
1241 $sql .= ", accountancy_code_buy_export";
1242 $sql .= ", accountancy_code_sell";
1243 $sql .= ", accountancy_code_sell_intra";
1244 $sql .= ", accountancy_code_sell_export";
1245 $sql .= ") VALUES (";
1246 $sql .= ((int) $this->id);
1247 $sql .= ", " . ((int) $conf->entity);
1248 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1249 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1250 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1251 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1252 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1253 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1254 $sql .= ")";
1255 $result = $this->db->query($sql);
1256 if (!$result) {
1257 $error++;
1258 $this->error = 'ErrorFailedToInsertAccountancyForEntity';
1259 }
1260 }
1261 } else {
1262 $error++;
1263 $this->error = 'ErrorFailedToGetInsertedId';
1264 }
1265 } else {
1266 $error++;
1267 $this->error = $this->db->lasterror();
1268 }
1269 } else {
1270 // Product already exists with this ref
1271 $langs->load("products");
1272 $error++;
1273 $this->error = "ErrorProductAlreadyExists";
1274 dol_syslog(get_class($this)."::Create fails, ref ".$this->ref." already exists");
1275 }
1276 } else {
1277 $error++;
1278 $this->error = $this->db->lasterror();
1279 }
1280
1281 if (!$error && !$notrigger) {
1282 // Call trigger
1283 $result = $this->call_trigger('PRODUCT_CREATE', $user);
1284 if ($result < 0) {
1285 $error++;
1286 }
1287 // End call triggers
1288 }
1289
1290 if (!$error) {
1291 $this->db->commit();
1292 return $this->id;
1293 } else {
1294 $this->db->rollback();
1295 return -$error;
1296 }
1297 } else {
1298 $this->db->rollback();
1299 dol_syslog(get_class($this)."::Create fails verify ".implode(',', $this->errors), LOG_WARNING);
1300 return -3;
1301 }
1302 }
1303
1304
1311 public function verify()
1312 {
1313 global $langs;
1314
1315 $this->errors = array();
1316
1317 $result = 0;
1318 $this->ref = trim($this->ref);
1319
1320 if (!$this->ref) {
1321 $this->errors[] = 'ErrorBadRef';
1322 $result = -2;
1323 }
1324
1325 $arrayofnonnegativevalue = array('weight' => 'Weight', 'width' => 'Width', 'height' => 'Height', 'length' => 'Length', 'surface' => 'Surface', 'volume' => 'Volume');
1326 foreach ($arrayofnonnegativevalue as $key => $value) {
1327 if (property_exists($this, $key) && !empty($this->$key) && ($this->$key < 0)) {
1328 $langs->loadLangs(array("main", "other"));
1329 $this->error = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
1330 $this->errors[] = $this->error;
1331 $result = -4;
1332 }
1333 }
1334
1335 $rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
1336 if ($rescode) {
1337 if ($rescode == -1) {
1338 $this->errors[] = 'ErrorBadBarCodeSyntax';
1339 } elseif ($rescode == -2) {
1340 $this->errors[] = 'ErrorBarCodeRequired';
1341 } elseif ($rescode == -3) {
1342 // Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
1343 $this->errors[] = 'ErrorBarCodeAlreadyUsed';
1344 }
1345
1346 $result = -3;
1347 }
1348
1349 return $result;
1350 }
1351
1352 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1363 public function check_barcode($valuetotest, $typefortest)
1364 {
1365 // phpcs:enable
1366 global $conf;
1367
1368 if (isModEnabled('barcode') && getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM')) {
1369 $module = strtolower(getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM'));
1370
1371 $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
1372 foreach ($dirsociete as $dirroot) {
1373 $res = dol_include_once($dirroot.$module.'.php');
1374 if ($res) {
1375 break;
1376 }
1377 }
1378
1379 $mod = new $module();
1380 '@phan-var-force ModeleNumRefBarCode $mod';
1383 dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
1384 $result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
1385 return $result;
1386 } else {
1387 return 0;
1388 }
1389 }
1390
1402 public function update($id, $user, $notrigger = 0, $action = 'update', $updatetype = false)
1403 {
1404 global $langs, $conf, $hookmanager;
1405
1406 $error = 0;
1407
1408 // Check parameters
1409 if (!$this->label) {
1410 $this->label = 'MISSING LABEL';
1411 }
1412
1413 // Clean parameters
1414 if (getDolGlobalInt('MAIN_SECURITY_ALLOW_UNSECURED_REF_LABELS')) {
1415 $this->ref = trim($this->ref);
1416 } else {
1417 $this->ref = dol_string_nospecial(trim($this->ref));
1418 }
1419 $this->label = trim($this->label);
1420 $this->description = trim($this->description);
1421 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : null);
1422 $this->note_public = (isset($this->note_public) ? trim($this->note_public) : null);
1423 $this->net_measure = price2num($this->net_measure);
1424 $this->net_measure_units = (!is_numeric($this->net_measure_units) ? null : (int) $this->net_measure_units);
1425 $this->weight = price2num($this->weight);
1426 $this->weight_units = (!is_numeric($this->weight_units) ? null : (int) $this->weight_units);
1427 $this->length = price2num($this->length);
1428 $this->length_units = (!is_numeric($this->length_units) ? null : (int) $this->length_units);
1429 $this->width = price2num($this->width);
1430 $this->width_units = (!is_numeric($this->width_units) ? null : (int) $this->width_units);
1431 $this->height = price2num($this->height);
1432 $this->height_units = (!is_numeric($this->height_units) ? null : (int) $this->height_units);
1433 $this->surface = price2num($this->surface);
1434 $this->surface_units = (!is_numeric($this->surface_units) ? null : (int) $this->surface_units);
1435 $this->volume = price2num($this->volume);
1436 $this->volume_units = (!is_numeric($this->volume_units) ? null : (int) $this->volume_units);
1437
1438 // set unit not defined
1439 if (is_numeric($this->length_units)) {
1440 $this->width_units = $this->length_units; // Not used yet
1441 }
1442 if (is_numeric($this->length_units)) {
1443 $this->height_units = $this->length_units; // Not used yet
1444 }
1445
1446 // Automated compute surface and volume if not filled
1447 if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
1448 $this->surface = (float) $this->length * (float) $this->width;
1449 $this->surface_units = measuring_units_squared((int) $this->length_units);
1450 }
1451 if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
1452 $this->volume = $this->surface * (float) $this->height;
1453 $this->volume_units = measuring_units_cubed((int) $this->height_units);
1454 }
1455
1456 if (empty($this->tva_tx)) {
1457 $this->tva_tx = 0;
1458 }
1459 if (empty($this->tva_npr)) {
1460 $this->tva_npr = 0;
1461 }
1462 if (empty($this->localtax1_tx)) {
1463 $this->localtax1_tx = 0;
1464 }
1465 if (empty($this->localtax2_tx)) {
1466 $this->localtax2_tx = 0;
1467 }
1468 if (empty($this->localtax1_type)) {
1469 $this->localtax1_type = '0';
1470 }
1471 if (empty($this->localtax2_type)) {
1472 $this->localtax2_type = '0';
1473 }
1474 if (empty($this->status)) {
1475 $this->status = 0;
1476 }
1477 if (empty($this->status_buy)) {
1478 $this->status_buy = 0;
1479 }
1480
1481 if (empty($this->country_id)) {
1482 $this->country_id = 0;
1483 }
1484 if (empty($this->country_id) && !empty($this->country_code)) {
1485 $country_id = getCountry($this->country_code, '3');
1486 $this->country_id = is_int($country_id) ? $country_id : 0;
1487 }
1488
1489 if (empty($this->state_id)) {
1490 $this->state_id = 0;
1491 }
1492
1493 if (empty($this->stockable_product)) {
1494 $this->stockable_product = 0;
1495 }
1496
1497 // For automatic creation during update action (not used by Dolibarr GUI, can be used by scripts)
1498 if ($this->barcode == '-1' || $this->barcode == 'auto') {
1499 $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
1500 }
1501
1502 // Barcode value
1503 $this->barcode = (empty($this->barcode) ? '' : trim($this->barcode));
1504
1505 $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1506 $this->accountancy_code_buy_intra = (!empty($this->accountancy_code_buy_intra) ? trim($this->accountancy_code_buy_intra) : '');
1507 $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
1508 $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1509 $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
1510 $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
1511
1512 // Normalize the accountancy codes the way the admin dropdown does it, so an API client that
1513 // sends '606111000' ends up with the same '606111' value the GUI stores (see issue #32343).
1514 // When ACCOUNTING_MANAGE_ZERO is on, trailing zeros are part of the code and must be kept.
1515 if (!getDolGlobalString('ACCOUNTING_MANAGE_ZERO')) {
1516 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1517 $this->accountancy_code_buy = clean_account($this->accountancy_code_buy);
1518 $this->accountancy_code_buy_intra = clean_account($this->accountancy_code_buy_intra);
1519 $this->accountancy_code_buy_export = clean_account($this->accountancy_code_buy_export);
1520 $this->accountancy_code_sell = clean_account($this->accountancy_code_sell);
1521 $this->accountancy_code_sell_intra = clean_account($this->accountancy_code_sell_intra);
1522 $this->accountancy_code_sell_export = clean_account($this->accountancy_code_sell_export);
1523 }
1524
1525 $this->db->begin();
1526
1527 $result = 0;
1528 // Check name is required and codes are ok or unique. If error, this->errors[] is filled
1529 if ($action != 'add') {
1530 $result = $this->verify(); // We don't check when update called during a create because verify was already done
1531 } else {
1532 // we can continue
1533 $result = 0;
1534 }
1535
1536 if ($result >= 0) {
1537 // $this->oldcopy should have been set by the caller of update (here properties were already modified)
1538 // Note that this->oldcopy must be a Product instance (not stdClass), otherwise the method
1539 // hasbatch() called below will fatal. Callers may set oldcopy via dol_clone($obj, 2) (which
1540 // returns a stdClass with scalar properties only) and then we cannot call methods on it,
1541 // so re-clone with native=1 in that case (see issues #38663, #38638).
1542 if (is_null($this->oldcopy) || (is_object($this->oldcopy) && empty($this->oldcopy->id)) || !($this->oldcopy instanceof Product)) {
1543 $this->oldcopy = dol_clone($this, 1); // 1 to clone with methods to avoid fatal error with $this->oldcopy->hasbatch()
1544 }
1545 // Test if batch management is activated on existing product
1546 // If yes, we create missing entries into product_batch
1547 if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
1548 //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
1549 $valueforundefinedlot = '000000';
1550 if (getDolGlobalString('STOCK_DEFAULT_BATCH')) {
1551 $valueforundefinedlot = getDolGlobalString('STOCK_DEFAULT_BATCH');
1552 }
1553
1554 dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
1555
1556 $this->load_stock();
1557 foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
1558 $qty_batch = 0;
1559 foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
1560 if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
1561 // We discard this line, we will create it later
1562 $sqlclean = "DELETE FROM ".$this->db->prefix()."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".((int) $ObjW->id);
1563 $result = $this->db->query($sqlclean);
1564 if (!$result) {
1565 dol_print_error($this->db);
1566 exit;
1567 }
1568 continue;
1569 }
1570
1571 $qty_batch += $detail->qty;
1572 }
1573 // Quantities in batch details are not same as stock quantity,
1574 // so we add a default batch record to complete and get same qty in parent and child table
1575 if ($ObjW->real != $qty_batch) {
1576 $ObjBatch = new Productbatch($this->db);
1577 $ObjBatch->batch = $valueforundefinedlot;
1578 $ObjBatch->qty = ($ObjW->real - $qty_batch);
1579 $ObjBatch->fk_product_stock = (int) $ObjW->id;
1580
1581 if ($ObjBatch->create($user, 1) < 0) {
1582 $error++;
1583 $this->errors = $ObjBatch->errors;
1584 } else {
1585 // we also add lot record if not exist
1586 $ObjLot = new Productlot($this->db);
1587 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1588 if ($ObjLot->fetch(0, $this->id, $valueforundefinedlot) == 0) {
1589 $ObjLot->fk_product = $this->id;
1590 $ObjLot->entity = (int) $this->entity;
1591 $ObjLot->fk_user_creat = $user->id;
1592 $ObjLot->batch = $valueforundefinedlot;
1593 if ($ObjLot->create($user, 1) < 0) {
1594 $error++;
1595 $this->errors = $ObjLot->errors;
1596 }
1597 }
1598 }
1599 }
1600 }
1601 }
1602
1603 $sql = "UPDATE ".$this->db->prefix()."product";
1604 $sql .= " SET label = '".$this->db->escape($this->label)."'";
1605
1606 if ($updatetype && ($this->isProduct() || $this->isService())) {
1607 $sql .= ", fk_product_type = ".((int) $this->type);
1608 }
1609
1610 $sql .= ", ref = '".$this->db->escape($this->ref)."'";
1611 $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1612 $sql .= ", default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null");
1613 $sql .= ", tva_tx = ".((float) $this->tva_tx);
1614 $sql .= ", recuperableonly = ".((int) $this->tva_npr);
1615 $sql .= ", localtax1_tx = ".((float) $this->localtax1_tx);
1616 $sql .= ", localtax2_tx = ".((float) $this->localtax2_tx);
1617 $sql .= ", localtax1_type = ".($this->localtax1_type != '' ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'");
1618 $sql .= ", localtax2_type = ".($this->localtax2_type != '' ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'");
1619
1620 $sql .= ", barcode = ".(empty($this->barcode) ? "null" : "'".$this->db->escape($this->barcode)."'");
1621 $sql .= ", fk_barcode_type = ".(empty($this->barcode_type) ? "null" : ((int) $this->barcode_type));
1622
1623 $sql .= ", tosell = ".(int) $this->status;
1624 $sql .= ", tobuy = ".(int) $this->status_buy;
1625 $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch);
1626 $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);
1627 $sql .= ", batch_mask = '".$this->db->escape($this->batch_mask)."'";
1628
1629 $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished === '') ? "null" : (int) $this->finished);
1630 $sql .= ", fk_default_bom = ".((!isset($this->fk_default_bom) || $this->fk_default_bom < 0 || $this->fk_default_bom == '') ? "null" : (int) $this->fk_default_bom);
1631 $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null');
1632 $sql .= ", net_measure_units = ".((string) $this->net_measure_units != '' ? ((int) $this->net_measure_units) : 'null');
1633 $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null');
1634 $sql .= ", weight_units = ".((string) $this->weight_units != '' ? ((int) $this->weight_units) : 'null');
1635 $sql .= ", length = ".($this->length != '' ? "'".$this->db->escape($this->length)."'" : 'null');
1636 $sql .= ", length_units = ".((string) $this->length_units != '' ? ((int) $this->length_units) : 'null');
1637 $sql .= ", width= ".($this->width != '' ? "'".$this->db->escape($this->width)."'" : 'null');
1638 $sql .= ", width_units = ".((string) $this->width_units != '' ? ((int) $this->width_units) : 'null');
1639 $sql .= ", height = ".($this->height != '' ? "'".$this->db->escape($this->height)."'" : 'null');
1640 $sql .= ", height_units = ".((string) $this->height_units != '' ? ((int) $this->height_units) : 'null');
1641 $sql .= ", surface = ".($this->surface != '' ? "'".$this->db->escape($this->surface)."'" : 'null');
1642 $sql .= ", surface_units = ".((string) $this->surface_units != '' ? ((int) $this->surface_units) : 'null');
1643 $sql .= ", volume = ".($this->volume != '' ? "'".$this->db->escape($this->volume)."'" : 'null');
1644 $sql .= ", volume_units = ".((string) $this->volume_units != '' ? ((int) $this->volume_units) : 'null');
1645 $sql .= ", fk_default_warehouse = ".($this->fk_default_warehouse > 0 ? ((int) $this->fk_default_warehouse) : 'null');
1646 $sql .= ", fk_default_workstation = ".($this->fk_default_workstation > 0 ? ((int) $this->fk_default_workstation) : 'null');
1647 $sql .= ", seuil_stock_alerte = ".((isset($this->seuil_stock_alerte) && is_numeric($this->seuil_stock_alerte)) ? (float) $this->seuil_stock_alerte : 'null');
1648 $sql .= ", description = '".$this->db->escape($this->description)."'";
1649 $sql .= ", url = ".($this->url ? "'".$this->db->escape($this->url)."'" : 'null');
1650 $sql .= ", customcode = '".$this->db->escape($this->customcode)."'";
1651 $sql .= ", fk_country = ".($this->country_id > 0 ? (int) $this->country_id : 'null');
1652 $sql .= ", fk_state = ".($this->state_id > 0 ? (int) $this->state_id : 'null');
1653 $sql .= ", lifetime = ".($this->lifetime > 0 ? (int) $this->lifetime : 'null');
1654 $sql .= ", qc_frequency = ".($this->qc_frequency > 0 ? (int) $this->qc_frequency : 'null');
1655 $sql .= ", note = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : 'null');
1656 $sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : 'null');
1657 $sql .= ", duration = '".$this->db->escape($this->duration_value.$this->duration_unit)."'";
1658 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1659 $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1660 $sql .= ", accountancy_code_buy_intra = '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1661 $sql .= ", accountancy_code_buy_export = '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1662 $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1663 $sql .= ", accountancy_code_sell_intra= '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1664 $sql .= ", accountancy_code_sell_export= '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1665 }
1666 $sql .= ", desiredstock = ".((isset($this->desiredstock) && is_numeric($this->desiredstock)) ? (float) $this->desiredstock : "null");
1667 $sql .= ", cost_price = ".($this->cost_price != '' ? ((float) $this->cost_price) : 'null');
1668 $sql .= ", fk_unit= ".(!$this->fk_unit ? 'NULL' : (int) $this->fk_unit);
1669 $sql .= ", price_autogen = ".(!$this->price_autogen ? 0 : 1);
1670 $sql .= ", fk_price_expression = ".($this->fk_price_expression != 0 ? (int) $this->fk_price_expression : 'NULL');
1671 $sql .= ", fk_user_modif = ".($user->id > 0 ? (int) $user->id : 'NULL');
1672 $sql .= ", mandatory_period = ".((int) $this->mandatory_period);
1673 $sql .= ", stockable_product = ".(int) $this->stockable_product;
1674 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1675 $sql .= ", packaging = ".(float) $this->packaging;
1676 }
1677
1678 // stock field is not here because it is a denormalized value from product_stock.
1679 $sql .= " WHERE rowid = ".((int) $id);
1680
1681 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1682
1683 $resql = $this->db->query($sql);
1684 if ($resql) {
1685 $this->id = $id;
1686
1687 // Multilangs
1688 if (getDolGlobalInt('MAIN_MULTILANGS')) {
1689 if ($this->setMultiLangs($user, $notrigger) < 0) {
1690 $this->db->rollback();
1691 return -2;
1692 }
1693 }
1694
1695 $action = 'update';
1696
1697 // update accountancy for this entity
1698 if (!$error && getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1699 $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " . ((int) $this->id) . " AND entity = " . ((int) $conf->entity));
1700
1701 $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
1702 $sql .= " fk_product";
1703 $sql .= ", entity";
1704 $sql .= ", accountancy_code_buy";
1705 $sql .= ", accountancy_code_buy_intra";
1706 $sql .= ", accountancy_code_buy_export";
1707 $sql .= ", accountancy_code_sell";
1708 $sql .= ", accountancy_code_sell_intra";
1709 $sql .= ", accountancy_code_sell_export";
1710 $sql .= ") VALUES (";
1711 $sql .= ((int) $this->id);
1712 $sql .= ", " . ((int) $conf->entity);
1713 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1714 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1715 $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1716 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1717 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1718 $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1719 $sql .= ")";
1720 $result = $this->db->query($sql);
1721 if (!$result) {
1722 $error++;
1723 $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1724 }
1725 }
1726
1727 if (!$this->hasbatch() && $this->oldcopy->hasbatch()) {
1728 // Selection of all product stock movements that contains batchs
1729 $sql = 'SELECT pb.qty, ps.fk_entrepot, pb.batch FROM '.MAIN_DB_PREFIX.'product_batch as pb';
1730 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_stock as ps ON (ps.rowid = pb.fk_product_stock)';
1731 $sql .= ' WHERE ps.fk_product = '.(int) $this->id;
1732
1733 $resql = $this->db->query($sql);
1734 if ($resql) {
1735 $inventorycode = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
1736
1737 while ($obj = $this->db->fetch_object($resql)) {
1738 $value = $obj->qty;
1739 $fk_entrepot = $obj->fk_entrepot;
1740 $price = 0;
1741 $dlc = '';
1742 $dluo = '';
1743 $batch = $obj->batch;
1744
1745 // To know how to revert stockMouvement (add or remove)
1746 $addOremove = $value > 0 ? 1 : 0; // 1 if remove, 0 if add
1747 $label = $langs->trans('BatchStockMouvementAddInGlobal');
1748 $res = $this->correct_stock_batch($user, $fk_entrepot, abs($value), $addOremove, $label, $price, $dlc, $dluo, $batch, $inventorycode, '', null, 0, null, true);
1749
1750 if ($res > 0) {
1751 $label = $langs->trans('BatchStockMouvementAddInGlobal');
1752 $res = $this->correct_stock($user, $fk_entrepot, abs($value), (int) empty($addOremove), $label, $price, $inventorycode, '', null, 0);
1753 if ($res < 0) {
1754 $error++;
1755 }
1756 } else {
1757 $error++;
1758 }
1759 }
1760 }
1761 }
1762
1763 // Actions on extra fields
1764 if (!$error) {
1765 $result = $this->insertExtraFields();
1766 if ($result < 0) {
1767 $error++;
1768 }
1769 }
1770
1771 if (!$error && !$notrigger) {
1772 // Call trigger
1773 $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1774 if ($result < 0) {
1775 $error++;
1776 }
1777 // End call triggers
1778 }
1779
1780 if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
1781 // We remove directory
1782 if ($conf->product->dir_output) {
1783 $olddir = $conf->product->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
1784 $newdir = $conf->product->dir_output."/".dol_sanitizeFileName($this->ref);
1785 if (file_exists($olddir)) {
1786 // include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1787 // $res = dol_move($olddir, $newdir);
1788 // do not use dol_move with directory
1789 $res = @rename($olddir, $newdir);
1790 if (!$res) {
1791 $langs->load("errors");
1792 $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
1793 $error++;
1794 } else {
1795 // to keep old entries with the new dir
1796 require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
1797 $ecmfiles = new EcmFiles($this->db);
1798 $ecmfiles->updateAfterRename("produit/".dol_sanitizeFileName($this->oldcopy->ref), "produit/".dol_sanitizeFileName($this->ref));
1799 }
1800 }
1801 }
1802 }
1803
1804 if (!$error) {
1805 if (isModEnabled('variants')) {
1806 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1807
1808 $comb = new ProductCombination($this->db);
1809
1810 foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) {
1811 $currcomb->updateProperties($this, $user);
1812 }
1813 }
1814
1815 $this->db->commit();
1816 return 1;
1817 } else {
1818 $this->db->rollback();
1819 return -$error;
1820 }
1821 } else {
1822 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1823 $langs->load("errors");
1824 if (empty($conf->barcode->enabled) || empty($this->barcode)) {
1825 $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref);
1826 } else {
1827 $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode);
1828 }
1829 $this->errors[] = $this->error;
1830 $this->db->rollback();
1831 return -1;
1832 } else {
1833 $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1834 $this->errors[] = $this->error;
1835 $this->db->rollback();
1836 return -2;
1837 }
1838 }
1839 } else {
1840 $this->db->rollback();
1841 dol_syslog(get_class($this)."::Update fails verify ".implode(',', $this->errors), LOG_WARNING);
1842 return -3;
1843 }
1844 }
1845
1853 public function delete(User $user, $notrigger = 0)
1854 {
1855 global $conf;
1856 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1857
1858 $error = 0;
1859
1860 // Check parameters
1861 if (empty($this->id)) {
1862 $this->error = "Object must be fetched before calling delete";
1863 return -1;
1864 }
1865 if (($this->isProduct() && !$user->hasRight('produit', 'supprimer')) || ($this->isService() && !$user->hasRight('service', 'supprimer'))) {
1866 $this->error = "ErrorForbidden";
1867 return 0;
1868 }
1869
1870 $objectisused = $this->isObjectUsed($this->id);
1871 if (empty($objectisused)) {
1872 $this->db->begin();
1873
1874 if (empty($notrigger)) {
1875 // Call trigger
1876 $result = $this->call_trigger('PRODUCT_DELETE', $user);
1877 if ($result < 0) {
1878 $error++;
1879 }
1880 // End call triggers
1881 }
1882
1883 // Delete from product_batch on product delete
1884 if (!$error) {
1885 $sql = "DELETE FROM ".$this->db->prefix().'product_batch';
1886 $sql .= " WHERE fk_product_stock IN (";
1887 $sql .= "SELECT rowid FROM ".$this->db->prefix().'product_stock';
1888 $sql .= " WHERE fk_product = ".((int) $this->id).")";
1889
1890 $result = $this->db->query($sql);
1891 if (!$result) {
1892 $error++;
1893 $this->errors[] = $this->db->lasterror();
1894 }
1895 }
1896
1897 // Delete pricelogs so we don't have any orphan rows, see #38383
1898 if (!$error) {
1899 $sql = "DELETE FROM " . $this->db->prefix() . "product_fournisseur_price_log";
1900 $sql .= " WHERE fk_product_fournisseur IN (";
1901 $sql .= " SELECT rowid FROM " . $this->db->prefix() . "product_fournisseur_price";
1902 $sql .= " WHERE fk_product = " . ((int) $this->id);
1903 $sql .= " )";
1904
1905 $resql = $this->db->query($sql);
1906 if (!$resql) {
1907 $error++;
1908 $this->errors[] = $this->db->lasterror();
1909 }
1910 }
1911
1912 // Delete all child tables
1913 if (!$error) {
1914 $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
1915 foreach ($elements as $table) {
1916 if (!$error) {
1917 $sql = "DELETE FROM ".$this->db->prefix().$table;
1918 $sql .= " WHERE fk_product = ".(int) $this->id;
1919
1920 $result = $this->db->query($sql);
1921 if (!$result) {
1922 $error++;
1923 $this->errors[] = $this->db->lasterror();
1924 }
1925 }
1926 }
1927 }
1928
1929 if (!$error && isModEnabled('variants')) {
1930 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1931 include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
1932
1933 // If it is a parent product, then we remove the association with child products
1934 $prodcomb = new ProductCombination($this->db);
1935
1936 if ($prodcomb->deleteByFkProductParent($user, $this->id) < 0) {
1937 $error++;
1938 $this->errors[] = 'Error deleting combinations';
1939 }
1940
1941 // We also check if it is a child product
1942 if (!$error && ($prodcomb->fetchByFkProductChild($this->id) > 0) && ($prodcomb->delete($user) < 0)) {
1943 $error++;
1944 $this->errors[] = 'Error deleting child combination';
1945 }
1946 }
1947
1948 // Delete from product_association
1949 if (!$error) {
1950 $sql = "DELETE FROM ".$this->db->prefix()."product_association";
1951 $sql .= " WHERE fk_product_pere = ".(int) $this->id." OR fk_product_fils = ".(int) $this->id;
1952
1953 $result = $this->db->query($sql);
1954 if (!$result) {
1955 $error++;
1956 $this->errors[] = $this->db->lasterror();
1957 }
1958 }
1959
1960 // Remove extrafields
1961 if (!$error) {
1962 $result = $this->deleteExtraFields();
1963 if ($result < 0) {
1964 $error++;
1965 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1966 }
1967 }
1968
1969 // Delete product
1970 if (!$error) {
1971 $sqlz = "DELETE FROM ".$this->db->prefix()."product";
1972 $sqlz .= " WHERE rowid = ".(int) $this->id;
1973
1974 $resultz = $this->db->query($sqlz);
1975 if (!$resultz) {
1976 $error++;
1977 $this->errors[] = $this->db->lasterror();
1978 }
1979 }
1980
1981 // Delete record into ECM index and physically
1982 if (!$error) {
1983 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1984 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
1985 if (!$res) {
1986 $error++;
1987 }
1988 }
1989
1990 if (!$error) {
1991 // We remove directory
1992 $ref = dol_sanitizeFileName($this->ref);
1993 if ($conf->product->dir_output) {
1994 $dir = $conf->product->dir_output."/".$ref;
1995 if (file_exists($dir)) {
1996 $res = @dol_delete_dir_recursive($dir);
1997 if (!$res) {
1998 $this->errors[] = 'ErrorFailToDeleteDir';
1999 $error++;
2000 }
2001 }
2002 }
2003 }
2004
2005 if (!$error) {
2006 $this->db->commit();
2007 return 1;
2008 } else {
2009 foreach ($this->errors as $errmsg) {
2010 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
2011 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2012 }
2013 $this->db->rollback();
2014 return -$error;
2015 }
2016 } else {
2017 $this->error = "ErrorRecordIsUsedCantDelete";
2018 return 0;
2019 }
2020 }
2021
2027 public static function getSellOrEatByMandatoryList()
2028 {
2029 global $langs;
2030
2031 $sellByLabel = $langs->trans('SellByDate');
2032 $eatByLabel = $langs->trans('EatByDate');
2033 return array(
2034 self::SELL_OR_EAT_BY_MANDATORY_ID_NONE => $langs->trans('BatchSellOrEatByMandatoryNone'),
2035 self::SELL_OR_EAT_BY_MANDATORY_ID_SELL_BY => $sellByLabel,
2036 self::SELL_OR_EAT_BY_MANDATORY_ID_EAT_BY => $eatByLabel,
2037 self::SELL_OR_EAT_BY_MANDATORY_ID_SELL_AND_EAT => $langs->trans('BatchSellOrEatByMandatoryAll', $sellByLabel, $eatByLabel),
2038 );
2039 }
2040
2047 {
2048 $sellOrEatByMandatoryLabel = '';
2049
2050 $sellOrEatByMandatoryList = self::getSellOrEatByMandatoryList();
2051 if (isset($sellOrEatByMandatoryList[$this->sell_or_eat_by_mandatory])) {
2052 $sellOrEatByMandatoryLabel = $sellOrEatByMandatoryList[$this->sell_or_eat_by_mandatory];
2053 }
2054
2055 return $sellOrEatByMandatoryLabel;
2056 }
2057
2065 public function setMultiLangs($user, $notrigger = 0)
2066 {
2067 global $langs;
2068
2069 $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
2070 $current_lang = $langs->getDefaultLang();
2071
2072 foreach ($langs_available as $key => $value) {
2073 if ($key == $current_lang) {
2074 $sql = "SELECT rowid";
2075 $sql .= " FROM ".$this->db->prefix()."product_lang";
2076 $sql .= " WHERE fk_product = ".((int) $this->id);
2077 $sql .= " AND lang = '".$this->db->escape($key)."'";
2078
2079 $result = $this->db->query($sql);
2080
2081 if ($this->db->num_rows($result)) { // if there is already a description line for this language
2082 $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
2083 $sql2 .= " SET ";
2084 $sql2 .= " label='".$this->db->escape($this->label)."',";
2085 $sql2 .= " description='".$this->db->escape($this->description)."'";
2086 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2087 $sql2 .= ", note='".$this->db->escape($this->other)."'";
2088 }
2089 $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
2090 } else {
2091 $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
2092 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2093 $sql2 .= ", note";
2094 }
2095 $sql2 .= ")";
2096 $sql2 .= " VALUES(".((int) $this->id).",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
2097 $sql2 .= " '".$this->db->escape($this->description)."'";
2098 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2099 $sql2 .= ", '".$this->db->escape($this->other)."'";
2100 }
2101 $sql2 .= ")";
2102 }
2103 dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
2104 if (!$this->db->query($sql2)) {
2105 $this->error = $this->db->lasterror();
2106 return -1;
2107 }
2108 } elseif (isset($this->multilangs[$key])) {
2109 if (empty($this->multilangs[$key]["label"])) {
2110 $this->errors[] = $key . ' : ' . $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
2111 return -1;
2112 }
2113
2114 $sql = "SELECT rowid";
2115 $sql .= " FROM ".$this->db->prefix()."product_lang";
2116 $sql .= " WHERE fk_product = ".((int) $this->id);
2117 $sql .= " AND lang = '".$this->db->escape($key)."'";
2118
2119 $result = $this->db->query($sql);
2120
2121 if ($this->db->num_rows($result)) { // if there is already a description line for this language
2122 $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
2123 $sql2 .= " SET ";
2124 $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
2125 $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
2126 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2127 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2128 $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
2129 }
2130 $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
2131 } else {
2132 $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
2133 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2134 $sql2 .= ", note";
2135 }
2136 $sql2 .= ")";
2137 $sql2 .= " VALUES(".((int) $this->id).",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
2138 $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
2139 if (getDolGlobalString('PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION')) {
2140 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2141 $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
2142 }
2143 $sql2 .= ")";
2144 }
2145
2146 // We do not save if main fields are empty
2147 if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
2148 if (!$this->db->query($sql2)) {
2149 $this->error = $this->db->lasterror();
2150 return -1;
2151 }
2152 }
2153 } else {
2154 // language is not current language and we didn't provide a multilang description for this language
2155 }
2156 }
2157
2158 if (empty($notrigger)) {
2159 // Call trigger
2160 $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
2161 if ($result < 0) {
2162 $this->error = $this->db->lasterror();
2163 return -1;
2164 }
2165 // End call triggers
2166 }
2167
2168 return 1;
2169 }
2170
2180 public function delMultiLangs($langtodelete, $user, $notrigger = 0)
2181 {
2182 $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
2183 $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
2184
2185 dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
2186 $result = $this->db->query($sql);
2187 if ($result) {
2188 if (empty($notrigger)) {
2189 // Call trigger
2190 $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
2191 if ($result < 0) {
2192 $this->error = $this->db->lasterror();
2193 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2194 return -1;
2195 }
2196 // End call triggers
2197 }
2198 unset($this->multilangs[$langtodelete]);
2199 return 1;
2200 } else {
2201 $this->error = $this->db->lasterror();
2202 dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
2203 return -1;
2204 }
2205 }
2206
2215 public function setAccountancyCode($type, $value)
2216 {
2217 global $user;
2218
2219 $error = 0;
2220
2221 $this->db->begin();
2222
2223 if ($type == 'buy') {
2224 $field = 'accountancy_code_buy';
2225 } elseif ($type == 'buy_intra') {
2226 $field = 'accountancy_code_buy_intra';
2227 } elseif ($type == 'buy_export') {
2228 $field = 'accountancy_code_buy_export';
2229 } elseif ($type == 'sell') {
2230 $field = 'accountancy_code_sell';
2231 } elseif ($type == 'sell_intra') {
2232 $field = 'accountancy_code_sell_intra';
2233 } elseif ($type == 'sell_export') {
2234 $field = 'accountancy_code_sell_export';
2235 } else {
2236 return -1;
2237 }
2238
2239 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
2240 $sql .= "$field = '".$this->db->escape($value)."'";
2241 $sql .= " WHERE rowid = ".((int) $this->id);
2242
2243 dol_syslog(__METHOD__, LOG_DEBUG);
2244 $resql = $this->db->query($sql);
2245
2246 if ($resql) {
2247 // Call trigger
2248 $result = $this->call_trigger('PRODUCT_MODIFY', $user);
2249 if ($result < 0) {
2250 $error++;
2251 }
2252 // End call triggers
2253
2254 if ($error) {
2255 $this->db->rollback();
2256 return -1;
2257 }
2258
2259 $this->$field = $value;
2260
2261 $this->db->commit();
2262 return 1;
2263 } else {
2264 $this->error = $this->db->lasterror();
2265 $this->db->rollback();
2266 return -1;
2267 }
2268 }
2269
2275 public function getMultiLangs()
2276 {
2277 global $langs;
2278
2279 $current_lang = '';
2280 if ($langs instanceOf Translate) {
2281 $current_lang = $langs->getDefaultLang();
2282 }
2283
2284 $sql = "SELECT lang, label, description, note as other";
2285 $sql .= " FROM ".$this->db->prefix()."product_lang";
2286 $sql .= " WHERE fk_product = ".((int) $this->id);
2287
2288 $result = $this->db->query($sql);
2289 if ($result) {
2290 while ($obj = $this->db->fetch_object($result)) {
2291 //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
2292 if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
2293 $this->label = $obj->label;
2294 $this->description = $obj->description;
2295 $this->other = $obj->other;
2296 }
2297 $this->multilangs[(string) $obj->lang]["label"] = $obj->label;
2298 $this->multilangs[(string) $obj->lang]["description"] = $obj->description;
2299 $this->multilangs[(string) $obj->lang]["other"] = $obj->other;
2300 }
2301 return 1;
2302 } else {
2303 $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
2304 return -1;
2305 }
2306 }
2307
2314 private function getArrayForPriceCompare($level = 0)
2315 {
2316 $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
2317
2318 foreach ($testExit as $field) {
2319 if (!isset($this->$field)) {
2320 return array();
2321 }
2322 $tmparray = $this->$field;
2323 if (!isset($tmparray[$level])) {
2324 return array();
2325 }
2326 }
2327
2328 $lastPrice = array(
2329 'level' => $level ? $level : 1,
2330 'multiprices' => (float) $this->multiprices[$level],
2331 'multiprices_ttc' => (float) $this->multiprices_ttc[$level],
2332 'multiprices_base_type' => $this->multiprices_base_type[$level],
2333 'multiprices_min' => (float) $this->multiprices_min[$level],
2334 'multiprices_min_ttc' => (float) $this->multiprices_min_ttc[$level],
2335 'multiprices_tva_tx' => (float) $this->multiprices_tva_tx[$level],
2336 'multiprices_recuperableonly' => (float) $this->multiprices_recuperableonly[$level],
2337 );
2338
2339 return $lastPrice;
2340 }
2341
2342
2343 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2351 private function _log_price($user, $level = 0)
2352 {
2353 // phpcs:enable
2354 global $conf;
2355
2356 $now = dol_now();
2357
2358 // Clean parameters
2359 if (empty($this->price_by_qty)) {
2360 $this->price_by_qty = 0;
2361 }
2362
2363 // Add new price
2364 $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,";
2365 $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
2366 $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)."'").", ".((float) price2num($this->price)).", ".((float) price2num($this->price_ttc)).",'".$this->db->escape($this->price_base_type)."',".((int) $this->status).", ".((float) price2num($this->tva_tx)).", ".($this->default_vat_code ? ("'".$this->db->escape($this->default_vat_code)."'") : "null").", ".((int) $this->tva_npr).",";
2367 $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');
2368 $sql .= ")";
2369
2370 dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
2371 $resql = $this->db->query($sql);
2372 if (!$resql) {
2373 $this->error = $this->db->lasterror();
2374 dol_print_error($this->db);
2375 return -1;
2376 } else {
2377 return 1;
2378 }
2379 }
2380
2381
2382 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2390 public function log_price_delete($user, $rowid)
2391 {
2392 // phpcs:enable
2393 $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
2394 $sql .= " WHERE fk_product_price = ".((int) $rowid);
2395 $sql .= " AND fk_product_price IN (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = ".((int) $this->id).")";
2396 $resql = $this->db->query($sql);
2397
2398 $sql = "DELETE FROM ".$this->db->prefix()."product_price_extrafields";
2399 $sql .= " WHERE fk_object = ".((int) $rowid);
2400 $resql = $this->db->query($sql);
2401
2402 $sql = "DELETE FROM ".$this->db->prefix()."product_price";
2403 $sql .= " WHERE rowid = ".((int) $rowid);
2404 $sql .= " AND fk_product = ".((int) $this->id);
2405 $resql = $this->db->query($sql);
2406 if ($resql) {
2407 return 1;
2408 } else {
2409 $this->error = $this->db->lasterror();
2410 return -1;
2411 }
2412 }
2413
2422 public function fetchAllPriceLogs($id)
2423 {
2424 dol_syslog(__METHOD__, LOG_DEBUG);
2425
2426 $logs = array();
2427
2428 $sql = "SELECT";
2429 $sql .= " pl.rowid as log_rowid,";
2430 $sql .= " pl.datec,";
2431 $sql .= " pl.price,";
2432 $sql .= " pl.quantity,";
2433 $sql .= " pl.fk_user,";
2434 $sql .= " pl.multicurrency_code,";
2435 $sql .= " pl.multicurrency_price,";
2436 // Supplier info
2437 $sql .= " pp.fk_soc as supplier_id,";
2438 $sql .= " pp.ref_fourn as supplier_ref,";
2439 $sql .= " pp.entity as entity";
2440
2441 $sql .= " FROM " . $this->db->prefix() . "product_fournisseur_price_log as pl";
2442 $sql .= " INNER JOIN " . $this->db->prefix() . "product_fournisseur_price as pp ON pl.fk_product_fournisseur = pp.rowid";
2443
2444 $sql .= " WHERE pp.fk_product = " . ((int) $id);
2445 $sql .= " AND pp.entity IN (" . getEntity('product') . ")";
2446 $sql .= " ORDER BY pl.datec DESC";
2447
2448 $resql = $this->db->query($sql);
2449 if ($resql) {
2450 while ($obj = $this->db->fetch_object($resql)) {
2451 if (is_string($obj->datec)) {
2452 $obj->datec = strtotime($obj->datec);
2453 }
2454 $logs[] = $obj;
2455 }
2456 $this->db->free($resql);
2457 } else {
2458 $this->error = $this->db->lasterror();
2459 }
2460
2461 return $logs;
2462 }
2463
2473 public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
2474 {
2475 global $hookmanager, $action;
2476
2477 // Call hook if any
2478 if (is_object($hookmanager)) {
2479 $parameters = array('thirdparty_seller' => $thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
2480 // Note that $action and $object may have been modified by some hooks
2481 $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
2482 if ($reshook > 0) {
2483 return $hookmanager->resArray;
2484 }
2485 }
2486
2487 // Update if prices fields are defined
2488 $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
2489 $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
2490 if (empty($tva_tx)) {
2491 $tva_npr = 0;
2492 }
2493
2494 $pu_ht = $this->price;
2495 $pu_ttc = $this->price_ttc;
2496 $price_min = $this->price_min;
2497 $price_min_ttc = $this->price_min_ttc;
2498 $price_base_type = (empty($this->price_base_type) ? 'HT' : $this->price_base_type);
2499
2500 // if price by customer / level
2501 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
2502 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
2503
2504 $prodcustprice = new ProductCustomerPrice($this->db);
2505
2506 $filter = array('t.fk_product' => (string) $this->id, 't.fk_soc' => (string) $thirdparty_buyer->id);
2507
2508 // If a price per customer exist
2509 $pricebycustomerexist = false;
2510 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
2511 if ($result) {
2512 if (count($prodcustprice->lines) > 0) {
2513 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
2514 foreach ($prodcustprice->lines as $k => $custprice_line) {
2515 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
2516 $pricebycustomerexist = true;
2517 $pu_ht = price($custprice_line->price);
2518 $price_min = price($custprice_line->price_min);
2519 $price_min_ttc = price($custprice_line->price_min_ttc);
2520 $pu_ttc = price($custprice_line->price_ttc);
2521 $price_base_type = $custprice_line->price_base_type;
2522 $tva_tx = $custprice_line->tva_tx;
2523 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
2524 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
2525 }
2526 $tva_npr = $custprice_line->recuperableonly;
2527 if (empty($tva_tx)) {
2528 $tva_npr = 0;
2529 }
2530 break;
2531 }
2532 }
2533 }
2534 }
2535
2536 if (!$pricebycustomerexist && !empty($thirdparty_buyer->price_level)) {
2537 $pu_ht = isset($this->multiprices[$thirdparty_buyer->price_level]) ? $this->multiprices[$thirdparty_buyer->price_level] : 0;
2538 $pu_ttc = isset($this->multiprices_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_ttc[$thirdparty_buyer->price_level] : 0;
2539 $price_min = isset($this->multiprices_min[$thirdparty_buyer->price_level]) ? $this->multiprices_min[$thirdparty_buyer->price_level] : 0;
2540 $price_min_ttc = isset($this->multiprices_min_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_min_ttc[$thirdparty_buyer->price_level] : 0;
2541 $price_base_type = isset($this->multiprices_base_type[$thirdparty_buyer->price_level]) ? $this->multiprices_base_type[$thirdparty_buyer->price_level] : 'HT';
2542 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
2543 // using this option is a bug. kept for backward compatibility
2544 if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
2545 $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
2546 }
2547 if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
2548 $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
2549 }
2550 if (empty($tva_tx)) {
2551 $tva_npr = 0;
2552 }
2553 }
2554 }
2555 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES') && !empty($thirdparty_buyer->price_level)) { // // If price per segment
2556 $pu_ht = isset($this->multiprices[$thirdparty_buyer->price_level]) ? $this->multiprices[$thirdparty_buyer->price_level] : 0;
2557 $pu_ttc = isset($this->multiprices_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_ttc[$thirdparty_buyer->price_level] : 0;
2558 $price_min = isset($this->multiprices_min[$thirdparty_buyer->price_level]) ? $this->multiprices_min[$thirdparty_buyer->price_level] : 0;
2559 $price_min_ttc = isset($this->multiprices_min_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_min_ttc[$thirdparty_buyer->price_level] : 0;
2560 $price_base_type = isset($this->multiprices_base_type[$thirdparty_buyer->price_level]) ? $this->multiprices_base_type[$thirdparty_buyer->price_level] : 'HT';
2561 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
2562 // using this option is a bug. kept for backward compatibility
2563 if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
2564 $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
2565 }
2566 if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
2567 $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
2568 }
2569 if (empty($tva_tx)) {
2570 $tva_npr = 0;
2571 }
2572 }
2573 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
2574 // If price per customer
2575 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
2576
2577 $prodcustprice = new ProductCustomerPrice($this->db);
2578
2579 $filter = array('t.fk_product' => (string) $this->id, 't.fk_soc' => (string) $thirdparty_buyer->id);
2580
2581 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
2582 if ($result) {
2583 if (count($prodcustprice->lines) > 0) {
2584 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
2585 foreach ($prodcustprice->lines as $k => $custprice_line) {
2586 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
2587 $pu_ht = price($custprice_line->price);
2588 $price_min = price($custprice_line->price_min);
2589 $price_min_ttc = price($custprice_line->price_min_ttc);
2590 $pu_ttc = price($custprice_line->price_ttc);
2591 $price_base_type = $custprice_line->price_base_type;
2592 $tva_tx = $custprice_line->tva_tx;
2593 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
2594 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
2595 }
2596 $tva_npr = $custprice_line->recuperableonly;
2597 if (empty($tva_tx)) {
2598 $tva_npr = 0;
2599 }
2600 break;
2601 }
2602 }
2603 }
2604 }
2605 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
2606 // If price per quantity
2607 if (!empty($this->prices_by_qty[0])) {
2608 // yes, this product has some prices per quantity
2609 // Search price into product_price_by_qty from $this->id
2610 foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
2611 if ($priceforthequantityarray['rowid'] != $pqp) {
2612 continue;
2613 }
2614 // We found the price
2615 if ($priceforthequantityarray['price_base_type'] == 'HT') {
2616 $pu_ht = $priceforthequantityarray['unitprice'];
2617 } else {
2618 $pu_ttc = $priceforthequantityarray['unitprice'];
2619 }
2620 break;
2621 }
2622 }
2623 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
2624 // If price per quantity and customer
2625 if (!empty($thirdparty_buyer->price_level)) {
2626 // The price of the level of the customer is the price to use when no price per quantity is selected
2627 $pu_ht = isset($this->multiprices[$thirdparty_buyer->price_level]) ? $this->multiprices[$thirdparty_buyer->price_level] : 0;
2628 $pu_ttc = isset($this->multiprices_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_ttc[$thirdparty_buyer->price_level] : 0;
2629 $price_min = isset($this->multiprices_min[$thirdparty_buyer->price_level]) ? $this->multiprices_min[$thirdparty_buyer->price_level] : 0;
2630 $price_min_ttc = isset($this->multiprices_min_ttc[$thirdparty_buyer->price_level]) ? $this->multiprices_min_ttc[$thirdparty_buyer->price_level] : 0;
2631 $price_base_type = empty($this->multiprices_base_type[$thirdparty_buyer->price_level]) ? 'HT' : $this->multiprices_base_type[$thirdparty_buyer->price_level];
2632 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
2633 // using this option is a bug. kept for backward compatibility
2634 if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
2635 $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
2636 }
2637 if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
2638 $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
2639 }
2640 if (empty($tva_tx)) {
2641 $tva_npr = 0;
2642 }
2643 }
2644 }
2645 if (!empty($thirdparty_buyer->price_level) && !empty($this->prices_by_qty[$thirdparty_buyer->price_level])) {
2646 // yes, this product has some prices per quantity
2647 // Search price into product_price_by_qty from $this->id
2648 foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
2649 if ($priceforthequantityarray['rowid'] != $pqp) {
2650 continue;
2651 }
2652 // We found the price
2653 if ($priceforthequantityarray['price_base_type'] == 'HT') {
2654 $pu_ht = $priceforthequantityarray['unitprice'];
2655 } else {
2656 $pu_ttc = $priceforthequantityarray['unitprice'];
2657 }
2658 break;
2659 }
2660 }
2661 }
2662
2663 $localtax1 = get_localtax((string) $tva_tx, 1, $thirdparty_buyer, $thirdparty_seller, $tva_npr);
2664 $localtax2 = get_localtax((string) $tva_tx, 2, $thirdparty_buyer, $thirdparty_seller, $tva_npr);
2665
2666 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);
2667 }
2668
2669 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2683 public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
2684 {
2685 // phpcs:enable
2686 global $action, $hookmanager;
2687
2688 // Call hook if any
2689 if (is_object($hookmanager)) {
2690 $parameters = array(
2691 'prodfournprice' => $prodfournprice,
2692 'qty' => $qty,
2693 'product_id' => $product_id,
2694 'fourn_ref' => $fourn_ref,
2695 'fk_soc' => $fk_soc,
2696 );
2697 // Note that $action and $object may have been modified by some hooks
2698 $reshook = $hookmanager->executeHooks('getBuyPrice', $parameters, $this, $action);
2699 if ($reshook > 0) {
2700 return $hookmanager->resArray;
2701 }
2702 }
2703
2704 $result = 0;
2705
2706 // 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)
2707 $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
2708 $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,";
2709 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
2710 $sql .= " pfp.packaging";
2711 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
2712 $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
2713 if ($qty > 0) {
2714 $sql .= " AND pfp.quantity <= ".((float) $qty);
2715 }
2716 $sql .= " ORDER BY pfp.quantity DESC";
2717
2718 dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
2719 $resql = $this->db->query($sql);
2720 if ($resql) {
2721 $obj = $this->db->fetch_object($resql);
2722 if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
2723 if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
2724 $prod_supplier = new ProductFournisseur($this->db);
2725 $prod_supplier->product_fourn_price_id = $obj->rowid;
2726 $prod_supplier->id = $obj->fk_product;
2727 $prod_supplier->fourn_qty = $obj->quantity;
2728 $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2729 $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2730
2731 include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2732 $priceparser = new PriceParser($this->db);
2733 $price_result = $priceparser->parseProductSupplier($prod_supplier);
2734 if ($price_result >= 0) {
2735 $obj->price = $price_result;
2736 }
2737 }
2738 $this->product_fourn_price_id = $obj->rowid;
2739 $this->buyprice = $obj->price; // deprecated
2740 $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
2741 $this->fourn_price_base_type = 'HT'; // Price base type
2742 $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2743 $this->ref_fourn = $obj->ref_supplier; // deprecated
2744 $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2745 $this->desc_supplier = $obj->desc_supplier; // desc supplier
2746 $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2747 $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2748 $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
2749 $this->fourn_multicurrency_price = $obj->multicurrency_price;
2750 $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2751 $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2752 $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2753 $this->fourn_multicurrency_code = $obj->multicurrency_code;
2754 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2755 $this->packaging = (float) $obj->packaging;
2756 }
2757 // Expose the supplier minimum purchase quantity so callers can enforce qty_min
2758 // on top of packaging-multiple rounding (#38783). pfp.quantity is the lowest
2759 // qty for which this price line is valid; for "below-min" callers this is the
2760 // floor they must round up to.
2761 $this->fourn_qty = $obj->quantity;
2762 $result = $obj->fk_product;
2763 return $result;
2764 } else { // If not found
2765 // 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.
2766 $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
2767 $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,";
2768 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
2769 $sql .= " pfp.packaging";
2770 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
2771 $sql .= " WHERE 1 = 1";
2772 if ($product_id > 0) {
2773 $sql .= " AND pfp.fk_product = ".((int) $product_id);
2774 }
2775 if ($fourn_ref != 'none') {
2776 $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
2777 }
2778 if ($fk_soc > 0) {
2779 $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
2780 }
2781 if ($qty > 0) {
2782 $sql .= " AND pfp.quantity <= ".((float) $qty);
2783 }
2784 $sql .= " ORDER BY pfp.quantity DESC";
2785 $sql .= " LIMIT 1";
2786
2787 dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
2788 $resql = $this->db->query($sql);
2789 if ($resql) {
2790 $obj = $this->db->fetch_object($resql);
2791 if ($obj && $obj->quantity > 0) { // If found
2792 if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
2793 $prod_supplier = new ProductFournisseur($this->db);
2794 $prod_supplier->product_fourn_price_id = $obj->rowid;
2795 $prod_supplier->id = $obj->fk_product;
2796 $prod_supplier->fourn_qty = $obj->quantity;
2797 $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2798 $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2799
2800 include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2801 $priceparser = new PriceParser($this->db);
2802 $price_result = $priceparser->parseProductSupplier($prod_supplier);
2803 if ($price_result >= 0) {
2804 $obj->price = $price_result;
2805 }
2806 }
2807 $this->product_fourn_price_id = $obj->rowid;
2808 $this->buyprice = $obj->price; // deprecated
2809 $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
2810 $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
2811 $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
2812 $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2813 $this->ref_fourn = $obj->ref_supplier; // deprecated
2814 $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2815 $this->desc_supplier = $obj->desc_supplier; // desc supplier
2816 $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2817 $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2818 $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
2819 $this->fourn_multicurrency_price = $obj->multicurrency_price;
2820 $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2821 $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2822 $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2823 $this->fourn_multicurrency_code = $obj->multicurrency_code;
2824 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
2825 $this->packaging = (float) $obj->packaging;
2826 }
2827 // Expose pfp.quantity so callers can enforce qty_min on top of packaging
2828 // rounding (#38783).
2829 $this->fourn_qty = $obj->quantity;
2830 $result = $obj->fk_product;
2831 return $result;
2832 } else {
2833 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.
2834 }
2835 } else {
2836 $this->error = $this->db->lasterror();
2837 return -3;
2838 }
2839 }
2840 } else {
2841 $this->error = $this->db->lasterror();
2842 return -2;
2843 }
2844 }
2845
2846
2865 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)
2866 {
2867 $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
2868
2869 $id = $this->id;
2870
2871 dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
2872
2873 // Clean parameters
2874 if (empty($this->tva_tx)) {
2875 $this->tva_tx = 0.0;
2876 }
2877 if (empty($newnpr)) {
2878 $newnpr = 0.0;
2879 }
2880 if (empty($newminprice)) {
2881 $newminprice = 0.0;
2882 }
2883
2884 // Check parameters
2885 if ($newvat === null || $newvat == '') { // Maintain '' for backwards compatibility
2886 $newvat = (float) $this->tva_tx;
2887 }
2888
2889 $localtaxtype1 = '';
2890 $localtaxtype2 = '';
2891
2892 // If multiprices are enabled, then we check if the current product is subject to price autogeneration
2893 // Price will be modified ONLY when the first one is the one that is being modified
2894 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
2895 return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
2896 }
2897
2898 if (!empty($newminprice) && ($newminprice > $newprice)) {
2899 $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
2900 return -1;
2901 }
2902
2903 if ($newprice === 0 || $newprice !== '') {
2904 if ($newpricebase == 'TTC') {
2905 $price_ttc = (float) price2num($newprice, 'MU');
2906 $price = (float) price2num($newprice) / (1 + ((float) $newvat / 100));
2907 $price = (float) price2num($price, 'MU');
2908
2909 if ((string) $newminprice != '0') {
2910 $price_min_ttc = (float) price2num($newminprice, 'MU');
2911 $price_min = (float) price2num($newminprice) / (1 + ($newvat / 100));
2912 $price_min = (float) price2num($price_min, 'MU');
2913 } else {
2914 $price_min = 0.0;
2915 $price_min_ttc = 0.0;
2916 }
2917 } else {
2918 $price = (float) price2num($newprice, 'MU');
2919 $price_ttc = ($newnpr != 1) ? (float) price2num($newprice) * (1 + ($newvat / 100)) : $price;
2920 $price_ttc = (float) price2num($price_ttc, 'MU');
2921
2922 if ((string) $newminprice != '0') {
2923 $price_min = (float) price2num($newminprice, 'MU');
2924 $price_min_ttc = (float) price2num($newminprice) * (1 + ($newvat / 100));
2925 $price_min_ttc = (float) price2num($price_min_ttc, 'MU');
2926 //print 'X'.$newminprice.'-'.$price_min;
2927 } else {
2928 $price_min = 0.0;
2929 $price_min_ttc = 0.0;
2930 }
2931 }
2932 //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
2933 if (count($localtaxes_array) > 0) {
2934 $localtaxtype1 = $localtaxes_array['0'];
2935 $localtax1 = $localtaxes_array['1'];
2936 $localtaxtype2 = $localtaxes_array['2'];
2937 $localtax2 = $localtaxes_array['3'];
2938 } else {
2939 // if array empty, we try to use the vat code
2940 if (!empty($newdefaultvatcode)) {
2941 global $mysoc;
2942 // Get record from code
2943 $sql = "SELECT t.rowid, t.code, t.recuperableonly as tva_npr, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
2944 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
2945 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($mysoc->country_code)."'";
2946 $sql .= " AND t.taux = ".((float) $newdefaultvatcode)." AND t.active = 1";
2947 $sql .= " AND t.code = '".$this->db->escape($newdefaultvatcode)."'";
2948 $resql = $this->db->query($sql);
2949 if ($resql) {
2950 $obj = $this->db->fetch_object($resql);
2951 if ($obj) {
2952 $npr = $obj->tva_npr;
2953 $localtax1 = $obj->localtax1;
2954 $localtax2 = $obj->localtax2;
2955 $localtaxtype1 = $obj->localtax1_type;
2956 $localtaxtype2 = $obj->localtax2_type;
2957 }
2958 }
2959 } else {
2960 // old method. deprecated because we can't retrieve type
2961 $localtaxtype1 = '0';
2962 $localtax1 = get_localtax($newvat, 1);
2963 $localtaxtype2 = '0';
2964 $localtax2 = get_localtax($newvat, 2);
2965 }
2966 }
2967 if (empty($localtax1)) {
2968 $localtax1 = 0; // If = '' then = 0
2969 }
2970 if (empty($localtax2)) {
2971 $localtax2 = 0; // If = '' then = 0
2972 }
2973
2974 $this->db->begin();
2975
2976 // The price columns of the table product hold the default price of the product, that is the price of the level 1
2977 // when multiprices are enabled (level is 0 when they are not). So they must not be overwritten by another level.
2978 // The vat columns are however shared by all levels, so they are always updated.
2979 $updatedefaultprice = (empty($level) || $level == 1);
2980
2981 // Don't put quotes here on decimal numbers.
2982 // This causes storage with base rounding instead of exact values.
2983 $sql = "UPDATE ".$this->db->prefix()."product SET";
2984 if ($updatedefaultprice) {
2985 $sql .= " price_base_type = '".$this->db->escape($newpricebase)."',";
2986 $sql .= " price = ".(float) $price.",";
2987 $sql .= " price_ttc = ".(float) $price_ttc.",";
2988 $sql .= " price_min = ".(float) $price_min.",";
2989 $sql .= " price_min_ttc = ".(float) $price_min_ttc.",";
2990 $sql .= " price_label = ".(!empty($price_label) ? "'".$this->db->escape($price_label)."'" : "null").",";
2991 }
2992 $sql .= " localtax1_tx = ".($localtax1 >= 0 ? (float) $localtax1 : 'NULL').",";
2993 $sql .= " localtax2_tx = ".($localtax2 >= 0 ? (float) $localtax2 : 'NULL').",";
2994 $sql .= " localtax1_type = ".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
2995 $sql .= " localtax2_type = ".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
2996 $sql .= " default_vat_code = ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
2997 $sql .= " tva_tx = ".(float) price2num($newvat).",";
2998 $sql .= " recuperableonly = '".$this->db->escape((string) $newnpr)."'";
2999 $sql .= " WHERE rowid = ".((int) $id);
3000
3001 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3002 $resql = $this->db->query($sql);
3003 if ($resql) {
3004 $this->multiprices[$level] = $price;
3005 $this->multiprices_ttc[$level] = $price_ttc;
3006 $this->multiprices_min[$level] = $price_min;
3007 $this->multiprices_min_ttc[$level] = $price_min_ttc;
3008 $this->multiprices_base_type[$level] = $newpricebase;
3009 $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
3010 $this->multiprices_tva_tx[$level] = $newvat;
3011 $this->multiprices_recuperableonly[$level] = $newnpr;
3012
3013 // Save the default price of the product to restore it after the log if we are updating another level
3014 // (_log_price() reads the price into the properties of the object to save the price of the level).
3015 $savdefaultprice = array($this->price, $this->price_label, $this->price_ttc, $this->price_min, $this->price_min_ttc, $this->price_base_type);
3016
3017 $this->price = $price;
3018 $this->price_label = $price_label;
3019 $this->price_ttc = $price_ttc;
3020 $this->price_min = $price_min;
3021 $this->price_min_ttc = $price_min_ttc;
3022 $this->price_base_type = $newpricebase;
3023 $this->default_vat_code = $newdefaultvatcode;
3024 $this->tva_tx = $newvat;
3025 $this->tva_npr = $newnpr;
3026
3027 //Local taxes
3028 $this->localtax1_tx = $localtax1;
3029 $this->localtax2_tx = $localtax2;
3030 $this->localtax1_type = $localtaxtype1;
3031 $this->localtax2_type = $localtaxtype2;
3032
3033 // Price by quantity
3034 $this->price_by_qty = $newpbq;
3035
3036 // check if price have really change before log
3037 $newPriceData = $this->getArrayForPriceCompare($level);
3038 if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || (!getDolGlobalString('PRODUIT_MULTIPRICES') && !getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
3039 $this->_log_price($user, $level); // Save price for level into table product_price
3040 }
3041
3042 if (!$updatedefaultprice) {
3043 // The price of the level is now saved, so we can restore the default price of the product
3044 list($this->price, $this->price_label, $this->price_ttc, $this->price_min, $this->price_min_ttc, $this->price_base_type) = $savdefaultprice;
3045 }
3046
3047 $this->level = $level; // Store level of price edited for trigger
3048
3049 // Call trigger
3050 if (!$notrigger) {
3051 $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
3052 if ($result < 0) {
3053 $this->db->rollback();
3054 return -1;
3055 }
3056 }
3057 // End call triggers
3058
3059 $this->db->commit();
3060 } else {
3061 $this->db->rollback();
3062 $this->error = $this->db->lasterror();
3063 return -1;
3064 }
3065 }
3066
3067 return 1;
3068 }
3069
3077 public function setPriceExpression($expression_id)
3078 {
3079 global $user;
3080
3081 $this->fk_price_expression = $expression_id;
3082
3083 return $this->update($this->id, $user);
3084 }
3085
3098 public function fetch($id = 0, $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
3099 {
3100 include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3101
3102 global $conf;
3103
3104 dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
3105
3106 // Check parameters
3107 if (!$id && !$ref && !$ref_ext && !$barcode) {
3108 $this->error = 'ErrorWrongParameters';
3109 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
3110 return -1;
3111 }
3112
3113 $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,";
3114 $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,";
3115 $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,";
3116 $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.last_main_doc,";
3117 $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,";
3118 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
3119 $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,";
3120 } else {
3121 $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,";
3122 }
3123
3124 // For MultiCompany
3125 // PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
3126 $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
3127 $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.
3128 $visibleWarehousesEntities = $conf->entity;
3129 if (getDolGlobalString('MULTICOMPANY_PRODUCT_SHARING_ENABLED')) {
3130 if (getDolGlobalString('MULTICOMPANY_PMP_PER_ENTITY_ENABLED')) {
3131 $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
3132 if ($this->db->num_rows($checkPMPPerEntity) > 0) {
3133 $separatedEntityPMP = true;
3134 }
3135 }
3136 global $mc;
3137 $separatedStock = true;
3138 if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
3139 $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
3140 }
3141 }
3142 if ($separatedEntityPMP) {
3143 $sql .= " ppe.pmp,";
3144 } else {
3145 $sql .= " p.pmp,";
3146 }
3147 $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,";
3148 $sql .= " p.fk_price_expression, p.price_autogen, p.stockable_product, p.model_pdf,";
3149 $sql .= " p.price_label,";
3150 if ($separatedStock) {
3151 $sql .= " SUM(sp.reel) as stock";
3152 } else {
3153 $sql .= " p.stock";
3154 }
3155 $sql .= " FROM ".$this->db->prefix()."product as p";
3156 $sql .= " LEFT JOIN ".$this->db->prefix()."product_extrafields as pef ON pef.fk_object=p.rowid";
3157 if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') || $separatedEntityPMP) {
3158 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
3159 }
3160 if ($separatedStock) {
3161 $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)."))";
3162 }
3163
3164 if ($id) {
3165 $sql .= " WHERE p.rowid = ".((int) $id);
3166 } else {
3167 $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
3168 if ($ref) {
3169 $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
3170 } elseif ($ref_ext) {
3171 $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
3172 } elseif ($barcode) {
3173 $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
3174 }
3175 }
3176 if ($separatedStock) {
3177 $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,";
3178 $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,";
3179 $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,";
3180 $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
3181 $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,";
3182 if (!getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
3183 $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,";
3184 } else {
3185 $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,";
3186 }
3187 if ($separatedEntityPMP) {
3188 $sql .= " ppe.pmp,";
3189 } else {
3190 $sql .= " p.pmp,";
3191 }
3192 $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,";
3193 $sql .= " p.fk_price_expression, p.price_autogen, p.stockable_product, p.model_pdf,";
3194 $sql .= " p.price_label";
3195 // can't be false TODO fix
3196 // if (!$separatedStock) {
3197 // $sql .= ", p.stock";
3198 // }
3199 }
3200
3201 $resql = $this->db->query($sql);
3202 if ($resql) {
3203 unset($this->oldcopy);
3204
3205 if ($this->db->num_rows($resql) > 0) {
3206 $obj = $this->db->fetch_object($resql);
3207
3208 $this->id = $obj->rowid;
3209 $this->ref = $obj->ref;
3210 $this->ref_ext = $obj->ref_ext;
3211 $this->label = $obj->label;
3212 $this->description = $obj->description;
3213 $this->url = $obj->url;
3214 $this->note_public = $obj->note_public;
3215 $this->note_private = $obj->note_private;
3216 $this->note = $obj->note_private; // deprecated
3217
3218 $this->type = $obj->fk_product_type;
3219 $this->price_label = $obj->price_label;
3220 $this->status = $obj->tosell;
3221 $this->status_buy = $obj->tobuy;
3222 $this->status_batch = $obj->tobatch;
3223 $this->sell_or_eat_by_mandatory = $obj->sell_or_eat_by_mandatory;
3224 $this->batch_mask = $obj->batch_mask;
3225
3226 $this->customcode = $obj->customcode;
3227 $this->country_id = $obj->fk_country;
3228 $this->country_code = getCountry($this->country_id, '2', $this->db);
3229 $this->state_id = $obj->fk_state;
3230 $this->lifetime = $obj->lifetime;
3231 $this->qc_frequency = $obj->qc_frequency;
3232 $this->price = $obj->price;
3233 $this->price_ttc = $obj->price_ttc;
3234 $this->price_min = $obj->price_min;
3235 $this->price_min_ttc = $obj->price_min_ttc;
3236 $this->price_base_type = (empty($obj->price_base_type) ? 'HT' : $obj->price_base_type);
3237 $this->cost_price = isset($obj->cost_price) ? (float) $obj->cost_price : null;
3238 $this->default_vat_code = $obj->default_vat_code;
3239 $this->tva_tx = $obj->tva_tx;
3241 $this->tva_npr = $obj->tva_npr;
3243 $this->localtax1_tx = $obj->localtax1_tx;
3244 $this->localtax2_tx = $obj->localtax2_tx;
3245 $this->localtax1_type = $obj->localtax1_type;
3246 $this->localtax2_type = $obj->localtax2_type;
3247
3248 $this->finished = $obj->finished;
3249 $this->fk_default_bom = $obj->fk_default_bom;
3250
3251 $this->duration = $obj->duration;
3252 $matches = [];
3253 preg_match('/([\d.]+)(\w+)/', $obj->duration, $matches);
3254 $this->duration_value = !empty($matches[1]) ? (float) $matches[1] : 0;
3255 $this->duration_unit = !empty($matches[2]) ? (string) $matches[2] : null;
3256 $this->canvas = $obj->canvas;
3257 $this->net_measure = $obj->net_measure;
3258 $this->net_measure_units = $obj->net_measure_units;
3259 $this->weight = $obj->weight;
3260 $this->weight_units = (is_null($obj->weight_units) ? 0 : $obj->weight_units);
3261 $this->length = $obj->length;
3262 $this->length_units = (is_null($obj->length_units) ? 0 : $obj->length_units);
3263 $this->width = $obj->width;
3264 $this->width_units = (is_null($obj->width_units) ? 0 : $obj->width_units);
3265 $this->height = $obj->height;
3266 $this->height_units = (is_null($obj->height_units) ? 0 : $obj->height_units);
3267
3268 $this->surface = $obj->surface;
3269 $this->surface_units = (is_null($obj->surface_units) ? 0 : $obj->surface_units);
3270 $this->volume = $obj->volume;
3271 $this->volume_units = (is_null($obj->volume_units) ? 0 : $obj->volume_units);
3272 $this->barcode = $obj->barcode;
3273 $this->barcode_type = $obj->fk_barcode_type;
3274
3275 $this->accountancy_code_buy = $obj->accountancy_code_buy;
3276 $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
3277 $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
3278 $this->accountancy_code_sell = $obj->accountancy_code_sell;
3279 $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
3280 $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
3281
3282 $this->fk_default_warehouse = $obj->fk_default_warehouse;
3283 $this->fk_default_workstation = $obj->fk_default_workstation;
3284 $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
3285 $this->desiredstock = $obj->desiredstock;
3286 $this->stock_reel = $obj->stock;
3287 $this->stockable_product = $obj->stockable_product;
3288 $this->pmp = $obj->pmp;
3289
3290 $this->date_creation = $this->db->jdate($obj->datec);
3291 $this->date_modification = $this->db->jdate($obj->tms);
3292
3293 $this->import_key = $obj->import_key;
3294 $this->entity = $obj->entity;
3295
3296 $this->ref_ext = $obj->ref_ext;
3297 $this->fk_price_expression = $obj->fk_price_expression;
3298 $this->fk_unit = $obj->fk_unit;
3299 $this->price_autogen = $obj->price_autogen;
3300 $this->model_pdf = $obj->model_pdf;
3301 $this->last_main_doc = $obj->last_main_doc;
3302
3303 $this->mandatory_period = $obj->mandatory_period;
3304
3305 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
3306 $this->packaging = (float) $obj->packaging;
3307 }
3308
3309 $this->db->free($resql);
3310
3311 // fetch optionals attributes and labels
3312 $this->fetch_optionals();
3313
3314 // Multilangs
3315 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($ignore_lang_load)) {
3316 $this->getMultiLangs();
3317 }
3318
3319 // Load multiprices array
3320 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($ignore_price_load)) { // prices per segment
3321 $produit_multiprices_limit = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
3322 for ($i = 1; $i <= $produit_multiprices_limit; $i++) {
3323 $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
3324 $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
3325 $sql .= " ,price_label";
3326 $sql .= " FROM ".$this->db->prefix()."product_price";
3327 $sql .= " WHERE entity IN (".getEntity('productprice').")";
3328 $sql .= " AND price_level=".((int) $i);
3329 $sql .= " AND fk_product = ".((int) $this->id);
3330 $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
3331 $sql .= " LIMIT 1"; // Only the first one
3332 $resql = $this->db->query($sql);
3333 if ($resql) {
3334 $result = $this->db->fetch_array($resql);
3335
3336 $this->multiprices[$i] = $result ? $result["price"] : null;
3337 $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
3338 $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
3339 $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
3340 $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
3341 // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
3342 $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].(!empty($result['default_vat_code']) ? ' ('.$result['default_vat_code'].')' : '') : null;
3343 $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
3344
3345 // Price by quantity
3346 /*
3347 $this->prices_by_qty[$i]=$result["price_by_qty"];
3348 $this->prices_by_qty_id[$i]=$result["rowid"];
3349 // Get the pricelist according to the qty if flag is set
3350 if ($this->prices_by_qty[$i] == 1)
3351 {
3352 $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
3353 $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
3354 $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
3355 $sql.= " ORDER BY quantity ASC";
3356
3357 $resql = $this->db->query($sql);
3358 if ($resql)
3359 {
3360 $resultat=array();
3361 $ii=0;
3362 while ($result= $this->db->fetch_array($resql)) {
3363 $resultat[$ii]=array();
3364 $resultat[$ii]["rowid"]=$result["rowid"];
3365 $resultat[$ii]["price"]= $result["price"];
3366 $resultat[$ii]["unitprice"]= $result["unitprice"];
3367 $resultat[$ii]["quantity"]= $result["quantity"];
3368 $resultat[$ii]["remise_percent"]= $result["remise_percent"];
3369 $resultat[$ii]["remise"]= $result["remise"]; // deprecated
3370 $resultat[$ii]["price_base_type"]= $result["price_base_type"];
3371 $ii++;
3372 }
3373 $this->prices_by_qty_list[$i]=$resultat;
3374 }
3375 else
3376 {
3377 dol_print_error($this->db);
3378 return -1;
3379 }
3380 }*/
3381 } else {
3382 $this->error = $this->db->lasterror;
3383 return -1;
3384 }
3385 }
3386 } elseif ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($ignore_price_load)) { // prices per customers
3387 // Nothing loaded by default. List may be very long.
3388 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') && empty($ignore_price_load)) { // prices per quantity
3389 $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
3390 $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
3391 $sql .= " FROM ".$this->db->prefix()."product_price";
3392 $sql .= " WHERE fk_product = ".((int) $this->id);
3393 $sql .= " ORDER BY date_price DESC, rowid DESC";
3394 $sql .= " LIMIT 1";
3395
3396 $resql = $this->db->query($sql);
3397 if ($resql) {
3398 $result = $this->db->fetch_array($resql);
3399
3400 if ($result) {
3401 // Price by quantity
3402 $this->prices_by_qty[0] = $result["price_by_qty"];
3403 $this->prices_by_qty_id[0] = $result["rowid"];
3404 // Get the pricelist according to the qty if flag is set
3405 if ($this->prices_by_qty[0] == 1) {
3406 $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
3407 $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
3408 $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
3409 $sql .= " ORDER BY quantity ASC";
3410
3411 $resql = $this->db->query($sql);
3412 if ($resql) {
3413 $resultat = array();
3414 $ii = 0;
3415 while ($result = $this->db->fetch_array($resql)) {
3416 $resultat[$ii] = array();
3417 $resultat[$ii]["rowid"] = $result["rowid"];
3418 $resultat[$ii]["price"] = $result["price"];
3419 $resultat[$ii]["unitprice"] = $result["unitprice"];
3420 $resultat[$ii]["quantity"] = $result["quantity"];
3421 $resultat[$ii]["remise_percent"] = $result["remise_percent"];
3422 //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
3423 $resultat[$ii]["price_base_type"] = $result["price_base_type"];
3424 $ii++;
3425 }
3426 $this->prices_by_qty_list[0] = $resultat;
3427 } else {
3428 $this->error = $this->db->lasterror;
3429 return -1;
3430 }
3431 }
3432 }
3433 } else {
3434 $this->error = $this->db->lasterror;
3435 return -1;
3436 }
3437 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') && empty($ignore_price_load)) { // prices per customer and quantity
3438 $produit_multiprices_limit = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
3439 for ($i = 1; $i <= $produit_multiprices_limit; $i++) {
3440 $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
3441 $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
3442 $sql .= " FROM ".$this->db->prefix()."product_price";
3443 $sql .= " WHERE entity IN (".getEntity('productprice').")";
3444 $sql .= " AND price_level=".((int) $i);
3445 $sql .= " AND fk_product = ".((int) $this->id);
3446 $sql .= " ORDER BY date_price DESC, rowid DESC";
3447 $sql .= " LIMIT 1";
3448 $resql = $this->db->query($sql);
3449 if (!$resql) {
3450 $this->error = $this->db->lasterror;
3451 return -1;
3452 } else {
3453 $result = $this->db->fetch_array($resql);
3454 $this->multiprices[$i] = (!empty($result["price"]) ? $result["price"] : 0);
3455 $this->multiprices_ttc[$i] = (!empty($result["price_ttc"]) ? $result["price_ttc"] : 0);
3456 $this->multiprices_min[$i] = (!empty($result["price_min"]) ? $result["price_min"] : 0);
3457 $this->multiprices_min_ttc[$i] = (!empty($result["price_min_ttc"]) ? $result["price_min_ttc"] : 0);
3458 $this->multiprices_base_type[$i] = (!empty($result["price_base_type"]) ? $result["price_base_type"] : '');
3459 // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
3460 $this->multiprices_tva_tx[$i] = (!empty($result["tva_tx"]) ? $result["tva_tx"] : 0); // TODO Add ' ('.$result['default_vat_code'].')'
3461 $this->multiprices_recuperableonly[$i] = (!empty($result["recuperableonly"]) ? $result["recuperableonly"] : 0);
3462
3463 // Price by quantity
3464 $this->prices_by_qty[$i] = (!empty($result["price_by_qty"]) ? $result["price_by_qty"] : 0);
3465 $this->prices_by_qty_id[$i] = (!empty($result["rowid"]) ? $result["rowid"] : 0);
3466 // Get the pricelist according to the qty if flag is set
3467 if ($this->prices_by_qty[$i] == 1) {
3468 $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
3469 $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
3470 $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
3471 $sql .= " ORDER BY quantity ASC";
3472
3473 $resql = $this->db->query($sql);
3474 if ($resql) {
3475 $resultat = array();
3476 $ii = 0;
3477 while ($result = $this->db->fetch_array($resql)) {
3478 $resultat[$ii] = array();
3479 $resultat[$ii]["rowid"] = $result["rowid"];
3480 $resultat[$ii]["price"] = $result["price"];
3481 $resultat[$ii]["unitprice"] = $result["unitprice"];
3482 $resultat[$ii]["quantity"] = $result["quantity"];
3483 $resultat[$ii]["remise_percent"] = $result["remise_percent"];
3484 $resultat[$ii]["remise"] = $result["remise"]; // deprecated
3485 $resultat[$ii]["price_base_type"] = $result["price_base_type"];
3486 $ii++;
3487 }
3488 $this->prices_by_qty_list[$i] = $resultat;
3489 } else {
3490 $this->error = $this->db->lasterror;
3491 return -1;
3492 }
3493 }
3494 }
3495 }
3496 }
3497
3498 if (isModEnabled('dynamicprices') && !empty($this->fk_price_expression) && empty($ignore_expression)) {
3499 include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
3500 $priceparser = new PriceParser($this->db);
3501 $price_result = $priceparser->parseProduct($this);
3502 if ($price_result >= 0) {
3503 $this->price = $price_result;
3504 // Calculate the VAT
3505 $this->price_ttc = (float) price2num($this->price) * (1 + ($this->tva_tx / 100));
3506 $this->price_ttc = (float) price2num($this->price_ttc, 'MU');
3507 }
3508 }
3509
3510 // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
3511 // Instead we just init the stock_warehouse array
3512 $this->stock_warehouse = array();
3513
3514 return 1;
3515 } else {
3516 return 0;
3517 }
3518 } else {
3519 $this->error = $this->db->lasterror();
3520 return -1;
3521 }
3522 }
3523
3524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3531 public function load_stats_mo($socid = 0)
3532 {
3533 // phpcs:enable
3534 global $user, $hookmanager, $action;
3535
3536 $error = 0;
3537
3538 foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
3539 $this->stats_mo['customers_'.$role] = 0;
3540 $this->stats_mo['nb_'.$role] = 0;
3541 $this->stats_mo['qty_'.$role] = 0;
3542
3543 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3544 $sql .= " SUM(mp.qty) as qty";
3545 $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
3546 $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
3547 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
3548 $sql .= " INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $user->id);
3549 }
3550 $sql .= " WHERE ";
3551 $sql .= " c.entity IN (".getEntity('mo').")";
3552
3553 $sql .= " AND mp.fk_product = ".((int) $this->id);
3554 $sql .= " AND mp.role ='".$this->db->escape($role)."'";
3555 if ($socid > 0) {
3556 $sql .= " AND c.fk_soc = ".((int) $socid);
3557 }
3558
3559 $result = $this->db->query($sql);
3560 if ($result) {
3561 $obj = $this->db->fetch_object($result);
3562 $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
3563 $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
3564 $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
3565 } else {
3566 $this->error = $this->db->error();
3567 $error++;
3568 }
3569 }
3570
3571 if (!empty($error)) {
3572 return -1;
3573 }
3574
3575 $parameters = array('socid' => $socid);
3576 $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
3577 if ($reshook > 0) {
3578 $this->stats_mo = $hookmanager->resArray['stats_mo'];
3579 }
3580
3581 return 1;
3582 }
3583
3584 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3591 public function load_stats_bom($socid = 0)
3592 {
3593 // phpcs:enable
3594 global $hookmanager, $action;
3595
3596 $error = 0;
3597
3598 $this->stats_bom['nb_toproduce'] = 0;
3599 $this->stats_bom['nb_toconsume'] = 0;
3600 $this->stats_bom['qty_toproduce'] = 0;
3601 $this->stats_bom['qty_toconsume'] = 0;
3602
3603 $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
3604 $sql .= " SUM(b.qty) as qty_toproduce";
3605 $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
3606 $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom = b.rowid";
3607 $sql .= " WHERE ";
3608 $sql .= " b.entity IN (".getEntity('bom').")";
3609 $sql .= " AND b.fk_product =".((int) $this->id);
3610 $sql .= " GROUP BY b.rowid";
3611
3612 $result = $this->db->query($sql);
3613 if ($result) {
3614 $obj = $this->db->fetch_object($result);
3615 $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
3616 $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
3617 } else {
3618 $this->error = $this->db->error();
3619 $error++;
3620 }
3621
3622 $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
3623 $sql .= " SUM(bl.qty) as qty_toconsume";
3624 $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
3625 $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
3626 $sql .= " WHERE ";
3627 $sql .= " b.entity IN (".getEntity('bom').")";
3628 $sql .= " AND bl.fk_product =".((int) $this->id);
3629
3630 $result = $this->db->query($sql);
3631 if ($result) {
3632 $obj = $this->db->fetch_object($result);
3633 $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
3634 $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
3635 } else {
3636 $this->error = $this->db->error();
3637 $error++;
3638 }
3639
3640 if (!empty($error)) {
3641 return -1;
3642 }
3643
3644 $parameters = array('socid' => $socid);
3645 $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
3646 if ($reshook > 0) {
3647 $this->stats_bom = $hookmanager->resArray['stats_bom'];
3648 }
3649
3650 return 1;
3651 }
3652
3653 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3660 public function load_stats_propale($socid = 0)
3661 {
3662 // phpcs:enable
3663 global $user, $hookmanager, $action;
3664
3665 $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
3666 $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
3667 $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
3668 $sql .= ", ".$this->db->prefix()."propal as p";
3669 $sql .= ", ".$this->db->prefix()."societe as s";
3670 $sql .= " WHERE p.rowid = pd.fk_propal";
3671 $sql .= " AND p.fk_soc = s.rowid";
3672 $sql .= " AND p.entity IN (".getEntity('propal').")";
3673 $sql .= " AND pd.fk_product = ".((int) $this->id);
3674 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
3675 $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).")";
3676 }
3677 //$sql.= " AND pr.fk_statut != 0";
3678 if ($socid > 0) {
3679 $sql .= " AND p.fk_soc = ".((int) $socid);
3680 }
3681 // Add where from hooks
3682 $parameters = array('socid' => $socid, 'type_element' => 'propal');
3683 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3684 $sql .= $hookmanager->resPrint;
3685 $result = $this->db->query($sql);
3686 if ($result) {
3687 $obj = $this->db->fetch_object($result);
3688 $this->stats_propale['customers'] = (int) $obj->nb_customers;
3689 $this->stats_propale['nb'] = (int) $obj->nb;
3690 $this->stats_propale['rows'] = (int) $obj->nb_rows;
3691 $this->stats_propale['qty'] = $obj->qty ? (float) $obj->qty : 0;
3692
3693 // if it's a virtual product, maybe it is in proposal by extension
3694 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
3695 $TFather = $this->getFather();
3696 if (is_array($TFather) && !empty($TFather)) {
3697 foreach ($TFather as &$fatherData) {
3698 $pFather = new Product($this->db);
3699 $pFather->id = (int) $fatherData['id'];
3700 $qtyCoef = $fatherData['qty'];
3701
3702 if ($fatherData['incdec']) {
3703 $pFather->load_stats_propale($socid);
3704
3705 if (!empty($pFather->stats_propale)) {
3706 $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
3707 $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
3708 $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
3709 $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
3710 }
3711 }
3712 }
3713 }
3714 }
3715
3716 $parameters = array('socid' => $socid);
3717 $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
3718 if ($reshook > 0) {
3719 $this->stats_propale = $hookmanager->resArray['stats_propale'];
3720 }
3721
3722 return 1;
3723 } else {
3724 $this->error = $this->db->error();
3725 return -1;
3726 }
3727 }
3728
3729
3730 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3737 public function load_stats_proposal_supplier($socid = 0)
3738 {
3739 // phpcs:enable
3740 global $user, $hookmanager, $action;
3741
3742 $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
3743 $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
3744 $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
3745 $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
3746 $sql .= ", ".$this->db->prefix()."societe as s";
3747 $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
3748 $sql .= " AND p.fk_soc = s.rowid";
3749 $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
3750 $sql .= " AND pd.fk_product = ".((int) $this->id);
3751 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
3752 $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).")";
3753 }
3754 //$sql.= " AND pr.fk_statut != 0";
3755 if ($socid > 0) {
3756 $sql .= " AND p.fk_soc = ".((int) $socid);
3757 }
3758
3759 $result = $this->db->query($sql);
3760 if ($result) {
3761 $obj = $this->db->fetch_object($result);
3762 $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
3763 $this->stats_proposal_supplier['nb'] = $obj->nb;
3764 $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
3765 $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
3766
3767 $parameters = array('socid' => $socid);
3768 $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
3769 if ($reshook > 0) {
3770 $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
3771 }
3772
3773 return 1;
3774 } else {
3775 $this->error = $this->db->error();
3776 return -1;
3777 }
3778 }
3779
3780
3781 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3790 public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3791 {
3792 // phpcs:enable
3793 global $user, $hookmanager, $action;
3794
3795
3796 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3797 $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3798 $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
3799 $sql .= ", ".$this->db->prefix()."commande as c";
3800 $sql .= ", ".$this->db->prefix()."societe as s";
3801 $sql .= " WHERE c.rowid = cd.fk_commande";
3802 $sql .= " AND c.fk_soc = s.rowid";
3803 $sql .= " AND c.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'commande').")";
3804 $sql .= " AND cd.fk_product = ".((int) $this->id);
3805 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
3806 $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).")";
3807 }
3808 if ($socid > 0) {
3809 $sql .= " AND c.fk_soc = ".((int) $socid);
3810 }
3811 if ($filtrestatut != '') {
3812 $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3813 }
3814 // Add where from hooks
3815 $parameters = array('socid' => $socid, 'type_element' => 'order');
3816 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3817 $sql .= $hookmanager->resPrint;
3818 $result = $this->db->query($sql);
3819 if ($result) {
3820 $obj = $this->db->fetch_object($result);
3821 $this->stats_commande['customers'] = (int) $obj->nb_customers;
3822 $this->stats_commande['nb'] = (int) $obj->nb;
3823 $this->stats_commande['rows'] = (int) $obj->nb_rows;
3824 $this->stats_commande['qty'] = $obj->qty ? (float) $obj->qty : 0;
3825
3826 // if it's a virtual product, maybe it is in order by extension
3827 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
3828 $TFather = $this->getFather();
3829 if (is_array($TFather) && !empty($TFather)) {
3830 foreach ($TFather as &$fatherData) {
3831 $pFather = new Product($this->db);
3832 $pFather->id = $fatherData['id'];
3833 $qtyCoef = $fatherData['qty'];
3834
3835 if ($fatherData['incdec']) {
3836 $pFather->load_stats_commande($socid, $filtrestatut);
3837
3838 $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
3839 $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
3840 $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
3841 $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
3842 }
3843 }
3844 }
3845 }
3846
3847 // If stock decrease is on invoice validation, the theoretical stock continue to
3848 // count the orders lines containing product in theoretical stock when some are already removed by invoice validation.
3849 if ($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
3850 // Do the request using an UNION instead of a OR in the JOIN that is very slow
3851 if (getDolGlobalString('DECREASE_ONLY_UNINVOICEDPRODUCTS')) {
3852 // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation but only if order not yet invoice.
3853 $adeduire = 0;
3854 $sql = "SELECT SUM(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
3855 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
3856 //$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'))";
3857 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande' ";
3858 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_source = c.rowid";
3859 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
3860 $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
3861
3862 $sql .= " UNION ";
3863
3864 $sql .= "SELECT SUM(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
3865 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
3866 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture' ";
3867 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_target = c.rowid";
3868 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
3869 $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
3870 // Add where from hooks
3871 $parameters = array('socid' => $socid, 'type_element' => 'order');
3872 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3873 $sql .= $hookmanager->resPrint;
3874 $resql = $this->db->query($sql);
3875 if ($resql) {
3876 while ($obj = $this->db->fetch_object($resql)) {
3877 $adeduire += (float) $obj->count;
3878 }
3879 }
3880
3881 $this->stats_commande['qty'] -= $adeduire;
3882 } else {
3883 // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is off, we make a compensation with lines of invoices linked to the order
3884 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3885
3886 // For every order having invoice already validated we need to decrease stock cause it's in physical stock
3887 $adeduire = 0;
3888 $sql = "SELECT sum(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
3889 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
3890 //$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'))";
3891 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande' ";
3892 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_source = c.rowid";
3893 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND f.fk_statut > ".Facture::STATUS_DRAFT." AND fd.fk_product = ".((int) $this->id);
3894 $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
3895
3896 $sql .= " UNION ALL ";
3897
3898 $sql .= "SELECT sum(".$this->db->ifsql('f.type=2', '-1', '1')." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
3899 $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
3900 $sql .= " JOIN ".$this->db->prefix()."element_element as el ON el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture' ";
3901 $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_target = c.rowid";
3902 $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND f.fk_statut > ".Facture::STATUS_DRAFT." AND fd.fk_product = ".((int) $this->id);
3903 $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
3904
3905 dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
3906 // Add where from hooks
3907 $parameters = array('socid' => $socid, 'type_element' => 'order');
3908 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3909 $sql .= $hookmanager->resPrint;
3910 $resql = $this->db->query($sql);
3911 if ($resql) {
3912 while ($obj = $this->db->fetch_object($resql)) {
3913 $adeduire += (float) $obj->count;
3914 }
3915 } else {
3916 $this->error = $this->db->error();
3917 return -1;
3918 }
3919
3920 $this->stats_commande['qty'] -= $adeduire;
3921 }
3922 }
3923
3924 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3925 $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
3926 if ($reshook > 0) {
3927 $this->stats_commande = $hookmanager->resArray['stats_commande'];
3928 }
3929 return 1;
3930 } else {
3931 $this->error = $this->db->error();
3932 return -1;
3933 }
3934 }
3935
3936 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3946 public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
3947 {
3948 // phpcs:enable
3949 global $user, $hookmanager, $action;
3950
3951 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
3952 $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3953 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
3954 $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
3955 $sql .= ", ".$this->db->prefix()."societe as s";
3956 $sql .= " WHERE c.rowid = cd.fk_commande";
3957 $sql .= " AND c.fk_soc = s.rowid";
3958 $sql .= " AND c.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'supplier_order').")";
3959 $sql .= " AND cd.fk_product = ".((int) $this->id);
3960 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
3961 $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).")";
3962 }
3963 if ($socid > 0) {
3964 $sql .= " AND c.fk_soc = ".((int) $socid);
3965 }
3966 if ($filtrestatut != '') {
3967 $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
3968 }
3969 if (!empty($dateofvirtualstock)) {
3970 $sql .= " AND c.date_livraison <= '".$this->db->idate($dateofvirtualstock)."'";
3971 }
3972
3973 $result = $this->db->query($sql);
3974 if ($result) {
3975 $obj = $this->db->fetch_object($result);
3976 $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
3977 $this->stats_commande_fournisseur['nb'] = $obj->nb;
3978 $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
3979 $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3980
3981 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3982 $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
3983 if ($reshook > 0) {
3984 $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
3985 }
3986
3987 return 1;
3988 } else {
3989 $this->error = $this->db->error().' sql='.$sql;
3990 return -1;
3991 }
3992 }
3993
3994 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4004 public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
4005 {
4006 // phpcs:enable
4007 global $user, $hookmanager, $action;
4008
4009 $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
4010 $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
4011 $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
4012 $sql .= ", ".$this->db->prefix()."commandedet as cd";
4013 $sql .= ", ".$this->db->prefix()."commande as c";
4014 $sql .= ", ".$this->db->prefix()."expedition as e";
4015 $sql .= ", ".$this->db->prefix()."societe as s";
4016 $sql .= " WHERE e.rowid = ed.fk_expedition";
4017 $sql .= " AND c.rowid = cd.fk_commande";
4018 $sql .= " AND e.fk_soc = s.rowid";
4019 $sql .= " AND e.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'expedition').")";
4020 $sql .= " AND ed.fk_elementdet = cd.rowid";
4021 $sql .= " AND cd.fk_product = ".((int) $this->id);
4022 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4023 $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).")";
4024 }
4025 if ($socid > 0) {
4026 $sql .= " AND e.fk_soc = ".((int) $socid);
4027 }
4028 if ($filtrestatut != '') {
4029 $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
4030 }
4031 if (!empty($filterShipmentStatus)) {
4032 $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
4033 }
4034
4035 $result = $this->db->query($sql);
4036 if ($result) {
4037 $obj = $this->db->fetch_object($result);
4038 $this->stats_expedition['customers'] = (int) $obj->nb_customers;
4039 $this->stats_expedition['nb'] = (int) $obj->nb;
4040 $this->stats_expedition['rows'] = (int) $obj->nb_rows;
4041 $this->stats_expedition['qty'] = $obj->qty ? (float) $obj->qty : 0;
4042
4043 // if it's a virtual product, maybe it is in sending by extension
4044 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4045 $TFather = $this->getFather();
4046 if (is_array($TFather) && !empty($TFather)) {
4047 foreach ($TFather as &$fatherData) {
4048 $pFather = new Product($this->db);
4049 $pFather->id = $fatherData['id'];
4050 $qtyCoef = $fatherData['qty'];
4051
4052 if ($fatherData['incdec']) {
4053 $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
4054
4055 if (!empty($pFather->stats_expedition)) {
4056 $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
4057 $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
4058 $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
4059 $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
4060 }
4061 }
4062 }
4063 }
4064 }
4065
4066 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
4067 $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
4068 if ($reshook > 0) {
4069 $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
4070 }
4071
4072 return 1;
4073 } else {
4074 $this->error = $this->db->error();
4075 return -1;
4076 }
4077 }
4078
4079 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4089 public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
4090 {
4091 // phpcs:enable
4092 global $user, $hookmanager, $action;
4093
4094 $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
4095 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4096 $sql .= " FROM ".$this->db->prefix()."receptiondet_batch as fd";
4097 $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
4098 $sql .= ", ".$this->db->prefix()."societe as s";
4099 $sql .= " WHERE cf.rowid = fd.fk_element";
4100 $sql .= " AND cf.fk_soc = s.rowid";
4101 $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'supplier_order').")";
4102 $sql .= " AND fd.fk_product = ".((int) $this->id);
4103 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4104 $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).")";
4105 }
4106 if ($socid > 0) {
4107 $sql .= " AND cf.fk_soc = ".((int) $socid);
4108 }
4109 if ($filtrestatut != '') {
4110 $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
4111 }
4112 if (!empty($dateofvirtualstock)) {
4113 $sql .= " AND fd.datec <= '".$this->db->idate($dateofvirtualstock)."'";
4114 }
4115
4116 $result = $this->db->query($sql);
4117 if ($result) {
4118 $obj = $this->db->fetch_object($result);
4119 $this->stats_reception['suppliers'] = $obj->nb_suppliers;
4120 $this->stats_reception['nb'] = $obj->nb;
4121 $this->stats_reception['rows'] = $obj->nb_rows;
4122 $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
4123
4124 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
4125 $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
4126 if ($reshook > 0) {
4127 $this->stats_reception = $hookmanager->resArray['stats_reception'];
4128 }
4129
4130 return 1;
4131 } else {
4132 $this->error = $this->db->error();
4133 return -1;
4134 }
4135 }
4136
4137 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4148 public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null, $warehouseid = 0)
4149 {
4150 // phpcs:enable
4151 global $user, $hookmanager, $action;
4152
4153 $serviceStockIsEnabled = isModEnabled("service") && getDolGlobalString('STOCK_SUPPORTS_SERVICES');
4154
4155 $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
4156 $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
4157 $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
4158 $sql .= ", ".$this->db->prefix()."mrp_mo as m";
4159 $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
4160 $sql .= " WHERE m.rowid = mp.fk_mo";
4161 $sql .= " AND m.entity IN (".getEntity(($forVirtualStock && getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE')) ? 'stock' : 'mrp').")";
4162 $sql .= " AND mp.fk_product = ".((int) $this->id);
4163 $sql .= " AND (mp.disable_stock_change IN (0) OR mp.disable_stock_change IS NULL)";
4164 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir') && !$forVirtualStock) { // For external user, restriction is done on filter on fk_soc directly
4165 $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).")";
4166 }
4167 if ($socid > 0) {
4168 $sql .= " AND m.fk_soc = ".((int) $socid);
4169 }
4170 if ($filtrestatut != '') {
4171 $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
4172 }
4173 if (!empty($dateofvirtualstock)) {
4174 $sql .= " AND m.date_valid <= '".$this->db->idate($dateofvirtualstock)."'"; // better date to code ? end of production ?
4175 }
4176 if (!$serviceStockIsEnabled) {
4177 $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))";
4178 }
4179 if (!empty($warehouseid)) {
4180 $sql .= " AND m.fk_warehouse = ".((int) $warehouseid);
4181 }
4182 $sql .= " GROUP BY role";
4183
4184 if ($warehouseid) {
4185 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] = 0;
4186 } else {
4187 $this->stats_mrptoconsume['customers'] = 0;
4188 $this->stats_mrptoconsume['nb'] = 0;
4189 $this->stats_mrptoconsume['rows'] = 0;
4190 $this->stats_mrptoconsume['qty'] = 0.0;
4191 $this->stats_mrptoproduce['customers'] = 0;
4192 $this->stats_mrptoproduce['nb'] = 0;
4193 $this->stats_mrptoproduce['rows'] = 0;
4194 $this->stats_mrptoproduce['qty'] = 0.0;
4195 }
4196
4197 $result = $this->db->query($sql);
4198 if ($result) {
4199 while ($obj = $this->db->fetch_object($result)) {
4200 if ($obj->role == 'toconsume' && empty($warehouseid)) {
4201 $this->stats_mrptoconsume['customers'] += (int) $obj->nb_customers;
4202 $this->stats_mrptoconsume['nb'] += (int) $obj->nb;
4203 $this->stats_mrptoconsume['rows'] += (int) $obj->nb_rows;
4204 $this->stats_mrptoconsume['qty'] += ($obj->qty ? (float) $obj->qty : 0.0);
4205 }
4206 if ($obj->role == 'consumed' && empty($warehouseid)) {
4207 //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
4208 //$this->stats_mrptoconsume['nb'] += $obj->nb;
4209 //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
4210 $this->stats_mrptoconsume['qty'] -= ($obj->qty ? (float) $obj->qty : 0.0);
4211 }
4212 if ($obj->role == 'toproduce') {
4213 if ($warehouseid) {
4214 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] += ($obj->qty ? (float) $obj->qty : 0.0);
4215 } else {
4216 $this->stats_mrptoproduce['customers'] += (int) $obj->nb_customers;
4217 $this->stats_mrptoproduce['nb'] += (int) $obj->nb;
4218 $this->stats_mrptoproduce['rows'] += (int) $obj->nb_rows;
4219 $this->stats_mrptoproduce['qty'] += ($obj->qty ? (float) $obj->qty : 0.0);
4220 }
4221 }
4222 if ($obj->role == 'produced') {
4223 //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
4224 //$this->stats_mrptoproduce['nb'] += $obj->nb;
4225 //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
4226 if ($warehouseid) {
4227 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
4228 } else {
4229 $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
4230 }
4231 }
4232 }
4233
4234 // Clean data
4235 if ($warehouseid) {
4236 if ($this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] < 0) {
4237 $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'] = 0;
4238 }
4239 } else {
4240 if ($this->stats_mrptoconsume['qty'] < 0) {
4241 $this->stats_mrptoconsume['qty'] = 0;
4242 }
4243 if ($this->stats_mrptoproduce['qty'] < 0) {
4244 $this->stats_mrptoproduce['qty'] = 0;
4245 }
4246 }
4247
4248 $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
4249 $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
4250 if ($reshook > 0) {
4251 $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
4252 }
4253
4254 return 1;
4255 } else {
4256 $this->error = $this->db->error();
4257 return -1;
4258 }
4259 }
4260
4261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4268 public function load_stats_contrat($socid = 0)
4269 {
4270 // phpcs:enable
4271 global $user, $hookmanager, $action;
4272
4273 $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
4274 $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
4275 $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
4276 $sql .= ", ".$this->db->prefix()."contrat as c";
4277 $sql .= ", ".$this->db->prefix()."societe as s";
4278 $sql .= " WHERE c.rowid = cd.fk_contrat";
4279 $sql .= " AND c.fk_soc = s.rowid";
4280 $sql .= " AND c.entity IN (".getEntity('contract').")";
4281 $sql .= " AND cd.fk_product = ".((int) $this->id);
4282 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4283 $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).")";
4284 }
4285 //$sql.= " AND c.statut != 0";
4286 if ($socid > 0) {
4287 $sql .= " AND c.fk_soc = ".((int) $socid);
4288 }
4289
4290 $result = $this->db->query($sql);
4291 if ($result) {
4292 $obj = $this->db->fetch_object($result);
4293 $this->stats_contrat['customers'] = (int) $obj->nb_customers;
4294 $this->stats_contrat['nb'] = (int) $obj->nb;
4295 $this->stats_contrat['rows'] = (int) $obj->nb_rows;
4296 $this->stats_contrat['qty'] = $obj->qty ? (float) $obj->qty : 0;
4297
4298 // if it's a virtual product, maybe it is in contract by extension
4299 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4300 $TFather = $this->getFather();
4301 if (is_array($TFather) && !empty($TFather)) {
4302 foreach ($TFather as &$fatherData) {
4303 $pFather = new Product($this->db);
4304 $pFather->id = $fatherData['id'];
4305 $qtyCoef = $fatherData['qty'];
4306
4307 if ($fatherData['incdec']) {
4308 $pFather->load_stats_contrat($socid);
4309
4310 if (!empty($pFather->stats_contrat)) {
4311 $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
4312 $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
4313 $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
4314 $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
4315 }
4316 }
4317 }
4318 }
4319 }
4320
4321 $parameters = array('socid' => $socid);
4322 $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
4323 if ($reshook > 0) {
4324 $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
4325 }
4326
4327 return 1;
4328 } else {
4329 $this->error = $this->db->error().' sql='.$sql;
4330 return -1;
4331 }
4332 }
4333
4334 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4341 public function load_stats_facture($socid = 0)
4342 {
4343 // phpcs:enable
4344 global $user, $hookmanager, $action;
4345
4346 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
4347 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
4348 $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
4349 $sql .= ", ".$this->db->prefix()."facture as f";
4350 $sql .= ", ".$this->db->prefix()."societe as s";
4351 $sql .= " WHERE f.rowid = fd.fk_facture";
4352 $sql .= " AND f.fk_soc = s.rowid";
4353 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4354 $sql .= " AND fd.fk_product = ".((int) $this->id);
4355 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4356 $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).")";
4357 }
4358 //$sql.= " AND f.fk_statut != 0";
4359 if ($socid > 0) {
4360 $sql .= " AND f.fk_soc = ".((int) $socid);
4361 }
4362
4363 $result = $this->db->query($sql);
4364 if ($result) {
4365 $obj = $this->db->fetch_object($result);
4366 $this->stats_facture['customers'] = (int) $obj->nb_customers;
4367 $this->stats_facture['nb'] = (int) $obj->nb;
4368 $this->stats_facture['rows'] = (int) $obj->nb_rows;
4369 $this->stats_facture['qty'] = $obj->qty ? (float) $obj->qty : 0;
4370
4371 // if it's a virtual product, maybe it is in invoice by extension
4372 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4373 $TFather = $this->getFather();
4374 if (is_array($TFather) && !empty($TFather)) {
4375 foreach ($TFather as &$fatherData) {
4376 $pFather = new Product($this->db);
4377 $pFather->id = $fatherData['id'];
4378 $qtyCoef = $fatherData['qty'];
4379
4380 if ($fatherData['incdec']) {
4381 $pFather->load_stats_facture($socid);
4382
4383 if (!empty($pFather->stats_facture)) {
4384 $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
4385 $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
4386 $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
4387 $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
4388 }
4389 }
4390 }
4391 }
4392 }
4393
4394 $parameters = array('socid' => $socid);
4395 $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
4396 if ($reshook > 0) {
4397 $this->stats_facture = $hookmanager->resArray['stats_facture'];
4398 }
4399
4400 return 1;
4401 } else {
4402 $this->error = $this->db->error();
4403 return -1;
4404 }
4405 }
4406
4407
4408 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4415 public function load_stats_facturerec($socid = 0)
4416 {
4417 // phpcs:enable
4418 global $user, $hookmanager, $action;
4419
4420 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
4421 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4422 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_rec as fd";
4423 $sql .= ", ".MAIN_DB_PREFIX."facture_rec as f";
4424 $sql .= ", ".MAIN_DB_PREFIX."societe as s";
4425 $sql .= " WHERE f.rowid = fd.fk_facture";
4426 $sql .= " AND f.fk_soc = s.rowid";
4427 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4428 $sql .= " AND fd.fk_product = ".((int) $this->id);
4429 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4430 $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).")";
4431 }
4432 //$sql.= " AND f.fk_statut != 0";
4433 if ($socid > 0) {
4434 $sql .= " AND f.fk_soc = ".((int) $socid);
4435 }
4436
4437 $result = $this->db->query($sql);
4438 if ($result) {
4439 $obj = $this->db->fetch_object($result);
4440 $this->stats_facturerec['customers'] = (int) $obj->nb_customers;
4441 $this->stats_facturerec['nb'] = (int) $obj->nb;
4442 $this->stats_facturerec['rows'] = (int) $obj->nb_rows;
4443 $this->stats_facturerec['qty'] = $obj->qty ? (float) $obj->qty : 0.0;
4444
4445 // if it's a virtual product, maybe it is in invoice by extension
4446 if (getDolGlobalString('PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC')) {
4447 $TFather = $this->getFather();
4448 if (is_array($TFather) && !empty($TFather)) {
4449 foreach ($TFather as &$fatherData) {
4450 $pFather = new Product($this->db);
4451 $pFather->id = $fatherData['id'];
4452 $qtyCoef = $fatherData['qty'];
4453
4454 if ($fatherData['incdec']) {
4455 $pFather->load_stats_facture($socid);
4456
4457 $this->stats_facturerec['customers'] += $pFather->stats_facturerec['customers'];
4458 $this->stats_facturerec['nb'] += $pFather->stats_facturerec['nb'];
4459 $this->stats_facturerec['rows'] += $pFather->stats_facturerec['rows'];
4460 $this->stats_facturerec['qty'] += $pFather->stats_facturerec['qty'] * $qtyCoef;
4461 }
4462 }
4463 }
4464 }
4465
4466 $parameters = array('socid' => $socid);
4467 $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoiceRec', $parameters, $this, $action);
4468 if ($reshook > 0) {
4469 $this->stats_facturerec = $hookmanager->resArray['stats_facturerec'];
4470 }
4471
4472 return 1;
4473 } else {
4474 $this->error = $this->db->error();
4475 return -1;
4476 }
4477 }
4478
4479 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4486 public function load_stats_facture_fournisseur($socid = 0)
4487 {
4488 // phpcs:enable
4489 global $user, $hookmanager, $action;
4490
4491 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
4492 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4493 $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
4494 $sql .= ", ".$this->db->prefix()."facture_fourn as f";
4495 $sql .= ", ".$this->db->prefix()."societe as s";
4496 $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
4497 $sql .= " AND f.fk_soc = s.rowid";
4498 $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
4499 $sql .= " AND fd.fk_product = ".((int) $this->id);
4500 if (empty($user->fk_soc) && !$user->hasRight('societe', 'client', 'voir')) { // For external user, restriction is done on filter on fk_soc directly
4501 $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).")";
4502 }
4503 //$sql.= " AND f.fk_statut != 0";
4504 if ($socid > 0) {
4505 $sql .= " AND f.fk_soc = ".((int) $socid);
4506 }
4507
4508 $result = $this->db->query($sql);
4509 if ($result) {
4510 $obj = $this->db->fetch_object($result);
4511 $this->stats_facture_fournisseur['suppliers'] = (int) $obj->nb_suppliers;
4512 $this->stats_facture_fournisseur['nb'] = (int) $obj->nb;
4513 $this->stats_facture_fournisseur['rows'] = (int) $obj->nb_rows;
4514 $this->stats_facture_fournisseur['qty'] = $obj->qty ? (float) $obj->qty : 0.0;
4515
4516 $parameters = array('socid' => $socid);
4517 $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
4518 if ($reshook > 0) {
4519 $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
4520 }
4521
4522 return 1;
4523 } else {
4524 $this->error = $this->db->error();
4525 return -1;
4526 }
4527 }
4528
4529 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4536 public function load_stats_facturefournrec($socid = 0)
4537 {
4538 // phpcs:enable
4539 global $user, $hookmanager, $action;
4540
4541 $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
4542 $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
4543 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det_rec as fd";
4544 $sql .= ", ".MAIN_DB_PREFIX."facture_fourn_rec as f";
4545 $sql .= ", ".MAIN_DB_PREFIX."societe as s";
4546 if (!$user->hasRight('societe', 'client', 'voir')) {
4547 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
4548 }
4549 $sql .= " WHERE f.rowid = fd.fk_facture";
4550 $sql .= " AND f.fk_soc = s.rowid";
4551 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4552 $sql .= " AND fd.fk_product = ".((int) $this->id);
4553 if (!$user->hasRight('societe', 'client', 'voir')) {
4554 $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4555 }
4556 //$sql.= " AND f.fk_statut != 0";
4557 if ($socid > 0) {
4558 $sql .= " AND f.fk_soc = ".((int) $socid);
4559 }
4560
4561 $result = $this->db->query($sql);
4562 if ($result) {
4563 $obj = $this->db->fetch_object($result);
4564 $this->stats_facturefournrec['suppliers'] = (int) $obj->nb_suppliers;
4565 $this->stats_facturefournrec['nb'] = (int) $obj->nb;
4566 $this->stats_facturefournrec['rows'] = (int) $obj->nb_rows;
4567 $this->stats_facturefournrec['qty'] = $obj->qty ? (float) $obj->qty : 0.0;
4568
4569 $parameters = array('socid' => $socid);
4570 $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoiceRec', $parameters, $this, $action);
4571 if ($reshook > 0) {
4572 $this->stats_facturefournrec = $hookmanager->resArray['stats_facturefournrec'];
4573 }
4574
4575 return 1;
4576 } else {
4577 $this->error = $this->db->error();
4578 return -1;
4579 }
4580 }
4581
4582 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4591 private function _get_stats($sql, $mode, $year = 0)
4592 {
4593 // phpcs:enable
4594 $tab = array();
4595
4596 $resql = $this->db->query($sql);
4597 if ($resql) {
4598 $num = $this->db->num_rows($resql);
4599 $i = 0;
4600 while ($i < $num) {
4601 $arr = $this->db->fetch_array($resql);
4602 if (is_array($arr)) {
4603 $keyfortab = (string) $arr[1];
4604 if ($year == -1) {
4605 $keyfortab = substr($keyfortab, -2);
4606 }
4607
4608 if ($mode == 'byunit') {
4609 $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
4610 } elseif ($mode == 'bynumber') {
4611 $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
4612 } elseif ($mode == 'byamount') {
4613 $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
4614 } else {
4615 // Bad value for $mode
4616 return -1;
4617 }
4618 }
4619 $i++;
4620 }
4621 } else {
4622 $this->error = $this->db->error().' sql='.$sql;
4623 return -1;
4624 }
4625
4626 if (empty($year)) {
4627 $year = dol_print_date(time(), '%Y');
4628 $month = dol_print_date(time(), '%m');
4629 } elseif ($year == -1) {
4630 $year = '';
4631 $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
4632 } else {
4633 $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
4634 }
4635
4636 $result = array();
4637
4638 for ($j = 0; $j < 12; $j++) {
4639 // $idx is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
4640 $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
4641
4642 // print $idx.'-'.$year.'-'.$month.'<br>';
4643 $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
4644 // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
4645
4646 $month = "0".($month - 1);
4647 if (dol_strlen($month) == 3) {
4648 $month = substr($month, 1);
4649 }
4650 if ($month == 0) {
4651 $month = 12;
4652 if ($year !== '') { // $year is '' when we want stats for all years
4653 $year -= 1;
4654 }
4655 }
4656 }
4657
4658 return array_reverse($result);
4659 }
4660
4661
4662 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4673 public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4674 {
4675 // phpcs:enable
4676 global $user;
4677
4678 $sql = "SELECT sum(d.qty) as qty, date_format(f.datef, '%Y%m')";
4679 if ($mode == 'bynumber') {
4680 $sql .= ", count(DISTINCT f.rowid)";
4681 }
4682 $sql .= ", sum(d.total_ht) as total_ht";
4683 $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
4684 if ($filteronproducttype >= 0) {
4685 $sql .= ", ".$this->db->prefix()."product as p";
4686 }
4687 if (!$user->hasRight('societe', 'client', 'voir')) {
4688 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4689 }
4690 $sql .= " WHERE f.rowid = d.fk_facture";
4691 if ($this->id > 0) {
4692 $sql .= " AND d.fk_product = ".((int) $this->id);
4693 } else {
4694 $sql .= " AND d.fk_product > 0";
4695 }
4696 if ($filteronproducttype >= 0) {
4697 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4698 }
4699 $sql .= " AND f.fk_soc = s.rowid";
4700 $sql .= " AND f.entity IN (".getEntity('invoice').")";
4701 if (!$user->hasRight('societe', 'client', 'voir')) {
4702 $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4703 }
4704 if ($socid > 0) {
4705 $sql .= " AND f.fk_soc = ".((int) $socid);
4706 }
4707 $sql .= $morefilter;
4708 $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
4709 $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
4710
4711 return $this->_get_stats($sql, $mode, $year);
4712 }
4713
4714
4715 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4726 public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4727 {
4728 // phpcs:enable
4729 global $user;
4730
4731 $sql = "SELECT sum(d.qty) as qty, date_format(f.datef, '%Y%m')";
4732 if ($mode == 'bynumber') {
4733 $sql .= ", count(DISTINCT f.rowid)";
4734 }
4735 $sql .= ", sum(d.total_ht) as total_ht";
4736 $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
4737 if ($filteronproducttype >= 0) {
4738 $sql .= ", ".$this->db->prefix()."product as p";
4739 }
4740 if (!$user->hasRight('societe', 'client', 'voir')) {
4741 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4742 }
4743 $sql .= " WHERE f.rowid = d.fk_facture_fourn";
4744 if ($this->id > 0) {
4745 $sql .= " AND d.fk_product = ".((int) $this->id);
4746 } else {
4747 $sql .= " AND d.fk_product > 0";
4748 }
4749 if ($filteronproducttype >= 0) {
4750 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4751 }
4752 $sql .= " AND f.fk_soc = s.rowid";
4753 $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
4754 if (!$user->hasRight('societe', 'client', 'voir')) {
4755 $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4756 }
4757 if ($socid > 0) {
4758 $sql .= " AND f.fk_soc = ".((int) $socid);
4759 }
4760 $sql .= $morefilter;
4761 $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
4762 $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
4763
4764 return $this->_get_stats($sql, $mode, $year);
4765 }
4766
4767 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4778 public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4779 {
4780 // phpcs:enable
4781 global $user, $hookmanager;
4782
4783 $sql = "SELECT sum(d.qty) as qty, date_format(p.datep, '%Y%m')";
4784 if ($mode == 'bynumber') {
4785 $sql .= ", count(DISTINCT p.rowid)";
4786 }
4787 $sql .= ", sum(d.total_ht) as total_ht";
4788 $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
4789 if ($filteronproducttype >= 0) {
4790 $sql .= ", ".$this->db->prefix()."product as prod";
4791 }
4792 if (!$user->hasRight('societe', 'client', 'voir')) {
4793 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4794 }
4795 $sql .= " WHERE p.rowid = d.fk_propal";
4796 if ($this->id > 0) {
4797 $sql .= " AND d.fk_product = ".((int) $this->id);
4798 } else {
4799 $sql .= " AND d.fk_product > 0";
4800 }
4801 if ($filteronproducttype >= 0) {
4802 $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
4803 }
4804 $sql .= " AND p.fk_soc = s.rowid";
4805 $sql .= " AND p.entity IN (".getEntity('propal').")";
4806 if (!$user->hasRight('societe', 'client', 'voir')) {
4807 $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4808 }
4809 if ($socid > 0) {
4810 $sql .= " AND p.fk_soc = ".((int) $socid);
4811 }
4812 $sql .= $morefilter;
4813 $parameters = array('socid' => $user->socid);
4814 $hookmanager->executeHooks('productGetNbPropal', $parameters, $this); // Note that $action and $object may have been modified by hook
4815 $sql .= $hookmanager->resPrint;
4816 $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
4817 $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
4818 return $this->_get_stats($sql, $mode, $year);
4819 }
4820
4821 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4832 public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4833 {
4834 // phpcs:enable
4835 global $user;
4836
4837 $sql = "SELECT sum(d.qty) as qty, date_format(p.date_valid, '%Y%m')";
4838 if ($mode == 'bynumber') {
4839 $sql .= ", count(DISTINCT p.rowid)";
4840 }
4841 $sql .= ", sum(d.total_ht) as total_ht";
4842 $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
4843 if ($filteronproducttype >= 0) {
4844 $sql .= ", ".$this->db->prefix()."product as prod";
4845 }
4846 if (!$user->hasRight('societe', 'client', 'voir')) {
4847 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4848 }
4849 $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
4850 if ($this->id > 0) {
4851 $sql .= " AND d.fk_product = ".((int) $this->id);
4852 } else {
4853 $sql .= " AND d.fk_product > 0";
4854 }
4855 if ($filteronproducttype >= 0) {
4856 $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
4857 }
4858 $sql .= " AND p.fk_soc = s.rowid";
4859 $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
4860 if (!$user->hasRight('societe', 'client', 'voir')) {
4861 $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4862 }
4863 if ($socid > 0) {
4864 $sql .= " AND p.fk_soc = ".((int) $socid);
4865 }
4866 $sql .= $morefilter;
4867 $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
4868 $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
4869
4870 return $this->_get_stats($sql, $mode, $year);
4871 }
4872
4873 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4884 public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4885 {
4886 // phpcs:enable
4887 global $user, $hookmanager;
4888
4889 $sql = "SELECT sum(d.qty) as qty, date_format(c.date_commande, '%Y%m')";
4890 if ($mode == 'bynumber') {
4891 $sql .= ", count(DISTINCT c.rowid)";
4892 }
4893 $sql .= ", sum(d.total_ht) as total_ht";
4894 $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
4895 if ($filteronproducttype >= 0) {
4896 $sql .= ", ".$this->db->prefix()."product as p";
4897 }
4898 if (!$user->hasRight('societe', 'client', 'voir')) {
4899 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4900 }
4901 $sql .= " WHERE c.rowid = d.fk_commande";
4902 if ($this->id > 0) {
4903 $sql .= " AND d.fk_product = ".((int) $this->id);
4904 } else {
4905 $sql .= " AND d.fk_product > 0";
4906 }
4907 if ($filteronproducttype >= 0) {
4908 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4909 }
4910 $sql .= " AND c.fk_soc = s.rowid";
4911 $sql .= " AND c.entity IN (".getEntity('commande').")";
4912 if (!$user->hasRight('societe', 'client', 'voir')) {
4913 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4914 }
4915 if ($socid > 0) {
4916 $sql .= " AND c.fk_soc = ".((int) $socid);
4917 }
4918 $sql .= $morefilter;
4919 $parameters = array('socid' => $user->socid);
4920 $hookmanager->executeHooks('productGetNbOrder', $parameters, $this); // Note that $action and $object may have been modified by hook
4921 $sql .= $hookmanager->resPrint;
4922 $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
4923 $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
4924
4925 return $this->_get_stats($sql, $mode, $year);
4926 }
4927
4928 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4939 public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4940 {
4941 // phpcs:enable
4942 global $user;
4943
4944 $sql = "SELECT sum(d.qty) as qty, date_format(c.date_commande, '%Y%m')";
4945 if ($mode == 'bynumber') {
4946 $sql .= ", count(DISTINCT c.rowid)";
4947 }
4948 $sql .= ", sum(d.total_ht) as total_ht";
4949 $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
4950 if ($filteronproducttype >= 0) {
4951 $sql .= ", ".$this->db->prefix()."product as p";
4952 }
4953 if (!$user->hasRight('societe', 'client', 'voir')) {
4954 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4955 }
4956 $sql .= " WHERE c.rowid = d.fk_commande";
4957 if ($this->id > 0) {
4958 $sql .= " AND d.fk_product = ".((int) $this->id);
4959 } else {
4960 $sql .= " AND d.fk_product > 0";
4961 }
4962 if ($filteronproducttype >= 0) {
4963 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4964 }
4965 $sql .= " AND c.fk_soc = s.rowid";
4966 $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
4967 if (!$user->hasRight('societe', 'client', 'voir')) {
4968 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4969 }
4970 if ($socid > 0) {
4971 $sql .= " AND c.fk_soc = ".((int) $socid);
4972 }
4973 $sql .= $morefilter;
4974 $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
4975 $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
4976
4977 return $this->_get_stats($sql, $mode, $year);
4978 }
4979
4980 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4991 public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4992 {
4993 // phpcs:enable
4994 global $user;
4995
4996 $sql = "SELECT sum(d.qty) as qty, date_format(c.date_contrat, '%Y%m')";
4997 if ($mode == 'bynumber') {
4998 $sql .= ", count(DISTINCT c.rowid)";
4999 }
5000 $sql .= ", sum(d.total_ht) as total_ht";
5001 $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
5002 if ($filteronproducttype >= 0) {
5003 $sql .= ", ".$this->db->prefix()."product as p";
5004 }
5005 if (!$user->hasRight('societe', 'client', 'voir')) {
5006 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5007 }
5008 $sql .= " WHERE c.entity IN (".getEntity('contract').")";
5009 $sql .= " AND c.rowid = d.fk_contrat";
5010
5011 if ($this->id > 0) {
5012 $sql .= " AND d.fk_product = ".((int) $this->id);
5013 } else {
5014 $sql .= " AND d.fk_product > 0";
5015 }
5016 if ($filteronproducttype >= 0) {
5017 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
5018 }
5019 $sql .= " AND c.fk_soc = s.rowid";
5020
5021 if (!$user->hasRight('societe', 'client', 'voir')) {
5022 $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5023 }
5024 if ($socid > 0) {
5025 $sql .= " AND c.fk_soc = ".((int) $socid);
5026 }
5027 $sql .= $morefilter;
5028 $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
5029 $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
5030
5031 return $this->_get_stats($sql, $mode, $year);
5032 }
5033
5034 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5045 public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
5046 {
5047 // phpcs:enable
5048 global $user;
5049
5050 $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
5051 if ($mode == 'bynumber') {
5052 $sql .= ", count(DISTINCT d.rowid)";
5053 }
5054 $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
5055 if ($filteronproducttype >= 0) {
5056 $sql .= ", ".$this->db->prefix()."product as p";
5057 }
5058 if (!$user->hasRight('societe', 'client', 'voir')) {
5059 $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
5060 }
5061
5062 $sql .= " WHERE d.entity IN (".getEntity('mo').")";
5063 $sql .= " AND d.status > 0";
5064
5065 if ($this->id > 0) {
5066 $sql .= " AND d.fk_product = ".((int) $this->id);
5067 } else {
5068 $sql .= " AND d.fk_product > 0";
5069 }
5070 if ($filteronproducttype >= 0) {
5071 $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
5072 }
5073
5074 if (!$user->hasRight('societe', 'client', 'voir')) {
5075 $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
5076 }
5077 if ($socid > 0) {
5078 $sql .= " AND d.fk_soc = ".((int) $socid);
5079 }
5080 $sql .= $morefilter;
5081 $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
5082 $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
5083
5084 return $this->_get_stats($sql, $mode, $year);
5085 }
5086
5087 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5098 public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1, $notrigger = 0)
5099 {
5100 // phpcs:enable
5101 global $user;
5102
5103 // Clean parameters
5104 if (!is_numeric($id_pere)) {
5105 $id_pere = 0;
5106 }
5107 if (!is_numeric($id_fils)) {
5108 $id_fils = 0;
5109 }
5110 if (!is_numeric($incdec)) {
5111 $incdec = 0;
5112 }
5113
5114 $result = $this->del_sousproduit($id_pere, $id_fils);
5115 if ($result < 0) {
5116 return $result;
5117 }
5118
5119 // Check not already father of id_pere (to avoid father -> child -> father links)
5120 $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
5121 $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
5122 if (!$this->db->query($sql)) {
5123 dol_print_error($this->db);
5124 return -1;
5125 } else {
5126 //Selection of the highest row
5127 $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
5128 $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
5129 $resql = $this->db->query($sql);
5130 if ($resql) {
5131 $obj = $this->db->fetch_object($resql);
5132 $rank = $obj->max_rank + 1;
5133 //Addition of a product with the highest rank +1
5134 $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
5135 $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".((int) $incdec).", ".((int) $rank).")";
5136 if (! $this->db->query($sql)) {
5137 dol_print_error($this->db);
5138 return -1;
5139 } else {
5140 if (!$notrigger) {
5141 // Call trigger
5142 $result = $this->call_trigger('PRODUCT_SUBPRODUCT_ADD', $user);
5143 if ($result < 0) {
5144 $this->error = $this->db->lasterror();
5145 dol_syslog(get_class($this).'::addSubproduct error='.$this->error, LOG_ERR);
5146 return -1;
5147 }
5148 }
5149 // End call triggers
5150
5151 return 1;
5152 }
5153 } else {
5154 dol_print_error($this->db);
5155 return -1;
5156 }
5157 }
5158 }
5159
5160 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5171 public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1, $notrigger = 0)
5172 {
5173 // phpcs:enable
5174 global $user;
5175
5176 // Clean parameters
5177 if (!is_numeric($id_pere)) {
5178 $id_pere = 0;
5179 }
5180 if (!is_numeric($id_fils)) {
5181 $id_fils = 0;
5182 }
5183 if (!is_numeric($incdec)) {
5184 $incdec = 1;
5185 }
5186 if (!is_numeric($qty)) {
5187 $qty = 1;
5188 }
5189
5190 $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
5191 $sql .= 'qty = '.price2num($qty, 'MS');
5192 $sql .= ',incdec = '.((int) $incdec);
5193 $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
5194
5195 if (!$this->db->query($sql)) {
5196 dol_print_error($this->db);
5197 return -1;
5198 } else {
5199 if (!$notrigger) {
5200 // Call trigger
5201 $result = $this->call_trigger('PRODUCT_SUBPRODUCT_UPDATE', $user);
5202 if ($result < 0) {
5203 $this->error = $this->db->lasterror();
5204 dol_syslog(get_class($this).'::updateSubproduct error='.$this->error, LOG_ERR);
5205 return -1;
5206 }
5207 // End call triggers
5208 }
5209
5210 return 1;
5211 }
5212 }
5213
5214 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5223 public function del_sousproduit($fk_parent, $fk_child, $notrigger = 0)
5224 {
5225 // phpcs:enable
5226 global $user;
5227
5228 if (!is_numeric($fk_parent)) {
5229 $fk_parent = 0;
5230 }
5231 if (!is_numeric($fk_child)) {
5232 $fk_child = 0;
5233 }
5234
5235 $sql = "DELETE FROM ".$this->db->prefix()."product_association";
5236 $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
5237 $sql .= " AND fk_product_fils = ".((int) $fk_child);
5238
5239 dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
5240 if (!$this->db->query($sql)) {
5241 dol_print_error($this->db);
5242 return -1;
5243 }
5244
5245 // Updated ranks so that none are missing
5246 $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
5247 $sqlrank .= " WHERE fk_product_pere = ".((int) $fk_parent);
5248 $sqlrank .= " ORDER BY rang";
5249 $resqlrank = $this->db->query($sqlrank);
5250 if ($resqlrank) {
5251 $cpt = 0;
5252 while ($objrank = $this->db->fetch_object($resqlrank)) {
5253 $cpt++;
5254 $sql = "UPDATE ".$this->db->prefix()."product_association";
5255 $sql .= " SET rang = ".((int) $cpt);
5256 $sql .= " WHERE rowid = ".((int) $objrank->rowid);
5257 if (! $this->db->query($sql)) {
5258 dol_print_error($this->db);
5259 return -1;
5260 }
5261 }
5262 }
5263
5264 if (!$notrigger) {
5265 // Call trigger
5266 $result = $this->call_trigger('PRODUCT_SUBPRODUCT_DELETE', $user);
5267 if ($result < 0) {
5268 $this->error = $this->db->lasterror();
5269 dol_syslog(get_class($this).'::delSubproduct error='.$this->error, LOG_ERR);
5270 return -1;
5271 }
5272 // End call triggers
5273 }
5274
5275 return 1;
5276 }
5277
5278 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5286 public function is_sousproduit($fk_parent, $fk_child)
5287 {
5288 // phpcs:enable
5289 $sql = "SELECT fk_product_pere, qty, incdec";
5290 $sql .= " FROM ".$this->db->prefix()."product_association";
5291 $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
5292 $sql .= " AND fk_product_fils = ".((int) $fk_child);
5293
5294 $result = $this->db->query($sql);
5295 if ($result) {
5296 $num = $this->db->num_rows($result);
5297
5298 if ($num > 0) {
5299 $obj = $this->db->fetch_object($result);
5300
5301 $this->is_sousproduit_qty = $obj->qty;
5302 $this->is_sousproduit_incdec = $obj->incdec;
5303
5304 return 1;
5305 } else {
5306 return 0;
5307 }
5308 } else {
5309 dol_print_error($this->db);
5310 return -1;
5311 }
5312 }
5313
5314
5315 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5326 public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
5327 {
5328 // phpcs:enable
5329 global $conf;
5330
5331 $now = dol_now();
5332
5333 dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
5334
5335 // Clean parameters
5336 $quantity = price2num($quantity, 'MS');
5337
5338 if ($ref_fourn) {
5339 // Check if ref is not already used
5340 $sql = "SELECT rowid, fk_product";
5341 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
5342 $sql .= " WHERE fk_soc = ".((int) $id_fourn);
5343 $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
5344 $sql .= " AND fk_product <> ".((int) $this->id);
5345 $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
5346
5347 $resql = $this->db->query($sql);
5348 if ($resql) {
5349 $obj = $this->db->fetch_object($resql);
5350 if ($obj) {
5351 // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
5352 $this->product_id_already_linked = $obj->fk_product;
5353 return -3;
5354 }
5355 $this->db->free($resql);
5356 }
5357 }
5358
5359 $sql = "SELECT rowid";
5360 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
5361 $sql .= " WHERE fk_soc = ".((int) $id_fourn);
5362 if ($ref_fourn) {
5363 $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
5364 } else {
5365 $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
5366 }
5367 $sql .= " AND quantity = ".((float) $quantity);
5368 $sql .= " AND fk_product = ".((int) $this->id);
5369 $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
5370
5371 $resql = $this->db->query($sql);
5372 if ($resql) {
5373 $obj = $this->db->fetch_object($resql);
5374
5375 // The reference supplier does not exist, we create it for this product.
5376 if (empty($obj)) {
5377 $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
5378 $sql .= "datec";
5379 $sql .= ", entity";
5380 $sql .= ", fk_product";
5381 $sql .= ", fk_soc";
5382 $sql .= ", ref_fourn";
5383 $sql .= ", quantity";
5384 $sql .= ", fk_user";
5385 $sql .= ", tva_tx";
5386 $sql .= ") VALUES (";
5387 $sql .= "'".$this->db->idate($now)."'";
5388 $sql .= ", ".((int) $conf->entity);
5389 $sql .= ", ".((int) $this->id);
5390 $sql .= ", ".((int) $id_fourn);
5391 $sql .= ", '".$this->db->escape($ref_fourn)."'";
5392 $sql .= ", ".((float) $quantity);
5393 $sql .= ", ".((int) $user->id);
5394 $sql .= ", 0";
5395 $sql .= ")";
5396
5397 if ($this->db->query($sql)) {
5398 $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
5399 return 1;
5400 } else {
5401 $this->error = $this->db->lasterror();
5402 return -1;
5403 }
5404 } else {
5405 // If the supplier price already exists for this product and quantity
5406 $this->product_fourn_price_id = $obj->rowid;
5407 return 0;
5408 }
5409 } else {
5410 $this->error = $this->db->lasterror();
5411 return -2;
5412 }
5413 }
5414
5415
5416 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5422 public function list_suppliers()
5423 {
5424 // phpcs:enable
5425 global $conf;
5426
5427 $list = array();
5428
5429 $sql = "SELECT DISTINCT p.fk_soc";
5430 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
5431 $sql .= " WHERE p.fk_product = ".((int) $this->id);
5432 $sql .= " AND p.entity = ".((int) $conf->entity);
5433
5434 $result = $this->db->query($sql);
5435 if ($result) {
5436 $num = $this->db->num_rows($result);
5437 $i = 0;
5438 while ($i < $num) {
5439 $obj = $this->db->fetch_object($result);
5440 $list[$i] = $obj->fk_soc;
5441 $i++;
5442 }
5443 }
5444
5445 return $list;
5446 }
5447
5448 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5456 public function clone_price($fromId, $toId)
5457 {
5458 // phpcs:enable
5459 global $user;
5460
5461 $now = dol_now();
5462
5463 $this->db->begin();
5464
5465 // prices
5466 $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
5467 $sql .= " entity";
5468 $sql .= ", fk_product";
5469 $sql .= ", date_price";
5470 $sql .= ", price_level";
5471 $sql .= ", price";
5472 $sql .= ", price_ttc";
5473 $sql .= ", price_min";
5474 $sql .= ", price_min_ttc";
5475 $sql .= ", price_base_type";
5476 $sql .= ", price_label";
5477 $sql .= ", default_vat_code";
5478 $sql .= ", tva_tx";
5479 $sql .= ", recuperableonly";
5480 $sql .= ", localtax1_tx";
5481 $sql .= ", localtax1_type";
5482 $sql .= ", localtax2_tx";
5483 $sql .= ", localtax2_type";
5484 $sql .= ", fk_user_author";
5485 $sql .= ", tosell";
5486 $sql .= ", price_by_qty";
5487 $sql .= ", fk_price_expression";
5488 $sql .= ", fk_multicurrency";
5489 $sql .= ", multicurrency_code";
5490 $sql .= ", multicurrency_tx";
5491 $sql .= ", multicurrency_price";
5492 $sql .= ", multicurrency_price_ttc";
5493 $sql .= ")";
5494 $sql .= " SELECT";
5495 $sql .= " entity";
5496 $sql .= ", ".((int) $toId);
5497 $sql .= ", '".$this->db->idate($now)."'";
5498 $sql .= ", price_level";
5499 $sql .= ", price";
5500 $sql .= ", price_ttc";
5501 $sql .= ", price_min";
5502 $sql .= ", price_min_ttc";
5503 $sql .= ", price_base_type";
5504 $sql .= ", price_label";
5505 $sql .= ", default_vat_code";
5506 $sql .= ", tva_tx";
5507 $sql .= ", recuperableonly";
5508 $sql .= ", localtax1_tx";
5509 $sql .= ", localtax1_type";
5510 $sql .= ", localtax2_tx";
5511 $sql .= ", localtax2_type";
5512 $sql .= ", ".((int) $user->id);
5513 $sql .= ", tosell";
5514 $sql .= ", price_by_qty";
5515 $sql .= ", fk_price_expression";
5516 $sql .= ", fk_multicurrency";
5517 $sql .= ", multicurrency_code";
5518 $sql .= ", multicurrency_tx";
5519 $sql .= ", multicurrency_price";
5520 $sql .= ", multicurrency_price_ttc";
5521 $sql .= " FROM ".$this->db->prefix()."product_price ps";
5522 $sql .= " WHERE fk_product = ".((int) $fromId);
5523 $sql .= " AND date_price IN (SELECT MAX(pd.date_price) FROM ".$this->db->prefix()."product_price pd WHERE pd.fk_product = ".((int) $fromId)." AND pd.price_level = ps.price_level)";
5524 $sql .= " ORDER BY date_price DESC";
5525
5526 dol_syslog(__METHOD__, LOG_DEBUG);
5527 $resql = $this->db->query($sql);
5528 if (!$resql) {
5529 $this->db->rollback();
5530 return -1;
5531 }
5532
5533 $this->db->commit();
5534 return 1;
5535 }
5536
5537 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5545 public function clone_associations($fromId, $toId)
5546 {
5547 // phpcs:enable
5548 $this->db->begin();
5549
5550 $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty, incdec)';
5551 $sql .= " SELECT ".((int) $toId).", fk_product_fils, qty, incdec FROM ".$this->db->prefix()."product_association";
5552 $sql .= " WHERE fk_product_pere = ".((int) $fromId);
5553
5554 dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
5555 if (!$this->db->query($sql)) {
5556 $this->db->rollback();
5557 return -1;
5558 }
5559
5560 $this->db->commit();
5561 return 1;
5562 }
5563
5564 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5572 public function clone_fournisseurs($fromId, $toId)
5573 {
5574 // phpcs:enable
5575 $this->db->begin();
5576
5577 $now = dol_now();
5578
5579 // les fournisseurs
5580 /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
5581 . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
5582 . " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, ref_fourn, fk_user_author"
5583 . " FROM ".$this->db->prefix()."product_fournisseur"
5584 . " WHERE fk_product = ".((int) $fromId);
5585
5586 if ( ! $this->db->query($sql ) )
5587 {
5588 $this->db->rollback();
5589 return -1;
5590 }*/
5591
5592 // les prix de fournisseurs.
5593 $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
5594 $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user, tva_tx)";
5595 $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user, tva_tx";
5596 $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
5597 $sql .= " WHERE fk_product = ".((int) $fromId);
5598
5599 dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
5600 $resql = $this->db->query($sql);
5601 if (!$resql) {
5602 $this->db->rollback();
5603 return -1;
5604 } else {
5605 $this->db->commit();
5606 return 1;
5607 }
5608 }
5609
5610 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5623 public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
5624 {
5625 // phpcs:enable
5626 $tmpproduct = null;
5627
5628 if ($multiply < 1) {
5629 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);
5630 $multiply = 1;
5631 }
5632
5633 //var_dump($prod);
5634 foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
5635 if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
5636 $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
5637 $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
5638 $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
5639 $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
5640 $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
5641
5642 //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
5643 if (is_null($tmpproduct)) {
5644 $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
5645 }
5646 $tmpproduct->fetch($id); // Load product to get ->ref
5647
5648 if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
5649 $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
5650 }
5651
5652 $this->res[] = array(
5653 'id' => $id, // Id product
5654 'id_parent' => $id_parent,
5655 'ref' => $tmpproduct->ref, // Ref product
5656 'nb' => $nb, // Nb of units that compose parent product
5657 'nb_total' => $nb * $multiply, // Nb of units for all nb of product
5658 'stock' => $tmpproduct->stock_reel, // Stock
5659 'stock_alert' => $tmpproduct->seuil_stock_alerte, // Stock alert
5660 'label' => $label,
5661 'fullpath' => $compl_path.$label, // Label
5662 'type' => $type, // Nb of units that compose parent product
5663 'desiredstock' => $tmpproduct->desiredstock,
5664 'level' => $level,
5665 'incdec' => $incdec,
5666 'entity' => $tmpproduct->entity
5667 );
5668
5669 // Recursive call if there child has children of its own
5670 if (isset($desc_pere['childs']) && is_array($desc_pere['childs'])) {
5671 if (!is_int($desc_pere[1] * $multiply)) {
5672 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);
5673 }
5674
5675 //print 'YYY We go down for '.$desc_pere[3]." -> \n";
5676 $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", (int) ceil($desc_pere[1] * $multiply), $level + 1, $id, $ignore_stock_load);
5677 }
5678 }
5679 }
5680 }
5681
5682 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5691 public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
5692 {
5693 // phpcs:enable
5694 $this->res = array();
5695 if (isset($this->sousprods) && is_array($this->sousprods)) {
5696 foreach ($this->sousprods as $prod_name => $desc_product) {
5697 if (is_array($desc_product)) {
5698 $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load); // This set $this->res
5699 }
5700 }
5701 }
5702 //var_dump($res);
5703 return $this->res;
5704 }
5705
5713 public function hasFatherOrChild($mode = 0)
5714 {
5715 $nb = 0;
5716
5717 $sql = "SELECT COUNT(pa.rowid) as nb";
5718 $sql .= " FROM ".$this->db->prefix()."product_association as pa";
5719 if ($mode == 0) {
5720 $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
5721 } elseif ($mode == -1) {
5722 $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)
5723 } elseif ($mode == 1) {
5724 $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)
5725 }
5726
5727 $resql = $this->db->query($sql);
5728 if ($resql) {
5729 $obj = $this->db->fetch_object($resql);
5730 if ($obj) {
5731 $nb = (int) $obj->nb;
5732 }
5733 } else {
5734 return -1;
5735 }
5736
5737 return $nb;
5738 }
5739
5745 public function hasVariants()
5746 {
5747 $nb = 0;
5748 if (!isModEnabled('variants')) {
5749 return $nb;
5750 }
5751 $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
5752 $sql .= " AND entity IN (".getEntity('product').")";
5753
5754 $resql = $this->db->query($sql);
5755 if ($resql) {
5756 $obj = $this->db->fetch_object($resql);
5757 if ($obj) {
5758 $nb = (int) $obj->nb;
5759 }
5760 }
5761
5762 return $nb;
5763 }
5764
5765
5771 public function isVariant()
5772 {
5773 if (isModEnabled('variants')) {
5774 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
5775
5776 $query = $this->db->query($sql);
5777
5778 if ($query) {
5779 if (!$this->db->num_rows($query)) {
5780 return false;
5781 }
5782 return true;
5783 } else {
5784 dol_print_error($this->db);
5785 return -1;
5786 }
5787 } else {
5788 return false;
5789 }
5790 }
5791
5798 public function getFather()
5799 {
5800 $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";
5801 $sql .= ", p.tosell as status, p.tobuy as status_buy";
5802 $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
5803 $sql .= " ".$this->db->prefix()."product as p";
5804 $sql .= " WHERE p.rowid = pa.fk_product_pere";
5805 $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
5806
5807 $res = $this->db->query($sql);
5808 if ($res) {
5809 $prods = array();
5810 while ($record = $this->db->fetch_array($res)) {
5811 // $record['id'] = $record['rowid'] = id of father
5812 $prods[$record['id']] = array();
5813 $prods[$record['id']]['id'] = $record['rowid'];
5814 $prods[$record['id']]['ref'] = $record['ref'];
5815 $prods[$record['id']]['label'] = $record['label'];
5816 $prods[$record['id']]['qty'] = $record['qty'];
5817 $prods[$record['id']]['incdec'] = $record['incdec'];
5818 $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
5819 $prods[$record['id']]['entity'] = $record['entity'];
5820 $prods[$record['id']]['status'] = $record['status'];
5821 $prods[$record['id']]['status_buy'] = $record['status_buy'];
5822 }
5823 return $prods;
5824 } else {
5825 dol_print_error($this->db);
5826 return -1;
5827 }
5828 }
5829
5830
5840 public function getChildsArbo($id, $firstlevelonly = 0, $level = 1, $parents = array())
5841 {
5842 if (empty($id)) {
5843 return array();
5844 }
5845
5846 $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
5847 $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
5848 $sql .= " pa.rowid as fk_association, pa.rang";
5849 $sql .= " FROM ".$this->db->prefix()."product as p,";
5850 $sql .= " ".$this->db->prefix()."product_association as pa";
5851 $sql .= " WHERE p.rowid = pa.fk_product_fils";
5852 $sql .= " AND pa.fk_product_pere = ".((int) $id);
5853 $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
5854 $sql .= " ORDER BY pa.rang";
5855
5856 dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level. ' parents='.(is_array($parents) ? implode(',', $parents) : $parents), LOG_DEBUG);
5857
5858 // Protection against infinite loop
5859 if ($level > 30) {
5860 return array();
5861 }
5862
5863 $res = $this->db->query($sql);
5864 if ($res) {
5865 $prods = array();
5866 if ($this->db->num_rows($res) > 0) {
5867 $parents[] = $id;
5868 }
5869
5870 while ($rec = $this->db->fetch_array($res)) {
5871 if (in_array($rec['id'], $parents)) {
5872 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);
5873 continue; // We discard this child if it is already found at a higher level in tree in the same branch.
5874 }
5875
5876 $prods[$rec['rowid']] = array(
5877 0 => $rec['rowid'],
5878 1 => $rec['qty'],
5879 2 => $rec['fk_product_type'],
5880 3 => $this->db->escape($rec['label']),
5881 4 => $rec['incdec'],
5882 5 => $rec['ref'],
5883 6 => $rec['fk_association'],
5884 7 => $rec['rang']
5885 );
5886 //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
5887 //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
5888 if (empty($firstlevelonly)) {
5889 $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1, $parents);
5890 foreach ($listofchilds as $keyChild => $valueChild) {
5891 $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
5892 }
5893 }
5894 }
5895
5896 return $prods;
5897 } else {
5898 dol_print_error($this->db);
5899 return -1;
5900 }
5901 }
5902
5903 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5910 public function get_sousproduits_arbo()
5911 {
5912 // phpcs:enable
5913 $parent = array();
5914
5915 foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
5916 $parent[$this->label][$keyChild] = $valueChild;
5917 }
5918 foreach ($parent as $key => $value) { // key=label, value is array of children
5919 $this->sousprods[$key] = $value; // @phan-suppress-current-line PhanTypeMismatchProperty
5920 }
5921 }
5922
5930 public function getTooltipContentArray($params)
5931 {
5932 global $conf, $langs, $user;
5933
5934 $langs->loadLangs(array('products', 'other'));
5935
5936 $datas = array();
5937 $nofetch = !empty($params['nofetch']);
5938
5939 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
5940 return ['optimize' => $langs->trans("ShowProduct")];
5941 }
5942
5943 // Does user has permission to read product/service
5944 $permissiontoreadproduct = 0;
5945 if ($this->type == self::TYPE_PRODUCT && $user->hasRight('product', 'read')) {
5946 $permissiontoreadproduct = 1;
5947 }
5948 if ($this->type == self::TYPE_SERVICE && $user->hasRight('service', 'read')) {
5949 $permissiontoreadproduct = 1;
5950 }
5951
5952 if (!empty($this->entity) && $permissiontoreadproduct) {
5953 $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80, 0, 0, 0, 0, '1');
5954 if ($this->nbphoto > 0) {
5955 $datas['photo'] = '<div class="photointooltip floatright">'."\n" . $tmpphoto . '</div>';
5956 }
5957 }
5958
5959 if ($this->isProduct()) {
5960 $datas['picto'] = img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
5961 } elseif ($this->isService()) {
5962 $datas['picto'] = img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
5963 }
5964 if (isset($this->status) && isset($this->status_buy)) {
5965 $datas['status'] = ' '.$this->getLibStatut(5, 0) . ' '.$this->getLibStatut(5, 1);
5966 }
5967
5968 if (!empty($this->ref)) {
5969 $datas['ref'] = '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
5970 }
5971 if (!empty($this->label)) {
5972 $datas['label'] = '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label.'<br>';
5973 }
5974
5975 if ($permissiontoreadproduct) {
5976 if (!empty($this->description) && getDolGlobalString('PRODUCT_SHOW_DESCRIPTION_IN_TOOLTIP')) {
5977 $datas['description'] = '<br><b>'.$langs->trans('ProductDescription').':</b> '.dolGetFirstLineOfText($this->description, 5);
5978 }
5979
5980 $datas['stockmanaged'] = "<br><b>".$langs->trans("StockableProduct").'</b>: '.yn($this->isStockManaged());
5981
5982 if ($this->isStockManaged()) {
5983 if (isModEnabled('productbatch')) {
5984 $langs->load("productbatch");
5985 $datas['batchstatus'] = "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
5986 if ($this->status_batch) {
5987 $datas['batchdlc'] = "<br><b>".$langs->trans("BatchSellOrEatByMandatoryList", $langs->transnoentitiesnoconv("SellByDate"), $langs->transnoentitiesnoconv("EatByDate")).'</b>: '.$this->getSellOrEatByMandatoryLabel();
5988 }
5989 }
5990 }
5991 if (isModEnabled('barcode')) {
5992 $datas['barcode'] = '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
5993 }
5994
5995 if ($this->isProduct()) {
5996 if ($this->weight) {
5997 $datas['weight'] = "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
5998 }
5999 $labelsize = "";
6000 if ($this->length) {
6001 $labelsize .= "<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
6002 }
6003 if ($this->width) {
6004 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
6005 }
6006 if ($this->height) {
6007 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
6008 }
6009 if ($labelsize) {
6010 $datas['size'] = "<br>".$labelsize;
6011 }
6012
6013 $labelsurfacevolume = "";
6014 if ($this->surface) {
6015 $labelsurfacevolume .= "<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
6016 }
6017 if ($this->volume) {
6018 $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
6019 }
6020 if ($labelsurfacevolume) {
6021 $datas['surface'] = "<br>" . $labelsurfacevolume;
6022 }
6023 }
6024 if ($this->isService() && !empty($this->duration_value)) {
6025 // Duration
6026 $datas['duration'] = '<br><b>'.$langs->trans("Duration").':</b> '.$this->duration_value;
6027 if ($this->duration_value > 1) {
6028 $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"));
6029 } elseif ($this->duration_value > 0) {
6030 $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"));
6031 }
6032 $datas['duration'] .= (!empty($this->duration_unit) && isset($dur[$this->duration_unit]) ? "&nbsp;".$langs->trans($dur[$this->duration_unit]) : '');
6033 }
6034 if (empty($user->socid)) {
6035 if ($this->isStockManaged() && isset($this->pmp) && $this->pmp) {
6036 $datas['pmp'] = "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
6037 }
6038
6039 if (isModEnabled('accounting')) {
6040 if ($this->status && isset($this->accountancy_code_sell)) {
6041 include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
6042 $selllabel = '<br>';
6043 $selllabel .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
6044 $selllabel .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
6045 $selllabel .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
6046 $datas['accountancysell'] = $selllabel;
6047 }
6048 if ($this->status_buy && isset($this->accountancy_code_buy)) {
6049 include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
6050 $buylabel = '';
6051 if (empty($this->status)) {
6052 $buylabel .= '<br>';
6053 }
6054 $buylabel .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
6055 $buylabel .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
6056 $buylabel .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
6057 $datas['accountancybuy'] = $buylabel;
6058 }
6059 }
6060 }
6061 // show categories for this record only in ajax to not overload lists
6062 if (isModEnabled('category') && !$nofetch) {
6063 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
6064 $form = new Form($this->db);
6065 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_PRODUCT, 1);
6066 }
6067 }
6068
6069 return $datas;
6070 }
6071
6085 public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
6086 {
6087 global $langs, $hookmanager;
6088
6089 include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
6090
6091 $result = '';
6092
6093 $newref = (string) $this->ref;
6094 if ($maxlength) {
6095 $newref = dol_trunc($newref, $maxlength, 'middle');
6096 }
6097 $params = [
6098 'id' => $this->id,
6099 'objecttype' => ($this->type == 1 ? 'service' : 'product'),
6100 'option' => $option,
6101 'nofetch' => 1,
6102 ];
6103 $classfortooltip = 'classfortooltip';
6104 $dataparams = '';
6105 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
6106 $classfortooltip = 'classforajaxtooltip';
6107 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
6108 $label = '';
6109 } else {
6110 $label = implode($this->getTooltipContentArray($params));
6111 }
6112
6113 $linkclose = '';
6114 if (empty($notooltip)) {
6115 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
6116 $label = $langs->trans("ShowProduct");
6117 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1, 1).'"';
6118 }
6119 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1, 1).'"' : ' title="tocomplete"');
6120 $linkclose .= $dataparams.' class="nowraponall '.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
6121 } else {
6122 $linkclose = ' class="nowraponall'.($morecss ? ' '.$morecss : '').'"';
6123 }
6124
6125 if ($option == 'supplier' || $option == 'category') {
6126 $url = DOL_URL_ROOT.'/product/price_suppliers.php?id='.$this->id;
6127 } elseif ($option == 'stock') {
6128 $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
6129 } elseif ($option == 'composition') {
6130 $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
6131 } else {
6132 $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
6133 }
6134
6135 if ($option !== 'nolink') {
6136 // Add param to save lastsearch_values or not
6137 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
6138 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
6139 $add_save_lastsearch_values = 1;
6140 }
6141 if ($add_save_lastsearch_values) {
6142 $url .= '&save_lastsearch_values=1';
6143 }
6144 }
6145
6146 $linkstart = '<a href="'.$url.'"';
6147 $linkstart .= $linkclose.'>';
6148 $linkend = '</a>';
6149
6150 $result .= $linkstart;
6151 if ($withpicto) {
6152 if ($this->isProduct()) {
6153 $result .= (img_object(($notooltip ? '' : $label), 'product', 'class="paddingright"', 0, 0, $notooltip ? 0 : 1));
6154 }
6155 if ($this->isService()) {
6156 $result .= (img_object(($notooltip ? '' : $label), 'service', 'class="paddingright"', 0, 0, $notooltip ? 0 : 1));
6157 }
6158 }
6159 $result .= '<span class="aaa">'.dol_escape_htmltag($newref).'</span>';
6160 $result .= $linkend;
6161 if ($withpicto != 2) {
6162 $result .= (($add_label && $this->label) ? $sep.dol_trunc($this->label, ($add_label > 1 ? $add_label : 0)) : '');
6163 }
6164
6165 global $action;
6166 $hookmanager->initHooks(array('productdao'));
6167 $parameters = array('id' => $this->id, 'getnomurl' => &$result, 'label' => &$label);
6168 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6169 if ($reshook > 0) {
6170 $result = $hookmanager->resPrint;
6171 } else {
6172 $result .= $hookmanager->resPrint;
6173 }
6174
6175 return $result;
6176 }
6177
6178
6189 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
6190 {
6191 global $langs;
6192
6193 $langs->load("products");
6194 $outputlangs->load("products");
6195
6196 if (!dol_strlen($modele)) {
6197 $modele = ''; // No doc template/generation by default
6198
6199 if (!empty($this->model_pdf)) {
6200 $modele = $this->model_pdf;
6201 } elseif (getDolGlobalString('PRODUCT_ADDON_PDF')) {
6202 $modele = getDolGlobalString('PRODUCT_ADDON_PDF');
6203 }
6204 }
6205
6206 if (empty($modele)) {
6207 return 0;
6208 } else {
6209 $modelpath = "core/modules/product/doc/";
6210 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
6211 }
6212 }
6213
6221 public function getLibStatut($mode = 0, $type = 0)
6222 {
6223 switch ($type) {
6224 case 0:
6225 return $this->LibStatut($this->status, $mode, $type);
6226 case 1:
6227 return $this->LibStatut($this->status_buy, $mode, $type);
6228 case 2:
6229 return $this->LibStatut($this->status_batch, $mode, $type);
6230 default:
6231 //Simulate previous behavior but should return an error string
6232 return $this->LibStatut($this->status_buy, $mode, $type);
6233 }
6234 }
6235
6236 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6245 public function LibStatut($status, $mode = 0, $type = 0)
6246 {
6247 // phpcs:enable
6248 global $langs;
6249
6250 $labelStatus = $labelStatusShort = '';
6251
6252 $langs->load('products');
6253 if (isModEnabled('productbatch')) {
6254 $langs->load("productbatch");
6255 }
6256
6257 if ($type == 2) {
6258 switch ($mode) {
6259 case 0:
6260 $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
6261 return dolGetStatus($label);
6262 case 1:
6263 $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
6264 return dolGetStatus($label);
6265 case 2:
6266 return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
6267 case 3:
6268 return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
6269 case 4:
6270 return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
6271 case 5:
6272 return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
6273 default:
6274 return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
6275 }
6276 }
6277
6278 $statuttrans = empty($status) ? 'status5' : 'status4';
6279
6280 if ($status == 0) {
6281 // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
6282 if ($type == 0) {
6283 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
6284 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
6285 } elseif ($type == 1) {
6286 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
6287 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
6288 } elseif ($type == 2) {
6289 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
6290 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
6291 }
6292 } elseif ($status == 1) {
6293 // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
6294 if ($type == 0) {
6295 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
6296 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
6297 } elseif ($type == 1) {
6298 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
6299 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
6300 } elseif ($type == 2) {
6301 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBatch');
6302 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBatchShort');
6303 }
6304 } elseif ($type == 2 && $status == 2) {
6305 $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
6306 $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
6307 }
6308
6309 if ($mode > 6) {
6310 return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
6311 } else {
6312 return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
6313 }
6314 }
6315
6316
6322 public function getLibFinished()
6323 {
6324 global $langs;
6325
6326 $langs->load('products');
6327 $label = '';
6328
6329 if (isset($this->finished) && $this->finished >= 0) {
6330 $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
6331 $resql = $this->db->query($sql);
6332 if (!$resql) {
6333 $this->error = $this->db->error().' sql='.$sql;
6334 dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
6335 return -1;
6336 } elseif ($this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
6337 $label = $langs->trans($res['label']);
6338 }
6339 $this->db->free($resql);
6340 }
6341
6342 return $label;
6343 }
6344
6345
6346 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6363 public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
6364 {
6365 // phpcs:enable
6366 if ($id_entrepot) {
6367 $this->db->begin();
6368
6369 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
6370
6371 // Ensure $nbpiece is a number and positive
6372 $nbpiece = (float) $nbpiece;
6373 if ($nbpiece < 0) {
6374 if (!$movement) {
6375 $movement = 1;
6376 }
6377 $nbpiece = abs($nbpiece);
6378 }
6379 $op = array();
6380 $op[0] = $nbpiece;
6381 $op[1] = -$nbpiece;
6382
6383 $movementstock = new MouvementStock($this->db);
6384 $movementstock->setOrigin($origin_element, (int) $origin_id); // Set ->origin_type and ->origin_id
6385 $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
6386
6387 if ($result >= 0) {
6388 if ($extrafields) {
6389 $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
6390 $movementstock->array_options = $array_options;
6391 $movementstock->insertExtraFields();
6392 }
6393 $this->db->commit();
6394 return 1;
6395 } else {
6396 $this->setErrorsFromObject($movementstock);
6397
6398 $this->db->rollback();
6399 return -1;
6400 }
6401 }
6402
6403 return -1;
6404 }
6405
6406 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6427 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)
6428 {
6429 // phpcs:enable
6430 if ($id_entrepot) {
6431 $this->db->begin();
6432
6433 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
6434
6435 // Ensure $nbpiece is a number and positive
6436 $nbpiece = (float) $nbpiece;
6437 if ($nbpiece < 0) {
6438 if (!$movement) {
6439 $movement = 1;
6440 }
6441 $nbpiece = abs($nbpiece);
6442 }
6443
6444 $op = array();
6445 $op[0] = $nbpiece;
6446 $op[1] = -$nbpiece;
6447
6448 $movementstock = new MouvementStock($this->db);
6449 $movementstock->setOrigin($origin_element, (int) $origin_id); // Set ->origin_type and ->fk_origin
6450 $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct, 0, $force_update_batch);
6451
6452 if ($result >= 0) {
6453 if ($extrafields) {
6454 $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
6455 $movementstock->array_options = $array_options;
6456 $movementstock->insertExtraFields();
6457 }
6458 $this->db->commit();
6459 return 1;
6460 } else {
6461 $this->error = $movementstock->error;
6462 $this->errors = $movementstock->errors;
6463
6464 $this->db->rollback();
6465 return -1;
6466 }
6467 }
6468 return -1;
6469 }
6470
6471 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6484 public function load_stock($option = '', $includedraftpoforvirtual = null, $dateofvirtualstock = null)
6485 {
6486 // phpcs:enable
6487 $this->stock_reel = 0;
6488 $this->stock_warehouse = array();
6489 $this->stock_theorique = 0;
6490
6491 // Set filter on warehouse status
6492 $warehouseStatus = array();
6493 if (preg_match('/warehouseclosed/', $option)) {
6495 }
6496 if (preg_match('/warehouseopen/', $option)) {
6498 }
6499 if (preg_match('/warehouseinternal/', $option)) {
6500 if (getDolGlobalString('ENTREPOT_EXTRA_STATUS')) {
6502 } else {
6504 }
6505 }
6506
6507 $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
6508 $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
6509 $sql .= ", ".$this->db->prefix()."entrepot as w";
6510 $sql .= " WHERE w.entity IN (".getEntity('stock').")";
6511 $sql .= " AND w.rowid = ps.fk_entrepot";
6512 $sql .= " AND ps.fk_product = ".((int) $this->id);
6513 if (count($warehouseStatus)) {
6514 $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
6515 }
6516
6517 $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;
6518
6519 dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
6520 $result = $this->db->query($sql);
6521 if ($result) {
6522 $num = $this->db->num_rows($result);
6523 $i = 0;
6524 if ($num > 0) {
6525 while ($i < $num) {
6526 $row = $this->db->fetch_object($result);
6527 $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
6528 $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
6529 $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
6530 if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
6531 $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
6532 }
6533 $this->stock_reel += $row->reel;
6534 $i++;
6535 }
6536 $this->stock_reel = (float) price2num($this->stock_reel, 'MS');
6537 }
6538 $this->db->free($result);
6539
6540 if (!preg_match('/novirtual/', $option)) {
6541 $this->load_virtual_stock($includedraftpoforvirtual, $dateofvirtualstock); // This load stock_theorique and also load all arrays stats_xxx...
6542 }
6543
6544 return 1;
6545 } else {
6546 $this->error = $this->db->lasterror();
6547 return -1;
6548 }
6549 }
6550
6551
6552 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6562 public function load_virtual_stock($includedraftpoforvirtual = null, $dateofvirtualstock = null)
6563 {
6564 // phpcs:enable
6565 global $hookmanager, $action;
6566
6567 $stock_commande_client = 0;
6568 $stock_commande_fournisseur = 0;
6569 $stock_sending_client = 0;
6570 $stock_reception_fournisseur = 0;
6571 $stock_inproduction = 0;
6572
6573 //dol_syslog("load_virtual_stock");
6574
6575 if (isModEnabled('order')) {
6576 $result = $this->load_stats_commande(0, '1,2', 1);
6577 if ($result < 0) {
6578 dol_print_error($this->db, $this->error);
6579 }
6580 $stock_commande_client = $this->stats_commande['qty'];
6581 }
6582 if (isModEnabled("shipping")) {
6583 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
6584 $filterShipmentStatus = '';
6585 if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT')) {
6586 $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
6587 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
6588 $filterShipmentStatus = Expedition::STATUS_CLOSED;
6589 }
6590 $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
6591 if ($result < 0) {
6592 dol_print_error($this->db, $this->error);
6593 }
6594 $stock_sending_client = $this->stats_expedition['qty'];
6595 }
6596 // Include supplier order lines
6597 if (isModEnabled("supplier_order")) {
6598 $filterStatus = getDolGlobalString('SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK', '3,4');
6599 if (isset($includedraftpoforvirtual)) {
6600 $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
6601 }
6602 $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1, $dateofvirtualstock);
6603 if ($result < 0) {
6604 dol_print_error($this->db, $this->error);
6605 }
6606 $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
6607 }
6608 // Include reception lines
6609 if (isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) {
6610 $filterStatus = getDolGlobalString('SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK', '4');
6611 if (isset($includedraftpoforvirtual)) {
6612 $filterStatus = '0,'.$filterStatus;
6613 }
6614 $result = $this->load_stats_reception(0, $filterStatus, 1, $dateofvirtualstock);
6615 if ($result < 0) {
6616 dol_print_error($this->db, $this->error);
6617 }
6618 $stock_reception_fournisseur = $this->stats_reception['qty'];
6619 }
6620 // Include manufacturing
6621 if (isModEnabled('mrp')) {
6622 $result = $this->load_stats_inproduction(0, '1,2', 1, $dateofvirtualstock);
6623 if ($result < 0) {
6624 dol_print_error($this->db, $this->error);
6625 }
6626 $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
6627 }
6628
6629 $this->stock_theorique = $this->stock_reel + $stock_inproduction;
6630
6631 // $weBillOrderOrShipmentReception is set to 'order' or 'shipmentreception'. it will be used to know how to make virtual stock
6632 // calculation when we have a stock increase or decrease on billing. Do we have to count orders to bill or shipment/reception to bill ?
6633 $weBillOrderOrShipmentReception = getDolGlobalString('STOCK_DO_WE_BILL_ORDER_OR_SHIPMENTECEPTION_FOR_VIRTUALSTOCK', 'order');
6634
6635 // Stock decrease mode
6636 if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
6637 $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
6638 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER')) {
6639 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
6640 $tmpnewprod = dol_clone($this, 1);
6641 $result = $tmpnewprod->load_stats_commande(0, '0', 1); // Get qty in draft orders
6642 $this->stock_theorique += $tmpnewprod->stats_commande['qty'];
6643 }
6644 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $weBillOrderOrShipmentReception == 'order') {
6645 $this->stock_theorique -= $stock_commande_client;
6646 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_BILL') && $weBillOrderOrShipmentReception == 'shipmentreception') {
6647 $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
6648 }
6649
6650 // Stock Increase mode
6651 if (getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE')) {
6652 $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
6653 } 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
6654 $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
6655 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER')) { // Warning: stock change "on approval", not on validation !
6656 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
6657 $tmpnewprod = dol_clone($this, 1);
6658 $result = $tmpnewprod->load_stats_commande_fournisseur(0, '0', 1); // Get qty in draft orders
6659 $this->stock_theorique += $this->stats_commande_fournisseur['qty'];
6660 }
6661 $this->stock_theorique -= $stock_reception_fournisseur;
6662 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $weBillOrderOrShipmentReception == 'order') {
6663 $this->stock_theorique += $stock_commande_fournisseur;
6664 } elseif (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') && $weBillOrderOrShipmentReception == 'shipmentreception') {
6665 $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
6666 }
6667
6668 $parameters = array('id' => $this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
6669 // Note that $action and $object may have been modified by some hooks
6670 $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
6671 if ($reshook > 0) {
6672 $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
6673 } elseif ($reshook == 0 && isset($hookmanager->resArray['stock_stats_hook'])) {
6674 $this->stock_theorique += $hookmanager->resArray['stock_stats_hook'];
6675 }
6676
6677 //Virtual Stock by Warehouse
6678 if (!empty($this->stock_warehouse) && getDolGlobalString('STOCK_ALLOW_VIRTUAL_STOCK_PER_WAREHOUSE')) {
6679 foreach ($this->stock_warehouse as $warehouseid => $stockwarehouse) {
6680 if (isModEnabled('mrp')) {
6681 $result = $this->load_stats_inproduction(0, '1,2', 1, $dateofvirtualstock, $warehouseid);
6682 if ($result < 0) {
6683 dol_print_error($this->db, $this->error);
6684 }
6685 }
6686
6687 if ($this->fk_default_warehouse == $warehouseid) {
6688 $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']);
6689 } else {
6690 $this->stock_warehouse[$warehouseid]->virtual = $this->stock_warehouse[$warehouseid]->real + $this->stock_warehouse[$warehouseid]->stats_mrptoproduce['qty'];
6691 }
6692 }
6693 }
6694
6695 return 1;
6696 }
6697
6705 public function loadStockForVirtualProduct($option = '', $qtyWish = 1)
6706 {
6707 $this->stock_warehouse = array();
6708 $error = 0;
6709
6710 $this->get_sousproduits_arbo();
6711 $prods_arbo = $this->get_arbo_each_prod($qtyWish, 1);
6712 if (count($prods_arbo) > 0) {
6713 $productCachedList = array();
6714 $stockByComponentList = array();
6715
6716 foreach ($prods_arbo as $componentArr) {
6717 $componentId = $componentArr['id'];
6718 // only component whose manage stock
6719 if ($componentArr['incdec'] == 1) {
6720 if (!isset($productCachedList[$componentId])) {
6721 $componentStatic = new self($this->db);
6722 $componentStatic->fetch($componentId);
6723 // check if it's a sub-kit
6724 $childrenNb = $componentStatic->hasFatherOrChild(1);
6725 if ($childrenNb == 0) {
6726 $componentStatic->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
6727 if (!isset($stockByComponentList[$componentId])) {
6728 $stockByComponentList[$componentId] = array(
6729 'qty_need' => 0
6730 );
6731 }
6732 $stockByComponentList[$componentId]['qty_need'] += $componentArr['nb_total'];
6733 }
6734 $productCachedList[$componentId] = $componentStatic;
6735 }
6736 }
6737 }
6738
6739 if (!empty($stockByComponentList)) {
6740 foreach ($stockByComponentList as $componentId => $stockByComponentArr) {
6741 if (!isset($productCachedList[$componentId])) {
6742 $componentStatic = new self($this->db);
6743 $componentStatic->fetch($componentId);
6744 $componentStatic->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
6745 $productCachedList[$componentId] = $componentStatic;
6746 }
6747 $component = $productCachedList[$componentId];
6748
6749
6750 if ($component->stock_reel < $stockByComponentArr['qty_need']) {
6751 // not enough stock for this component to assemble this virtual product
6752 $error++;
6753 $this->error = 'Not enough component [id='.$componentId.'] in stock, real='.$component->stock_reel.' and need='.$stockByComponentArr['qty_need'];
6754 $this->errors[] = $this->error;
6755 dol_syslog(__METHOD__.' : '.$this->error, LOG_ERR);
6756 } else {
6757 if (!empty($component->stock_warehouse)) {
6758 foreach ($component->stock_warehouse as $warehouseId => $warehouseObj) {
6759 $kitWarehouseAvailable = new stdClass();
6760 $kitWarehouseAvailable->id = $warehouseObj->id;
6761 $kitWarehouseAvailable->real = $qtyWish;
6762 $this->stock_warehouse[$warehouseId] = $kitWarehouseAvailable;
6763 }
6764 }
6765 }
6766
6767 if ($error) {
6768 break;
6769 }
6770 }
6771 } elseif (getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE') && empty($productCachedList)) {
6772 // if all sub product are not stock managed when use parent stock
6773 $this->load_stock('warehouseopen');
6774 }
6775 }
6776
6777 if ($error) {
6778 return -1;
6779 } else {
6780 return 1;
6781 }
6782 }
6783
6791 public function loadBatchInfo($batch)
6792 {
6793 $result = array();
6794
6795 // 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)
6796 $sql = "SELECT pb.batch, pl.eatby, pl.sellby, SUM(pb.qty) AS qty FROM ".$this->db->prefix()."product_batch as pb";
6797 $sql .= " INNER JOIN ".$this->db->prefix()."product_stock as ps ON pb.fk_product_stock = ps.rowid";
6798 $sql .= " LEFT JOIN ".$this->db->prefix()."product_lot as pl ON pl.fk_product = ps.fk_product AND pl.batch = pb.batch";
6799 $sql .= " WHERE ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
6800 $sql .= " GROUP BY pb.batch, pl.eatby, pl.sellby";
6801 dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
6802 $resql = $this->db->query($sql);
6803 if ($resql) {
6804 $num = $this->db->num_rows($resql);
6805 $i = 0;
6806 while ($i < $num) {
6807 $obj = $this->db->fetch_object($resql);
6808 $result[] = array('batch' => $batch, 'eatby' => $this->db->jdate($obj->eatby), 'sellby' => $this->db->jdate($obj->sellby), 'qty' => $obj->qty);
6809 $i++;
6810 }
6811 return $result;
6812 } else {
6813 dol_print_error($this->db);
6814 $this->db->rollback();
6815 return array();
6816 }
6817 }
6818
6819 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6828 public function add_photo($sdir, $file)
6829 {
6830 // phpcs:enable
6831 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6832
6833 $result = 0;
6834
6835 $dir = $sdir;
6836 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
6837 $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
6838 } else {
6839 $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
6840 }
6841
6842 dol_mkdir($dir);
6843
6844 $dir_osencoded = $dir;
6845
6846 if (is_dir($dir_osencoded)) {
6847 $originImage = $dir.'/'.$file['name'];
6848
6849 // Cree fichier en taille origine
6850 $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
6851
6852 if (file_exists(dol_osencode($originImage))) {
6853 // Create thumbs
6854 $this->addThumbs($originImage);
6855 }
6856 }
6857
6858 if (is_numeric($result) && $result > 0) {
6859 return 1;
6860 } else {
6861 return -1;
6862 }
6863 }
6864
6865 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6872 public function is_photo_available($sdir)
6873 {
6874 // phpcs:enable
6875 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6876 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6877
6878 $dir = $sdir;
6879 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
6880 $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
6881 } else {
6882 $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
6883 }
6884
6885 $dir_osencoded = dol_osencode($dir);
6886 if (file_exists($dir_osencoded)) {
6887 $handle = opendir($dir_osencoded);
6888 if (is_resource($handle)) {
6889 while (($file = readdir($handle)) !== false) {
6890 if (!utf8_check($file)) {
6891 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
6892 }
6893 if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
6894 return true;
6895 }
6896 }
6897 }
6898 }
6899
6900 return false;
6901 }
6902
6903 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6911 public function liste_photos($dir, $nbmax = 0)
6912 {
6913 // phpcs:enable
6914 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6915 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6916
6917 $nbphoto = 0;
6918 $tabobj = array();
6919
6920 $dir_osencoded = dol_osencode($dir);
6921 $handle = @opendir($dir_osencoded);
6922 if (is_resource($handle)) {
6923 while (($file = readdir($handle)) !== false) {
6924 if (!utf8_check($file)) {
6925 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // readdir returns ISO
6926 }
6927 if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
6928 $nbphoto++;
6929
6930 // We forge name of thumb.
6931 $photo = $file;
6932 $photo_vignette = '';
6933 $regs = array();
6934 if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
6935 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
6936 }
6937
6938 $dirthumb = $dir.'thumbs/';
6939
6940 // Object
6941 $obj = array();
6942 $obj['photo'] = $photo;
6943 if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
6944 $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
6945 } else {
6946 $obj['photo_vignette'] = "";
6947 }
6948
6949 $tabobj[$nbphoto - 1] = $obj;
6950
6951 // Do we have to continue with next photo ?
6952 if ($nbmax && $nbphoto >= $nbmax) {
6953 break;
6954 }
6955 }
6956 }
6957
6958 closedir($handle);
6959 }
6960
6961 return $tabobj;
6962 }
6963
6964 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6971 public function delete_photo($file)
6972 {
6973 // phpcs:enable
6974 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6975 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6976
6977 $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
6978 $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
6979 $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
6980
6981 // On efface l'image d'origine
6982 dol_delete_file($file, 0, 0, 0, $this); // For triggers
6983
6984 // Si elle existe, on efface la vignette
6985 if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
6986 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
6987 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
6988 dol_delete_file($dirthumb.$photo_vignette);
6989 }
6990
6991 $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
6992 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
6993 dol_delete_file($dirthumb.$photo_vignette);
6994 }
6995 }
6996 }
6997
6998 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7005 public function get_image_size($file)
7006 {
7007 // phpcs:enable
7008 $file_osencoded = dol_osencode($file);
7009 $infoImg = getimagesize($file_osencoded); // Get information on image
7010 $this->imgWidth = $infoImg[0]; // Largeur de l'image
7011 $this->imgHeight = $infoImg[1]; // Hauteur de l'image
7012 }
7013
7019 public function loadStateBoard()
7020 {
7021 global $hookmanager;
7022
7023 $this->nb = array();
7024
7025 $sql = "SELECT count(p.rowid) as nb, fk_product_type";
7026 $sql .= " FROM ".$this->db->prefix()."product as p";
7027 $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
7028 // Add where from hooks
7029 if (is_object($hookmanager)) {
7030 $parameters = array();
7031 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
7032 $sql .= $hookmanager->resPrint;
7033 }
7034 $sql .= ' GROUP BY fk_product_type';
7035
7036 $resql = $this->db->query($sql);
7037 if ($resql) {
7038 while ($obj = $this->db->fetch_object($resql)) {
7039 if ($obj->fk_product_type == 1) {
7040 $this->nb["services"] = $obj->nb;
7041 } else {
7042 $this->nb["products"] = $obj->nb;
7043 }
7044 }
7045 $this->db->free($resql);
7046 return 1;
7047 } else {
7048 dol_print_error($this->db);
7049 $this->error = $this->db->error();
7050 return -1;
7051 }
7052 }
7053
7059 public function isProduct()
7060 {
7061 return $this->type == Product::TYPE_PRODUCT;
7062 }
7063
7069 public function isService()
7070 {
7071 return $this->type == Product::TYPE_SERVICE;
7072 }
7073
7079 public function isStockManaged()
7080 {
7081 return (($this->isProduct() || ($this->isService() && getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) && ($this->stockable_product > 0));
7082 }
7083
7089 public function isMandatoryPeriod()
7090 {
7091 return $this->mandatory_period == 1;
7092 }
7093
7099 public function hasbatch()
7100 {
7101 return $this->status_batch > 0;
7102 }
7103
7104
7105 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7114 public function get_barcode($object, $type = '')
7115 {
7116 // phpcs:enable
7117 global $conf;
7118
7119 $result = '';
7120 if (getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM')) {
7121 $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
7122 foreach ($dirsociete as $dirroot) {
7123 $res = dol_include_once($dirroot . getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM').'.php');
7124 if ($res) {
7125 break;
7126 }
7127 }
7128 $var = getDolGlobalString('BARCODE_PRODUCT_ADDON_NUM');
7129 $mod = new $var();
7130 '@phan-var-force ModeleNumRefBarCode $mod';
7131
7132 $result = $mod->getNextValue($object, $type);
7133
7134 dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
7135 }
7136 return $result;
7137 }
7138
7146 public function initAsSpecimen()
7147 {
7148 $now = dol_now();
7149
7150 // Initialize parameters
7151 $this->specimen = 1;
7152 $this->id = 0;
7153 $this->ref = 'PRODUCT_SPEC';
7154 $this->label = 'PRODUCT SPECIMEN';
7155 $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
7156 $this->specimen = 1;
7157 $this->country_id = 1;
7158 $this->status = 1;
7159 $this->status_buy = 1;
7160 $this->tobatch = 0;
7161 $this->sell_or_eat_by_mandatory = 0;
7162 $this->note_private = 'This is a comment (private)';
7163 $this->note_public = 'This is a comment (public)';
7164 $this->date_creation = $now;
7165 $this->date_modification = $now;
7166
7167 $this->weight = 4;
7168 $this->weight_units = 3;
7169
7170 $this->length = 5;
7171 $this->length_units = 1;
7172 $this->width = 6;
7173 $this->width_units = 0;
7174 $this->height = null;
7175 $this->height_units = null;
7176
7177 $this->surface = 30;
7178 $this->surface_units = 0;
7179 $this->volume = 300;
7180 $this->volume_units = 0;
7181
7182 $this->barcode = -1; // Create barcode automatically
7183
7184 return 1;
7185 }
7186
7196 public function getLabelOfUnit($type = 'long', $outputlangs = null, $noentities = 0)
7197 {
7198 global $langs;
7199
7200 if (empty($this->fk_unit)) {
7201 return '';
7202 }
7203 if (empty($outputlangs)) {
7204 $outputlangs = $langs;
7205 }
7206
7207 $outputlangs->load('products');
7208 $label = '';
7209
7210 $sql = "SELECT code, label, short_label FROM ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
7211
7212 $resql = $this->db->query($sql);
7213 if (!$resql) {
7214 $this->error = $this->db->error();
7215 dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
7216 return -1;
7217 } elseif ($this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
7218 if ($type == 'short') {
7219 if ($noentities) {
7220 $label = $outputlangs->transnoentitiesnoconv($res['short_label']);
7221 } else {
7222 $label = $outputlangs->trans($res['short_label']);
7223 }
7224 } elseif ($type == 'code') {
7225 $label = $res['code'];
7226 } else {
7227 if ($outputlangs->trans('unit'.$res['code']) == 'unit'.$res['code']) {
7228 // No translation available
7229 $label = $res['label'];
7230 } else {
7231 // Return the translated value
7232 if ($noentities) {
7233 $label = $outputlangs->transnoentitiesnoconv('unit'.$res['code']);
7234 } else {
7235 $label = $outputlangs->trans('unit'.$res['code']);
7236 }
7237 }
7238 }
7239 }
7240 $this->db->free($resql);
7241
7242 return $label;
7243 }
7244
7245 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7251 public function min_recommended_price()
7252 {
7253 // phpcs:enable
7254 $maxpricesupplier = 0;
7255
7256 if (getDolGlobalString('PRODUCT_MINIMUM_RECOMMENDED_PRICE')) {
7257 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
7258 $product_fourn = new ProductFournisseur($this->db);
7259 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
7260
7261 if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
7262 foreach ($product_fourn_list as $productfourn) {
7263 if ($productfourn->fourn_unitprice > $maxpricesupplier) {
7264 $maxpricesupplier = $productfourn->fourn_unitprice;
7265 }
7266 }
7267
7268 $maxpricesupplier *= getDolGlobalString('PRODUCT_MINIMUM_RECOMMENDED_PRICE');
7269 }
7270 }
7271
7272 return $maxpricesupplier;
7273 }
7274
7275
7286 public function setCategories($categories)
7287 {
7288 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7289 return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
7290 }
7291
7300 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
7301 {
7302 /* we firstly delete origin product prices existing in destination before update */
7303 $sql = " DELETE FROM ".$dbs->prefix()."product_customer_price";
7304 $sql .= " WHERE fk_soc = ".(int) $origin_id;
7305 $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)";
7306 //$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.')';
7307
7308 if (!$dbs->query($sql)) {
7309 return false;
7310 }
7311
7312 $tables = array(
7313 'product_customer_price',
7314 'product_customer_price_log'
7315 );
7316
7317 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
7318 }
7319
7331 public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
7332 {
7333 $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
7334 $query = $this->db->query($sql);
7335
7336 $rules = array();
7337
7338 while ($result = $this->db->fetch_object($query)) {
7339 $rules[$result->level] = $result;
7340 }
7341
7342 //Because prices can be based on other level's prices, we temporarily store them
7343 $prices = array(
7344 1 => $baseprice
7345 );
7346
7347 $nbofproducts = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
7348 for ($i = 1; $i <= $nbofproducts; $i++) {
7349 $price = $baseprice;
7350 $price_min = $baseprice;
7351
7352 //We have to make sure it does exist and it is > 0
7353 //First price level only allows changing min_price
7354 if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
7355 $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
7356 }
7357
7358 $prices[$i] = $price;
7359
7360 //We have to make sure it does exist and it is > 0
7361 if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
7362 $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
7363 }
7364
7365 //Little check to make sure the price is modified before triggering generation
7366 $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
7367 $check_type = ($baseprice == $this->multiprices_base_type[$i]);
7368
7369 if ($check_amount && $check_type) {
7370 continue;
7371 }
7372
7373 if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, 1) < 0) {
7374 return -1;
7375 }
7376 }
7377
7378 return 1;
7379 }
7380
7386 public function getRights()
7387 {
7388 global $user;
7389
7390 if ($this->isProduct()) {
7391 return $user->rights->produit;
7392 } else {
7393 return $user->rights->service;
7394 }
7395 }
7396
7403 public function info($id)
7404 {
7405 $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, GREATEST(p.tms, COALESCE(pef.tms, p.tms)) as date_modification,";
7406 $sql .= " p.fk_user_author, p.fk_user_modif";
7407 $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
7408 $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as pef ON pef.fk_object=p.rowid";
7409 $sql .= " WHERE p.rowid = ".((int) $id);
7410
7411 $result = $this->db->query($sql);
7412 if ($result) {
7413 if ($this->db->num_rows($result)) {
7414 $obj = $this->db->fetch_object($result);
7415
7416 $this->id = $obj->rowid;
7417 $this->ref = $obj->ref;
7418
7419 $this->user_creation_id = $obj->fk_user_author;
7420 $this->user_modification_id = $obj->fk_user_modif;
7421
7422 $this->date_creation = $this->db->jdate($obj->date_creation);
7423 $this->date_modification = $this->db->jdate($obj->date_modification);
7424 }
7425
7426 $this->db->free($result);
7427 } else {
7428 dol_print_error($this->db);
7429 }
7430 }
7431
7432
7438 public function getProductDurationHours()
7439 {
7440 if (empty($this->duration_value)) {
7441 $this->errors[] = 'ErrorDurationForServiceNotDefinedCantCalculateHourlyPrice';
7442 return -1;
7443 }
7444 if ($this->duration_unit == 's') {
7445 $prodDurationHours = 1. / 3600;
7446 } elseif ($this->duration_unit == 'i' || $this->duration_unit == 'mn' || $this->duration_unit == 'min') {
7447 $prodDurationHours = 1. / 60;
7448 } elseif ($this->duration_unit == 'h') {
7449 $prodDurationHours = 1.;
7450 } elseif ($this->duration_unit == 'd') {
7451 $prodDurationHours = 24.;
7452 } elseif ($this->duration_unit == 'w') {
7453 $prodDurationHours = 24. * 7;
7454 } elseif ($this->duration_unit == 'm') {
7455 $prodDurationHours = 24. * 30;
7456 } elseif ($this->duration_unit == 'y') {
7457 $prodDurationHours = 24. * 365;
7458 } else {
7459 // Unknown unit: the duration cannot be converted. Returning 0 silently made callers
7460 // compute a zero duration, and time.php divides by this value (#40805).
7461 $this->errors[] = 'ErrorDurationForServiceNotDefinedCantCalculateHourlyPrice';
7462 return -1;
7463 }
7464 $prodDurationHours *= $this->duration_value;
7465
7466 return $prodDurationHours;
7467 }
7468
7469
7477 public function getKanbanView($option = '', $arraydata = null)
7478 {
7479 global $langs, $conf;
7480
7481 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
7482
7483 $return = '<div class="box-flex-item box-flex-grow-zero">';
7484 $return .= '<div class="info-box info-box-sm">';
7485 $return .= '<div class="info-box-img">';
7486 $label = '';
7487 if ($this->entity !== null && $this->is_photo_available($conf->product->multidir_output[$this->entity])) {
7488 $label .= $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 120, 160, 0, 0, 0, '', 'photoref photokanban');
7489 $return .= $label;
7490 } else {
7491 if ($this->isProduct()) {
7492 $label .= img_picto('', 'product');
7493 } elseif ($this->isService()) {
7494 $label .= img_picto('', 'service');
7495 }
7496 $return .= $label;
7497 }
7498 $return .= '</div>';
7499 $return .= '<div class="info-box-content">';
7500 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
7501 if ($selected >= 0) {
7502 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
7503 }
7504 $return .= '<br><span class="info-box-label opacitymedium inline-block tdoverflowmax150 valignmiddle" title="'.dol_escape_htmltag($this->label).'">'.dol_escape_htmltag($this->label).'</span>';
7505 if ($this->price_base_type == 'TTC') {
7506 $return .= '<br><span class="info-box-status amount">'.price($this->price_ttc).' '.$langs->trans("TTC").'</span>';
7507 } else {
7508 if ($this->status) {
7509 $return .= '<br><span class="info-box-status amount">'.price($this->price).' '.$langs->trans("HT").'</span>';
7510 }
7511 }
7512 $br = 1;
7513 if ($this->isProduct()) {
7514 $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>';
7515 $br = 0;
7516 }
7517 if ($br) {
7518 $return .= '<br>';
7519 $return .= '<div class="info-box-status inline-block valignmiddle">'.$this->getLibStatut(3, 1).' '.$this->getLibStatut(3, 0).'</div>';
7520 } else {
7521 $return .= '<div class="info-box-status inline-block valignmiddle marginleftonly paddingleft">'.$this->getLibStatut(3, 1).' '.$this->getLibStatut(3, 0).'</div>';
7522 }
7523 $return .= '</div>';
7524 $return .= '</div>';
7525 $return .= '</div>';
7526 return $return;
7527 }
7528}
7529
7535{
7536 public $picto = 'service';
7537}
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.
$object ref
Definition info.php:90
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
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...
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.
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.
getMultiLangs()
Load array this->multilangs.
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.
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.
getRights()
Returns the rights used for this class.
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.
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_facture($socid=0)
Charge tableau des stats facture pour le produit/service.
setCategories($categories)
Sets object to supplied categories.
load_stats_reception($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null)
Loads supplier reception statistics table for given product or service.
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.
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.
load_stats_inproduction($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null, $warehouseid=0)
Charge tableau des stats production pour le produit/service.
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)
getNomUrl($withpicto=0, $option='', $maxlength=0, $save_lastsearch_value=-1, $notooltip=0, $morecss='', $add_label=0, $sep=' - ')
Return clickable link of object (with eventually picto)
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)
min_recommended_price()
Return minimum product recommended price.
_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.
load_stats_commande_fournisseur($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null)
Charge tableau des stats commande fournisseur pour le produit/service.
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.
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 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
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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_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...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
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)
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
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)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137