dolibarr  16.0.5
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-2021 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; // Price net
135 
141  public $price_ttc;
142 
148  public $price_min;
149 
155  public $price_min_ttc;
156 
161  public $price_base_type;
162 
164  public $multiprices = array();
165  public $multiprices_ttc = array();
166  public $multiprices_base_type = array();
167  public $multiprices_min = array();
168  public $multiprices_min_ttc = array();
169  public $multiprices_tva_tx = array();
170  public $multiprices_recuperableonly = array();
171 
174  public $prices_by_qty = array();
175  public $prices_by_qty_id = array();
176  public $prices_by_qty_list = array();
177 
179  public $multilangs = array();
180 
183 
185  public $tva_tx;
186 
188  public $tva_npr = 0;
189 
192  public $localtax2_tx;
193  public $localtax1_type;
194  public $localtax2_type;
195 
196  public $lifetime;
197 
198  public $qc_frequency;
199 
205  public $stock_reel = 0;
206 
212  public $stock_theorique;
213 
219  public $cost_price;
220 
222  public $pmp;
223 
229  public $seuil_stock_alerte = 0;
230 
234  public $desiredstock = 0;
235 
236  /*
237  * Service expiration
238  */
239  public $duration_value;
240 
245 
251  public $status = 0;
252 
258  public $status_buy = 0;
259 
265  public $finished;
266 
272  public $fk_default_bom;
273 
279  public $status_batch = 0;
280 
286  public $batch_mask = '';
287 
293  public $customcode;
294 
300  public $url;
301 
303  public $weight;
304  public $weight_units; // scale -3, 0, 3, 6
305  public $length;
306  public $length_units; // scale -3, 0, 3, 6
307  public $width;
308  public $width_units; // scale -3, 0, 3, 6
309  public $height;
310  public $height_units; // scale -3, 0, 3, 6
311  public $surface;
312  public $surface_units; // scale -3, 0, 3, 6
313  public $volume;
314  public $volume_units; // scale -3, 0, 3, 6
315 
316  public $net_measure;
317  public $net_measure_units; // scale -3, 0, 3, 6
318 
319  public $accountancy_code_sell;
320  public $accountancy_code_sell_intra;
321  public $accountancy_code_sell_export;
322  public $accountancy_code_buy;
323  public $accountancy_code_buy_intra;
324  public $accountancy_code_buy_export;
325 
331  public $barcode;
332 
338  public $barcode_type;
339 
345  public $barcode_type_code;
346 
347  public $stats_propale = array();
348  public $stats_commande = array();
349  public $stats_contrat = array();
350  public $stats_facture = array();
351  public $stats_commande_fournisseur = array();
352  public $stats_reception = array();
353  public $stats_mrptoconsume = array();
354  public $stats_mrptoproduce = array();
355 
357  public $imgWidth;
358  public $imgHeight;
359 
363  public $date_creation;
364 
368  public $date_modification;
369 
372 
375 
376  public $nbphoto = 0;
377 
379  public $stock_warehouse = array();
380 
381  public $oldcopy;
382 
386  public $fk_default_warehouse;
390  public $fk_price_expression;
391 
392  /* To store supplier price found */
393  public $fourn_pu;
394  public $fourn_price_base_type;
395  public $fourn_socid;
396 
401  public $ref_fourn;
402 
406  public $ref_supplier;
407 
413  public $fk_unit;
414 
420  public $price_autogen = 0;
421 
427  public $supplierprices;
428 
434  public $is_object_used;
435 
436 
442  public $mandatory_period;
443 
472  public $fields = array(
473  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
474  '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'),
475  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>5),
476  'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>2, 'position'=>15),
477  'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'!empty($conf->barcode->enabled)', 'position'=>20, 'visible'=>-1, 'showoncombobox'=>3),
478  'fk_barcode_type' => array('type'=>'integer', 'label'=>'BarcodeType', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>-1,),
479  'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61),
480  'note' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62),
481  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
482  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
483  //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
484  'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
485  'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
486  //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
487  'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,),
488  'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,),
489  'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,),
490  'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,),
491  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
492  //'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')),
493  //'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')),
494  'mandatory_period' => array('type'=>'integer', 'label'=>'mandatory_period', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000),
495  );
496 
500  const TYPE_PRODUCT = 0;
504  const TYPE_SERVICE = 1;
508  const TYPE_ASSEMBLYKIT = 2;
512  const TYPE_STOCKKIT = 3;
513 
514 
520  public function __construct($db)
521  {
522  $this->db = $db;
523  $this->canvas = '';
524  }
525 
531  public function check()
532  {
533  $this->ref = dol_sanitizeFileName(stripslashes($this->ref));
534 
535  $err = 0;
536  if (dol_strlen(trim($this->ref)) == 0) {
537  $err++;
538  }
539 
540  if (dol_strlen(trim($this->label)) == 0) {
541  $err++;
542  }
543 
544  if ($err > 0) {
545  return 0;
546  } else {
547  return 1;
548  }
549  }
550 
558  public function create($user, $notrigger = 0)
559  {
560  global $conf, $langs;
561 
562  $error = 0;
563 
564  // Clean parameters
565  $this->ref = dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)));
566  $this->label = trim($this->label);
567  $this->price_ttc = price2num($this->price_ttc);
568  $this->price = price2num($this->price);
569  $this->price_min_ttc = price2num($this->price_min_ttc);
570  $this->price_min = price2num($this->price_min);
571  if (empty($this->tva_tx)) {
572  $this->tva_tx = 0;
573  }
574  if (empty($this->tva_npr)) {
575  $this->tva_npr = 0;
576  }
577  //Local taxes
578  if (empty($this->localtax1_tx)) {
579  $this->localtax1_tx = 0;
580  }
581  if (empty($this->localtax2_tx)) {
582  $this->localtax2_tx = 0;
583  }
584  if (empty($this->localtax1_type)) {
585  $this->localtax1_type = '0';
586  }
587  if (empty($this->localtax2_type)) {
588  $this->localtax2_type = '0';
589  }
590  if (empty($this->price)) {
591  $this->price = 0;
592  }
593  if (empty($this->price_min)) {
594  $this->price_min = 0;
595  }
596  // Price by quantity
597  if (empty($this->price_by_qty)) {
598  $this->price_by_qty = 0;
599  }
600 
601  if (empty($this->status)) {
602  $this->status = 0;
603  }
604  if (empty($this->status_buy)) {
605  $this->status_buy = 0;
606  }
607 
608  $price_ht = 0;
609  $price_ttc = 0;
610  $price_min_ht = 0;
611  $price_min_ttc = 0;
612 
613  //
614  if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
615  $price_ttc = price2num($this->price_ttc, 'MU');
616  $price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
617  }
618 
619  //
620  if ($this->price_base_type != 'TTC' && $this->price > 0) {
621  $price_ht = price2num($this->price, 'MU');
622  $price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
623  }
624 
625  //
626  if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
627  $price_min_ttc = price2num($this->price_min_ttc, 'MU');
628  $price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
629  }
630 
631  //
632  if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
633  $price_min_ht = price2num($this->price_min, 'MU');
634  $price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
635  }
636 
637  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
638  $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
639  $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
640  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
641  $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
642  $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
643 
644  // Barcode value
645  $this->barcode = trim($this->barcode);
646  $this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
647  // Check parameters
648  if (empty($this->label)) {
649  $this->error = 'ErrorMandatoryParametersNotProvided';
650  return -1;
651  }
652 
653  if (empty($this->ref) || $this->ref == 'auto') {
654  // Load object modCodeProduct
655  $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard');
656  if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
657  if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
658  $module = substr($module, 0, dol_strlen($module) - 4);
659  }
660  dol_include_once('/core/modules/product/'.$module.'.php');
661  $modCodeProduct = new $module;
662  if (!empty($modCodeProduct->code_auto)) {
663  $this->ref = $modCodeProduct->getNextValue($this, $this->type);
664  }
665  unset($modCodeProduct);
666  }
667 
668  if (empty($this->ref)) {
669  $this->error = 'ProductModuleNotSetupForAutoRef';
670  return -2;
671  }
672  }
673 
674  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);
675 
676  $now = dol_now();
677 
678  $this->db->begin();
679 
680  // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
681  if ($this->barcode == -1) {
682  $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
683  }
684 
685  // Check more parameters
686  // If error, this->errors[] is filled
687  $result = $this->verify();
688 
689  if ($result >= 0) {
690  $sql = "SELECT count(*) as nb";
691  $sql .= " FROM ".$this->db->prefix()."product";
692  $sql .= " WHERE entity IN (".getEntity('product').")";
693  $sql .= " AND ref = '".$this->db->escape($this->ref)."'";
694 
695  $result = $this->db->query($sql);
696  if ($result) {
697  $obj = $this->db->fetch_object($result);
698  if ($obj->nb == 0) {
699  // Produit non deja existant
700  $sql = "INSERT INTO ".$this->db->prefix()."product (";
701  $sql .= "datec";
702  $sql .= ", entity";
703  $sql .= ", ref";
704  $sql .= ", ref_ext";
705  $sql .= ", price_min";
706  $sql .= ", price_min_ttc";
707  $sql .= ", label";
708  $sql .= ", fk_user_author";
709  $sql .= ", fk_product_type";
710  $sql .= ", price";
711  $sql .= ", price_ttc";
712  $sql .= ", price_base_type";
713  $sql .= ", tobuy";
714  $sql .= ", tosell";
715  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
716  $sql .= ", accountancy_code_buy";
717  $sql .= ", accountancy_code_buy_intra";
718  $sql .= ", accountancy_code_buy_export";
719  $sql .= ", accountancy_code_sell";
720  $sql .= ", accountancy_code_sell_intra";
721  $sql .= ", accountancy_code_sell_export";
722  }
723  $sql .= ", canvas";
724  $sql .= ", finished";
725  $sql .= ", tobatch";
726  $sql .= ", batch_mask";
727  $sql .= ", fk_unit";
728  $sql .= ", mandatory_period";
729  $sql .= ") VALUES (";
730  $sql .= "'".$this->db->idate($now)."'";
731  $sql .= ", ".((int) $conf->entity);
732  $sql .= ", '".$this->db->escape($this->ref)."'";
733  $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
734  $sql .= ", ".price2num($price_min_ht);
735  $sql .= ", ".price2num($price_min_ttc);
736  $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
737  $sql .= ", ".((int) $user->id);
738  $sql .= ", ".((int) $this->type);
739  $sql .= ", ".price2num($price_ht, 'MT');
740  $sql .= ", ".price2num($price_ttc, 'MT');
741  $sql .= ", '".$this->db->escape($this->price_base_type)."'";
742  $sql .= ", ".((int) $this->status);
743  $sql .= ", ".((int) $this->status_buy);
744  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
745  $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
746  $sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
747  $sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
748  $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
749  $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
750  $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
751  }
752  $sql .= ", '".$this->db->escape($this->canvas)."'";
753  $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
754  $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
755  $sql .= ", '".$this->db->escape($this->batch_mask)."'";
756  $sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
757  $sql .= ", '".$this->db->escape($this->mandatory_period)."'";
758  $sql .= ")";
759 
760  dol_syslog(get_class($this)."::Create", LOG_DEBUG);
761  $result = $this->db->query($sql);
762  if ($result) {
763  $id = $this->db->last_insert_id($this->db->prefix()."product");
764 
765  if ($id > 0) {
766  $this->id = $id;
767  $this->price = $price_ht;
768  $this->price_ttc = $price_ttc;
769  $this->price_min = $price_min_ht;
770  $this->price_min_ttc = $price_min_ttc;
771 
772  $result = $this->_log_price($user);
773  if ($result > 0) {
774  if ($this->update($id, $user, true, 'add') <= 0) {
775  $error++;
776  }
777  } else {
778  $error++;
779  $this->error = $this->db->lasterror();
780  }
781 
782  // update accountancy for this entity
783  if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
784  $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
785 
786  $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
787  $sql .= " fk_product";
788  $sql .= ", entity";
789  $sql .= ", accountancy_code_buy";
790  $sql .= ", accountancy_code_buy_intra";
791  $sql .= ", accountancy_code_buy_export";
792  $sql .= ", accountancy_code_sell";
793  $sql .= ", accountancy_code_sell_intra";
794  $sql .= ", accountancy_code_sell_export";
795  $sql .= ") VALUES (";
796  $sql .= $this->id;
797  $sql .= ", " . $conf->entity;
798  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
799  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
800  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
801  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
802  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
803  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
804  $sql .= ")";
805  $result = $this->db->query($sql);
806  if (!$result) {
807  $error++;
808  $this->error = 'ErrorFailedToInsertAccountancyForEntity';
809  }
810  }
811  } else {
812  $error++;
813  $this->error = 'ErrorFailedToGetInsertedId';
814  }
815  } else {
816  $error++;
817  $this->error = $this->db->lasterror();
818  }
819  } else {
820  // Product already exists with this ref
821  $langs->load("products");
822  $error++;
823  $this->error = "ErrorProductAlreadyExists";
824  }
825  } else {
826  $error++;
827  $this->error = $this->db->lasterror();
828  }
829 
830  if (!$error && !$notrigger) {
831  // Call trigger
832  $result = $this->call_trigger('PRODUCT_CREATE', $user);
833  if ($result < 0) {
834  $error++;
835  }
836  // End call triggers
837  }
838 
839  if (!$error) {
840  $this->db->commit();
841  return $this->id;
842  } else {
843  $this->db->rollback();
844  return -$error;
845  }
846  } else {
847  $this->db->rollback();
848  dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
849  return -3;
850  }
851  }
852 
853 
860  public function verify()
861  {
862  global $langs;
863 
864  $this->errors = array();
865 
866  $result = 0;
867  $this->ref = trim($this->ref);
868 
869  if (!$this->ref) {
870  $this->errors[] = 'ErrorBadRef';
871  $result = -2;
872  }
873 
874  $arrayofnonnegativevalue = array('weight'=>'Weight', 'width'=>'Width', 'height'=>'Height', 'length'=>'Length', 'surface'=>'Surface', 'volume'=>'Volume');
875  foreach ($arrayofnonnegativevalue as $key => $value) {
876  if (property_exists($this, $key) && !empty($this->$key) && ($this->$key < 0)) {
877  $langs->loadLangs(array("main", "other"));
878  $this->error = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
879  $this->errors[] = $this->error;
880  $result = -4;
881  }
882  }
883 
884  $rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
885  if ($rescode) {
886  if ($rescode == -1) {
887  $this->errors[] = 'ErrorBadBarCodeSyntax';
888  } elseif ($rescode == -2) {
889  $this->errors[] = 'ErrorBarCodeRequired';
890  } elseif ($rescode == -3) {
891  // Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
892  $this->errors[] = 'ErrorBarCodeAlreadyUsed';
893  }
894 
895  $result = -3;
896  }
897 
898  return $result;
899  }
900 
901  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
912  public function check_barcode($valuetotest, $typefortest)
913  {
914  // phpcs:enable
915  global $conf;
916  if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
917  $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);
918 
919  $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
920  foreach ($dirsociete as $dirroot) {
921  $res = dol_include_once($dirroot.$module.'.php');
922  if ($res) {
923  break;
924  }
925  }
926 
927  $mod = new $module();
928 
929  dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
930  $result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
931  return $result;
932  } else {
933  return 0;
934  }
935  }
936 
948  public function update($id, $user, $notrigger = false, $action = 'update', $updatetype = false)
949  {
950  global $langs, $conf, $hookmanager;
951 
952  $error = 0;
953 
954  // Check parameters
955  if (!$this->label) {
956  $this->label = 'MISSING LABEL';
957  }
958 
959  // Clean parameters
960  $this->ref = dol_string_nospecial(trim($this->ref));
961  $this->label = trim($this->label);
962  $this->description = trim($this->description);
963  $this->note = (isset($this->note) ? trim($this->note) : null);
964  $this->net_measure = price2num($this->net_measure);
965  $this->net_measure_units = trim($this->net_measure_units);
966  $this->weight = price2num($this->weight);
967  $this->weight_units = trim($this->weight_units);
968  $this->length = price2num($this->length);
969  $this->length_units = trim($this->length_units);
970  $this->width = price2num($this->width);
971  $this->width_units = trim($this->width_units);
972  $this->height = price2num($this->height);
973  $this->height_units = trim($this->height_units);
974  $this->surface = price2num($this->surface);
975  $this->surface_units = trim($this->surface_units);
976  $this->volume = price2num($this->volume);
977  $this->volume_units = trim($this->volume_units);
978 
979  // set unit not defined
980  if (is_numeric($this->length_units)) {
981  $this->width_units = $this->length_units; // Not used yet
982  }
983  if (is_numeric($this->length_units)) {
984  $this->height_units = $this->length_units; // Not used yet
985  }
986 
987  // Automated compute surface and volume if not filled
988  if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
989  $this->surface = $this->length * $this->width;
990  $this->surface_units = measuring_units_squared($this->length_units);
991  }
992  if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
993  $this->volume = $this->surface * $this->height;
994  $this->volume_units = measuring_units_cubed($this->height_units);
995  }
996 
997  if (empty($this->tva_tx)) {
998  $this->tva_tx = 0;
999  }
1000  if (empty($this->tva_npr)) {
1001  $this->tva_npr = 0;
1002  }
1003  if (empty($this->localtax1_tx)) {
1004  $this->localtax1_tx = 0;
1005  }
1006  if (empty($this->localtax2_tx)) {
1007  $this->localtax2_tx = 0;
1008  }
1009  if (empty($this->localtax1_type)) {
1010  $this->localtax1_type = '0';
1011  }
1012  if (empty($this->localtax2_type)) {
1013  $this->localtax2_type = '0';
1014  }
1015  if (empty($this->status)) {
1016  $this->status = 0;
1017  }
1018  if (empty($this->status_buy)) {
1019  $this->status_buy = 0;
1020  }
1021 
1022  if (empty($this->country_id)) {
1023  $this->country_id = 0;
1024  }
1025 
1026  if (empty($this->state_id)) {
1027  $this->state_id = 0;
1028  }
1029 
1030  // Barcode value
1031  $this->barcode = trim($this->barcode);
1032 
1033  $this->accountancy_code_buy = trim($this->accountancy_code_buy);
1034  $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
1035  $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
1036  $this->accountancy_code_sell = trim($this->accountancy_code_sell);
1037  $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
1038  $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
1039 
1040 
1041  $this->db->begin();
1042 
1043  $result = 0;
1044  // Check name is required and codes are ok or unique. If error, this->errors[] is filled
1045  if ($action != 'add') {
1046  $result = $this->verify(); // We don't check when update called during a create because verify was already done
1047  } else {
1048  // we can continue
1049  $result = 0;
1050  }
1051 
1052  if ($result >= 0) {
1053  if (empty($this->oldcopy)) {
1054  $org = new self($this->db);
1055  $org->fetch($this->id);
1056  $this->oldcopy = $org;
1057  }
1058 
1059  // Test if batch management is activated on existing product
1060  // If yes, we create missing entries into product_batch
1061  if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
1062  //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
1063  $valueforundefinedlot = '000000';
1064  if (!empty($conf->global->STOCK_DEFAULT_BATCH)) {
1065  $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH;
1066  }
1067 
1068  dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
1069 
1070  $this->load_stock();
1071  foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
1072  $qty_batch = 0;
1073  foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
1074  if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
1075  // We discard this line, we will create it later
1076  $sqlclean = "DELETE FROM ".$this->db->prefix()."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".((int) $ObjW->id);
1077  $result = $this->db->query($sqlclean);
1078  if (!$result) {
1079  dol_print_error($this->db);
1080  exit;
1081  }
1082  continue;
1083  }
1084 
1085  $qty_batch += $detail->qty;
1086  }
1087  // Quantities in batch details are not same as stock quantity,
1088  // so we add a default batch record to complete and get same qty in parent and child table
1089  if ($ObjW->real <> $qty_batch) {
1090  $ObjBatch = new Productbatch($this->db);
1091  $ObjBatch->batch = $valueforundefinedlot;
1092  $ObjBatch->qty = ($ObjW->real - $qty_batch);
1093  $ObjBatch->fk_product_stock = $ObjW->id;
1094 
1095  if ($ObjBatch->create($user, 1) < 0) {
1096  $error++;
1097  $this->errors = $ObjBatch->errors;
1098  }
1099  }
1100  }
1101  }
1102 
1103  // For automatic creation
1104  if ($this->barcode == -1) {
1105  $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
1106  }
1107 
1108  $sql = "UPDATE ".$this->db->prefix()."product";
1109  $sql .= " SET label = '".$this->db->escape($this->label)."'";
1110 
1111  if ($updatetype && ($this->isProduct() || $this->isService())) {
1112  $sql .= ", fk_product_type = ".((int) $this->type);
1113  }
1114 
1115  $sql .= ", ref = '".$this->db->escape($this->ref)."'";
1116  $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1117  $sql .= ", default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null");
1118  $sql .= ", tva_tx = ".((float) $this->tva_tx);
1119  $sql .= ", recuperableonly = ".((int) $this->tva_npr);
1120  $sql .= ", localtax1_tx = ".((float) $this->localtax1_tx);
1121  $sql .= ", localtax2_tx = ".((float) $this->localtax2_tx);
1122  $sql .= ", localtax1_type = ".($this->localtax1_type != '' ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'");
1123  $sql .= ", localtax2_type = ".($this->localtax2_type != '' ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'");
1124 
1125  $sql .= ", barcode = ".(empty($this->barcode) ? "null" : "'".$this->db->escape($this->barcode)."'");
1126  $sql .= ", fk_barcode_type = ".(empty($this->barcode_type) ? "null" : $this->db->escape($this->barcode_type));
1127 
1128  $sql .= ", tosell = ".(int) $this->status;
1129  $sql .= ", tobuy = ".(int) $this->status_buy;
1130  $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch);
1131  $sql .= ", batch_mask = '".$this->db->escape($this->batch_mask)."'";
1132 
1133  $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? "null" : (int) $this->finished);
1134  $sql .= ", fk_default_bom = ".((!isset($this->fk_default_bom) || $this->fk_default_bom < 0 || $this->fk_default_bom == '') ? "null" : (int) $this->fk_default_bom);
1135  $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null');
1136  $sql .= ", net_measure_units = ".($this->net_measure_units != '' ? "'".$this->db->escape($this->net_measure_units)."'" : 'null');
1137  $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null');
1138  $sql .= ", weight_units = ".($this->weight_units != '' ? "'".$this->db->escape($this->weight_units)."'" : 'null');
1139  $sql .= ", length = ".($this->length != '' ? "'".$this->db->escape($this->length)."'" : 'null');
1140  $sql .= ", length_units = ".($this->length_units != '' ? "'".$this->db->escape($this->length_units)."'" : 'null');
1141  $sql .= ", width= ".($this->width != '' ? "'".$this->db->escape($this->width)."'" : 'null');
1142  $sql .= ", width_units = ".($this->width_units != '' ? "'".$this->db->escape($this->width_units)."'" : 'null');
1143  $sql .= ", height = ".($this->height != '' ? "'".$this->db->escape($this->height)."'" : 'null');
1144  $sql .= ", height_units = ".($this->height_units != '' ? "'".$this->db->escape($this->height_units)."'" : 'null');
1145  $sql .= ", surface = ".($this->surface != '' ? "'".$this->db->escape($this->surface)."'" : 'null');
1146  $sql .= ", surface_units = ".($this->surface_units != '' ? "'".$this->db->escape($this->surface_units)."'" : 'null');
1147  $sql .= ", volume = ".($this->volume != '' ? "'".$this->db->escape($this->volume)."'" : 'null');
1148  $sql .= ", volume_units = ".($this->volume_units != '' ? "'".$this->db->escape($this->volume_units)."'" : 'null');
1149  $sql .= ", fk_default_warehouse = ".($this->fk_default_warehouse > 0 ? $this->db->escape($this->fk_default_warehouse) : 'null');
1150  $sql .= ", seuil_stock_alerte = ".((isset($this->seuil_stock_alerte) && is_numeric($this->seuil_stock_alerte)) ? (float) $this->seuil_stock_alerte : 'null');
1151  $sql .= ", description = '".$this->db->escape($this->description)."'";
1152  $sql .= ", url = ".($this->url ? "'".$this->db->escape($this->url)."'" : 'null');
1153  $sql .= ", customcode = '".$this->db->escape($this->customcode)."'";
1154  $sql .= ", fk_country = ".($this->country_id > 0 ? (int) $this->country_id : 'null');
1155  $sql .= ", fk_state = ".($this->state_id > 0 ? (int) $this->state_id : 'null');
1156  $sql .= ", lifetime = ".($this->lifetime > 0 ? (int) $this->lifetime : 'null');
1157  $sql .= ", qc_frequency = ".($this->qc_frequency > 0 ? (int) $this->qc_frequency : 'null');
1158  $sql .= ", note = ".(isset($this->note) ? "'".$this->db->escape($this->note)."'" : 'null');
1159  $sql .= ", duration = '".$this->db->escape($this->duration_value.$this->duration_unit)."'";
1160  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
1161  $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
1162  $sql .= ", accountancy_code_buy_intra = '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1163  $sql .= ", accountancy_code_buy_export = '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1164  $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
1165  $sql .= ", accountancy_code_sell_intra= '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1166  $sql .= ", accountancy_code_sell_export= '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1167  }
1168  $sql .= ", desiredstock = ".((isset($this->desiredstock) && is_numeric($this->desiredstock)) ? (float) $this->desiredstock : "null");
1169  $sql .= ", cost_price = ".($this->cost_price != '' ? $this->db->escape($this->cost_price) : 'null');
1170  $sql .= ", fk_unit= ".(!$this->fk_unit ? 'NULL' : (int) $this->fk_unit);
1171  $sql .= ", price_autogen = ".(!$this->price_autogen ? 0 : 1);
1172  $sql .= ", fk_price_expression = ".($this->fk_price_expression != 0 ? (int) $this->fk_price_expression : 'NULL');
1173  $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : 'NULL');
1174  $sql .= ", mandatory_period = ".($this->mandatory_period );
1175  // stock field is not here because it is a denormalized value from product_stock.
1176  $sql .= " WHERE rowid = ".((int) $id);
1177 
1178  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1179 
1180  $resql = $this->db->query($sql);
1181  if ($resql) {
1182  $this->id = $id;
1183 
1184  // Multilangs
1185  if (!empty($conf->global->MAIN_MULTILANGS)) {
1186  if ($this->setMultiLangs($user) < 0) {
1187  $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1188  return -2;
1189  }
1190  }
1191 
1192  $action = 'update';
1193 
1194  // update accountancy for this entity
1195  if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
1196  $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " . ((int) $this->id) . " AND entity = " . ((int) $conf->entity));
1197 
1198  $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
1199  $sql .= " fk_product";
1200  $sql .= ", entity";
1201  $sql .= ", accountancy_code_buy";
1202  $sql .= ", accountancy_code_buy_intra";
1203  $sql .= ", accountancy_code_buy_export";
1204  $sql .= ", accountancy_code_sell";
1205  $sql .= ", accountancy_code_sell_intra";
1206  $sql .= ", accountancy_code_sell_export";
1207  $sql .= ") VALUES (";
1208  $sql .= $this->id;
1209  $sql .= ", " . $conf->entity;
1210  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
1211  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
1212  $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
1213  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
1214  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
1215  $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
1216  $sql .= ")";
1217  $result = $this->db->query($sql);
1218  if (!$result) {
1219  $error++;
1220  $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
1221  }
1222  }
1223 
1224  // Actions on extra fields
1225  if (!$error) {
1226  $result = $this->insertExtraFields();
1227  if ($result < 0) {
1228  $error++;
1229  }
1230  }
1231 
1232  if (!$error && !$notrigger) {
1233  // Call trigger
1234  $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1235  if ($result < 0) {
1236  $error++;
1237  }
1238  // End call triggers
1239  }
1240 
1241  if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
1242  // We remove directory
1243  if ($conf->product->dir_output) {
1244  $olddir = $conf->product->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
1245  $newdir = $conf->product->dir_output."/".dol_sanitizeFileName($this->ref);
1246  if (file_exists($olddir)) {
1247  //include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1248  //$res = dol_move($olddir, $newdir);
1249  // do not use dol_move with directory
1250  $res = @rename($olddir, $newdir);
1251  if (!$res) {
1252  $langs->load("errors");
1253  $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
1254  $error++;
1255  }
1256  }
1257  }
1258  }
1259 
1260  if (!$error) {
1261  if (!empty($conf->variants->enabled)) {
1262  include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1263 
1264  $comb = new ProductCombination($this->db);
1265 
1266  foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) {
1267  $currcomb->updateProperties($this, $user);
1268  }
1269  }
1270 
1271  $this->db->commit();
1272  return 1;
1273  } else {
1274  $this->db->rollback();
1275  return -$error;
1276  }
1277  } else {
1278  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1279  $langs->load("errors");
1280  if (empty($conf->barcode->enabled) || empty($this->barcode)) {
1281  $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref);
1282  } else {
1283  $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode);
1284  }
1285  $this->errors[] = $this->error;
1286  $this->db->rollback();
1287  return -1;
1288  } else {
1289  $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1290  $this->errors[] = $this->error;
1291  $this->db->rollback();
1292  return -2;
1293  }
1294  }
1295  } else {
1296  $this->db->rollback();
1297  dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1298  return -3;
1299  }
1300  }
1301 
1309  public function delete(User $user, $notrigger = 0)
1310  {
1311  global $conf, $langs;
1312  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1313 
1314  $error = 0;
1315 
1316  // Check parameters
1317  if (empty($this->id)) {
1318  $this->error = "Object must be fetched before calling delete";
1319  return -1;
1320  }
1321  if (($this->type == Product::TYPE_PRODUCT && empty($user->rights->produit->supprimer)) || ($this->type == Product::TYPE_SERVICE && empty($user->rights->service->supprimer))) {
1322  $this->error = "ErrorForbidden";
1323  return 0;
1324  }
1325 
1326  $objectisused = $this->isObjectUsed($this->id);
1327  if (empty($objectisused)) {
1328  $this->db->begin();
1329 
1330  if (!$error && empty($notrigger)) {
1331  // Call trigger
1332  $result = $this->call_trigger('PRODUCT_DELETE', $user);
1333  if ($result < 0) {
1334  $error++;
1335  }
1336  // End call triggers
1337  }
1338 
1339  // Delete from product_batch on product delete
1340  if (!$error) {
1341  $sql = "DELETE FROM ".$this->db->prefix().'product_batch';
1342  $sql .= " WHERE fk_product_stock IN (";
1343  $sql .= "SELECT rowid FROM ".$this->db->prefix().'product_stock';
1344  $sql .= " WHERE fk_product = ".((int) $this->id).")";
1345 
1346  $result = $this->db->query($sql);
1347  if (!$result) {
1348  $error++;
1349  $this->errors[] = $this->db->lasterror();
1350  }
1351  }
1352 
1353  // Delete all child tables
1354  if (!$error) {
1355  $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
1356  foreach ($elements as $table) {
1357  if (!$error) {
1358  $sql = "DELETE FROM ".$this->db->prefix().$table;
1359  $sql .= " WHERE fk_product = ".(int) $this->id;
1360 
1361  $result = $this->db->query($sql);
1362  if (!$result) {
1363  $error++;
1364  $this->errors[] = $this->db->lasterror();
1365  }
1366  }
1367  }
1368  }
1369 
1370  if (!$error) {
1371  include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
1372  include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
1373 
1374  //If it is a parent product, then we remove the association with child products
1375  $prodcomb = new ProductCombination($this->db);
1376 
1377  if ($prodcomb->deleteByFkProductParent($user, $this->id) < 0) {
1378  $error++;
1379  $this->errors[] = 'Error deleting combinations';
1380  }
1381 
1382  //We also check if it is a child product
1383  if (!$error && ($prodcomb->fetchByFkProductChild($this->id) > 0) && ($prodcomb->delete($user) < 0)) {
1384  $error++;
1385  $this->errors[] = 'Error deleting child combination';
1386  }
1387  }
1388 
1389  // Delete from product_association
1390  if (!$error) {
1391  $sql = "DELETE FROM ".$this->db->prefix()."product_association";
1392  $sql .= " WHERE fk_product_pere = ".(int) $this->id." OR fk_product_fils = ".(int) $this->id;
1393 
1394  $result = $this->db->query($sql);
1395  if (!$result) {
1396  $error++;
1397  $this->errors[] = $this->db->lasterror();
1398  }
1399  }
1400 
1401  // Remove extrafields
1402  if (!$error) {
1403  $result = $this->deleteExtraFields();
1404  if ($result < 0) {
1405  $error++;
1406  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1407  }
1408  }
1409 
1410  // Delete product
1411  if (!$error) {
1412  $sqlz = "DELETE FROM ".$this->db->prefix()."product";
1413  $sqlz .= " WHERE rowid = ".(int) $this->id;
1414 
1415  $resultz = $this->db->query($sqlz);
1416  if (!$resultz) {
1417  $error++;
1418  $this->errors[] = $this->db->lasterror();
1419  }
1420  }
1421 
1422  // Delete record into ECM index and physically
1423  if (!$error) {
1424  $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
1425  if (!$res) {
1426  $error++;
1427  }
1428  }
1429 
1430  if (!$error) {
1431  // We remove directory
1432  $ref = dol_sanitizeFileName($this->ref);
1433  if ($conf->product->dir_output) {
1434  $dir = $conf->product->dir_output."/".$ref;
1435  if (file_exists($dir)) {
1436  $res = @dol_delete_dir_recursive($dir);
1437  if (!$res) {
1438  $this->errors[] = 'ErrorFailToDeleteDir';
1439  $error++;
1440  }
1441  }
1442  }
1443  }
1444 
1445  if (!$error) {
1446  $this->db->commit();
1447  return 1;
1448  } else {
1449  foreach ($this->errors as $errmsg) {
1450  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1451  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1452  }
1453  $this->db->rollback();
1454  return -$error;
1455  }
1456  } else {
1457  $this->error = "ErrorRecordIsUsedCantDelete";
1458  return 0;
1459  }
1460  }
1461 
1468  public function setMultiLangs($user)
1469  {
1470  global $conf, $langs;
1471 
1472  $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
1473  $current_lang = $langs->getDefaultLang();
1474 
1475  foreach ($langs_available as $key => $value) {
1476  if ($key == $current_lang) {
1477  $sql = "SELECT rowid";
1478  $sql .= " FROM ".$this->db->prefix()."product_lang";
1479  $sql .= " WHERE fk_product = ".((int) $this->id);
1480  $sql .= " AND lang = '".$this->db->escape($key)."'";
1481 
1482  $result = $this->db->query($sql);
1483 
1484  if ($this->db->num_rows($result)) { // if there is already a description line for this language
1485  $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
1486  $sql2 .= " SET ";
1487  $sql2 .= " label='".$this->db->escape($this->label)."',";
1488  $sql2 .= " description='".$this->db->escape($this->description)."'";
1489  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1490  $sql2 .= ", note='".$this->db->escape($this->other)."'";
1491  }
1492  $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
1493  } else {
1494  $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
1495  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1496  $sql2 .= ", note";
1497  }
1498  $sql2 .= ")";
1499  $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
1500  $sql2 .= " '".$this->db->escape($this->description)."'";
1501  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1502  $sql2 .= ", '".$this->db->escape($this->other)."'";
1503  }
1504  $sql2 .= ")";
1505  }
1506  dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
1507  if (!$this->db->query($sql2)) {
1508  $this->error = $this->db->lasterror();
1509  return -1;
1510  }
1511  } elseif (isset($this->multilangs[$key])) {
1512  if (empty($this->multilangs["$key"]["label"])) {
1513  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
1514  return -1;
1515  }
1516 
1517  $sql = "SELECT rowid";
1518  $sql .= " FROM ".$this->db->prefix()."product_lang";
1519  $sql .= " WHERE fk_product = ".((int) $this->id);
1520  $sql .= " AND lang = '".$this->db->escape($key)."'";
1521 
1522  $result = $this->db->query($sql);
1523 
1524  if ($this->db->num_rows($result)) { // if there is already a description line for this language
1525  $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
1526  $sql2 .= " SET ";
1527  $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
1528  $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
1529  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1530  $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
1531  }
1532  $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
1533  } else {
1534  $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
1535  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1536  $sql2 .= ", note";
1537  }
1538  $sql2 .= ")";
1539  $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
1540  $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
1541  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1542  $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
1543  }
1544  $sql2 .= ")";
1545  }
1546 
1547  // We do not save if main fields are empty
1548  if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
1549  if (!$this->db->query($sql2)) {
1550  $this->error = $this->db->lasterror();
1551  return -1;
1552  }
1553  }
1554  } else {
1555  // language is not current language and we didn't provide a multilang description for this language
1556  }
1557  }
1558 
1559  // Call trigger
1560  $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
1561  if ($result < 0) {
1562  $this->error = $this->db->lasterror();
1563  return -1;
1564  }
1565  // End call triggers
1566 
1567  return 1;
1568  }
1569 
1578  public function delMultiLangs($langtodelete, $user)
1579  {
1580  $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
1581  $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
1582 
1583  dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
1584  $result = $this->db->query($sql);
1585  if ($result) {
1586  // Call trigger
1587  $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
1588  if ($result < 0) {
1589  $this->error = $this->db->lasterror();
1590  dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
1591  return -1;
1592  }
1593  // End call triggers
1594  return 1;
1595  } else {
1596  $this->error = $this->db->lasterror();
1597  dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
1598  return -1;
1599  }
1600  }
1601 
1610  public function setAccountancyCode($type, $value)
1611  {
1612  global $user, $langs, $conf;
1613 
1614  $error = 0;
1615 
1616  $this->db->begin();
1617 
1618  if ($type == 'buy') {
1619  $field = 'accountancy_code_buy';
1620  } elseif ($type == 'buy_intra') {
1621  $field = 'accountancy_code_buy_intra';
1622  } elseif ($type == 'buy_export') {
1623  $field = 'accountancy_code_buy_export';
1624  } elseif ($type == 'sell') {
1625  $field = 'accountancy_code_sell';
1626  } elseif ($type == 'sell_intra') {
1627  $field = 'accountancy_code_sell_intra';
1628  } elseif ($type == 'sell_export') {
1629  $field = 'accountancy_code_sell_export';
1630  } else {
1631  return -1;
1632  }
1633 
1634  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
1635  $sql .= "$field = '".$this->db->escape($value)."'";
1636  $sql .= " WHERE rowid = ".((int) $this->id);
1637 
1638  dol_syslog(__METHOD__."", LOG_DEBUG);
1639  $resql = $this->db->query($sql);
1640 
1641  if ($resql) {
1642  // Call trigger
1643  $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1644  if ($result < 0) {
1645  $error++;
1646  }
1647  // End call triggers
1648 
1649  if ($error) {
1650  $this->db->rollback();
1651  return -1;
1652  }
1653 
1654  $this->$field = $value;
1655 
1656  $this->db->commit();
1657  return 1;
1658  } else {
1659  $this->error = $this->db->lasterror();
1660  $this->db->rollback();
1661  return -1;
1662  }
1663  }
1664 
1670  public function getMultiLangs()
1671  {
1672  global $langs;
1673 
1674  $current_lang = $langs->getDefaultLang();
1675 
1676  $sql = "SELECT lang, label, description, note as other";
1677  $sql .= " FROM ".$this->db->prefix()."product_lang";
1678  $sql .= " WHERE fk_product = ".((int) $this->id);
1679 
1680  $result = $this->db->query($sql);
1681  if ($result) {
1682  while ($obj = $this->db->fetch_object($result)) {
1683  //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
1684  if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
1685  $this->label = $obj->label;
1686  $this->description = $obj->description;
1687  $this->other = $obj->other;
1688  }
1689  $this->multilangs["$obj->lang"]["label"] = $obj->label;
1690  $this->multilangs["$obj->lang"]["description"] = $obj->description;
1691  $this->multilangs["$obj->lang"]["other"] = $obj->other;
1692  }
1693  return 1;
1694  } else {
1695  $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
1696  return -1;
1697  }
1698  }
1699 
1706  private function getArrayForPriceCompare($level = 0)
1707  {
1708 
1709  $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
1710 
1711  foreach ($testExit as $field) {
1712  if (!isset($this->$field)) {
1713  return array();
1714  }
1715  $tmparray = $this->$field;
1716  if (!isset($tmparray[$level])) {
1717  return array();
1718  }
1719  }
1720 
1721  $lastPrice = array(
1722  'level' => $level ? $level : 1,
1723  'multiprices' => doubleval($this->multiprices[$level]),
1724  'multiprices_ttc' => doubleval($this->multiprices_ttc[$level]),
1725  'multiprices_base_type' => $this->multiprices_base_type[$level],
1726  'multiprices_min' => doubleval($this->multiprices_min[$level]),
1727  'multiprices_min_ttc' => doubleval($this->multiprices_min_ttc[$level]),
1728  'multiprices_tva_tx' => doubleval($this->multiprices_tva_tx[$level]),
1729  'multiprices_recuperableonly' => doubleval($this->multiprices_recuperableonly[$level]),
1730  );
1731 
1732  return $lastPrice;
1733  }
1734 
1735 
1736  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1744  private function _log_price($user, $level = 0)
1745  {
1746  // phpcs:enable
1747  global $conf;
1748 
1749  $now = dol_now();
1750 
1751  // Clean parameters
1752  if (empty($this->price_by_qty)) {
1753  $this->price_by_qty = 0;
1754  }
1755 
1756  // Add new price
1757  $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,";
1758  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
1759  $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).",";
1760  $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');
1761  $sql .= ")";
1762 
1763  dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
1764  $resql = $this->db->query($sql);
1765  if (!$resql) {
1766  $this->error = $this->db->lasterror();
1767  dol_print_error($this->db);
1768  return -1;
1769  } else {
1770  return 1;
1771  }
1772  }
1773 
1774 
1775  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1783  public function log_price_delete($user, $rowid)
1784  {
1785  // phpcs:enable
1786  $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
1787  $sql .= " WHERE fk_product_price = ".((int) $rowid);
1788  $resql = $this->db->query($sql);
1789 
1790  $sql = "DELETE FROM ".$this->db->prefix()."product_price";
1791  $sql .= " WHERE rowid=".((int) $rowid);
1792  $resql = $this->db->query($sql);
1793  if ($resql) {
1794  return 1;
1795  } else {
1796  $this->error = $this->db->lasterror();
1797  return -1;
1798  }
1799  }
1800 
1801 
1811  public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
1812  {
1813  global $conf, $db, $hookmanager, $action;
1814 
1815  // Call hook if any
1816  if (is_object($hookmanager)) {
1817  $parameters = array('thirdparty_seller'=>$thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
1818  // Note that $action and $object may have been modified by some hooks
1819  $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
1820  if ($reshook > 0) {
1821  return $hookmanager->resArray;
1822  }
1823  }
1824 
1825  // Update if prices fields are defined
1826  $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
1827  $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
1828  if (empty($tva_tx)) {
1829  $tva_npr = 0;
1830  }
1831 
1832  $pu_ht = $this->price;
1833  $pu_ttc = $this->price_ttc;
1834  $price_min = $this->price_min;
1835  $price_base_type = $this->price_base_type;
1836 
1837  // If price per segment
1838  if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($thirdparty_buyer->price_level)) {
1839  $pu_ht = $this->multiprices[$thirdparty_buyer->price_level];
1840  $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
1841  $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
1842  $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
1843  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
1844  if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
1845  $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
1846  }
1847  if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
1848  $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
1849  }
1850  if (empty($tva_tx)) {
1851  $tva_npr = 0;
1852  }
1853  }
1854  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
1855  // If price per customer
1856  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
1857 
1858  $prodcustprice = new Productcustomerprice($this->db);
1859 
1860  $filter = array('t.fk_product' => $this->id, 't.fk_soc' => $thirdparty_buyer->id);
1861 
1862  $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
1863  if ($result) {
1864  if (count($prodcustprice->lines) > 0) {
1865  $pu_ht = price($prodcustprice->lines[0]->price);
1866  $price_min = price($prodcustprice->lines[0]->price_min);
1867  $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
1868  $price_base_type = $prodcustprice->lines[0]->price_base_type;
1869  $tva_tx = $prodcustprice->lines[0]->tva_tx;
1870  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
1871  $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
1872  }
1873  $tva_npr = $prodcustprice->lines[0]->recuperableonly;
1874  if (empty($tva_tx)) {
1875  $tva_npr = 0;
1876  }
1877  }
1878  }
1879  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
1880  // If price per quantity
1881  if ($this->prices_by_qty[0]) {
1882  // yes, this product has some prices per quantity
1883  // Search price into product_price_by_qty from $this->id
1884  foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
1885  if ($priceforthequantityarray['rowid'] != $pqp) {
1886  continue;
1887  }
1888  // We found the price
1889  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1890  $pu_ht = $priceforthequantityarray['unitprice'];
1891  } else {
1892  $pu_ttc = $priceforthequantityarray['unitprice'];
1893  }
1894  break;
1895  }
1896  }
1897  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
1898  // If price per quantity and customer
1899  if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
1900  // yes, this product has some prices per quantity
1901  // Search price into product_price_by_qty from $this->id
1902  foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
1903  if ($priceforthequantityarray['rowid'] != $pqp) {
1904  continue;
1905  }
1906  // We found the price
1907  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1908  $pu_ht = $priceforthequantityarray['unitprice'];
1909  } else {
1910  $pu_ttc = $priceforthequantityarray['unitprice'];
1911  }
1912  break;
1913  }
1914  }
1915  }
1916 
1917  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);
1918  }
1919 
1920  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1934  public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
1935  {
1936  // phpcs:enable
1937  global $conf;
1938  $result = 0;
1939 
1940  // We do a first seach with a select by searching with couple prodfournprice and qty only (later we will search on triplet qty/product_id/fourn_ref)
1941  $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent,";
1942  $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,";
1943  $sql .= " pfp.default_vat_code,";
1944  $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
1945  $sql .= " pfp.packaging";
1946  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
1947  $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
1948  if ($qty > 0) {
1949  $sql .= " AND pfp.quantity <= ".((float) $qty);
1950  }
1951  $sql .= " ORDER BY pfp.quantity DESC";
1952 
1953  dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
1954  $resql = $this->db->query($sql);
1955  if ($resql) {
1956  $obj = $this->db->fetch_object($resql);
1957  if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
1958  if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
1959  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
1960  $prod_supplier = new ProductFournisseur($this->db);
1961  $prod_supplier->product_fourn_price_id = $obj->rowid;
1962  $prod_supplier->id = $obj->fk_product;
1963  $prod_supplier->fourn_qty = $obj->quantity;
1964  $prod_supplier->fourn_tva_tx = $obj->tva_tx;
1965  $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
1966  $priceparser = new PriceParser($this->db);
1967  $price_result = $priceparser->parseProductSupplier($prod_supplier);
1968  if ($price_result >= 0) {
1969  $obj->price = $price_result;
1970  }
1971  }
1972  $this->product_fourn_price_id = $obj->rowid;
1973  $this->buyprice = $obj->price; // deprecated
1974  $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
1975  $this->fourn_price_base_type = 'HT'; // Price base type
1976  $this->fourn_socid = $obj->fk_soc; // Company that offer this price
1977  $this->ref_fourn = $obj->ref_fourn; // deprecated
1978  $this->ref_supplier = $obj->ref_fourn; // Ref supplier
1979  $this->desc_supplier = $obj->desc_fourn; // desc supplier
1980  $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
1981  $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
1982  $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
1983  $this->fourn_multicurrency_price = $obj->multicurrency_price;
1984  $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
1985  $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
1986  $this->fourn_multicurrency_id = $obj->fk_multicurrency;
1987  $this->fourn_multicurrency_code = $obj->multicurrency_code;
1988  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
1989  $this->packaging = $obj->packaging;
1990  }
1991  $result = $obj->fk_product;
1992  return $result;
1993  } else { // If not found
1994  // 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.
1995  $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
1996  $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.fk_supplier_price_expression,";
1997  $sql .= " pfp.default_vat_code,";
1998  $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
1999  $sql .= " pfp.packaging";
2000  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
2001  $sql .= " WHERE 1 = 1";
2002  if ($product_id > 0) {
2003  $sql .= " AND pfp.fk_product = ".((int) $product_id);
2004  }
2005  if ($fourn_ref != 'none') {
2006  $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
2007  }
2008  if ($fk_soc > 0) {
2009  $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
2010  }
2011  if ($qty > 0) {
2012  $sql .= " AND pfp.quantity <= ".((float) $qty);
2013  }
2014  $sql .= " ORDER BY pfp.quantity DESC";
2015  $sql .= " LIMIT 1";
2016 
2017  dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
2018  $resql = $this->db->query($sql);
2019  if ($resql) {
2020  $obj = $this->db->fetch_object($resql);
2021  if ($obj && $obj->quantity > 0) { // If found
2022  if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
2023  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2024  $prod_supplier = new ProductFournisseur($this->db);
2025  $prod_supplier->product_fourn_price_id = $obj->rowid;
2026  $prod_supplier->id = $obj->fk_product;
2027  $prod_supplier->fourn_qty = $obj->quantity;
2028  $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2029  $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2030  $priceparser = new PriceParser($this->db);
2031  $price_result = $priceparser->parseProductSupplier($prod_supplier);
2032  if ($result >= 0) {
2033  $obj->price = $price_result;
2034  }
2035  }
2036  $this->product_fourn_price_id = $obj->rowid;
2037  $this->buyprice = $obj->price; // deprecated
2038  $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
2039  $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
2040  $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
2041  $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2042  $this->ref_fourn = $obj->ref_supplier; // deprecated
2043  $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2044  $this->desc_supplier = $obj->desc_supplier; // desc supplier
2045  $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2046  $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2047  $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
2048  $this->fourn_multicurrency_price = $obj->multicurrency_price;
2049  $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2050  $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2051  $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2052  $this->fourn_multicurrency_code = $obj->multicurrency_code;
2053  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
2054  $this->packaging = $obj->packaging;
2055  }
2056  $result = $obj->fk_product;
2057  return $result;
2058  } else {
2059  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é.
2060  }
2061  } else {
2062  $this->error = $this->db->lasterror();
2063  return -3;
2064  }
2065  }
2066  } else {
2067  $this->error = $this->db->lasterror();
2068  return -2;
2069  }
2070  }
2071 
2072 
2089  public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '')
2090  {
2091  global $conf, $langs;
2092 
2093  $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
2094 
2095  $id = $this->id;
2096 
2097  dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
2098 
2099  // Clean parameters
2100  if (empty($this->tva_tx)) {
2101  $this->tva_tx = 0;
2102  }
2103  if (empty($newnpr)) {
2104  $newnpr = 0;
2105  }
2106  if (empty($newminprice)) {
2107  $newminprice = 0;
2108  }
2109  if (empty($newminprice)) {
2110  $newminprice = 0;
2111  }
2112 
2113  // Check parameters
2114  if ($newvat == '') {
2115  $newvat = $this->tva_tx;
2116  }
2117 
2118  // If multiprices are enabled, then we check if the current product is subject to price autogeneration
2119  // Price will be modified ONLY when the first one is the one that is being modified
2120  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
2121  return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
2122  }
2123 
2124  if (!empty($newminprice) && ($newminprice > $newprice)) {
2125  $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
2126  return -1;
2127  }
2128 
2129  if ($newprice !== '' || $newprice === 0) {
2130  if ($newpricebase == 'TTC') {
2131  $price_ttc = price2num($newprice, 'MU');
2132  $price = price2num($newprice) / (1 + ($newvat / 100));
2133  $price = price2num($price, 'MU');
2134 
2135  if ($newminprice != '' || $newminprice == 0) {
2136  $price_min_ttc = price2num($newminprice, 'MU');
2137  $price_min = price2num($newminprice) / (1 + ($newvat / 100));
2138  $price_min = price2num($price_min, 'MU');
2139  } else {
2140  $price_min = 0;
2141  $price_min_ttc = 0;
2142  }
2143  } else {
2144  $price = price2num($newprice, 'MU');
2145  $price_ttc = ($newnpr != 1) ? price2num($newprice) * (1 + ($newvat / 100)) : $price;
2146  $price_ttc = price2num($price_ttc, 'MU');
2147 
2148  if ($newminprice !== '' || $newminprice === 0) {
2149  $price_min = price2num($newminprice, 'MU');
2150  $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100));
2151  $price_min_ttc = price2num($price_min_ttc, 'MU');
2152  //print 'X'.$newminprice.'-'.$price_min;
2153  } else {
2154  $price_min = 0;
2155  $price_min_ttc = 0;
2156  }
2157  }
2158  //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
2159 
2160  if (count($localtaxes_array) > 0) {
2161  $localtaxtype1 = $localtaxes_array['0'];
2162  $localtax1 = $localtaxes_array['1'];
2163  $localtaxtype2 = $localtaxes_array['2'];
2164  $localtax2 = $localtaxes_array['3'];
2165  } else // old method. deprecated because ot can't retrieve type
2166  {
2167  $localtaxtype1 = '0';
2168  $localtax1 = get_localtax($newvat, 1);
2169  $localtaxtype2 = '0';
2170  $localtax2 = get_localtax($newvat, 2);
2171  }
2172  if (empty($localtax1)) {
2173  $localtax1 = 0; // If = '' then = 0
2174  }
2175  if (empty($localtax2)) {
2176  $localtax2 = 0; // If = '' then = 0
2177  }
2178 
2179  $this->db->begin();
2180 
2181  // Ne pas mettre de quote sur les numeriques decimaux.
2182  // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes.
2183  $sql = "UPDATE ".$this->db->prefix()."product SET";
2184  $sql .= " price_base_type='".$this->db->escape($newpricebase)."',";
2185  $sql .= " price=".$price.",";
2186  $sql .= " price_ttc=".$price_ttc.",";
2187  $sql .= " price_min=".$price_min.",";
2188  $sql .= " price_min_ttc=".$price_min_ttc.",";
2189  $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').",";
2190  $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').",";
2191  $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
2192  $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
2193  $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
2194  $sql .= " tva_tx='".price2num($newvat)."',";
2195  $sql .= " recuperableonly='".$this->db->escape($newnpr)."'";
2196  $sql .= " WHERE rowid = ".((int) $id);
2197 
2198  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2199  $resql = $this->db->query($sql);
2200  if ($resql) {
2201  $this->multiprices[$level] = $price;
2202  $this->multiprices_ttc[$level] = $price_ttc;
2203  $this->multiprices_min[$level] = $price_min;
2204  $this->multiprices_min_ttc[$level] = $price_min_ttc;
2205  $this->multiprices_base_type[$level] = $newpricebase;
2206  $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
2207  $this->multiprices_tva_tx[$level] = $newvat;
2208  $this->multiprices_recuperableonly[$level] = $newnpr;
2209 
2210  $this->price = $price;
2211  $this->price_ttc = $price_ttc;
2212  $this->price_min = $price_min;
2213  $this->price_min_ttc = $price_min_ttc;
2214  $this->price_base_type = $newpricebase;
2215  $this->default_vat_code = $newdefaultvatcode;
2216  $this->tva_tx = $newvat;
2217  $this->tva_npr = $newnpr;
2218  //Local taxes
2219  $this->localtax1_tx = $localtax1;
2220  $this->localtax2_tx = $localtax2;
2221  $this->localtax1_type = $localtaxtype1;
2222  $this->localtax2_type = $localtaxtype2;
2223 
2224  // Price by quantity
2225  $this->price_by_qty = $newpbq;
2226 
2227  // check if price have really change before log
2228  $newPriceData = $this->getArrayForPriceCompare($level);
2229  if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || empty($conf->global->PRODUIT_MULTIPRICES)) {
2230  $this->_log_price($user, $level); // Save price for level into table product_price
2231  }
2232 
2233  $this->level = $level; // Store level of price edited for trigger
2234 
2235  // Call trigger
2236  $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
2237  if ($result < 0) {
2238  $this->db->rollback();
2239  return -1;
2240  }
2241  // End call triggers
2242 
2243  $this->db->commit();
2244  } else {
2245  $this->db->rollback();
2246  $this->error = $this->db->lasterror();
2247  return -1;
2248  }
2249  }
2250 
2251  return 1;
2252  }
2253 
2261  public function setPriceExpression($expression_id)
2262  {
2263  global $user;
2264 
2265  $this->fk_price_expression = $expression_id;
2266 
2267  return $this->update($this->id, $user);
2268  }
2269 
2282  public function fetch($id = '', $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
2283  {
2284  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
2285 
2286  global $langs, $conf;
2287 
2288  dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
2289 
2290  // Check parameters
2291  if (!$id && !$ref && !$ref_ext && !$barcode) {
2292  $this->error = 'ErrorWrongParameters';
2293  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2294  return -1;
2295  }
2296 
2297  $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,";
2298  $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,";
2299  $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
2300  $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
2301  $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,";
2302  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
2303  $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,";
2304  } else {
2305  $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,";
2306  }
2307 
2308  //For MultiCompany
2309  //PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
2310  $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
2311  $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.
2312  $visibleWarehousesEntities = $conf->entity;
2313  if (!empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
2314  if (!empty($conf->global->MULTICOMPANY_PMP_PER_ENTITY_ENABLED)) {
2315  $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
2316  if ($this->db->num_rows($checkPMPPerEntity)>0) {
2317  $separatedEntityPMP = true;
2318  }
2319  }
2320  global $mc;
2321  $separatedStock = true;
2322  if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
2323  $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
2324  }
2325  }
2326  if ($separatedEntityPMP) {
2327  $sql .= " ppe.pmp,";
2328  } else {
2329  $sql .= " p.pmp,";
2330  }
2331  $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
2332  $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf,";
2333  if ($separatedStock) {
2334  $sql .= " SUM(sp.reel) as stock";
2335  } else {
2336  $sql .= " p.stock";
2337  }
2338  $sql .= " FROM ".$this->db->prefix()."product as p";
2339  if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) || $separatedEntityPMP) {
2340  $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
2341  }
2342  if ($separatedStock) {
2343  $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)."))";
2344  }
2345 
2346  if ($id) {
2347  $sql .= " WHERE p.rowid = ".((int) $id);
2348  } else {
2349  $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
2350  if ($ref) {
2351  $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
2352  } elseif ($ref_ext) {
2353  $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
2354  } elseif ($barcode) {
2355  $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
2356  }
2357  }
2358  if ($separatedStock) {
2359  $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,";
2360  $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,";
2361  $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
2362  $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
2363  $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished,";
2364  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
2365  $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,";
2366  } else {
2367  $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,";
2368  }
2369  if ($separatedEntityPMP) {
2370  $sql .= " ppe.pmp,";
2371  } else {
2372  $sql .= " p.pmp,";
2373  }
2374  $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
2375  $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf";
2376  if (!$separatedStock) {
2377  $sql .= ", p.stock";
2378  }
2379  }
2380 
2381  $resql = $this->db->query($sql);
2382  if ($resql) {
2383  unset($this->oldcopy);
2384 
2385  if ($this->db->num_rows($resql) > 0) {
2386  $obj = $this->db->fetch_object($resql);
2387 
2388  $this->id = $obj->rowid;
2389  $this->ref = $obj->ref;
2390  $this->ref_ext = $obj->ref_ext;
2391  $this->label = $obj->label;
2392  $this->description = $obj->description;
2393  $this->url = $obj->url;
2394  $this->note_public = $obj->note_public;
2395  $this->note_private = $obj->note_private;
2396  $this->note = $obj->note_private; // deprecated
2397 
2398  $this->type = $obj->fk_product_type;
2399  $this->status = $obj->tosell;
2400  $this->status_buy = $obj->tobuy;
2401  $this->status_batch = $obj->tobatch;
2402  $this->batch_mask = $obj->batch_mask;
2403 
2404  $this->customcode = $obj->customcode;
2405  $this->country_id = $obj->fk_country;
2406  $this->country_code = getCountry($this->country_id, 2, $this->db);
2407  $this->state_id = $obj->fk_state;
2408  $this->lifetime = $obj->lifetime;
2409  $this->qc_frequency = $obj->qc_frequency;
2410  $this->price = $obj->price;
2411  $this->price_ttc = $obj->price_ttc;
2412  $this->price_min = $obj->price_min;
2413  $this->price_min_ttc = $obj->price_min_ttc;
2414  $this->price_base_type = $obj->price_base_type;
2415  $this->cost_price = $obj->cost_price;
2416  $this->default_vat_code = $obj->default_vat_code;
2417  $this->tva_tx = $obj->tva_tx;
2419  $this->tva_npr = $obj->tva_npr;
2420  $this->recuperableonly = $obj->tva_npr; // For backward compatibility
2422  $this->localtax1_tx = $obj->localtax1_tx;
2423  $this->localtax2_tx = $obj->localtax2_tx;
2424  $this->localtax1_type = $obj->localtax1_type;
2425  $this->localtax2_type = $obj->localtax2_type;
2426 
2427  $this->finished = $obj->finished;
2428  $this->fk_default_bom = $obj->fk_default_bom;
2429 
2430  $this->duration = $obj->duration;
2431  $this->duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1);
2432  $this->duration_unit = substr($obj->duration, -1);
2433  $this->canvas = $obj->canvas;
2434  $this->net_measure = $obj->net_measure;
2435  $this->net_measure_units = $obj->net_measure_units;
2436  $this->weight = $obj->weight;
2437  $this->weight_units = $obj->weight_units;
2438  $this->length = $obj->length;
2439  $this->length_units = $obj->length_units;
2440  $this->width = $obj->width;
2441  $this->width_units = $obj->width_units;
2442  $this->height = $obj->height;
2443  $this->height_units = $obj->height_units;
2444 
2445  $this->surface = $obj->surface;
2446  $this->surface_units = $obj->surface_units;
2447  $this->volume = $obj->volume;
2448  $this->volume_units = $obj->volume_units;
2449  $this->barcode = $obj->barcode;
2450  $this->barcode_type = $obj->fk_barcode_type;
2451 
2452  $this->accountancy_code_buy = $obj->accountancy_code_buy;
2453  $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
2454  $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
2455  $this->accountancy_code_sell = $obj->accountancy_code_sell;
2456  $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
2457  $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
2458 
2459  $this->fk_default_warehouse = $obj->fk_default_warehouse;
2460  $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
2461  $this->desiredstock = $obj->desiredstock;
2462  $this->stock_reel = $obj->stock;
2463  $this->pmp = $obj->pmp;
2464 
2465  $this->date_creation = $obj->datec;
2466  $this->date_modification = $obj->tms;
2467  $this->import_key = $obj->import_key;
2468  $this->entity = $obj->entity;
2469 
2470  $this->ref_ext = $obj->ref_ext;
2471  $this->fk_price_expression = $obj->fk_price_expression;
2472  $this->fk_unit = $obj->fk_unit;
2473  $this->price_autogen = $obj->price_autogen;
2474  $this->model_pdf = $obj->model_pdf;
2475 
2476  $this->mandatory_period = $obj->mandatory_period;
2477 
2478  $this->db->free($resql);
2479 
2480  // fetch optionals attributes and labels
2481  $this->fetch_optionals();
2482 
2483  // Multilangs
2484  if (!empty($conf->global->MAIN_MULTILANGS) && empty($ignore_lang_load)) {
2485  $this->getMultiLangs();
2486  }
2487 
2488  // Load multiprices array
2489  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
2490  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
2491  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2492  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
2493  $sql .= " FROM ".$this->db->prefix()."product_price";
2494  $sql .= " WHERE entity IN (".getEntity('productprice').")";
2495  $sql .= " AND price_level=".((int) $i);
2496  $sql .= " AND fk_product = ".((int) $this->id);
2497  $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
2498  $sql .= " LIMIT 1"; // Only the first one
2499  $resql = $this->db->query($sql);
2500  if ($resql) {
2501  $result = $this->db->fetch_array($resql);
2502 
2503  $this->multiprices[$i] = $result ? $result["price"] : null;
2504  $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
2505  $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
2506  $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
2507  $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
2508  // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
2509  $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].($result ? ' ('.$result['default_vat_code'].')' : '') : null;
2510  $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
2511 
2512  // Price by quantity
2513  /*
2514  $this->prices_by_qty[$i]=$result["price_by_qty"];
2515  $this->prices_by_qty_id[$i]=$result["rowid"];
2516  // Récuperation de la liste des prix selon qty si flag positionné
2517  if ($this->prices_by_qty[$i] == 1)
2518  {
2519  $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
2520  $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
2521  $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
2522  $sql.= " ORDER BY quantity ASC";
2523  $resultat=array();
2524  $resql = $this->db->query($sql);
2525  if ($resql)
2526  {
2527  $ii=0;
2528  while ($result= $this->db->fetch_array($resql)) {
2529  $resultat[$ii]=array();
2530  $resultat[$ii]["rowid"]=$result["rowid"];
2531  $resultat[$ii]["price"]= $result["price"];
2532  $resultat[$ii]["unitprice"]= $result["unitprice"];
2533  $resultat[$ii]["quantity"]= $result["quantity"];
2534  $resultat[$ii]["remise_percent"]= $result["remise_percent"];
2535  $resultat[$ii]["remise"]= $result["remise"]; // deprecated
2536  $resultat[$ii]["price_base_type"]= $result["price_base_type"];
2537  $ii++;
2538  }
2539  $this->prices_by_qty_list[$i]=$resultat;
2540  }
2541  else
2542  {
2543  dol_print_error($this->db);
2544  return -1;
2545  }
2546  }*/
2547  } else {
2548  $this->error = $this->db->lasterror;
2549  return -1;
2550  }
2551  }
2552  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
2553  // Nothing loaded by default. List may be very long.
2554  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
2555  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2556  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
2557  $sql .= " FROM ".$this->db->prefix()."product_price";
2558  $sql .= " WHERE fk_product = ".((int) $this->id);
2559  $sql .= " ORDER BY date_price DESC, rowid DESC";
2560  $sql .= " LIMIT 1";
2561  $resql = $this->db->query($sql);
2562  if ($resql) {
2563  $result = $this->db->fetch_array($resql);
2564 
2565  // Price by quantity
2566  $this->prices_by_qty[0] = $result["price_by_qty"];
2567  $this->prices_by_qty_id[0] = $result["rowid"];
2568  // Récuperation de la liste des prix selon qty si flag positionné
2569  if ($this->prices_by_qty[0] == 1) {
2570  $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
2571  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2572  $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
2573  $sql .= " ORDER BY quantity ASC";
2574  $resultat = array();
2575  $resql = $this->db->query($sql);
2576  if ($resql) {
2577  $ii = 0;
2578  while ($result = $this->db->fetch_array($resql)) {
2579  $resultat[$ii] = array();
2580  $resultat[$ii]["rowid"] = $result["rowid"];
2581  $resultat[$ii]["price"] = $result["price"];
2582  $resultat[$ii]["unitprice"] = $result["unitprice"];
2583  $resultat[$ii]["quantity"] = $result["quantity"];
2584  $resultat[$ii]["remise_percent"] = $result["remise_percent"];
2585  //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
2586  $resultat[$ii]["price_base_type"] = $result["price_base_type"];
2587  $ii++;
2588  }
2589  $this->prices_by_qty_list[0] = $resultat;
2590  } else {
2591  $this->error = $this->db->lasterror;
2592  return -1;
2593  }
2594  }
2595  } else {
2596  $this->error = $this->db->lasterror;
2597  return -1;
2598  }
2599  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
2600  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
2601  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2602  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
2603  $sql .= " FROM ".$this->db->prefix()."product_price";
2604  $sql .= " WHERE entity IN (".getEntity('productprice').")";
2605  $sql .= " AND price_level=".((int) $i);
2606  $sql .= " AND fk_product = ".((int) $this->id);
2607  $sql .= " ORDER BY date_price DESC, rowid DESC";
2608  $sql .= " LIMIT 1";
2609  $resql = $this->db->query($sql);
2610  if ($resql) {
2611  $result = $this->db->fetch_array($resql);
2612 
2613  $this->multiprices[$i] = $result["price"];
2614  $this->multiprices_ttc[$i] = $result["price_ttc"];
2615  $this->multiprices_min[$i] = $result["price_min"];
2616  $this->multiprices_min_ttc[$i] = $result["price_min_ttc"];
2617  $this->multiprices_base_type[$i] = $result["price_base_type"];
2618  // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
2619  $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')'
2620  $this->multiprices_recuperableonly[$i] = $result["recuperableonly"];
2621 
2622  // Price by quantity
2623  $this->prices_by_qty[$i] = $result["price_by_qty"];
2624  $this->prices_by_qty_id[$i] = $result["rowid"];
2625  // Récuperation de la liste des prix selon qty si flag positionné
2626  if ($this->prices_by_qty[$i] == 1) {
2627  $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
2628  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2629  $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
2630  $sql .= " ORDER BY quantity ASC";
2631  $resultat = array();
2632  $resql = $this->db->query($sql);
2633  if ($resql) {
2634  $ii = 0;
2635  while ($result = $this->db->fetch_array($resql)) {
2636  $resultat[$ii] = array();
2637  $resultat[$ii]["rowid"] = $result["rowid"];
2638  $resultat[$ii]["price"] = $result["price"];
2639  $resultat[$ii]["unitprice"] = $result["unitprice"];
2640  $resultat[$ii]["quantity"] = $result["quantity"];
2641  $resultat[$ii]["remise_percent"] = $result["remise_percent"];
2642  $resultat[$ii]["remise"] = $result["remise"]; // deprecated
2643  $resultat[$ii]["price_base_type"] = $result["price_base_type"];
2644  $ii++;
2645  }
2646  $this->prices_by_qty_list[$i] = $resultat;
2647  } else {
2648  $this->error = $this->db->lasterror;
2649  return -1;
2650  }
2651  }
2652  } else {
2653  $this->error = $this->db->lasterror;
2654  return -1;
2655  }
2656  }
2657  }
2658 
2659  if (!empty($conf->dynamicprices->enabled) && !empty($this->fk_price_expression) && empty($ignore_expression)) {
2660  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2661  $priceparser = new PriceParser($this->db);
2662  $price_result = $priceparser->parseProduct($this);
2663  if ($price_result >= 0) {
2664  $this->price = $price_result;
2665  // Calculate the VAT
2666  $this->price_ttc = price2num($this->price) * (1 + ($this->tva_tx / 100));
2667  $this->price_ttc = price2num($this->price_ttc, 'MU');
2668  }
2669  }
2670 
2671  // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
2672  // Instead we just init the stock_warehouse array
2673  $this->stock_warehouse = array();
2674 
2675  return 1;
2676  } else {
2677  return 0;
2678  }
2679  } else {
2680  $this->error = $this->db->lasterror();
2681  return -1;
2682  }
2683  }
2684 
2685  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2692  public function load_stats_mo($socid = 0)
2693  {
2694  // phpcs:enable
2695  global $user, $hookmanager, $action;
2696 
2697  $error = 0;
2698 
2699  foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
2700  $this->stats_mo['customers_'.$role] = 0;
2701  $this->stats_mo['nb_'.$role] = 0;
2702  $this->stats_mo['qty_'.$role] = 0;
2703 
2704  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
2705  $sql .= " SUM(mp.qty) as qty";
2706  $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
2707  $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
2708  if (empty($user->rights->societe->client->voir) && !$socid) {
2709  $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
2710  }
2711  $sql .= " WHERE ";
2712  $sql .= " c.entity IN (".getEntity('mo').")";
2713 
2714  $sql .= " AND mp.fk_product = ".((int) $this->id);
2715  $sql .= " AND mp.role ='".$this->db->escape($role)."'";
2716  if ($socid > 0) {
2717  $sql .= " AND c.fk_soc = ".((int) $socid);
2718  }
2719 
2720  $result = $this->db->query($sql);
2721  if ($result) {
2722  $obj = $this->db->fetch_object($result);
2723  $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
2724  $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
2725  $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
2726  } else {
2727  $this->error = $this->db->error();
2728  $error++;
2729  }
2730  }
2731 
2732  if (!empty($error)) {
2733  return -1;
2734  }
2735 
2736  $parameters = array('socid' => $socid);
2737  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
2738  if ($reshook > 0) {
2739  $this->stats_mo = $hookmanager->resArray['stats_mo'];
2740  }
2741 
2742  return 1;
2743  }
2744 
2745  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2752  public function load_stats_bom($socid = 0)
2753  {
2754  // phpcs:enable
2755  global $user, $hookmanager, $action;
2756 
2757  $error = 0;
2758 
2759  $this->stats_bom['nb_toproduce'] = 0;
2760  $this->stats_bom['nb_toconsume'] = 0;
2761  $this->stats_bom['qty_toproduce'] = 0;
2762  $this->stats_bom['qty_toconsume'] = 0;
2763 
2764  $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
2765  $sql .= " SUM(b.qty) as qty_toproduce";
2766  $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
2767  $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
2768  $sql .= " WHERE ";
2769  $sql .= " b.entity IN (".getEntity('bom').")";
2770  $sql .= " AND b.fk_product =".((int) $this->id);
2771  $sql .= " GROUP BY b.rowid";
2772 
2773  $result = $this->db->query($sql);
2774  if ($result) {
2775  $obj = $this->db->fetch_object($result);
2776  $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
2777  $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
2778  } else {
2779  $this->error = $this->db->error();
2780  $error++;
2781  }
2782 
2783  $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
2784  $sql .= " SUM(bl.qty) as qty_toconsume";
2785  $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
2786  $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
2787  $sql .= " WHERE ";
2788  $sql .= " b.entity IN (".getEntity('bom').")";
2789  $sql .= " AND bl.fk_product =".((int) $this->id);
2790 
2791  $result = $this->db->query($sql);
2792  if ($result) {
2793  $obj = $this->db->fetch_object($result);
2794  $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
2795  $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
2796  } else {
2797  $this->error = $this->db->error();
2798  $error++;
2799  }
2800 
2801  if (!empty($error)) {
2802  return -1;
2803  }
2804 
2805  $parameters = array('socid' => $socid);
2806  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
2807  if ($reshook > 0) {
2808  $this->stats_bom = $hookmanager->resArray['stats_bom'];
2809  }
2810 
2811  return 1;
2812  }
2813 
2814  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2821  public function load_stats_propale($socid = 0)
2822  {
2823  // phpcs:enable
2824  global $conf, $user, $hookmanager, $action;
2825 
2826  $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
2827  $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
2828  $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
2829  $sql .= ", ".$this->db->prefix()."propal as p";
2830  $sql .= ", ".$this->db->prefix()."societe as s";
2831  if (empty($user->rights->societe->client->voir) && !$socid) {
2832  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2833  }
2834  $sql .= " WHERE p.rowid = pd.fk_propal";
2835  $sql .= " AND p.fk_soc = s.rowid";
2836  $sql .= " AND p.entity IN (".getEntity('propal').")";
2837  $sql .= " AND pd.fk_product = ".((int) $this->id);
2838  if (empty($user->rights->societe->client->voir) && !$socid) {
2839  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2840  }
2841  //$sql.= " AND pr.fk_statut != 0";
2842  if ($socid > 0) {
2843  $sql .= " AND p.fk_soc = ".((int) $socid);
2844  }
2845 
2846  $result = $this->db->query($sql);
2847  if ($result) {
2848  $obj = $this->db->fetch_object($result);
2849  $this->stats_propale['customers'] = $obj->nb_customers;
2850  $this->stats_propale['nb'] = $obj->nb;
2851  $this->stats_propale['rows'] = $obj->nb_rows;
2852  $this->stats_propale['qty'] = $obj->qty ? $obj->qty : 0;
2853 
2854  // if it's a virtual product, maybe it is in proposal by extension
2855  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
2856  $TFather = $this->getFather();
2857  if (is_array($TFather) && !empty($TFather)) {
2858  foreach ($TFather as &$fatherData) {
2859  $pFather = new Product($this->db);
2860  $pFather->id = $fatherData['id'];
2861  $qtyCoef = $fatherData['qty'];
2862 
2863  if ($fatherData['incdec']) {
2864  $pFather->load_stats_propale($socid);
2865 
2866  $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
2867  $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
2868  $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
2869  $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
2870  }
2871  }
2872  }
2873  }
2874 
2875  $parameters = array('socid' => $socid);
2876  $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
2877  if ($reshook > 0) {
2878  $this->stats_propale = $hookmanager->resArray['stats_propale'];
2879  }
2880 
2881  return 1;
2882  } else {
2883  $this->error = $this->db->error();
2884  return -1;
2885  }
2886  }
2887 
2888 
2889  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2896  public function load_stats_proposal_supplier($socid = 0)
2897  {
2898  // phpcs:enable
2899  global $conf, $user, $hookmanager, $action;
2900 
2901  $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
2902  $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
2903  $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
2904  $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
2905  $sql .= ", ".$this->db->prefix()."societe as s";
2906  if (empty($user->rights->societe->client->voir) && !$socid) {
2907  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2908  }
2909  $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
2910  $sql .= " AND p.fk_soc = s.rowid";
2911  $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
2912  $sql .= " AND pd.fk_product = ".((int) $this->id);
2913  if (empty($user->rights->societe->client->voir) && !$socid) {
2914  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2915  }
2916  //$sql.= " AND pr.fk_statut != 0";
2917  if ($socid > 0) {
2918  $sql .= " AND p.fk_soc = ".((int) $socid);
2919  }
2920 
2921  $result = $this->db->query($sql);
2922  if ($result) {
2923  $obj = $this->db->fetch_object($result);
2924  $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
2925  $this->stats_proposal_supplier['nb'] = $obj->nb;
2926  $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
2927  $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
2928 
2929  $parameters = array('socid' => $socid);
2930  $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
2931  if ($reshook > 0) {
2932  $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
2933  }
2934 
2935  return 1;
2936  } else {
2937  $this->error = $this->db->error();
2938  return -1;
2939  }
2940  }
2941 
2942 
2943  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2952  public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
2953  {
2954  // phpcs:enable
2955  global $conf, $user, $hookmanager, $action;
2956 
2957  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
2958  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
2959  $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
2960  $sql .= ", ".$this->db->prefix()."commande as c";
2961  $sql .= ", ".$this->db->prefix()."societe as s";
2962  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
2963  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2964  }
2965  $sql .= " WHERE c.rowid = cd.fk_commande";
2966  $sql .= " AND c.fk_soc = s.rowid";
2967  $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
2968  $sql .= " AND cd.fk_product = ".((int) $this->id);
2969  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
2970  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2971  }
2972  if ($socid > 0) {
2973  $sql .= " AND c.fk_soc = ".((int) $socid);
2974  }
2975  if ($filtrestatut <> '') {
2976  $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")";
2977  }
2978 
2979  $result = $this->db->query($sql);
2980  if ($result) {
2981  $obj = $this->db->fetch_object($result);
2982  $this->stats_commande['customers'] = $obj->nb_customers;
2983  $this->stats_commande['nb'] = $obj->nb;
2984  $this->stats_commande['rows'] = $obj->nb_rows;
2985  $this->stats_commande['qty'] = $obj->qty ? $obj->qty : 0;
2986 
2987  // if it's a virtual product, maybe it is in order by extension
2988  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
2989  $TFather = $this->getFather();
2990  if (is_array($TFather) && !empty($TFather)) {
2991  foreach ($TFather as &$fatherData) {
2992  $pFather = new Product($this->db);
2993  $pFather->id = $fatherData['id'];
2994  $qtyCoef = $fatherData['qty'];
2995 
2996  if ($fatherData['incdec']) {
2997  $pFather->load_stats_commande($socid, $filtrestatut);
2998 
2999  $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
3000  $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
3001  $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
3002  $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
3003  }
3004  }
3005  }
3006  }
3007 
3008  // If stock decrease is on invoice validation, the theorical stock continue to
3009  // count the orders to ship in theorical stock when some are already removed b invoice validation.
3010  // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation.
3011  if (!empty($conf->global->STOCK_CALCULATE_ON_BILL) && $forVirtualStock) {
3012  if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) {
3013  $adeduire = 0;
3014  $sql = "SELECT SUM(".$this->db->ifsql('f.type=2', -1, 1)." * fd.qty) as count FROM ".$this->db->prefix()."facturedet fd ";
3015  $sql .= " JOIN ".$this->db->prefix()."facture f ON fd.fk_facture = f.rowid ";
3016  $sql .= " JOIN ".$this->db->prefix()."element_element el ON el.fk_target = f.rowid and el.targettype = 'facture' and sourcetype = 'commande'";
3017  $sql .= " JOIN ".$this->db->prefix()."commande c ON el.fk_source = c.rowid ";
3018  $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
3019  dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
3020 
3021  $resql = $this->db->query($sql);
3022  if ($resql) {
3023  if ($this->db->num_rows($resql) > 0) {
3024  $obj = $this->db->fetch_object($resql);
3025  $adeduire += $obj->count;
3026  }
3027  } else {
3028  $this->error = $this->db->error();
3029  return -1;
3030  }
3031 
3032  $this->stats_commande['qty'] -= $adeduire;
3033  }
3034  }
3035 
3036  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3037  $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
3038  if ($reshook > 0) {
3039  $this->stats_commande = $hookmanager->resArray['stats_commande'];
3040  }
3041  return 1;
3042  } else {
3043  $this->error = $this->db->error();
3044  return -1;
3045  }
3046  }
3047 
3048  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3057  public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3058  {
3059  // phpcs:enable
3060  global $conf, $user, $hookmanager, $action;
3061 
3062  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
3063  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3064  $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
3065  $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
3066  $sql .= ", ".$this->db->prefix()."societe as s";
3067  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3068  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3069  }
3070  $sql .= " WHERE c.rowid = cd.fk_commande";
3071  $sql .= " AND c.fk_soc = s.rowid";
3072  $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
3073  $sql .= " AND cd.fk_product = ".((int) $this->id);
3074  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3075  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3076  }
3077  if ($socid > 0) {
3078  $sql .= " AND c.fk_soc = ".((int) $socid);
3079  }
3080  if ($filtrestatut != '') {
3081  $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
3082  }
3083 
3084  $result = $this->db->query($sql);
3085  if ($result) {
3086  $obj = $this->db->fetch_object($result);
3087  $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
3088  $this->stats_commande_fournisseur['nb'] = $obj->nb;
3089  $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
3090  $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3091 
3092  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3093  $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
3094  if ($reshook > 0) {
3095  $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
3096  }
3097 
3098  return 1;
3099  } else {
3100  $this->error = $this->db->error().' sql='.$sql;
3101  return -1;
3102  }
3103  }
3104 
3105  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3115  public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
3116  {
3117  // phpcs:enable
3118  global $conf, $user, $hookmanager, $action;
3119 
3120  $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
3121  $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
3122  $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
3123  $sql .= ", ".$this->db->prefix()."commandedet as cd";
3124  $sql .= ", ".$this->db->prefix()."commande as c";
3125  $sql .= ", ".$this->db->prefix()."expedition as e";
3126  $sql .= ", ".$this->db->prefix()."societe as s";
3127  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3128  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3129  }
3130  $sql .= " WHERE e.rowid = ed.fk_expedition";
3131  $sql .= " AND c.rowid = cd.fk_commande";
3132  $sql .= " AND e.fk_soc = s.rowid";
3133  $sql .= " AND e.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
3134  $sql .= " AND ed.fk_origin_line = cd.rowid";
3135  $sql .= " AND cd.fk_product = ".((int) $this->id);
3136  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3137  $sql .= " AND e.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3138  }
3139  if ($socid > 0) {
3140  $sql .= " AND e.fk_soc = ".((int) $socid);
3141  }
3142  if ($filtrestatut <> '') {
3143  $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3144  }
3145  if (!empty($filterShipmentStatus)) {
3146  $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
3147  }
3148 
3149  $result = $this->db->query($sql);
3150  if ($result) {
3151  $obj = $this->db->fetch_object($result);
3152  $this->stats_expedition['customers'] = $obj->nb_customers;
3153  $this->stats_expedition['nb'] = $obj->nb;
3154  $this->stats_expedition['rows'] = $obj->nb_rows;
3155  $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
3156 
3157  // if it's a virtual product, maybe it is in sending by extension
3158  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3159  $TFather = $this->getFather();
3160  if (is_array($TFather) && !empty($TFather)) {
3161  foreach ($TFather as &$fatherData) {
3162  $pFather = new Product($this->db);
3163  $pFather->id = $fatherData['id'];
3164  $qtyCoef = $fatherData['qty'];
3165 
3166  if ($fatherData['incdec']) {
3167  $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
3168 
3169  $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
3170  $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
3171  $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
3172  $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
3173  }
3174  }
3175  }
3176  }
3177 
3178  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
3179  $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
3180  if ($reshook > 0) {
3181  $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
3182  }
3183 
3184  return 1;
3185  } else {
3186  $this->error = $this->db->error();
3187  return -1;
3188  }
3189  }
3190 
3191  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3200  public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3201  {
3202  // phpcs:enable
3203  global $conf, $user, $hookmanager, $action;
3204 
3205  $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
3206  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3207  $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as fd";
3208  $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
3209  $sql .= ", ".$this->db->prefix()."societe as s";
3210  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3211  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3212  }
3213  $sql .= " WHERE cf.rowid = fd.fk_commande";
3214  $sql .= " AND cf.fk_soc = s.rowid";
3215  $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
3216  $sql .= " AND fd.fk_product = ".((int) $this->id);
3217  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3218  $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3219  }
3220  if ($socid > 0) {
3221  $sql .= " AND cf.fk_soc = ".((int) $socid);
3222  }
3223  if ($filtrestatut <> '') {
3224  $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3225  }
3226 
3227  $result = $this->db->query($sql);
3228  if ($result) {
3229  $obj = $this->db->fetch_object($result);
3230  $this->stats_reception['suppliers'] = $obj->nb_suppliers;
3231  $this->stats_reception['nb'] = $obj->nb;
3232  $this->stats_reception['rows'] = $obj->nb_rows;
3233  $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
3234 
3235  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3236  $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
3237  if ($reshook > 0) {
3238  $this->stats_reception = $hookmanager->resArray['stats_reception'];
3239  }
3240 
3241  return 1;
3242  } else {
3243  $this->error = $this->db->error();
3244  return -1;
3245  }
3246  }
3247 
3248  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3257  public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3258  {
3259  // phpcs:enable
3260  global $conf, $user, $hookmanager, $action;
3261 
3262  $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
3263  $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
3264  $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
3265  $sql .= ", ".$this->db->prefix()."mrp_mo as m";
3266  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
3267  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3268  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3269  }
3270  $sql .= " WHERE m.rowid = mp.fk_mo";
3271  $sql .= " AND m.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mrp').")";
3272  $sql .= " AND mp.fk_product = ".((int) $this->id);
3273  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3274  $sql .= " AND m.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3275  }
3276  if ($socid > 0) {
3277  $sql .= " AND m.fk_soc = ".((int) $socid);
3278  }
3279  if ($filtrestatut <> '') {
3280  $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
3281  }
3282  $sql .= " GROUP BY role";
3283 
3284  $this->stats_mrptoconsume['customers'] = 0;
3285  $this->stats_mrptoconsume['nb'] = 0;
3286  $this->stats_mrptoconsume['rows'] = 0;
3287  $this->stats_mrptoconsume['qty'] = 0;
3288  $this->stats_mrptoproduce['customers'] = 0;
3289  $this->stats_mrptoproduce['nb'] = 0;
3290  $this->stats_mrptoproduce['rows'] = 0;
3291  $this->stats_mrptoproduce['qty'] = 0;
3292 
3293  $result = $this->db->query($sql);
3294  if ($result) {
3295  while ($obj = $this->db->fetch_object($result)) {
3296  if ($obj->role == 'toconsume') {
3297  $this->stats_mrptoconsume['customers'] += $obj->nb_customers;
3298  $this->stats_mrptoconsume['nb'] += $obj->nb;
3299  $this->stats_mrptoconsume['rows'] += $obj->nb_rows;
3300  $this->stats_mrptoconsume['qty'] += ($obj->qty ? $obj->qty : 0);
3301  }
3302  if ($obj->role == 'consumed') {
3303  //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
3304  //$this->stats_mrptoconsume['nb'] += $obj->nb;
3305  //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
3306  $this->stats_mrptoconsume['qty'] -= ($obj->qty ? $obj->qty : 0);
3307  }
3308  if ($obj->role == 'toproduce') {
3309  $this->stats_mrptoproduce['customers'] += $obj->nb_customers;
3310  $this->stats_mrptoproduce['nb'] += $obj->nb;
3311  $this->stats_mrptoproduce['rows'] += $obj->nb_rows;
3312  $this->stats_mrptoproduce['qty'] += ($obj->qty ? $obj->qty : 0);
3313  }
3314  if ($obj->role == 'produced') {
3315  //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
3316  //$this->stats_mrptoproduce['nb'] += $obj->nb;
3317  //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
3318  $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
3319  }
3320  }
3321 
3322  // Clean data
3323  if ($this->stats_mrptoconsume['qty'] < 0) {
3324  $this->stats_mrptoconsume['qty'] = 0;
3325  }
3326  if ($this->stats_mrptoproduce['qty'] < 0) {
3327  $this->stats_mrptoproduce['qty'] = 0;
3328  }
3329 
3330  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3331  $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
3332  if ($reshook > 0) {
3333  $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
3334  }
3335 
3336  return 1;
3337  } else {
3338  $this->error = $this->db->error();
3339  return -1;
3340  }
3341  }
3342 
3343  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3350  public function load_stats_contrat($socid = 0)
3351  {
3352  // phpcs:enable
3353  global $conf, $user, $hookmanager, $action;
3354 
3355  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3356  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3357  $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
3358  $sql .= ", ".$this->db->prefix()."contrat as c";
3359  $sql .= ", ".$this->db->prefix()."societe as s";
3360  if (empty($user->rights->societe->client->voir) && !$socid) {
3361  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3362  }
3363  $sql .= " WHERE c.rowid = cd.fk_contrat";
3364  $sql .= " AND c.fk_soc = s.rowid";
3365  $sql .= " AND c.entity IN (".getEntity('contract').")";
3366  $sql .= " AND cd.fk_product = ".((int) $this->id);
3367  if (empty($user->rights->societe->client->voir) && !$socid) {
3368  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3369  }
3370  //$sql.= " AND c.statut != 0";
3371  if ($socid > 0) {
3372  $sql .= " AND c.fk_soc = ".((int) $socid);
3373  }
3374 
3375  $result = $this->db->query($sql);
3376  if ($result) {
3377  $obj = $this->db->fetch_object($result);
3378  $this->stats_contrat['customers'] = $obj->nb_customers;
3379  $this->stats_contrat['nb'] = $obj->nb;
3380  $this->stats_contrat['rows'] = $obj->nb_rows;
3381  $this->stats_contrat['qty'] = $obj->qty ? $obj->qty : 0;
3382 
3383  // if it's a virtual product, maybe it is in contract by extension
3384  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3385  $TFather = $this->getFather();
3386  if (is_array($TFather) && !empty($TFather)) {
3387  foreach ($TFather as &$fatherData) {
3388  $pFather = new Product($this->db);
3389  $pFather->id = $fatherData['id'];
3390  $qtyCoef = $fatherData['qty'];
3391 
3392  if ($fatherData['incdec']) {
3393  $pFather->load_stats_contrat($socid);
3394 
3395  $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
3396  $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
3397  $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
3398  $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
3399  }
3400  }
3401  }
3402  }
3403 
3404  $parameters = array('socid' => $socid);
3405  $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
3406  if ($reshook > 0) {
3407  $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
3408  }
3409 
3410  return 1;
3411  } else {
3412  $this->error = $this->db->error().' sql='.$sql;
3413  return -1;
3414  }
3415  }
3416 
3417  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3424  public function load_stats_facture($socid = 0)
3425  {
3426  // phpcs:enable
3427  global $db, $conf, $user, $hookmanager, $action;
3428 
3429  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
3430  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
3431  $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
3432  $sql .= ", ".$this->db->prefix()."facture as f";
3433  $sql .= ", ".$this->db->prefix()."societe as s";
3434  if (empty($user->rights->societe->client->voir) && !$socid) {
3435  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3436  }
3437  $sql .= " WHERE f.rowid = fd.fk_facture";
3438  $sql .= " AND f.fk_soc = s.rowid";
3439  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3440  $sql .= " AND fd.fk_product = ".((int) $this->id);
3441  if (empty($user->rights->societe->client->voir) && !$socid) {
3442  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3443  }
3444  //$sql.= " AND f.fk_statut != 0";
3445  if ($socid > 0) {
3446  $sql .= " AND f.fk_soc = ".((int) $socid);
3447  }
3448 
3449  $result = $this->db->query($sql);
3450  if ($result) {
3451  $obj = $this->db->fetch_object($result);
3452  $this->stats_facture['customers'] = $obj->nb_customers;
3453  $this->stats_facture['nb'] = $obj->nb;
3454  $this->stats_facture['rows'] = $obj->nb_rows;
3455  $this->stats_facture['qty'] = $obj->qty ? $obj->qty : 0;
3456 
3457  // if it's a virtual product, maybe it is in invoice by extension
3458  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3459  $TFather = $this->getFather();
3460  if (is_array($TFather) && !empty($TFather)) {
3461  foreach ($TFather as &$fatherData) {
3462  $pFather = new Product($this->db);
3463  $pFather->id = $fatherData['id'];
3464  $qtyCoef = $fatherData['qty'];
3465 
3466  if ($fatherData['incdec']) {
3467  $pFather->load_stats_facture($socid);
3468 
3469  $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
3470  $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
3471  $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
3472  $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
3473  }
3474  }
3475  }
3476  }
3477 
3478  $parameters = array('socid' => $socid);
3479  $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
3480  if ($reshook > 0) {
3481  $this->stats_facture = $hookmanager->resArray['stats_facture'];
3482  }
3483 
3484  return 1;
3485  } else {
3486  $this->error = $this->db->error();
3487  return -1;
3488  }
3489  }
3490 
3491 
3492  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3499  public function load_stats_facturerec($socid = 0)
3500  {
3501  // phpcs:enable
3502  global $db, $conf, $user, $hookmanager;
3503 
3504  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
3505  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3506  $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_rec as fd";
3507  $sql .= ", ".MAIN_DB_PREFIX."facture_rec as f";
3508  $sql .= ", ".MAIN_DB_PREFIX."societe as s";
3509  if (empty($user->rights->societe->client->voir) && !$socid) {
3510  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3511  }
3512  $sql .= " WHERE f.rowid = fd.fk_facture";
3513  $sql .= " AND f.fk_soc = s.rowid";
3514  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3515  $sql .= " AND fd.fk_product = ".((int) $this->id);
3516  if (empty($user->rights->societe->client->voir) && !$socid) {
3517  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3518  }
3519  //$sql.= " AND f.fk_statut != 0";
3520  if ($socid > 0) {
3521  $sql .= " AND f.fk_soc = ".((int) $socid);
3522  }
3523 
3524  $result = $this->db->query($sql);
3525  if ($result) {
3526  $obj = $this->db->fetch_object($result);
3527  $this->stats_facturerec['customers'] = $obj->nb_customers;
3528  $this->stats_facturerec['nb'] = $obj->nb;
3529  $this->stats_facturerec['rows'] = $obj->nb_rows;
3530  $this->stats_facturerec['qty'] = $obj->qty ? $obj->qty : 0;
3531 
3532  // if it's a virtual product, maybe it is in invoice by extension
3533  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3534  $TFather = $this->getFather();
3535  if (is_array($TFather) && !empty($TFather)) {
3536  foreach ($TFather as &$fatherData) {
3537  $pFather = new Product($this->db);
3538  $pFather->id = $fatherData['id'];
3539  $qtyCoef = $fatherData['qty'];
3540 
3541  if ($fatherData['incdec']) {
3542  $pFather->load_stats_facture($socid);
3543 
3544  $this->stats_facturerec['customers'] += $pFather->stats_facturerec['customers'];
3545  $this->stats_facturerec['nb'] += $pFather->stats_facturerec['nb'];
3546  $this->stats_facturerec['rows'] += $pFather->stats_facturerec['rows'];
3547  $this->stats_facturerec['qty'] += $pFather->stats_facturerec['qty'] * $qtyCoef;
3548  }
3549  }
3550  }
3551  }
3552 
3553  $parameters = array('socid' => $socid);
3554  $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoiceRec', $parameters, $this, $action);
3555  if ($reshook > 0) {
3556  $this->stats_facturerec = $hookmanager->resArray['stats_facturerec'];
3557  }
3558 
3559  return 1;
3560  } else {
3561  $this->error = $this->db->error();
3562  return -1;
3563  }
3564  }
3565 
3566  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3573  public function load_stats_facture_fournisseur($socid = 0)
3574  {
3575  // phpcs:enable
3576  global $conf, $user, $hookmanager, $action;
3577 
3578  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
3579  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3580  $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
3581  $sql .= ", ".$this->db->prefix()."facture_fourn as f";
3582  $sql .= ", ".$this->db->prefix()."societe as s";
3583  if (empty($user->rights->societe->client->voir) && !$socid) {
3584  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3585  }
3586  $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
3587  $sql .= " AND f.fk_soc = s.rowid";
3588  $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
3589  $sql .= " AND fd.fk_product = ".((int) $this->id);
3590  if (empty($user->rights->societe->client->voir) && !$socid) {
3591  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3592  }
3593  //$sql.= " AND f.fk_statut != 0";
3594  if ($socid > 0) {
3595  $sql .= " AND f.fk_soc = ".((int) $socid);
3596  }
3597 
3598  $result = $this->db->query($sql);
3599  if ($result) {
3600  $obj = $this->db->fetch_object($result);
3601  $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers;
3602  $this->stats_facture_fournisseur['nb'] = $obj->nb;
3603  $this->stats_facture_fournisseur['rows'] = $obj->nb_rows;
3604  $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3605 
3606  $parameters = array('socid' => $socid);
3607  $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
3608  if ($reshook > 0) {
3609  $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
3610  }
3611 
3612  return 1;
3613  } else {
3614  $this->error = $this->db->error();
3615  return -1;
3616  }
3617  }
3618 
3619  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3628  private function _get_stats($sql, $mode, $year = 0)
3629  {
3630  // phpcs:enable
3631  $tab = array();
3632 
3633  $resql = $this->db->query($sql);
3634  if ($resql) {
3635  $num = $this->db->num_rows($resql);
3636  $i = 0;
3637  while ($i < $num) {
3638  $arr = $this->db->fetch_array($resql);
3639  $keyfortab = (string) $arr[1];
3640  if ($year == -1) {
3641  $keyfortab = substr($keyfortab, -2);
3642  }
3643 
3644  if ($mode == 'byunit') {
3645  $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
3646  } elseif ($mode == 'bynumber') {
3647  $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
3648  }
3649  $i++;
3650  }
3651  } else {
3652  $this->error = $this->db->error().' sql='.$sql;
3653  return -1;
3654  }
3655 
3656  if (empty($year)) {
3657  $year = strftime('%Y', time());
3658  $month = strftime('%m', time());
3659  } elseif ($year == -1) {
3660  $year = '';
3661  $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
3662  } else {
3663  $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
3664  }
3665 
3666  $result = array();
3667 
3668  for ($j = 0; $j < 12; $j++) {
3669  // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
3670  $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
3671 
3672  //print $idx.'-'.$year.'-'.$month.'<br>';
3673  $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
3674  // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
3675 
3676  $month = "0".($month - 1);
3677  if (dol_strlen($month) == 3) {
3678  $month = substr($month, 1);
3679  }
3680  if ($month == 0) {
3681  $month = 12;
3682  $year = $year - 1;
3683  }
3684  }
3685 
3686  return array_reverse($result);
3687  }
3688 
3689 
3690  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3701  public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3702  {
3703  // phpcs:enable
3704  global $conf;
3705  global $user;
3706 
3707  $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
3708  if ($mode == 'bynumber') {
3709  $sql .= ", count(DISTINCT f.rowid)";
3710  }
3711  $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
3712  if ($filteronproducttype >= 0) {
3713  $sql .= ", ".$this->db->prefix()."product as p";
3714  }
3715  if (empty($user->rights->societe->client->voir) && !$socid) {
3716  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3717  }
3718  $sql .= " WHERE f.rowid = d.fk_facture";
3719  if ($this->id > 0) {
3720  $sql .= " AND d.fk_product = ".((int) $this->id);
3721  } else {
3722  $sql .= " AND d.fk_product > 0";
3723  }
3724  if ($filteronproducttype >= 0) {
3725  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3726  }
3727  $sql .= " AND f.fk_soc = s.rowid";
3728  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3729  if (empty($user->rights->societe->client->voir) && !$socid) {
3730  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3731  }
3732  if ($socid > 0) {
3733  $sql .= " AND f.fk_soc = $socid";
3734  }
3735  $sql .= $morefilter;
3736  $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
3737  $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
3738 
3739  return $this->_get_stats($sql, $mode, $year);
3740  }
3741 
3742 
3743  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3754  public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3755  {
3756  // phpcs:enable
3757  global $conf;
3758  global $user;
3759 
3760  $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
3761  if ($mode == 'bynumber') {
3762  $sql .= ", count(DISTINCT f.rowid)";
3763  }
3764  $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
3765  if ($filteronproducttype >= 0) {
3766  $sql .= ", ".$this->db->prefix()."product as p";
3767  }
3768  if (empty($user->rights->societe->client->voir) && !$socid) {
3769  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3770  }
3771  $sql .= " WHERE f.rowid = d.fk_facture_fourn";
3772  if ($this->id > 0) {
3773  $sql .= " AND d.fk_product = ".((int) $this->id);
3774  } else {
3775  $sql .= " AND d.fk_product > 0";
3776  }
3777  if ($filteronproducttype >= 0) {
3778  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3779  }
3780  $sql .= " AND f.fk_soc = s.rowid";
3781  $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
3782  if (empty($user->rights->societe->client->voir) && !$socid) {
3783  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3784  }
3785  if ($socid > 0) {
3786  $sql .= " AND f.fk_soc = $socid";
3787  }
3788  $sql .= $morefilter;
3789  $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
3790  $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
3791 
3792  return $this->_get_stats($sql, $mode, $year);
3793  }
3794 
3795  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3806  public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3807  {
3808  // phpcs:enable
3809  global $conf, $user;
3810 
3811  $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')";
3812  if ($mode == 'bynumber') {
3813  $sql .= ", count(DISTINCT p.rowid)";
3814  }
3815  $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
3816  if ($filteronproducttype >= 0) {
3817  $sql .= ", ".$this->db->prefix()."product as prod";
3818  }
3819  if (empty($user->rights->societe->client->voir) && !$socid) {
3820  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3821  }
3822  $sql .= " WHERE p.rowid = d.fk_propal";
3823  if ($this->id > 0) {
3824  $sql .= " AND d.fk_product = ".((int) $this->id);
3825  } else {
3826  $sql .= " AND d.fk_product > 0";
3827  }
3828  if ($filteronproducttype >= 0) {
3829  $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
3830  }
3831  $sql .= " AND p.fk_soc = s.rowid";
3832  $sql .= " AND p.entity IN (".getEntity('propal').")";
3833  if (empty($user->rights->societe->client->voir) && !$socid) {
3834  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3835  }
3836  if ($socid > 0) {
3837  $sql .= " AND p.fk_soc = ".((int) $socid);
3838  }
3839  $sql .= $morefilter;
3840  $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
3841  $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
3842 
3843  return $this->_get_stats($sql, $mode, $year);
3844  }
3845 
3846  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3857  public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3858  {
3859  // phpcs:enable
3860  global $conf;
3861  global $user;
3862 
3863  $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')";
3864  if ($mode == 'bynumber') {
3865  $sql .= ", count(DISTINCT p.rowid)";
3866  }
3867  $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
3868  if ($filteronproducttype >= 0) {
3869  $sql .= ", ".$this->db->prefix()."product as prod";
3870  }
3871  if (empty($user->rights->societe->client->voir) && !$socid) {
3872  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3873  }
3874  $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
3875  if ($this->id > 0) {
3876  $sql .= " AND d.fk_product = ".((int) $this->id);
3877  } else {
3878  $sql .= " AND d.fk_product > 0";
3879  }
3880  if ($filteronproducttype >= 0) {
3881  $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
3882  }
3883  $sql .= " AND p.fk_soc = s.rowid";
3884  $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
3885  if (empty($user->rights->societe->client->voir) && !$socid) {
3886  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3887  }
3888  if ($socid > 0) {
3889  $sql .= " AND p.fk_soc = ".((int) $socid);
3890  }
3891  $sql .= $morefilter;
3892  $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
3893  $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
3894 
3895  return $this->_get_stats($sql, $mode, $year);
3896  }
3897 
3898  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3909  public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3910  {
3911  // phpcs:enable
3912  global $conf, $user;
3913 
3914  $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
3915  if ($mode == 'bynumber') {
3916  $sql .= ", count(DISTINCT c.rowid)";
3917  }
3918  $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
3919  if ($filteronproducttype >= 0) {
3920  $sql .= ", ".$this->db->prefix()."product as p";
3921  }
3922  if (empty($user->rights->societe->client->voir) && !$socid) {
3923  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3924  }
3925  $sql .= " WHERE c.rowid = d.fk_commande";
3926  if ($this->id > 0) {
3927  $sql .= " AND d.fk_product = ".((int) $this->id);
3928  } else {
3929  $sql .= " AND d.fk_product > 0";
3930  }
3931  if ($filteronproducttype >= 0) {
3932  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3933  }
3934  $sql .= " AND c.fk_soc = s.rowid";
3935  $sql .= " AND c.entity IN (".getEntity('commande').")";
3936  if (empty($user->rights->societe->client->voir) && !$socid) {
3937  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3938  }
3939  if ($socid > 0) {
3940  $sql .= " AND c.fk_soc = ".((int) $socid);
3941  }
3942  $sql .= $morefilter;
3943  $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
3944  $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
3945 
3946  return $this->_get_stats($sql, $mode, $year);
3947  }
3948 
3949  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3960  public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3961  {
3962  // phpcs:enable
3963  global $conf, $user;
3964 
3965  $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
3966  if ($mode == 'bynumber') {
3967  $sql .= ", count(DISTINCT c.rowid)";
3968  }
3969  $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
3970  if ($filteronproducttype >= 0) {
3971  $sql .= ", ".$this->db->prefix()."product as p";
3972  }
3973  if (empty($user->rights->societe->client->voir) && !$socid) {
3974  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3975  }
3976  $sql .= " WHERE c.rowid = d.fk_commande";
3977  if ($this->id > 0) {
3978  $sql .= " AND d.fk_product = ".((int) $this->id);
3979  } else {
3980  $sql .= " AND d.fk_product > 0";
3981  }
3982  if ($filteronproducttype >= 0) {
3983  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3984  }
3985  $sql .= " AND c.fk_soc = s.rowid";
3986  $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
3987  if (empty($user->rights->societe->client->voir) && !$socid) {
3988  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3989  }
3990  if ($socid > 0) {
3991  $sql .= " AND c.fk_soc = ".((int) $socid);
3992  }
3993  $sql .= $morefilter;
3994  $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
3995  $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
3996 
3997  return $this->_get_stats($sql, $mode, $year);
3998  }
3999 
4000  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4011  public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4012  {
4013  // phpcs:enable
4014  global $conf, $user;
4015 
4016  $sql = "SELECT sum(d.qty), date_format(c.date_contrat, '%Y%m')";
4017  if ($mode == 'bynumber') {
4018  $sql .= ", count(DISTINCT c.rowid)";
4019  }
4020  $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
4021  if ($filteronproducttype >= 0) {
4022  $sql .= ", ".$this->db->prefix()."product as p";
4023  }
4024  if (empty($user->rights->societe->client->voir) && !$socid) {
4025  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4026  }
4027 
4028  $sql .= " WHERE c.entity IN (".getEntity('contract').")";
4029  $sql .= " AND c.rowid = d.fk_contrat";
4030 
4031  if ($this->id > 0) {
4032  $sql .= " AND d.fk_product = ".((int) $this->id);
4033  } else {
4034  $sql .= " AND d.fk_product > 0";
4035  }
4036  if ($filteronproducttype >= 0) {
4037  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4038  }
4039  $sql .= " AND c.fk_soc = s.rowid";
4040 
4041  if (empty($user->rights->societe->client->voir) && !$socid) {
4042  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4043  }
4044  if ($socid > 0) {
4045  $sql .= " AND c.fk_soc = ".((int) $socid);
4046  }
4047  $sql .= $morefilter;
4048  $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
4049  $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
4050 
4051  return $this->_get_stats($sql, $mode, $year);
4052  }
4053 
4054  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4065  public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4066  {
4067  // phpcs:enable
4068  global $conf, $user;
4069 
4070  $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
4071  if ($mode == 'bynumber') {
4072  $sql .= ", count(DISTINCT d.rowid)";
4073  }
4074  $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
4075  if ($filteronproducttype >= 0) {
4076  $sql .= ", ".$this->db->prefix()."product as p";
4077  }
4078  if (empty($user->rights->societe->client->voir) && !$socid) {
4079  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4080  }
4081 
4082  $sql .= " WHERE d.entity IN (".getEntity('mo').")";
4083  $sql .= " AND d.status > 0";
4084 
4085  if ($this->id > 0) {
4086  $sql .= " AND d.fk_product = ".((int) $this->id);
4087  } else {
4088  $sql .= " AND d.fk_product > 0";
4089  }
4090  if ($filteronproducttype >= 0) {
4091  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4092  }
4093 
4094  if (empty($user->rights->societe->client->voir) && !$socid) {
4095  $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4096  }
4097  if ($socid > 0) {
4098  $sql .= " AND d.fk_soc = ".((int) $socid);
4099  }
4100  $sql .= $morefilter;
4101  $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
4102  $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
4103 
4104  return $this->_get_stats($sql, $mode, $year);
4105  }
4106 
4107  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4117  public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
4118  {
4119  // phpcs:enable
4120  // Clean parameters
4121  if (!is_numeric($id_pere)) {
4122  $id_pere = 0;
4123  }
4124  if (!is_numeric($id_fils)) {
4125  $id_fils = 0;
4126  }
4127  if (!is_numeric($incdec)) {
4128  $incdec = 0;
4129  }
4130 
4131  $result = $this->del_sousproduit($id_pere, $id_fils);
4132  if ($result < 0) {
4133  return $result;
4134  }
4135 
4136  // Check not already father of id_pere (to avoid father -> child -> father links)
4137  $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
4138  $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
4139  if (!$this->db->query($sql)) {
4140  dol_print_error($this->db);
4141  return -1;
4142  } else {
4143  //Selection of the highest row
4144  $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
4145  $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
4146  $resql = $this->db->query($sql);
4147  if ($resql > 0) {
4148  $obj = $this->db->fetch_object($resql);
4149  $rank = $obj->max_rank + 1;
4150  //Addition of a product with the highest rank +1
4151  $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
4152  $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".price2num($incdec, 'MS').", ".((int) $rank).")";
4153  if (! $this->db->query($sql)) {
4154  dol_print_error($this->db);
4155  return -1;
4156  } else {
4157  return 1;
4158  }
4159  } else {
4160  dol_print_error($this->db);
4161  return -1;
4162  }
4163  }
4164  }
4165 
4166  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4176  public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
4177  {
4178  // phpcs:enable
4179  // Clean parameters
4180  if (!is_numeric($id_pere)) {
4181  $id_pere = 0;
4182  }
4183  if (!is_numeric($id_fils)) {
4184  $id_fils = 0;
4185  }
4186  if (!is_numeric($incdec)) {
4187  $incdec = 1;
4188  }
4189  if (!is_numeric($qty)) {
4190  $qty = 1;
4191  }
4192 
4193  $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
4194  $sql .= 'qty = '.price2num($qty, 'MS');
4195  $sql .= ',incdec = '.price2num($incdec, 'MS');
4196  $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
4197 
4198  if (!$this->db->query($sql)) {
4199  dol_print_error($this->db);
4200  return -1;
4201  } else {
4202  return 1;
4203  }
4204  }
4205 
4206  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4214  public function del_sousproduit($fk_parent, $fk_child)
4215  {
4216  // phpcs:enable
4217  if (!is_numeric($fk_parent)) {
4218  $fk_parent = 0;
4219  }
4220  if (!is_numeric($fk_child)) {
4221  $fk_child = 0;
4222  }
4223 
4224  $sql = "DELETE FROM ".$this->db->prefix()."product_association";
4225  $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
4226  $sql .= " AND fk_product_fils = ".((int) $fk_child);
4227 
4228  dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
4229  if (!$this->db->query($sql)) {
4230  dol_print_error($this->db);
4231  return -1;
4232  }
4233 
4234  // Updated ranks so that none are missing
4235  $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
4236  $sqlrank.= " WHERE fk_product_pere = ".((int) $fk_parent);
4237  $sqlrank.= " ORDER BY rang";
4238  $resqlrank = $this->db->query($sqlrank);
4239  if ($resqlrank) {
4240  $cpt = 0;
4241  while ($objrank = $this->db->fetch_object($resqlrank)) {
4242  $cpt++;
4243  $sql = "UPDATE ".$this->db->prefix()."product_association";
4244  $sql.= " SET rang = ".((int) $cpt);
4245  $sql.= " WHERE rowid = ".((int) $objrank->rowid);
4246  if (! $this->db->query($sql)) {
4247  dol_print_error($this->db);
4248  return -1;
4249  }
4250  }
4251  }
4252  return 1;
4253  }
4254 
4255  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4263  public function is_sousproduit($fk_parent, $fk_child)
4264  {
4265  // phpcs:enable
4266  $sql = "SELECT fk_product_pere, qty, incdec";
4267  $sql .= " FROM ".$this->db->prefix()."product_association";
4268  $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
4269  $sql .= " AND fk_product_fils = ".((int) $fk_child);
4270 
4271  $result = $this->db->query($sql);
4272  if ($result) {
4273  $num = $this->db->num_rows($result);
4274 
4275  if ($num > 0) {
4276  $obj = $this->db->fetch_object($result);
4277 
4278  $this->is_sousproduit_qty = $obj->qty;
4279  $this->is_sousproduit_incdec = $obj->incdec;
4280 
4281  return true;
4282  } else {
4283  return false;
4284  }
4285  } else {
4286  dol_print_error($this->db);
4287  return -1;
4288  }
4289  }
4290 
4291 
4292  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4303  public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
4304  {
4305  // phpcs:enable
4306  global $conf;
4307 
4308  $now = dol_now();
4309 
4310  dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
4311 
4312  // Clean parameters
4313  $quantity = price2num($quantity, 'MS');
4314 
4315  if ($ref_fourn) {
4316  $sql = "SELECT rowid, fk_product";
4317  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4318  $sql .= " WHERE fk_soc = ".((int) $id_fourn);
4319  $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
4320  $sql .= " AND fk_product <> ".((int) $this->id);
4321  $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
4322 
4323  $resql = $this->db->query($sql);
4324  if ($resql) {
4325  $obj = $this->db->fetch_object($resql);
4326  if ($obj) {
4327  // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
4328  $this->product_id_already_linked = $obj->fk_product;
4329  return -3;
4330  }
4331  $this->db->free($resql);
4332  }
4333  }
4334 
4335  $sql = "SELECT rowid";
4336  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4337  $sql .= " WHERE fk_soc = ".((int) $id_fourn);
4338  if ($ref_fourn) {
4339  $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
4340  } else {
4341  $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
4342  }
4343  $sql .= " AND quantity = ".((float) $quantity);
4344  $sql .= " AND fk_product = ".((int) $this->id);
4345  $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
4346 
4347  $resql = $this->db->query($sql);
4348  if ($resql) {
4349  $obj = $this->db->fetch_object($resql);
4350 
4351  // The reference supplier does not exist, we create it for this product.
4352  if (empty($obj)) {
4353  $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
4354  $sql .= "datec";
4355  $sql .= ", entity";
4356  $sql .= ", fk_product";
4357  $sql .= ", fk_soc";
4358  $sql .= ", ref_fourn";
4359  $sql .= ", quantity";
4360  $sql .= ", fk_user";
4361  $sql .= ", tva_tx";
4362  $sql .= ") VALUES (";
4363  $sql .= "'".$this->db->idate($now)."'";
4364  $sql .= ", ".$conf->entity;
4365  $sql .= ", ".$this->id;
4366  $sql .= ", ".$id_fourn;
4367  $sql .= ", '".$this->db->escape($ref_fourn)."'";
4368  $sql .= ", ".$quantity;
4369  $sql .= ", ".$user->id;
4370  $sql .= ", 0";
4371  $sql .= ")";
4372 
4373  if ($this->db->query($sql)) {
4374  $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
4375  return 1;
4376  } else {
4377  $this->error = $this->db->lasterror();
4378  return -1;
4379  }
4380  } else {
4381  // If the supplier price already exists for this product and quantity
4382  $this->product_fourn_price_id = $obj->rowid;
4383  return 0;
4384  }
4385  } else {
4386  $this->error = $this->db->lasterror();
4387  return -2;
4388  }
4389  }
4390 
4391 
4392  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4398  public function list_suppliers()
4399  {
4400  // phpcs:enable
4401  global $conf;
4402 
4403  $list = array();
4404 
4405  $sql = "SELECT DISTINCT p.fk_soc";
4406  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
4407  $sql .= " WHERE p.fk_product = ".((int) $this->id);
4408  $sql .= " AND p.entity = ".((int) $conf->entity);
4409 
4410  $result = $this->db->query($sql);
4411  if ($result) {
4412  $num = $this->db->num_rows($result);
4413  $i = 0;
4414  while ($i < $num) {
4415  $obj = $this->db->fetch_object($result);
4416  $list[$i] = $obj->fk_soc;
4417  $i++;
4418  }
4419  }
4420 
4421  return $list;
4422  }
4423 
4424  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4432  public function clone_price($fromId, $toId)
4433  {
4434  global $conf, $user;
4435 
4436  $now = dol_now();
4437 
4438  $this->db->begin();
4439 
4440  // prices
4441  $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
4442  $sql .= " entity";
4443  $sql .= ", fk_product";
4444  $sql .= ", date_price";
4445  $sql .= ", price_level";
4446  $sql .= ", price";
4447  $sql .= ", price_ttc";
4448  $sql .= ", price_min";
4449  $sql .= ", price_min_ttc";
4450  $sql .= ", price_base_type";
4451  $sql .= ", default_vat_code";
4452  $sql .= ", tva_tx";
4453  $sql .= ", recuperableonly";
4454  $sql .= ", localtax1_tx";
4455  $sql .= ", localtax1_type";
4456  $sql .= ", localtax2_tx";
4457  $sql .= ", localtax2_type";
4458  $sql .= ", fk_user_author";
4459  $sql .= ", tosell";
4460  $sql .= ", price_by_qty";
4461  $sql .= ", fk_price_expression";
4462  $sql .= ", fk_multicurrency";
4463  $sql .= ", multicurrency_code";
4464  $sql .= ", multicurrency_tx";
4465  $sql .= ", multicurrency_price";
4466  $sql .= ", multicurrency_price_ttc";
4467  $sql .= ")";
4468  $sql .= " SELECT";
4469  $sql .= " entity";
4470  $sql .= ", ".$toId;
4471  $sql .= ", '".$this->db->idate($now)."'";
4472  $sql .= ", price_level";
4473  $sql .= ", price";
4474  $sql .= ", price_ttc";
4475  $sql .= ", price_min";
4476  $sql .= ", price_min_ttc";
4477  $sql .= ", price_base_type";
4478  $sql .= ", default_vat_code";
4479  $sql .= ", tva_tx";
4480  $sql .= ", recuperableonly";
4481  $sql .= ", localtax1_tx";
4482  $sql .= ", localtax1_type";
4483  $sql .= ", localtax2_tx";
4484  $sql .= ", localtax2_type";
4485  $sql .= ", ".$user->id;
4486  $sql .= ", tosell";
4487  $sql .= ", price_by_qty";
4488  $sql .= ", fk_price_expression";
4489  $sql .= ", fk_multicurrency";
4490  $sql .= ", multicurrency_code";
4491  $sql .= ", multicurrency_tx";
4492  $sql .= ", multicurrency_price";
4493  $sql .= ", multicurrency_price_ttc";
4494  $sql .= " FROM ".$this->db->prefix()."product_price";
4495  $sql .= " WHERE fk_product = ".((int) $fromId);
4496  $sql .= " ORDER BY date_price DESC";
4497  if ($conf->global->PRODUIT_MULTIPRICES_LIMIT > 0) {
4498  $sql .= " LIMIT ".$conf->global->PRODUIT_MULTIPRICES_LIMIT;
4499  }
4500 
4501  dol_syslog(__METHOD__, LOG_DEBUG);
4502  $resql = $this->db->query($sql);
4503  if (!$resql) {
4504  $this->db->rollback();
4505  return -1;
4506  }
4507 
4508  $this->db->commit();
4509  return 1;
4510  }
4511 
4512  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4520  public function clone_associations($fromId, $toId)
4521  {
4522  // phpcs:enable
4523  $this->db->begin();
4524 
4525  $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty)';
4526  $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".$this->db->prefix()."product_association";
4527  $sql .= " WHERE fk_product_pere = ".((int) $fromId);
4528 
4529  dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
4530  if (!$this->db->query($sql)) {
4531  $this->db->rollback();
4532  return -1;
4533  }
4534 
4535  $this->db->commit();
4536  return 1;
4537  }
4538 
4539  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4547  public function clone_fournisseurs($fromId, $toId)
4548  {
4549  // phpcs:enable
4550  $this->db->begin();
4551 
4552  $now = dol_now();
4553 
4554  // les fournisseurs
4555  /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
4556  . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
4557  . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author"
4558  . " FROM ".$this->db->prefix()."product_fournisseur"
4559  . " WHERE fk_product = ".((int) $fromId);
4560 
4561  if ( ! $this->db->query($sql ) )
4562  {
4563  $this->db->rollback();
4564  return -1;
4565  }*/
4566 
4567  // les prix de fournisseurs.
4568  $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
4569  $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)";
4570  $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user";
4571  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4572  $sql .= " WHERE fk_product = ".((int) $fromId);
4573 
4574  dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
4575  $resql = $this->db->query($sql);
4576  if (!$resql) {
4577  $this->db->rollback();
4578  return -1;
4579  } else {
4580  $this->db->commit();
4581  return 1;
4582  }
4583  }
4584 
4585  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4598  public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
4599  {
4600  // phpcs:enable
4601  global $conf, $langs;
4602 
4603  $tmpproduct = null;
4604  //var_dump($prod);
4605  foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
4606  if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
4607  $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
4608  $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
4609  $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
4610  $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
4611  $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
4612 
4613  if ($multiply < 1) {
4614  $multiply = 1;
4615  }
4616 
4617  //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
4618  if (is_null($tmpproduct)) {
4619  $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
4620  }
4621  $tmpproduct->fetch($id); // Load product to get ->ref
4622 
4623  if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
4624  $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
4625  }
4626 
4627  $this->res[] = array(
4628  'id'=>$id, // Id product
4629  'id_parent'=>$id_parent,
4630  'ref'=>$tmpproduct->ref, // Ref product
4631  'nb'=>$nb, // Nb of units that compose parent product
4632  'nb_total'=>$nb * $multiply, // Nb of units for all nb of product
4633  'stock'=>$tmpproduct->stock_reel, // Stock
4634  'stock_alert'=>$tmpproduct->seuil_stock_alerte, // Stock alert
4635  'label'=>$label,
4636  'fullpath'=>$compl_path.$label, // Label
4637  'type'=>$type, // Nb of units that compose parent product
4638  'desiredstock'=>$tmpproduct->desiredstock,
4639  'level'=>$level,
4640  'incdec'=>$incdec,
4641  'entity'=>$tmpproduct->entity
4642  );
4643 
4644  // Recursive call if there is childs to child
4645  if (isset($desc_pere['childs']) && is_array($desc_pere['childs'])) {
4646  //print 'YYY We go down for '.$desc_pere[3]." -> \n";
4647  $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load);
4648  }
4649  }
4650  }
4651  }
4652 
4653  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4662  public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
4663  {
4664  // phpcs:enable
4665  $this->res = array();
4666  if (isset($this->sousprods) && is_array($this->sousprods)) {
4667  foreach ($this->sousprods as $prod_name => $desc_product) {
4668  if (is_array($desc_product)) {
4669  $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load);
4670  }
4671  }
4672  }
4673  //var_dump($this->res);
4674  return $this->res;
4675  }
4676 
4684  public function hasFatherOrChild($mode = 0)
4685  {
4686  $nb = 0;
4687 
4688  $sql = "SELECT COUNT(pa.rowid) as nb";
4689  $sql .= " FROM ".$this->db->prefix()."product_association as pa";
4690  if ($mode == 0) {
4691  $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
4692  } elseif ($mode == -1) {
4693  $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)
4694  } elseif ($mode == 1) {
4695  $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)
4696  }
4697 
4698  $resql = $this->db->query($sql);
4699  if ($resql) {
4700  $obj = $this->db->fetch_object($resql);
4701  if ($obj) {
4702  $nb = $obj->nb;
4703  }
4704  } else {
4705  return -1;
4706  }
4707 
4708  return $nb;
4709  }
4710 
4716  public function hasVariants()
4717  {
4718  $nb = 0;
4719  $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
4720  $sql .= " AND entity IN (".getEntity('product').")";
4721 
4722  $resql = $this->db->query($sql);
4723  if ($resql) {
4724  $obj = $this->db->fetch_object($resql);
4725  if ($obj) {
4726  $nb = $obj->nb;
4727  }
4728  }
4729 
4730  return $nb;
4731  }
4732 
4733 
4739  public function isVariant()
4740  {
4741  global $conf;
4742  if (!empty($conf->variants->enabled)) {
4743  $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
4744 
4745  $query = $this->db->query($sql);
4746 
4747  if ($query) {
4748  if (!$this->db->num_rows($query)) {
4749  return false;
4750  }
4751  return true;
4752  } else {
4753  dol_print_error($this->db);
4754  return -1;
4755  }
4756  } else {
4757  return false;
4758  }
4759  }
4760 
4767  public function getFather()
4768  {
4769  $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";
4770  $sql .= ", p.tosell as status, p.tobuy as status_buy";
4771  $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
4772  $sql .= " ".$this->db->prefix()."product as p";
4773  $sql .= " WHERE p.rowid = pa.fk_product_pere";
4774  $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
4775 
4776  $res = $this->db->query($sql);
4777  if ($res) {
4778  $prods = array();
4779  while ($record = $this->db->fetch_array($res)) {
4780  // $record['id'] = $record['rowid'] = id of father
4781  $prods[$record['id']]['id'] = $record['rowid'];
4782  $prods[$record['id']]['ref'] = $record['ref'];
4783  $prods[$record['id']]['label'] = $record['label'];
4784  $prods[$record['id']]['qty'] = $record['qty'];
4785  $prods[$record['id']]['incdec'] = $record['incdec'];
4786  $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
4787  $prods[$record['id']]['entity'] = $record['entity'];
4788  $prods[$record['id']]['status'] = $record['status'];
4789  $prods[$record['id']]['status_buy'] = $record['status_buy'];
4790  }
4791  return $prods;
4792  } else {
4793  dol_print_error($this->db);
4794  return -1;
4795  }
4796  }
4797 
4798 
4808  public function getChildsArbo($id, $firstlevelonly = 0, $level = 1, $parents = array())
4809  {
4810  global $alreadyfound;
4811 
4812  if (empty($id)) {
4813  return array();
4814  }
4815 
4816  $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
4817  $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
4818  $sql .= " pa.rowid as fk_association, pa.rang";
4819  $sql .= " FROM ".$this->db->prefix()."product as p,";
4820  $sql .= " ".$this->db->prefix()."product_association as pa";
4821  $sql .= " WHERE p.rowid = pa.fk_product_fils";
4822  $sql .= " AND pa.fk_product_pere = ".((int) $id);
4823  $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
4824  $sql.= " ORDER BY pa.rang";
4825 
4826  dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level. ' parents='.(is_array($parents)?implode(',', $parents):$parents), LOG_DEBUG);
4827 
4828  if ($level == 1) {
4829  $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
4830  }
4831  // Protection against infinite loop
4832  if ($level > 30) {
4833  return array();
4834  }
4835 
4836  $res = $this->db->query($sql);
4837  if ($res) {
4838  $prods = array();
4839  while ($rec = $this->db->fetch_array($res)) {
4840  if (!empty($alreadyfound[$rec['rowid']])) {
4841  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);
4842  if (in_array($rec['id'], $parents)) {
4843  continue; // We discard this child if it is already found at a higher level in tree in the same branch.
4844  }
4845  }
4846  $alreadyfound[$rec['rowid']] = 1;
4847  $prods[$rec['rowid']] = array(
4848  0=>$rec['rowid'],
4849  1=>$rec['qty'],
4850  2=>$rec['fk_product_type'],
4851  3=>$this->db->escape($rec['label']),
4852  4=>$rec['incdec'],
4853  5=>$rec['ref'],
4854  6=>$rec['fk_association'],
4855  7=>$rec['rang']
4856  );
4857  //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
4858  //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
4859  if (empty($firstlevelonly)) {
4860  $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1, array_push($parents, $rec['rowid']));
4861  foreach ($listofchilds as $keyChild => $valueChild) {
4862  $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
4863  }
4864  }
4865  }
4866 
4867  return $prods;
4868  } else {
4869  dol_print_error($this->db);
4870  return -1;
4871  }
4872  }
4873 
4874  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4881  public function get_sousproduits_arbo()
4882  {
4883  // phpcs:enable
4884  $parent = array();
4885 
4886  foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
4887  $parent[$this->label][$keyChild] = $valueChild;
4888  }
4889  foreach ($parent as $key => $value) { // key=label, value is array of childs
4890  $this->sousprods[$key] = $value;
4891  }
4892  }
4893 
4904  public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0)
4905  {
4906  global $conf, $langs, $hookmanager;
4907  include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
4908 
4909  $result = ''; $label = '';
4910 
4911  $newref = $this->ref;
4912  if ($maxlength) {
4913  $newref = dol_trunc($newref, $maxlength, 'middle');
4914  }
4915 
4916  if (!empty($this->entity)) {
4917  $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
4918  if ($this->nbphoto > 0) {
4919  $label .= '<div class="photointooltip floatright">';
4920  $label .= $tmpphoto;
4921  $label .= '</div>';
4922  //$label .= '<div style="clear: both;"></div>';
4923  }
4924  }
4925 
4926  if ($this->type == Product::TYPE_PRODUCT) {
4927  $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
4928  } elseif ($this->type == Product::TYPE_SERVICE) {
4929  $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
4930  }
4931  if (isset($this->status) && isset($this->status_buy)) {
4932  $label .= ' '.$this->getLibStatut(5, 0);
4933  $label .= ' '.$this->getLibStatut(5, 1);
4934  }
4935 
4936  if (!empty($this->ref)) {
4937  $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
4938  }
4939  if (!empty($this->label)) {
4940  $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
4941  }
4942  if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
4943  if (!empty($conf->productbatch->enabled)) {
4944  $langs->load("productbatch");
4945  $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
4946  }
4947  }
4948  if (!empty($conf->barcode->enabled)) {
4949  $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
4950  }
4951 
4952  if ($this->type == Product::TYPE_PRODUCT) {
4953  if ($this->weight) {
4954  $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
4955  }
4956  $labelsize = "";
4957  if ($this->length) {
4958  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
4959  }
4960  if ($this->width) {
4961  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
4962  }
4963  if ($this->height) {
4964  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
4965  }
4966  if ($labelsize) {
4967  $label .= "<br>".$labelsize;
4968  }
4969 
4970  $labelsurfacevolume = "";
4971  if ($this->surface) {
4972  $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
4973  }
4974  if ($this->volume) {
4975  $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
4976  }
4977  if ($labelsurfacevolume) {
4978  $label .= "<br>".$labelsurfacevolume;
4979  }
4980  }
4981  if (!empty($this->pmp) && $this->pmp) {
4982  $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
4983  }
4984 
4985  if (!empty($conf->accounting->enabled)) {
4986  if ($this->status && isset($this->accountancy_code_sell)) {
4987  include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
4988  $label .= '<br>';
4989  $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
4990  $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
4991  $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
4992  }
4993  if ($this->status_buy && isset($this->accountancy_code_buy)) {
4994  include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
4995  if (empty($this->status)) {
4996  $label .= '<br>';
4997  }
4998  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
4999  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
5000  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
5001  }
5002  }
5003 
5004  $linkclose = '';
5005  if (empty($notooltip)) {
5006  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
5007  $label = $langs->trans("ShowProduct");
5008  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
5009  }
5010 
5011  $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
5012  $linkclose .= ' class="nowraponall classfortooltip"';
5013  } else {
5014  $linkclose = ' class="nowraponall"';
5015  }
5016 
5017  if ($option == 'supplier' || $option == 'category') {
5018  $url = DOL_URL_ROOT.'/product/fournisseurs.php?id='.$this->id;
5019  } elseif ($option == 'stock') {
5020  $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
5021  } elseif ($option == 'composition') {
5022  $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
5023  } else {
5024  $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
5025  }
5026 
5027  if ($option !== 'nolink') {
5028  // Add param to save lastsearch_values or not
5029  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
5030  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
5031  $add_save_lastsearch_values = 1;
5032  }
5033  if ($add_save_lastsearch_values) {
5034  $url .= '&save_lastsearch_values=1';
5035  }
5036  }
5037 
5038  $linkstart = '<a href="'.$url.'"';
5039  $linkstart .= $linkclose.'>';
5040  $linkend = '</a>';
5041 
5042  $result .= $linkstart;
5043  if ($withpicto) {
5044  if ($this->type == Product::TYPE_PRODUCT) {
5045  $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
5046  }
5047  if ($this->type == Product::TYPE_SERVICE) {
5048  $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
5049  }
5050  }
5051  $result .= $newref;
5052  $result .= $linkend;
5053 
5054  global $action;
5055  $hookmanager->initHooks(array('productdao'));
5056  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
5057  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5058  if ($reshook > 0) {
5059  $result = $hookmanager->resPrint;
5060  } else {
5061  $result .= $hookmanager->resPrint;
5062  }
5063 
5064  return $result;
5065  }
5066 
5067 
5078  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
5079  {
5080  global $conf, $user, $langs;
5081 
5082  $langs->load("products");
5083  $outputlangs->load("products");
5084 
5085  // Positionne le modele sur le nom du modele a utiliser
5086  if (!dol_strlen($modele)) {
5087  if (!empty($conf->global->PRODUCT_ADDON_PDF)) {
5088  $modele = $conf->global->PRODUCT_ADDON_PDF;
5089  } else {
5090  $modele = 'strato';
5091  }
5092  }
5093 
5094  $modelpath = "core/modules/product/doc/";
5095 
5096  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
5097  }
5098 
5106  public function getLibStatut($mode = 0, $type = 0)
5107  {
5108  switch ($type) {
5109  case 0:
5110  return $this->LibStatut($this->status, $mode, $type);
5111  case 1:
5112  return $this->LibStatut($this->status_buy, $mode, $type);
5113  case 2:
5114  return $this->LibStatut($this->status_batch, $mode, $type);
5115  default:
5116  //Simulate previous behavior but should return an error string
5117  return $this->LibStatut($this->status_buy, $mode, $type);
5118  }
5119  }
5120 
5121  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5130  public function LibStatut($status, $mode = 0, $type = 0)
5131  {
5132  // phpcs:enable
5133  global $conf, $langs;
5134 
5135  $labelStatus = $labelStatusShort = '';
5136 
5137  $langs->load('products');
5138  if (!empty($conf->productbatch->enabled)) {
5139  $langs->load("productbatch");
5140  }
5141 
5142  if ($type == 2) {
5143  switch ($mode) {
5144  case 0:
5145  $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
5146  return dolGetStatus($label);
5147  case 1:
5148  $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
5149  return dolGetStatus($label);
5150  case 2:
5151  return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
5152  case 3:
5153  return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
5154  case 4:
5155  return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
5156  case 5:
5157  return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
5158  default:
5159  return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
5160  }
5161  }
5162 
5163  $statuttrans = empty($status) ? 'status5' : 'status4';
5164 
5165  if ($status == 0) {
5166  // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
5167  if ($type == 0) {
5168  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
5169  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
5170  } elseif ($type == 1) {
5171  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
5172  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
5173  } elseif ($type == 2) {
5174  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
5175  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
5176  }
5177  } elseif ($status == 1) {
5178  // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
5179  if ($type == 0) {
5180  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
5181  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
5182  } elseif ($type == 1) {
5183  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
5184  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
5185  } elseif ($type == 2) {
5186  $labelStatus = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial'));
5187  $labelStatusShort = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort'));
5188  }
5189  } elseif ( $type == 2 && $status == 2 ) {
5190  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
5191  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
5192  }
5193 
5194  if ($mode > 6) {
5195  return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
5196  } else {
5197  return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
5198  }
5199  }
5200 
5201 
5207  public function getLibFinished()
5208  {
5209  global $langs;
5210  $langs->load('products');
5211 
5212  if (isset($this->finished) && $this->finished >= 0) {
5213  $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
5214  $resql = $this->db->query($sql);
5215  if ($resql && $this->db->num_rows($resql) > 0) {
5216  $res = $this->db->fetch_array($resql);
5217  $label = $langs->trans($res['label']);
5218  $this->db->free($resql);
5219  return $label;
5220  } else {
5221  $this->error = $this->db->error().' sql='.$sql;
5222  dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
5223  return -1;
5224  }
5225  }
5226 
5227  return '';
5228  }
5229 
5230 
5231  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5248  public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
5249  {
5250  // phpcs:enable
5251  if ($id_entrepot) {
5252  $this->db->begin();
5253 
5254  include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
5255 
5256  if ($nbpiece < 0) {
5257  if (!$movement) {
5258  $movement = 1;
5259  }
5260  $nbpiece = abs($nbpiece);
5261  }
5262 
5263  $op[0] = "+".trim($nbpiece);
5264  $op[1] = "-".trim($nbpiece);
5265 
5266  $movementstock = new MouvementStock($this->db);
5267  $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->origin_id
5268  $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
5269 
5270  if ($result >= 0) {
5271  if ($extrafields) {
5272  $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
5273  $movementstock->array_options = $array_options;
5274  $movementstock->insertExtraFields();
5275  }
5276  $this->db->commit();
5277  return 1;
5278  } else {
5279  $this->error = $movementstock->error;
5280  $this->errors = $movementstock->errors;
5281 
5282  $this->db->rollback();
5283  return -1;
5284  }
5285  }
5286  }
5287 
5288  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5308  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)
5309  {
5310  // phpcs:enable
5311  if ($id_entrepot) {
5312  $this->db->begin();
5313 
5314  include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
5315 
5316  if ($nbpiece < 0) {
5317  if (!$movement) {
5318  $movement = 1;
5319  }
5320  $nbpiece = abs($nbpiece);
5321  }
5322 
5323  $op[0] = "+".trim($nbpiece);
5324  $op[1] = "-".trim($nbpiece);
5325 
5326  $movementstock = new MouvementStock($this->db);
5327  $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->fk_origin
5328  $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct);
5329 
5330  if ($result >= 0) {
5331  if ($extrafields) {
5332  $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
5333  $movementstock->array_options = $array_options;
5334  $movementstock->insertExtraFields();
5335  }
5336  $this->db->commit();
5337  return 1;
5338  } else {
5339  $this->error = $movementstock->error;
5340  $this->errors = $movementstock->errors;
5341 
5342  $this->db->rollback();
5343  return -1;
5344  }
5345  }
5346  }
5347 
5348  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5360  public function load_stock($option = '', $includedraftpoforvirtual = null)
5361  {
5362  // phpcs:enable
5363  global $conf;
5364 
5365  $this->stock_reel = 0;
5366  $this->stock_warehouse = array();
5367  $this->stock_theorique = 0;
5368 
5369  // Set filter on warehouse status
5370  $warehouseStatus = array();
5371  if (preg_match('/warehouseclosed/', $option)) {
5373  }
5374  if (preg_match('/warehouseopen/', $option)) {
5376  }
5377  if (preg_match('/warehouseinternal/', $option)) {
5378  if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
5380  } else {
5382  }
5383  }
5384 
5385  $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
5386  $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
5387  $sql .= ", ".$this->db->prefix()."entrepot as w";
5388  $sql .= " WHERE w.entity IN (".getEntity('stock').")";
5389  $sql .= " AND w.rowid = ps.fk_entrepot";
5390  $sql .= " AND ps.fk_product = ".((int) $this->id);
5391  if (count($warehouseStatus)) {
5392  $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
5393  }
5394 
5395  $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;
5396 
5397  dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
5398  $result = $this->db->query($sql);
5399  if ($result) {
5400  $num = $this->db->num_rows($result);
5401  $i = 0;
5402  if ($num > 0) {
5403  while ($i < $num) {
5404  $row = $this->db->fetch_object($result);
5405  $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
5406  $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
5407  $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
5408  if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
5409  $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
5410  }
5411  $this->stock_reel += $row->reel;
5412  $i++;
5413  }
5414  }
5415  $this->db->free($result);
5416 
5417  if (!preg_match('/novirtual/', $option)) {
5418  $this->load_virtual_stock($includedraftpoforvirtual); // This also load all arrays stats_xxx...
5419  }
5420 
5421  return 1;
5422  } else {
5423  $this->error = $this->db->lasterror();
5424  return -1;
5425  }
5426  }
5427 
5428 
5429  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5438  public function load_virtual_stock($includedraftpoforvirtual = null)
5439  {
5440  // phpcs:enable
5441  global $conf, $hookmanager, $action;
5442 
5443  $stock_commande_client = 0;
5444  $stock_commande_fournisseur = 0;
5445  $stock_sending_client = 0;
5446  $stock_reception_fournisseur = 0;
5447  $stock_inproduction = 0;
5448 
5449  //dol_syslog("load_virtual_stock");
5450 
5451  if (!empty($conf->commande->enabled)) {
5452  $result = $this->load_stats_commande(0, '1,2', 1);
5453  if ($result < 0) {
5454  dol_print_error($this->db, $this->error);
5455  }
5456  $stock_commande_client = $this->stats_commande['qty'];
5457  }
5458  if (!empty($conf->expedition->enabled)) {
5459  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
5460  $filterShipmentStatus = '';
5461  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
5462  $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
5463  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
5464  $filterShipmentStatus = Expedition::STATUS_CLOSED;
5465  }
5466  $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
5467  if ($result < 0) {
5468  dol_print_error($this->db, $this->error);
5469  }
5470  $stock_sending_client = $this->stats_expedition['qty'];
5471  }
5472  if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) {
5473  $filterStatus = empty($conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK) ? '3,4' : $conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK;
5474  if (isset($includedraftpoforvirtual)) {
5475  $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
5476  }
5477  $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1);
5478  if ($result < 0) {
5479  dol_print_error($this->db, $this->error);
5480  }
5481  $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
5482  }
5483  if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) {
5484  // Case module reception is not used
5485  $filterStatus = '4';
5486  if (isset($includedraftpoforvirtual)) {
5487  $filterStatus = '0,'.$filterStatus;
5488  }
5489  $result = $this->load_stats_reception(0, $filterStatus, 1);
5490  if ($result < 0) {
5491  dol_print_error($this->db, $this->error);
5492  }
5493  $stock_reception_fournisseur = $this->stats_reception['qty'];
5494  }
5495  if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && !empty($conf->reception->enabled)) {
5496  // Case module reception is used
5497  $filterStatus = '4';
5498  if (isset($includedraftpoforvirtual)) {
5499  $filterStatus = '0,'.$filterStatus;
5500  }
5501  $result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used.
5502  if ($result < 0) {
5503  dol_print_error($this->db, $this->error);
5504  }
5505  $stock_reception_fournisseur = $this->stats_reception['qty'];
5506  }
5507  if (!empty($conf->mrp->enabled)) {
5508  $result = $this->load_stats_inproduction(0, '1,2', 1);
5509  if ($result < 0) {
5510  dol_print_error($this->db, $this->error);
5511  }
5512  $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
5513  }
5514 
5515  $this->stock_theorique = $this->stock_reel + $stock_inproduction;
5516 
5517  // Stock decrease mode
5518  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
5519  $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
5520  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) {
5521  $this->stock_theorique += 0;
5522  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
5523  $this->stock_theorique -= $stock_commande_client;
5524  }
5525  // Stock Increase mode
5526  if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
5527  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5528  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
5529  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5530  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
5531  $this->stock_theorique -= $stock_reception_fournisseur;
5532  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
5533  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5534  }
5535 
5536  if (!is_object($hookmanager)) {
5537  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
5538  $hookmanager = new HookManager($this->db);
5539  }
5540  $hookmanager->initHooks(array('productdao'));
5541  $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
5542  // Note that $action and $object may have been modified by some hooks
5543  $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
5544  if ($reshook > 0) {
5545  $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
5546  }
5547 
5548  return 1;
5549  }
5550 
5551 
5559  public function loadBatchInfo($batch)
5560  {
5561  $result = array();
5562 
5563  $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";
5564  $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
5565  $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby";
5566  dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
5567  $resql = $this->db->query($sql);
5568  if ($resql) {
5569  $num = $this->db->num_rows($resql);
5570  $i = 0;
5571  while ($i < $num) {
5572  $obj = $this->db->fetch_object($resql);
5573  $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
5574  $i++;
5575  }
5576  return $result;
5577  } else {
5578  dol_print_error($this->db);
5579  $this->db->rollback();
5580  return array();
5581  }
5582  }
5583 
5584  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5592  public function add_photo($sdir, $file)
5593  {
5594  // phpcs:enable
5595  global $conf;
5596 
5597  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5598 
5599  $result = 0;
5600 
5601  $dir = $sdir;
5602  if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
5603  $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
5604  } else {
5605  $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
5606  }
5607 
5608  dol_mkdir($dir);
5609 
5610  $dir_osencoded = $dir;
5611 
5612  if (is_dir($dir_osencoded)) {
5613  $originImage = $dir.'/'.$file['name'];
5614 
5615  // Cree fichier en taille origine
5616  $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
5617 
5618  if (file_exists(dol_osencode($originImage))) {
5619  // Create thumbs
5620  $this->addThumbs($originImage);
5621  }
5622  }
5623 
5624  if (is_numeric($result) && $result > 0) {
5625  return 1;
5626  } else {
5627  return -1;
5628  }
5629  }
5630 
5631  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5638  public function is_photo_available($sdir)
5639  {
5640  // phpcs:enable
5641  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5642  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5643 
5644  global $conf;
5645 
5646  $dir = $sdir;
5647  if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
5648  $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
5649  } else {
5650  $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
5651  }
5652 
5653  $nbphoto = 0;
5654 
5655  $dir_osencoded = dol_osencode($dir);
5656  if (file_exists($dir_osencoded)) {
5657  $handle = opendir($dir_osencoded);
5658  if (is_resource($handle)) {
5659  while (($file = readdir($handle)) !== false) {
5660  if (!utf8_check($file)) {
5661  $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
5662  }
5663  if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
5664  return true;
5665  }
5666  }
5667  }
5668  }
5669  return false;
5670  }
5671 
5672  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5680  public function liste_photos($dir, $nbmax = 0)
5681  {
5682  // phpcs:enable
5683  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5684  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5685 
5686  $nbphoto = 0;
5687  $tabobj = array();
5688 
5689  $dir_osencoded = dol_osencode($dir);
5690  $handle = @opendir($dir_osencoded);
5691  if (is_resource($handle)) {
5692  while (($file = readdir($handle)) !== false) {
5693  if (!utf8_check($file)) {
5694  $file = utf8_encode($file); // readdir returns ISO
5695  }
5696  if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
5697  $nbphoto++;
5698 
5699  // We forge name of thumb.
5700  $photo = $file;
5701  $photo_vignette = '';
5702  $regs = array();
5703  if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
5704  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
5705  }
5706 
5707  $dirthumb = $dir.'thumbs/';
5708 
5709  // Objet
5710  $obj = array();
5711  $obj['photo'] = $photo;
5712  if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
5713  $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
5714  } else {
5715  $obj['photo_vignette'] = "";
5716  }
5717 
5718  $tabobj[$nbphoto - 1] = $obj;
5719 
5720  // Do we have to continue with next photo ?
5721  if ($nbmax && $nbphoto >= $nbmax) {
5722  break;
5723  }
5724  }
5725  }
5726 
5727  closedir($handle);
5728  }
5729 
5730  return $tabobj;
5731  }
5732 
5733  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5740  public function delete_photo($file)
5741  {
5742  // phpcs:enable
5743  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5744  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5745 
5746  $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
5747  $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
5748  $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
5749 
5750  // On efface l'image d'origine
5751  dol_delete_file($file, 0, 0, 0, $this); // For triggers
5752 
5753  // Si elle existe, on efface la vignette
5754  if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
5755  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
5756  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
5757  dol_delete_file($dirthumb.$photo_vignette);
5758  }
5759 
5760  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
5761  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
5762  dol_delete_file($dirthumb.$photo_vignette);
5763  }
5764  }
5765  }
5766 
5767  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5774  public function get_image_size($file)
5775  {
5776  // phpcs:enable
5777  $file_osencoded = dol_osencode($file);
5778  $infoImg = getimagesize($file_osencoded); // Get information on image
5779  $this->imgWidth = $infoImg[0]; // Largeur de l'image
5780  $this->imgHeight = $infoImg[1]; // Hauteur de l'image
5781  }
5782 
5783  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5789  public function load_state_board()
5790  {
5791  // phpcs:enable
5792  global $hookmanager;
5793 
5794  $this->nb = array();
5795 
5796  $sql = "SELECT count(p.rowid) as nb, fk_product_type";
5797  $sql .= " FROM ".$this->db->prefix()."product as p";
5798  $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
5799  // Add where from hooks
5800  if (is_object($hookmanager)) {
5801  $parameters = array();
5802  $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5803  $sql .= $hookmanager->resPrint;
5804  }
5805  $sql .= ' GROUP BY fk_product_type';
5806 
5807  $resql = $this->db->query($sql);
5808  if ($resql) {
5809  while ($obj = $this->db->fetch_object($resql)) {
5810  if ($obj->fk_product_type == 1) {
5811  $this->nb["services"] = $obj->nb;
5812  } else {
5813  $this->nb["products"] = $obj->nb;
5814  }
5815  }
5816  $this->db->free($resql);
5817  return 1;
5818  } else {
5819  dol_print_error($this->db);
5820  $this->error = $this->db->error();
5821  return -1;
5822  }
5823  }
5824 
5830  public function isProduct()
5831  {
5832  return ($this->type == Product::TYPE_PRODUCT ? true : false);
5833  }
5834 
5840  public function isService()
5841  {
5842  return ($this->type == Product::TYPE_SERVICE ? true : false);
5843  }
5844 
5845 
5851  public function isMandatoryPeriod()
5852  {
5853  return ($this->mandatory_period == 1 ? true : false);
5854  }
5855  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5864  public function get_barcode($object, $type = '')
5865  {
5866  // phpcs:enable
5867  global $conf;
5868 
5869  $result = '';
5870  if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
5871  $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
5872  foreach ($dirsociete as $dirroot) {
5873  $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
5874  if ($res) {
5875  break;
5876  }
5877  }
5878  $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
5879  $mod = new $var;
5880 
5881  $result = $mod->getNextValue($object, $type);
5882 
5883  dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
5884  }
5885  return $result;
5886  }
5887 
5895  public function initAsSpecimen()
5896  {
5897  global $user, $langs, $conf, $mysoc;
5898 
5899  $now = dol_now();
5900 
5901  // Initialize parameters
5902  $this->specimen = 1;
5903  $this->id = 0;
5904  $this->ref = 'PRODUCT_SPEC';
5905  $this->label = 'PRODUCT SPECIMEN';
5906  $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
5907  $this->specimen = 1;
5908  $this->country_id = 1;
5909  $this->tosell = 1;
5910  $this->tobuy = 1;
5911  $this->tobatch = 0;
5912  $this->note = 'This is a comment (private)';
5913  $this->date_creation = $now;
5914  $this->date_modification = $now;
5915 
5916  $this->weight = 4;
5917  $this->weight_units = 3;
5918 
5919  $this->length = 5;
5920  $this->length_units = 1;
5921  $this->width = 6;
5922  $this->width_units = 0;
5923  $this->height = null;
5924  $this->height_units = null;
5925 
5926  $this->surface = 30;
5927  $this->surface_units = 0;
5928  $this->volume = 300;
5929  $this->volume_units = 0;
5930 
5931  $this->barcode = -1; // Create barcode automatically
5932  }
5933 
5940  public function getLabelOfUnit($type = 'long')
5941  {
5942  global $langs;
5943 
5944  if (!$this->fk_unit) {
5945  return '';
5946  }
5947 
5948  $langs->load('products');
5949 
5950  $label_type = 'label';
5951  if ($type == 'short') {
5952  $label_type = 'short_label';
5953  }
5954 
5955  $sql = "SELECT ".$label_type.", code from ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
5956 
5957  $resql = $this->db->query($sql);
5958  if ($resql && $this->db->num_rows($resql) > 0) {
5959  $res = $this->db->fetch_array($resql);
5960  $label = ($label_type == 'short_label' ? $res[$label_type] : 'unit'.$res['code']);
5961  $this->db->free($resql);
5962  return $label;
5963  } else {
5964  $this->error = $this->db->error();
5965  dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
5966  return -1;
5967  }
5968  }
5969 
5975  public function hasbatch()
5976  {
5977  return ($this->status_batch > 0 ? true : false);
5978  }
5979 
5980 
5981  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5987  public function min_recommended_price()
5988  {
5989  // phpcs:enable
5990  global $conf;
5991 
5992  $maxpricesupplier = 0;
5993 
5994  if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
5995  include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
5996  $product_fourn = new ProductFournisseur($this->db);
5997  $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
5998 
5999  if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
6000  foreach ($product_fourn_list as $productfourn) {
6001  if ($productfourn->fourn_unitprice > $maxpricesupplier) {
6002  $maxpricesupplier = $productfourn->fourn_unitprice;
6003  }
6004  }
6005 
6006  $maxpricesupplier *= $conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE;
6007  }
6008  }
6009 
6010  return $maxpricesupplier;
6011  }
6012 
6013 
6024  public function setCategories($categories)
6025  {
6026  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6027  return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
6028  }
6029 
6038  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
6039  {
6040  $tables = array(
6041  'product_customer_price',
6042  'product_customer_price_log'
6043  );
6044 
6045  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
6046  }
6047 
6059  public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
6060  {
6061  global $conf, $db;
6062 
6063  $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
6064  $query = $this->db->query($sql);
6065 
6066  $rules = array();
6067 
6068  while ($result = $this->db->fetch_object($query)) {
6069  $rules[$result->level] = $result;
6070  }
6071 
6072  //Because prices can be based on other level's prices, we temporarily store them
6073  $prices = array(
6074  1 => $baseprice
6075  );
6076 
6077  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
6078  $price = $baseprice;
6079  $price_min = $baseprice;
6080 
6081  //We have to make sure it does exist and it is > 0
6082  //First price level only allows changing min_price
6083  if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
6084  $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
6085  }
6086 
6087  $prices[$i] = $price;
6088 
6089  //We have to make sure it does exist and it is > 0
6090  if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
6091  $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
6092  }
6093 
6094  //Little check to make sure the price is modified before triggering generation
6095  $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
6096  $check_type = ($baseprice == $this->multiprices_base_type[$i]);
6097 
6098  if ($check_amount && $check_type) {
6099  continue;
6100  }
6101 
6102  if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, true) < 0) {
6103  return -1;
6104  }
6105  }
6106 
6107  return 1;
6108  }
6109 
6115  public function getRights()
6116  {
6117  global $user;
6118 
6119  if ($this->isProduct()) {
6120  return $user->rights->produit;
6121  } else {
6122  return $user->rights->service;
6123  }
6124  }
6125 
6132  public function info($id)
6133  {
6134  $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,";
6135  $sql .= " p.fk_user_author, p.fk_user_modif";
6136  $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
6137  $sql .= " WHERE p.rowid = ".((int) $id);
6138 
6139  $result = $this->db->query($sql);
6140  if ($result) {
6141  if ($this->db->num_rows($result)) {
6142  $obj = $this->db->fetch_object($result);
6143 
6144  $this->id = $obj->rowid;
6145 
6146  if ($obj->fk_user_author) {
6147  $cuser = new User($this->db);
6148  $cuser->fetch($obj->fk_user_author);
6149  $this->user_creation = $cuser;
6150  }
6151 
6152  if ($obj->fk_user_modif) {
6153  $muser = new User($this->db);
6154  $muser->fetch($obj->fk_user_modif);
6155  $this->user_modification = $muser;
6156  }
6157 
6158  $this->ref = $obj->ref;
6159  $this->date_creation = $this->db->jdate($obj->date_creation);
6160  $this->date_modification = $this->db->jdate($obj->date_modification);
6161  }
6162 
6163  $this->db->free($result);
6164  } else {
6165  dol_print_error($this->db);
6166  }
6167  }
6168 }
6169 
6170 
6171 
6177 {
6178  public $picto = 'service';
6179 }
Productbatch\findAll
static findAll($dbs, $fk_product_stock, $with_qty=0, $fk_product=0)
Return all batch detail records for a given product and warehouse.
Definition: productbatch.class.php:437
Product\get_nb_ordersupplier
get_nb_ordersupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
Definition: product.class.php:3960
Product\$localtax1_tx
$localtax1_tx
Other local taxes.
Definition: product.class.php:191
Product\setCategories
setCategories($categories)
Sets object to supplied categories.
Definition: product.class.php:6024
Product\getLibFinished
getLibFinished()
Retour label of nature of product.
Definition: product.class.php:5207
Product\isProduct
isProduct()
Return if object is a product.
Definition: product.class.php:5830
db
$conf db
API class for accounts.
Definition: inc.php:41
Productbatch
Manage record for batch number management.
Definition: productbatch.class.php:31
Product\load_stats_facture_fournisseur
load_stats_facture_fournisseur($socid=0)
Charge tableau des stats facture pour le produit/service.
Definition: product.class.php:3573
Product\$ref_fourn
$ref_fourn
Definition: product.class.php:401
dol_trunc
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.
Definition: functions.lib.php:3805
Product\update
update($id, $user, $notrigger=false, $action='update', $updatetype=false)
Update a record into database.
Definition: product.class.php:948
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
description
print *****$script_file(".$version.") pid cd cd cd description as description
Definition: email_expire_services_to_customers.php:83
Product\load_stats_bom
load_stats_bom($socid=0)
Charge tableau des stats OF pour le produit/service.
Definition: product.class.php:2752
Product\get_nb_order
get_nb_order($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
Definition: product.class.php:3909
dol_delete_dir_recursive
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:1383
Product\clone_associations
clone_associations($fromId, $toId)
Clone links between products.
Definition: product.class.php:4520
Product\$desiredstock
$desiredstock
Ask for replenishment when $desiredstock < $stock_reel.
Definition: product.class.php:234
ProductCombination
Class ProductCombination Used to represent a product combination.
Definition: ProductCombination.class.php:25
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
Product\add_sousproduit
add_sousproduit($id_pere, $id_fils, $qty, $incdec=1)
Link a product/service to a parent product/service.
Definition: product.class.php:4117
Productcustomerprice
File of class to manage predefined price products or services by customer.
Definition: productcustomerprice.class.php:29
dol_osencode
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
Definition: functions.lib.php:8499
ProductFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.product.class.php:41
Product\getSellPrice
getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp=0)
Return price of sell of a product for a seller/buyer/product.
Definition: product.class.php:1811
Product\isService
isService()
Return if object is a product.
Definition: product.class.php:5840
Product\hasbatch
hasbatch()
Return if object has a sell-by date or eat-by date.
Definition: product.class.php:5975
Product\fetch_prod_arbo
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...
Definition: product.class.php:4598
Product\load_stats_commande_fournisseur
load_stats_commande_fournisseur($socid=0, $filtrestatut='', $forVirtualStock=0)
Charge tableau des stats commande fournisseur pour le produit/service.
Definition: product.class.php:3057
Product\$multiprices
$multiprices
Arrays for multiprices.
Definition: product.class.php:164
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
Product\isMandatoryPeriod
isMandatoryPeriod()
Return if object have a constraint on mandatory_period.
Definition: product.class.php:5851
Product\verify
verify()
Check properties of product are ok (like name, barcode, ...).
Definition: product.class.php:860
Product\check_barcode
check_barcode($valuetotest, $typefortest)
Check barcode.
Definition: product.class.php:912
Product\get_barcode
get_barcode($object, $type='')
Get a barcode from the module to generate barcode values.
Definition: product.class.php:5864
Entrepot\STATUS_OPEN_INTERNAL
const STATUS_OPEN_INTERNAL
Warehouse open and operations for stock transfers/corrections allowed (not for customer shipping and ...
Definition: entrepot.class.php:161
measuring_units_squared
measuring_units_squared($unit)
Transform a given unit scale into the square of that unit, if known.
Definition: product.lib.php:679
Product\load_stats_contrat
load_stats_contrat($socid=0)
Charge tableau des stats contrat pour le produit/service.
Definition: product.class.php:3350
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
Product\$libelle
$libelle
Definition: product.class.php:99
Product\getFather
getFather()
Return all parent products for current product (first level only)
Definition: product.class.php:4767
Product\load_stock
load_stock($option='', $includedraftpoforvirtual=null)
Load information about stock of a product into ->stock_reel, ->stock_warehouse[] (including stock_war...
Definition: product.class.php:5360
CommonObject\addThumbs
addThumbs($file)
Build thumb.
Definition: commonobject.class.php:5701
Product\add_fournisseur
add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
Add a supplier price for the product.
Definition: product.class.php:4303
Product\clone_fournisseurs
clone_fournisseurs($fromId, $toId)
Recopie les fournisseurs et prix fournisseurs d'un produit/service sur un autre.
Definition: product.class.php:4547
ref
$object ref
Definition: info.php:77
Product\getArrayForPriceCompare
getArrayForPriceCompare($level=0)
used to check if price have really change to avoid log pollution
Definition: product.class.php:1706
Product\load_stats_commande
load_stats_commande($socid=0, $filtrestatut='', $forVirtualStock=0)
Charge tableau des stats commande client pour le produit/service.
Definition: product.class.php:2952
Product\get_nb_mos
get_nb_mos($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
Definition: product.class.php:4065
Product\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create a document onto disk according to template module.
Definition: product.class.php:5078
image_format_supported
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:80
Product\load_stats_reception
load_stats_reception($socid=0, $filtrestatut='', $forVirtualStock=0)
Charge tableau des stats réception fournisseur pour le produit/service.
Definition: product.class.php:3200
Product\$multilangs
$multilangs
Array for multilangs.
Definition: product.class.php:179
Product\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: product.class.php:5895
Product\__construct
__construct($db)
Constructor.
Definition: product.class.php:520
Product\$weight
$weight
Metric of products.
Definition: product.class.php:303
Product\log_price_delete
log_price_delete($user, $rowid)
Delete a price line.
Definition: product.class.php:1783
Product\is_photo_available
is_photo_available($sdir)
Return if at least one photo is available.
Definition: product.class.php:5638
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
Product\load_stats_facture
load_stats_facture($socid=0)
Charge tableau des stats facture pour le produit/service.
Definition: product.class.php:3424
Product\$product_id_already_linked
$product_id_already_linked
Product ID already linked to a reference supplier.
Definition: product.class.php:374
CommonObject\isObjectUsed
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
Definition: commonobject.class.php:4556
Expedition\STATUS_CLOSED
const STATUS_CLOSED
Closed status.
Definition: expedition.class.php:193
Product\getNomUrl
getNomUrl($withpicto=0, $option='', $maxlength=0, $save_lastsearch_value=-1, $notooltip=0)
Return clicable link of object (with eventually picto)
Definition: product.class.php:4904
Product\get_nb_vente
get_nb_vente($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units or customers invoices in which product is included.
Definition: product.class.php:3701
Product\LibStatut
LibStatut($status, $mode=0, $type=0)
Return label of a given status.
Definition: product.class.php:5130
Product\getLibStatut
getLibStatut($mode=0, $type=0)
Return label of status of object.
Definition: product.class.php:5106
dol_is_file
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:477
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
measuringUnitString
measuringUnitString($unit, $measuring_style='', $scale='', $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
Definition: product.lib.php:619
Product\correct_stock
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.
Definition: product.class.php:5248
Product\update_sousproduit
update_sousproduit($id_pere, $id_fils, $qty, $incdec=1)
Modify composed product.
Definition: product.class.php:4176
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
Product\delete_photo
delete_photo($file)
Delete a photo and its thumbs.
Definition: product.class.php:5740
Entrepot\STATUS_OPEN_ALL
const STATUS_OPEN_ALL
Warehouse open and operations for customer shipping, supplier dispatch, internal stock transfers/corr...
Definition: entrepot.class.php:156
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
utf8_check
utf8_check($str)
Check if a string is in UTF8.
Definition: functions.lib.php:8438
PriceParser
Class to parse product price expressions.
Definition: price_parser.class.php:33
dol_delete_file
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:1231
Product\setMultiLangs
setMultiLangs($user)
Update or add a translation for a product.
Definition: product.class.php:1468
dol_move_uploaded_file
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:1092
get_default_npr
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
Definition: functions.lib.php:6405
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:148
Product\loadBatchInfo
loadBatchInfo($batch)
Load existing information about a serial.
Definition: product.class.php:5559
get_localtax
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate,...
Definition: functions.lib.php:5837
dol_string_nospecial
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
Definition: functions.lib.php:1376
MouvementStock
Class to manage stock movements.
Definition: mouvementstock.class.php:31
Product\load_stats_facturerec
load_stats_facturerec($socid=0)
Charge tableau des stats facture recurrentes pour le produit/service.
Definition: product.class.php:3499
Product\list_suppliers
list_suppliers()
Return list of suppliers providing the product or service.
Definition: product.class.php:4398
Product\info
info($id)
Load information for tab info.
Definition: product.class.php:6132
Product\setPriceExpression
setPriceExpression($expression_id)
Sets the supplier price expression.
Definition: product.class.php:2261
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6156
Product\$imgWidth
$imgWidth
Size of image.
Definition: product.class.php:357
Product\liste_photos
liste_photos($dir, $nbmax=0)
Return an array with all photos of product found on disk.
Definition: product.class.php:5680
Product\create
create($user, $notrigger=0)
Insert product into database.
Definition: product.class.php:558
length_accountg
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
Definition: accounting.lib.php:94
ProductService
Class to manage products or services.
Definition: product.class.php:6176
Product\get_arbo_each_prod
get_arbo_each_prod($multiply=1, $ignore_stock_load=0)
Build the tree of subproducts into an array ->res and return it.
Definition: product.class.php:4662
Product\TYPE_STOCKKIT
const TYPE_STOCKKIT
Advanced feature: stock kit.
Definition: product.class.php:512
Product\delMultiLangs
delMultiLangs($langtodelete, $user)
Delete a language for this product.
Definition: product.class.php:1578
Product\min_recommended_price
min_recommended_price()
Return minimum product recommended price.
Definition: product.class.php:5987
Product\hasVariants
hasVariants()
Return if a product has variants or not.
Definition: product.class.php:4716
Product\get_nb_propal
get_nb_propal($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in proposals in which product is included.
Definition: product.class.php:3806
CommonObject\deleteEcmFiles
deleteEcmFiles($mode=0)
Delete related files of object in database.
Definition: commonobject.class.php:9966
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8347
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
Product\$stock_warehouse
$stock_warehouse
Contains detail of stock of product into each warehouse.
Definition: product.class.php:379
Product\generateMultiprices
generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
Generates prices for a product based on product multiprice generation rules.
Definition: product.class.php:6059
Product\TYPE_ASSEMBLYKIT
const TYPE_ASSEMBLYKIT
Advanced feature: assembly kit.
Definition: product.class.php:508
CommonObject\fetch_optionals
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...
Definition: commonobject.class.php:6007
Product\getLabelOfUnit
getLabelOfUnit($type='long')
Returns the text label from units dictionary.
Definition: product.class.php:5940
Product\load_stats_sending
load_stats_sending($socid=0, $filtrestatut='', $forVirtualStock=0, $filterShipmentStatus='')
Charge tableau des stats expedition client pour le produit/service.
Definition: product.class.php:3115
get_default_tva
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...
Definition: functions.lib.php:6304
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
Product\get_nb_propalsupplier
get_nb_propalsupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in proposals in which product is included.
Definition: product.class.php:3857
Product\load_stats_mo
load_stats_mo($socid=0)
Charge tableau des stats OF pour le produit/service.
Definition: product.class.php:2692
Product\load_stats_propale
load_stats_propale($socid=0)
Charge tableau des stats propale pour le produit/service.
Definition: product.class.php:2821
Product\setAccountancyCode
setAccountancyCode($type, $value)
Sets an accountancy code for a product.
Definition: product.class.php:1610
Product\replaceThirdparty
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: product.class.php:6038
Product\correct_stock_batch
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.
Definition: product.class.php:5308
User
Class to manage Dolibarr users.
Definition: user.class.php:44
measuring_units_cubed
measuring_units_cubed($unit)
Transform a given unit scale into the cube of that unit, if known.
Definition: product.lib.php:699
CommonObject\show_photos
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.
Definition: commonobject.class.php:8476
Product\$duration_unit
$duration_unit
Exoiration unit.
Definition: product.class.php:244
Expedition\STATUS_VALIDATED
const STATUS_VALIDATED
Validated status.
Definition: expedition.class.php:188
Product\$product_fourn_id
$product_fourn_id
Id du fournisseur.
Definition: product.class.php:371
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6116
Product\get_sousproduits_arbo
get_sousproduits_arbo()
Definition: product.class.php:4881
Entrepot\STATUS_CLOSED
const STATUS_CLOSED
Warehouse closed, inactive.
Definition: entrepot.class.php:151
Product
Class to manage products or services.
Definition: product.class.php:46
Product\$tva_tx
$tva_tx
Default VAT rate of product.
Definition: product.class.php:185
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
Product\load_stats_inproduction
load_stats_inproduction($socid=0, $filtrestatut='', $forVirtualStock=0)
Charge tableau des stats production pour le produit/service.
Definition: product.class.php:3257
Product\add_photo
add_photo($sdir, $file)
Move an uploaded file described into $file array into target directory $sdir.
Definition: product.class.php:5592
Product\_log_price
_log_price($user, $level=0)
Insert a track that we changed a customer price.
Definition: product.class.php:1744
Product\hasFatherOrChild
hasFatherOrChild($mode=0)
Count all parent and children products for current product (first level only)
Definition: product.class.php:4684
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
Product\_get_stats
_get_stats($sql, $mode, $year=0)
Return an array formated for showing graphs.
Definition: product.class.php:3628
Product\$pmp
$pmp
Average price value for product entry into stock (PMP)
Definition: product.class.php:222
Product\updatePrice
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.
Definition: product.class.php:2089
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->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->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
Product\$table_ref_field
$table_ref_field
{}
Definition: product.class.php:91
Product\clone_price
clone_price($fromId, $toId)
Recopie les prix d'un produit/service sur un autre.
Definition: product.class.php:4432
Product\load_stats_proposal_supplier
load_stats_proposal_supplier($socid=0)
Charge tableau des stats propale pour le produit/service.
Definition: product.class.php:2896
Product\get_nb_achat
get_nb_achat($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units or supplier invoices in which product is included.
Definition: product.class.php:3754
Product\del_sousproduit
del_sousproduit($fk_parent, $fk_child)
Remove a link between a subproduct and a parent product/service.
Definition: product.class.php:4214
Product\$default_vat_code
$default_vat_code
Default VAT code for product (link to code into llx_c_tva but without foreign keys)
Definition: product.class.php:182
price
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.
Definition: functions.lib.php:5541
Product\TYPE_SERVICE
const TYPE_SERVICE
Service.
Definition: product.class.php:504
Product\getMultiLangs
getMultiLangs()
Load array this->multilangs.
Definition: product.class.php:1670
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:489
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
Product\getChildsArbo
getChildsArbo($id, $firstlevelonly=0, $level=1, $parents=array())
Return childs of product $id.
Definition: product.class.php:4808
Product\get_nb_contract
get_nb_contract($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='')
Return nb of units in orders in which product is included.
Definition: product.class.php:4011
Product\TYPE_PRODUCT
const TYPE_PRODUCT
Regular product.
Definition: product.class.php:500
Product\get_image_size
get_image_size($file)
Load size of image file.
Definition: product.class.php:5774
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
dol_mktime
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...
Definition: functions.lib.php:2757
type
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
Product\load_state_board
load_state_board()
Load indicators this->nb for the dashboard.
Definition: product.class.php:5789
Product\fetch
fetch($id='', $ref='', $ref_ext='', $barcode='', $ignore_expression=0, $ignore_price_load=0, $ignore_lang_load=0)
Load a product in memory from database.
Definition: product.class.php:2282
Product\is_sousproduit
is_sousproduit($fk_parent, $fk_child)
Check if it is a sub-product into a kit.
Definition: product.class.php:4263
Product\check
check()
Check that ref and label are ok.
Definition: product.class.php:531
HookManager
Class to manage hooks.
Definition: hookmanager.class.php:30
Product\load_virtual_stock
load_virtual_stock($includedraftpoforvirtual=null)
Load value ->stock_theorique of a product.
Definition: product.class.php:5438
Product\$tva_npr
$tva_npr
French VAT NPR (0 or 1)
Definition: product.class.php:188
Product\get_buyprice
get_buyprice($prodfournprice, $qty, $product_id=0, $fourn_ref='', $fk_soc=0)
Read price used by a provider.
Definition: product.class.php:1934
Product\$price_by_qty
$price_by_qty
Price by quantity arrays.
Definition: product.class.php:173
Product\getRights
getRights()
Returns the rights used for this class.
Definition: product.class.php:6115
float
div float
Buy price without taxes.
Definition: style.css.php:809
Product\isVariant
isVariant()
Return if loaded product is a variant.
Definition: product.class.php:4739