dolibarr  16.0.1
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  if (!$error) {
1423  // We remove directory
1424  $ref = dol_sanitizeFileName($this->ref);
1425  if ($conf->product->dir_output) {
1426  $dir = $conf->product->dir_output."/".$ref;
1427  if (file_exists($dir)) {
1428  $res = @dol_delete_dir_recursive($dir);
1429  if (!$res) {
1430  $this->errors[] = 'ErrorFailToDeleteDir';
1431  $error++;
1432  }
1433  }
1434  }
1435  }
1436 
1437  if (!$error) {
1438  $this->db->commit();
1439  return 1;
1440  } else {
1441  foreach ($this->errors as $errmsg) {
1442  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1443  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1444  }
1445  $this->db->rollback();
1446  return -$error;
1447  }
1448  } else {
1449  $this->error = "ErrorRecordIsUsedCantDelete";
1450  return 0;
1451  }
1452  }
1453 
1460  public function setMultiLangs($user)
1461  {
1462  global $conf, $langs;
1463 
1464  $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
1465  $current_lang = $langs->getDefaultLang();
1466 
1467  foreach ($langs_available as $key => $value) {
1468  if ($key == $current_lang) {
1469  $sql = "SELECT rowid";
1470  $sql .= " FROM ".$this->db->prefix()."product_lang";
1471  $sql .= " WHERE fk_product = ".((int) $this->id);
1472  $sql .= " AND lang = '".$this->db->escape($key)."'";
1473 
1474  $result = $this->db->query($sql);
1475 
1476  if ($this->db->num_rows($result)) { // if there is already a description line for this language
1477  $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
1478  $sql2 .= " SET ";
1479  $sql2 .= " label='".$this->db->escape($this->label)."',";
1480  $sql2 .= " description='".$this->db->escape($this->description)."'";
1481  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1482  $sql2 .= ", note='".$this->db->escape($this->other)."'";
1483  }
1484  $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
1485  } else {
1486  $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
1487  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1488  $sql2 .= ", note";
1489  }
1490  $sql2 .= ")";
1491  $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
1492  $sql2 .= " '".$this->db->escape($this->description)."'";
1493  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1494  $sql2 .= ", '".$this->db->escape($this->other)."'";
1495  }
1496  $sql2 .= ")";
1497  }
1498  dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
1499  if (!$this->db->query($sql2)) {
1500  $this->error = $this->db->lasterror();
1501  return -1;
1502  }
1503  } elseif (isset($this->multilangs[$key])) {
1504  if (empty($this->multilangs["$key"]["label"])) {
1505  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
1506  return -1;
1507  }
1508 
1509  $sql = "SELECT rowid";
1510  $sql .= " FROM ".$this->db->prefix()."product_lang";
1511  $sql .= " WHERE fk_product = ".((int) $this->id);
1512  $sql .= " AND lang = '".$this->db->escape($key)."'";
1513 
1514  $result = $this->db->query($sql);
1515 
1516  if ($this->db->num_rows($result)) { // if there is already a description line for this language
1517  $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
1518  $sql2 .= " SET ";
1519  $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
1520  $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
1521  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1522  $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
1523  }
1524  $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
1525  } else {
1526  $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
1527  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1528  $sql2 .= ", note";
1529  }
1530  $sql2 .= ")";
1531  $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
1532  $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
1533  if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
1534  $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
1535  }
1536  $sql2 .= ")";
1537  }
1538 
1539  // We do not save if main fields are empty
1540  if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
1541  if (!$this->db->query($sql2)) {
1542  $this->error = $this->db->lasterror();
1543  return -1;
1544  }
1545  }
1546  } else {
1547  // language is not current language and we didn't provide a multilang description for this language
1548  }
1549  }
1550 
1551  // Call trigger
1552  $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
1553  if ($result < 0) {
1554  $this->error = $this->db->lasterror();
1555  return -1;
1556  }
1557  // End call triggers
1558 
1559  return 1;
1560  }
1561 
1570  public function delMultiLangs($langtodelete, $user)
1571  {
1572  $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
1573  $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
1574 
1575  dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
1576  $result = $this->db->query($sql);
1577  if ($result) {
1578  // Call trigger
1579  $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
1580  if ($result < 0) {
1581  $this->error = $this->db->lasterror();
1582  dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
1583  return -1;
1584  }
1585  // End call triggers
1586  return 1;
1587  } else {
1588  $this->error = $this->db->lasterror();
1589  dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
1590  return -1;
1591  }
1592  }
1593 
1602  public function setAccountancyCode($type, $value)
1603  {
1604  global $user, $langs, $conf;
1605 
1606  $error = 0;
1607 
1608  $this->db->begin();
1609 
1610  if ($type == 'buy') {
1611  $field = 'accountancy_code_buy';
1612  } elseif ($type == 'buy_intra') {
1613  $field = 'accountancy_code_buy_intra';
1614  } elseif ($type == 'buy_export') {
1615  $field = 'accountancy_code_buy_export';
1616  } elseif ($type == 'sell') {
1617  $field = 'accountancy_code_sell';
1618  } elseif ($type == 'sell_intra') {
1619  $field = 'accountancy_code_sell_intra';
1620  } elseif ($type == 'sell_export') {
1621  $field = 'accountancy_code_sell_export';
1622  } else {
1623  return -1;
1624  }
1625 
1626  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
1627  $sql .= "$field = '".$this->db->escape($value)."'";
1628  $sql .= " WHERE rowid = ".((int) $this->id);
1629 
1630  dol_syslog(__METHOD__."", LOG_DEBUG);
1631  $resql = $this->db->query($sql);
1632 
1633  if ($resql) {
1634  // Call trigger
1635  $result = $this->call_trigger('PRODUCT_MODIFY', $user);
1636  if ($result < 0) {
1637  $error++;
1638  }
1639  // End call triggers
1640 
1641  if ($error) {
1642  $this->db->rollback();
1643  return -1;
1644  }
1645 
1646  $this->$field = $value;
1647 
1648  $this->db->commit();
1649  return 1;
1650  } else {
1651  $this->error = $this->db->lasterror();
1652  $this->db->rollback();
1653  return -1;
1654  }
1655  }
1656 
1662  public function getMultiLangs()
1663  {
1664  global $langs;
1665 
1666  $current_lang = $langs->getDefaultLang();
1667 
1668  $sql = "SELECT lang, label, description, note as other";
1669  $sql .= " FROM ".$this->db->prefix()."product_lang";
1670  $sql .= " WHERE fk_product = ".((int) $this->id);
1671 
1672  $result = $this->db->query($sql);
1673  if ($result) {
1674  while ($obj = $this->db->fetch_object($result)) {
1675  //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
1676  if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
1677  $this->label = $obj->label;
1678  $this->description = $obj->description;
1679  $this->other = $obj->other;
1680  }
1681  $this->multilangs["$obj->lang"]["label"] = $obj->label;
1682  $this->multilangs["$obj->lang"]["description"] = $obj->description;
1683  $this->multilangs["$obj->lang"]["other"] = $obj->other;
1684  }
1685  return 1;
1686  } else {
1687  $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
1688  return -1;
1689  }
1690  }
1691 
1698  private function getArrayForPriceCompare($level = 0)
1699  {
1700 
1701  $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
1702 
1703  foreach ($testExit as $field) {
1704  if (!isset($this->$field)) {
1705  return array();
1706  }
1707  $tmparray = $this->$field;
1708  if (!isset($tmparray[$level])) {
1709  return array();
1710  }
1711  }
1712 
1713  $lastPrice = array(
1714  'level' => $level ? $level : 1,
1715  'multiprices' => doubleval($this->multiprices[$level]),
1716  'multiprices_ttc' => doubleval($this->multiprices_ttc[$level]),
1717  'multiprices_base_type' => $this->multiprices_base_type[$level],
1718  'multiprices_min' => doubleval($this->multiprices_min[$level]),
1719  'multiprices_min_ttc' => doubleval($this->multiprices_min_ttc[$level]),
1720  'multiprices_tva_tx' => doubleval($this->multiprices_tva_tx[$level]),
1721  'multiprices_recuperableonly' => doubleval($this->multiprices_recuperableonly[$level]),
1722  );
1723 
1724  return $lastPrice;
1725  }
1726 
1727 
1728  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736  private function _log_price($user, $level = 0)
1737  {
1738  // phpcs:enable
1739  global $conf;
1740 
1741  $now = dol_now();
1742 
1743  // Clean parameters
1744  if (empty($this->price_by_qty)) {
1745  $this->price_by_qty = 0;
1746  }
1747 
1748  // Add new price
1749  $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,";
1750  $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
1751  $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).",";
1752  $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');
1753  $sql .= ")";
1754 
1755  dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
1756  $resql = $this->db->query($sql);
1757  if (!$resql) {
1758  $this->error = $this->db->lasterror();
1759  dol_print_error($this->db);
1760  return -1;
1761  } else {
1762  return 1;
1763  }
1764  }
1765 
1766 
1767  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1775  public function log_price_delete($user, $rowid)
1776  {
1777  // phpcs:enable
1778  $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
1779  $sql .= " WHERE fk_product_price = ".((int) $rowid);
1780  $resql = $this->db->query($sql);
1781 
1782  $sql = "DELETE FROM ".$this->db->prefix()."product_price";
1783  $sql .= " WHERE rowid=".((int) $rowid);
1784  $resql = $this->db->query($sql);
1785  if ($resql) {
1786  return 1;
1787  } else {
1788  $this->error = $this->db->lasterror();
1789  return -1;
1790  }
1791  }
1792 
1793 
1803  public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
1804  {
1805  global $conf, $db, $hookmanager, $action;
1806 
1807  // Call hook if any
1808  if (is_object($hookmanager)) {
1809  $parameters = array('thirdparty_seller'=>$thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
1810  // Note that $action and $object may have been modified by some hooks
1811  $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
1812  if ($reshook > 0) {
1813  return $hookmanager->resArray;
1814  }
1815  }
1816 
1817  // Update if prices fields are defined
1818  $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
1819  $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
1820  if (empty($tva_tx)) {
1821  $tva_npr = 0;
1822  }
1823 
1824  $pu_ht = $this->price;
1825  $pu_ttc = $this->price_ttc;
1826  $price_min = $this->price_min;
1827  $price_base_type = $this->price_base_type;
1828 
1829  // If price per segment
1830  if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($thirdparty_buyer->price_level)) {
1831  $pu_ht = $this->multiprices[$thirdparty_buyer->price_level];
1832  $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
1833  $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
1834  $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
1835  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
1836  if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
1837  $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
1838  }
1839  if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
1840  $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
1841  }
1842  if (empty($tva_tx)) {
1843  $tva_npr = 0;
1844  }
1845  }
1846  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
1847  // If price per customer
1848  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
1849 
1850  $prodcustprice = new Productcustomerprice($this->db);
1851 
1852  $filter = array('t.fk_product' => $this->id, 't.fk_soc' => $thirdparty_buyer->id);
1853 
1854  $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
1855  if ($result) {
1856  if (count($prodcustprice->lines) > 0) {
1857  $pu_ht = price($prodcustprice->lines[0]->price);
1858  $price_min = price($prodcustprice->lines[0]->price_min);
1859  $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
1860  $price_base_type = $prodcustprice->lines[0]->price_base_type;
1861  $tva_tx = $prodcustprice->lines[0]->tva_tx;
1862  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
1863  $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
1864  }
1865  $tva_npr = $prodcustprice->lines[0]->recuperableonly;
1866  if (empty($tva_tx)) {
1867  $tva_npr = 0;
1868  }
1869  }
1870  }
1871  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
1872  // If price per quantity
1873  if ($this->prices_by_qty[0]) {
1874  // yes, this product has some prices per quantity
1875  // Search price into product_price_by_qty from $this->id
1876  foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
1877  if ($priceforthequantityarray['rowid'] != $pqp) {
1878  continue;
1879  }
1880  // We found the price
1881  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1882  $pu_ht = $priceforthequantityarray['unitprice'];
1883  } else {
1884  $pu_ttc = $priceforthequantityarray['unitprice'];
1885  }
1886  break;
1887  }
1888  }
1889  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
1890  // If price per quantity and customer
1891  if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
1892  // yes, this product has some prices per quantity
1893  // Search price into product_price_by_qty from $this->id
1894  foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
1895  if ($priceforthequantityarray['rowid'] != $pqp) {
1896  continue;
1897  }
1898  // We found the price
1899  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1900  $pu_ht = $priceforthequantityarray['unitprice'];
1901  } else {
1902  $pu_ttc = $priceforthequantityarray['unitprice'];
1903  }
1904  break;
1905  }
1906  }
1907  }
1908 
1909  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);
1910  }
1911 
1912  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1926  public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
1927  {
1928  // phpcs:enable
1929  global $conf;
1930  $result = 0;
1931 
1932  // 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)
1933  $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent,";
1934  $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,";
1935  $sql .= " pfp.default_vat_code,";
1936  $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
1937  $sql .= " pfp.packaging";
1938  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
1939  $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
1940  if ($qty > 0) {
1941  $sql .= " AND pfp.quantity <= ".((float) $qty);
1942  }
1943  $sql .= " ORDER BY pfp.quantity DESC";
1944 
1945  dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
1946  $resql = $this->db->query($sql);
1947  if ($resql) {
1948  $obj = $this->db->fetch_object($resql);
1949  if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
1950  if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
1951  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
1952  $prod_supplier = new ProductFournisseur($this->db);
1953  $prod_supplier->product_fourn_price_id = $obj->rowid;
1954  $prod_supplier->id = $obj->fk_product;
1955  $prod_supplier->fourn_qty = $obj->quantity;
1956  $prod_supplier->fourn_tva_tx = $obj->tva_tx;
1957  $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
1958  $priceparser = new PriceParser($this->db);
1959  $price_result = $priceparser->parseProductSupplier($prod_supplier);
1960  if ($price_result >= 0) {
1961  $obj->price = $price_result;
1962  }
1963  }
1964  $this->product_fourn_price_id = $obj->rowid;
1965  $this->buyprice = $obj->price; // deprecated
1966  $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
1967  $this->fourn_price_base_type = 'HT'; // Price base type
1968  $this->fourn_socid = $obj->fk_soc; // Company that offer this price
1969  $this->ref_fourn = $obj->ref_fourn; // deprecated
1970  $this->ref_supplier = $obj->ref_fourn; // Ref supplier
1971  $this->desc_supplier = $obj->desc_fourn; // desc supplier
1972  $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
1973  $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
1974  $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
1975  $this->fourn_multicurrency_price = $obj->multicurrency_price;
1976  $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
1977  $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
1978  $this->fourn_multicurrency_id = $obj->fk_multicurrency;
1979  $this->fourn_multicurrency_code = $obj->multicurrency_code;
1980  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
1981  $this->packaging = $obj->packaging;
1982  }
1983  $result = $obj->fk_product;
1984  return $result;
1985  } else { // If not found
1986  // 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.
1987  $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
1988  $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.fk_supplier_price_expression,";
1989  $sql .= " pfp.default_vat_code,";
1990  $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
1991  $sql .= " pfp.packaging";
1992  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
1993  $sql .= " WHERE 1 = 1";
1994  if ($product_id > 0) {
1995  $sql .= " AND pfp.fk_product = ".((int) $product_id);
1996  }
1997  if ($fourn_ref != 'none') {
1998  $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
1999  }
2000  if ($fk_soc > 0) {
2001  $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
2002  }
2003  if ($qty > 0) {
2004  $sql .= " AND pfp.quantity <= ".((float) $qty);
2005  }
2006  $sql .= " ORDER BY pfp.quantity DESC";
2007  $sql .= " LIMIT 1";
2008 
2009  dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
2010  $resql = $this->db->query($sql);
2011  if ($resql) {
2012  $obj = $this->db->fetch_object($resql);
2013  if ($obj && $obj->quantity > 0) { // If found
2014  if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
2015  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2016  $prod_supplier = new ProductFournisseur($this->db);
2017  $prod_supplier->product_fourn_price_id = $obj->rowid;
2018  $prod_supplier->id = $obj->fk_product;
2019  $prod_supplier->fourn_qty = $obj->quantity;
2020  $prod_supplier->fourn_tva_tx = $obj->tva_tx;
2021  $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
2022  $priceparser = new PriceParser($this->db);
2023  $price_result = $priceparser->parseProductSupplier($prod_supplier);
2024  if ($result >= 0) {
2025  $obj->price = $price_result;
2026  }
2027  }
2028  $this->product_fourn_price_id = $obj->rowid;
2029  $this->buyprice = $obj->price; // deprecated
2030  $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
2031  $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
2032  $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
2033  $this->fourn_socid = $obj->fk_soc; // Company that offer this price
2034  $this->ref_fourn = $obj->ref_supplier; // deprecated
2035  $this->ref_supplier = $obj->ref_supplier; // Ref supplier
2036  $this->desc_supplier = $obj->desc_supplier; // desc supplier
2037  $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
2038  $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
2039  $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
2040  $this->fourn_multicurrency_price = $obj->multicurrency_price;
2041  $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
2042  $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
2043  $this->fourn_multicurrency_id = $obj->fk_multicurrency;
2044  $this->fourn_multicurrency_code = $obj->multicurrency_code;
2045  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
2046  $this->packaging = $obj->packaging;
2047  }
2048  $result = $obj->fk_product;
2049  return $result;
2050  } else {
2051  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é.
2052  }
2053  } else {
2054  $this->error = $this->db->lasterror();
2055  return -3;
2056  }
2057  }
2058  } else {
2059  $this->error = $this->db->lasterror();
2060  return -2;
2061  }
2062  }
2063 
2064 
2081  public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '')
2082  {
2083  global $conf, $langs;
2084 
2085  $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
2086 
2087  $id = $this->id;
2088 
2089  dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
2090 
2091  // Clean parameters
2092  if (empty($this->tva_tx)) {
2093  $this->tva_tx = 0;
2094  }
2095  if (empty($newnpr)) {
2096  $newnpr = 0;
2097  }
2098  if (empty($newminprice)) {
2099  $newminprice = 0;
2100  }
2101  if (empty($newminprice)) {
2102  $newminprice = 0;
2103  }
2104 
2105  // Check parameters
2106  if ($newvat == '') {
2107  $newvat = $this->tva_tx;
2108  }
2109 
2110  // If multiprices are enabled, then we check if the current product is subject to price autogeneration
2111  // Price will be modified ONLY when the first one is the one that is being modified
2112  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
2113  return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
2114  }
2115 
2116  if (!empty($newminprice) && ($newminprice > $newprice)) {
2117  $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
2118  return -1;
2119  }
2120 
2121  if ($newprice !== '' || $newprice === 0) {
2122  if ($newpricebase == 'TTC') {
2123  $price_ttc = price2num($newprice, 'MU');
2124  $price = price2num($newprice) / (1 + ($newvat / 100));
2125  $price = price2num($price, 'MU');
2126 
2127  if ($newminprice != '' || $newminprice == 0) {
2128  $price_min_ttc = price2num($newminprice, 'MU');
2129  $price_min = price2num($newminprice) / (1 + ($newvat / 100));
2130  $price_min = price2num($price_min, 'MU');
2131  } else {
2132  $price_min = 0;
2133  $price_min_ttc = 0;
2134  }
2135  } else {
2136  $price = price2num($newprice, 'MU');
2137  $price_ttc = ($newnpr != 1) ? price2num($newprice) * (1 + ($newvat / 100)) : $price;
2138  $price_ttc = price2num($price_ttc, 'MU');
2139 
2140  if ($newminprice !== '' || $newminprice === 0) {
2141  $price_min = price2num($newminprice, 'MU');
2142  $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100));
2143  $price_min_ttc = price2num($price_min_ttc, 'MU');
2144  //print 'X'.$newminprice.'-'.$price_min;
2145  } else {
2146  $price_min = 0;
2147  $price_min_ttc = 0;
2148  }
2149  }
2150  //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
2151 
2152  if (count($localtaxes_array) > 0) {
2153  $localtaxtype1 = $localtaxes_array['0'];
2154  $localtax1 = $localtaxes_array['1'];
2155  $localtaxtype2 = $localtaxes_array['2'];
2156  $localtax2 = $localtaxes_array['3'];
2157  } else // old method. deprecated because ot can't retrieve type
2158  {
2159  $localtaxtype1 = '0';
2160  $localtax1 = get_localtax($newvat, 1);
2161  $localtaxtype2 = '0';
2162  $localtax2 = get_localtax($newvat, 2);
2163  }
2164  if (empty($localtax1)) {
2165  $localtax1 = 0; // If = '' then = 0
2166  }
2167  if (empty($localtax2)) {
2168  $localtax2 = 0; // If = '' then = 0
2169  }
2170 
2171  $this->db->begin();
2172 
2173  // Ne pas mettre de quote sur les numeriques decimaux.
2174  // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes.
2175  $sql = "UPDATE ".$this->db->prefix()."product SET";
2176  $sql .= " price_base_type='".$this->db->escape($newpricebase)."',";
2177  $sql .= " price=".$price.",";
2178  $sql .= " price_ttc=".$price_ttc.",";
2179  $sql .= " price_min=".$price_min.",";
2180  $sql .= " price_min_ttc=".$price_min_ttc.",";
2181  $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').",";
2182  $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').",";
2183  $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
2184  $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
2185  $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
2186  $sql .= " tva_tx='".price2num($newvat)."',";
2187  $sql .= " recuperableonly='".$this->db->escape($newnpr)."'";
2188  $sql .= " WHERE rowid = ".((int) $id);
2189 
2190  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2191  $resql = $this->db->query($sql);
2192  if ($resql) {
2193  $this->multiprices[$level] = $price;
2194  $this->multiprices_ttc[$level] = $price_ttc;
2195  $this->multiprices_min[$level] = $price_min;
2196  $this->multiprices_min_ttc[$level] = $price_min_ttc;
2197  $this->multiprices_base_type[$level] = $newpricebase;
2198  $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
2199  $this->multiprices_tva_tx[$level] = $newvat;
2200  $this->multiprices_recuperableonly[$level] = $newnpr;
2201 
2202  $this->price = $price;
2203  $this->price_ttc = $price_ttc;
2204  $this->price_min = $price_min;
2205  $this->price_min_ttc = $price_min_ttc;
2206  $this->price_base_type = $newpricebase;
2207  $this->default_vat_code = $newdefaultvatcode;
2208  $this->tva_tx = $newvat;
2209  $this->tva_npr = $newnpr;
2210  //Local taxes
2211  $this->localtax1_tx = $localtax1;
2212  $this->localtax2_tx = $localtax2;
2213  $this->localtax1_type = $localtaxtype1;
2214  $this->localtax2_type = $localtaxtype2;
2215 
2216  // Price by quantity
2217  $this->price_by_qty = $newpbq;
2218 
2219  // check if price have really change before log
2220  $newPriceData = $this->getArrayForPriceCompare($level);
2221  if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || empty($conf->global->PRODUIT_MULTIPRICES)) {
2222  $this->_log_price($user, $level); // Save price for level into table product_price
2223  }
2224 
2225  $this->level = $level; // Store level of price edited for trigger
2226 
2227  // Call trigger
2228  $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
2229  if ($result < 0) {
2230  $this->db->rollback();
2231  return -1;
2232  }
2233  // End call triggers
2234 
2235  $this->db->commit();
2236  } else {
2237  $this->db->rollback();
2238  $this->error = $this->db->lasterror();
2239  return -1;
2240  }
2241  }
2242 
2243  return 1;
2244  }
2245 
2253  public function setPriceExpression($expression_id)
2254  {
2255  global $user;
2256 
2257  $this->fk_price_expression = $expression_id;
2258 
2259  return $this->update($this->id, $user);
2260  }
2261 
2274  public function fetch($id = '', $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
2275  {
2276  include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
2277 
2278  global $langs, $conf;
2279 
2280  dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
2281 
2282  // Check parameters
2283  if (!$id && !$ref && !$ref_ext && !$barcode) {
2284  $this->error = 'ErrorWrongParameters';
2285  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2286  return -1;
2287  }
2288 
2289  $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,";
2290  $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,";
2291  $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,";
2292  $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
2293  $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,";
2294  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
2295  $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,";
2296  } else {
2297  $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,";
2298  }
2299 
2300  //For MultiCompany
2301  //PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
2302  $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
2303  $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.
2304  $visibleWarehousesEntities = $conf->entity;
2305  if (!empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
2306  if (!empty($conf->global->MULTICOMPANY_PMP_PER_ENTITY_ENABLED)) {
2307  $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
2308  if ($this->db->num_rows($checkPMPPerEntity)>0) {
2309  $separatedEntityPMP = true;
2310  }
2311  }
2312  global $mc;
2313  $separatedStock = true;
2314  if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
2315  $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
2316  }
2317  }
2318  if ($separatedEntityPMP) {
2319  $sql .= " ppe.pmp,";
2320  } else {
2321  $sql .= " p.pmp,";
2322  }
2323  $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
2324  $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf,";
2325  if ($separatedStock) {
2326  $sql .= " SUM(sp.reel) as stock";
2327  } else {
2328  $sql .= " p.stock";
2329  }
2330  $sql .= " FROM ".$this->db->prefix()."product as p";
2331  if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) || $separatedEntityPMP) {
2332  $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
2333  }
2334  if ($separatedStock) {
2335  $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)."))";
2336  }
2337 
2338  if ($id) {
2339  $sql .= " WHERE p.rowid = ".((int) $id);
2340  } else {
2341  $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
2342  if ($ref) {
2343  $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
2344  } elseif ($ref_ext) {
2345  $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
2346  } elseif ($barcode) {
2347  $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
2348  }
2349  }
2350  if ($separatedStock) {
2351  $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,";
2352  $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,";
2353  $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,";
2354  $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
2355  $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished,";
2356  if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
2357  $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,";
2358  } else {
2359  $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,";
2360  }
2361  if ($separatedEntityPMP) {
2362  $sql .= " ppe.pmp,";
2363  } else {
2364  $sql .= " p.pmp,";
2365  }
2366  $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
2367  $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf";
2368  if (!$separatedStock) {
2369  $sql .= ", p.stock";
2370  }
2371  }
2372 
2373  $resql = $this->db->query($sql);
2374  if ($resql) {
2375  unset($this->oldcopy);
2376 
2377  if ($this->db->num_rows($resql) > 0) {
2378  $obj = $this->db->fetch_object($resql);
2379 
2380  $this->id = $obj->rowid;
2381  $this->ref = $obj->ref;
2382  $this->ref_ext = $obj->ref_ext;
2383  $this->label = $obj->label;
2384  $this->description = $obj->description;
2385  $this->url = $obj->url;
2386  $this->note_public = $obj->note_public;
2387  $this->note_private = $obj->note_private;
2388  $this->note = $obj->note_private; // deprecated
2389 
2390  $this->type = $obj->fk_product_type;
2391  $this->status = $obj->tosell;
2392  $this->status_buy = $obj->tobuy;
2393  $this->status_batch = $obj->tobatch;
2394  $this->batch_mask = $obj->batch_mask;
2395 
2396  $this->customcode = $obj->customcode;
2397  $this->country_id = $obj->fk_country;
2398  $this->country_code = getCountry($this->country_id, 2, $this->db);
2399  $this->state_id = $obj->fk_state;
2400  $this->lifetime = $obj->lifetime;
2401  $this->qc_frequency = $obj->qc_frequency;
2402  $this->price = $obj->price;
2403  $this->price_ttc = $obj->price_ttc;
2404  $this->price_min = $obj->price_min;
2405  $this->price_min_ttc = $obj->price_min_ttc;
2406  $this->price_base_type = $obj->price_base_type;
2407  $this->cost_price = $obj->cost_price;
2408  $this->default_vat_code = $obj->default_vat_code;
2409  $this->tva_tx = $obj->tva_tx;
2411  $this->tva_npr = $obj->tva_npr;
2412  $this->recuperableonly = $obj->tva_npr; // For backward compatibility
2414  $this->localtax1_tx = $obj->localtax1_tx;
2415  $this->localtax2_tx = $obj->localtax2_tx;
2416  $this->localtax1_type = $obj->localtax1_type;
2417  $this->localtax2_type = $obj->localtax2_type;
2418 
2419  $this->finished = $obj->finished;
2420  $this->fk_default_bom = $obj->fk_default_bom;
2421 
2422  $this->duration = $obj->duration;
2423  $this->duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1);
2424  $this->duration_unit = substr($obj->duration, -1);
2425  $this->canvas = $obj->canvas;
2426  $this->net_measure = $obj->net_measure;
2427  $this->net_measure_units = $obj->net_measure_units;
2428  $this->weight = $obj->weight;
2429  $this->weight_units = $obj->weight_units;
2430  $this->length = $obj->length;
2431  $this->length_units = $obj->length_units;
2432  $this->width = $obj->width;
2433  $this->width_units = $obj->width_units;
2434  $this->height = $obj->height;
2435  $this->height_units = $obj->height_units;
2436 
2437  $this->surface = $obj->surface;
2438  $this->surface_units = $obj->surface_units;
2439  $this->volume = $obj->volume;
2440  $this->volume_units = $obj->volume_units;
2441  $this->barcode = $obj->barcode;
2442  $this->barcode_type = $obj->fk_barcode_type;
2443 
2444  $this->accountancy_code_buy = $obj->accountancy_code_buy;
2445  $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
2446  $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
2447  $this->accountancy_code_sell = $obj->accountancy_code_sell;
2448  $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
2449  $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
2450 
2451  $this->fk_default_warehouse = $obj->fk_default_warehouse;
2452  $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
2453  $this->desiredstock = $obj->desiredstock;
2454  $this->stock_reel = $obj->stock;
2455  $this->pmp = $obj->pmp;
2456 
2457  $this->date_creation = $obj->datec;
2458  $this->date_modification = $obj->tms;
2459  $this->import_key = $obj->import_key;
2460  $this->entity = $obj->entity;
2461 
2462  $this->ref_ext = $obj->ref_ext;
2463  $this->fk_price_expression = $obj->fk_price_expression;
2464  $this->fk_unit = $obj->fk_unit;
2465  $this->price_autogen = $obj->price_autogen;
2466  $this->model_pdf = $obj->model_pdf;
2467 
2468  $this->mandatory_period = $obj->mandatory_period;
2469 
2470  $this->db->free($resql);
2471 
2472  // fetch optionals attributes and labels
2473  $this->fetch_optionals();
2474 
2475  // Multilangs
2476  if (!empty($conf->global->MAIN_MULTILANGS) && empty($ignore_lang_load)) {
2477  $this->getMultiLangs();
2478  }
2479 
2480  // Load multiprices array
2481  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
2482  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
2483  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2484  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
2485  $sql .= " FROM ".$this->db->prefix()."product_price";
2486  $sql .= " WHERE entity IN (".getEntity('productprice').")";
2487  $sql .= " AND price_level=".((int) $i);
2488  $sql .= " AND fk_product = ".((int) $this->id);
2489  $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
2490  $sql .= " LIMIT 1"; // Only the first one
2491  $resql = $this->db->query($sql);
2492  if ($resql) {
2493  $result = $this->db->fetch_array($resql);
2494 
2495  $this->multiprices[$i] = $result ? $result["price"] : null;
2496  $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
2497  $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
2498  $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
2499  $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
2500  // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
2501  $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].($result ? ' ('.$result['default_vat_code'].')' : '') : null;
2502  $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
2503 
2504  // Price by quantity
2505  /*
2506  $this->prices_by_qty[$i]=$result["price_by_qty"];
2507  $this->prices_by_qty_id[$i]=$result["rowid"];
2508  // Récuperation de la liste des prix selon qty si flag positionné
2509  if ($this->prices_by_qty[$i] == 1)
2510  {
2511  $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
2512  $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
2513  $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
2514  $sql.= " ORDER BY quantity ASC";
2515  $resultat=array();
2516  $resql = $this->db->query($sql);
2517  if ($resql)
2518  {
2519  $ii=0;
2520  while ($result= $this->db->fetch_array($resql)) {
2521  $resultat[$ii]=array();
2522  $resultat[$ii]["rowid"]=$result["rowid"];
2523  $resultat[$ii]["price"]= $result["price"];
2524  $resultat[$ii]["unitprice"]= $result["unitprice"];
2525  $resultat[$ii]["quantity"]= $result["quantity"];
2526  $resultat[$ii]["remise_percent"]= $result["remise_percent"];
2527  $resultat[$ii]["remise"]= $result["remise"]; // deprecated
2528  $resultat[$ii]["price_base_type"]= $result["price_base_type"];
2529  $ii++;
2530  }
2531  $this->prices_by_qty_list[$i]=$resultat;
2532  }
2533  else
2534  {
2535  dol_print_error($this->db);
2536  return -1;
2537  }
2538  }*/
2539  } else {
2540  $this->error = $this->db->lasterror;
2541  return -1;
2542  }
2543  }
2544  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
2545  // Nothing loaded by default. List may be very long.
2546  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
2547  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2548  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
2549  $sql .= " FROM ".$this->db->prefix()."product_price";
2550  $sql .= " WHERE fk_product = ".((int) $this->id);
2551  $sql .= " ORDER BY date_price DESC, rowid DESC";
2552  $sql .= " LIMIT 1";
2553  $resql = $this->db->query($sql);
2554  if ($resql) {
2555  $result = $this->db->fetch_array($resql);
2556 
2557  // Price by quantity
2558  $this->prices_by_qty[0] = $result["price_by_qty"];
2559  $this->prices_by_qty_id[0] = $result["rowid"];
2560  // Récuperation de la liste des prix selon qty si flag positionné
2561  if ($this->prices_by_qty[0] == 1) {
2562  $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
2563  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2564  $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
2565  $sql .= " ORDER BY quantity ASC";
2566  $resultat = array();
2567  $resql = $this->db->query($sql);
2568  if ($resql) {
2569  $ii = 0;
2570  while ($result = $this->db->fetch_array($resql)) {
2571  $resultat[$ii] = array();
2572  $resultat[$ii]["rowid"] = $result["rowid"];
2573  $resultat[$ii]["price"] = $result["price"];
2574  $resultat[$ii]["unitprice"] = $result["unitprice"];
2575  $resultat[$ii]["quantity"] = $result["quantity"];
2576  $resultat[$ii]["remise_percent"] = $result["remise_percent"];
2577  //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
2578  $resultat[$ii]["price_base_type"] = $result["price_base_type"];
2579  $ii++;
2580  }
2581  $this->prices_by_qty_list[0] = $resultat;
2582  } else {
2583  $this->error = $this->db->lasterror;
2584  return -1;
2585  }
2586  }
2587  } else {
2588  $this->error = $this->db->lasterror;
2589  return -1;
2590  }
2591  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
2592  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
2593  $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
2594  $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
2595  $sql .= " FROM ".$this->db->prefix()."product_price";
2596  $sql .= " WHERE entity IN (".getEntity('productprice').")";
2597  $sql .= " AND price_level=".((int) $i);
2598  $sql .= " AND fk_product = ".((int) $this->id);
2599  $sql .= " ORDER BY date_price DESC, rowid DESC";
2600  $sql .= " LIMIT 1";
2601  $resql = $this->db->query($sql);
2602  if ($resql) {
2603  $result = $this->db->fetch_array($resql);
2604 
2605  $this->multiprices[$i] = $result["price"];
2606  $this->multiprices_ttc[$i] = $result["price_ttc"];
2607  $this->multiprices_min[$i] = $result["price_min"];
2608  $this->multiprices_min_ttc[$i] = $result["price_min_ttc"];
2609  $this->multiprices_base_type[$i] = $result["price_base_type"];
2610  // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
2611  $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')'
2612  $this->multiprices_recuperableonly[$i] = $result["recuperableonly"];
2613 
2614  // Price by quantity
2615  $this->prices_by_qty[$i] = $result["price_by_qty"];
2616  $this->prices_by_qty_id[$i] = $result["rowid"];
2617  // Récuperation de la liste des prix selon qty si flag positionné
2618  if ($this->prices_by_qty[$i] == 1) {
2619  $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
2620  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2621  $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
2622  $sql .= " ORDER BY quantity ASC";
2623  $resultat = array();
2624  $resql = $this->db->query($sql);
2625  if ($resql) {
2626  $ii = 0;
2627  while ($result = $this->db->fetch_array($resql)) {
2628  $resultat[$ii] = array();
2629  $resultat[$ii]["rowid"] = $result["rowid"];
2630  $resultat[$ii]["price"] = $result["price"];
2631  $resultat[$ii]["unitprice"] = $result["unitprice"];
2632  $resultat[$ii]["quantity"] = $result["quantity"];
2633  $resultat[$ii]["remise_percent"] = $result["remise_percent"];
2634  $resultat[$ii]["remise"] = $result["remise"]; // deprecated
2635  $resultat[$ii]["price_base_type"] = $result["price_base_type"];
2636  $ii++;
2637  }
2638  $this->prices_by_qty_list[$i] = $resultat;
2639  } else {
2640  $this->error = $this->db->lasterror;
2641  return -1;
2642  }
2643  }
2644  } else {
2645  $this->error = $this->db->lasterror;
2646  return -1;
2647  }
2648  }
2649  }
2650 
2651  if (!empty($conf->dynamicprices->enabled) && !empty($this->fk_price_expression) && empty($ignore_expression)) {
2652  include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2653  $priceparser = new PriceParser($this->db);
2654  $price_result = $priceparser->parseProduct($this);
2655  if ($price_result >= 0) {
2656  $this->price = $price_result;
2657  // Calculate the VAT
2658  $this->price_ttc = price2num($this->price) * (1 + ($this->tva_tx / 100));
2659  $this->price_ttc = price2num($this->price_ttc, 'MU');
2660  }
2661  }
2662 
2663  // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
2664  // Instead we just init the stock_warehouse array
2665  $this->stock_warehouse = array();
2666 
2667  return 1;
2668  } else {
2669  return 0;
2670  }
2671  } else {
2672  $this->error = $this->db->lasterror();
2673  return -1;
2674  }
2675  }
2676 
2677  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2684  public function load_stats_mo($socid = 0)
2685  {
2686  // phpcs:enable
2687  global $user, $hookmanager, $action;
2688 
2689  $error = 0;
2690 
2691  foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
2692  $this->stats_mo['customers_'.$role] = 0;
2693  $this->stats_mo['nb_'.$role] = 0;
2694  $this->stats_mo['qty_'.$role] = 0;
2695 
2696  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
2697  $sql .= " SUM(mp.qty) as qty";
2698  $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
2699  $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
2700  if (empty($user->rights->societe->client->voir) && !$socid) {
2701  $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
2702  }
2703  $sql .= " WHERE ";
2704  $sql .= " c.entity IN (".getEntity('mo').")";
2705 
2706  $sql .= " AND mp.fk_product = ".((int) $this->id);
2707  $sql .= " AND mp.role ='".$this->db->escape($role)."'";
2708  if ($socid > 0) {
2709  $sql .= " AND c.fk_soc = ".((int) $socid);
2710  }
2711 
2712  $result = $this->db->query($sql);
2713  if ($result) {
2714  $obj = $this->db->fetch_object($result);
2715  $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
2716  $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
2717  $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
2718  } else {
2719  $this->error = $this->db->error();
2720  $error++;
2721  }
2722  }
2723 
2724  if (!empty($error)) {
2725  return -1;
2726  }
2727 
2728  $parameters = array('socid' => $socid);
2729  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
2730  if ($reshook > 0) {
2731  $this->stats_mo = $hookmanager->resArray['stats_mo'];
2732  }
2733 
2734  return 1;
2735  }
2736 
2737  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2744  public function load_stats_bom($socid = 0)
2745  {
2746  // phpcs:enable
2747  global $user, $hookmanager, $action;
2748 
2749  $error = 0;
2750 
2751  $this->stats_bom['nb_toproduce'] = 0;
2752  $this->stats_bom['nb_toconsume'] = 0;
2753  $this->stats_bom['qty_toproduce'] = 0;
2754  $this->stats_bom['qty_toconsume'] = 0;
2755 
2756  $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
2757  $sql .= " SUM(b.qty) as qty_toproduce";
2758  $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
2759  $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
2760  $sql .= " WHERE ";
2761  $sql .= " b.entity IN (".getEntity('bom').")";
2762  $sql .= " AND b.fk_product =".((int) $this->id);
2763  $sql .= " GROUP BY b.rowid";
2764 
2765  $result = $this->db->query($sql);
2766  if ($result) {
2767  $obj = $this->db->fetch_object($result);
2768  $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
2769  $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
2770  } else {
2771  $this->error = $this->db->error();
2772  $error++;
2773  }
2774 
2775  $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
2776  $sql .= " SUM(bl.qty) as qty_toconsume";
2777  $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
2778  $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
2779  $sql .= " WHERE ";
2780  $sql .= " b.entity IN (".getEntity('bom').")";
2781  $sql .= " AND bl.fk_product =".((int) $this->id);
2782 
2783  $result = $this->db->query($sql);
2784  if ($result) {
2785  $obj = $this->db->fetch_object($result);
2786  $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
2787  $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
2788  } else {
2789  $this->error = $this->db->error();
2790  $error++;
2791  }
2792 
2793  if (!empty($error)) {
2794  return -1;
2795  }
2796 
2797  $parameters = array('socid' => $socid);
2798  $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
2799  if ($reshook > 0) {
2800  $this->stats_bom = $hookmanager->resArray['stats_bom'];
2801  }
2802 
2803  return 1;
2804  }
2805 
2806  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2813  public function load_stats_propale($socid = 0)
2814  {
2815  // phpcs:enable
2816  global $conf, $user, $hookmanager, $action;
2817 
2818  $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
2819  $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
2820  $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
2821  $sql .= ", ".$this->db->prefix()."propal as p";
2822  $sql .= ", ".$this->db->prefix()."societe as s";
2823  if (empty($user->rights->societe->client->voir) && !$socid) {
2824  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2825  }
2826  $sql .= " WHERE p.rowid = pd.fk_propal";
2827  $sql .= " AND p.fk_soc = s.rowid";
2828  $sql .= " AND p.entity IN (".getEntity('propal').")";
2829  $sql .= " AND pd.fk_product = ".((int) $this->id);
2830  if (empty($user->rights->societe->client->voir) && !$socid) {
2831  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2832  }
2833  //$sql.= " AND pr.fk_statut != 0";
2834  if ($socid > 0) {
2835  $sql .= " AND p.fk_soc = ".((int) $socid);
2836  }
2837 
2838  $result = $this->db->query($sql);
2839  if ($result) {
2840  $obj = $this->db->fetch_object($result);
2841  $this->stats_propale['customers'] = $obj->nb_customers;
2842  $this->stats_propale['nb'] = $obj->nb;
2843  $this->stats_propale['rows'] = $obj->nb_rows;
2844  $this->stats_propale['qty'] = $obj->qty ? $obj->qty : 0;
2845 
2846  // if it's a virtual product, maybe it is in proposal by extension
2847  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
2848  $TFather = $this->getFather();
2849  if (is_array($TFather) && !empty($TFather)) {
2850  foreach ($TFather as &$fatherData) {
2851  $pFather = new Product($this->db);
2852  $pFather->id = $fatherData['id'];
2853  $qtyCoef = $fatherData['qty'];
2854 
2855  if ($fatherData['incdec']) {
2856  $pFather->load_stats_propale($socid);
2857 
2858  $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
2859  $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
2860  $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
2861  $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
2862  }
2863  }
2864  }
2865  }
2866 
2867  $parameters = array('socid' => $socid);
2868  $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
2869  if ($reshook > 0) {
2870  $this->stats_propale = $hookmanager->resArray['stats_propale'];
2871  }
2872 
2873  return 1;
2874  } else {
2875  $this->error = $this->db->error();
2876  return -1;
2877  }
2878  }
2879 
2880 
2881  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2888  public function load_stats_proposal_supplier($socid = 0)
2889  {
2890  // phpcs:enable
2891  global $conf, $user, $hookmanager, $action;
2892 
2893  $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
2894  $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
2895  $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
2896  $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
2897  $sql .= ", ".$this->db->prefix()."societe as s";
2898  if (empty($user->rights->societe->client->voir) && !$socid) {
2899  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2900  }
2901  $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
2902  $sql .= " AND p.fk_soc = s.rowid";
2903  $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
2904  $sql .= " AND pd.fk_product = ".((int) $this->id);
2905  if (empty($user->rights->societe->client->voir) && !$socid) {
2906  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2907  }
2908  //$sql.= " AND pr.fk_statut != 0";
2909  if ($socid > 0) {
2910  $sql .= " AND p.fk_soc = ".((int) $socid);
2911  }
2912 
2913  $result = $this->db->query($sql);
2914  if ($result) {
2915  $obj = $this->db->fetch_object($result);
2916  $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
2917  $this->stats_proposal_supplier['nb'] = $obj->nb;
2918  $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
2919  $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
2920 
2921  $parameters = array('socid' => $socid);
2922  $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
2923  if ($reshook > 0) {
2924  $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
2925  }
2926 
2927  return 1;
2928  } else {
2929  $this->error = $this->db->error();
2930  return -1;
2931  }
2932  }
2933 
2934 
2935  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2944  public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
2945  {
2946  // phpcs:enable
2947  global $conf, $user, $hookmanager, $action;
2948 
2949  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
2950  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
2951  $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
2952  $sql .= ", ".$this->db->prefix()."commande as c";
2953  $sql .= ", ".$this->db->prefix()."societe as s";
2954  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
2955  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
2956  }
2957  $sql .= " WHERE c.rowid = cd.fk_commande";
2958  $sql .= " AND c.fk_soc = s.rowid";
2959  $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
2960  $sql .= " AND cd.fk_product = ".((int) $this->id);
2961  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
2962  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2963  }
2964  if ($socid > 0) {
2965  $sql .= " AND c.fk_soc = ".((int) $socid);
2966  }
2967  if ($filtrestatut <> '') {
2968  $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")";
2969  }
2970 
2971  $result = $this->db->query($sql);
2972  if ($result) {
2973  $obj = $this->db->fetch_object($result);
2974  $this->stats_commande['customers'] = $obj->nb_customers;
2975  $this->stats_commande['nb'] = $obj->nb;
2976  $this->stats_commande['rows'] = $obj->nb_rows;
2977  $this->stats_commande['qty'] = $obj->qty ? $obj->qty : 0;
2978 
2979  // if it's a virtual product, maybe it is in order by extension
2980  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
2981  $TFather = $this->getFather();
2982  if (is_array($TFather) && !empty($TFather)) {
2983  foreach ($TFather as &$fatherData) {
2984  $pFather = new Product($this->db);
2985  $pFather->id = $fatherData['id'];
2986  $qtyCoef = $fatherData['qty'];
2987 
2988  if ($fatherData['incdec']) {
2989  $pFather->load_stats_commande($socid, $filtrestatut);
2990 
2991  $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
2992  $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
2993  $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
2994  $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
2995  }
2996  }
2997  }
2998  }
2999 
3000  // If stock decrease is on invoice validation, the theorical stock continue to
3001  // count the orders to ship in theorical stock when some are already removed b invoice validation.
3002  // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation.
3003  if (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3004  if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) {
3005  $adeduire = 0;
3006  $sql = "SELECT sum(fd.qty) as count FROM ".$this->db->prefix()."facturedet fd ";
3007  $sql .= " JOIN ".$this->db->prefix()."facture f ON fd.fk_facture = f.rowid ";
3008  $sql .= " JOIN ".$this->db->prefix()."element_element el ON el.fk_target = f.rowid and el.targettype = 'facture' and sourcetype = 'commande'";
3009  $sql .= " JOIN ".$this->db->prefix()."commande c ON el.fk_source = c.rowid ";
3010  $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
3011  dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
3012 
3013  $resql = $this->db->query($sql);
3014  if ($resql) {
3015  if ($this->db->num_rows($resql) > 0) {
3016  $obj = $this->db->fetch_object($resql);
3017  $adeduire += $obj->count;
3018  }
3019  }
3020 
3021  $this->stats_commande['qty'] -= $adeduire;
3022  }
3023  }
3024 
3025  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3026  $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
3027  if ($reshook > 0) {
3028  $this->stats_commande = $hookmanager->resArray['stats_commande'];
3029  }
3030  return 1;
3031  } else {
3032  $this->error = $this->db->error();
3033  return -1;
3034  }
3035  }
3036 
3037  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3046  public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3047  {
3048  // phpcs:enable
3049  global $conf, $user, $hookmanager, $action;
3050 
3051  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
3052  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3053  $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
3054  $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
3055  $sql .= ", ".$this->db->prefix()."societe as s";
3056  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3057  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3058  }
3059  $sql .= " WHERE c.rowid = cd.fk_commande";
3060  $sql .= " AND c.fk_soc = s.rowid";
3061  $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
3062  $sql .= " AND cd.fk_product = ".((int) $this->id);
3063  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3064  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3065  }
3066  if ($socid > 0) {
3067  $sql .= " AND c.fk_soc = ".((int) $socid);
3068  }
3069  if ($filtrestatut != '') {
3070  $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
3071  }
3072 
3073  $result = $this->db->query($sql);
3074  if ($result) {
3075  $obj = $this->db->fetch_object($result);
3076  $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
3077  $this->stats_commande_fournisseur['nb'] = $obj->nb;
3078  $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
3079  $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3080 
3081  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3082  $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
3083  if ($reshook > 0) {
3084  $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
3085  }
3086 
3087  return 1;
3088  } else {
3089  $this->error = $this->db->error().' sql='.$sql;
3090  return -1;
3091  }
3092  }
3093 
3094  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3104  public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
3105  {
3106  // phpcs:enable
3107  global $conf, $user, $hookmanager, $action;
3108 
3109  $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
3110  $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
3111  $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
3112  $sql .= ", ".$this->db->prefix()."commandedet as cd";
3113  $sql .= ", ".$this->db->prefix()."commande as c";
3114  $sql .= ", ".$this->db->prefix()."expedition as e";
3115  $sql .= ", ".$this->db->prefix()."societe as s";
3116  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3117  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3118  }
3119  $sql .= " WHERE e.rowid = ed.fk_expedition";
3120  $sql .= " AND c.rowid = cd.fk_commande";
3121  $sql .= " AND e.fk_soc = s.rowid";
3122  $sql .= " AND e.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
3123  $sql .= " AND ed.fk_origin_line = cd.rowid";
3124  $sql .= " AND cd.fk_product = ".((int) $this->id);
3125  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3126  $sql .= " AND e.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3127  }
3128  if ($socid > 0) {
3129  $sql .= " AND e.fk_soc = ".((int) $socid);
3130  }
3131  if ($filtrestatut <> '') {
3132  $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3133  }
3134  if (!empty($filterShipmentStatus)) {
3135  $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
3136  }
3137 
3138  $result = $this->db->query($sql);
3139  if ($result) {
3140  $obj = $this->db->fetch_object($result);
3141  $this->stats_expedition['customers'] = $obj->nb_customers;
3142  $this->stats_expedition['nb'] = $obj->nb;
3143  $this->stats_expedition['rows'] = $obj->nb_rows;
3144  $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
3145 
3146  // if it's a virtual product, maybe it is in sending by extension
3147  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3148  $TFather = $this->getFather();
3149  if (is_array($TFather) && !empty($TFather)) {
3150  foreach ($TFather as &$fatherData) {
3151  $pFather = new Product($this->db);
3152  $pFather->id = $fatherData['id'];
3153  $qtyCoef = $fatherData['qty'];
3154 
3155  if ($fatherData['incdec']) {
3156  $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
3157 
3158  $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
3159  $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
3160  $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
3161  $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
3162  }
3163  }
3164  }
3165  }
3166 
3167  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
3168  $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
3169  if ($reshook > 0) {
3170  $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
3171  }
3172 
3173  return 1;
3174  } else {
3175  $this->error = $this->db->error();
3176  return -1;
3177  }
3178  }
3179 
3180  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3189  public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3190  {
3191  // phpcs:enable
3192  global $conf, $user, $hookmanager, $action;
3193 
3194  $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
3195  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3196  $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as fd";
3197  $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
3198  $sql .= ", ".$this->db->prefix()."societe as s";
3199  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3200  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3201  }
3202  $sql .= " WHERE cf.rowid = fd.fk_commande";
3203  $sql .= " AND cf.fk_soc = s.rowid";
3204  $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
3205  $sql .= " AND fd.fk_product = ".((int) $this->id);
3206  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3207  $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3208  }
3209  if ($socid > 0) {
3210  $sql .= " AND cf.fk_soc = ".((int) $socid);
3211  }
3212  if ($filtrestatut <> '') {
3213  $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
3214  }
3215 
3216  $result = $this->db->query($sql);
3217  if ($result) {
3218  $obj = $this->db->fetch_object($result);
3219  $this->stats_reception['suppliers'] = $obj->nb_suppliers;
3220  $this->stats_reception['nb'] = $obj->nb;
3221  $this->stats_reception['rows'] = $obj->nb_rows;
3222  $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
3223 
3224  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3225  $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
3226  if ($reshook > 0) {
3227  $this->stats_reception = $hookmanager->resArray['stats_reception'];
3228  }
3229 
3230  return 1;
3231  } else {
3232  $this->error = $this->db->error();
3233  return -1;
3234  }
3235  }
3236 
3237  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3246  public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
3247  {
3248  // phpcs:enable
3249  global $conf, $user, $hookmanager, $action;
3250 
3251  $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
3252  $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
3253  $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
3254  $sql .= ", ".$this->db->prefix()."mrp_mo as m";
3255  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
3256  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3257  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3258  }
3259  $sql .= " WHERE m.rowid = mp.fk_mo";
3260  $sql .= " AND m.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mrp').")";
3261  $sql .= " AND mp.fk_product = ".((int) $this->id);
3262  if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
3263  $sql .= " AND m.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3264  }
3265  if ($socid > 0) {
3266  $sql .= " AND m.fk_soc = ".((int) $socid);
3267  }
3268  if ($filtrestatut <> '') {
3269  $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
3270  }
3271  $sql .= " GROUP BY role";
3272 
3273  $this->stats_mrptoconsume['customers'] = 0;
3274  $this->stats_mrptoconsume['nb'] = 0;
3275  $this->stats_mrptoconsume['rows'] = 0;
3276  $this->stats_mrptoconsume['qty'] = 0;
3277  $this->stats_mrptoproduce['customers'] = 0;
3278  $this->stats_mrptoproduce['nb'] = 0;
3279  $this->stats_mrptoproduce['rows'] = 0;
3280  $this->stats_mrptoproduce['qty'] = 0;
3281 
3282  $result = $this->db->query($sql);
3283  if ($result) {
3284  while ($obj = $this->db->fetch_object($result)) {
3285  if ($obj->role == 'toconsume') {
3286  $this->stats_mrptoconsume['customers'] += $obj->nb_customers;
3287  $this->stats_mrptoconsume['nb'] += $obj->nb;
3288  $this->stats_mrptoconsume['rows'] += $obj->nb_rows;
3289  $this->stats_mrptoconsume['qty'] += ($obj->qty ? $obj->qty : 0);
3290  }
3291  if ($obj->role == 'consumed') {
3292  //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
3293  //$this->stats_mrptoconsume['nb'] += $obj->nb;
3294  //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
3295  $this->stats_mrptoconsume['qty'] -= ($obj->qty ? $obj->qty : 0);
3296  }
3297  if ($obj->role == 'toproduce') {
3298  $this->stats_mrptoproduce['customers'] += $obj->nb_customers;
3299  $this->stats_mrptoproduce['nb'] += $obj->nb;
3300  $this->stats_mrptoproduce['rows'] += $obj->nb_rows;
3301  $this->stats_mrptoproduce['qty'] += ($obj->qty ? $obj->qty : 0);
3302  }
3303  if ($obj->role == 'produced') {
3304  //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
3305  //$this->stats_mrptoproduce['nb'] += $obj->nb;
3306  //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
3307  $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
3308  }
3309  }
3310 
3311  // Clean data
3312  if ($this->stats_mrptoconsume['qty'] < 0) {
3313  $this->stats_mrptoconsume['qty'] = 0;
3314  }
3315  if ($this->stats_mrptoproduce['qty'] < 0) {
3316  $this->stats_mrptoproduce['qty'] = 0;
3317  }
3318 
3319  $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
3320  $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
3321  if ($reshook > 0) {
3322  $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
3323  }
3324 
3325  return 1;
3326  } else {
3327  $this->error = $this->db->error();
3328  return -1;
3329  }
3330  }
3331 
3332  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3339  public function load_stats_contrat($socid = 0)
3340  {
3341  // phpcs:enable
3342  global $conf, $user, $hookmanager, $action;
3343 
3344  $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
3345  $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
3346  $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
3347  $sql .= ", ".$this->db->prefix()."contrat as c";
3348  $sql .= ", ".$this->db->prefix()."societe as s";
3349  if (empty($user->rights->societe->client->voir) && !$socid) {
3350  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3351  }
3352  $sql .= " WHERE c.rowid = cd.fk_contrat";
3353  $sql .= " AND c.fk_soc = s.rowid";
3354  $sql .= " AND c.entity IN (".getEntity('contract').")";
3355  $sql .= " AND cd.fk_product = ".((int) $this->id);
3356  if (empty($user->rights->societe->client->voir) && !$socid) {
3357  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3358  }
3359  //$sql.= " AND c.statut != 0";
3360  if ($socid > 0) {
3361  $sql .= " AND c.fk_soc = ".((int) $socid);
3362  }
3363 
3364  $result = $this->db->query($sql);
3365  if ($result) {
3366  $obj = $this->db->fetch_object($result);
3367  $this->stats_contrat['customers'] = $obj->nb_customers;
3368  $this->stats_contrat['nb'] = $obj->nb;
3369  $this->stats_contrat['rows'] = $obj->nb_rows;
3370  $this->stats_contrat['qty'] = $obj->qty ? $obj->qty : 0;
3371 
3372  // if it's a virtual product, maybe it is in contract by extension
3373  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3374  $TFather = $this->getFather();
3375  if (is_array($TFather) && !empty($TFather)) {
3376  foreach ($TFather as &$fatherData) {
3377  $pFather = new Product($this->db);
3378  $pFather->id = $fatherData['id'];
3379  $qtyCoef = $fatherData['qty'];
3380 
3381  if ($fatherData['incdec']) {
3382  $pFather->load_stats_contrat($socid);
3383 
3384  $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
3385  $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
3386  $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
3387  $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
3388  }
3389  }
3390  }
3391  }
3392 
3393  $parameters = array('socid' => $socid);
3394  $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
3395  if ($reshook > 0) {
3396  $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
3397  }
3398 
3399  return 1;
3400  } else {
3401  $this->error = $this->db->error().' sql='.$sql;
3402  return -1;
3403  }
3404  }
3405 
3406  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3413  public function load_stats_facture($socid = 0)
3414  {
3415  // phpcs:enable
3416  global $db, $conf, $user, $hookmanager, $action;
3417 
3418  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
3419  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
3420  $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
3421  $sql .= ", ".$this->db->prefix()."facture as f";
3422  $sql .= ", ".$this->db->prefix()."societe as s";
3423  if (empty($user->rights->societe->client->voir) && !$socid) {
3424  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3425  }
3426  $sql .= " WHERE f.rowid = fd.fk_facture";
3427  $sql .= " AND f.fk_soc = s.rowid";
3428  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3429  $sql .= " AND fd.fk_product = ".((int) $this->id);
3430  if (empty($user->rights->societe->client->voir) && !$socid) {
3431  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3432  }
3433  //$sql.= " AND f.fk_statut != 0";
3434  if ($socid > 0) {
3435  $sql .= " AND f.fk_soc = ".((int) $socid);
3436  }
3437 
3438  $result = $this->db->query($sql);
3439  if ($result) {
3440  $obj = $this->db->fetch_object($result);
3441  $this->stats_facture['customers'] = $obj->nb_customers;
3442  $this->stats_facture['nb'] = $obj->nb;
3443  $this->stats_facture['rows'] = $obj->nb_rows;
3444  $this->stats_facture['qty'] = $obj->qty ? $obj->qty : 0;
3445 
3446  // if it's a virtual product, maybe it is in invoice by extension
3447  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3448  $TFather = $this->getFather();
3449  if (is_array($TFather) && !empty($TFather)) {
3450  foreach ($TFather as &$fatherData) {
3451  $pFather = new Product($this->db);
3452  $pFather->id = $fatherData['id'];
3453  $qtyCoef = $fatherData['qty'];
3454 
3455  if ($fatherData['incdec']) {
3456  $pFather->load_stats_facture($socid);
3457 
3458  $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
3459  $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
3460  $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
3461  $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
3462  }
3463  }
3464  }
3465  }
3466 
3467  $parameters = array('socid' => $socid);
3468  $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
3469  if ($reshook > 0) {
3470  $this->stats_facture = $hookmanager->resArray['stats_facture'];
3471  }
3472 
3473  return 1;
3474  } else {
3475  $this->error = $this->db->error();
3476  return -1;
3477  }
3478  }
3479 
3480 
3481  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3488  public function load_stats_facturerec($socid = 0)
3489  {
3490  // phpcs:enable
3491  global $db, $conf, $user, $hookmanager;
3492 
3493  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
3494  $sql .= " COUNT(fd.rowid) as nb_rows, SUM('fd.qty') as qty";
3495  $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_rec as fd";
3496  $sql .= ", ".MAIN_DB_PREFIX."facture_rec as f";
3497  $sql .= ", ".MAIN_DB_PREFIX."societe as s";
3498  if (empty($user->rights->societe->client->voir) && !$socid) {
3499  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
3500  }
3501  $sql .= " WHERE f.rowid = fd.fk_facture";
3502  $sql .= " AND f.fk_soc = s.rowid";
3503  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3504  $sql .= " AND fd.fk_product = ".((int) $this->id);
3505  if (empty($user->rights->societe->client->voir) && !$socid) {
3506  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3507  }
3508  //$sql.= " AND f.fk_statut != 0";
3509  if ($socid > 0) {
3510  $sql .= " AND f.fk_soc = ".((int) $socid);
3511  }
3512 
3513  $result = $this->db->query($sql);
3514  if ($result) {
3515  $obj = $this->db->fetch_object($result);
3516  $this->stats_facturerec['customers'] = $obj->nb_customers;
3517  $this->stats_facturerec['nb'] = $obj->nb;
3518  $this->stats_facturerec['rows'] = $obj->nb_rows;
3519  $this->stats_facturerec['qty'] = $obj->qty ? $obj->qty : 0;
3520 
3521  // if it's a virtual product, maybe it is in invoice by extension
3522  if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
3523  $TFather = $this->getFather();
3524  if (is_array($TFather) && !empty($TFather)) {
3525  foreach ($TFather as &$fatherData) {
3526  $pFather = new Product($this->db);
3527  $pFather->id = $fatherData['id'];
3528  $qtyCoef = $fatherData['qty'];
3529 
3530  if ($fatherData['incdec']) {
3531  $pFather->load_stats_facture($socid);
3532 
3533  $this->stats_facturerec['customers'] += $pFather->stats_facturerec['customers'];
3534  $this->stats_facturerec['nb'] += $pFather->stats_facturerec['nb'];
3535  $this->stats_facturerec['rows'] += $pFather->stats_facturerec['rows'];
3536  $this->stats_facturerec['qty'] += $pFather->stats_facturerec['qty'] * $qtyCoef;
3537  }
3538  }
3539  }
3540  }
3541 
3542  $parameters = array('socid' => $socid);
3543  $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoiceRec', $parameters, $this, $action);
3544  if ($reshook > 0) {
3545  $this->stats_facturerec = $hookmanager->resArray['stats_facturerec'];
3546  }
3547 
3548  return 1;
3549  } else {
3550  $this->error = $this->db->error();
3551  return -1;
3552  }
3553  }
3554 
3555  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3562  public function load_stats_facture_fournisseur($socid = 0)
3563  {
3564  // phpcs:enable
3565  global $conf, $user, $hookmanager, $action;
3566 
3567  $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
3568  $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
3569  $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
3570  $sql .= ", ".$this->db->prefix()."facture_fourn as f";
3571  $sql .= ", ".$this->db->prefix()."societe as s";
3572  if (empty($user->rights->societe->client->voir) && !$socid) {
3573  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3574  }
3575  $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
3576  $sql .= " AND f.fk_soc = s.rowid";
3577  $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
3578  $sql .= " AND fd.fk_product = ".((int) $this->id);
3579  if (empty($user->rights->societe->client->voir) && !$socid) {
3580  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3581  }
3582  //$sql.= " AND f.fk_statut != 0";
3583  if ($socid > 0) {
3584  $sql .= " AND f.fk_soc = ".((int) $socid);
3585  }
3586 
3587  $result = $this->db->query($sql);
3588  if ($result) {
3589  $obj = $this->db->fetch_object($result);
3590  $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers;
3591  $this->stats_facture_fournisseur['nb'] = $obj->nb;
3592  $this->stats_facture_fournisseur['rows'] = $obj->nb_rows;
3593  $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
3594 
3595  $parameters = array('socid' => $socid);
3596  $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
3597  if ($reshook > 0) {
3598  $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
3599  }
3600 
3601  return 1;
3602  } else {
3603  $this->error = $this->db->error();
3604  return -1;
3605  }
3606  }
3607 
3608  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3617  private function _get_stats($sql, $mode, $year = 0)
3618  {
3619  // phpcs:enable
3620  $tab = array();
3621 
3622  $resql = $this->db->query($sql);
3623  if ($resql) {
3624  $num = $this->db->num_rows($resql);
3625  $i = 0;
3626  while ($i < $num) {
3627  $arr = $this->db->fetch_array($resql);
3628  $keyfortab = (string) $arr[1];
3629  if ($year == -1) {
3630  $keyfortab = substr($keyfortab, -2);
3631  }
3632 
3633  if ($mode == 'byunit') {
3634  $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
3635  } elseif ($mode == 'bynumber') {
3636  $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
3637  }
3638  $i++;
3639  }
3640  } else {
3641  $this->error = $this->db->error().' sql='.$sql;
3642  return -1;
3643  }
3644 
3645  if (empty($year)) {
3646  $year = strftime('%Y', time());
3647  $month = strftime('%m', time());
3648  } elseif ($year == -1) {
3649  $year = '';
3650  $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
3651  } else {
3652  $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
3653  }
3654 
3655  $result = array();
3656 
3657  for ($j = 0; $j < 12; $j++) {
3658  // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
3659  $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
3660 
3661  //print $idx.'-'.$year.'-'.$month.'<br>';
3662  $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
3663  // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
3664 
3665  $month = "0".($month - 1);
3666  if (dol_strlen($month) == 3) {
3667  $month = substr($month, 1);
3668  }
3669  if ($month == 0) {
3670  $month = 12;
3671  $year = $year - 1;
3672  }
3673  }
3674 
3675  return array_reverse($result);
3676  }
3677 
3678 
3679  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3690  public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3691  {
3692  // phpcs:enable
3693  global $conf;
3694  global $user;
3695 
3696  $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
3697  if ($mode == 'bynumber') {
3698  $sql .= ", count(DISTINCT f.rowid)";
3699  }
3700  $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
3701  if ($filteronproducttype >= 0) {
3702  $sql .= ", ".$this->db->prefix()."product as p";
3703  }
3704  if (empty($user->rights->societe->client->voir) && !$socid) {
3705  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3706  }
3707  $sql .= " WHERE f.rowid = d.fk_facture";
3708  if ($this->id > 0) {
3709  $sql .= " AND d.fk_product = ".((int) $this->id);
3710  } else {
3711  $sql .= " AND d.fk_product > 0";
3712  }
3713  if ($filteronproducttype >= 0) {
3714  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3715  }
3716  $sql .= " AND f.fk_soc = s.rowid";
3717  $sql .= " AND f.entity IN (".getEntity('invoice').")";
3718  if (empty($user->rights->societe->client->voir) && !$socid) {
3719  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3720  }
3721  if ($socid > 0) {
3722  $sql .= " AND f.fk_soc = $socid";
3723  }
3724  $sql .= $morefilter;
3725  $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
3726  $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
3727 
3728  return $this->_get_stats($sql, $mode, $year);
3729  }
3730 
3731 
3732  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3743  public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3744  {
3745  // phpcs:enable
3746  global $conf;
3747  global $user;
3748 
3749  $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
3750  if ($mode == 'bynumber') {
3751  $sql .= ", count(DISTINCT f.rowid)";
3752  }
3753  $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
3754  if ($filteronproducttype >= 0) {
3755  $sql .= ", ".$this->db->prefix()."product as p";
3756  }
3757  if (empty($user->rights->societe->client->voir) && !$socid) {
3758  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3759  }
3760  $sql .= " WHERE f.rowid = d.fk_facture_fourn";
3761  if ($this->id > 0) {
3762  $sql .= " AND d.fk_product = ".((int) $this->id);
3763  } else {
3764  $sql .= " AND d.fk_product > 0";
3765  }
3766  if ($filteronproducttype >= 0) {
3767  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3768  }
3769  $sql .= " AND f.fk_soc = s.rowid";
3770  $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
3771  if (empty($user->rights->societe->client->voir) && !$socid) {
3772  $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3773  }
3774  if ($socid > 0) {
3775  $sql .= " AND f.fk_soc = $socid";
3776  }
3777  $sql .= $morefilter;
3778  $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
3779  $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
3780 
3781  return $this->_get_stats($sql, $mode, $year);
3782  }
3783 
3784  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3795  public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3796  {
3797  // phpcs:enable
3798  global $conf, $user;
3799 
3800  $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')";
3801  if ($mode == 'bynumber') {
3802  $sql .= ", count(DISTINCT p.rowid)";
3803  }
3804  $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
3805  if ($filteronproducttype >= 0) {
3806  $sql .= ", ".$this->db->prefix()."product as prod";
3807  }
3808  if (empty($user->rights->societe->client->voir) && !$socid) {
3809  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3810  }
3811  $sql .= " WHERE p.rowid = d.fk_propal";
3812  if ($this->id > 0) {
3813  $sql .= " AND d.fk_product = ".((int) $this->id);
3814  } else {
3815  $sql .= " AND d.fk_product > 0";
3816  }
3817  if ($filteronproducttype >= 0) {
3818  $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
3819  }
3820  $sql .= " AND p.fk_soc = s.rowid";
3821  $sql .= " AND p.entity IN (".getEntity('propal').")";
3822  if (empty($user->rights->societe->client->voir) && !$socid) {
3823  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3824  }
3825  if ($socid > 0) {
3826  $sql .= " AND p.fk_soc = ".((int) $socid);
3827  }
3828  $sql .= $morefilter;
3829  $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
3830  $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
3831 
3832  return $this->_get_stats($sql, $mode, $year);
3833  }
3834 
3835  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3846  public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3847  {
3848  // phpcs:enable
3849  global $conf;
3850  global $user;
3851 
3852  $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')";
3853  if ($mode == 'bynumber') {
3854  $sql .= ", count(DISTINCT p.rowid)";
3855  }
3856  $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
3857  if ($filteronproducttype >= 0) {
3858  $sql .= ", ".$this->db->prefix()."product as prod";
3859  }
3860  if (empty($user->rights->societe->client->voir) && !$socid) {
3861  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3862  }
3863  $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
3864  if ($this->id > 0) {
3865  $sql .= " AND d.fk_product = ".((int) $this->id);
3866  } else {
3867  $sql .= " AND d.fk_product > 0";
3868  }
3869  if ($filteronproducttype >= 0) {
3870  $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
3871  }
3872  $sql .= " AND p.fk_soc = s.rowid";
3873  $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
3874  if (empty($user->rights->societe->client->voir) && !$socid) {
3875  $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3876  }
3877  if ($socid > 0) {
3878  $sql .= " AND p.fk_soc = ".((int) $socid);
3879  }
3880  $sql .= $morefilter;
3881  $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
3882  $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
3883 
3884  return $this->_get_stats($sql, $mode, $year);
3885  }
3886 
3887  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3898  public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3899  {
3900  // phpcs:enable
3901  global $conf, $user;
3902 
3903  $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
3904  if ($mode == 'bynumber') {
3905  $sql .= ", count(DISTINCT c.rowid)";
3906  }
3907  $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
3908  if ($filteronproducttype >= 0) {
3909  $sql .= ", ".$this->db->prefix()."product as p";
3910  }
3911  if (empty($user->rights->societe->client->voir) && !$socid) {
3912  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3913  }
3914  $sql .= " WHERE c.rowid = d.fk_commande";
3915  if ($this->id > 0) {
3916  $sql .= " AND d.fk_product = ".((int) $this->id);
3917  } else {
3918  $sql .= " AND d.fk_product > 0";
3919  }
3920  if ($filteronproducttype >= 0) {
3921  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3922  }
3923  $sql .= " AND c.fk_soc = s.rowid";
3924  $sql .= " AND c.entity IN (".getEntity('commande').")";
3925  if (empty($user->rights->societe->client->voir) && !$socid) {
3926  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3927  }
3928  if ($socid > 0) {
3929  $sql .= " AND c.fk_soc = ".((int) $socid);
3930  }
3931  $sql .= $morefilter;
3932  $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
3933  $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
3934 
3935  return $this->_get_stats($sql, $mode, $year);
3936  }
3937 
3938  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3949  public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
3950  {
3951  // phpcs:enable
3952  global $conf, $user;
3953 
3954  $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
3955  if ($mode == 'bynumber') {
3956  $sql .= ", count(DISTINCT c.rowid)";
3957  }
3958  $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
3959  if ($filteronproducttype >= 0) {
3960  $sql .= ", ".$this->db->prefix()."product as p";
3961  }
3962  if (empty($user->rights->societe->client->voir) && !$socid) {
3963  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
3964  }
3965  $sql .= " WHERE c.rowid = d.fk_commande";
3966  if ($this->id > 0) {
3967  $sql .= " AND d.fk_product = ".((int) $this->id);
3968  } else {
3969  $sql .= " AND d.fk_product > 0";
3970  }
3971  if ($filteronproducttype >= 0) {
3972  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
3973  }
3974  $sql .= " AND c.fk_soc = s.rowid";
3975  $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
3976  if (empty($user->rights->societe->client->voir) && !$socid) {
3977  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3978  }
3979  if ($socid > 0) {
3980  $sql .= " AND c.fk_soc = ".((int) $socid);
3981  }
3982  $sql .= $morefilter;
3983  $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
3984  $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
3985 
3986  return $this->_get_stats($sql, $mode, $year);
3987  }
3988 
3989  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4000  public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4001  {
4002  // phpcs:enable
4003  global $conf, $user;
4004 
4005  $sql = "SELECT sum(d.qty), date_format(c.date_contrat, '%Y%m')";
4006  if ($mode == 'bynumber') {
4007  $sql .= ", count(DISTINCT c.rowid)";
4008  }
4009  $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
4010  if ($filteronproducttype >= 0) {
4011  $sql .= ", ".$this->db->prefix()."product as p";
4012  }
4013  if (empty($user->rights->societe->client->voir) && !$socid) {
4014  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4015  }
4016 
4017  $sql .= " WHERE c.entity IN (".getEntity('contract').")";
4018  $sql .= " AND c.rowid = d.fk_contrat";
4019 
4020  if ($this->id > 0) {
4021  $sql .= " AND d.fk_product = ".((int) $this->id);
4022  } else {
4023  $sql .= " AND d.fk_product > 0";
4024  }
4025  if ($filteronproducttype >= 0) {
4026  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4027  }
4028  $sql .= " AND c.fk_soc = s.rowid";
4029 
4030  if (empty($user->rights->societe->client->voir) && !$socid) {
4031  $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4032  }
4033  if ($socid > 0) {
4034  $sql .= " AND c.fk_soc = ".((int) $socid);
4035  }
4036  $sql .= $morefilter;
4037  $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
4038  $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
4039 
4040  return $this->_get_stats($sql, $mode, $year);
4041  }
4042 
4043  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4054  public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
4055  {
4056  // phpcs:enable
4057  global $conf, $user;
4058 
4059  $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
4060  if ($mode == 'bynumber') {
4061  $sql .= ", count(DISTINCT d.rowid)";
4062  }
4063  $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
4064  if ($filteronproducttype >= 0) {
4065  $sql .= ", ".$this->db->prefix()."product as p";
4066  }
4067  if (empty($user->rights->societe->client->voir) && !$socid) {
4068  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
4069  }
4070 
4071  $sql .= " WHERE d.entity IN (".getEntity('mo').")";
4072  $sql .= " AND d.status > 0";
4073 
4074  if ($this->id > 0) {
4075  $sql .= " AND d.fk_product = ".((int) $this->id);
4076  } else {
4077  $sql .= " AND d.fk_product > 0";
4078  }
4079  if ($filteronproducttype >= 0) {
4080  $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
4081  }
4082 
4083  if (empty($user->rights->societe->client->voir) && !$socid) {
4084  $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4085  }
4086  if ($socid > 0) {
4087  $sql .= " AND d.fk_soc = ".((int) $socid);
4088  }
4089  $sql .= $morefilter;
4090  $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
4091  $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
4092 
4093  return $this->_get_stats($sql, $mode, $year);
4094  }
4095 
4096  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4106  public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
4107  {
4108  // phpcs:enable
4109  // Clean parameters
4110  if (!is_numeric($id_pere)) {
4111  $id_pere = 0;
4112  }
4113  if (!is_numeric($id_fils)) {
4114  $id_fils = 0;
4115  }
4116  if (!is_numeric($incdec)) {
4117  $incdec = 0;
4118  }
4119 
4120  $result = $this->del_sousproduit($id_pere, $id_fils);
4121  if ($result < 0) {
4122  return $result;
4123  }
4124 
4125  // Check not already father of id_pere (to avoid father -> child -> father links)
4126  $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
4127  $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
4128  if (!$this->db->query($sql)) {
4129  dol_print_error($this->db);
4130  return -1;
4131  } else {
4132  //Selection of the highest row
4133  $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
4134  $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
4135  $resql = $this->db->query($sql);
4136  if ($resql > 0) {
4137  $obj = $this->db->fetch_object($resql);
4138  $rank = $obj->max_rank + 1;
4139  //Addition of a product with the highest rank +1
4140  $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
4141  $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".price2num($incdec, 'MS').", ".((int) $rank).")";
4142  if (! $this->db->query($sql)) {
4143  dol_print_error($this->db);
4144  return -1;
4145  } else {
4146  return 1;
4147  }
4148  } else {
4149  dol_print_error($this->db);
4150  return -1;
4151  }
4152  }
4153  }
4154 
4155  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4165  public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
4166  {
4167  // phpcs:enable
4168  // Clean parameters
4169  if (!is_numeric($id_pere)) {
4170  $id_pere = 0;
4171  }
4172  if (!is_numeric($id_fils)) {
4173  $id_fils = 0;
4174  }
4175  if (!is_numeric($incdec)) {
4176  $incdec = 1;
4177  }
4178  if (!is_numeric($qty)) {
4179  $qty = 1;
4180  }
4181 
4182  $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
4183  $sql .= 'qty = '.price2num($qty, 'MS');
4184  $sql .= ',incdec = '.price2num($incdec, 'MS');
4185  $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
4186 
4187  if (!$this->db->query($sql)) {
4188  dol_print_error($this->db);
4189  return -1;
4190  } else {
4191  return 1;
4192  }
4193  }
4194 
4195  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4203  public function del_sousproduit($fk_parent, $fk_child)
4204  {
4205  // phpcs:enable
4206  if (!is_numeric($fk_parent)) {
4207  $fk_parent = 0;
4208  }
4209  if (!is_numeric($fk_child)) {
4210  $fk_child = 0;
4211  }
4212 
4213  $sql = "DELETE FROM ".$this->db->prefix()."product_association";
4214  $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
4215  $sql .= " AND fk_product_fils = ".((int) $fk_child);
4216 
4217  dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
4218  if (!$this->db->query($sql)) {
4219  dol_print_error($this->db);
4220  return -1;
4221  }
4222 
4223  // Updated ranks so that none are missing
4224  $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
4225  $sqlrank.= " WHERE fk_product_pere = ".((int) $fk_parent);
4226  $sqlrank.= " ORDER BY rang";
4227  $resqlrank = $this->db->query($sqlrank);
4228  if ($resqlrank) {
4229  $cpt = 0;
4230  while ($objrank = $this->db->fetch_object($resqlrank)) {
4231  $cpt++;
4232  $sql = "UPDATE ".$this->db->prefix()."product_association";
4233  $sql.= " SET rang = ".((int) $cpt);
4234  $sql.= " WHERE rowid = ".((int) $objrank->rowid);
4235  if (! $this->db->query($sql)) {
4236  dol_print_error($this->db);
4237  return -1;
4238  }
4239  }
4240  }
4241  return 1;
4242  }
4243 
4244  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4252  public function is_sousproduit($fk_parent, $fk_child)
4253  {
4254  // phpcs:enable
4255  $sql = "SELECT fk_product_pere, qty, incdec";
4256  $sql .= " FROM ".$this->db->prefix()."product_association";
4257  $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
4258  $sql .= " AND fk_product_fils = ".((int) $fk_child);
4259 
4260  $result = $this->db->query($sql);
4261  if ($result) {
4262  $num = $this->db->num_rows($result);
4263 
4264  if ($num > 0) {
4265  $obj = $this->db->fetch_object($result);
4266 
4267  $this->is_sousproduit_qty = $obj->qty;
4268  $this->is_sousproduit_incdec = $obj->incdec;
4269 
4270  return true;
4271  } else {
4272  return false;
4273  }
4274  } else {
4275  dol_print_error($this->db);
4276  return -1;
4277  }
4278  }
4279 
4280 
4281  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4292  public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
4293  {
4294  // phpcs:enable
4295  global $conf;
4296 
4297  $now = dol_now();
4298 
4299  dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
4300 
4301  // Clean parameters
4302  $quantity = price2num($quantity, 'MS');
4303 
4304  if ($ref_fourn) {
4305  $sql = "SELECT rowid, fk_product";
4306  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4307  $sql .= " WHERE fk_soc = ".((int) $id_fourn);
4308  $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
4309  $sql .= " AND fk_product <> ".((int) $this->id);
4310  $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
4311 
4312  $resql = $this->db->query($sql);
4313  if ($resql) {
4314  $obj = $this->db->fetch_object($resql);
4315  if ($obj) {
4316  // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
4317  $this->product_id_already_linked = $obj->fk_product;
4318  return -3;
4319  }
4320  $this->db->free($resql);
4321  }
4322  }
4323 
4324  $sql = "SELECT rowid";
4325  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4326  $sql .= " WHERE fk_soc = ".((int) $id_fourn);
4327  if ($ref_fourn) {
4328  $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
4329  } else {
4330  $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
4331  }
4332  $sql .= " AND quantity = ".((float) $quantity);
4333  $sql .= " AND fk_product = ".((int) $this->id);
4334  $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
4335 
4336  $resql = $this->db->query($sql);
4337  if ($resql) {
4338  $obj = $this->db->fetch_object($resql);
4339 
4340  // The reference supplier does not exist, we create it for this product.
4341  if (empty($obj)) {
4342  $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
4343  $sql .= "datec";
4344  $sql .= ", entity";
4345  $sql .= ", fk_product";
4346  $sql .= ", fk_soc";
4347  $sql .= ", ref_fourn";
4348  $sql .= ", quantity";
4349  $sql .= ", fk_user";
4350  $sql .= ", tva_tx";
4351  $sql .= ") VALUES (";
4352  $sql .= "'".$this->db->idate($now)."'";
4353  $sql .= ", ".$conf->entity;
4354  $sql .= ", ".$this->id;
4355  $sql .= ", ".$id_fourn;
4356  $sql .= ", '".$this->db->escape($ref_fourn)."'";
4357  $sql .= ", ".$quantity;
4358  $sql .= ", ".$user->id;
4359  $sql .= ", 0";
4360  $sql .= ")";
4361 
4362  if ($this->db->query($sql)) {
4363  $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
4364  return 1;
4365  } else {
4366  $this->error = $this->db->lasterror();
4367  return -1;
4368  }
4369  } else {
4370  // If the supplier price already exists for this product and quantity
4371  $this->product_fourn_price_id = $obj->rowid;
4372  return 0;
4373  }
4374  } else {
4375  $this->error = $this->db->lasterror();
4376  return -2;
4377  }
4378  }
4379 
4380 
4381  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4387  public function list_suppliers()
4388  {
4389  // phpcs:enable
4390  global $conf;
4391 
4392  $list = array();
4393 
4394  $sql = "SELECT DISTINCT p.fk_soc";
4395  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
4396  $sql .= " WHERE p.fk_product = ".((int) $this->id);
4397  $sql .= " AND p.entity = ".((int) $conf->entity);
4398 
4399  $result = $this->db->query($sql);
4400  if ($result) {
4401  $num = $this->db->num_rows($result);
4402  $i = 0;
4403  while ($i < $num) {
4404  $obj = $this->db->fetch_object($result);
4405  $list[$i] = $obj->fk_soc;
4406  $i++;
4407  }
4408  }
4409 
4410  return $list;
4411  }
4412 
4413  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4421  public function clone_price($fromId, $toId)
4422  {
4423  global $conf, $user;
4424 
4425  $now = dol_now();
4426 
4427  $this->db->begin();
4428 
4429  // prices
4430  $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
4431  $sql .= " entity";
4432  $sql .= ", fk_product";
4433  $sql .= ", date_price";
4434  $sql .= ", price_level";
4435  $sql .= ", price";
4436  $sql .= ", price_ttc";
4437  $sql .= ", price_min";
4438  $sql .= ", price_min_ttc";
4439  $sql .= ", price_base_type";
4440  $sql .= ", default_vat_code";
4441  $sql .= ", tva_tx";
4442  $sql .= ", recuperableonly";
4443  $sql .= ", localtax1_tx";
4444  $sql .= ", localtax1_type";
4445  $sql .= ", localtax2_tx";
4446  $sql .= ", localtax2_type";
4447  $sql .= ", fk_user_author";
4448  $sql .= ", tosell";
4449  $sql .= ", price_by_qty";
4450  $sql .= ", fk_price_expression";
4451  $sql .= ", fk_multicurrency";
4452  $sql .= ", multicurrency_code";
4453  $sql .= ", multicurrency_tx";
4454  $sql .= ", multicurrency_price";
4455  $sql .= ", multicurrency_price_ttc";
4456  $sql .= ")";
4457  $sql .= " SELECT";
4458  $sql .= " entity";
4459  $sql .= ", ".$toId;
4460  $sql .= ", '".$this->db->idate($now)."'";
4461  $sql .= ", price_level";
4462  $sql .= ", price";
4463  $sql .= ", price_ttc";
4464  $sql .= ", price_min";
4465  $sql .= ", price_min_ttc";
4466  $sql .= ", price_base_type";
4467  $sql .= ", default_vat_code";
4468  $sql .= ", tva_tx";
4469  $sql .= ", recuperableonly";
4470  $sql .= ", localtax1_tx";
4471  $sql .= ", localtax1_type";
4472  $sql .= ", localtax2_tx";
4473  $sql .= ", localtax2_type";
4474  $sql .= ", ".$user->id;
4475  $sql .= ", tosell";
4476  $sql .= ", price_by_qty";
4477  $sql .= ", fk_price_expression";
4478  $sql .= ", fk_multicurrency";
4479  $sql .= ", multicurrency_code";
4480  $sql .= ", multicurrency_tx";
4481  $sql .= ", multicurrency_price";
4482  $sql .= ", multicurrency_price_ttc";
4483  $sql .= " FROM ".$this->db->prefix()."product_price";
4484  $sql .= " WHERE fk_product = ".((int) $fromId);
4485  $sql .= " ORDER BY date_price DESC";
4486  if ($conf->global->PRODUIT_MULTIPRICES_LIMIT > 0) {
4487  $sql .= " LIMIT ".$conf->global->PRODUIT_MULTIPRICES_LIMIT;
4488  }
4489 
4490  dol_syslog(__METHOD__, LOG_DEBUG);
4491  $resql = $this->db->query($sql);
4492  if (!$resql) {
4493  $this->db->rollback();
4494  return -1;
4495  }
4496 
4497  $this->db->commit();
4498  return 1;
4499  }
4500 
4501  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4509  public function clone_associations($fromId, $toId)
4510  {
4511  // phpcs:enable
4512  $this->db->begin();
4513 
4514  $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty)';
4515  $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".$this->db->prefix()."product_association";
4516  $sql .= " WHERE fk_product_pere = ".((int) $fromId);
4517 
4518  dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
4519  if (!$this->db->query($sql)) {
4520  $this->db->rollback();
4521  return -1;
4522  }
4523 
4524  $this->db->commit();
4525  return 1;
4526  }
4527 
4528  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4536  public function clone_fournisseurs($fromId, $toId)
4537  {
4538  // phpcs:enable
4539  $this->db->begin();
4540 
4541  $now = dol_now();
4542 
4543  // les fournisseurs
4544  /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
4545  . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
4546  . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author"
4547  . " FROM ".$this->db->prefix()."product_fournisseur"
4548  . " WHERE fk_product = ".((int) $fromId);
4549 
4550  if ( ! $this->db->query($sql ) )
4551  {
4552  $this->db->rollback();
4553  return -1;
4554  }*/
4555 
4556  // les prix de fournisseurs.
4557  $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
4558  $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)";
4559  $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user";
4560  $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
4561  $sql .= " WHERE fk_product = ".((int) $fromId);
4562 
4563  dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
4564  $resql = $this->db->query($sql);
4565  if (!$resql) {
4566  $this->db->rollback();
4567  return -1;
4568  } else {
4569  $this->db->commit();
4570  return 1;
4571  }
4572  }
4573 
4574  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4587  public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
4588  {
4589  // phpcs:enable
4590  global $conf, $langs;
4591 
4592  $tmpproduct = null;
4593  //var_dump($prod);
4594  foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
4595  if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
4596  $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
4597  $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
4598  $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
4599  $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
4600  $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
4601 
4602  if ($multiply < 1) {
4603  $multiply = 1;
4604  }
4605 
4606  //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
4607  if (is_null($tmpproduct)) {
4608  $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
4609  }
4610  $tmpproduct->fetch($id); // Load product to get ->ref
4611 
4612  if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
4613  $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
4614  }
4615 
4616  $this->res[] = array(
4617  'id'=>$id, // Id product
4618  'id_parent'=>$id_parent,
4619  'ref'=>$tmpproduct->ref, // Ref product
4620  'nb'=>$nb, // Nb of units that compose parent product
4621  'nb_total'=>$nb * $multiply, // Nb of units for all nb of product
4622  'stock'=>$tmpproduct->stock_reel, // Stock
4623  'stock_alert'=>$tmpproduct->seuil_stock_alerte, // Stock alert
4624  'label'=>$label,
4625  'fullpath'=>$compl_path.$label, // Label
4626  'type'=>$type, // Nb of units that compose parent product
4627  'desiredstock'=>$tmpproduct->desiredstock,
4628  'level'=>$level,
4629  'incdec'=>$incdec,
4630  'entity'=>$tmpproduct->entity
4631  );
4632 
4633  // Recursive call if there is childs to child
4634  if (isset($desc_pere['childs']) && is_array($desc_pere['childs'])) {
4635  //print 'YYY We go down for '.$desc_pere[3]." -> \n";
4636  $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load);
4637  }
4638  }
4639  }
4640  }
4641 
4642  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4651  public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
4652  {
4653  // phpcs:enable
4654  $this->res = array();
4655  if (isset($this->sousprods) && is_array($this->sousprods)) {
4656  foreach ($this->sousprods as $prod_name => $desc_product) {
4657  if (is_array($desc_product)) {
4658  $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load);
4659  }
4660  }
4661  }
4662  //var_dump($this->res);
4663  return $this->res;
4664  }
4665 
4673  public function hasFatherOrChild($mode = 0)
4674  {
4675  $nb = 0;
4676 
4677  $sql = "SELECT COUNT(pa.rowid) as nb";
4678  $sql .= " FROM ".$this->db->prefix()."product_association as pa";
4679  if ($mode == 0) {
4680  $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
4681  } elseif ($mode == -1) {
4682  $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)
4683  } elseif ($mode == 1) {
4684  $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)
4685  }
4686 
4687  $resql = $this->db->query($sql);
4688  if ($resql) {
4689  $obj = $this->db->fetch_object($resql);
4690  if ($obj) {
4691  $nb = $obj->nb;
4692  }
4693  } else {
4694  return -1;
4695  }
4696 
4697  return $nb;
4698  }
4699 
4705  public function hasVariants()
4706  {
4707  $nb = 0;
4708  $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
4709  $sql .= " AND entity IN (".getEntity('product').")";
4710 
4711  $resql = $this->db->query($sql);
4712  if ($resql) {
4713  $obj = $this->db->fetch_object($resql);
4714  if ($obj) {
4715  $nb = $obj->nb;
4716  }
4717  }
4718 
4719  return $nb;
4720  }
4721 
4722 
4728  public function isVariant()
4729  {
4730  global $conf;
4731  if (!empty($conf->variants->enabled)) {
4732  $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
4733 
4734  $query = $this->db->query($sql);
4735 
4736  if ($query) {
4737  if (!$this->db->num_rows($query)) {
4738  return false;
4739  }
4740  return true;
4741  } else {
4742  dol_print_error($this->db);
4743  return -1;
4744  }
4745  } else {
4746  return false;
4747  }
4748  }
4749 
4756  public function getFather()
4757  {
4758  $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";
4759  $sql .= ", p.tosell as status, p.tobuy as status_buy";
4760  $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
4761  $sql .= " ".$this->db->prefix()."product as p";
4762  $sql .= " WHERE p.rowid = pa.fk_product_pere";
4763  $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
4764 
4765  $res = $this->db->query($sql);
4766  if ($res) {
4767  $prods = array();
4768  while ($record = $this->db->fetch_array($res)) {
4769  // $record['id'] = $record['rowid'] = id of father
4770  $prods[$record['id']]['id'] = $record['rowid'];
4771  $prods[$record['id']]['ref'] = $record['ref'];
4772  $prods[$record['id']]['label'] = $record['label'];
4773  $prods[$record['id']]['qty'] = $record['qty'];
4774  $prods[$record['id']]['incdec'] = $record['incdec'];
4775  $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
4776  $prods[$record['id']]['entity'] = $record['entity'];
4777  $prods[$record['id']]['status'] = $record['status'];
4778  $prods[$record['id']]['status_buy'] = $record['status_buy'];
4779  }
4780  return $prods;
4781  } else {
4782  dol_print_error($this->db);
4783  return -1;
4784  }
4785  }
4786 
4787 
4797  public function getChildsArbo($id, $firstlevelonly = 0, $level = 1, $parents = array())
4798  {
4799  global $alreadyfound;
4800 
4801  if (empty($id)) {
4802  return array();
4803  }
4804 
4805  $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
4806  $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
4807  $sql .= " pa.rowid as fk_association, pa.rang";
4808  $sql .= " FROM ".$this->db->prefix()."product as p,";
4809  $sql .= " ".$this->db->prefix()."product_association as pa";
4810  $sql .= " WHERE p.rowid = pa.fk_product_fils";
4811  $sql .= " AND pa.fk_product_pere = ".((int) $id);
4812  $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
4813  $sql.= " ORDER BY pa.rang";
4814 
4815  dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level. ' parents='.(is_array($parents)?implode(',', $parents):$parents), LOG_DEBUG);
4816 
4817  if ($level == 1) {
4818  $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
4819  }
4820  // Protection against infinite loop
4821  if ($level > 30) {
4822  return array();
4823  }
4824 
4825  $res = $this->db->query($sql);
4826  if ($res) {
4827  $prods = array();
4828  while ($rec = $this->db->fetch_array($res)) {
4829  if (!empty($alreadyfound[$rec['rowid']])) {
4830  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);
4831  if (in_array($rec['id'], $parents)) {
4832  continue; // We discard this child if it is already found at a higher level in tree in the same branch.
4833  }
4834  }
4835  $alreadyfound[$rec['rowid']] = 1;
4836  $prods[$rec['rowid']] = array(
4837  0=>$rec['rowid'],
4838  1=>$rec['qty'],
4839  2=>$rec['fk_product_type'],
4840  3=>$this->db->escape($rec['label']),
4841  4=>$rec['incdec'],
4842  5=>$rec['ref'],
4843  6=>$rec['fk_association'],
4844  7=>$rec['rang']
4845  );
4846  //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
4847  //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
4848  if (empty($firstlevelonly)) {
4849  $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1, array_push($parents, $rec['rowid']));
4850  foreach ($listofchilds as $keyChild => $valueChild) {
4851  $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
4852  }
4853  }
4854  }
4855 
4856  return $prods;
4857  } else {
4858  dol_print_error($this->db);
4859  return -1;
4860  }
4861  }
4862 
4863  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4870  public function get_sousproduits_arbo()
4871  {
4872  // phpcs:enable
4873  $parent = array();
4874 
4875  foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
4876  $parent[$this->label][$keyChild] = $valueChild;
4877  }
4878  foreach ($parent as $key => $value) { // key=label, value is array of childs
4879  $this->sousprods[$key] = $value;
4880  }
4881  }
4882 
4893  public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0)
4894  {
4895  global $conf, $langs, $hookmanager;
4896  include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
4897 
4898  $result = ''; $label = '';
4899 
4900  $newref = $this->ref;
4901  if ($maxlength) {
4902  $newref = dol_trunc($newref, $maxlength, 'middle');
4903  }
4904 
4905  if (!empty($this->entity)) {
4906  $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
4907  if ($this->nbphoto > 0) {
4908  $label .= '<div class="photointooltip floatright">';
4909  $label .= $tmpphoto;
4910  $label .= '</div>';
4911  //$label .= '<div style="clear: both;"></div>';
4912  }
4913  }
4914 
4915  if ($this->type == Product::TYPE_PRODUCT) {
4916  $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
4917  } elseif ($this->type == Product::TYPE_SERVICE) {
4918  $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
4919  }
4920  if (isset($this->status) && isset($this->status_buy)) {
4921  $label .= ' '.$this->getLibStatut(5, 0);
4922  $label .= ' '.$this->getLibStatut(5, 1);
4923  }
4924 
4925  if (!empty($this->ref)) {
4926  $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
4927  }
4928  if (!empty($this->label)) {
4929  $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
4930  }
4931  if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
4932  if (!empty($conf->productbatch->enabled)) {
4933  $langs->load("productbatch");
4934  $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
4935  }
4936  }
4937  if (!empty($conf->barcode->enabled)) {
4938  $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
4939  }
4940 
4941  if ($this->type == Product::TYPE_PRODUCT) {
4942  if ($this->weight) {
4943  $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
4944  }
4945  $labelsize = "";
4946  if ($this->length) {
4947  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
4948  }
4949  if ($this->width) {
4950  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
4951  }
4952  if ($this->height) {
4953  $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
4954  }
4955  if ($labelsize) {
4956  $label .= "<br>".$labelsize;
4957  }
4958 
4959  $labelsurfacevolume = "";
4960  if ($this->surface) {
4961  $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
4962  }
4963  if ($this->volume) {
4964  $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
4965  }
4966  if ($labelsurfacevolume) {
4967  $label .= "<br>".$labelsurfacevolume;
4968  }
4969  }
4970  if (!empty($this->pmp) && $this->pmp) {
4971  $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
4972  }
4973 
4974  if (!empty($conf->accounting->enabled)) {
4975  if ($this->status && isset($this->accountancy_code_sell)) {
4976  include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
4977  $label .= '<br>';
4978  $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
4979  $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
4980  $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
4981  }
4982  if ($this->status_buy && isset($this->accountancy_code_buy)) {
4983  include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
4984  if (empty($this->status)) {
4985  $label .= '<br>';
4986  }
4987  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
4988  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
4989  $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
4990  }
4991  }
4992 
4993  $linkclose = '';
4994  if (empty($notooltip)) {
4995  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
4996  $label = $langs->trans("ShowProduct");
4997  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
4998  }
4999 
5000  $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
5001  $linkclose .= ' class="nowraponall classfortooltip"';
5002  } else {
5003  $linkclose = ' class="nowraponall"';
5004  }
5005 
5006  if ($option == 'supplier' || $option == 'category') {
5007  $url = DOL_URL_ROOT.'/product/fournisseurs.php?id='.$this->id;
5008  } elseif ($option == 'stock') {
5009  $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
5010  } elseif ($option == 'composition') {
5011  $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
5012  } else {
5013  $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
5014  }
5015 
5016  if ($option !== 'nolink') {
5017  // Add param to save lastsearch_values or not
5018  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
5019  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
5020  $add_save_lastsearch_values = 1;
5021  }
5022  if ($add_save_lastsearch_values) {
5023  $url .= '&save_lastsearch_values=1';
5024  }
5025  }
5026 
5027  $linkstart = '<a href="'.$url.'"';
5028  $linkstart .= $linkclose.'>';
5029  $linkend = '</a>';
5030 
5031  $result .= $linkstart;
5032  if ($withpicto) {
5033  if ($this->type == Product::TYPE_PRODUCT) {
5034  $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
5035  }
5036  if ($this->type == Product::TYPE_SERVICE) {
5037  $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
5038  }
5039  }
5040  $result .= $newref;
5041  $result .= $linkend;
5042 
5043  global $action;
5044  $hookmanager->initHooks(array('productdao'));
5045  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
5046  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5047  if ($reshook > 0) {
5048  $result = $hookmanager->resPrint;
5049  } else {
5050  $result .= $hookmanager->resPrint;
5051  }
5052 
5053  return $result;
5054  }
5055 
5056 
5067  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
5068  {
5069  global $conf, $user, $langs;
5070 
5071  $langs->load("products");
5072  $outputlangs->load("products");
5073 
5074  // Positionne le modele sur le nom du modele a utiliser
5075  if (!dol_strlen($modele)) {
5076  if (!empty($conf->global->PRODUCT_ADDON_PDF)) {
5077  $modele = $conf->global->PRODUCT_ADDON_PDF;
5078  } else {
5079  $modele = 'strato';
5080  }
5081  }
5082 
5083  $modelpath = "core/modules/product/doc/";
5084 
5085  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
5086  }
5087 
5095  public function getLibStatut($mode = 0, $type = 0)
5096  {
5097  switch ($type) {
5098  case 0:
5099  return $this->LibStatut($this->status, $mode, $type);
5100  case 1:
5101  return $this->LibStatut($this->status_buy, $mode, $type);
5102  case 2:
5103  return $this->LibStatut($this->status_batch, $mode, $type);
5104  default:
5105  //Simulate previous behavior but should return an error string
5106  return $this->LibStatut($this->status_buy, $mode, $type);
5107  }
5108  }
5109 
5110  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5119  public function LibStatut($status, $mode = 0, $type = 0)
5120  {
5121  // phpcs:enable
5122  global $conf, $langs;
5123 
5124  $labelStatus = $labelStatusShort = '';
5125 
5126  $langs->load('products');
5127  if (!empty($conf->productbatch->enabled)) {
5128  $langs->load("productbatch");
5129  }
5130 
5131  if ($type == 2) {
5132  switch ($mode) {
5133  case 0:
5134  $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
5135  return dolGetStatus($label);
5136  case 1:
5137  $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
5138  return dolGetStatus($label);
5139  case 2:
5140  return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
5141  case 3:
5142  return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
5143  case 4:
5144  return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
5145  case 5:
5146  return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
5147  default:
5148  return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
5149  }
5150  }
5151 
5152  $statuttrans = empty($status) ? 'status5' : 'status4';
5153 
5154  if ($status == 0) {
5155  // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
5156  if ($type == 0) {
5157  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
5158  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
5159  } elseif ($type == 1) {
5160  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
5161  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
5162  } elseif ($type == 2) {
5163  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
5164  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
5165  }
5166  } elseif ($status == 1) {
5167  // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
5168  if ($type == 0) {
5169  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
5170  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
5171  } elseif ($type == 1) {
5172  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
5173  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
5174  } elseif ($type == 2) {
5175  $labelStatus = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial'));
5176  $labelStatusShort = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort'));
5177  }
5178  } elseif ( $type == 2 && $status == 2 ) {
5179  $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
5180  $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
5181  }
5182 
5183  if ($mode > 6) {
5184  return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
5185  } else {
5186  return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
5187  }
5188  }
5189 
5190 
5196  public function getLibFinished()
5197  {
5198  global $langs;
5199  $langs->load('products');
5200 
5201  if (isset($this->finished) && $this->finished >= 0) {
5202  $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
5203  $resql = $this->db->query($sql);
5204  if ($resql && $this->db->num_rows($resql) > 0) {
5205  $res = $this->db->fetch_array($resql);
5206  $label = $langs->trans($res['label']);
5207  $this->db->free($resql);
5208  return $label;
5209  } else {
5210  $this->error = $this->db->error().' sql='.$sql;
5211  dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
5212  return -1;
5213  }
5214  }
5215 
5216  return '';
5217  }
5218 
5219 
5220  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5237  public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
5238  {
5239  // phpcs:enable
5240  if ($id_entrepot) {
5241  $this->db->begin();
5242 
5243  include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
5244 
5245  if ($nbpiece < 0) {
5246  if (!$movement) {
5247  $movement = 1;
5248  }
5249  $nbpiece = abs($nbpiece);
5250  }
5251 
5252  $op[0] = "+".trim($nbpiece);
5253  $op[1] = "-".trim($nbpiece);
5254 
5255  $movementstock = new MouvementStock($this->db);
5256  $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->origin_id
5257  $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
5258 
5259  if ($result >= 0) {
5260  if ($extrafields) {
5261  $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
5262  $movementstock->array_options = $array_options;
5263  $movementstock->insertExtraFields();
5264  }
5265  $this->db->commit();
5266  return 1;
5267  } else {
5268  $this->error = $movementstock->error;
5269  $this->errors = $movementstock->errors;
5270 
5271  $this->db->rollback();
5272  return -1;
5273  }
5274  }
5275  }
5276 
5277  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5297  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)
5298  {
5299  // phpcs:enable
5300  if ($id_entrepot) {
5301  $this->db->begin();
5302 
5303  include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
5304 
5305  if ($nbpiece < 0) {
5306  if (!$movement) {
5307  $movement = 1;
5308  }
5309  $nbpiece = abs($nbpiece);
5310  }
5311 
5312  $op[0] = "+".trim($nbpiece);
5313  $op[1] = "-".trim($nbpiece);
5314 
5315  $movementstock = new MouvementStock($this->db);
5316  $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->fk_origin
5317  $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct);
5318 
5319  if ($result >= 0) {
5320  if ($extrafields) {
5321  $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
5322  $movementstock->array_options = $array_options;
5323  $movementstock->insertExtraFields();
5324  }
5325  $this->db->commit();
5326  return 1;
5327  } else {
5328  $this->error = $movementstock->error;
5329  $this->errors = $movementstock->errors;
5330 
5331  $this->db->rollback();
5332  return -1;
5333  }
5334  }
5335  }
5336 
5337  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5349  public function load_stock($option = '', $includedraftpoforvirtual = null)
5350  {
5351  // phpcs:enable
5352  global $conf;
5353 
5354  $this->stock_reel = 0;
5355  $this->stock_warehouse = array();
5356  $this->stock_theorique = 0;
5357 
5358  // Set filter on warehouse status
5359  $warehouseStatus = array();
5360  if (preg_match('/warehouseclosed/', $option)) {
5362  }
5363  if (preg_match('/warehouseopen/', $option)) {
5365  }
5366  if (preg_match('/warehouseinternal/', $option)) {
5367  if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
5369  } else {
5371  }
5372  }
5373 
5374  $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
5375  $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
5376  $sql .= ", ".$this->db->prefix()."entrepot as w";
5377  $sql .= " WHERE w.entity IN (".getEntity('stock').")";
5378  $sql .= " AND w.rowid = ps.fk_entrepot";
5379  $sql .= " AND ps.fk_product = ".((int) $this->id);
5380  if (count($warehouseStatus)) {
5381  $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
5382  }
5383 
5384  $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;
5385 
5386  dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
5387  $result = $this->db->query($sql);
5388  if ($result) {
5389  $num = $this->db->num_rows($result);
5390  $i = 0;
5391  if ($num > 0) {
5392  while ($i < $num) {
5393  $row = $this->db->fetch_object($result);
5394  $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
5395  $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
5396  $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
5397  if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
5398  $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
5399  }
5400  $this->stock_reel += $row->reel;
5401  $i++;
5402  }
5403  }
5404  $this->db->free($result);
5405 
5406  if (!preg_match('/novirtual/', $option)) {
5407  $this->load_virtual_stock($includedraftpoforvirtual); // This also load all arrays stats_xxx...
5408  }
5409 
5410  return 1;
5411  } else {
5412  $this->error = $this->db->lasterror();
5413  return -1;
5414  }
5415  }
5416 
5417 
5418  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5427  public function load_virtual_stock($includedraftpoforvirtual = null)
5428  {
5429  // phpcs:enable
5430  global $conf, $hookmanager, $action;
5431 
5432  $stock_commande_client = 0;
5433  $stock_commande_fournisseur = 0;
5434  $stock_sending_client = 0;
5435  $stock_reception_fournisseur = 0;
5436  $stock_inproduction = 0;
5437 
5438  //dol_syslog("load_virtual_stock");
5439 
5440  if (!empty($conf->commande->enabled)) {
5441  $result = $this->load_stats_commande(0, '1,2', 1);
5442  if ($result < 0) {
5443  dol_print_error($this->db, $this->error);
5444  }
5445  $stock_commande_client = $this->stats_commande['qty'];
5446  }
5447  if (!empty($conf->expedition->enabled)) {
5448  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
5449  $filterShipmentStatus = '';
5450  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
5451  $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
5452  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
5453  $filterShipmentStatus = Expedition::STATUS_CLOSED;
5454  }
5455  $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
5456  if ($result < 0) {
5457  dol_print_error($this->db, $this->error);
5458  }
5459  $stock_sending_client = $this->stats_expedition['qty'];
5460  }
5461  if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) {
5462  $filterStatus = empty($conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK) ? '3,4' : $conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK;
5463  if (isset($includedraftpoforvirtual)) {
5464  $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
5465  }
5466  $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1);
5467  if ($result < 0) {
5468  dol_print_error($this->db, $this->error);
5469  }
5470  $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
5471  }
5472  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)) {
5473  // Case module reception is not used
5474  $filterStatus = '4';
5475  if (isset($includedraftpoforvirtual)) {
5476  $filterStatus = '0,'.$filterStatus;
5477  }
5478  $result = $this->load_stats_reception(0, $filterStatus, 1);
5479  if ($result < 0) {
5480  dol_print_error($this->db, $this->error);
5481  }
5482  $stock_reception_fournisseur = $this->stats_reception['qty'];
5483  }
5484  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)) {
5485  // Case module reception is used
5486  $filterStatus = '4';
5487  if (isset($includedraftpoforvirtual)) {
5488  $filterStatus = '0,'.$filterStatus;
5489  }
5490  $result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used.
5491  if ($result < 0) {
5492  dol_print_error($this->db, $this->error);
5493  }
5494  $stock_reception_fournisseur = $this->stats_reception['qty'];
5495  }
5496  if (!empty($conf->mrp->enabled)) {
5497  $result = $this->load_stats_inproduction(0, '1,2', 1);
5498  if ($result < 0) {
5499  dol_print_error($this->db, $this->error);
5500  }
5501  $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
5502  }
5503 
5504  $this->stock_theorique = $this->stock_reel + $stock_inproduction;
5505 
5506  // Stock decrease mode
5507  if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
5508  $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
5509  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) {
5510  $this->stock_theorique += 0;
5511  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
5512  $this->stock_theorique -= $stock_commande_client;
5513  }
5514  // Stock Increase mode
5515  if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
5516  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5517  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
5518  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5519  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
5520  $this->stock_theorique -= $stock_reception_fournisseur;
5521  } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
5522  $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
5523  }
5524 
5525  if (!is_object($hookmanager)) {
5526  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
5527  $hookmanager = new HookManager($this->db);
5528  }
5529  $hookmanager->initHooks(array('productdao'));
5530  $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
5531  // Note that $action and $object may have been modified by some hooks
5532  $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
5533  if ($reshook > 0) {
5534  $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
5535  }
5536 
5537  return 1;
5538  }
5539 
5540 
5548  public function loadBatchInfo($batch)
5549  {
5550  $result = array();
5551 
5552  $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";
5553  $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
5554  $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby";
5555  dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
5556  $resql = $this->db->query($sql);
5557  if ($resql) {
5558  $num = $this->db->num_rows($resql);
5559  $i = 0;
5560  while ($i < $num) {
5561  $obj = $this->db->fetch_object($resql);
5562  $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
5563  $i++;
5564  }
5565  return $result;
5566  } else {
5567  dol_print_error($this->db);
5568  $this->db->rollback();
5569  return array();
5570  }
5571  }
5572 
5573  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5581  public function add_photo($sdir, $file)
5582  {
5583  // phpcs:enable
5584  global $conf;
5585 
5586  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5587 
5588  $result = 0;
5589 
5590  $dir = $sdir;
5591  if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
5592  $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
5593  } else {
5594  $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
5595  }
5596 
5597  dol_mkdir($dir);
5598 
5599  $dir_osencoded = $dir;
5600 
5601  if (is_dir($dir_osencoded)) {
5602  $originImage = $dir.'/'.$file['name'];
5603 
5604  // Cree fichier en taille origine
5605  $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
5606 
5607  if (file_exists(dol_osencode($originImage))) {
5608  // Create thumbs
5609  $this->addThumbs($originImage);
5610  }
5611  }
5612 
5613  if (is_numeric($result) && $result > 0) {
5614  return 1;
5615  } else {
5616  return -1;
5617  }
5618  }
5619 
5620  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5627  public function is_photo_available($sdir)
5628  {
5629  // phpcs:enable
5630  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5631  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5632 
5633  global $conf;
5634 
5635  $dir = $sdir;
5636  if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
5637  $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
5638  } else {
5639  $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
5640  }
5641 
5642  $nbphoto = 0;
5643 
5644  $dir_osencoded = dol_osencode($dir);
5645  if (file_exists($dir_osencoded)) {
5646  $handle = opendir($dir_osencoded);
5647  if (is_resource($handle)) {
5648  while (($file = readdir($handle)) !== false) {
5649  if (!utf8_check($file)) {
5650  $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
5651  }
5652  if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
5653  return true;
5654  }
5655  }
5656  }
5657  }
5658  return false;
5659  }
5660 
5661  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5669  public function liste_photos($dir, $nbmax = 0)
5670  {
5671  // phpcs:enable
5672  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5673  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5674 
5675  $nbphoto = 0;
5676  $tabobj = array();
5677 
5678  $dir_osencoded = dol_osencode($dir);
5679  $handle = @opendir($dir_osencoded);
5680  if (is_resource($handle)) {
5681  while (($file = readdir($handle)) !== false) {
5682  if (!utf8_check($file)) {
5683  $file = utf8_encode($file); // readdir returns ISO
5684  }
5685  if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
5686  $nbphoto++;
5687 
5688  // We forge name of thumb.
5689  $photo = $file;
5690  $photo_vignette = '';
5691  $regs = array();
5692  if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
5693  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
5694  }
5695 
5696  $dirthumb = $dir.'thumbs/';
5697 
5698  // Objet
5699  $obj = array();
5700  $obj['photo'] = $photo;
5701  if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
5702  $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
5703  } else {
5704  $obj['photo_vignette'] = "";
5705  }
5706 
5707  $tabobj[$nbphoto - 1] = $obj;
5708 
5709  // Do we have to continue with next photo ?
5710  if ($nbmax && $nbphoto >= $nbmax) {
5711  break;
5712  }
5713  }
5714  }
5715 
5716  closedir($handle);
5717  }
5718 
5719  return $tabobj;
5720  }
5721 
5722  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5729  public function delete_photo($file)
5730  {
5731  // phpcs:enable
5732  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5733  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5734 
5735  $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
5736  $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
5737  $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
5738 
5739  // On efface l'image d'origine
5740  dol_delete_file($file, 0, 0, 0, $this); // For triggers
5741 
5742  // Si elle existe, on efface la vignette
5743  if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
5744  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
5745  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
5746  dol_delete_file($dirthumb.$photo_vignette);
5747  }
5748 
5749  $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
5750  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
5751  dol_delete_file($dirthumb.$photo_vignette);
5752  }
5753  }
5754  }
5755 
5756  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5763  public function get_image_size($file)
5764  {
5765  // phpcs:enable
5766  $file_osencoded = dol_osencode($file);
5767  $infoImg = getimagesize($file_osencoded); // Get information on image
5768  $this->imgWidth = $infoImg[0]; // Largeur de l'image
5769  $this->imgHeight = $infoImg[1]; // Hauteur de l'image
5770  }
5771 
5772  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5778  public function load_state_board()
5779  {
5780  // phpcs:enable
5781  global $hookmanager;
5782 
5783  $this->nb = array();
5784 
5785  $sql = "SELECT count(p.rowid) as nb, fk_product_type";
5786  $sql .= " FROM ".$this->db->prefix()."product as p";
5787  $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
5788  // Add where from hooks
5789  if (is_object($hookmanager)) {
5790  $parameters = array();
5791  $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
5792  $sql .= $hookmanager->resPrint;
5793  }
5794  $sql .= ' GROUP BY fk_product_type';
5795 
5796  $resql = $this->db->query($sql);
5797  if ($resql) {
5798  while ($obj = $this->db->fetch_object($resql)) {
5799  if ($obj->fk_product_type == 1) {
5800  $this->nb["services"] = $obj->nb;
5801  } else {
5802  $this->nb["products"] = $obj->nb;
5803  }
5804  }
5805  $this->db->free($resql);
5806  return 1;
5807  } else {
5808  dol_print_error($this->db);
5809  $this->error = $this->db->error();
5810  return -1;
5811  }
5812  }
5813 
5819  public function isProduct()
5820  {
5821  return ($this->type == Product::TYPE_PRODUCT ? true : false);
5822  }
5823 
5829  public function isService()
5830  {
5831  return ($this->type == Product::TYPE_SERVICE ? true : false);
5832  }
5833 
5834 
5840  public function isMandatoryPeriod()
5841  {
5842  return ($this->mandatory_period == 1 ? true : false);
5843  }
5844  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5853  public function get_barcode($object, $type = '')
5854  {
5855  // phpcs:enable
5856  global $conf;
5857 
5858  $result = '';
5859  if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
5860  $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
5861  foreach ($dirsociete as $dirroot) {
5862  $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
5863  if ($res) {
5864  break;
5865  }
5866  }
5867  $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
5868  $mod = new $var;
5869 
5870  $result = $mod->getNextValue($object, $type);
5871 
5872  dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
5873  }
5874  return $result;
5875  }
5876 
5884  public function initAsSpecimen()
5885  {
5886  global $user, $langs, $conf, $mysoc;
5887 
5888  $now = dol_now();
5889 
5890  // Initialize parameters
5891  $this->specimen = 1;
5892  $this->id = 0;
5893  $this->ref = 'PRODUCT_SPEC';
5894  $this->label = 'PRODUCT SPECIMEN';
5895  $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
5896  $this->specimen = 1;
5897  $this->country_id = 1;
5898  $this->tosell = 1;
5899  $this->tobuy = 1;
5900  $this->tobatch = 0;
5901  $this->note = 'This is a comment (private)';
5902  $this->date_creation = $now;
5903  $this->date_modification = $now;
5904 
5905  $this->weight = 4;
5906  $this->weight_units = 3;
5907 
5908  $this->length = 5;
5909  $this->length_units = 1;
5910  $this->width = 6;
5911  $this->width_units = 0;
5912  $this->height = null;
5913  $this->height_units = null;
5914 
5915  $this->surface = 30;
5916  $this->surface_units = 0;
5917  $this->volume = 300;
5918  $this->volume_units = 0;
5919 
5920  $this->barcode = -1; // Create barcode automatically
5921  }
5922 
5929  public function getLabelOfUnit($type = 'long')
5930  {
5931  global $langs;
5932 
5933  if (!$this->fk_unit) {
5934  return '';
5935  }
5936 
5937  $langs->load('products');
5938 
5939  $label_type = 'label';
5940  if ($type == 'short') {
5941  $label_type = 'short_label';
5942  }
5943 
5944  $sql = "SELECT ".$label_type.", code from ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
5945 
5946  $resql = $this->db->query($sql);
5947  if ($resql && $this->db->num_rows($resql) > 0) {
5948  $res = $this->db->fetch_array($resql);
5949  $label = ($label_type == 'short_label' ? $res[$label_type] : 'unit'.$res['code']);
5950  $this->db->free($resql);
5951  return $label;
5952  } else {
5953  $this->error = $this->db->error();
5954  dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
5955  return -1;
5956  }
5957  }
5958 
5964  public function hasbatch()
5965  {
5966  return ($this->status_batch > 0 ? true : false);
5967  }
5968 
5969 
5970  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5976  public function min_recommended_price()
5977  {
5978  // phpcs:enable
5979  global $conf;
5980 
5981  $maxpricesupplier = 0;
5982 
5983  if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
5984  include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
5985  $product_fourn = new ProductFournisseur($this->db);
5986  $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
5987 
5988  if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
5989  foreach ($product_fourn_list as $productfourn) {
5990  if ($productfourn->fourn_unitprice > $maxpricesupplier) {
5991  $maxpricesupplier = $productfourn->fourn_unitprice;
5992  }
5993  }
5994 
5995  $maxpricesupplier *= $conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE;
5996  }
5997  }
5998 
5999  return $maxpricesupplier;
6000  }
6001 
6002 
6013  public function setCategories($categories)
6014  {
6015  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6016  return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
6017  }
6018 
6027  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
6028  {
6029  $tables = array(
6030  'product_customer_price',
6031  'product_customer_price_log'
6032  );
6033 
6034  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
6035  }
6036 
6048  public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
6049  {
6050  global $conf, $db;
6051 
6052  $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
6053  $query = $this->db->query($sql);
6054 
6055  $rules = array();
6056 
6057  while ($result = $this->db->fetch_object($query)) {
6058  $rules[$result->level] = $result;
6059  }
6060 
6061  //Because prices can be based on other level's prices, we temporarily store them
6062  $prices = array(
6063  1 => $baseprice
6064  );
6065 
6066  for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
6067  $price = $baseprice;
6068  $price_min = $baseprice;
6069 
6070  //We have to make sure it does exist and it is > 0
6071  //First price level only allows changing min_price
6072  if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
6073  $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
6074  }
6075 
6076  $prices[$i] = $price;
6077 
6078  //We have to make sure it does exist and it is > 0
6079  if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
6080  $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
6081  }
6082 
6083  //Little check to make sure the price is modified before triggering generation
6084  $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
6085  $check_type = ($baseprice == $this->multiprices_base_type[$i]);
6086 
6087  if ($check_amount && $check_type) {
6088  continue;
6089  }
6090 
6091  if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, true) < 0) {
6092  return -1;
6093  }
6094  }
6095 
6096  return 1;
6097  }
6098 
6104  public function getRights()
6105  {
6106  global $user;
6107 
6108  if ($this->isProduct()) {
6109  return $user->rights->produit;
6110  } else {
6111  return $user->rights->service;
6112  }
6113  }
6114 
6121  public function info($id)
6122  {
6123  $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,";
6124  $sql .= " p.fk_user_author, p.fk_user_modif";
6125  $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
6126  $sql .= " WHERE p.rowid = ".((int) $id);
6127 
6128  $result = $this->db->query($sql);
6129  if ($result) {
6130  if ($this->db->num_rows($result)) {
6131  $obj = $this->db->fetch_object($result);
6132 
6133  $this->id = $obj->rowid;
6134 
6135  if ($obj->fk_user_author) {
6136  $cuser = new User($this->db);
6137  $cuser->fetch($obj->fk_user_author);
6138  $this->user_creation = $cuser;
6139  }
6140 
6141  if ($obj->fk_user_modif) {
6142  $muser = new User($this->db);
6143  $muser->fetch($obj->fk_user_modif);
6144  $this->user_modification = $muser;
6145  }
6146 
6147  $this->ref = $obj->ref;
6148  $this->date_creation = $this->db->jdate($obj->date_creation);
6149  $this->date_modification = $this->db->jdate($obj->date_modification);
6150  }
6151 
6152  $this->db->free($result);
6153  } else {
6154  dol_print_error($this->db);
6155  }
6156  }
6157 }
6158 
6159 
6160 
6166 {
6167  public $picto = 'service';
6168 }
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
is_sousproduit($fk_parent, $fk_child)
Check if it is a sub-product into a kit.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
File of class to manage predefined price products or services by customer.
update_sousproduit($id_pere, $id_fils, $qty, $incdec=1)
Modify composed product.
load_stats_inproduction($socid=0, $filtrestatut= '', $forVirtualStock=0)
Charge tableau des stats production pour le produit/service.
$multiprices
Arrays for multiprices.
hasVariants()
Return if a product has variants or not.
Class to manage stock movements.
getLibFinished()
Retour label of nature of product.
get_nb_contract($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units in orders in which product is included.
load_stats_facture_fournisseur($socid=0)
Charge tableau des stats facture pour le produit/service.
get_nb_vente($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units or customers invoices in which product is included.
getRights()
Returns the rights used for this class.
const STATUS_CLOSED
Warehouse closed, inactive.
create($user, $notrigger=0)
Insert product into database.
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...
Class to parse product price expressions.
addThumbs($file)
Build thumb.
dol_mkdir($dir, $dataroot= '', $newmask= '')
Creation of a directory (this can create recursive subdir)
get_nb_achat($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units or supplier invoices in which product is included.
load_stats_commande($socid=0, $filtrestatut= '', $forVirtualStock=0)
Charge tableau des stats commande client pour le produit/service.
const STATUS_OPEN_ALL
Warehouse open and operations for customer shipping, supplier dispatch, internal stock transfers/corr...
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
isVariant()
Return if loaded product is a variant.
setPriceExpression($expression_id)
Sets the supplier price expression.
$conf db
API class for accounts.
Definition: inc.php:41
load_stats_propale($socid=0)
Charge tableau des stats propale pour le produit/service.
get_barcode($object, $type= '')
Get a barcode from the module to generate barcode values.
$multilangs
Array for multilangs.
$duration_unit
Exoiration unit.
loadBatchInfo($batch)
Load existing information about a serial.
$product_fourn_id
Id du fournisseur.
Class to manage products or services.
dol_now($mode= 'auto')
Return date for now.
const TYPE_ASSEMBLYKIT
Advanced feature: assembly kit.
$table_ref_field
{}
verify()
Check properties of product are ok (like name, barcode, ...).
Class to manage Dolibarr users.
Definition: user.class.php:44
load_stats_commande_fournisseur($socid=0, $filtrestatut= '', $forVirtualStock=0)
Charge tableau des stats commande fournisseur pour le produit/service.
const TYPE_STOCKKIT
Advanced feature: stock kit.
Class to manage Dolibarr database access.
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.
$weight
Metric of products.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setMultiLangs($user)
Update or add a translation for a product.
isProduct()
Return if object is a product.
clone_price($fromId, $toId)
Recopie les prix d&#39;un produit/service sur un autre.
const TYPE_SERVICE
Service.
getFather()
Return all parent products for current product (first level only)
$product_id_already_linked
Product ID already linked to a reference supplier.
dol_string_nospecial($str, $newstr= '_', $badcharstoreplace= '', $badcharstoremove= '')
Clean a string from all punctuation characters to use it as a ref or login.
Class to manage products or services.
load_stats_sending($socid=0, $filtrestatut= '', $forVirtualStock=0, $filterShipmentStatus= '')
Charge tableau des stats expedition client pour le produit/service.
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.
LibStatut($status, $mode=0, $type=0)
Return label of a given status.
const TYPE_PRODUCT
Regular product.
info($id)
Load information for tab info.
is_photo_available($sdir)
Return if at least one photo is available.
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&#39;arborescence des sousprodu...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
liste_photos($dir, $nbmax=0)
Return an array with all photos of product found on disk.
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller Note: This function applies same rules than get_default_tva.
del_sousproduit($fk_parent, $fk_child)
Remove a link between a subproduct and a parent product/service.
clone_fournisseurs($fromId, $toId)
Recopie les fournisseurs et prix fournisseurs d&#39;un produit/service sur un autre.
const STATUS_CLOSED
Closed status.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:58
$desiredstock
Ask for replenishment when $desiredstock &lt; $stock_reel.
$localtax1_tx
Other local taxes.
load_stats_facture($socid=0)
Charge tableau des stats facture pour le produit/service.
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...
$default_vat_code
Default VAT code for product (link to code into llx_c_tva but without foreign keys) ...
getLabelOfUnit($type= 'long')
Returns the text label from units dictionary.
$price_by_qty
Price by quantity arrays.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
initAsSpecimen()
Initialise an instance with random values.
Class to manage hooks.
list_suppliers()
Return list of suppliers providing the product or service.
$tva_tx
Default VAT rate of product.
$stock_warehouse
Contains detail of stock of product into each warehouse.
add_sousproduit($id_pere, $id_fils, $qty, $incdec=1)
Link a product/service to a parent product/service.
load_stats_bom($socid=0)
Charge tableau des stats OF pour le produit/service.
load_stock($option= '', $includedraftpoforvirtual=null)
Load information about stock of a product into -&gt;stock_reel, -&gt;stock_warehouse[] (including stock_war...
add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
Add a supplier price for the product.
const STATUS_OPEN_INTERNAL
Warehouse open and operations for stock transfers/corrections allowed (not for customer shipping and ...
check_barcode($valuetotest, $typefortest)
Check barcode.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
$tva_npr
French VAT NPR (0 or 1)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create a document onto disk according to template module.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
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:1382
delete_photo($file)
Delete a photo and its thumbs.
measuring_units_squared($unit)
Transform a given unit scale into the square of that unit, if known.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
get_image_size($file)
Load size of image file.
getChildsArbo($id, $firstlevelonly=0, $level=1, $parents=array())
Return childs of product $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
_log_price($user, $level=0)
Insert a track that we changed a customer price.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
min_recommended_price()
Return minimum product recommended price.
deleteExtraFields()
Delete all extra fields values for the current object.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
_get_stats($sql, $mode, $year=0)
Return an array formated for showing graphs.
utf8_check($str)
Check if a string is in UTF8.
Class ProductCombination Used to represent a product combination.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
isMandatoryPeriod()
Return if object have a constraint on mandatory_period.
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:1091
isService()
Return if object is a product.
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:476
add_photo($sdir, $file)
Move an uploaded file described into $file array into target directory $sdir.
const STATUS_VALIDATED
Validated status.
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
fetch($id= '', $ref= '', $ref_ext= '', $barcode= '', $ignore_expression=0, $ignore_price_load=0, $ignore_lang_load=0)
Load a product in memory from database.
load_virtual_stock($includedraftpoforvirtual=null)
Load value -&gt;stock_theorique of a product.
setAccountancyCode($type, $value)
Sets an accountancy code for a product.
load_stats_reception($socid=0, $filtrestatut= '', $forVirtualStock=0)
Charge tableau des stats réception fournisseur pour le produit/service.
delMultiLangs($langtodelete, $user)
Delete a language for this product.
Manage record for batch number management.
div float
Buy price without taxes.
Definition: style.css.php:809
$pmp
Average price value for product entry into stock (PMP)
print *****$script_file(".$version.") pid cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
call_trigger($triggerName, $user)
Call trigger based on this instance.
update($id, $user, $notrigger=false, $action= 'update', $updatetype=false)
Update a record into database.
measuring_units_cubed($unit)
Transform a given unit scale into the cube of that unit, if known.
getNomUrl($withpicto=0, $option= '', $maxlength=0, $save_lastsearch_value=-1, $notooltip=0)
Return clicable link of object (with eventually picto)
getArrayForPriceCompare($level=0)
used to check if price have really change to avoid log pollution
$object ref
Definition: info.php:77
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_arbo_each_prod($multiply=1, $ignore_stock_load=0)
Build the tree of subproducts into an array -&gt;res and return it.
get_sousproduits_arbo()
Return tree of all subproducts for product.
$imgWidth
Size of image.
get_buyprice($prodfournprice, $qty, $product_id=0, $fourn_ref= '', $fk_soc=0)
Read price used by a provider.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;…&#39; if string larger than length. ...
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
load_state_board()
Load indicators this-&gt;nb for the dashboard.
static findAll($dbs, $fk_product_stock, $with_qty=0, $fk_product=0)
Return all batch detail records for a given product and warehouse.
log_price_delete($user, $rowid)
Delete a price line.
clone_associations($fromId, $toId)
Clone links between products.
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.
get_nb_order($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units in orders in which product is included.
setCategories($categories)
Sets object to supplied categories.
getMultiLangs()
Load array this-&gt;multilangs.
get_nb_mos($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units in orders in which product is included.
hasFatherOrChild($mode=0)
Count all parent and children products for current product (first level only)
load_stats_contrat($socid=0)
Charge tableau des stats contrat pour le produit/service.
check()
Check that ref and label are ok.
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous) ...
get_nb_ordersupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units in orders in which product is included.
getLibStatut($mode=0, $type=0)
Return label of status of object.
get_nb_propalsupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units in proposals in which product is included.
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.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
load_stats_proposal_supplier($socid=0)
Charge tableau des stats propale pour le produit/service.
getCountry($searchkey, $withcode= '', $dbtouse=0, $outputlangs= '', $entconv=1, $searchlabel= '')
Return country label, code or id from an id, code or label.
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:1230
generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
Generates prices for a product based on product multiprice generation rules.
get_nb_propal($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter= '')
Return nb of units in proposals in which product is included.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
Class to manage predefined suppliers products.
load_stats_mo($socid=0)
Charge tableau des stats OF pour le produit/service.
getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp=0)
Return price of sell of a product for a seller/buyer/product.
measuringUnitString($unit, $measuring_style= '', $scale= '', $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
hasbatch()
Return if object has a sell-by date or eat-by date.
load_stats_facturerec($socid=0)
Charge tableau des stats facture recurrentes pour le produit/service.
__construct($db)
Constructor.