dolibarr  19.0.0-dev
api_products.class.php
1 <?php
2 /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3  * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
19 use Luracast\Restler\RestException;
20 
21 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
22 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
23 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
24 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
25 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
26 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
27 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
28 
35 class Products extends DolibarrApi
36 {
40  public static $FIELDS = array(
41  'ref',
42  'label'
43  );
44 
48  public $product;
49 
53  public $productsupplier;
54 
58  public function __construct()
59  {
60  global $db, $conf;
61 
62  $this->db = $db;
63  $this->product = new Product($this->db);
64  $this->productsupplier = new ProductFournisseur($this->db);
65  }
66 
83  public function get($id, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
84  {
85  return $this->_fetch($id, '', '', '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
86  }
87 
107  public function getByRef($ref, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
108  {
109  return $this->_fetch('', $ref, '', '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
110  }
111 
131  public function getByRefExt($ref_ext, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
132  {
133  return $this->_fetch('', '', $ref_ext, '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
134  }
135 
155  public function getByBarcode($barcode, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
156  {
157  return $this->_fetch('', '', '', $barcode, $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
158  }
159 
178  public function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false, $variant_filter = 0, $pagination_data = false, $includestockdata = 0)
179  {
180  global $db, $conf;
181 
182  if (!DolibarrApiAccess::$user->rights->produit->lire) {
183  throw new RestException(403);
184  }
185 
186  $obj_ret = array();
187 
188  $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
189 
190  $sql = "SELECT t.rowid, t.ref, t.ref_ext";
191  $sql .= " FROM ".$this->db->prefix()."product as t";
192  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields AS ef ON ef.fk_object = t.rowid"; // So we will be able to filter on extrafields
193  if ($category > 0) {
194  $sql .= ", ".$this->db->prefix()."categorie_product as c";
195  }
196  $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
197 
198  if ($variant_filter == 1) {
199  $sql .= ' AND t.rowid not in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
200  $sql .= ' AND t.rowid not in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
201  }
202  if ($variant_filter == 2) {
203  $sql .= ' AND t.rowid in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
204  }
205  if ($variant_filter == 3) {
206  $sql .= ' AND t.rowid in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
207  }
208 
209  // Select products of given category
210  if ($category > 0) {
211  $sql .= " AND c.fk_categorie = ".((int) $category);
212  $sql .= " AND c.fk_product = t.rowid";
213  }
214  if ($mode == 1) {
215  // Show only products
216  $sql .= " AND t.fk_product_type = 0";
217  } elseif ($mode == 2) {
218  // Show only services
219  $sql .= " AND t.fk_product_type = 1";
220  }
221 
222  // Add sql filters
223  if ($sqlfilters) {
224  $errormessage = '';
225  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
226  if ($errormessage) {
227  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
228  }
229  }
230 
231  //this query will return total products with the filters given
232  $sqlTotals = str_replace('SELECT t.rowid, t.ref, t.ref_ext', 'SELECT count(t.rowid) as total', $sql);
233 
234  $sql .= $this->db->order($sortfield, $sortorder);
235  if ($limit) {
236  if ($page < 0) {
237  $page = 0;
238  }
239  $offset = $limit * $page;
240 
241  $sql .= $this->db->plimit($limit + 1, $offset);
242  }
243 
244  $result = $this->db->query($sql);
245  if ($result) {
246  $num = $this->db->num_rows($result);
247  $min = min($num, ($limit <= 0 ? $num : $limit));
248  $i = 0;
249  while ($i < $min) {
250  $obj = $this->db->fetch_object($result);
251  if (!$ids_only) {
252  $product_static = new Product($this->db);
253  if ($product_static->fetch($obj->rowid)) {
254  if (!empty($includestockdata) && DolibarrApiAccess::$user->rights->stock->lire) {
255  $product_static->load_stock();
256 
257  if (is_array($product_static->stock_warehouse)) {
258  foreach ($product_static->stock_warehouse as $keytmp => $valtmp) {
259  if (isset($product_static->stock_warehouse[$keytmp]->detail_batch) && is_array($product_static->stock_warehouse[$keytmp]->detail_batch)) {
260  foreach ($product_static->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
261  unset($product_static->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
262  }
263  }
264  }
265  }
266  }
267 
268 
269  $obj_ret[] = $this->_cleanObjectDatas($product_static);
270  }
271  } else {
272  $obj_ret[] = $obj->rowid;
273  }
274  $i++;
275  }
276  } else {
277  throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
278  }
279  if (!count($obj_ret)) {
280  throw new RestException(404, 'No product found');
281  }
282 
283  //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
284  if ($pagination_data) {
285  $totalsResult = $this->db->query($sqlTotals);
286  $total = $this->db->fetch_object($totalsResult)->total;
287 
288  $tmp = $obj_ret;
289  $obj_ret = array();
290 
291  $obj_ret['data'] = $tmp;
292  $obj_ret['pagination'] = array(
293  'total' => (int) $total,
294  'page' => $page, //count starts from 0
295  'page_count' => ceil((int) $total/$limit),
296  'limit' => $limit
297  );
298  }
299 
300  return $obj_ret;
301  }
302 
309  public function post($request_data = null)
310  {
311  if (!DolibarrApiAccess::$user->rights->produit->creer) {
312  throw new RestException(401);
313  }
314  // Check mandatory fields
315  $result = $this->_validate($request_data);
316 
317  foreach ($request_data as $field => $value) {
318  $this->product->$field = $value;
319  }
320  if ($this->product->create(DolibarrApiAccess::$user) < 0) {
321  throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors));
322  }
323 
324  return $this->product->id;
325  }
326 
338  public function put($id, $request_data = null)
339  {
340  global $conf;
341 
342  if (!DolibarrApiAccess::$user->rights->produit->creer) {
343  throw new RestException(401);
344  }
345 
346  $result = $this->product->fetch($id);
347  if (!$result) {
348  throw new RestException(404, 'Product not found');
349  }
350 
351  if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
352  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
353  }
354 
355  $oldproduct = dol_clone($this->product);
356 
357  foreach ($request_data as $field => $value) {
358  if ($field == 'id') {
359  continue;
360  }
361  if ($field == 'stock_reel') {
362  throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead');
363  }
364  $this->product->$field = $value;
365  }
366 
367  $updatetype = false;
368  if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) {
369  $updatetype = true;
370  }
371 
372  $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype);
373 
374  // If price mode is 1 price per product
375  if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) {
376  // We update price only if it was changed
377  $pricemodified = false;
378  if ($this->product->price_base_type != $oldproduct->price_base_type) {
379  $pricemodified = true;
380  } else {
381  if ($this->product->tva_tx != $oldproduct->tva_tx) {
382  $pricemodified = true;
383  }
384  if ($this->product->tva_npr != $oldproduct->tva_npr) {
385  $pricemodified = true;
386  }
387  if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
388  $pricemodified = true;
389  }
390 
391  if ($this->product->price_base_type == 'TTC') {
392  if ($this->product->price_ttc != $oldproduct->price_ttc) {
393  $pricemodified = true;
394  }
395  if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
396  $pricemodified = true;
397  }
398  } else {
399  if ($this->product->price != $oldproduct->price) {
400  $pricemodified = true;
401  }
402  if ($this->product->price_min != $oldproduct->price_min) {
403  $pricemodified = true;
404  }
405  }
406  }
407 
408  if ($pricemodified) {
409  $newvat = $this->product->tva_tx;
410  $newnpr = $this->product->tva_npr;
411  $newvatsrccode = $this->product->default_vat_code;
412 
413  $newprice = $this->product->price;
414  $newpricemin = $this->product->price_min;
415  if ($this->product->price_base_type == 'TTC') {
416  $newprice = $this->product->price_ttc;
417  $newpricemin = $this->product->price_min_ttc;
418  }
419 
420  $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode);
421  }
422  }
423 
424  if ($result <= 0) {
425  throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors));
426  }
427 
428  return $this->get($id);
429  }
430 
437  public function delete($id)
438  {
439  if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
440  throw new RestException(401);
441  }
442  $result = $this->product->fetch($id);
443  if (!$result) {
444  throw new RestException(404, 'Product not found');
445  }
446 
447  if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
448  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
449  }
450 
451  // The Product::delete() method uses the global variable $user.
452  global $user;
453  $user = DolibarrApiAccess::$user;
454 
455  $res = $this->product->delete(DolibarrApiAccess::$user);
456  if ($res < 0) {
457  throw new RestException(500, "Can't delete, error occurs");
458  } elseif ($res == 0) {
459  throw new RestException(409, "Can't delete, that product is probably used");
460  }
461 
462  return array(
463  'success' => array(
464  'code' => 200,
465  'message' => 'Object deleted'
466  )
467  );
468  }
469 
482  public function getSubproducts($id)
483  {
484  if (!DolibarrApiAccess::$user->rights->produit->lire) {
485  throw new RestException(401);
486  }
487 
488  if (!DolibarrApi::_checkAccessToResource('product', $id)) {
489  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
490  }
491 
492  $childsArbo = $this->product->getChildsArbo($id, 1);
493 
494  $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
495  $childs = array();
496  foreach ($childsArbo as $values) {
497  $childs[] = array_combine($keys, $values);
498  }
499 
500  return $childs;
501  }
502 
520  public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1)
521  {
522  if (!DolibarrApiAccess::$user->rights->produit->creer) {
523  throw new RestException(401);
524  }
525 
526  if (!DolibarrApi::_checkAccessToResource('product', $id)) {
527  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
528  }
529 
530  $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec);
531  if ($result <= 0) {
532  throw new RestException(500, "Error adding product child");
533  }
534  return $result;
535  }
536 
550  public function delSubproducts($id, $subproduct_id)
551  {
552  if (!DolibarrApiAccess::$user->rights->produit->creer) {
553  throw new RestException(401);
554  }
555 
556  if (!DolibarrApi::_checkAccessToResource('product', $id)) {
557  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
558  }
559 
560  $result = $this->product->del_sousproduit($id, $subproduct_id);
561  if ($result <= 0) {
562  throw new RestException(500, "Error while removing product child");
563  }
564  return $result;
565  }
566 
567 
581  public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
582  {
583  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
584  throw new RestException(401);
585  }
586 
587  $categories = new Categorie($this->db);
588 
589  $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page);
590 
591  if (empty($result)) {
592  throw new RestException(404, 'No category found');
593  }
594 
595  if ($result < 0) {
596  throw new RestException(503, 'Error when retrieve category list : '.join(',', array_merge(array($categories->error), $categories->errors)));
597  }
598 
599  return $result;
600  }
601 
611  public function getCustomerPricesPerSegment($id)
612  {
613  global $conf;
614 
615  if (!DolibarrApiAccess::$user->rights->produit->lire) {
616  throw new RestException(401);
617  }
618 
619  if (empty($conf->global->PRODUIT_MULTIPRICES)) {
620  throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
621  }
622 
623  $result = $this->product->fetch($id);
624  if (!$result) {
625  throw new RestException(404, 'Product not found');
626  }
627 
628  if ($result < 0) {
629  throw new RestException(503, 'Error when retrieve prices list : '.join(',', array_merge(array($this->product->error), $this->product->errors)));
630  }
631 
632  return array(
633  'multiprices'=>$this->product->multiprices,
634  'multiprices_inc_tax'=>$this->product->multiprices_ttc,
635  'multiprices_min'=>$this->product->multiprices_min,
636  'multiprices_min_inc_tax'=>$this->product->multiprices_min_ttc,
637  'multiprices_vat'=>$this->product->multiprices_tva_tx,
638  'multiprices_base_type'=>$this->product->multiprices_base_type,
639  //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code
640  );
641  }
642 
653  public function getCustomerPricesPerCustomer($id, $thirdparty_id = '')
654  {
655  global $conf;
656 
657  if (!DolibarrApiAccess::$user->rights->produit->lire) {
658  throw new RestException(401);
659  }
660 
661  if (empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
662  throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
663  }
664 
665  $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
666  if ($socid > 0 && $socid != $thirdparty_id) {
667  throw new RestException(401, 'Getting prices for all customers or for the customer ID '.$thirdparty_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
668  }
669 
670  $result = $this->product->fetch($id);
671  if (!$result) {
672  throw new RestException(404, 'Product not found');
673  }
674 
675  if ($result > 0) {
676  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
677  $prodcustprice = new Productcustomerprice($this->db);
678  $filter = array();
679  $filter['t.fk_product'] = $id;
680  if ($thirdparty_id) {
681  $filter['t.fk_soc'] = $thirdparty_id;
682  }
683  $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
684  }
685 
686  if (empty($prodcustprice->lines)) {
687  throw new RestException(404, 'Prices not found');
688  }
689 
690  return $prodcustprice->lines;
691  }
692 
702  public function getCustomerPricesPerQuantity($id)
703  {
704  global $conf;
705 
706  if (!DolibarrApiAccess::$user->rights->produit->lire) {
707  throw new RestException(401);
708  }
709 
710  if (empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
711  throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
712  }
713 
714  $result = $this->product->fetch($id);
715  if (!$result) {
716  throw new RestException(404, 'Product not found');
717  }
718 
719  if ($result < 0) {
720  throw new RestException(503, 'Error when retrieve prices list : '.join(',', array_merge(array($this->product->error), $this->product->errors)));
721  }
722 
723  return array(
724  'prices_by_qty'=>$this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product
725  'prices_by_qty_list'=>$this->product->prices_by_qty_list[0]
726  );
727  }
728 
762  public function addPurchasePrice($id, $qty, $buyprice, $price_base_type, $fourn_id, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = null)
763  {
764  if (!DolibarrApiAccess::$user->rights->produit->creer) {
765  throw new RestException(401);
766  }
767 
768  $result = $this->productsupplier->fetch($id);
769  if (!$result) {
770  throw new RestException(404, 'Product not found');
771  }
772 
773  if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
774  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
775  }
776 
777  $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
778  if ($socid > 0 && $socid != $fourn_id) {
779  throw new RestException(401, 'Adding purchase price for the supplier ID '.$fourn_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
780  }
781 
782  $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty);
783  if ($result < 0) {
784  throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror());
785  }
786 
787  $fourn = new Fournisseur($this->db);
788  $result = $fourn->fetch($fourn_id);
789  if ($result <= 0) {
790  throw new RestException(404, 'Supplier not found');
791  }
792 
793  // Clean data
794  $ref_fourn = sanitizeVal($ref_fourn, 'alphanohtml');
795  $desc_fourn = sanitizeVal($desc_fourn, 'restricthtml');
796  $barcode = sanitizeVal($barcode, 'alphanohtml');
797 
798  $result = $this->productsupplier->update_buyprice($qty, $buyprice, DolibarrApiAccess::$user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges, $remise_percent, $remise, $newnpr, $delivery_time_days, $supplier_reputation, $localtaxes_array, $newdefaultvatcode, $multicurrency_buyprice, $multicurrency_price_base_type, $multicurrency_tx, $multicurrency_code, $desc_fourn, $barcode, $fk_barcode_type);
799 
800  if ($result <= 0) {
801  throw new RestException(500, "Error updating buy price : ".$this->db->lasterror());
802  }
803  return (int) $this->productsupplier->product_fourn_price_id;
804  }
805 
820  public function deletePurchasePrice($id, $priceid)
821  {
822  if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
823  throw new RestException(401);
824  }
825  $result = $this->productsupplier->fetch($id);
826  if (!$result) {
827  throw new RestException(404, 'Product not found');
828  }
829 
830  if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
831  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
832  }
833 
834  $resultsupplier = 0;
835  if ($result > 0) {
836  $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid);
837  }
838 
839  return $resultsupplier;
840  }
841 
857  public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '')
858  {
859  global $db, $conf;
860 
861  if (!DolibarrApiAccess::$user->rights->produit->lire) {
862  throw new RestException(401);
863  }
864 
865  $obj_ret = array();
866 
867  // Force id of company for external users
868  $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
869  if ($socid > 0) {
870  if ($supplier != $socid || empty($supplier)) {
871  throw new RestException(401, 'As an external user, you can request only for your supplier id = '.$socid);
872  }
873  }
874 
875  $sql = "SELECT t.rowid, t.ref, t.ref_ext";
876  $sql .= " FROM ".MAIN_DB_PREFIX."product AS t LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
877 
878  if ($category > 0) {
879  $sql .= ", ".$this->db->prefix()."categorie_product as c";
880  }
881  $sql .= ", ".$this->db->prefix()."product_fournisseur_price as s";
882 
883  $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
884 
885  if ($supplier > 0) {
886  $sql .= " AND s.fk_soc = ".((int) $supplier);
887  }
888  if ($socid > 0) { // if external user
889  $sql .= " AND s.fk_soc = ".((int) $socid);
890  }
891  $sql .= " AND s.fk_product = t.rowid";
892  // Select products of given category
893  if ($category > 0) {
894  $sql .= " AND c.fk_categorie = ".((int) $category);
895  $sql .= " AND c.fk_product = t.rowid";
896  }
897  if ($mode == 1) {
898  // Show only products
899  $sql .= " AND t.fk_product_type = 0";
900  } elseif ($mode == 2) {
901  // Show only services
902  $sql .= " AND t.fk_product_type = 1";
903  }
904  // Add sql filters
905  if ($sqlfilters) {
906  $errormessage = '';
907  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
908  if ($errormessage) {
909  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
910  }
911  }
912 
913  $sql .= $this->db->order($sortfield, $sortorder);
914  if ($limit) {
915  if ($page < 0) {
916  $page = 0;
917  }
918  $offset = $limit * $page;
919  $sql .= $this->db->plimit($limit + 1, $offset);
920  }
921  $result = $this->db->query($sql);
922  if ($result) {
923  $num = $this->db->num_rows($result);
924  $min = min($num, ($limit <= 0 ? $num : $limit));
925  $i = 0;
926  while ($i < $min) {
927  $obj = $this->db->fetch_object($result);
928 
929  $product_fourn = new ProductFournisseur($this->db);
930  $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0);
931  foreach ($product_fourn_list as $tmpobj) {
932  $this->_cleanObjectDatas($tmpobj);
933  }
934 
935  //var_dump($product_fourn_list->db);exit;
936  $obj_ret[$obj->rowid] = $product_fourn_list;
937 
938  $i++;
939  }
940  } else {
941  throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
942  }
943  if (!count($obj_ret)) {
944  throw new RestException(404, 'No product found');
945  }
946  return $obj_ret;
947  }
948 
968  public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '')
969  {
970  if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
971  throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
972  }
973 
974  $id = (empty($id) ? 0 : $id);
975 
976  if (!DolibarrApiAccess::$user->rights->produit->lire) {
977  throw new RestException(403);
978  }
979 
980  $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
981 
982  $result = $this->product->fetch($id, $ref, $ref_ext, $barcode);
983  if (!$result) {
984  throw new RestException(404, 'Product not found');
985  }
986 
987  if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
988  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
989  }
990 
991  $product_fourn_list = array();
992 
993  if ($result) {
994  $product_fourn = new ProductFournisseur($this->db);
995  $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0, ($socid > 0 ? $socid : 0));
996  }
997 
998  foreach ($product_fourn_list as $tmpobj) {
999  $this->_cleanObjectDatas($tmpobj);
1000  }
1001 
1002  return $this->_cleanObjectDatas($product_fourn_list);
1003  }
1004 
1021  public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
1022  {
1023  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1024  throw new RestException(401);
1025  }
1026 
1027  $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.position, t.entity";
1028  $sql .= " FROM ".$this->db->prefix()."product_attribute as t";
1029  $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
1030 
1031  // Add sql filters
1032  if ($sqlfilters) {
1033  $errormessage = '';
1034  $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
1035  if ($errormessage) {
1036  throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
1037  }
1038  }
1039 
1040  $sql .= $this->db->order($sortfield, $sortorder);
1041  if ($limit) {
1042  if ($page < 0) {
1043  $page = 0;
1044  }
1045  $offset = $limit * $page;
1046 
1047  $sql .= $this->db->plimit($limit, $offset);
1048  }
1049 
1050  $result = $this->db->query($sql);
1051 
1052  if (!$result) {
1053  throw new RestException(503, 'Error when retrieve product attribute list : '.$this->db->lasterror());
1054  }
1055 
1056  $return = array();
1057  while ($result = $this->db->fetch_object($query)) {
1058  $tmp = new ProductAttribute($this->db);
1059  $tmp->id = $result->rowid;
1060  $tmp->ref = $result->ref;
1061  $tmp->ref_ext = $result->ref_ext;
1062  $tmp->label = $result->label;
1063  $tmp->position = $result->position;
1064  $tmp->entity = $result->entity;
1065 
1066  $return[] = $this->_cleanObjectDatas($tmp);
1067  }
1068 
1069  if (!count($return)) {
1070  throw new RestException(404, 'No product attribute found');
1071  }
1072 
1073  return $return;
1074  }
1075 
1087  public function getAttributeById($id)
1088  {
1089  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1090  throw new RestException(401);
1091  }
1092 
1093  $prodattr = new ProductAttribute($this->db);
1094  $result = $prodattr->fetch((int) $id);
1095 
1096  if ($result < 0) {
1097  throw new RestException(404, "Product attribute not found");
1098  }
1099 
1100  $fields = ["id", "ref", "ref_ext", "label", "position", "entity"];
1101 
1102  foreach ($prodattr as $field => $value) {
1103  if (!in_array($field, $fields)) {
1104  unset($prodattr->{$field});
1105  }
1106  }
1107 
1108  $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1109  $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1110  $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")";
1111 
1112  $resql = $this->db->query($sql);
1113  $obj = $this->db->fetch_object($resql);
1114  $prodattr->is_used_by_products = (int) $obj->nb;
1115 
1116  return $this->_cleanObjectDatas($prodattr);
1117  }
1118 
1130  public function getAttributesByRef($ref)
1131  {
1132  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1133  throw new RestException(401);
1134  }
1135 
1136  $ref = trim($ref);
1137 
1138  $sql = "SELECT rowid, ref, ref_ext, label, position, entity FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."' AND entity IN (".getEntity('product').")";
1139 
1140  $query = $this->db->query($sql);
1141 
1142  if (!$this->db->num_rows($query)) {
1143  throw new RestException(404);
1144  }
1145 
1146  $result = $this->db->fetch_object($query);
1147 
1148  $attr = array();
1149  $attr['id'] = $result->rowid;
1150  $attr['ref'] = $result->ref;
1151  $attr['ref_ext'] = $result->ref_ext;
1152  $attr['label'] = $result->label;
1153  $attr['rang'] = $result->position;
1154  $attr['position'] = $result->position;
1155  $attr['entity'] = $result->entity;
1156 
1157  $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1158  $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1159  $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1160 
1161  $resql = $this->db->query($sql);
1162  $obj = $this->db->fetch_object($resql);
1163 
1164  $attr["is_used_by_products"] = (int) $obj->nb;
1165 
1166  return $attr;
1167  }
1168 
1180  public function getAttributesByRefExt($ref_ext)
1181  {
1182  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1183  throw new RestException(401);
1184  }
1185 
1186  $ref_ext = trim($ref_ext);
1187 
1188  $sql = "SELECT rowid, ref, ref_ext, label, position, entity FROM ".$this->db->prefix()."product_attribute WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."' AND entity IN (".getEntity('product').")";
1189 
1190  $query = $this->db->query($sql);
1191 
1192  if (!$this->db->num_rows($query)) {
1193  throw new RestException(404);
1194  }
1195 
1196  $result = $this->db->fetch_object($query);
1197 
1198  $attr = array();
1199  $attr['id'] = $result->rowid;
1200  $attr['ref'] = $result->ref;
1201  $attr['ref_ext'] = $result->ref_ext;
1202  $attr['label'] = $result->label;
1203  $attr['rang'] = $result->position;
1204  $attr['position'] = $result->position;
1205  $attr['entity'] = $result->entity;
1206 
1207  $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1208  $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1209  $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1210 
1211  $resql = $this->db->query($sql);
1212  $obj = $this->db->fetch_object($resql);
1213 
1214  $attr["is_used_by_products"] = (int) $obj->nb;
1215 
1216  return $attr;
1217  }
1218 
1232  public function addAttributes($ref, $label, $ref_ext = '')
1233  {
1234  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1235  throw new RestException(401);
1236  }
1237 
1238  $prodattr = new ProductAttribute($this->db);
1239  $prodattr->label = $label;
1240  $prodattr->ref = $ref;
1241  $prodattr->ref_ext = $ref_ext;
1242 
1243  $resid = $prodattr->create(DolibarrApiAccess::$user);
1244  if ($resid <= 0) {
1245  throw new RestException(500, "Error creating new attribute");
1246  }
1247 
1248  return $resid;
1249  }
1250 
1264  public function putAttributes($id, $request_data = null)
1265  {
1266  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1267  throw new RestException(401);
1268  }
1269 
1270  $prodattr = new ProductAttribute($this->db);
1271 
1272  $result = $prodattr->fetch((int) $id);
1273  if ($result == 0) {
1274  throw new RestException(404, 'Attribute not found');
1275  } elseif ($result < 0) {
1276  throw new RestException(500, "Error fetching attribute");
1277  }
1278 
1279  foreach ($request_data as $field => $value) {
1280  if ($field == 'rowid') {
1281  continue;
1282  }
1283  $prodattr->$field = $value;
1284  }
1285 
1286  if ($prodattr->update(DolibarrApiAccess::$user) > 0) {
1287  $result = $prodattr->fetch((int) $id);
1288  if ($result == 0) {
1289  throw new RestException(404, 'Attribute not found');
1290  } elseif ($result < 0) {
1291  throw new RestException(500, "Error fetching attribute");
1292  } else {
1293  return $this->_cleanObjectDatas($prodattr);
1294  }
1295  }
1296  throw new RestException(500, "Error updating attribute");
1297  }
1298 
1310  public function deleteAttributes($id)
1311  {
1312  if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1313  throw new RestException(401);
1314  }
1315 
1316  $prodattr = new ProductAttribute($this->db);
1317  $prodattr->id = (int) $id;
1318  $result = $prodattr->delete(DolibarrApiAccess::$user);
1319 
1320  if ($result <= 0) {
1321  throw new RestException(500, "Error deleting attribute");
1322  }
1323 
1324  return $result;
1325  }
1326 
1338  public function getAttributeValueById($id)
1339  {
1340  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1341  throw new RestException(401);
1342  }
1343 
1344  $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")";
1345 
1346  $query = $this->db->query($sql);
1347 
1348  if (!$query) {
1349  throw new RestException(401);
1350  }
1351 
1352  if (!$this->db->num_rows($query)) {
1353  throw new RestException(404, 'Attribute value not found');
1354  }
1355 
1356  $result = $this->db->fetch_object($query);
1357 
1358  $attrval = array();
1359  $attrval['id'] = $result->rowid;
1360  $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1361  $attrval['ref'] = $result->ref;
1362  $attrval['value'] = $result->value;
1363 
1364  return $attrval;
1365  }
1366 
1379  public function getAttributeValueByRef($id, $ref)
1380  {
1381  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1382  throw new RestException(401);
1383  }
1384 
1385  $ref = trim($ref);
1386 
1387  $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value";
1388  $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1389 
1390  $query = $this->db->query($sql);
1391 
1392  if (!$query) {
1393  throw new RestException(401);
1394  }
1395 
1396  if (!$this->db->num_rows($query)) {
1397  throw new RestException(404, 'Attribute value not found');
1398  }
1399 
1400  $result = $this->db->fetch_object($query);
1401 
1402  $attrval = array();
1403  $attrval['id'] = $result->rowid;
1404  $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1405  $attrval['ref'] = $result->ref;
1406  $attrval['value'] = $result->value;
1407 
1408  return $attrval;
1409  }
1410 
1422  public function deleteAttributeValueByRef($id, $ref)
1423  {
1424  if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1425  throw new RestException(401);
1426  }
1427 
1428  $ref = trim($ref);
1429 
1430  $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_value";
1431  $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1432  $query = $this->db->query($sql);
1433 
1434  if (!$query) {
1435  throw new RestException(401);
1436  }
1437 
1438  if (!$this->db->num_rows($query)) {
1439  throw new RestException(404, 'Attribute value not found');
1440  }
1441 
1442  $result = $this->db->fetch_object($query);
1443 
1444  $attrval = new ProductAttributeValue($this->db);
1445  $attrval->id = $result->rowid;
1446  $result = $attrval->delete(DolibarrApiAccess::$user);
1447  if ($result > 0) {
1448  return 1;
1449  }
1450 
1451  throw new RestException(500, "Error deleting attribute value");
1452  }
1453 
1465  public function getAttributeValues($id)
1466  {
1467  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1468  throw new RestException(401);
1469  }
1470 
1471  $objectval = new ProductAttributeValue($this->db);
1472 
1473  $return = $objectval->fetchAllByProductAttribute((int) $id);
1474 
1475  if (count($return) == 0) {
1476  throw new RestException(404, 'Attribute values not found');
1477  }
1478 
1479  foreach ($return as $key => $val) {
1480  $return[$key] = $this->_cleanObjectDatas($return[$key]);
1481  }
1482 
1483  return $return;
1484  }
1485 
1496  public function getAttributeValuesByRef($ref)
1497  {
1498  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1499  throw new RestException(401);
1500  }
1501 
1502  $ref = trim($ref);
1503 
1504  $return = array();
1505 
1506  $sql = "SELECT ";
1507  $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM ".$this->db->prefix()."product_attribute_value as v";
1508  $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."')";
1509 
1510  $resql = $this->db->query($sql);
1511 
1512  while ($result = $this->db->fetch_object($resql)) {
1513  $tmp = new ProductAttributeValue($this->db);
1514  $tmp->fk_product_attribute = $result->fk_product_attribute;
1515  $tmp->id = $result->rowid;
1516  $tmp->ref = $result->ref;
1517  $tmp->value = $result->value;
1518 
1519  $return[] = $this->_cleanObjectDatas($tmp);
1520  }
1521 
1522  return $return;
1523  }
1524 
1538  public function addAttributeValue($id, $ref, $value)
1539  {
1540  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1541  throw new RestException(401);
1542  }
1543 
1544  if (empty($ref) || empty($value)) {
1545  throw new RestException(401);
1546  }
1547 
1548  $objectval = new ProductAttributeValue($this->db);
1549  $objectval->fk_product_attribute = ((int) $id);
1550  $objectval->ref = $ref;
1551  $objectval->value = $value;
1552 
1553  if ($objectval->create(DolibarrApiAccess::$user) > 0) {
1554  return $objectval->id;
1555  }
1556  throw new RestException(500, "Error creating new attribute value");
1557  }
1558 
1571  public function putAttributeValue($id, $request_data)
1572  {
1573  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1574  throw new RestException(401);
1575  }
1576 
1577  $objectval = new ProductAttributeValue($this->db);
1578  $result = $objectval->fetch((int) $id);
1579 
1580  if ($result == 0) {
1581  throw new RestException(404, 'Attribute value not found');
1582  } elseif ($result < 0) {
1583  throw new RestException(500, "Error fetching attribute value");
1584  }
1585 
1586  foreach ($request_data as $field => $value) {
1587  if ($field == 'rowid') {
1588  continue;
1589  }
1590  $objectval->$field = $value;
1591  }
1592 
1593  if ($objectval->update(DolibarrApiAccess::$user) > 0) {
1594  $result = $objectval->fetch((int) $id);
1595  if ($result == 0) {
1596  throw new RestException(404, 'Attribute not found');
1597  } elseif ($result < 0) {
1598  throw new RestException(500, "Error fetching attribute");
1599  } else {
1600  return $this->_cleanObjectDatas($objectval);
1601  }
1602  }
1603  throw new RestException(500, "Error updating attribute");
1604  }
1605 
1617  public function deleteAttributeValueById($id)
1618  {
1619  if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1620  throw new RestException(401);
1621  }
1622 
1623  $objectval = new ProductAttributeValue($this->db);
1624  $objectval->id = (int) $id;
1625 
1626  if ($objectval->delete(DolibarrApiAccess::$user) > 0) {
1627  return 1;
1628  }
1629  throw new RestException(500, "Error deleting attribute value");
1630  }
1631 
1644  public function getVariants($id, $includestock = 0)
1645  {
1646  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1647  throw new RestException(401);
1648  }
1649 
1650  $prodcomb = new ProductCombination($this->db);
1651  $combinations = $prodcomb->fetchAllByFkProductParent((int) $id);
1652 
1653  foreach ($combinations as $key => $combination) {
1654  $prodc2vp = new ProductCombination2ValuePair($this->db);
1655  $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1656  $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1657 
1658  if (!empty($includestock) && DolibarrApiAccess::$user->rights->stock->lire) {
1659  $productModel = new Product($this->db);
1660  $productModel->fetch((int) $combination->fk_product_child);
1661  $productModel->load_stock($includestock);
1662  $combinations[$key]->stock_warehouse = $this->_cleanObjectDatas($productModel)->stock_warehouse;
1663  }
1664  }
1665 
1666  return $combinations;
1667  }
1668 
1680  public function getVariantsByProdRef($ref)
1681  {
1682  if (!DolibarrApiAccess::$user->rights->produit->lire) {
1683  throw new RestException(401);
1684  }
1685 
1686  $result = $this->product->fetch('', $ref);
1687  if (!$result) {
1688  throw new RestException(404, 'Product not found');
1689  }
1690 
1691  $prodcomb = new ProductCombination($this->db);
1692  $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id);
1693 
1694  foreach ($combinations as $key => $combination) {
1695  $prodc2vp = new ProductCombination2ValuePair($this->db);
1696  $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1697  $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1698  }
1699 
1700  return $combinations;
1701  }
1702 
1723  public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '')
1724  {
1725  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1726  throw new RestException(401);
1727  }
1728 
1729  if (empty($id) || empty($features) || !is_array($features)) {
1730  throw new RestException(401);
1731  }
1732 
1733  $weight_impact = price2num($weight_impact);
1734  $price_impact = price2num($price_impact);
1735 
1736  $prodattr = new ProductAttribute($this->db);
1737  $prodattr_val = new ProductAttributeValue($this->db);
1738  foreach ($features as $id_attr => $id_value) {
1739  if ($prodattr->fetch((int) $id_attr) < 0) {
1740  throw new RestException(401);
1741  }
1742  if ($prodattr_val->fetch((int) $id_value) < 0) {
1743  throw new RestException(401);
1744  }
1745  }
1746 
1747  $result = $this->product->fetch((int) $id);
1748  if (!$result) {
1749  throw new RestException(404, 'Product not found');
1750  }
1751 
1752  $prodcomb = new ProductCombination($this->db);
1753 
1754  $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
1755  if ($result > 0) {
1756  return $result;
1757  } else {
1758  throw new RestException(500, "Error creating new product variant");
1759  }
1760  }
1761 
1780  public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
1781  {
1782  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1783  throw new RestException(401);
1784  }
1785 
1786  if (empty($ref) || empty($features) || !is_array($features)) {
1787  throw new RestException(401);
1788  }
1789 
1790  $weight_impact = price2num($weight_impact);
1791  $price_impact = price2num($price_impact);
1792 
1793  $prodattr = new ProductAttribute($this->db);
1794  $prodattr_val = new ProductAttributeValue($this->db);
1795  foreach ($features as $id_attr => $id_value) {
1796  if ($prodattr->fetch((int) $id_attr) < 0) {
1797  throw new RestException(404);
1798  }
1799  if ($prodattr_val->fetch((int) $id_value) < 0) {
1800  throw new RestException(404);
1801  }
1802  }
1803 
1804  $result = $this->product->fetch('', trim($ref));
1805  if (!$result) {
1806  throw new RestException(404, 'Product not found');
1807  }
1808 
1809  $prodcomb = new ProductCombination($this->db);
1810  if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
1811  $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
1812  if ($result > 0) {
1813  return $result;
1814  } else {
1815  throw new RestException(500, "Error creating new product variant");
1816  }
1817  } else {
1818  return $prodcomb->id;
1819  }
1820  }
1821 
1834  public function putVariant($id, $request_data = null)
1835  {
1836  if (!DolibarrApiAccess::$user->rights->produit->creer) {
1837  throw new RestException(401);
1838  }
1839 
1840  $prodcomb = new ProductCombination($this->db);
1841  $prodcomb->fetch((int) $id);
1842 
1843  foreach ($request_data as $field => $value) {
1844  if ($field == 'rowid') {
1845  continue;
1846  }
1847  $prodcomb->$field = $value;
1848  }
1849 
1850  $result = $prodcomb->update(DolibarrApiAccess::$user);
1851  if ($result > 0) {
1852  return 1;
1853  }
1854  throw new RestException(500, "Error editing variant");
1855  }
1856 
1868  public function deleteVariant($id)
1869  {
1870  if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1871  throw new RestException(401);
1872  }
1873 
1874  $prodcomb = new ProductCombination($this->db);
1875  $prodcomb->id = (int) $id;
1876  $result = $prodcomb->delete(DolibarrApiAccess::$user);
1877  if ($result <= 0) {
1878  throw new RestException(500, "Error deleting variant");
1879  }
1880  return $result;
1881  }
1882 
1897  public function getStock($id, $selected_warehouse_id = null)
1898  {
1899  if (!DolibarrApiAccess::$user->rights->produit->lire || !DolibarrApiAccess::$user->rights->stock->lire) {
1900  throw new RestException(401);
1901  }
1902 
1903  if (!DolibarrApi::_checkAccessToResource('product', $id)) {
1904  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1905  }
1906 
1907  $product_model = new Product($this->db);
1908  $product_model->fetch($id);
1909  $product_model->load_stock();
1910 
1911  $stockData = $this->_cleanObjectDatas($product_model)->stock_warehouse;
1912  if ($selected_warehouse_id) {
1913  foreach ($stockData as $warehouse_id => $warehouse) {
1914  if ($warehouse_id != $selected_warehouse_id) {
1915  unset($stockData[$warehouse_id]);
1916  }
1917  }
1918  }
1919 
1920  if (empty($stockData)) {
1921  throw new RestException(404, 'No stock found');
1922  }
1923 
1924  return array('stock_warehouses'=>$stockData);
1925  }
1926 
1927  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1934  protected function _cleanObjectDatas($object)
1935  {
1936  // phpcs:enable
1937  $object = parent::_cleanObjectDatas($object);
1938 
1939  unset($object->statut);
1940 
1941  unset($object->regeximgext);
1942  unset($object->price_by_qty);
1943  unset($object->prices_by_qty_id);
1944  unset($object->libelle);
1945  unset($object->product_id_already_linked);
1946  unset($object->reputations);
1947  unset($object->db);
1948  unset($object->name);
1949  unset($object->firstname);
1950  unset($object->lastname);
1951  unset($object->civility_id);
1952  unset($object->contact);
1953  unset($object->contact_id);
1954  unset($object->thirdparty);
1955  unset($object->user);
1956  unset($object->origin);
1957  unset($object->origin_id);
1958  unset($object->fourn_pu);
1959  unset($object->fourn_price_base_type);
1960  unset($object->fourn_socid);
1961  unset($object->ref_fourn);
1962  unset($object->ref_supplier);
1963  unset($object->product_fourn_id);
1964  unset($object->fk_project);
1965 
1966  unset($object->mode_reglement_id);
1967  unset($object->cond_reglement_id);
1968  unset($object->demand_reason_id);
1969  unset($object->transport_mode_id);
1970  unset($object->cond_reglement);
1971  unset($object->shipping_method_id);
1972  unset($object->model_pdf);
1973  unset($object->note);
1974 
1975  unset($object->nbphoto);
1976  unset($object->recuperableonly);
1977  unset($object->multiprices_recuperableonly);
1978  unset($object->tva_npr);
1979  unset($object->lines);
1980  unset($object->fk_bank);
1981  unset($object->fk_account);
1982 
1983  unset($object->supplierprices); // Mut use another API to get them
1984 
1985  if (empty(DolibarrApiAccess::$user->rights->stock->lire)) {
1986  unset($object->stock_reel);
1987  unset($object->stock_theorique);
1988  unset($object->stock_warehouse);
1989  }
1990 
1991  return $object;
1992  }
1993 
2001  private function _validate($data)
2002  {
2003  $product = array();
2004  foreach (Products::$FIELDS as $field) {
2005  if (!isset($data[$field])) {
2006  throw new RestException(400, "$field field missing");
2007  }
2008  $product[$field] = $data[$field];
2009  }
2010  return $product;
2011  }
2012 
2032  private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false, $includetrans = false)
2033  {
2034  if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
2035  throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
2036  }
2037 
2038  $id = (empty($id) ? 0 : $id);
2039 
2040  if (!DolibarrApiAccess::$user->rights->produit->lire) {
2041  throw new RestException(403);
2042  }
2043 
2044  $result = $this->product->fetch($id, $ref, $ref_ext, $barcode, 0, 0, ($includetrans ? 0 : 1));
2045  if (!$result) {
2046  throw new RestException(404, 'Product not found');
2047  }
2048 
2049  if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
2050  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2051  }
2052 
2053  if (!empty($includestockdata) && DolibarrApiAccess::$user->rights->stock->lire) {
2054  $this->product->load_stock($includestockdata);
2055 
2056  if (is_array($this->product->stock_warehouse)) {
2057  foreach ($this->product->stock_warehouse as $keytmp => $valtmp) {
2058  if (isset($this->product->stock_warehouse[$keytmp]->detail_batch) && is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) {
2059  foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
2060  unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
2061  }
2062  }
2063  }
2064  }
2065  }
2066 
2067  if ($includesubproducts) {
2068  $childsArbo = $this->product->getChildsArbo($id, 1);
2069 
2070  $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
2071  $childs = array();
2072  foreach ($childsArbo as $values) {
2073  $childs[] = array_combine($keys, $values);
2074  }
2075 
2076  $this->product->sousprods = $childs;
2077  }
2078 
2079  if ($includeparentid) {
2080  $prodcomb = new ProductCombination($this->db);
2081  $this->product->fk_product_parent = null;
2082  if (($fk_product_parent = $prodcomb->fetchByFkProductChild($this->product->id)) > 0) {
2083  $this->product->fk_product_parent = $fk_product_parent;
2084  }
2085  }
2086 
2087  if ($includeifobjectisused) {
2088  $this->product->is_object_used = ($this->product->isObjectUsed() > 0);
2089  }
2090 
2091  return $this->_cleanObjectDatas($this->product);
2092  }
2093 }
Class to manage categories.
Class for API REST v1.
Definition: api.class.php:31
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
Definition: api.class.php:282
Class to manage suppliers.
Class ProductAttribute Used to represent a product attribute.
Class ProductAttributeValue Used to represent a product attribute value.
Class ProductCombination2ValuePair Used to represent the relation between a product combination,...
Class ProductCombination Used to represent a product combination.
Class to manage predefined suppliers products.
Class to manage products or services.
File of class to manage predefined price products or services by customer.
_cleanObjectDatas($object)
Clean sensible object datas.
putAttributeValue($id, $request_data)
Update attribute value.
deleteAttributes($id)
Delete attributes by id.
index($sortfield="t.ref", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $sqlfilters='', $ids_only=false, $variant_filter=0, $pagination_data=false, $includestockdata=0)
List products.
deletePurchasePrice($id, $priceid)
Delete purchase price for a product.
getAttributeValuesByRef($ref)
Get all values for an attribute ref.
putVariant($id, $request_data=null)
Put product variants.
put($id, $request_data=null)
Update product.
addAttributeValue($id, $ref, $value)
Add attribute value.
addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
Add variant by product ref.
getAttributeValueById($id)
Get attribute value by id.
getVariantsByProdRef($ref)
Get product variants by Product ref.
getCustomerPricesPerQuantity($id)
Get prices per quantity for a product.
__construct()
Constructor.
getPurchasePrices($id, $ref='', $ref_ext='', $barcode='')
Get purchase prices for a product.
delSubproducts($id, $subproduct_id)
Remove subproduct.
getVariants($id, $includestock=0)
Get product variants.
putAttributes($id, $request_data=null)
Update attributes by id.
deleteAttributeValueById($id)
Delete attribute value by id.
getAttributeValues($id)
Get all values for an attribute id.
addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference='', $ref_ext='')
Add variant.
getSubproducts($id)
Get the list of subproducts of the product.
getAttributesByRefExt($ref_ext)
Get attributes by ref_ext.
getByRef($ref, $includestockdata=0, $includesubproducts=false, $includeparentid=false, $includetrans=false)
Get properties of a product object by ref.
deleteAttributeValueByRef($id, $ref)
Delete attribute value by ref.
post($request_data=null)
Create product object.
addPurchasePrice($id, $qty, $buyprice, $price_base_type, $fourn_id, $availability, $ref_fourn, $tva_tx, $charges=0, $remise_percent=0, $remise=0, $newnpr=0, $delivery_time_days=0, $supplier_reputation='', $localtaxes_array=array(), $newdefaultvatcode='', $multicurrency_buyprice=0, $multicurrency_price_base_type='HT', $multicurrency_tx=1, $multicurrency_code='', $desc_fourn='', $barcode='', $fk_barcode_type=null)
Add/Update purchase prices for a product.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get categories for a product.
getByBarcode($barcode, $includestockdata=0, $includesubproducts=false, $includeparentid=false, $includetrans=false)
Get properties of a product object by barcode.
getByRefExt($ref_ext, $includestockdata=0, $includesubproducts=false, $includeparentid=false, $includetrans=false)
Get properties of a product object by ref_ext.
getCustomerPricesPerCustomer($id, $thirdparty_id='')
Get prices per customer for a product.
deleteVariant($id)
Delete product variants.
_validate($data)
Validate fields before create or update object.
getCustomerPricesPerSegment($id)
Get prices per segment for a product.
_fetch($id, $ref='', $ref_ext='', $barcode='', $includestockdata=0, $includesubproducts=false, $includeparentid=false, $includeifobjectisused=false, $includetrans=false)
Get properties of 1 product object.
addAttributes($ref, $label, $ref_ext='')
Add attributes.
getAttributeValueByRef($id, $ref)
Get attribute value by ref.
getSupplierProducts($sortfield="t.ref", $sortorder='ASC', $limit=100, $page=0, $mode=0, $category=0, $supplier=0, $sqlfilters='')
Get a list of all purchase prices of products.
getAttributeById($id)
Get attribute by ID.
getStock($id, $selected_warehouse_id=null)
Get stock data for the product id given.
getAttributes($sortfield="t.ref", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='')
Get attributes.
getAttributesByRef($ref)
Get attributes by ref.
addSubproducts($id, $subproduct_id, $qty, $incdec=1)
Add subproduct.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.