dolibarr  17.0.4
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-2018 Ferran Marcet <fmarcet@2byte.es>
16  * Copyright (C) 2017 Gustavo Novaro
17  * Copyright (C) 2019-2022 Frédéric France <frederic.france@netlogic.fr>
18  *
19  * This program is free software; you can redistribute it and/or modify
20  * it under the terms of the GNU General Public License as published by
21  * the Free Software Foundation; either version 3 of the License, or
22  * (at your option) any later version.
23  *
24  * This program is distributed in the hope that it will be useful,
25  * but WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27  * GNU General Public License for more details.
28  *
29  * You should have received a copy of the GNU General Public License
30  * along with this program. If not, see <https://www.gnu.org/licenses/>.
31  */
32 
38 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
42 
46 class Product extends CommonObject
47 {
51  public $element = 'product';
52 
56  public $table_element = 'product';
57 
61  public $fk_element = 'fk_product';
62 
66  protected $childtables = array(
67  'supplier_proposaldet' => array('name' => 'SupplierProposal', 'parent' => 'supplier_proposal', 'parentkey' => 'fk_supplier_proposal'),
68  'propaldet' => array('name' => 'Proposal', 'parent' => 'propal', 'parentkey' => 'fk_propal'),
69  'commandedet' => array('name' => 'Order', 'parent' => 'commande', 'parentkey' => 'fk_commande'),
70  'facturedet' => array('name' => 'Invoice', 'parent' => 'facture', 'parentkey' => 'fk_facture'),
71  'contratdet' => array('name' => 'Contract', 'parent' => 'contrat', 'parentkey' => 'fk_contrat'),
72  'facture_fourn_det' => array('name' => 'SupplierInvoice', 'parent' => 'facture_fourn', 'parentkey' => 'fk_facture_fourn'),
73  'commande_fournisseurdet' => array('name' => 'SupplierOrder', 'parent' => 'commande_fournisseur', 'parentkey' => 'fk_commande')
74  );
75 
81  public $ismultientitymanaged = 1;
82 
86  public $picto = 'product';
87 
91  protected $table_ref_field = 'ref';
92 
93  public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php
94 
99  public $libelle;
100 
106  public $label;
107 
113  public $description;
114 
120  public $other;
121 
127  public $type = self::TYPE_PRODUCT;
128 
134  public $price;
135 
136  public $price_formated; // used by takepos/ajax/ajax.php
137 
143  public $price_ttc;
144 
145  public $price_ttc_formated; // used by takepos/ajax/ajax.php
146 
152  public $price_min;
153 
159  public $price_min_ttc;
160 
165  public $price_base_type;
166 
168  public $multiprices = array();
169  public $multiprices_ttc = array();
170  public $multiprices_base_type = array();
171  public $multiprices_min = array();
172  public $multiprices_min_ttc = array();
173  public $multiprices_tva_tx = array();
174  public $multiprices_recuperableonly = array();
175 
178  public $prices_by_qty = array();
179  public $prices_by_qty_id = array();
180  public $prices_by_qty_list = array();
181 
183  public $multilangs = array();
184 
187 
189  public $tva_tx;
190 
192  public $tva_npr = 0;
193 
196 
199  public $localtax2_tx;
200  public $localtax1_type;
201  public $localtax2_type;
202 
203  // Properties set by get_buyprice() for return
204 
205  public $desc_supplier;
206  public $vatrate_supplier;
207  public $default_vat_code_supplier;
208  public $fourn_multicurrency_price;
209  public $fourn_multicurrency_unitprice;
210  public $fourn_multicurrency_tx;
211  public $fourn_multicurrency_id;
212  public $fourn_multicurrency_code;
213  public $packaging;
214 
215 
216  public $lifetime;
217 
218  public $qc_frequency;
219 
225  public $stock_reel = 0;
226 
232  public $stock_theorique;
233 
239  public $cost_price;
240 
242  public $pmp;
243 
249  public $seuil_stock_alerte = 0;
250 
254  public $desiredstock = 0;
255 
256  /*
257  * Service expiration
258  */
259  public $duration_value;
260 
261  /*
262  * Service Workstation
263  */
264  public $fk_default_workstation;
265 
270 
276  public $status = 0;
277 
284  public $tosell;
285 
291  public $status_buy = 0;
292 
299  public $tobuy;
300 
306  public $finished;
307 
313  public $fk_default_bom;
314 
320  public $status_batch = 0;
321 
327  public $batch_mask = '';
328 
334  public $customcode;
335 
341  public $url;
342 
344  public $weight;
345  public $weight_units; // scale -3, 0, 3, 6
346  public $length;
347  public $length_units; // scale -3, 0, 3, 6
348  public $width;
349  public $width_units; // scale -3, 0, 3, 6
350  public $height;
351  public $height_units; // scale -3, 0, 3, 6
352  public $surface;
353  public $surface_units; // scale -3, 0, 3, 6
354  public $volume;
355  public $volume_units; // scale -3, 0, 3, 6
356 
357  public $net_measure;
358  public $net_measure_units; // scale -3, 0, 3, 6
359 
360  public $accountancy_code_sell;
361  public $accountancy_code_sell_intra;
362  public $accountancy_code_sell_export;
363  public $accountancy_code_buy;
364  public $accountancy_code_buy_intra;
365  public $accountancy_code_buy_export;
366 
372  public $barcode;
373 
379  public $barcode_type;
380 
386  public $barcode_type_code;
387 
388  public $stats_propale = array();
389  public $stats_commande = array();
390  public $stats_contrat = array();
391  public $stats_facture = array();
392  public $stats_commande_fournisseur = array();
393  public $stats_reception = array();
394  public $stats_mrptoconsume = array();
395  public $stats_mrptoproduce = array();
396 
398  public $imgWidth;
399  public $imgHeight;
400 
404  public $date_creation;
405 
409  public $date_modification;
410 
413 
416 
417  public $nbphoto = 0;
418 
420  public $stock_warehouse = array();
421 
422  public $oldcopy;
423 
427  public $fk_default_warehouse;
431  public $fk_price_expression;
432 
433  /* To store supplier price found */
434  public $fourn_qty;
435  public $fourn_pu;
436  public $fourn_price_base_type;
437  public $fourn_socid;
438 
443  public $ref_fourn;
444 
448  public $ref_supplier;
449 
455  public $fk_unit;
456 
462  public $price_autogen = 0;
463 
469  public $supplierprices;
470 
476  public $is_object_used;
477 
478 
484  public $mandatory_period;
485 
514  public $fields = array(
515  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
516  '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'),
517  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>5),
518  'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>2, 'position'=>15),
519  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'isModEnabled("barcode")', 'position'=>20, 'visible'=>-1, 'showoncombobox'=>3),
520  'fk_barcode_type' => array('type'=>'integer', 'label'=>'BarcodeType', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>-1,),
521  'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61),
522  'note' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62),
523  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
524  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
525  //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
526  'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
527  'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
528  //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
529  'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,),
530  'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,),
531  'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,),
532  'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,),
533  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
534  //'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')),
535  //'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')),
536  'mandatory_period' => array('type'=>'integer', 'label'=>'mandatory_period', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000),
537  );
538 
542  const TYPE_PRODUCT = 0;
546  const TYPE_SERVICE = 1;
550  const TYPE_ASSEMBLYKIT = 2;
554  const TYPE_STOCKKIT = 3;
555 
556 
562  public function __construct($db)
563  {
564  $this->db = $db;
565  $this->canvas = '';
566  }
567 
573  public function check()
574  {
575  $this->ref = dol_sanitizeFileName(stripslashes($this->ref));
576 
577  $err = 0;
578  if (dol_strlen(trim($this->ref)) == 0) {
579  $err++;
580  }
581 
582  if (dol_strlen(trim($this->label)) == 0) {
583  $err++;
584  }
585 
586  if ($err > 0) {
587  return 0;
588  } else {
589  return 1;
590  }
591  }
592 
600  public function create($user, $notrigger = 0)
601  {
602  global $conf, $langs;
603 
604  $error = 0;
605 
606  // Clean parameters
607  $this->ref = dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)));
608  $this->label = trim($this->label);
609  $this->price_ttc = price2num($this->price_ttc);
610  $this->price = price2num($this->price);
611  $this->price_min_ttc = price2num($this->price_min_ttc);
612  $this->price_min = price2num($this->price_min);
613  if (empty($this->tva_tx)) {
614  $this->tva_tx = 0;
615  }
616  if (empty($this->tva_npr)) {
617  $this->tva_npr = 0;
618  }
619  //Local taxes
620  if (empty($this->localtax1_tx)) {
621  $this->localtax1_tx = 0;
622  }
623  if (empty($this->localtax2_tx)) {
624  $this->localtax2_tx = 0;
625  }
626  if (empty($this->localtax1_type)) {
627  $this->localtax1_type = '0';
628  }
629  if (empty($this->localtax2_type)) {
630  $this->localtax2_type = '0';
631  }
632  if (empty($this->price)) {
633  $this->price = 0;
634  }
635  if (empty($this->price_min)) {
636  $this->price_min = 0;
637  }
638  // Price by quantity
639  if (empty($this->price_by_qty)) {
640  $this->price_by_qty = 0;
641  }
642 
643  if (empty($this->status)) {
644  $this->status = 0;
645  }
646  if (empty($this->status_buy)) {
647  $this->status_buy = 0;
648  }
649 
650  $price_ht = 0;
651  $price_ttc = 0;
652  $price_min_ht = 0;
653  $price_min_ttc = 0;
654 
655  //
656  if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
657  $price_ttc = price2num($this->price_ttc, 'MU');
658  $price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
659  }
660 
661  //
662  if ($this->price_base_type != 'TTC' && $this->price > 0) {
663  $price_ht = price2num($this->price, 'MU');
664  $price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
665  }
666 
667  //
668  if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
669  $price_min_ttc = price2num($this->price_min_ttc, 'MU');
670  $price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
671  }
672 
673  //
674  if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
675  $price_min_ht = price2num($this->price_min, 'MU');
676  $price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
677  }
678 
679  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
680  $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
681  $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
682  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
683  $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
684  $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
685 
686  // Barcode value
687  $this->barcode = trim($this->barcode);
688  $this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
689  // Check parameters
690  if (empty($this->label)) {
691  $this->error = 'ErrorMandatoryParametersNotProvided';
692  return -1;
693  }
694 
695  if (empty($this->ref) || $this->ref == 'auto') {
696  // Load object modCodeProduct
697  $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard');
698  if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
699  if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
700  $module = substr($module, 0, dol_strlen($module) - 4);
701  }
702  dol_include_once('/core/modules/product/'.$module.'.php');
703  $modCodeProduct = new $module;
704  if (!empty($modCodeProduct->code_auto)) {
705  $this->ref = $modCodeProduct->getNextValue($this, $this->type);
706  }
707  unset($modCodeProduct);
708  }
709 
710  if (empty($this->ref)) {
711  $this->error = 'ProductModuleNotSetupForAutoRef';
712  return -2;
713  }
714  }
715 
716  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);
717 
718  $now = dol_now();
719 
720  $this->db->begin();
721 
722  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
723  if ($this->barcode == -1) {
724  $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
725  }
726 
727  // Check more parameters
728  // If error, this->errors[] is filled
729  $result = $this->verify();
730 
731  if ($result >= 0) {
732  $sql = "SELECT count(*) as nb";
733  $sql .= " FROM ".$this->db->prefix()."product";
734  $sql .= " WHERE entity IN (".getEntity('product').")";
735  $sql .= " AND ref = '".$this->db->escape($this->ref)."'";
736 
737  $result = $this->db->query($sql);
738  if ($result) {
739  $obj = $this->db->fetch_object($result);
740  if ($obj->nb == 0) {
741  // Produit non deja existant
742  $sql = "INSERT INTO ".$this->db->prefix()."product (";
743  $sql .= "datec";
744  $sql .= ", entity";
745  $sql .= ", ref";
746  $sql .= ", ref_ext";
747  $sql .= ", price_min";
748  $sql .= ", price_min_ttc";
749  $sql .= ", label";
750  $sql .= ", fk_user_author";
751  $sql .= ", fk_product_type";
752  $sql .= ", price";
753  $sql .= ", price_ttc";
754  $sql .= ", price_base_type";
755  $sql .= ", tobuy";
756  $sql .= ", tosell";
757  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
758  $sql .= ", accountancy_code_buy";
759  $sql .= ", accountancy_code_buy_intra";
760  $sql .= ", accountancy_code_buy_export";
761  $sql .= ", accountancy_code_sell";
762  $sql .= ", accountancy_code_sell_intra";
763  $sql .= ", accountancy_code_sell_export";
764  }
765  $sql .= ", canvas";
766  $sql .= ", finished";
767  $sql .= ", tobatch";
768  $sql .= ", batch_mask";
769  $sql .= ", fk_unit";
770  $sql .= ", mandatory_period";
771  $sql .= ") VALUES (";
772  $sql .= "'".$this->db->idate($now)."'";
773  $sql .= ", ".(!empty($this->entity) ? (int) $this->entity : (int) $conf->entity);
774  $sql .= ", '".$this->db->escape($this->ref)."'";
775  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
776  $sql .= ", ".price2num($price_min_ht);
777  $sql .= ", ".price2num($price_min_ttc);
778  $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
779  $sql .= ", ".((int) $user->id);
780  $sql .= ", ".((int) $this->type);
781  $sql .= ", ".price2num($price_ht, 'MT');
782  $sql .= ", ".price2num($price_ttc, 'MT');
783  $sql .= ", '".$this->db->escape($this->price_base_type)."'";
784  $sql .= ", ".((int) $this->status);
785  $sql .= ", ".((int) $this->status_buy);
786  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
787  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
788  $sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
789  $sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
790  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
791  $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
792  $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
793  }
794  $sql .= ", '".$this->db->escape($this->canvas)."'";
795  $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
796  $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
797  $sql .= ", '".$this->db->escape($this->batch_mask)."'";
798  $sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
799  $sql .= ", '".$this->db->escape($this->mandatory_period)."'";
800  $sql .= ")";
801 
802  dol_syslog(get_class($this)."::Create", LOG_DEBUG);
803  $result = $this->db->query($sql);
804  if ($result) {
805  $id = $this->db->last_insert_id($this->db->prefix()."product");
806 
807  if ($id > 0) {
808  $this->id = $id;
809  $this->price = $price_ht;
810  $this->price_ttc = $price_ttc;
811  $this->price_min = $price_min_ht;
812  $this->price_min_ttc = $price_min_ttc;
813 
814  $result = $this->_log_price($user);
815  if ($result > 0) {
816  if ($this->update($id, $user, true, 'add') <= 0) {
817  $error++;
818  }
819  } else {
820  $error++;
821  $this->error = $this->db->lasterror();
822  }
823 
824  // update accountancy for this entity
825  if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
826  $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
827 
828  $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
829  $sql .= " fk_product";
830  $sql .= ", entity";
831  $sql .= ", accountancy_code_buy";
832  $sql .= ", accountancy_code_buy_intra";
833  $sql .= ", accountancy_code_buy_export";
834  $sql .= ", accountancy_code_sell";
835  $sql .= ", accountancy_code_sell_intra";
836  $sql .= ", accountancy_code_sell_export";
837  $sql .= ") VALUES (";
838  $sql .= $this->id;
839  $sql .= ", " . $conf->entity;
840  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
841  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
842  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
843  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
844  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
845  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
846  $sql .= ")";
847  $result = $this->db->query($sql);
848  if (!$result) {
849  $error++;
850  $this->error = 'ErrorFailedToInsertAccountancyForEntity';
851  }
852  }
853  } else {
854  $error++;
855  $this->error = 'ErrorFailedToGetInsertedId';
856  }
857  } else {
858  $error++;
859  $this->error = $this->db->lasterror();
860  }
861  } else {
862  // Product already exists with this ref
863  $langs->load("products");
864  $error++;
865  $this->error = "ErrorProductAlreadyExists";
866  }
867  } else {
868  $error++;
869  $this->error = $this->db->lasterror();
870  }
871 
872  if (!$error && !$notrigger) {
873  // Call trigger
874  $result = $this->call_trigger('PRODUCT_CREATE', $user);
875  if ($result < 0) {
876  $error++;
877  }
878  // End call triggers
879  }
880 
881  if (!$error) {
882  $this->db->commit();
883  return $this->id;
884  } else {
885  $this->db->rollback();
886  return -$error;
887  }
888  } else {
889  $this->db->rollback();
890  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
891  return -3;
892  }
893  }
894 
895 
902  public function verify()
903  {
904  global $langs;
905 
906  $this->errors = array();
907 
908  $result = 0;
909  $this->ref = trim($this->ref);
910 
911  if (!$this->ref) {
912  $this->errors[] = 'ErrorBadRef';
913  $result = -2;
914  }
915 
916  $arrayofnonnegativevalue = array('weight'=>'Weight', 'width'=>'Width', 'height'=>'Height', 'length'=>'Length', 'surface'=>'Surface', 'volume'=>'Volume');
917  foreach ($arrayofnonnegativevalue as $key => $value) {
918  if (property_exists($this, $key) && !empty($this->$key) && ($this->$key < 0)) {
919  $langs->loadLangs(array("main", "other"));
920  $this->error = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
921  $this->errors[] = $this->error;
922  $result = -4;
923  }
924  }
925 
926  $rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
927  if ($rescode) {
928  if ($rescode == -1) {
929  $this->errors[] = 'ErrorBadBarCodeSyntax';
930  } elseif ($rescode == -2) {
931  $this->errors[] = 'ErrorBarCodeRequired';
932  } elseif ($rescode == -3) {
933  // Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
934  $this->errors[] = 'ErrorBarCodeAlreadyUsed';
935  }
936 
937  $result = -3;
938  }
939 
940  return $result;
941  }
942 
943  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
954  public function check_barcode($valuetotest, $typefortest)
955  {
956  // phpcs:enable
957  global $conf;
958  if (isModEnabled('barcode') && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
959  $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);
960 
961  $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
962  foreach ($dirsociete as $dirroot) {
963  $res = dol_include_once($dirroot.$module.'.php');
964  if ($res) {
965  break;
966  }
967  }
968 
969  $mod = new $module();
970 
971  dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
972  $result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
973  return $result;
974  } else {
975  return 0;
976  }
977  }
978 
990  public function update($id, $user, $notrigger = false, $action = 'update', $updatetype = false)
991  {
992  global $langs, $conf, $hookmanager;
993 
994  $error = 0;
995 
996  // Check parameters
997  if (!$this->label) {
998  $this->label = 'MISSING LABEL';
999  }
1000 
1001  // Clean parameters
1002  $this->ref = dol_string_nospecial(trim($this->ref));
1003  $this->label = trim($this->label);
1004  $this->description = trim($this->description);
1005  $this->note_private = (isset($this->note_private) ? trim($this->note_private) : null);
1006  $this->note_public = (isset($this->note_public) ? trim($this->note_public) : null);
1007  $this->net_measure = price2num($this->net_measure);
1008  $this->net_measure_units = trim($this->net_measure_units);
1009  $this->weight = price2num($this->weight);
1010  $this->weight_units = trim($this->weight_units);
1011  $this->length = price2num($this->length);
1012  $this->length_units = trim($this->length_units);
1013  $this->width = price2num($this->width);
1014  $this->width_units = trim($this->width_units);
1015  $this->height = price2num($this->height);
1016  $this->height_units = trim($this->height_units);
1017  $this->surface = price2num($this->surface);
1018  $this->surface_units = trim($this->surface_units);
1019  $this->volume = price2num($this->volume);
1020  $this->volume_units = trim($this->volume_units);
1021 
1022  // set unit not defined
1023  if (is_numeric($this->length_units)) {
1024  $this->width_units = $this->length_units; // Not used yet
1025  }
1026  if (is_numeric($this->length_units)) {
1027  $this->height_units = $this->length_units; // Not used yet
1028  }
1029 
1030  // Automated compute surface and volume if not filled
1031  if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
1032  $this->surface = $this->length * $this->width;
1033  $this->surface_units = measuring_units_squared($this->length_units);
1034  }
1035  if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
1036  $this->volume = $this->surface * $this->height;
1037  $this->volume_units = measuring_units_cubed($this->height_units);
1038  }
1039 
1040  if (empty($this->tva_tx)) {
1041  $this->tva_tx = 0;
1042  }
1043  if (empty($this->tva_npr)) {
1044  $this->tva_npr = 0;
1045  }
1046  if (empty($this->localtax1_tx)) {
1047  $this->localtax1_tx = 0;
1048  }
1049  if (empty($this->localtax2_tx)) {
1050  $this->localtax2_tx = 0;
1051  }
1052  if (empty($this->localtax1_type)) {
1053  $this->localtax1_type = '0';
1054  }
1055  if (empty($this->localtax2_type)) {
1056  $this->localtax2_type = '0';
1057  }
1058  if (empty($this->status)) {
1059  $this->status = 0;
1060  }
1061  if (empty($this->status_buy)) {
1062  $this->status_buy = 0;
1063  }
1064 
1065  if (empty($this->country_id)) {
1066  $this->country_id = 0;
1067  }
1068 
1069  if (empty($this->state_id)) {
1070  $this->state_id = 0;
1071  }
1072 
1073  // Barcode value
1074  $this->barcode = trim($this->barcode);
1075 
1076  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1077  $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
1078  $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
1079  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1080  $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
1081  $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
1082 
1083 
1084  $this->db->begin();
1085 
1086  $result = 0;
1087  // Check name is required and codes are ok or unique. If error, this->errors[] is filled
1088  if ($action != 'add') {
1089  $result = $this->verify(); // We don't check when update called during a create because verify was already done
1090  } else {
1091  // we can continue
1092  $result = 0;
1093  }
1094 
1095  if ($result >= 0) {
1096  // $this->oldcopy should have been set by the caller of update (here properties were already modified)
1097  if (empty($this->oldcopy)) {
1098  $this->oldcopy = dol_clone($this);
1099  }
1100 
1101  // Test if batch management is activated on existing product
1102  // If yes, we create missing entries into product_batch
1103  if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
1104  //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
1105  $valueforundefinedlot = '000000';
1106  if (!empty($conf->global->STOCK_DEFAULT_BATCH)) {
1107  $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH;
1108  }
1109 
1110  dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
1111 
1112  $this->load_stock();
1113  foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
1114  $qty_batch = 0;
1115  foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
1116  if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
1117  // We discard this line, we will create it later
1118  $sqlclean = "DELETE FROM ".$this->db->prefix()."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".((int) $ObjW->id);
1119  $result = $this->db->query($sqlclean);
1120  if (!$result) {
1121  dol_print_error($this->db);
1122  exit;
1123  }
1124  continue;
1125  }
1126 
1127  $qty_batch += $detail->qty;
1128  }
1129  // Quantities in batch details are not same as stock quantity,
1130  // so we add a default batch record to complete and get same qty in parent and child table
1131  if ($ObjW->real <> $qty_batch) {
1132  $ObjBatch = new Productbatch($this->db);
1133  $ObjBatch->batch = $valueforundefinedlot;
1134  $ObjBatch->qty = ($ObjW->real - $qty_batch);
1135  $ObjBatch->fk_product_stock = $ObjW->id;
1136 
1137  if ($ObjBatch->create($user, 1) < 0) {
1138  $error++;
1139  $this->errors = $ObjBatch->errors;
1140  }
1141  }
1142  }
1143  }
1144 
1145  // For automatic creation
1146  if ($this->barcode == -1) {
1147  $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
1148  }
1149 
1150  $sql = "UPDATE ".$this->db->prefix()."product";
1151  $sql .= " SET label = '".$this->db->escape($this->label)."'";
1152 
1153  if ($updatetype && ($this->isProduct() || $this->isService())) {
1154  $sql .= ", fk_product_type = ".((int) $this->type);
1155  }
1156 
1157  $sql .= ", ref = '".$this->db->escape($this->ref)."'";
1158  $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1159  $sql .= ", default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null");
1160  $sql .= ", tva_tx = ".((float) $this->tva_tx);
1161  $sql .= ", recuperableonly = ".((int) $this->tva_npr);
1162  $sql .= ", localtax1_tx = ".((float) $this->localtax1_tx);
1163  $sql .= ", localtax2_tx = ".((float) $this->localtax2_tx);
1164  $sql .= ", localtax1_type = ".($this->localtax1_type != '' ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'");
1165  $sql .= ", localtax2_type = ".($this->localtax2_type != '' ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'");
1166 
1167  $sql .= ", barcode = ".(empty($this->barcode) ? "null" : "'".$this->db->escape($this->barcode)."'");
1168  $sql .= ", fk_barcode_type = ".(empty($this->barcode_type) ? "null" : $this->db->escape($this->barcode_type));
1169 
1170  $sql .= ", tosell = ".(int) $this->status;
1171  $sql .= ", tobuy = ".(int) $this->status_buy;
1172  $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch);
1173  $sql .= ", batch_mask = '".$this->db->escape($this->batch_mask)."'";
1174 
1175  $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? "null" : (int) $this->finished);
1176  $sql .= ", fk_default_bom = ".((!isset($this->fk_default_bom) || $this->fk_default_bom < 0 || $this->fk_default_bom == '') ? "null" : (int) $this->fk_default_bom);
1177  $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null');
1178  $sql .= ", net_measure_units = ".($this->net_measure_units != '' ? "'".$this->db->escape($this->net_measure_units)."'" : 'null');
1179  $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null');
1180  $sql .= ", weight_units = ".($this->weight_units != '' ? "'".$this->db->escape($this->weight_units)."'" : 'null');
1181  $sql .= ", length = ".($this->length != '' ? "'".$this->db->escape($this->length)."'" : 'null');
1182  $sql .= ", length_units = ".($this->length_units != '' ? "'".$this->db->escape($this->length_units)."'" : 'null');
1183  $sql .= ", width= ".($this->width != '' ? "'".$this->db->escape($this->width)."'" : 'null');
1184  $sql .= ", width_units = ".($this->width_units != '' ? "'".$this->db->escape($this->width_units)."'" : 'null');
1185  $sql .= ", height = ".($this->height != '' ? "'".$this->db->escape($this->height)."'" : 'null');
1186  $sql .= ", height_units = ".($this->height_units != '' ? "'".$this->db->escape($this->height_units)."'" : 'null');
1187  $sql .= ", surface = ".($this->surface != '' ? "'".$this->db->escape($this->surface)."'" : 'null');
1188  $sql .= ", surface_units = ".($this->surface_units != '' ? "'".$this->db->escape($this->surface_units)."'" : 'null');
1189  $sql .= ", volume = ".($this->volume != '' ? "'".$this->db->escape($this->volume)."'" : 'null');
1190  $sql .= ", volume_units = ".($this->volume_units != '' ? "'".$this->db->escape($this->volume_units)."'" : 'null');
1191  $sql .= ", fk_default_warehouse = ".($this->fk_default_warehouse > 0 ? $this->db->escape($this->fk_default_warehouse) : 'null');
1192  $sql .= ", fk_default_workstation = ".($this->fk_default_workstation > 0 ? $this->db->escape($this->fk_default_workstation) : 'null');
1193  $sql .= ", seuil_stock_alerte = ".((isset($this->seuil_stock_alerte) && is_numeric($this->seuil_stock_alerte)) ? (float) $this->seuil_stock_alerte : 'null');
1194  $sql .= ", description = '".$this->db->escape($this->description)."'";
1195  $sql .= ", url = ".($this->url ? "'".$this->db->escape($this->url)."'" : 'null');
1196  $sql .= ", customcode = '".$this->db->escape($this->customcode)."'";
1197  $sql .= ", fk_country = ".($this->country_id > 0 ? (int) $this->country_id : 'null');
1198  $sql .= ", fk_state = ".($this->state_id > 0 ? (int) $this->state_id : 'null');
1199  $sql .= ", lifetime = ".($this->lifetime > 0 ? (int) $this->lifetime : 'null');
1200  $sql .= ", qc_frequency = ".($this->qc_frequency > 0 ? (int) $this->qc_frequency : 'null');
1201  $sql .= ", note = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : 'null');
1202  $sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : 'null');
1203  $sql .= ", duration = '".$this->db->escape($this->duration_value.$this->duration_unit)."'";
1204  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
1205  $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1206  $sql .= ", accountancy_code_buy_intra = '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1207  $sql .= ", accountancy_code_buy_export = '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1208  $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1209  $sql .= ", accountancy_code_sell_intra= '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1210  $sql .= ", accountancy_code_sell_export= '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1211  }
1212  $sql .= ", desiredstock = ".((isset($this->desiredstock) && is_numeric($this->desiredstock)) ? (float) $this->desiredstock : "null");
1213  $sql .= ", cost_price = ".($this->cost_price != '' ? $this->db->escape($this->cost_price) : 'null');
1214  $sql .= ", fk_unit= ".(!$this->fk_unit ? 'NULL' : (int) $this->fk_unit);
1215  $sql .= ", price_autogen = ".(!$this->price_autogen ? 0 : 1);
1216  $sql .= ", fk_price_expression = ".($this->fk_price_expression != 0 ? (int) $this->fk_price_expression : 'NULL');
1217  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : 'NULL');
1218  $sql .= ", mandatory_period = ".($this->mandatory_period );
1219  // stock field is not here because it is a denormalized value from product_stock.
1220  $sql .= " WHERE rowid = ".((int) $id);
1221 
1222  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1223 
1224  $resql = $this->db->query($sql);
1225  if ($resql) {
1226  $this->id = $id;
1227 
1228  // Multilangs
1229  if (getDolGlobalInt('MAIN_MULTILANGS')) {
1230  if ($this->setMultiLangs($user) < 0) {
1231  $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1232  return -2;
1233  }
1234  }
1235 
1236  $action = 'update';
1237 
1238  // update accountancy for this entity
1239  if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
1240  $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " . ((int) $this->id) . " AND entity = " . ((int) $conf->entity));
1241 
1242  $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
1243  $sql .= " fk_product";
1244  $sql .= ", entity";
1245  $sql .= ", accountancy_code_buy";
1246  $sql .= ", accountancy_code_buy_intra";
1247  $sql .= ", accountancy_code_buy_export";
1248  $sql .= ", accountancy_code_sell";
1249  $sql .= ", accountancy_code_sell_intra";
1250  $sql .= ", accountancy_code_sell_export";
1251  $sql .= ") VALUES (";
1252  $sql .= $this->id;
1253  $sql .= ", " . $conf->entity;
1254  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1255  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1256  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1257  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1258  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1259  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1260  $sql .= ")";
1261  $result = $this->db->query($sql);
1262  if (!$result) {
1263  $error++;
1264  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1265  }
1266  }
1267 
1268  // Actions on extra fields
1269  if (!$error) {
1270  $result = $this->insertExtraFields();
1271  if ($result < 0) {
1272  $error++;
1273  }
1274  }
1275 
1276  if (!$error && !$notrigger) {
1277  // Call trigger
1278  $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1279  if ($result < 0) {
1280  $error++;
1281  }
1282  // End call triggers
1283  }
1284 
1285  if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
1286  // We remove directory
1287  if ($conf->product->dir_output) {
1288  $olddir = $conf->product->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
1289  $newdir = $conf->product->dir_output."/".dol_sanitizeFileName($this->ref);
1290  if (file_exists($olddir)) {
1291  //include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1292  //$res = dol_move($olddir, $newdir);
1293  // do not use dol_move with directory
1294  $res = @rename($olddir, $newdir);
1295  if (!$res) {
1296  $langs->load("errors");
1297  $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
1298  $error++;
1299  }
1300  }
1301  }
1302  }
1303 
1304  if (!$error) {
1305  if (isModEnabled('variants')) {
1306  include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1307 
1308  $comb = new ProductCombination($this->db);
1309 
1310  foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) {
1311  $currcomb->updateProperties($this, $user);
1312  }
1313  }
1314 
1315  $this->db->commit();
1316  return 1;
1317  } else {
1318  $this->db->rollback();
1319  return -$error;
1320  }
1321  } else {
1322  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1323  $langs->load("errors");
1324  if (empty($conf->barcode->enabled) || empty($this->barcode)) {
1325  $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref);
1326  } else {
1327  $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode);
1328  }
1329  $this->errors[] = $this->error;
1330  $this->db->rollback();
1331  return -1;
1332  } else {
1333  $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1334  $this->errors[] = $this->error;
1335  $this->db->rollback();
1336  return -2;
1337  }
1338  }
1339  } else {
1340  $this->db->rollback();
1341  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1342  return -3;
1343  }
1344  }
1345 
1353  public function delete(User $user, $notrigger = 0)
1354  {
1355  global $conf, $langs;
1356  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1357 
1358  $error = 0;
1359 
1360  // Check parameters
1361  if (empty($this->id)) {
1362  $this->error = "Object must be fetched before calling delete";
1363  return -1;
1364  }
1365  if (($this->type == Product::TYPE_PRODUCT && empty($user->rights->produit->supprimer)) || ($this->type == Product::TYPE_SERVICE && empty($user->rights->service->supprimer))) {
1366  $this->error = "ErrorForbidden";
1367  return 0;
1368  }
1369 
1370  $objectisused = $this->isObjectUsed($this->id);
1371  if (empty($objectisused)) {
1372  $this->db->begin();
1373 
1374  if (!$error && empty($notrigger)) {
1375  // Call trigger
1376  $result = $this->call_trigger('PRODUCT_DELETE', $user);
1377  if ($result < 0) {
1378  $error++;
1379  }
1380  // End call triggers
1381  }
1382 
1383  // Delete from product_batch on product delete
1384  if (!$error) {
1385  $sql = "DELETE FROM ".$this->db->prefix().'product_batch';
1386  $sql .= " WHERE fk_product_stock IN (";
1387  $sql .= "SELECT rowid FROM ".$this->db->prefix().'product_stock';
1388  $sql .= " WHERE fk_product = ".((int) $this->id).")";
1389 
1390  $result = $this->db->query($sql);
1391  if (!$result) {
1392  $error++;
1393  $this->errors[] = $this->db->lasterror();
1394  }
1395  }
1396 
1397  // Delete all child tables
1398  if (!$error) {
1399  $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
1400  foreach ($elements as $table) {
1401  if (!$error) {
1402  $sql = "DELETE FROM ".$this->db->prefix().$table;
1403  $sql .= " WHERE fk_product = ".(int) $this->id;
1404 
1405  $result = $this->db->query($sql);
1406  if (!$result) {
1407  $error++;
1408  $this->errors[] = $this->db->lasterror();
1409  }
1410  }
1411  }
1412  }
1413 
1414  if (!$error) {
1415  include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1416  include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
1417 
1418  //If it is a parent product, then we remove the association with child products
1419  $prodcomb = new ProductCombination($this->db);
1420 
1421  if ($prodcomb->deleteByFkProductParent($user, $this->id) < 0) {
1422  $error++;
1423  $this->errors[] = 'Error deleting combinations';
1424  }
1425 
1426  //We also check if it is a child product
1427  if (!$error && ($prodcomb->fetchByFkProductChild($this->id) > 0) && ($prodcomb->delete($user) < 0)) {
1428  $error++;
1429  $this->errors[] = 'Error deleting child combination';
1430  }
1431  }
1432 
1433  // Delete from product_association
1434  if (!$error) {
1435  $sql = "DELETE FROM ".$this->db->prefix()."product_association";
1436  $sql .= " WHERE fk_product_pere = ".(int) $this->id." OR fk_product_fils = ".(int) $this->id;
1437 
1438  $result = $this->db->query($sql);
1439  if (!$result) {
1440  $error++;
1441  $this->errors[] = $this->db->lasterror();
1442  }
1443  }
1444 
1445  // Remove extrafields
1446  if (!$error) {
1447  $result = $this->deleteExtraFields();
1448  if ($result < 0) {
1449  $error++;
1450  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1451  }
1452  }
1453 
1454  // Delete product
1455  if (!$error) {
1456  $sqlz = "DELETE FROM ".$this->db->prefix()."product";
1457  $sqlz .= " WHERE rowid = ".(int) $this->id;
1458 
1459  $resultz = $this->db->query($sqlz);
1460  if (!$resultz) {
1461  $error++;
1462  $this->errors[] = $this->db->lasterror();
1463  }
1464  }
1465 
1466  // Delete record into ECM index and physically
1467  if (!$error) {
1468  $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1469  if (!$res) {
1470  $error++;
1471  }
1472  }
1473 
1474  if (!$error) {
1475  // We remove directory
1476  $ref = dol_sanitizeFileName($this->ref);
1477  if ($conf->product->dir_output) {
1478  $dir = $conf->product->dir_output."/".$ref;
1479  if (file_exists($dir)) {
1480  $res = @dol_delete_dir_recursive($dir);
1481  if (!$res) {
1482  $this->errors[] = 'ErrorFailToDeleteDir';
1483  $error++;
1484  }
1485  }
1486  }
1487  }
1488 
1489  if (!$error) {
1490  $this->db->commit();
1491  return 1;
1492  } else {
1493  foreach ($this->errors as $errmsg) {
1494  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1495  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1496  }
1497  $this->db->rollback();
1498  return -$error;
1499  }
1500  } else {
1501  $this->error = "ErrorRecordIsUsedCantDelete";
1502  return 0;
1503  }
1504  }
1505 
1512  public function setMultiLangs($user)
1513  {
1514  global $conf, $langs;
1515 
1516  $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
1517  $current_lang = $langs->getDefaultLang();
1518 
1519  foreach ($langs_available as $key => $value) {
1520  if ($key == $current_lang) {
1521  $sql = "SELECT rowid";
1522  $sql .= " FROM ".$this->db->prefix()."product_lang";
1523  $sql .= " WHERE fk_product = ".((int) $this->id);
1524  $sql .= " AND lang = '".$this->db->escape($key)."'";
1525 
1526  $result = $this->db->query($sql);
1527 
1528  if ($this->db->num_rows($result)) { // if there is already a description line for this language
1529  $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
1530  $sql2 .= " SET ";
1531  $sql2 .= " label='".$this->db->escape($this->label)."',";
1532  $sql2 .= " description='".$this->db->escape($this->description)."'";
1533  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1534  $sql2 .= ", note='".$this->db->escape($this->other)."'";
1535  }
1536  $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
1537  } else {
1538  $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
1539  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1540  $sql2 .= ", note";
1541  }
1542  $sql2 .= ")";
1543  $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
1544  $sql2 .= " '".$this->db->escape($this->description)."'";
1545  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1546  $sql2 .= ", '".$this->db->escape($this->other)."'";
1547  }
1548  $sql2 .= ")";
1549  }
1550  dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
1551  if (!$this->db->query($sql2)) {
1552  $this->error = $this->db->lasterror();
1553  return -1;
1554  }
1555  } elseif (isset($this->multilangs[$key])) {
1556  if (empty($this->multilangs["$key"]["label"])) {
1557  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
1558  return -1;
1559  }
1560 
1561  $sql = "SELECT rowid";
1562  $sql .= " FROM ".$this->db->prefix()."product_lang";
1563  $sql .= " WHERE fk_product = ".((int) $this->id);
1564  $sql .= " AND lang = '".$this->db->escape($key)."'";
1565 
1566  $result = $this->db->query($sql);
1567 
1568  if ($this->db->num_rows($result)) { // if there is already a description line for this language
1569  $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
1570  $sql2 .= " SET ";
1571  $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
1572  $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
1573  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1574  $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
1575  }
1576  $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
1577  } else {
1578  $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
1579  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1580  $sql2 .= ", note";
1581  }
1582  $sql2 .= ")";
1583  $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
1584  $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
1585  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1586  $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
1587  }
1588  $sql2 .= ")";
1589  }
1590 
1591  // We do not save if main fields are empty
1592  if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
1593  if (!$this->db->query($sql2)) {
1594  $this->error = $this->db->lasterror();
1595  return -1;
1596  }
1597  }
1598  } else {
1599  // language is not current language and we didn't provide a multilang description for this language
1600  }
1601  }
1602 
1603  // Call trigger
1604  $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
1605  if ($result < 0) {
1606  $this->error = $this->db->lasterror();
1607  return -1;
1608  }
1609  // End call triggers
1610 
1611  return 1;
1612  }
1613 
1622  public function delMultiLangs($langtodelete, $user)
1623  {
1624  $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
1625  $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
1626 
1627  dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
1628  $result = $this->db->query($sql);
1629  if ($result) {
1630  // Call trigger
1631  $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
1632  if ($result < 0) {
1633  $this->error = $this->db->lasterror();
1634  dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
1635  return -1;
1636  }
1637  // End call triggers
1638  return 1;
1639  } else {
1640  $this->error = $this->db->lasterror();
1641  dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
1642  return -1;
1643  }
1644  }
1645 
1654  public function setAccountancyCode($type, $value)
1655  {
1656  global $user, $langs, $conf;
1657 
1658  $error = 0;
1659 
1660  $this->db->begin();
1661 
1662  if ($type == 'buy') {
1663  $field = 'accountancy_code_buy';
1664  } elseif ($type == 'buy_intra') {
1665  $field = 'accountancy_code_buy_intra';
1666  } elseif ($type == 'buy_export') {
1667  $field = 'accountancy_code_buy_export';
1668  } elseif ($type == 'sell') {
1669  $field = 'accountancy_code_sell';
1670  } elseif ($type == 'sell_intra') {
1671  $field = 'accountancy_code_sell_intra';
1672  } elseif ($type == 'sell_export') {
1673  $field = 'accountancy_code_sell_export';
1674  } else {
1675  return -1;
1676  }
1677 
1678  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
1679  $sql .= "$field = '".$this->db->escape($value)."'";
1680  $sql .= " WHERE rowid = ".((int) $this->id);
1681 
1682  dol_syslog(__METHOD__."", LOG_DEBUG);
1683  $resql = $this->db->query($sql);
1684 
1685  if ($resql) {
1686  // Call trigger
1687  $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1688  if ($result < 0) {
1689  $error++;
1690  }
1691  // End call triggers
1692 
1693  if ($error) {
1694  $this->db->rollback();
1695  return -1;
1696  }
1697 
1698  $this->$field = $value;
1699 
1700  $this->db->commit();
1701  return 1;
1702  } else {
1703  $this->error = $this->db->lasterror();
1704  $this->db->rollback();
1705  return -1;
1706  }
1707  }
1708 
1714  public function getMultiLangs()
1715  {
1716  global $langs;
1717 
1718  $current_lang = $langs->getDefaultLang();
1719 
1720  $sql = "SELECT lang, label, description, note as other";
1721  $sql .= " FROM ".$this->db->prefix()."product_lang";
1722  $sql .= " WHERE fk_product = ".((int) $this->id);
1723 
1724  $result = $this->db->query($sql);
1725  if ($result) {
1726  while ($obj = $this->db->fetch_object($result)) {
1727  //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
1728  if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
1729  $this->label = $obj->label;
1730  $this->description = $obj->description;
1731  $this->other = $obj->other;
1732  }
1733  $this->multilangs["$obj->lang"]["label"] = $obj->label;
1734  $this->multilangs["$obj->lang"]["description"] = $obj->description;
1735  $this->multilangs["$obj->lang"]["other"] = $obj->other;
1736  }
1737  return 1;
1738  } else {
1739  $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
1740  return -1;
1741  }
1742  }
1743 
1750  private function getArrayForPriceCompare($level = 0)
1751  {
1752 
1753  $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
1754 
1755  foreach ($testExit as $field) {
1756  if (!isset($this->$field)) {
1757  return array();
1758  }
1759  $tmparray = $this->$field;
1760  if (!isset($tmparray[$level])) {
1761  return array();
1762  }
1763  }
1764 
1765  $lastPrice = array(
1766  'level' => $level ? $level : 1,
1767  'multiprices' => doubleval($this->multiprices[$level]),
1768  'multiprices_ttc' => doubleval($this->multiprices_ttc[$level]),
1769  'multiprices_base_type' => $this->multiprices_base_type[$level],
1770  'multiprices_min' => doubleval($this->multiprices_min[$level]),
1771  'multiprices_min_ttc' => doubleval($this->multiprices_min_ttc[$level]),
1772  'multiprices_tva_tx' => doubleval($this->multiprices_tva_tx[$level]),
1773  'multiprices_recuperableonly' => doubleval($this->multiprices_recuperableonly[$level]),
1774  );
1775 
1776  return $lastPrice;
1777  }
1778 
1779 
1780  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1788  private function _log_price($user, $level = 0)
1789  {
1790  // phpcs:enable
1791  global $conf;
1792 
1793  $now = dol_now();
1794 
1795  // Clean parameters
1796  if (empty($this->price_by_qty)) {
1797  $this->price_by_qty = 0;
1798  }
1799 
1800  // Add new price
1801  $sql = "INSERT INTO ".$this->db->prefix()."product_price(price_level,date_price, fk_product, fk_user_author, price, price_ttc, price_base_type,tosell, tva_tx, default_vat_code, recuperableonly,";
1802  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
1803  $sql .= " VALUES(".($level ? ((int) $level) : 1).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $user->id).", ".((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).",";
1804  $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');
1805  $sql .= ")";
1806 
1807  dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
1808  $resql = $this->db->query($sql);
1809  if (!$resql) {
1810  $this->error = $this->db->lasterror();
1811  dol_print_error($this->db);
1812  return -1;
1813  } else {
1814  return 1;
1815  }
1816  }
1817 
1818 
1819  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1827  public function log_price_delete($user, $rowid)
1828  {
1829  // phpcs:enable
1830  $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
1831  $sql .= " WHERE fk_product_price = ".((int) $rowid);
1832  $resql = $this->db->query($sql);
1833 
1834  $sql = "DELETE FROM ".$this->db->prefix()."product_price";
1835  $sql .= " WHERE rowid=".((int) $rowid);
1836  $resql = $this->db->query($sql);
1837  if ($resql) {
1838  return 1;
1839  } else {
1840  $this->error = $this->db->lasterror();
1841  return -1;
1842  }
1843  }
1844 
1845 
1855  public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
1856  {
1857  global $conf, $db, $hookmanager, $action;
1858 
1859  // Call hook if any
1860  if (is_object($hookmanager)) {
1861  $parameters = array('thirdparty_seller'=>$thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
1862  // Note that $action and $object may have been modified by some hooks
1863  $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
1864  if ($reshook > 0) {
1865  return $hookmanager->resArray;
1866  }
1867  }
1868 
1869  // Update if prices fields are defined
1870  $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
1871  $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
1872  if (empty($tva_tx)) {
1873  $tva_npr = 0;
1874  }
1875 
1876  $pu_ht = $this->price;
1877  $pu_ttc = $this->price_ttc;
1878  $price_min = $this->price_min;
1879  $price_base_type = $this->price_base_type;
1880 
1881  // If price per segment
1882  if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($thirdparty_buyer->price_level)) {
1883  $pu_ht = $this->multiprices[$thirdparty_buyer->price_level];
1884  $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
1885  $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
1886  $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
1887  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
1888  if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
1889  $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
1890  }
1891  if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
1892  $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
1893  }
1894  if (empty($tva_tx)) {
1895  $tva_npr = 0;
1896  }
1897  }
1898  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
1899  // If price per customer
1900  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
1901 
1902  $prodcustprice = new Productcustomerprice($this->db);
1903 
1904  $filter = array('t.fk_product' => $this->id, 't.fk_soc' => $thirdparty_buyer->id);
1905 
1906  $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1907  if ($result) {
1908  if (count($prodcustprice->lines) > 0) {
1909  $pu_ht = price($prodcustprice->lines[0]->price);
1910  $price_min = price($prodcustprice->lines[0]->price_min);
1911  $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
1912  $price_base_type = $prodcustprice->lines[0]->price_base_type;
1913  $tva_tx = $prodcustprice->lines[0]->tva_tx;
1914  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
1915  $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
1916  }
1917  $tva_npr = $prodcustprice->lines[0]->recuperableonly;
1918  if (empty($tva_tx)) {
1919  $tva_npr = 0;
1920  }
1921  }
1922  }
1923  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
1924  // If price per quantity
1925  if ($this->prices_by_qty[0]) {
1926  // yes, this product has some prices per quantity
1927  // Search price into product_price_by_qty from $this->id
1928  foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
1929  if ($priceforthequantityarray['rowid'] != $pqp) {
1930  continue;
1931  }
1932  // We found the price
1933  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1934  $pu_ht = $priceforthequantityarray['unitprice'];
1935  } else {
1936  $pu_ttc = $priceforthequantityarray['unitprice'];
1937  }
1938  break;
1939  }
1940  }
1941  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
1942  // If price per quantity and customer
1943  if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
1944  // yes, this product has some prices per quantity
1945  // Search price into product_price_by_qty from $this->id
1946  foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
1947  if ($priceforthequantityarray['rowid'] != $pqp) {
1948  continue;
1949  }
1950  // We found the price
1951  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1952  $pu_ht = $priceforthequantityarray['unitprice'];
1953  } else {
1954  $pu_ttc = $priceforthequantityarray['unitprice'];
1955  }
1956  break;
1957  }
1958  }
1959  }
1960 
1961  return array('pu_ht'=>$pu_ht, 'pu_ttc'=>$pu_ttc, 'price_min'=>$price_min, 'price_base_type'=>$price_base_type, 'tva_tx'=>$tva_tx, 'tva_npr'=>$tva_npr);
1962  }
1963 
1964  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1978  public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
1979  {
1980  // phpcs:enable
1981  global $conf;
1982  $result = 0;
1983 
1984  // 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)
1985  $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
1986  $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,";
1987  $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
1988  $sql .= " pfp.packaging";
1989  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
1990  $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
1991  if ($qty > 0) {
1992  $sql .= " AND pfp.quantity <= ".((float) $qty);
1993  }
1994  $sql .= " ORDER BY pfp.quantity DESC";
1995 
1996  dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
1997  $resql = $this->db->query($sql);
1998  if ($resql) {
1999  $obj = $this->db->fetch_object($resql);
2000  if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
2001  if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
2002  $prod_supplier = new ProductFournisseur($this->db);
2003  $prod_supplier->product_fourn_price_id = $obj->rowid;
2004  $prod_supplier->id = $obj->fk_product;
2005  $prod_supplier->fourn_qty = $obj->quantity;
2006  $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2007  $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2008 
2009  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2010  $priceparser = new PriceParser($this->db);
2011  $price_result = $priceparser->parseProductSupplier($prod_supplier);
2012  if ($price_result >= 0) {
2013  $obj->price = $price_result;
2014  }
2015  }
2016  $this->product_fourn_price_id = $obj->rowid;
2017  $this->buyprice = $obj->price; // deprecated
2018  $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
2019  $this->fourn_price_base_type = 'HT'; // Price base type
2020  $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2021  $this->ref_fourn = $obj->ref_supplier; // deprecated
2022  $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2023  $this->desc_supplier = $obj->desc_supplier; // desc supplier
2024  $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2025  $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2026  $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
2027  $this->fourn_multicurrency_price = $obj->multicurrency_price;
2028  $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2029  $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2030  $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2031  $this->fourn_multicurrency_code = $obj->multicurrency_code;
2032  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
2033  $this->packaging = $obj->packaging;
2034  }
2035  $result = $obj->fk_product;
2036  return $result;
2037  } else { // If not found
2038  // 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.
2039  $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
2040  $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,";
2041  $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
2042  $sql .= " pfp.packaging";
2043  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
2044  $sql .= " WHERE 1 = 1";
2045  if ($product_id > 0) {
2046  $sql .= " AND pfp.fk_product = ".((int) $product_id);
2047  }
2048  if ($fourn_ref != 'none') {
2049  $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
2050  }
2051  if ($fk_soc > 0) {
2052  $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
2053  }
2054  if ($qty > 0) {
2055  $sql .= " AND pfp.quantity <= ".((float) $qty);
2056  }
2057  $sql .= " ORDER BY pfp.quantity DESC";
2058  $sql .= " LIMIT 1";
2059 
2060  dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
2061  $resql = $this->db->query($sql);
2062  if ($resql) {
2063  $obj = $this->db->fetch_object($resql);
2064  if ($obj && $obj->quantity > 0) { // If found
2065  if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
2066  $prod_supplier = new ProductFournisseur($this->db);
2067  $prod_supplier->product_fourn_price_id = $obj->rowid;
2068  $prod_supplier->id = $obj->fk_product;
2069  $prod_supplier->fourn_qty = $obj->quantity;
2070  $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2071  $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2072 
2073  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2074  $priceparser = new PriceParser($this->db);
2075  $price_result = $priceparser->parseProductSupplier($prod_supplier);
2076  if ($result >= 0) {
2077  $obj->price = $price_result;
2078  }
2079  }
2080  $this->product_fourn_price_id = $obj->rowid;
2081  $this->buyprice = $obj->price; // deprecated
2082  $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
2083  $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
2084  $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
2085  $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2086  $this->ref_fourn = $obj->ref_supplier; // deprecated
2087  $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2088  $this->desc_supplier = $obj->desc_supplier; // desc supplier
2089  $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2090  $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2091  $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
2092  $this->fourn_multicurrency_price = $obj->multicurrency_price;
2093  $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2094  $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2095  $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2096  $this->fourn_multicurrency_code = $obj->multicurrency_code;
2097  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
2098  $this->packaging = $obj->packaging;
2099  }
2100  $result = $obj->fk_product;
2101  return $result;
2102  } else {
2103  return -1; // Ce produit n'existe pas avec cet id tarif fournisseur ou existe mais qte insuffisante, ni pour le couple produit/ref fournisseur dans la quantité.
2104  }
2105  } else {
2106  $this->error = $this->db->lasterror();
2107  return -3;
2108  }
2109  }
2110  } else {
2111  $this->error = $this->db->lasterror();
2112  return -2;
2113  }
2114  }
2115 
2116 
2133  public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '')
2134  {
2135  global $conf, $langs;
2136 
2137  $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
2138 
2139  $id = $this->id;
2140 
2141  dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
2142 
2143  // Clean parameters
2144  if (empty($this->tva_tx)) {
2145  $this->tva_tx = 0;
2146  }
2147  if (empty($newnpr)) {
2148  $newnpr = 0;
2149  }
2150  if (empty($newminprice)) {
2151  $newminprice = 0;
2152  }
2153  if (empty($newminprice)) {
2154  $newminprice = 0;
2155  }
2156 
2157  // Check parameters
2158  if ($newvat == '') {
2159  $newvat = $this->tva_tx;
2160  }
2161 
2162  // If multiprices are enabled, then we check if the current product is subject to price autogeneration
2163  // Price will be modified ONLY when the first one is the one that is being modified
2164  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
2165  return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
2166  }
2167 
2168  if (!empty($newminprice) && ($newminprice > $newprice)) {
2169  $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
2170  return -1;
2171  }
2172 
2173  if ($newprice !== '' || $newprice === 0) {
2174  if ($newpricebase == 'TTC') {
2175  $price_ttc = price2num($newprice, 'MU');
2176  $price = price2num($newprice) / (1 + ($newvat / 100));
2177  $price = price2num($price, 'MU');
2178 
2179  if ($newminprice != '' || $newminprice == 0) {
2180  $price_min_ttc = price2num($newminprice, 'MU');
2181  $price_min = price2num($newminprice) / (1 + ($newvat / 100));
2182  $price_min = price2num($price_min, 'MU');
2183  } else {
2184  $price_min = 0;
2185  $price_min_ttc = 0;
2186  }
2187  } else {
2188  $price = price2num($newprice, 'MU');
2189  $price_ttc = ($newnpr != 1) ? (float) price2num($newprice) * (1 + ($newvat / 100)) : $price;
2190  $price_ttc = price2num($price_ttc, 'MU');
2191 
2192  if ($newminprice !== '' || $newminprice === 0) {
2193  $price_min = price2num($newminprice, 'MU');
2194  $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100));
2195  $price_min_ttc = price2num($price_min_ttc, 'MU');
2196  //print 'X'.$newminprice.'-'.$price_min;
2197  } else {
2198  $price_min = 0;
2199  $price_min_ttc = 0;
2200  }
2201  }
2202  //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
2203 
2204  if (count($localtaxes_array) > 0) {
2205  $localtaxtype1 = $localtaxes_array['0'];
2206  $localtax1 = $localtaxes_array['1'];
2207  $localtaxtype2 = $localtaxes_array['2'];
2208  $localtax2 = $localtaxes_array['3'];
2209  } else {
2210  // if array empty, we try to use the vat code
2211  if (!empty($newdefaultvatcode)) {
2212  global $mysoc;
2213  // Get record from code
2214  $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
2215  $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
2216  $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($mysoc->country_code)."'";
2217  $sql .= " AND t.taux = ".((float) $newdefaultvatcode)." AND t.active = 1";
2218  $sql .= " AND t.code = '".$this->db->escape($newdefaultvatcode)."'";
2219  $resql = $this->db->query($sql);
2220  if ($resql) {
2221  $obj = $this->db->fetch_object($resql);
2222  if ($obj) {
2223  $npr = $obj->recuperableonly;
2224  $localtax1 = $obj->localtax1;
2225  $localtax2 = $obj->localtax2;
2226  $localtaxtype1 = $obj->localtax1_type;
2227  $localtaxtype2 = $obj->localtax2_type;
2228  }
2229  }
2230  } else {
2231  // old method. deprecated because we can't retrieve type
2232  $localtaxtype1 = '0';
2233  $localtax1 = get_localtax($newvat, 1);
2234  $localtaxtype2 = '0';
2235  $localtax2 = get_localtax($newvat, 2);
2236  }
2237  }
2238  if (empty($localtax1)) {
2239  $localtax1 = 0; // If = '' then = 0
2240  }
2241  if (empty($localtax2)) {
2242  $localtax2 = 0; // If = '' then = 0
2243  }
2244 
2245  $this->db->begin();
2246 
2247  // Ne pas mettre de quote sur les numeriques decimaux.
2248  // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes.
2249  $sql = "UPDATE ".$this->db->prefix()."product SET";
2250  $sql .= " price_base_type='".$this->db->escape($newpricebase)."',";
2251  $sql .= " price=".$price.",";
2252  $sql .= " price_ttc=".$price_ttc.",";
2253  $sql .= " price_min=".$price_min.",";
2254  $sql .= " price_min_ttc=".$price_min_ttc.",";
2255  $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').",";
2256  $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').",";
2257  $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
2258  $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
2259  $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
2260  $sql .= " tva_tx='".price2num($newvat)."',";
2261  $sql .= " recuperableonly='".$this->db->escape($newnpr)."'";
2262  $sql .= " WHERE rowid = ".((int) $id);
2263 
2264  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2265  $resql = $this->db->query($sql);
2266  if ($resql) {
2267  $this->multiprices[$level] = $price;
2268  $this->multiprices_ttc[$level] = $price_ttc;
2269  $this->multiprices_min[$level] = $price_min;
2270  $this->multiprices_min_ttc[$level] = $price_min_ttc;
2271  $this->multiprices_base_type[$level] = $newpricebase;
2272  $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
2273  $this->multiprices_tva_tx[$level] = $newvat;
2274  $this->multiprices_recuperableonly[$level] = $newnpr;
2275 
2276  $this->price = $price;
2277  $this->price_ttc = $price_ttc;
2278  $this->price_min = $price_min;
2279  $this->price_min_ttc = $price_min_ttc;
2280  $this->price_base_type = $newpricebase;
2281  $this->default_vat_code = $newdefaultvatcode;
2282  $this->tva_tx = $newvat;
2283  $this->tva_npr = $newnpr;
2284  //Local taxes
2285  $this->localtax1_tx = $localtax1;
2286  $this->localtax2_tx = $localtax2;
2287  $this->localtax1_type = $localtaxtype1;
2288  $this->localtax2_type = $localtaxtype2;
2289 
2290  // Price by quantity
2291  $this->price_by_qty = $newpbq;
2292 
2293  // check if price have really change before log
2294  $newPriceData = $this->getArrayForPriceCompare($level);
2295  if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || empty($conf->global->PRODUIT_MULTIPRICES)) {
2296  $this->_log_price($user, $level); // Save price for level into table product_price
2297  }
2298 
2299  $this->level = $level; // Store level of price edited for trigger
2300 
2301  // Call trigger
2302  $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
2303  if ($result < 0) {
2304  $this->db->rollback();
2305  return -1;
2306  }
2307  // End call triggers
2308 
2309  $this->db->commit();
2310  } else {
2311  $this->db->rollback();
2312  $this->error = $this->db->lasterror();
2313  return -1;
2314  }
2315  }
2316 
2317  return 1;
2318  }
2319 
2327  public function setPriceExpression($expression_id)
2328  {
2329  global $user;
2330 
2331  $this->fk_price_expression = $expression_id;
2332 
2333  return $this->update($this->id, $user);
2334  }
2335 
2348  public function fetch($id = '', $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
2349  {
2350  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
2351 
2352  global $langs, $conf;
2353 
2354  dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
2355 
2356  // Check parameters
2357  if (!$id && !$ref && !$ref_ext && !$barcode) {
2358  $this->error = 'ErrorWrongParameters';
2359  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2360  return -1;
2361  }
2362 
2363  $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,";
2364  $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,";
2365  $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,";
2366  $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
2367  $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,";
2368  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
2369  $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,";
2370  } else {
2371  $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,";
2372  }
2373 
2374  //For MultiCompany
2375  //PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
2376  $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
2377  $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.
2378  $visibleWarehousesEntities = $conf->entity;
2379  if (!empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
2380  if (!empty($conf->global->MULTICOMPANY_PMP_PER_ENTITY_ENABLED)) {
2381  $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
2382  if ($this->db->num_rows($checkPMPPerEntity)>0) {
2383  $separatedEntityPMP = true;
2384  }
2385  }
2386  global $mc;
2387  $separatedStock = true;
2388  if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
2389  $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
2390  }
2391  }
2392  if ($separatedEntityPMP) {
2393  $sql .= " ppe.pmp,";
2394  } else {
2395  $sql .= " p.pmp,";
2396  }
2397  $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
2398  $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf,";
2399  if ($separatedStock) {
2400  $sql .= " SUM(sp.reel) as stock";
2401  } else {
2402  $sql .= " p.stock";
2403  }
2404  $sql .= " FROM ".$this->db->prefix()."product as p";
2405  if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) || $separatedEntityPMP) {
2406  $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
2407  }
2408  if ($separatedStock) {
2409  $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)."))";
2410  }
2411 
2412  if ($id) {
2413  $sql .= " WHERE p.rowid = ".((int) $id);
2414  } else {
2415  $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
2416  if ($ref) {
2417  $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
2418  } elseif ($ref_ext) {
2419  $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
2420  } elseif ($barcode) {
2421  $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
2422  }
2423  }
2424  if ($separatedStock) {
2425  $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,";
2426  $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,";
2427  $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,";
2428  $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
2429  $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished,";
2430  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
2431  $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,";
2432  } else {
2433  $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,";
2434  }
2435  if ($separatedEntityPMP) {
2436  $sql .= " ppe.pmp,";
2437  } else {
2438  $sql .= " p.pmp,";
2439  }
2440  $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
2441  $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf";
2442  if (!$separatedStock) {
2443  $sql .= ", p.stock";
2444  }
2445  }
2446 
2447  $resql = $this->db->query($sql);
2448  if ($resql) {
2449  unset($this->oldcopy);
2450 
2451  if ($this->db->num_rows($resql) > 0) {
2452  $obj = $this->db->fetch_object($resql);
2453 
2454  $this->id = $obj->rowid;
2455  $this->ref = $obj->ref;
2456  $this->ref_ext = $obj->ref_ext;
2457  $this->label = $obj->label;
2458  $this->description = $obj->description;
2459  $this->url = $obj->url;
2460  $this->note_public = $obj->note_public;
2461  $this->note_private = $obj->note_private;
2462  $this->note = $obj->note_private; // deprecated
2463 
2464  $this->type = $obj->fk_product_type;
2465  $this->status = $obj->tosell;
2466  $this->status_buy = $obj->tobuy;
2467  $this->status_batch = $obj->tobatch;
2468  $this->batch_mask = $obj->batch_mask;
2469 
2470  $this->customcode = $obj->customcode;
2471  $this->country_id = $obj->fk_country;
2472  $this->country_code = getCountry($this->country_id, 2, $this->db);
2473  $this->state_id = $obj->fk_state;
2474  $this->lifetime = $obj->lifetime;
2475  $this->qc_frequency = $obj->qc_frequency;
2476  $this->price = $obj->price;
2477  $this->price_ttc = $obj->price_ttc;
2478  $this->price_min = $obj->price_min;
2479  $this->price_min_ttc = $obj->price_min_ttc;
2480  $this->price_base_type = $obj->price_base_type;
2481  $this->cost_price = $obj->cost_price;
2482  $this->default_vat_code = $obj->default_vat_code;
2483  $this->tva_tx = $obj->tva_tx;
2485  $this->tva_npr = $obj->tva_npr;
2486  $this->recuperableonly = $obj->tva_npr; // For backward compatibility
2488  $this->localtax1_tx = $obj->localtax1_tx;
2489  $this->localtax2_tx = $obj->localtax2_tx;
2490  $this->localtax1_type = $obj->localtax1_type;
2491  $this->localtax2_type = $obj->localtax2_type;
2492 
2493  $this->finished = $obj->finished;
2494  $this->fk_default_bom = $obj->fk_default_bom;
2495 
2496  $this->duration = $obj->duration;
2497  $this->duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1);
2498  $this->duration_unit = substr($obj->duration, -1);
2499  $this->canvas = $obj->canvas;
2500  $this->net_measure = $obj->net_measure;
2501  $this->net_measure_units = $obj->net_measure_units;
2502  $this->weight = $obj->weight;
2503  $this->weight_units = $obj->weight_units;
2504  $this->length = $obj->length;
2505  $this->length_units = $obj->length_units;
2506  $this->width = $obj->width;
2507  $this->width_units = $obj->width_units;
2508  $this->height = $obj->height;
2509  $this->height_units = $obj->height_units;
2510 
2511  $this->surface = $obj->surface;
2512  $this->surface_units = $obj->surface_units;
2513  $this->volume = $obj->volume;
2514  $this->volume_units = $obj->volume_units;
2515  $this->barcode = $obj->barcode;
2516  $this->barcode_type = $obj->fk_barcode_type;
2517 
2518  $this->accountancy_code_buy = $obj->accountancy_code_buy;
2519  $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
2520  $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
2521  $this->accountancy_code_sell = $obj->accountancy_code_sell;
2522  $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
2523  $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
2524 
2525  $this->fk_default_warehouse = $obj->fk_default_warehouse;
2526  $this->fk_default_workstation = $obj->fk_default_workstation;
2527  $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
2528  $this->desiredstock = $obj->desiredstock;
2529  $this->stock_reel = $obj->stock;
2530  $this->pmp = $obj->pmp;
2531 
2532  $this->date_creation = $obj->datec;
2533  $this->date_modification = $obj->tms;
2534  $this->import_key = $obj->import_key;
2535  $this->entity = $obj->entity;
2536 
2537  $this->ref_ext = $obj->ref_ext;
2538  $this->fk_price_expression = $obj->fk_price_expression;
2539  $this->fk_unit = $obj->fk_unit;
2540  $this->price_autogen = $obj->price_autogen;
2541  $this->model_pdf = $obj->model_pdf;
2542 
2543  $this->mandatory_period = $obj->mandatory_period;
2544 
2545  $this->db->free($resql);
2546 
2547  // fetch optionals attributes and labels
2548  $this->fetch_optionals();
2549 
2550  // Multilangs
2551  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($ignore_lang_load)) {
2552  $this->getMultiLangs();
2553  }
2554 
2555  // Load multiprices array
2556  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
2557  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
2558  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2559  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
2560  $sql .= " FROM ".$this->db->prefix()."product_price";
2561  $sql .= " WHERE entity IN (".getEntity('productprice').")";
2562  $sql .= " AND price_level=".((int) $i);
2563  $sql .= " AND fk_product = ".((int) $this->id);
2564  $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
2565  $sql .= " LIMIT 1"; // Only the first one
2566  $resql = $this->db->query($sql);
2567  if ($resql) {
2568  $result = $this->db->fetch_array($resql);
2569 
2570  $this->multiprices[$i] = $result ? $result["price"] : null;
2571  $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
2572  $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
2573  $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
2574  $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
2575  // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
2576  $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].($result ? ' ('.$result['default_vat_code'].')' : '') : null;
2577  $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
2578 
2579  // Price by quantity
2580  /*
2581  $this->prices_by_qty[$i]=$result["price_by_qty"];
2582  $this->prices_by_qty_id[$i]=$result["rowid"];
2583  // Récuperation de la liste des prix selon qty si flag positionné
2584  if ($this->prices_by_qty[$i] == 1)
2585  {
2586  $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
2587  $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
2588  $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
2589  $sql.= " ORDER BY quantity ASC";
2590  $resultat=array();
2591  $resql = $this->db->query($sql);
2592  if ($resql)
2593  {
2594  $ii=0;
2595  while ($result= $this->db->fetch_array($resql)) {
2596  $resultat[$ii]=array();
2597  $resultat[$ii]["rowid"]=$result["rowid"];
2598  $resultat[$ii]["price"]= $result["price"];
2599  $resultat[$ii]["unitprice"]= $result["unitprice"];
2600  $resultat[$ii]["quantity"]= $result["quantity"];
2601  $resultat[$ii]["remise_percent"]= $result["remise_percent"];
2602  $resultat[$ii]["remise"]= $result["remise"]; // deprecated
2603  $resultat[$ii]["price_base_type"]= $result["price_base_type"];
2604  $ii++;
2605  }
2606  $this->prices_by_qty_list[$i]=$resultat;
2607  }
2608  else
2609  {
2610  dol_print_error($this->db);
2611  return -1;
2612  }
2613  }*/
2614  } else {
2615  $this->error = $this->db->lasterror;
2616  return -1;
2617  }
2618  }
2619  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
2620  // Nothing loaded by default. List may be very long.
2621  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
2622  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2623  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
2624  $sql .= " FROM ".$this->db->prefix()."product_price";
2625  $sql .= " WHERE fk_product = ".((int) $this->id);
2626  $sql .= " ORDER BY date_price DESC, rowid DESC";
2627  $sql .= " LIMIT 1";
2628  $resql = $this->db->query($sql);
2629  if ($resql) {
2630  $result = $this->db->fetch_array($resql);
2631 
2632  // Price by quantity
2633  $this->prices_by_qty[0] = $result["price_by_qty"];
2634  $this->prices_by_qty_id[0] = $result["rowid"];
2635  // Récuperation de la liste des prix selon qty si flag positionné
2636  if ($this->prices_by_qty[0] == 1) {
2637  $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
2638  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2639  $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
2640  $sql .= " ORDER BY quantity ASC";
2641  $resultat = array();
2642  $resql = $this->db->query($sql);
2643  if ($resql) {
2644  $ii = 0;
2645  while ($result = $this->db->fetch_array($resql)) {
2646  $resultat[$ii] = array();
2647  $resultat[$ii]["rowid"] = $result["rowid"];
2648  $resultat[$ii]["price"] = $result["price"];
2649  $resultat[$ii]["unitprice"] = $result["unitprice"];
2650  $resultat[$ii]["quantity"] = $result["quantity"];
2651  $resultat[$ii]["remise_percent"] = $result["remise_percent"];
2652  //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
2653  $resultat[$ii]["price_base_type"] = $result["price_base_type"];
2654  $ii++;
2655  }
2656  $this->prices_by_qty_list[0] = $resultat;
2657  } else {
2658  $this->error = $this->db->lasterror;
2659  return -1;
2660  }
2661  }
2662  } else {
2663  $this->error = $this->db->lasterror;
2664  return -1;
2665  }
2666  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
2667  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
2668  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2669  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
2670  $sql .= " FROM ".$this->db->prefix()."product_price";
2671  $sql .= " WHERE entity IN (".getEntity('productprice').")";
2672  $sql .= " AND price_level=".((int) $i);
2673  $sql .= " AND fk_product = ".((int) $this->id);
2674  $sql .= " ORDER BY date_price DESC, rowid DESC";
2675  $sql .= " LIMIT 1";
2676  $resql = $this->db->query($sql);
2677  if ($resql) {
2678  $result = $this->db->fetch_array($resql);
2679 
2680  $this->multiprices[$i] = (!empty($result["price"]) ? $result["price"] : 0);
2681  $this->multiprices_ttc[$i] = (!empty($result["price_ttc"]) ? $result["price_ttc"] : 0);
2682  $this->multiprices_min[$i] = (!empty($result["price_min"]) ? $result["price_min"] : 0);
2683  $this->multiprices_min_ttc[$i] = (!empty($result["price_min_ttc"]) ? $result["price_min_ttc"] : 0);
2684  $this->multiprices_base_type[$i] = (!empty($result["price_base_type"]) ? $result["price_base_type"] : '');
2685  // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
2686  $this->multiprices_tva_tx[$i] = (!empty($result["tva_tx"]) ? $result["tva_tx"] : 0); // TODO Add ' ('.$result['default_vat_code'].')'
2687  $this->multiprices_recuperableonly[$i] = (!empty($result["recuperableonly"]) ? $result["recuperableonly"] : 0);
2688 
2689  // Price by quantity
2690  $this->prices_by_qty[$i] = (!empty($result["price_by_qty"]) ? $result["price_by_qty"] : 0);
2691  $this->prices_by_qty_id[$i] = (!empty($result["rowid"]) ? $result["rowid"] : 0);
2692  // Récuperation de la liste des prix selon qty si flag positionné
2693  if ($this->prices_by_qty[$i] == 1) {
2694  $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
2695  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2696  $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
2697  $sql .= " ORDER BY quantity ASC";
2698  $resultat = array();
2699  $resql = $this->db->query($sql);
2700  if ($resql) {
2701  $ii = 0;
2702  while ($result = $this->db->fetch_array($resql)) {
2703  $resultat[$ii] = array();
2704  $resultat[$ii]["rowid"] = $result["rowid"];
2705  $resultat[$ii]["price"] = $result["price"];
2706  $resultat[$ii]["unitprice"] = $result["unitprice"];
2707  $resultat[$ii]["quantity"] = $result["quantity"];
2708  $resultat[$ii]["remise_percent"] = $result["remise_percent"];
2709  $resultat[$ii]["remise"] = $result["remise"]; // deprecated
2710  $resultat[$ii]["price_base_type"] = $result["price_base_type"];
2711  $ii++;
2712  }
2713  $this->prices_by_qty_list[$i] = $resultat;
2714  } else {
2715  $this->error = $this->db->lasterror;
2716  return -1;
2717  }
2718  }
2719  } else {
2720  $this->error = $this->db->lasterror;
2721  return -1;
2722  }
2723  }
2724  }
2725 
2726  if (isModEnabled('dynamicprices') && !empty($this->fk_price_expression) && empty($ignore_expression)) {
2727  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2728  $priceparser = new PriceParser($this->db);
2729  $price_result = $priceparser->parseProduct($this);
2730  if ($price_result >= 0) {
2731  $this->price = $price_result;
2732  // Calculate the VAT
2733  $this->price_ttc = price2num($this->price) * (1 + ($this->tva_tx / 100));
2734  $this->price_ttc = price2num($this->price_ttc, 'MU');
2735  }
2736  }
2737 
2738  // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
2739  // Instead we just init the stock_warehouse array
2740  $this->stock_warehouse = array();
2741 
2742  return 1;
2743  } else {
2744  return 0;
2745  }
2746  } else {
2747  $this->error = $this->db->lasterror();
2748  return -1;
2749  }
2750  }
2751 
2752  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2759  public function load_stats_mo($socid = 0)
2760  {
2761  // phpcs:enable
2762  global $user, $hookmanager, $action;
2763 
2764  $error = 0;
2765 
2766  foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
2767  $this->stats_mo['customers_'.$role] = 0;
2768  $this->stats_mo['nb_'.$role] = 0;
2769  $this->stats_mo['qty_'.$role] = 0;
2770 
2771  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
2772  $sql .= " SUM(mp.qty) as qty";
2773  $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
2774  $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
2775  if (empty($user->rights->societe->client->voir) && !$socid) {
2776  $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
2777  }
2778  $sql .= " WHERE ";
2779  $sql .= " c.entity IN (".getEntity('mo').")";
2780 
2781  $sql .= " AND mp.fk_product = ".((int) $this->id);
2782  $sql .= " AND mp.role ='".$this->db->escape($role)."'";
2783  if ($socid > 0) {
2784  $sql .= " AND c.fk_soc = ".((int) $socid);
2785  }
2786 
2787  $result = $this->db->query($sql);
2788  if ($result) {
2789  $obj = $this->db->fetch_object($result);
2790  $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
2791  $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
2792  $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
2793  } else {
2794  $this->error = $this->db->error();
2795  $error++;
2796  }
2797  }
2798 
2799  if (!empty($error)) {
2800  return -1;
2801  }
2802 
2803  $parameters = array('socid' => $socid);
2804  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
2805  if ($reshook > 0) {
2806  $this->stats_mo = $hookmanager->resArray['stats_mo'];
2807  }
2808 
2809  return 1;
2810  }
2811 
2812  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2819  public function load_stats_bom($socid = 0)
2820  {
2821  // phpcs:enable
2822  global $user, $hookmanager, $action;
2823 
2824  $error = 0;
2825 
2826  $this->stats_bom['nb_toproduce'] = 0;
2827  $this->stats_bom['nb_toconsume'] = 0;
2828  $this->stats_bom['qty_toproduce'] = 0;
2829  $this->stats_bom['qty_toconsume'] = 0;
2830 
2831  $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
2832  $sql .= " SUM(b.qty) as qty_toproduce";
2833  $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
2834  $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
2835  $sql .= " WHERE ";
2836  $sql .= " b.entity IN (".getEntity('bom').")";
2837  $sql .= " AND b.fk_product =".((int) $this->id);
2838  $sql .= " GROUP BY b.rowid";
2839 
2840  $result = $this->db->query($sql);
2841  if ($result) {
2842  $obj = $this->db->fetch_object($result);
2843  $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
2844  $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
2845  } else {
2846  $this->error = $this->db->error();
2847  $error++;
2848  }
2849 
2850  $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
2851  $sql .= " SUM(bl.qty) as qty_toconsume";
2852  $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
2853  $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
2854  $sql .= " WHERE ";
2855  $sql .= " b.entity IN (".getEntity('bom').")";
2856  $sql .= " AND bl.fk_product =".((int) $this->id);
2857 
2858  $result = $this->db->query($sql);
2859  if ($result) {
2860  $obj = $this->db->fetch_object($result);
2861  $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
2862  $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
2863  } else {
2864  $this->error = $this->db->error();
2865  $error++;
2866  }
2867 
2868  if (!empty($error)) {
2869  return -1;
2870  }
2871 
2872  $parameters = array('socid' => $socid);
2873  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
2874  if ($reshook > 0) {
2875  $this->stats_bom = $hookmanager->resArray['stats_bom'];
2876  }
2877 
2878  return 1;
2879  }
2880 
2881  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2888  public function load_stats_propale($socid = 0)
2889  {
2890  // phpcs:enable
2891  global $conf, $user, $hookmanager, $action;
2892 
2893  $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
2894  $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
2895  $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
2896  $sql .= ", ".$this->db->prefix()."propal as p";
2897  $sql .= ", ".$this->db->prefix()."societe as s";
2898  if (empty($user->rights->societe->client->voir) && !$socid) {
2899  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2900  }
2901  $sql .= " WHERE p.rowid = pd.fk_propal";
2902  $sql .= " AND p.fk_soc = s.rowid";
2903  $sql .= " AND p.entity IN (".getEntity('propal').")";
2904  $sql .= " AND pd.fk_product = ".((int) $this->id);
2905  if (empty($user->rights->societe->client->voir) && !$socid) {
2906  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2907  }
2908  //$sql.= " AND pr.fk_statut != 0";
2909  if ($socid > 0) {
2910  $sql .= " AND p.fk_soc = ".((int) $socid);
2911  }
2912 
2913  $result = $this->db->query($sql);
2914  if ($result) {
2915  $obj = $this->db->fetch_object($result);
2916  $this->stats_propale['customers'] = $obj->nb_customers;
2917  $this->stats_propale['nb'] = $obj->nb;
2918  $this->stats_propale['rows'] = $obj->nb_rows;
2919  $this->stats_propale['qty'] = $obj->qty ? $obj->qty : 0;
2920 
2921  // if it's a virtual product, maybe it is in proposal by extension
2922  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
2923  $TFather = $this->getFather();
2924  if (is_array($TFather) && !empty($TFather)) {
2925  foreach ($TFather as &$fatherData) {
2926  $pFather = new Product($this->db);
2927  $pFather->id = $fatherData['id'];
2928  $qtyCoef = $fatherData['qty'];
2929 
2930  if ($fatherData['incdec']) {
2931  $pFather->load_stats_propale($socid);
2932 
2933  $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
2934  $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
2935  $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
2936  $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
2937  }
2938  }
2939  }
2940  }
2941 
2942  $parameters = array('socid' => $socid);
2943  $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
2944  if ($reshook > 0) {
2945  $this->stats_propale = $hookmanager->resArray['stats_propale'];
2946  }
2947 
2948  return 1;
2949  } else {
2950  $this->error = $this->db->error();
2951  return -1;
2952  }
2953  }
2954 
2955 
2956  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2963  public function load_stats_proposal_supplier($socid = 0)
2964  {
2965  // phpcs:enable
2966  global $conf, $user, $hookmanager, $action;
2967 
2968  $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
2969  $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
2970  $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
2971  $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
2972  $sql .= ", ".$this->db->prefix()."societe as s";
2973  if (empty($user->rights->societe->client->voir) && !$socid) {
2974  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2975  }
2976  $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
2977  $sql .= " AND p.fk_soc = s.rowid";
2978  $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
2979  $sql .= " AND pd.fk_product = ".((int) $this->id);
2980  if (empty($user->rights->societe->client->voir) && !$socid) {
2981  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2982  }
2983  //$sql.= " AND pr.fk_statut != 0";
2984  if ($socid > 0) {
2985  $sql .= " AND p.fk_soc = ".((int) $socid);
2986  }
2987 
2988  $result = $this->db->query($sql);
2989  if ($result) {
2990  $obj = $this->db->fetch_object($result);
2991  $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
2992  $this->stats_proposal_supplier['nb'] = $obj->nb;
2993  $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
2994  $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
2995 
2996  $parameters = array('socid' => $socid);
2997  $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
2998  if ($reshook > 0) {
2999  $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
3000  }
3001 
3002  return 1;
3003  } else {
3004  $this->error = $this->db->error();
3005  return -1;
3006  }
3007  }
3008 
3009 
3010  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3019  public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3020  {
3021  // phpcs:enable
3022  global $conf, $user, $hookmanager, $action;
3023 
3024  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3025  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3026  $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
3027  $sql .= ", ".$this->db->prefix()."commande as c";
3028  $sql .= ", ".$this->db->prefix()."societe as s";
3029  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3030  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3031  }
3032  $sql .= " WHERE c.rowid = cd.fk_commande";
3033  $sql .= " AND c.fk_soc = s.rowid";
3034  $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
3035  $sql .= " AND cd.fk_product = ".((int) $this->id);
3036  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3037  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3038  }
3039  if ($socid > 0) {
3040  $sql .= " AND c.fk_soc = ".((int) $socid);
3041  }
3042  if ($filtrestatut <> '') {
3043  $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")";
3044  }
3045 
3046  $result = $this->db->query($sql);
3047  if ($result) {
3048  $obj = $this->db->fetch_object($result);
3049  $this->stats_commande['customers'] = $obj->nb_customers;
3050  $this->stats_commande['nb'] = $obj->nb;
3051  $this->stats_commande['rows'] = $obj->nb_rows;
3052  $this->stats_commande['qty'] = $obj->qty ? $obj->qty : 0;
3053 
3054  // if it's a virtual product, maybe it is in order by extension
3055  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3056  $TFather = $this->getFather();
3057  if (is_array($TFather) && !empty($TFather)) {
3058  foreach ($TFather as &$fatherData) {
3059  $pFather = new Product($this->db);
3060  $pFather->id = $fatherData['id'];
3061  $qtyCoef = $fatherData['qty'];
3062 
3063  if ($fatherData['incdec']) {
3064  $pFather->load_stats_commande($socid, $filtrestatut);
3065 
3066  $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
3067  $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
3068  $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
3069  $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
3070  }
3071  }
3072  }
3073  }
3074 
3075  // If stock decrease is on invoice validation, the theorical stock continue to
3076  // count the orders to ship in theorical stock when some are already removed by invoice validation.
3077  if ($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3078  if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) {
3079  // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation but only if order not yet invoice.
3080  $adeduire = 0;
3081  $sql = "SELECT SUM(".$this->db->ifsql('f.type=2', -1, 1)." * fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
3082  $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid";
3083  $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'))";
3084  $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_source = c.rowid";
3085  $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
3086 
3087  dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
3088  $resql = $this->db->query($sql);
3089  if ($resql) {
3090  if ($this->db->num_rows($resql) > 0) {
3091  $obj = $this->db->fetch_object($resql);
3092  $adeduire += $obj->count;
3093  }
3094  }
3095 
3096  $this->stats_commande['qty'] -= $adeduire;
3097  } else {
3098  // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is off, we make a compensation with lines of invoices linked to the order
3099  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3100 
3101  // For every order having invoice already validated we need to decrease stock cause it's in physical stock
3102  $adeduire = 0;
3103  $sql = "SELECT sum(".$this->db->ifsql('f.type=2', -1, 1)." * fd.qty) as count FROM ".MAIN_DB_PREFIX."facturedet as fd ";
3104  $sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON fd.fk_facture = f.rowid";
3105  $sql .= " JOIN ".MAIN_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'))";
3106  $sql .= " JOIN ".MAIN_DB_PREFIX."commande as c ON el.fk_source = c.rowid";
3107  $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND f.fk_statut > ".Facture::STATUS_DRAFT." AND fd.fk_product = ".((int) $this->id);
3108 
3109  dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
3110  $resql = $this->db->query($sql);
3111  if ($resql) {
3112  if ($this->db->num_rows($resql) > 0) {
3113  $obj = $this->db->fetch_object($resql);
3114  $adeduire += $obj->count;
3115  }
3116  } else {
3117  $this->error = $this->db->error();
3118  return -1;
3119  }
3120 
3121  $this->stats_commande['qty'] -= $adeduire;
3122  }
3123  }
3124 
3125  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3126  $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
3127  if ($reshook > 0) {
3128  $this->stats_commande = $hookmanager->resArray['stats_commande'];
3129  }
3130  return 1;
3131  } else {
3132  $this->error = $this->db->error();
3133  return -1;
3134  }
3135  }
3136 
3137  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3147  public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
3148  {
3149  // phpcs:enable
3150  global $conf, $user, $hookmanager, $action;
3151 
3152  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
3153  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3154  $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
3155  $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
3156  $sql .= ", ".$this->db->prefix()."societe as s";
3157  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3158  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3159  }
3160  $sql .= " WHERE c.rowid = cd.fk_commande";
3161  $sql .= " AND c.fk_soc = s.rowid";
3162  $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
3163  $sql .= " AND cd.fk_product = ".((int) $this->id);
3164  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3165  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3166  }
3167  if ($socid > 0) {
3168  $sql .= " AND c.fk_soc = ".((int) $socid);
3169  }
3170  if ($filtrestatut != '') {
3171  $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
3172  }
3173  if (!empty($dateofvirtualstock)) {
3174  $sql .= " AND c.date_livraison <= '".$this->db->idate($dateofvirtualstock)."'";
3175  }
3176 
3177  $result = $this->db->query($sql);
3178  if ($result) {
3179  $obj = $this->db->fetch_object($result);
3180  $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
3181  $this->stats_commande_fournisseur['nb'] = $obj->nb;
3182  $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
3183  $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3184 
3185  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3186  $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
3187  if ($reshook > 0) {
3188  $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
3189  }
3190 
3191  return 1;
3192  } else {
3193  $this->error = $this->db->error().' sql='.$sql;
3194  return -1;
3195  }
3196  }
3197 
3198  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3208  public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
3209  {
3210  // phpcs:enable
3211  global $conf, $user, $hookmanager, $action;
3212 
3213  $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
3214  $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
3215  $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
3216  $sql .= ", ".$this->db->prefix()."commandedet as cd";
3217  $sql .= ", ".$this->db->prefix()."commande as c";
3218  $sql .= ", ".$this->db->prefix()."expedition as e";
3219  $sql .= ", ".$this->db->prefix()."societe as s";
3220  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3221  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3222  }
3223  $sql .= " WHERE e.rowid = ed.fk_expedition";
3224  $sql .= " AND c.rowid = cd.fk_commande";
3225  $sql .= " AND e.fk_soc = s.rowid";
3226  $sql .= " AND e.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
3227  $sql .= " AND ed.fk_origin_line = cd.rowid";
3228  $sql .= " AND cd.fk_product = ".((int) $this->id);
3229  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3230  $sql .= " AND e.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3231  }
3232  if ($socid > 0) {
3233  $sql .= " AND e.fk_soc = ".((int) $socid);
3234  }
3235  if ($filtrestatut <> '') {
3236  $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3237  }
3238  if (!empty($filterShipmentStatus)) {
3239  $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
3240  }
3241 
3242  $result = $this->db->query($sql);
3243  if ($result) {
3244  $obj = $this->db->fetch_object($result);
3245  $this->stats_expedition['customers'] = $obj->nb_customers;
3246  $this->stats_expedition['nb'] = $obj->nb;
3247  $this->stats_expedition['rows'] = $obj->nb_rows;
3248  $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
3249 
3250  // if it's a virtual product, maybe it is in sending by extension
3251  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3252  $TFather = $this->getFather();
3253  if (is_array($TFather) && !empty($TFather)) {
3254  foreach ($TFather as &$fatherData) {
3255  $pFather = new Product($this->db);
3256  $pFather->id = $fatherData['id'];
3257  $qtyCoef = $fatherData['qty'];
3258 
3259  if ($fatherData['incdec']) {
3260  $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
3261 
3262  $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
3263  $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
3264  $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
3265  $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
3266  }
3267  }
3268  }
3269  }
3270 
3271  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
3272  $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
3273  if ($reshook > 0) {
3274  $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
3275  }
3276 
3277  return 1;
3278  } else {
3279  $this->error = $this->db->error();
3280  return -1;
3281  }
3282  }
3283 
3284  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3294  public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
3295  {
3296  // phpcs:enable
3297  global $conf, $user, $hookmanager, $action;
3298 
3299  $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
3300  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3301  $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as fd";
3302  $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
3303  $sql .= ", ".$this->db->prefix()."societe as s";
3304  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3305  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3306  }
3307  $sql .= " WHERE cf.rowid = fd.fk_commande";
3308  $sql .= " AND cf.fk_soc = s.rowid";
3309  $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
3310  $sql .= " AND fd.fk_product = ".((int) $this->id);
3311  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3312  $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3313  }
3314  if ($socid > 0) {
3315  $sql .= " AND cf.fk_soc = ".((int) $socid);
3316  }
3317  if ($filtrestatut <> '') {
3318  $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3319  }
3320  if (!empty($dateofvirtualstock)) {
3321  $sql .= " AND fd.datec <= '".$this->db->idate($dateofvirtualstock)."'";
3322  }
3323 
3324  $result = $this->db->query($sql);
3325  if ($result) {
3326  $obj = $this->db->fetch_object($result);
3327  $this->stats_reception['suppliers'] = $obj->nb_suppliers;
3328  $this->stats_reception['nb'] = $obj->nb;
3329  $this->stats_reception['rows'] = $obj->nb_rows;
3330  $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
3331 
3332  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3333  $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
3334  if ($reshook > 0) {
3335  $this->stats_reception = $hookmanager->resArray['stats_reception'];
3336  }
3337 
3338  return 1;
3339  } else {
3340  $this->error = $this->db->error();
3341  return -1;
3342  }
3343  }
3344 
3345  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3355  public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
3356  {
3357  // phpcs:enable
3358  global $conf, $user, $hookmanager, $action;
3359 
3360  $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
3361  $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
3362  $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
3363  $sql .= ", ".$this->db->prefix()."mrp_mo as m";
3364  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
3365  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3366  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3367  }
3368  $sql .= " WHERE m.rowid = mp.fk_mo";
3369  $sql .= " AND m.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mrp').")";
3370  $sql .= " AND mp.fk_product = ".((int) $this->id);
3371  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3372  $sql .= " AND m.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3373  }
3374  if ($socid > 0) {
3375  $sql .= " AND m.fk_soc = ".((int) $socid);
3376  }
3377  if ($filtrestatut <> '') {
3378  $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
3379  }
3380  if (!empty($dateofvirtualstock)) {
3381  $sql .= " AND m.date_valid <= '".$this->db->idate($dateofvirtualstock)."'"; // better date to code ? end of production ?
3382  }
3383  $sql .= " GROUP BY role";
3384 
3385  $this->stats_mrptoconsume['customers'] = 0;
3386  $this->stats_mrptoconsume['nb'] = 0;
3387  $this->stats_mrptoconsume['rows'] = 0;
3388  $this->stats_mrptoconsume['qty'] = 0;
3389  $this->stats_mrptoproduce['customers'] = 0;
3390  $this->stats_mrptoproduce['nb'] = 0;
3391  $this->stats_mrptoproduce['rows'] = 0;
3392  $this->stats_mrptoproduce['qty'] = 0;
3393 
3394  $result = $this->db->query($sql);
3395  if ($result) {
3396  while ($obj = $this->db->fetch_object($result)) {
3397  if ($obj->role == 'toconsume') {
3398  $this->stats_mrptoconsume['customers'] += $obj->nb_customers;
3399  $this->stats_mrptoconsume['nb'] += $obj->nb;
3400  $this->stats_mrptoconsume['rows'] += $obj->nb_rows;
3401  $this->stats_mrptoconsume['qty'] += ($obj->qty ? $obj->qty : 0);
3402  }
3403  if ($obj->role == 'consumed') {
3404  //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
3405  //$this->stats_mrptoconsume['nb'] += $obj->nb;
3406  //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
3407  $this->stats_mrptoconsume['qty'] -= ($obj->qty ? $obj->qty : 0);
3408  }
3409  if ($obj->role == 'toproduce') {
3410  $this->stats_mrptoproduce['customers'] += $obj->nb_customers;
3411  $this->stats_mrptoproduce['nb'] += $obj->nb;
3412  $this->stats_mrptoproduce['rows'] += $obj->nb_rows;
3413  $this->stats_mrptoproduce['qty'] += ($obj->qty ? $obj->qty : 0);
3414  }
3415  if ($obj->role == 'produced') {
3416  //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
3417  //$this->stats_mrptoproduce['nb'] += $obj->nb;
3418  //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
3419  $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
3420  }
3421  }
3422 
3423  // Clean data
3424  if ($this->stats_mrptoconsume['qty'] < 0) {
3425  $this->stats_mrptoconsume['qty'] = 0;
3426  }
3427  if ($this->stats_mrptoproduce['qty'] < 0) {
3428  $this->stats_mrptoproduce['qty'] = 0;
3429  }
3430 
3431  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3432  $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
3433  if ($reshook > 0) {
3434  $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
3435  }
3436 
3437  return 1;
3438  } else {
3439  $this->error = $this->db->error();
3440  return -1;
3441  }
3442  }
3443 
3444  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3451  public function load_stats_contrat($socid = 0)
3452  {
3453  // phpcs:enable
3454  global $conf, $user, $hookmanager, $action;
3455 
3456  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3457  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3458  $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
3459  $sql .= ", ".$this->db->prefix()."contrat as c";
3460  $sql .= ", ".$this->db->prefix()."societe as s";
3461  if (empty($user->rights->societe->client->voir) && !$socid) {
3462  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3463  }
3464  $sql .= " WHERE c.rowid = cd.fk_contrat";
3465  $sql .= " AND c.fk_soc = s.rowid";
3466  $sql .= " AND c.entity IN (".getEntity('contract').")";
3467  $sql .= " AND cd.fk_product = ".((int) $this->id);
3468  if (empty($user->rights->societe->client->voir) && !$socid) {
3469  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3470  }
3471  //$sql.= " AND c.statut != 0";
3472  if ($socid > 0) {
3473  $sql .= " AND c.fk_soc = ".((int) $socid);
3474  }
3475 
3476  $result = $this->db->query($sql);
3477  if ($result) {
3478  $obj = $this->db->fetch_object($result);
3479  $this->stats_contrat['customers'] = $obj->nb_customers;
3480  $this->stats_contrat['nb'] = $obj->nb;
3481  $this->stats_contrat['rows'] = $obj->nb_rows;
3482  $this->stats_contrat['qty'] = $obj->qty ? $obj->qty : 0;
3483 
3484  // if it's a virtual product, maybe it is in contract by extension
3485  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3486  $TFather = $this->getFather();
3487  if (is_array($TFather) && !empty($TFather)) {
3488  foreach ($TFather as &$fatherData) {
3489  $pFather = new Product($this->db);
3490  $pFather->id = $fatherData['id'];
3491  $qtyCoef = $fatherData['qty'];
3492 
3493  if ($fatherData['incdec']) {
3494  $pFather->load_stats_contrat($socid);
3495 
3496  $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
3497  $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
3498  $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
3499  $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
3500  }
3501  }
3502  }
3503  }
3504 
3505  $parameters = array('socid' => $socid);
3506  $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
3507  if ($reshook > 0) {
3508  $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
3509  }
3510 
3511  return 1;
3512  } else {
3513  $this->error = $this->db->error().' sql='.$sql;
3514  return -1;
3515  }
3516  }
3517 
3518  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3525  public function load_stats_facture($socid = 0)
3526  {
3527  // phpcs:enable
3528  global $db, $conf, $user, $hookmanager, $action;
3529 
3530  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
3531  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
3532  $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
3533  $sql .= ", ".$this->db->prefix()."facture as f";
3534  $sql .= ", ".$this->db->prefix()."societe as s";
3535  if (empty($user->rights->societe->client->voir) && !$socid) {
3536  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3537  }
3538  $sql .= " WHERE f.rowid = fd.fk_facture";
3539  $sql .= " AND f.fk_soc = s.rowid";
3540  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3541  $sql .= " AND fd.fk_product = ".((int) $this->id);
3542  if (empty($user->rights->societe->client->voir) && !$socid) {
3543  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3544  }
3545  //$sql.= " AND f.fk_statut != 0";
3546  if ($socid > 0) {
3547  $sql .= " AND f.fk_soc = ".((int) $socid);
3548  }
3549 
3550  $result = $this->db->query($sql);
3551  if ($result) {
3552  $obj = $this->db->fetch_object($result);
3553  $this->stats_facture['customers'] = $obj->nb_customers;
3554  $this->stats_facture['nb'] = $obj->nb;
3555  $this->stats_facture['rows'] = $obj->nb_rows;
3556  $this->stats_facture['qty'] = $obj->qty ? $obj->qty : 0;
3557 
3558  // if it's a virtual product, maybe it is in invoice by extension
3559  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3560  $TFather = $this->getFather();
3561  if (is_array($TFather) && !empty($TFather)) {
3562  foreach ($TFather as &$fatherData) {
3563  $pFather = new Product($this->db);
3564  $pFather->id = $fatherData['id'];
3565  $qtyCoef = $fatherData['qty'];
3566 
3567  if ($fatherData['incdec']) {
3568  $pFather->load_stats_facture($socid);
3569 
3570  $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
3571  $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
3572  $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
3573  $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
3574  }
3575  }
3576  }
3577  }
3578 
3579  $parameters = array('socid' => $socid);
3580  $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
3581  if ($reshook > 0) {
3582  $this->stats_facture = $hookmanager->resArray['stats_facture'];
3583  }
3584 
3585  return 1;
3586  } else {
3587  $this->error = $this->db->error();
3588  return -1;
3589  }
3590  }
3591 
3592 
3593  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3600  public function load_stats_facturerec($socid = 0)
3601  {
3602  // phpcs:enable
3603  global $db, $conf, $user, $hookmanager;
3604 
3605  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
3606  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3607  $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_rec as fd";
3608  $sql .= ", ".MAIN_DB_PREFIX."facture_rec as f";
3609  $sql .= ", ".MAIN_DB_PREFIX."societe as s";
3610  if (empty($user->rights->societe->client->voir) && !$socid) {
3611  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3612  }
3613  $sql .= " WHERE f.rowid = fd.fk_facture";
3614  $sql .= " AND f.fk_soc = s.rowid";
3615  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3616  $sql .= " AND fd.fk_product = ".((int) $this->id);
3617  if (empty($user->rights->societe->client->voir) && !$socid) {
3618  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3619  }
3620  //$sql.= " AND f.fk_statut != 0";
3621  if ($socid > 0) {
3622  $sql .= " AND f.fk_soc = ".((int) $socid);
3623  }
3624 
3625  $result = $this->db->query($sql);
3626  if ($result) {
3627  $obj = $this->db->fetch_object($result);
3628  $this->stats_facturerec['customers'] = $obj->nb_customers;
3629  $this->stats_facturerec['nb'] = $obj->nb;
3630  $this->stats_facturerec['rows'] = $obj->nb_rows;
3631  $this->stats_facturerec['qty'] = $obj->qty ? $obj->qty : 0;
3632 
3633  // if it's a virtual product, maybe it is in invoice by extension
3634  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3635  $TFather = $this->getFather();
3636  if (is_array($TFather) && !empty($TFather)) {
3637  foreach ($TFather as &$fatherData) {
3638  $pFather = new Product($this->db);
3639  $pFather->id = $fatherData['id'];
3640  $qtyCoef = $fatherData['qty'];
3641 
3642  if ($fatherData['incdec']) {
3643  $pFather->load_stats_facture($socid);
3644 
3645  $this->stats_facturerec['customers'] += $pFather->stats_facturerec['customers'];
3646  $this->stats_facturerec['nb'] += $pFather->stats_facturerec['nb'];
3647  $this->stats_facturerec['rows'] += $pFather->stats_facturerec['rows'];
3648  $this->stats_facturerec['qty'] += $pFather->stats_facturerec['qty'] * $qtyCoef;
3649  }
3650  }
3651  }
3652  }
3653 
3654  $parameters = array('socid' => $socid);
3655  $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoiceRec', $parameters, $this, $action);
3656  if ($reshook > 0) {
3657  $this->stats_facturerec = $hookmanager->resArray['stats_facturerec'];
3658  }
3659 
3660  return 1;
3661  } else {
3662  $this->error = $this->db->error();
3663  return -1;
3664  }
3665  }
3666 
3667  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3674  public function load_stats_facture_fournisseur($socid = 0)
3675  {
3676  // phpcs:enable
3677  global $conf, $user, $hookmanager, $action;
3678 
3679  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
3680  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3681  $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
3682  $sql .= ", ".$this->db->prefix()."facture_fourn as f";
3683  $sql .= ", ".$this->db->prefix()."societe as s";
3684  if (empty($user->rights->societe->client->voir) && !$socid) {
3685  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3686  }
3687  $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
3688  $sql .= " AND f.fk_soc = s.rowid";
3689  $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
3690  $sql .= " AND fd.fk_product = ".((int) $this->id);
3691  if (empty($user->rights->societe->client->voir) && !$socid) {
3692  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3693  }
3694  //$sql.= " AND f.fk_statut != 0";
3695  if ($socid > 0) {
3696  $sql .= " AND f.fk_soc = ".((int) $socid);
3697  }
3698 
3699  $result = $this->db->query($sql);
3700  if ($result) {
3701  $obj = $this->db->fetch_object($result);
3702  $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers;
3703  $this->stats_facture_fournisseur['nb'] = $obj->nb;
3704  $this->stats_facture_fournisseur['rows'] = $obj->nb_rows;
3705  $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3706 
3707  $parameters = array('socid' => $socid);
3708  $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
3709  if ($reshook > 0) {
3710  $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
3711  }
3712 
3713  return 1;
3714  } else {
3715  $this->error = $this->db->error();
3716  return -1;
3717  }
3718  }
3719 
3720  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3729  private function _get_stats($sql, $mode, $year = 0)
3730  {
3731  // phpcs:enable
3732  $tab = array();
3733 
3734  $resql = $this->db->query($sql);
3735  if ($resql) {
3736  $num = $this->db->num_rows($resql);
3737  $i = 0;
3738  while ($i < $num) {
3739  $arr = $this->db->fetch_array($resql);
3740  $keyfortab = (string) $arr[1];
3741  if ($year == -1) {
3742  $keyfortab = substr($keyfortab, -2);
3743  }
3744 
3745  if ($mode == 'byunit') {
3746  $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
3747  } elseif ($mode == 'bynumber') {
3748  $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
3749  }
3750  $i++;
3751  }
3752  } else {
3753  $this->error = $this->db->error().' sql='.$sql;
3754  return -1;
3755  }
3756 
3757  if (empty($year)) {
3758  $year = strftime('%Y', time());
3759  $month = strftime('%m', time());
3760  } elseif ($year == -1) {
3761  $year = '';
3762  $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
3763  } else {
3764  $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
3765  }
3766 
3767  $result = array();
3768 
3769  for ($j = 0; $j < 12; $j++) {
3770  // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
3771  $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
3772 
3773  //print $idx.'-'.$year.'-'.$month.'<br>';
3774  $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
3775  // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
3776 
3777  $month = "0".($month - 1);
3778  if (dol_strlen($month) == 3) {
3779  $month = substr($month, 1);
3780  }
3781  if ($month == 0) {
3782  $month = 12;
3783  $year = $year - 1;
3784  }
3785  }
3786 
3787  return array_reverse($result);
3788  }
3789 
3790 
3791  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3802  public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3803  {
3804  // phpcs:enable
3805  global $conf;
3806  global $user;
3807 
3808  $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
3809  if ($mode == 'bynumber') {
3810  $sql .= ", count(DISTINCT f.rowid)";
3811  }
3812  $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
3813  if ($filteronproducttype >= 0) {
3814  $sql .= ", ".$this->db->prefix()."product as p";
3815  }
3816  if (empty($user->rights->societe->client->voir) && !$socid) {
3817  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3818  }
3819  $sql .= " WHERE f.rowid = d.fk_facture";
3820  if ($this->id > 0) {
3821  $sql .= " AND d.fk_product = ".((int) $this->id);
3822  } else {
3823  $sql .= " AND d.fk_product > 0";
3824  }
3825  if ($filteronproducttype >= 0) {
3826  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3827  }
3828  $sql .= " AND f.fk_soc = s.rowid";
3829  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3830  if (empty($user->rights->societe->client->voir) && !$socid) {
3831  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3832  }
3833  if ($socid > 0) {
3834  $sql .= " AND f.fk_soc = $socid";
3835  }
3836  $sql .= $morefilter;
3837  $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
3838  $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
3839 
3840  return $this->_get_stats($sql, $mode, $year);
3841  }
3842 
3843 
3844  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3855  public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3856  {
3857  // phpcs:enable
3858  global $conf;
3859  global $user;
3860 
3861  $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
3862  if ($mode == 'bynumber') {
3863  $sql .= ", count(DISTINCT f.rowid)";
3864  }
3865  $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
3866  if ($filteronproducttype >= 0) {
3867  $sql .= ", ".$this->db->prefix()."product as p";
3868  }
3869  if (empty($user->rights->societe->client->voir) && !$socid) {
3870  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3871  }
3872  $sql .= " WHERE f.rowid = d.fk_facture_fourn";
3873  if ($this->id > 0) {
3874  $sql .= " AND d.fk_product = ".((int) $this->id);
3875  } else {
3876  $sql .= " AND d.fk_product > 0";
3877  }
3878  if ($filteronproducttype >= 0) {
3879  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3880  }
3881  $sql .= " AND f.fk_soc = s.rowid";
3882  $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
3883  if (empty($user->rights->societe->client->voir) && !$socid) {
3884  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3885  }
3886  if ($socid > 0) {
3887  $sql .= " AND f.fk_soc = $socid";
3888  }
3889  $sql .= $morefilter;
3890  $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
3891  $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
3892 
3893  return $this->_get_stats($sql, $mode, $year);
3894  }
3895 
3896  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3907  public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3908  {
3909  // phpcs:enable
3910  global $conf, $user;
3911 
3912  $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')";
3913  if ($mode == 'bynumber') {
3914  $sql .= ", count(DISTINCT p.rowid)";
3915  }
3916  $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
3917  if ($filteronproducttype >= 0) {
3918  $sql .= ", ".$this->db->prefix()."product as prod";
3919  }
3920  if (empty($user->rights->societe->client->voir) && !$socid) {
3921  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3922  }
3923  $sql .= " WHERE p.rowid = d.fk_propal";
3924  if ($this->id > 0) {
3925  $sql .= " AND d.fk_product = ".((int) $this->id);
3926  } else {
3927  $sql .= " AND d.fk_product > 0";
3928  }
3929  if ($filteronproducttype >= 0) {
3930  $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
3931  }
3932  $sql .= " AND p.fk_soc = s.rowid";
3933  $sql .= " AND p.entity IN (".getEntity('propal').")";
3934  if (empty($user->rights->societe->client->voir) && !$socid) {
3935  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3936  }
3937  if ($socid > 0) {
3938  $sql .= " AND p.fk_soc = ".((int) $socid);
3939  }
3940  $sql .= $morefilter;
3941  $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
3942  $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
3943 
3944  return $this->_get_stats($sql, $mode, $year);
3945  }
3946 
3947  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3958  public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3959  {
3960  // phpcs:enable
3961  global $conf;
3962  global $user;
3963 
3964  $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')";
3965  if ($mode == 'bynumber') {
3966  $sql .= ", count(DISTINCT p.rowid)";
3967  }
3968  $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
3969  if ($filteronproducttype >= 0) {
3970  $sql .= ", ".$this->db->prefix()."product as prod";
3971  }
3972  if (empty($user->rights->societe->client->voir) && !$socid) {
3973  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3974  }
3975  $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
3976  if ($this->id > 0) {
3977  $sql .= " AND d.fk_product = ".((int) $this->id);
3978  } else {
3979  $sql .= " AND d.fk_product > 0";
3980  }
3981  if ($filteronproducttype >= 0) {
3982  $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
3983  }
3984  $sql .= " AND p.fk_soc = s.rowid";
3985  $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
3986  if (empty($user->rights->societe->client->voir) && !$socid) {
3987  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3988  }
3989  if ($socid > 0) {
3990  $sql .= " AND p.fk_soc = ".((int) $socid);
3991  }
3992  $sql .= $morefilter;
3993  $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
3994  $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
3995 
3996  return $this->_get_stats($sql, $mode, $year);
3997  }
3998 
3999  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4010  public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4011  {
4012  // phpcs:enable
4013  global $conf, $user;
4014 
4015  $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
4016  if ($mode == 'bynumber') {
4017  $sql .= ", count(DISTINCT c.rowid)";
4018  }
4019  $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
4020  if ($filteronproducttype >= 0) {
4021  $sql .= ", ".$this->db->prefix()."product as p";
4022  }
4023  if (empty($user->rights->societe->client->voir) && !$socid) {
4024  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4025  }
4026  $sql .= " WHERE c.rowid = d.fk_commande";
4027  if ($this->id > 0) {
4028  $sql .= " AND d.fk_product = ".((int) $this->id);
4029  } else {
4030  $sql .= " AND d.fk_product > 0";
4031  }
4032  if ($filteronproducttype >= 0) {
4033  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4034  }
4035  $sql .= " AND c.fk_soc = s.rowid";
4036  $sql .= " AND c.entity IN (".getEntity('commande').")";
4037  if (empty($user->rights->societe->client->voir) && !$socid) {
4038  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4039  }
4040  if ($socid > 0) {
4041  $sql .= " AND c.fk_soc = ".((int) $socid);
4042  }
4043  $sql .= $morefilter;
4044  $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
4045  $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
4046 
4047  return $this->_get_stats($sql, $mode, $year);
4048  }
4049 
4050  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4061  public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4062  {
4063  // phpcs:enable
4064  global $conf, $user;
4065 
4066  $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
4067  if ($mode == 'bynumber') {
4068  $sql .= ", count(DISTINCT c.rowid)";
4069  }
4070  $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
4071  if ($filteronproducttype >= 0) {
4072  $sql .= ", ".$this->db->prefix()."product as p";
4073  }
4074  if (empty($user->rights->societe->client->voir) && !$socid) {
4075  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4076  }
4077  $sql .= " WHERE c.rowid = d.fk_commande";
4078  if ($this->id > 0) {
4079  $sql .= " AND d.fk_product = ".((int) $this->id);
4080  } else {
4081  $sql .= " AND d.fk_product > 0";
4082  }
4083  if ($filteronproducttype >= 0) {
4084  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4085  }
4086  $sql .= " AND c.fk_soc = s.rowid";
4087  $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
4088  if (empty($user->rights->societe->client->voir) && !$socid) {
4089  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4090  }
4091  if ($socid > 0) {
4092  $sql .= " AND c.fk_soc = ".((int) $socid);
4093  }
4094  $sql .= $morefilter;
4095  $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
4096  $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
4097 
4098  return $this->_get_stats($sql, $mode, $year);
4099  }
4100 
4101  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4112  public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4113  {
4114  // phpcs:enable
4115  global $conf, $user;
4116 
4117  $sql = "SELECT sum(d.qty), date_format(c.date_contrat, '%Y%m')";
4118  if ($mode == 'bynumber') {
4119  $sql .= ", count(DISTINCT c.rowid)";
4120  }
4121  $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
4122  if ($filteronproducttype >= 0) {
4123  $sql .= ", ".$this->db->prefix()."product as p";
4124  }
4125  if (empty($user->rights->societe->client->voir) && !$socid) {
4126  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4127  }
4128 
4129  $sql .= " WHERE c.entity IN (".getEntity('contract').")";
4130  $sql .= " AND c.rowid = d.fk_contrat";
4131 
4132  if ($this->id > 0) {
4133  $sql .= " AND d.fk_product = ".((int) $this->id);
4134  } else {
4135  $sql .= " AND d.fk_product > 0";
4136  }
4137  if ($filteronproducttype >= 0) {
4138  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4139  }
4140  $sql .= " AND c.fk_soc = s.rowid";
4141 
4142  if (empty($user->rights->societe->client->voir) && !$socid) {
4143  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4144  }
4145  if ($socid > 0) {
4146  $sql .= " AND c.fk_soc = ".((int) $socid);
4147  }
4148  $sql .= $morefilter;
4149  $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
4150  $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
4151 
4152  return $this->_get_stats($sql, $mode, $year);
4153  }
4154 
4155  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4166  public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4167  {
4168  // phpcs:enable
4169  global $conf, $user;
4170 
4171  $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
4172  if ($mode == 'bynumber') {
4173  $sql .= ", count(DISTINCT d.rowid)";
4174  }
4175  $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
4176  if ($filteronproducttype >= 0) {
4177  $sql .= ", ".$this->db->prefix()."product as p";
4178  }
4179  if (empty($user->rights->societe->client->voir) && !$socid) {
4180  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4181  }
4182 
4183  $sql .= " WHERE d.entity IN (".getEntity('mo').")";
4184  $sql .= " AND d.status > 0";
4185 
4186  if ($this->id > 0) {
4187  $sql .= " AND d.fk_product = ".((int) $this->id);
4188  } else {
4189  $sql .= " AND d.fk_product > 0";
4190  }
4191  if ($filteronproducttype >= 0) {
4192  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4193  }
4194 
4195  if (empty($user->rights->societe->client->voir) && !$socid) {
4196  $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4197  }
4198  if ($socid > 0) {
4199  $sql .= " AND d.fk_soc = ".((int) $socid);
4200  }
4201  $sql .= $morefilter;
4202  $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
4203  $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
4204 
4205  return $this->_get_stats($sql, $mode, $year);
4206  }
4207 
4208  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4218  public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
4219  {
4220  // phpcs:enable
4221  // Clean parameters
4222  if (!is_numeric($id_pere)) {
4223  $id_pere = 0;
4224  }
4225  if (!is_numeric($id_fils)) {
4226  $id_fils = 0;
4227  }
4228  if (!is_numeric($incdec)) {
4229  $incdec = 0;
4230  }
4231 
4232  $result = $this->del_sousproduit($id_pere, $id_fils);
4233  if ($result < 0) {
4234  return $result;
4235  }
4236 
4237  // Check not already father of id_pere (to avoid father -> child -> father links)
4238  $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
4239  $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
4240  if (!$this->db->query($sql)) {
4241  dol_print_error($this->db);
4242  return -1;
4243  } else {
4244  //Selection of the highest row
4245  $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
4246  $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
4247  $resql = $this->db->query($sql);
4248  if ($resql) {
4249  $obj = $this->db->fetch_object($resql);
4250  $rank = $obj->max_rank + 1;
4251  //Addition of a product with the highest rank +1
4252  $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
4253  $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".price2num($incdec, 'MS').", ".((int) $rank).")";
4254  if (! $this->db->query($sql)) {
4255  dol_print_error($this->db);
4256  return -1;
4257  } else {
4258  return 1;
4259  }
4260  } else {
4261  dol_print_error($this->db);
4262  return -1;
4263  }
4264  }
4265  }
4266 
4267  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4277  public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
4278  {
4279  // phpcs:enable
4280  // Clean parameters
4281  if (!is_numeric($id_pere)) {
4282  $id_pere = 0;
4283  }
4284  if (!is_numeric($id_fils)) {
4285  $id_fils = 0;
4286  }
4287  if (!is_numeric($incdec)) {
4288  $incdec = 1;
4289  }
4290  if (!is_numeric($qty)) {
4291  $qty = 1;
4292  }
4293 
4294  $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
4295  $sql .= 'qty = '.price2num($qty, 'MS');
4296  $sql .= ',incdec = '.price2num($incdec, 'MS');
4297  $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
4298 
4299  if (!$this->db->query($sql)) {
4300  dol_print_error($this->db);
4301  return -1;
4302  } else {
4303  return 1;
4304  }
4305  }
4306 
4307  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4315  public function del_sousproduit($fk_parent, $fk_child)
4316  {
4317  // phpcs:enable
4318  if (!is_numeric($fk_parent)) {
4319  $fk_parent = 0;
4320  }
4321  if (!is_numeric($fk_child)) {
4322  $fk_child = 0;
4323  }
4324 
4325  $sql = "DELETE FROM ".$this->db->prefix()."product_association";
4326  $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
4327  $sql .= " AND fk_product_fils = ".((int) $fk_child);
4328 
4329  dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
4330  if (!$this->db->query($sql)) {
4331  dol_print_error($this->db);
4332  return -1;
4333  }
4334 
4335  // Updated ranks so that none are missing
4336  $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
4337  $sqlrank.= " WHERE fk_product_pere = ".((int) $fk_parent);
4338  $sqlrank.= " ORDER BY rang";
4339  $resqlrank = $this->db->query($sqlrank);
4340  if ($resqlrank) {
4341  $cpt = 0;
4342  while ($objrank = $this->db->fetch_object($resqlrank)) {
4343  $cpt++;
4344  $sql = "UPDATE ".$this->db->prefix()."product_association";
4345  $sql.= " SET rang = ".((int) $cpt);
4346  $sql.= " WHERE rowid = ".((int) $objrank->rowid);
4347  if (! $this->db->query($sql)) {
4348  dol_print_error($this->db);
4349  return -1;
4350  }
4351  }
4352  }
4353  return 1;
4354  }
4355 
4356  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4364  public function is_sousproduit($fk_parent, $fk_child)
4365  {
4366  // phpcs:enable
4367  $sql = "SELECT fk_product_pere, qty, incdec";
4368  $sql .= " FROM ".$this->db->prefix()."product_association";
4369  $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
4370  $sql .= " AND fk_product_fils = ".((int) $fk_child);
4371 
4372  $result = $this->db->query($sql);
4373  if ($result) {
4374  $num = $this->db->num_rows($result);
4375 
4376  if ($num > 0) {
4377  $obj = $this->db->fetch_object($result);
4378 
4379  $this->is_sousproduit_qty = $obj->qty;
4380  $this->is_sousproduit_incdec = $obj->incdec;
4381 
4382  return true;
4383  } else {
4384  return false;
4385  }
4386  } else {
4387  dol_print_error($this->db);
4388  return -1;
4389  }
4390  }
4391 
4392 
4393  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4404  public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
4405  {
4406  // phpcs:enable
4407  global $conf;
4408 
4409  $now = dol_now();
4410 
4411  dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
4412 
4413  // Clean parameters
4414  $quantity = price2num($quantity, 'MS');
4415 
4416  if ($ref_fourn) {
4417  $sql = "SELECT rowid, fk_product";
4418  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4419  $sql .= " WHERE fk_soc = ".((int) $id_fourn);
4420  $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
4421  $sql .= " AND fk_product <> ".((int) $this->id);
4422  $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
4423 
4424  $resql = $this->db->query($sql);
4425  if ($resql) {
4426  $obj = $this->db->fetch_object($resql);
4427  if ($obj) {
4428  // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
4429  $this->product_id_already_linked = $obj->fk_product;
4430  return -3;
4431  }
4432  $this->db->free($resql);
4433  }
4434  }
4435 
4436  $sql = "SELECT rowid";
4437  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4438  $sql .= " WHERE fk_soc = ".((int) $id_fourn);
4439  if ($ref_fourn) {
4440  $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
4441  } else {
4442  $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
4443  }
4444  $sql .= " AND quantity = ".((float) $quantity);
4445  $sql .= " AND fk_product = ".((int) $this->id);
4446  $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
4447 
4448  $resql = $this->db->query($sql);
4449  if ($resql) {
4450  $obj = $this->db->fetch_object($resql);
4451 
4452  // The reference supplier does not exist, we create it for this product.
4453  if (empty($obj)) {
4454  $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
4455  $sql .= "datec";
4456  $sql .= ", entity";
4457  $sql .= ", fk_product";
4458  $sql .= ", fk_soc";
4459  $sql .= ", ref_fourn";
4460  $sql .= ", quantity";
4461  $sql .= ", fk_user";
4462  $sql .= ", tva_tx";
4463  $sql .= ") VALUES (";
4464  $sql .= "'".$this->db->idate($now)."'";
4465  $sql .= ", ".$conf->entity;
4466  $sql .= ", ".$this->id;
4467  $sql .= ", ".$id_fourn;
4468  $sql .= ", '".$this->db->escape($ref_fourn)."'";
4469  $sql .= ", ".$quantity;
4470  $sql .= ", ".$user->id;
4471  $sql .= ", 0";
4472  $sql .= ")";
4473 
4474  if ($this->db->query($sql)) {
4475  $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
4476  return 1;
4477  } else {
4478  $this->error = $this->db->lasterror();
4479  return -1;
4480  }
4481  } else {
4482  // If the supplier price already exists for this product and quantity
4483  $this->product_fourn_price_id = $obj->rowid;
4484  return 0;
4485  }
4486  } else {
4487  $this->error = $this->db->lasterror();
4488  return -2;
4489  }
4490  }
4491 
4492 
4493  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4499  public function list_suppliers()
4500  {
4501  // phpcs:enable
4502  global $conf;
4503 
4504  $list = array();
4505 
4506  $sql = "SELECT DISTINCT p.fk_soc";
4507  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
4508  $sql .= " WHERE p.fk_product = ".((int) $this->id);
4509  $sql .= " AND p.entity = ".((int) $conf->entity);
4510 
4511  $result = $this->db->query($sql);
4512  if ($result) {
4513  $num = $this->db->num_rows($result);
4514  $i = 0;
4515  while ($i < $num) {
4516  $obj = $this->db->fetch_object($result);
4517  $list[$i] = $obj->fk_soc;
4518  $i++;
4519  }
4520  }
4521 
4522  return $list;
4523  }
4524 
4525  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4533  public function clone_price($fromId, $toId)
4534  {
4535  global $conf, $user;
4536 
4537  $now = dol_now();
4538 
4539  $this->db->begin();
4540 
4541  // prices
4542  $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
4543  $sql .= " entity";
4544  $sql .= ", fk_product";
4545  $sql .= ", date_price";
4546  $sql .= ", price_level";
4547  $sql .= ", price";
4548  $sql .= ", price_ttc";
4549  $sql .= ", price_min";
4550  $sql .= ", price_min_ttc";
4551  $sql .= ", price_base_type";
4552  $sql .= ", default_vat_code";
4553  $sql .= ", tva_tx";
4554  $sql .= ", recuperableonly";
4555  $sql .= ", localtax1_tx";
4556  $sql .= ", localtax1_type";
4557  $sql .= ", localtax2_tx";
4558  $sql .= ", localtax2_type";
4559  $sql .= ", fk_user_author";
4560  $sql .= ", tosell";
4561  $sql .= ", price_by_qty";
4562  $sql .= ", fk_price_expression";
4563  $sql .= ", fk_multicurrency";
4564  $sql .= ", multicurrency_code";
4565  $sql .= ", multicurrency_tx";
4566  $sql .= ", multicurrency_price";
4567  $sql .= ", multicurrency_price_ttc";
4568  $sql .= ")";
4569  $sql .= " SELECT";
4570  $sql .= " entity";
4571  $sql .= ", ".$toId;
4572  $sql .= ", '".$this->db->idate($now)."'";
4573  $sql .= ", price_level";
4574  $sql .= ", price";
4575  $sql .= ", price_ttc";
4576  $sql .= ", price_min";
4577  $sql .= ", price_min_ttc";
4578  $sql .= ", price_base_type";
4579  $sql .= ", default_vat_code";
4580  $sql .= ", tva_tx";
4581  $sql .= ", recuperableonly";
4582  $sql .= ", localtax1_tx";
4583  $sql .= ", localtax1_type";
4584  $sql .= ", localtax2_tx";
4585  $sql .= ", localtax2_type";
4586  $sql .= ", ".$user->id;
4587  $sql .= ", tosell";
4588  $sql .= ", price_by_qty";
4589  $sql .= ", fk_price_expression";
4590  $sql .= ", fk_multicurrency";
4591  $sql .= ", multicurrency_code";
4592  $sql .= ", multicurrency_tx";
4593  $sql .= ", multicurrency_price";
4594  $sql .= ", multicurrency_price_ttc";
4595  $sql .= " FROM ".$this->db->prefix()."product_price";
4596  $sql .= " WHERE fk_product = ".((int) $fromId);
4597  $sql .= " ORDER BY date_price DESC";
4598  if ($conf->global->PRODUIT_MULTIPRICES_LIMIT > 0) {
4599  $sql .= " LIMIT ".$conf->global->PRODUIT_MULTIPRICES_LIMIT;
4600  }
4601 
4602  dol_syslog(__METHOD__, LOG_DEBUG);
4603  $resql = $this->db->query($sql);
4604  if (!$resql) {
4605  $this->db->rollback();
4606  return -1;
4607  }
4608 
4609  $this->db->commit();
4610  return 1;
4611  }
4612 
4613  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4621  public function clone_associations($fromId, $toId)
4622  {
4623  // phpcs:enable
4624  $this->db->begin();
4625 
4626  $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty)';
4627  $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".$this->db->prefix()."product_association";
4628  $sql .= " WHERE fk_product_pere = ".((int) $fromId);
4629 
4630  dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
4631  if (!$this->db->query($sql)) {
4632  $this->db->rollback();
4633  return -1;
4634  }
4635 
4636  $this->db->commit();
4637  return 1;
4638  }
4639 
4640  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4648  public function clone_fournisseurs($fromId, $toId)
4649  {
4650  // phpcs:enable
4651  $this->db->begin();
4652 
4653  $now = dol_now();
4654 
4655  // les fournisseurs
4656  /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
4657  . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
4658  . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author"
4659  . " FROM ".$this->db->prefix()."product_fournisseur"
4660  . " WHERE fk_product = ".((int) $fromId);
4661 
4662  if ( ! $this->db->query($sql ) )
4663  {
4664  $this->db->rollback();
4665  return -1;
4666  }*/
4667 
4668  // les prix de fournisseurs.
4669  $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
4670  $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)";
4671  $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user";
4672  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4673  $sql .= " WHERE fk_product = ".((int) $fromId);
4674 
4675  dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
4676  $resql = $this->db->query($sql);
4677  if (!$resql) {
4678  $this->db->rollback();
4679  return -1;
4680  } else {
4681  $this->db->commit();
4682  return 1;
4683  }
4684  }
4685 
4686  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4699  public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
4700  {
4701  // phpcs:enable
4702  global $conf, $langs;
4703 
4704  $tmpproduct = null;
4705  //var_dump($prod);
4706  foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
4707  if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
4708  $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
4709  $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
4710  $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
4711  $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
4712  $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
4713 
4714  if ($multiply < 1) {
4715  $multiply = 1;
4716  }
4717 
4718  //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
4719  if (is_null($tmpproduct)) {
4720  $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
4721  }
4722  $tmpproduct->fetch($id); // Load product to get ->ref
4723 
4724  if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
4725  $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
4726  }
4727 
4728  $this->res[] = array(
4729  'id'=>$id, // Id product
4730  'id_parent'=>$id_parent,
4731  'ref'=>$tmpproduct->ref, // Ref product
4732  'nb'=>$nb, // Nb of units that compose parent product
4733  'nb_total'=>$nb * $multiply, // Nb of units for all nb of product
4734  'stock'=>$tmpproduct->stock_reel, // Stock
4735  'stock_alert'=>$tmpproduct->seuil_stock_alerte, // Stock alert
4736  'label'=>$label,
4737  'fullpath'=>$compl_path.$label, // Label
4738  'type'=>$type, // Nb of units that compose parent product
4739  'desiredstock'=>$tmpproduct->desiredstock,
4740  'level'=>$level,
4741  'incdec'=>$incdec,
4742  'entity'=>$tmpproduct->entity
4743  );
4744 
4745  // Recursive call if there is childs to child
4746  if (isset($desc_pere['childs']) && is_array($desc_pere['childs'])) {
4747  //print 'YYY We go down for '.$desc_pere[3]." -> \n";
4748  $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load);
4749  }
4750  }
4751  }
4752  }
4753 
4754  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4763  public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
4764  {
4765  // phpcs:enable
4766  $this->res = array();
4767  if (isset($this->sousprods) && is_array($this->sousprods)) {
4768  foreach ($this->sousprods as $prod_name => $desc_product) {
4769  if (is_array($desc_product)) {
4770  $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load);
4771  }
4772  }
4773  }
4774  //var_dump($this->res);
4775  return $this->res;
4776  }
4777 
4785  public function hasFatherOrChild($mode = 0)
4786  {
4787  $nb = 0;
4788 
4789  $sql = "SELECT COUNT(pa.rowid) as nb";
4790  $sql .= " FROM ".$this->db->prefix()."product_association as pa";
4791  if ($mode == 0) {
4792  $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
4793  } elseif ($mode == -1) {
4794  $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)
4795  } elseif ($mode == 1) {
4796  $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)
4797  }
4798 
4799  $resql = $this->db->query($sql);
4800  if ($resql) {
4801  $obj = $this->db->fetch_object($resql);
4802  if ($obj) {
4803  $nb = $obj->nb;
4804  }
4805  } else {
4806  return -1;
4807  }
4808 
4809  return $nb;
4810  }
4811 
4817  public function hasVariants()
4818  {
4819  $nb = 0;
4820  $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
4821  $sql .= " AND entity IN (".getEntity('product').")";
4822 
4823  $resql = $this->db->query($sql);
4824  if ($resql) {
4825  $obj = $this->db->fetch_object($resql);
4826  if ($obj) {
4827  $nb = $obj->nb;
4828  }
4829  }
4830 
4831  return $nb;
4832  }
4833 
4834 
4840  public function isVariant()
4841  {
4842  global $conf;
4843  if (isModEnabled('variants')) {
4844  $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
4845 
4846  $query = $this->db->query($sql);
4847 
4848  if ($query) {
4849  if (!$this->db->num_rows($query)) {
4850  return false;
4851  }
4852  return true;
4853  } else {
4854  dol_print_error($this->db);
4855  return -1;
4856  }
4857  } else {
4858  return false;
4859  }
4860  }
4861 
4868  public function getFather()
4869  {
4870  $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";
4871  $sql .= ", p.tosell as status, p.tobuy as status_buy";
4872  $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
4873  $sql .= " ".$this->db->prefix()."product as p";
4874  $sql .= " WHERE p.rowid = pa.fk_product_pere";
4875  $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
4876 
4877  $res = $this->db->query($sql);
4878  if ($res) {
4879  $prods = array();
4880  while ($record = $this->db->fetch_array($res)) {
4881  // $record['id'] = $record['rowid'] = id of father
4882  $prods[$record['id']]['id'] = $record['rowid'];
4883  $prods[$record['id']]['ref'] = $record['ref'];
4884  $prods[$record['id']]['label'] = $record['label'];
4885  $prods[$record['id']]['qty'] = $record['qty'];
4886  $prods[$record['id']]['incdec'] = $record['incdec'];
4887  $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
4888  $prods[$record['id']]['entity'] = $record['entity'];
4889  $prods[$record['id']]['status'] = $record['status'];
4890  $prods[$record['id']]['status_buy'] = $record['status_buy'];
4891  }
4892  return $prods;
4893  } else {
4894  dol_print_error($this->db);
4895  return -1;
4896  }
4897  }
4898 
4899 
4909  public function getChildsArbo($id, $firstlevelonly = 0, $level = 1, $parents = array())
4910  {
4911  global $alreadyfound;
4912 
4913  if (empty($id)) {
4914  return array();
4915  }
4916 
4917  $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
4918  $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
4919  $sql .= " pa.rowid as fk_association, pa.rang";
4920  $sql .= " FROM ".$this->db->prefix()."product as p,";
4921  $sql .= " ".$this->db->prefix()."product_association as pa";
4922  $sql .= " WHERE p.rowid = pa.fk_product_fils";
4923  $sql .= " AND pa.fk_product_pere = ".((int) $id);
4924  $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
4925  $sql.= " ORDER BY pa.rang";
4926 
4927  dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level. ' parents='.(is_array($parents)?implode(',', $parents):$parents), LOG_DEBUG);
4928 
4929  if ($level == 1) {
4930  $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly
4931  }
4932  // Protection against infinite loop
4933  if ($level > 30) {
4934  return array();
4935  }
4936 
4937  $res = $this->db->query($sql);
4938  if ($res) {
4939  $prods = array();
4940  while ($rec = $this->db->fetch_array($res)) {
4941  if (!empty($alreadyfound[$rec['rowid']])) {
4942  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);
4943  if (in_array($rec['id'], $parents)) {
4944  continue; // We discard this child if it is already found at a higher level in tree in the same branch.
4945  }
4946  }
4947  $alreadyfound[$rec['rowid']] = 1;
4948  $prods[$rec['rowid']] = array(
4949  0=>$rec['rowid'],
4950  1=>$rec['qty'],
4951  2=>$rec['fk_product_type'],
4952  3=>$this->db->escape($rec['label']),
4953  4=>$rec['incdec'],
4954  5=>$rec['ref'],
4955  6=>$rec['fk_association'],
4956  7=>$rec['rang']
4957  );
4958  //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
4959  //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
4960  if (empty($firstlevelonly)) {
4961  $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1, array_push($parents, $rec['rowid']));
4962  foreach ($listofchilds as $keyChild => $valueChild) {
4963  $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
4964  }
4965  }
4966  }
4967 
4968  return $prods;
4969  } else {
4970  dol_print_error($this->db);
4971  return -1;
4972  }
4973  }
4974 
4975  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4982  public function get_sousproduits_arbo()
4983  {
4984  // phpcs:enable
4985  $parent = array();
4986 
4987  foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
4988  $parent[$this->label][$keyChild] = $valueChild;
4989  }
4990  foreach ($parent as $key => $value) { // key=label, value is array of childs
4991  $this->sousprods[$key] = $value;
4992  }
4993  }
4994 
5008  public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
5009  {
5010  global $conf, $langs, $hookmanager;
5011  include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
5012 
5013  $result = ''; $label = '';
5014 
5015  $newref = $this->ref;
5016  if ($maxlength) {
5017  $newref = dol_trunc($newref, $maxlength, 'middle');
5018  }
5019 
5020  if (!empty($this->entity)) {
5021  $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
5022  if ($this->nbphoto > 0) {
5023  $label .= '<div class="photointooltip floatright">';
5024  $label .= $tmpphoto;
5025  $label .= '</div>';
5026  //$label .= '<div style="clear: both;"></div>';
5027  }
5028  }
5029 
5030  if ($this->type == Product::TYPE_PRODUCT) {
5031  $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
5032  } elseif ($this->type == Product::TYPE_SERVICE) {
5033  $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
5034  }
5035  if (isset($this->status) && isset($this->status_buy)) {
5036  $label .= ' '.$this->getLibStatut(5, 0);
5037  $label .= ' '.$this->getLibStatut(5, 1);
5038  }
5039 
5040  if (!empty($this->ref)) {
5041  $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
5042  }
5043  if (!empty($this->label)) {
5044  $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
5045  }
5046  if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
5047  if (isModEnabled('productbatch')) {
5048  $langs->load("productbatch");
5049  $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
5050  }
5051  }
5052  if (isModEnabled('barcode')) {
5053  $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
5054  }
5055 
5056  if ($this->type == Product::TYPE_PRODUCT) {
5057  if ($this->weight) {
5058  $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
5059  }
5060  $labelsize = "";
5061  if ($this->length) {
5062  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
5063  }
5064  if ($this->width) {
5065  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
5066  }
5067  if ($this->height) {
5068  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
5069  }
5070  if ($labelsize) {
5071  $label .= "<br>".$labelsize;
5072  }
5073 
5074  $labelsurfacevolume = "";
5075  if ($this->surface) {
5076  $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
5077  }
5078  if ($this->volume) {
5079  $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
5080  }
5081  if ($labelsurfacevolume) {
5082  $label .= "<br>".$labelsurfacevolume;
5083  }
5084  }
5085  if (!empty($this->pmp) && $this->pmp) {
5086  $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
5087  }
5088 
5089  if (isModEnabled('accounting')) {
5090  if ($this->status && isset($this->accountancy_code_sell)) {
5091  include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
5092  $label .= '<br>';
5093  $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
5094  $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
5095  $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
5096  }
5097  if ($this->status_buy && isset($this->accountancy_code_buy)) {
5098  include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
5099  if (empty($this->status)) {
5100  $label .= '<br>';
5101  }
5102  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
5103  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
5104  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
5105  }
5106  }
5107 
5108  $linkclose = '';
5109  if (empty($notooltip)) {
5110  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
5111  $label = $langs->trans("ShowProduct");
5112  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
5113  }
5114 
5115  $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
5116  $linkclose .= ' class="nowraponall classfortooltip'.($morecss ? ' '.$morecss : '').'"';
5117  } else {
5118  $linkclose = ' class="nowraponall'.($morecss ? ' '.$morecss : '').'"';
5119  }
5120 
5121  if ($option == 'supplier' || $option == 'category') {
5122  $url = DOL_URL_ROOT.'/product/fournisseurs.php?id='.$this->id;
5123  } elseif ($option == 'stock') {
5124  $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
5125  } elseif ($option == 'composition') {
5126  $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
5127  } else {
5128  $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
5129  }
5130 
5131  if ($option !== 'nolink') {
5132  // Add param to save lastsearch_values or not
5133  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
5134  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
5135  $add_save_lastsearch_values = 1;
5136  }
5137  if ($add_save_lastsearch_values) {
5138  $url .= '&save_lastsearch_values=1';
5139  }
5140  }
5141 
5142  $linkstart = '<a href="'.$url.'"';
5143  $linkstart .= $linkclose.'>';
5144  $linkend = '</a>';
5145 
5146  $result .= $linkstart;
5147  if ($withpicto) {
5148  if ($this->type == Product::TYPE_PRODUCT) {
5149  $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
5150  }
5151  if ($this->type == Product::TYPE_SERVICE) {
5152  $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
5153  }
5154  }
5155  $result .= dol_escape_htmltag($newref);
5156  $result .= $linkend;
5157  if ($withpicto != 2) {
5158  $result .= (($add_label && $this->label) ? $sep.dol_trunc($this->label, ($add_label > 1 ? $add_label : 0)) : '');
5159  }
5160 
5161  global $action;
5162  $hookmanager->initHooks(array('productdao'));
5163  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
5164  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5165  if ($reshook > 0) {
5166  $result = $hookmanager->resPrint;
5167  } else {
5168  $result .= $hookmanager->resPrint;
5169  }
5170 
5171  return $result;
5172  }
5173 
5174 
5185  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
5186  {
5187  global $conf, $user, $langs;
5188 
5189  $langs->load("products");
5190  $outputlangs->load("products");
5191 
5192  // Positionne le modele sur le nom du modele a utiliser
5193  if (!dol_strlen($modele)) {
5194  $modele = getDolGlobalString('PRODUCT_ADDON_PDF', 'strato');
5195  }
5196 
5197  $modelpath = "core/modules/product/doc/";
5198 
5199  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
5200  }
5201 
5209  public function getLibStatut($mode = 0, $type = 0)
5210  {
5211  switch ($type) {
5212  case 0:
5213  return $this->LibStatut($this->status, $mode, $type);
5214  case 1:
5215  return $this->LibStatut($this->status_buy, $mode, $type);
5216  case 2:
5217  return $this->LibStatut($this->status_batch, $mode, $type);
5218  default:
5219  //Simulate previous behavior but should return an error string
5220  return $this->LibStatut($this->status_buy, $mode, $type);
5221  }
5222  }
5223 
5224  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5233  public function LibStatut($status, $mode = 0, $type = 0)
5234  {
5235  // phpcs:enable
5236  global $conf, $langs;
5237 
5238  $labelStatus = $labelStatusShort = '';
5239 
5240  $langs->load('products');
5241  if (isModEnabled('productbatch')) {
5242  $langs->load("productbatch");
5243  }
5244 
5245  if ($type == 2) {
5246  switch ($mode) {
5247  case 0:
5248  $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
5249  return dolGetStatus($label);
5250  case 1:
5251  $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
5252  return dolGetStatus($label);
5253  case 2:
5254  return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
5255  case 3:
5256  return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
5257  case 4:
5258  return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
5259  case 5:
5260  return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
5261  default:
5262  return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
5263  }
5264  }
5265 
5266  $statuttrans = empty($status) ? 'status5' : 'status4';
5267 
5268  if ($status == 0) {
5269  // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
5270  if ($type == 0) {
5271  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
5272  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
5273  } elseif ($type == 1) {
5274  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
5275  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
5276  } elseif ($type == 2) {
5277  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
5278  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
5279  }
5280  } elseif ($status == 1) {
5281  // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
5282  if ($type == 0) {
5283  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
5284  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
5285  } elseif ($type == 1) {
5286  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
5287  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
5288  } elseif ($type == 2) {
5289  $labelStatus = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial'));
5290  $labelStatusShort = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort'));
5291  }
5292  } elseif ( $type == 2 && $status == 2 ) {
5293  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
5294  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
5295  }
5296 
5297  if ($mode > 6) {
5298  return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
5299  } else {
5300  return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
5301  }
5302  }
5303 
5304 
5310  public function getLibFinished()
5311  {
5312  global $langs;
5313  $langs->load('products');
5314 
5315  if (isset($this->finished) && $this->finished >= 0) {
5316  $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
5317  $resql = $this->db->query($sql);
5318  if ($resql && $this->db->num_rows($resql) > 0) {
5319  $res = $this->db->fetch_array($resql);
5320  $label = $langs->trans($res['label']);
5321  $this->db->free($resql);
5322  return $label;
5323  } else {
5324  $this->error = $this->db->error().' sql='.$sql;
5325  dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
5326  return -1;
5327  }
5328  }
5329 
5330  return '';
5331  }
5332 
5333 
5334  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5351  public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
5352  {
5353  // phpcs:enable
5354  if ($id_entrepot) {
5355  $this->db->begin();
5356 
5357  include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
5358 
5359  if ($nbpiece < 0) {
5360  if (!$movement) {
5361  $movement = 1;
5362  }
5363  $nbpiece = abs($nbpiece);
5364  }
5365 
5366  $op[0] = "+".trim($nbpiece);
5367  $op[1] = "-".trim($nbpiece);
5368 
5369  $movementstock = new MouvementStock($this->db);
5370  $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->origin_id
5371  $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
5372 
5373  if ($result >= 0) {
5374  if ($extrafields) {
5375  $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
5376  $movementstock->array_options = $array_options;
5377  $movementstock->insertExtraFields();
5378  }
5379  $this->db->commit();
5380  return 1;
5381  } else {
5382  $this->error = $movementstock->error;
5383  $this->errors = $movementstock->errors;
5384 
5385  $this->db->rollback();
5386  return -1;
5387  }
5388  }
5389  }
5390 
5391  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5411  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)
5412  {
5413  // phpcs:enable
5414  if ($id_entrepot) {
5415  $this->db->begin();
5416 
5417  include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
5418 
5419  if ($nbpiece < 0) {
5420  if (!$movement) {
5421  $movement = 1;
5422  }
5423  $nbpiece = abs($nbpiece);
5424  }
5425 
5426  $op[0] = "+".trim($nbpiece);
5427  $op[1] = "-".trim($nbpiece);
5428 
5429  $movementstock = new MouvementStock($this->db);
5430  $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->fk_origin
5431  $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct);
5432 
5433  if ($result >= 0) {
5434  if ($extrafields) {
5435  $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
5436  $movementstock->array_options = $array_options;
5437  $movementstock->insertExtraFields();
5438  }
5439  $this->db->commit();
5440  return 1;
5441  } else {
5442  $this->error = $movementstock->error;
5443  $this->errors = $movementstock->errors;
5444 
5445  $this->db->rollback();
5446  return -1;
5447  }
5448  }
5449  }
5450 
5451  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5464  public function load_stock($option = '', $includedraftpoforvirtual = null, $dateofvirtualstock = null)
5465  {
5466  // phpcs:enable
5467  global $conf;
5468 
5469  $this->stock_reel = 0;
5470  $this->stock_warehouse = array();
5471  $this->stock_theorique = 0;
5472 
5473  // Set filter on warehouse status
5474  $warehouseStatus = array();
5475  if (preg_match('/warehouseclosed/', $option)) {
5477  }
5478  if (preg_match('/warehouseopen/', $option)) {
5480  }
5481  if (preg_match('/warehouseinternal/', $option)) {
5482  if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
5484  } else {
5486  }
5487  }
5488 
5489  $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
5490  $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
5491  $sql .= ", ".$this->db->prefix()."entrepot as w";
5492  $sql .= " WHERE w.entity IN (".getEntity('stock').")";
5493  $sql .= " AND w.rowid = ps.fk_entrepot";
5494  $sql .= " AND ps.fk_product = ".((int) $this->id);
5495  if (count($warehouseStatus)) {
5496  $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
5497  }
5498 
5499  $sql .= " ORDER BY ps.reel ".(!empty($conf->global->DO_NOT_TRY_TO_DEFRAGMENT_STOCKS_WAREHOUSE)?'DESC':'ASC'); // Note : qty ASC is important for expedition card, to avoid stock fragmentation;
5500 
5501  dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
5502  $result = $this->db->query($sql);
5503  if ($result) {
5504  $num = $this->db->num_rows($result);
5505  $i = 0;
5506  if ($num > 0) {
5507  while ($i < $num) {
5508  $row = $this->db->fetch_object($result);
5509  $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
5510  $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
5511  $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
5512  if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
5513  $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
5514  }
5515  $this->stock_reel += $row->reel;
5516  $i++;
5517  }
5518  }
5519  $this->db->free($result);
5520 
5521  if (!preg_match('/novirtual/', $option)) {
5522  $this->load_virtual_stock($includedraftpoforvirtual, $dateofvirtualstock); // This also load all arrays stats_xxx...
5523  }
5524 
5525  return 1;
5526  } else {
5527  $this->error = $this->db->lasterror();
5528  return -1;
5529  }
5530  }
5531 
5532 
5533  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5543  public function load_virtual_stock($includedraftpoforvirtual = null, $dateofvirtualstock = null)
5544  {
5545  // phpcs:enable
5546  global $conf, $hookmanager, $action;
5547 
5548  $stock_commande_client = 0;
5549  $stock_commande_fournisseur = 0;
5550  $stock_sending_client = 0;
5551  $stock_reception_fournisseur = 0;
5552  $stock_inproduction = 0;
5553 
5554  //dol_syslog("load_virtual_stock");
5555 
5556  if (isModEnabled('commande')) {
5557  $result = $this->load_stats_commande(0, '1,2', 1);
5558  if ($result < 0) {
5559  dol_print_error($this->db, $this->error);
5560  }
5561  $stock_commande_client = $this->stats_commande['qty'];
5562  }
5563  if (isModEnabled("expedition")) {
5564  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
5565  $filterShipmentStatus = '';
5566  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
5567  $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
5568  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
5569  $filterShipmentStatus = Expedition::STATUS_CLOSED;
5570  }
5571  $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
5572  if ($result < 0) {
5573  dol_print_error($this->db, $this->error);
5574  }
5575  $stock_sending_client = $this->stats_expedition['qty'];
5576  }
5577  if ((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order")) {
5578  $filterStatus = empty($conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK) ? '3,4' : $conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK;
5579  if (isset($includedraftpoforvirtual)) {
5580  $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
5581  }
5582  $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1, $dateofvirtualstock);
5583  if ($result < 0) {
5584  dol_print_error($this->db, $this->error);
5585  }
5586  $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
5587  }
5588  if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && empty($conf->reception->enabled)) {
5589  // Case module reception is not used
5590  $filterStatus = '4';
5591  if (isset($includedraftpoforvirtual)) {
5592  $filterStatus = '0,'.$filterStatus;
5593  }
5594  $result = $this->load_stats_reception(0, $filterStatus, 1, $dateofvirtualstock);
5595  if ($result < 0) {
5596  dol_print_error($this->db, $this->error);
5597  }
5598  $stock_reception_fournisseur = $this->stats_reception['qty'];
5599  }
5600  if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && isModEnabled("reception")) {
5601  // Case module reception is used
5602  $filterStatus = '4';
5603  if (isset($includedraftpoforvirtual)) {
5604  $filterStatus = '0,'.$filterStatus;
5605  }
5606  $result = $this->load_stats_reception(0, $filterStatus, 1, $dateofvirtualstock); // Use same tables than when module reception is not used.
5607  if ($result < 0) {
5608  dol_print_error($this->db, $this->error);
5609  }
5610  $stock_reception_fournisseur = $this->stats_reception['qty'];
5611  }
5612  if (isModEnabled('mrp')) {
5613  $result = $this->load_stats_inproduction(0, '1,2', 1, $dateofvirtualstock);
5614  if ($result < 0) {
5615  dol_print_error($this->db, $this->error);
5616  }
5617  $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
5618  }
5619 
5620  $this->stock_theorique = $this->stock_reel + $stock_inproduction;
5621 
5622  // Stock decrease mode
5623  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
5624  $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
5625  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) {
5626  $this->stock_theorique += 0;
5627  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
5628  $this->stock_theorique -= $stock_commande_client;
5629  }
5630  // Stock Increase mode
5631  if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
5632  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5633  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
5634  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5635  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
5636  $this->stock_theorique -= $stock_reception_fournisseur;
5637  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
5638  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5639  }
5640 
5641  if (!is_object($hookmanager)) {
5642  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
5643  $hookmanager = new HookManager($this->db);
5644  }
5645  $hookmanager->initHooks(array('productdao'));
5646  $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
5647  // Note that $action and $object may have been modified by some hooks
5648  $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
5649  if ($reshook > 0) {
5650  $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
5651  }
5652 
5653  return 1;
5654  }
5655 
5656 
5664  public function loadBatchInfo($batch)
5665  {
5666  $result = array();
5667 
5668  $sql = "SELECT pb.batch, pb.eatby, pb.sellby, SUM(pb.qty) AS qty FROM ".$this->db->prefix()."product_batch as pb, ".$this->db->prefix()."product_stock as ps";
5669  $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
5670  $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby";
5671  dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
5672  $resql = $this->db->query($sql);
5673  if ($resql) {
5674  $num = $this->db->num_rows($resql);
5675  $i = 0;
5676  while ($i < $num) {
5677  $obj = $this->db->fetch_object($resql);
5678  $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
5679  $i++;
5680  }
5681  return $result;
5682  } else {
5683  dol_print_error($this->db);
5684  $this->db->rollback();
5685  return array();
5686  }
5687  }
5688 
5689  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5697  public function add_photo($sdir, $file)
5698  {
5699  // phpcs:enable
5700  global $conf;
5701 
5702  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5703 
5704  $result = 0;
5705 
5706  $dir = $sdir;
5707  if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
5708  $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
5709  } else {
5710  $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
5711  }
5712 
5713  dol_mkdir($dir);
5714 
5715  $dir_osencoded = $dir;
5716 
5717  if (is_dir($dir_osencoded)) {
5718  $originImage = $dir.'/'.$file['name'];
5719 
5720  // Cree fichier en taille origine
5721  $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
5722 
5723  if (file_exists(dol_osencode($originImage))) {
5724  // Create thumbs
5725  $this->addThumbs($originImage);
5726  }
5727  }
5728 
5729  if (is_numeric($result) && $result > 0) {
5730  return 1;
5731  } else {
5732  return -1;
5733  }
5734  }
5735 
5736  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5743  public function is_photo_available($sdir)
5744  {
5745  // phpcs:enable
5746  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5747  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5748 
5749  global $conf;
5750 
5751  $dir = $sdir;
5752  if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
5753  $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
5754  } else {
5755  $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
5756  }
5757 
5758  $nbphoto = 0;
5759 
5760  $dir_osencoded = dol_osencode($dir);
5761  if (file_exists($dir_osencoded)) {
5762  $handle = opendir($dir_osencoded);
5763  if (is_resource($handle)) {
5764  while (($file = readdir($handle)) !== false) {
5765  if (!utf8_check($file)) {
5766  $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
5767  }
5768  if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
5769  return true;
5770  }
5771  }
5772  }
5773  }
5774  return false;
5775  }
5776 
5777  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5785  public function liste_photos($dir, $nbmax = 0)
5786  {
5787  // phpcs:enable
5788  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5789  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5790 
5791  $nbphoto = 0;
5792  $tabobj = array();
5793 
5794  $dir_osencoded = dol_osencode($dir);
5795  $handle = @opendir($dir_osencoded);
5796  if (is_resource($handle)) {
5797  while (($file = readdir($handle)) !== false) {
5798  if (!utf8_check($file)) {
5799  $file = utf8_encode($file); // readdir returns ISO
5800  }
5801  if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
5802  $nbphoto++;
5803 
5804  // We forge name of thumb.
5805  $photo = $file;
5806  $photo_vignette = '';
5807  $regs = array();
5808  if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
5809  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
5810  }
5811 
5812  $dirthumb = $dir.'thumbs/';
5813 
5814  // Objet
5815  $obj = array();
5816  $obj['photo'] = $photo;
5817  if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
5818  $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
5819  } else {
5820  $obj['photo_vignette'] = "";
5821  }
5822 
5823  $tabobj[$nbphoto - 1] = $obj;
5824 
5825  // Do we have to continue with next photo ?
5826  if ($nbmax && $nbphoto >= $nbmax) {
5827  break;
5828  }
5829  }
5830  }
5831 
5832  closedir($handle);
5833  }
5834 
5835  return $tabobj;
5836  }
5837 
5838  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5845  public function delete_photo($file)
5846  {
5847  // phpcs:enable
5848  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5849  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5850 
5851  $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
5852  $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
5853  $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
5854 
5855  // On efface l'image d'origine
5856  dol_delete_file($file, 0, 0, 0, $this); // For triggers
5857 
5858  // Si elle existe, on efface la vignette
5859  if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
5860  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
5861  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
5862  dol_delete_file($dirthumb.$photo_vignette);
5863  }
5864 
5865  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
5866  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
5867  dol_delete_file($dirthumb.$photo_vignette);
5868  }
5869  }
5870  }
5871 
5872  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5879  public function get_image_size($file)
5880  {
5881  // phpcs:enable
5882  $file_osencoded = dol_osencode($file);
5883  $infoImg = getimagesize($file_osencoded); // Get information on image
5884  $this->imgWidth = $infoImg[0]; // Largeur de l'image
5885  $this->imgHeight = $infoImg[1]; // Hauteur de l'image
5886  }
5887 
5888  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5894  public function load_state_board()
5895  {
5896  // phpcs:enable
5897  global $hookmanager;
5898 
5899  $this->nb = array();
5900 
5901  $sql = "SELECT count(p.rowid) as nb, fk_product_type";
5902  $sql .= " FROM ".$this->db->prefix()."product as p";
5903  $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
5904  // Add where from hooks
5905  if (is_object($hookmanager)) {
5906  $parameters = array();
5907  $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5908  $sql .= $hookmanager->resPrint;
5909  }
5910  $sql .= ' GROUP BY fk_product_type';
5911 
5912  $resql = $this->db->query($sql);
5913  if ($resql) {
5914  while ($obj = $this->db->fetch_object($resql)) {
5915  if ($obj->fk_product_type == 1) {
5916  $this->nb["services"] = $obj->nb;
5917  } else {
5918  $this->nb["products"] = $obj->nb;
5919  }
5920  }
5921  $this->db->free($resql);
5922  return 1;
5923  } else {
5924  dol_print_error($this->db);
5925  $this->error = $this->db->error();
5926  return -1;
5927  }
5928  }
5929 
5935  public function isProduct()
5936  {
5937  return ($this->type == Product::TYPE_PRODUCT ? true : false);
5938  }
5939 
5945  public function isService()
5946  {
5947  return ($this->type == Product::TYPE_SERVICE ? true : false);
5948  }
5949 
5950 
5956  public function isMandatoryPeriod()
5957  {
5958  return ($this->mandatory_period == 1 ? true : false);
5959  }
5960  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5969  public function get_barcode($object, $type = '')
5970  {
5971  // phpcs:enable
5972  global $conf;
5973 
5974  $result = '';
5975  if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
5976  $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
5977  foreach ($dirsociete as $dirroot) {
5978  $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
5979  if ($res) {
5980  break;
5981  }
5982  }
5983  $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
5984  $mod = new $var;
5985 
5986  $result = $mod->getNextValue($object, $type);
5987 
5988  dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
5989  }
5990  return $result;
5991  }
5992 
6000  public function initAsSpecimen()
6001  {
6002  global $user, $langs, $conf, $mysoc;
6003 
6004  $now = dol_now();
6005 
6006  // Initialize parameters
6007  $this->specimen = 1;
6008  $this->id = 0;
6009  $this->ref = 'PRODUCT_SPEC';
6010  $this->label = 'PRODUCT SPECIMEN';
6011  $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
6012  $this->specimen = 1;
6013  $this->country_id = 1;
6014  $this->status = 1;
6015  $this->status_buy = 1;
6016  $this->tobatch = 0;
6017  $this->note_private = 'This is a comment (private)';
6018  $this->note_public = 'This is a comment (public)';
6019  $this->date_creation = $now;
6020  $this->date_modification = $now;
6021 
6022  $this->weight = 4;
6023  $this->weight_units = 3;
6024 
6025  $this->length = 5;
6026  $this->length_units = 1;
6027  $this->width = 6;
6028  $this->width_units = 0;
6029  $this->height = null;
6030  $this->height_units = null;
6031 
6032  $this->surface = 30;
6033  $this->surface_units = 0;
6034  $this->volume = 300;
6035  $this->volume_units = 0;
6036 
6037  $this->barcode = -1; // Create barcode automatically
6038  }
6039 
6046  public function getLabelOfUnit($type = 'long')
6047  {
6048  global $langs;
6049 
6050  if (!$this->fk_unit) {
6051  return '';
6052  }
6053 
6054  $langs->load('products');
6055 
6056  $label_type = 'label';
6057  if ($type == 'short') {
6058  $label_type = 'short_label';
6059  }
6060 
6061  $sql = "SELECT ".$label_type.", code from ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
6062 
6063  $resql = $this->db->query($sql);
6064  if ($resql && $this->db->num_rows($resql) > 0) {
6065  $res = $this->db->fetch_array($resql);
6066  $label = ($label_type == 'short_label' ? $res[$label_type] : 'unit'.$res['code']);
6067  $this->db->free($resql);
6068  return $label;
6069  } else {
6070  $this->error = $this->db->error();
6071  dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
6072  return -1;
6073  }
6074  }
6075 
6081  public function hasbatch()
6082  {
6083  return ($this->status_batch > 0 ? true : false);
6084  }
6085 
6086 
6087  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6093  public function min_recommended_price()
6094  {
6095  // phpcs:enable
6096  global $conf;
6097 
6098  $maxpricesupplier = 0;
6099 
6100  if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
6101  include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
6102  $product_fourn = new ProductFournisseur($this->db);
6103  $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
6104 
6105  if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
6106  foreach ($product_fourn_list as $productfourn) {
6107  if ($productfourn->fourn_unitprice > $maxpricesupplier) {
6108  $maxpricesupplier = $productfourn->fourn_unitprice;
6109  }
6110  }
6111 
6112  $maxpricesupplier *= $conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE;
6113  }
6114  }
6115 
6116  return $maxpricesupplier;
6117  }
6118 
6119 
6130  public function setCategories($categories)
6131  {
6132  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6133  return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
6134  }
6135 
6144  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
6145  {
6146  $tables = array(
6147  'product_customer_price',
6148  'product_customer_price_log'
6149  );
6150 
6151  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
6152  }
6153 
6165  public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
6166  {
6167  global $conf, $db;
6168 
6169  $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
6170  $query = $this->db->query($sql);
6171 
6172  $rules = array();
6173 
6174  while ($result = $this->db->fetch_object($query)) {
6175  $rules[$result->level] = $result;
6176  }
6177 
6178  //Because prices can be based on other level's prices, we temporarily store them
6179  $prices = array(
6180  1 => $baseprice
6181  );
6182 
6183  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
6184  $price = $baseprice;
6185  $price_min = $baseprice;
6186 
6187  //We have to make sure it does exist and it is > 0
6188  //First price level only allows changing min_price
6189  if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
6190  $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
6191  }
6192 
6193  $prices[$i] = $price;
6194 
6195  //We have to make sure it does exist and it is > 0
6196  if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
6197  $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
6198  }
6199 
6200  //Little check to make sure the price is modified before triggering generation
6201  $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
6202  $check_type = ($baseprice == $this->multiprices_base_type[$i]);
6203 
6204  if ($check_amount && $check_type) {
6205  continue;
6206  }
6207 
6208  if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, true) < 0) {
6209  return -1;
6210  }
6211  }
6212 
6213  return 1;
6214  }
6215 
6221  public function getRights()
6222  {
6223  global $user;
6224 
6225  if ($this->isProduct()) {
6226  return $user->rights->produit;
6227  } else {
6228  return $user->rights->service;
6229  }
6230  }
6231 
6238  public function info($id)
6239  {
6240  $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,";
6241  $sql .= " p.fk_user_author, p.fk_user_modif";
6242  $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
6243  $sql .= " WHERE p.rowid = ".((int) $id);
6244 
6245  $result = $this->db->query($sql);
6246  if ($result) {
6247  if ($this->db->num_rows($result)) {
6248  $obj = $this->db->fetch_object($result);
6249 
6250  $this->id = $obj->rowid;
6251 
6252  if ($obj->fk_user_author) {
6253  $cuser = new User($this->db);
6254  $cuser->fetch($obj->fk_user_author);
6255  $this->user_creation = $cuser;
6256  }
6257 
6258  if ($obj->fk_user_modif) {
6259  $muser = new User($this->db);
6260  $muser->fetch($obj->fk_user_modif);
6261  $this->user_modification = $muser;
6262  }
6263 
6264  $this->ref = $obj->ref;
6265  $this->date_creation = $this->db->jdate($obj->date_creation);
6266  $this->date_modification = $this->db->jdate($obj->date_modification);
6267  }
6268 
6269  $this->db->free($result);
6270  } else {
6271  dol_print_error($this->db);
6272  }
6273  }
6274 
6275 
6280  public function getProductDurationHours()
6281  {
6282  global $langs;
6283 
6284  if (empty($this->duration_value)) {
6285  $this->errors[]='ErrorDurationForServiceNotDefinedCantCalculateHourlyPrice';
6286  return -1;
6287  }
6288 
6289  if ($this->duration_unit == 'i') {
6290  $prodDurationHours = 1. / 60;
6291  }
6292  if ($this->duration_unit == 'h') {
6293  $prodDurationHours = 1.;
6294  }
6295  if ($this->duration_unit == 'd') {
6296  $prodDurationHours = 24.;
6297  }
6298  if ($this->duration_unit == 'w') {
6299  $prodDurationHours = 24. * 7;
6300  }
6301  if ($this->duration_unit == 'm') {
6302  $prodDurationHours = 24. * 30;
6303  }
6304  if ($this->duration_unit == 'y') {
6305  $prodDurationHours = 24. * 365;
6306  }
6307  $prodDurationHours *= $this->duration_value;
6308 
6309  return $prodDurationHours;
6310  }
6311 }
6312 
6318 {
6319  public $picto = 'service';
6320 }
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
$object ref
Definition: info.php:78
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.
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
deleteExtraFields()
Delete all extra fields values for the current object.
addThumbs($file)
Build thumb.
static commonReplaceThirdparty(DoliDB $db, $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, $notitle=0, $usesharelink=0)
Show photos of an object (nbmax maximum), into several columns.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
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.
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
Class to manage hooks.
Class to manage stock movements.
Class to parse product price expressions.
Class ProductCombination Used to represent a product combination.
Class to manage predefined suppliers products.
Class to manage products or services.
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.
$price_by_qty
Price by quantity arrays.
is_sousproduit($fk_parent, $fk_child)
Check if it is a sub-product into a kit.
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 into an array ->res and return it.
check_barcode($valuetotest, $typefortest)
Check barcode.
correct_stock_batch($user, $id_entrepot, $nbpiece, $movement, $label='', $price=0, $dlc='', $dluo='', $lot='', $inventorycode='', $origin_element='', $origin_id=null, $disablestockchangeforsubproduct=0, $extrafields=null)
Adjust stock in a warehouse for product with batch number.
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.
hasVariants()
Return if a product has variants or not.
delMultiLangs($langtodelete, $user)
Delete a language for this product.
getLabelOfUnit($type='long')
Returns the text label from units dictionary.
load_stats_proposal_supplier($socid=0)
Charge tableau des stats propale pour le produit/service.
getLibFinished()
Retour label of nature of product.
add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
Add a supplier price for the product.
hasFatherOrChild($mode=0)
Count all parent and children products for current product (first level only)
load_stats_facturerec($socid=0)
Charge tableau des stats facture recurrentes pour le produit/service.
$product_id_already_linked
Product ID already linked to a reference supplier.
get_nb_propalsupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in proposals in which product is included.
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)
Charge tableau des stats facture pour le produit/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 object is a product.
getRights()
Returns the rights used for this class.
loadBatchInfo($batch)
Load existing information about a serial.
$pmp
Average price value for product entry into stock (PMP)
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 in Hours of a service base on duration fields.
fetch($id='', $ref='', $ref_ext='', $barcode='', $ignore_expression=0, $ignore_price_load=0, $ignore_lang_load=0)
Load a product in memory from database.
$default_vat_code
Default VAT code for product (link to code into llx_c_tva but without foreign keys)
$duration_unit
Exoiration unit.
get_buyprice($prodfournprice, $qty, $product_id=0, $fourn_ref='', $fk_soc=0)
Read price used by a provider.
clone_fournisseurs($fromId, $toId)
Recopie les fournisseurs et prix fournisseurs d'un produit/service sur un autre.
const TYPE_PRODUCT
Regular product.
$stock_warehouse
Contains detail of stock of product into each warehouse.
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.
update_sousproduit($id_pere, $id_fils, $qty, $incdec=1)
Modify composed product.
update($id, $user, $notrigger=false, $action='update', $updatetype=false)
Update a record into database.
info($id)
Load information for tab info.
const TYPE_STOCKKIT
Advanced feature: stock kit.
load_stats_inproduction($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null)
Charge tableau des stats production pour le produit/service.
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.
$multiprices
Arrays for multiprices.
$localtax1_tx
Other local taxes.
getChildsArbo($id, $firstlevelonly=0, $level=1, $parents=array())
Return childs 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.
$remise_percent
Default discount percent.
$imgWidth
Size of image.
setCategories($categories)
Sets object to supplied categories.
load_stats_reception($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null)
Charge tableau des stats réception fournisseur pour le produit/service.
get_nb_propal($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in proposals in which product is included.
setMultiLangs($user)
Update or add a translation for a product.
$tva_npr
French VAT NPR (0 or 1)
$tva_tx
Default VAT rate of product.
load_stats_bom($socid=0)
Charge tableau des stats OF pour le produit/service.
hasbatch()
Return if object has a sell-by date or eat-by date.
$weight
Metric of products.
$table_ref_field
{}
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)
Fonction recursive uniquement utilisee par get_arbo_each_prod, recompose l'arborescence des sousprodu...
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.
check()
Check that ref and label are ok.
updatePrice($newprice, $newpricebase, $user, $newvat='', $newminprice=0, $level=0, $newnpr=0, $newpbq=0, $ignore_autogen=0, $localtaxes_array=array(), $newdefaultvatcode='')
Modify customer price of a product/Service for a given level.
initAsSpecimen()
Initialise an instance with random values.
liste_photos($dir, $nbmax=0)
Return an array with all photos of product found on disk.
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 clicable link of object (with eventually picto)
$product_fourn_id
Id du fournisseur.
$desiredstock
Ask for replenishment when $desiredstock < $stock_reel.
add_sousproduit($id_pere, $id_fils, $qty, $incdec=1)
Link a product/service to a parent product/service.
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.
del_sousproduit($fk_parent, $fk_child)
Remove a link between a subproduct and a parent product/service.
load_state_board()
Load indicators this->nb for the dashboard.
min_recommended_price()
Return minimum product recommended price.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
_log_price($user, $level=0)
Insert a track that we changed a customer price.
_get_stats($sql, $mode, $year=0)
Return an array formated for showing graphs.
$multilangs
Array for multilangs.
load_stats_commande_fournisseur($socid=0, $filtrestatut='', $forVirtualStock=0, $dateofvirtualstock=null)
Charge tableau des stats commande fournisseur pour le produit/service.
isMandatoryPeriod()
Return if object have a constraint on mandatory_period.
isProduct()
Return if 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.
const TYPE_ASSEMBLYKIT
Advanced feature: assembly kit.
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.
File of class to manage predefined price products or services by customer.
Class to manage Dolibarr users.
Definition: user.class.php:47
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
print *****$script_file(".$version.") pid cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1402
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.
Definition: files.lib.php:1251
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile', $upload_dir='')
Make control on an uploaded file from an GUI page and move it to final destination.
Definition: files.lib.php:1112
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:481
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
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_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate,...
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
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.
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...
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)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:80