dolibarr 18.0.6
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
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
22require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
23require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
24require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
25require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
26require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
27require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
28
35class 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 if ($field == 'array_options' && is_array($value)) {
365 foreach ($value as $index => $val) {
366 $this->product->array_options[$index] = $this->_checkValForAPI($field, $val, $this->product);
367 }
368 continue;
369 }
370 $this->product->$field = $value;
371 }
372
373 $updatetype = false;
374 if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) {
375 $updatetype = true;
376 }
377
378 $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype);
379
380 // If price mode is 1 price per product
381 if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) {
382 // We update price only if it was changed
383 $pricemodified = false;
384 if ($this->product->price_base_type != $oldproduct->price_base_type) {
385 $pricemodified = true;
386 } else {
387 if ($this->product->tva_tx != $oldproduct->tva_tx) {
388 $pricemodified = true;
389 }
390 if ($this->product->tva_npr != $oldproduct->tva_npr) {
391 $pricemodified = true;
392 }
393 if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
394 $pricemodified = true;
395 }
396
397 if ($this->product->price_base_type == 'TTC') {
398 if ($this->product->price_ttc != $oldproduct->price_ttc) {
399 $pricemodified = true;
400 }
401 if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
402 $pricemodified = true;
403 }
404 } else {
405 if ($this->product->price != $oldproduct->price) {
406 $pricemodified = true;
407 }
408 if ($this->product->price_min != $oldproduct->price_min) {
409 $pricemodified = true;
410 }
411 }
412 }
413
414 if ($pricemodified) {
415 $newvat = $this->product->tva_tx;
416 $newnpr = $this->product->tva_npr;
417 $newvatsrccode = $this->product->default_vat_code;
418
419 $newprice = $this->product->price;
420 $newpricemin = $this->product->price_min;
421 if ($this->product->price_base_type == 'TTC') {
422 $newprice = $this->product->price_ttc;
423 $newpricemin = $this->product->price_min_ttc;
424 }
425
426 $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode);
427 }
428 }
429
430 if ($result <= 0) {
431 throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors));
432 }
433
434 return $this->get($id);
435 }
436
443 public function delete($id)
444 {
445 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
446 throw new RestException(401);
447 }
448 $result = $this->product->fetch($id);
449 if (!$result) {
450 throw new RestException(404, 'Product not found');
451 }
452
453 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
454 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
455 }
456
457 // The Product::delete() method uses the global variable $user.
458 global $user;
459 $user = DolibarrApiAccess::$user;
460
461 $res = $this->product->delete(DolibarrApiAccess::$user);
462 if ($res < 0) {
463 throw new RestException(500, "Can't delete, error occurs");
464 } elseif ($res == 0) {
465 throw new RestException(409, "Can't delete, that product is probably used");
466 }
467
468 return array(
469 'success' => array(
470 'code' => 200,
471 'message' => 'Object deleted'
472 )
473 );
474 }
475
488 public function getSubproducts($id)
489 {
490 if (!DolibarrApiAccess::$user->rights->produit->lire) {
491 throw new RestException(401);
492 }
493
494 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
495 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
496 }
497
498 $childsArbo = $this->product->getChildsArbo($id, 1);
499
500 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
501 $childs = array();
502 foreach ($childsArbo as $values) {
503 $childs[] = array_combine($keys, $values);
504 }
505
506 return $childs;
507 }
508
526 public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1)
527 {
528 if (!DolibarrApiAccess::$user->rights->produit->creer) {
529 throw new RestException(401);
530 }
531
532 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
533 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
534 }
535
536 $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec);
537 if ($result <= 0) {
538 throw new RestException(500, "Error adding product child");
539 }
540 return $result;
541 }
542
556 public function delSubproducts($id, $subproduct_id)
557 {
558 if (!DolibarrApiAccess::$user->rights->produit->creer) {
559 throw new RestException(401);
560 }
561
562 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
563 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
564 }
565
566 $result = $this->product->del_sousproduit($id, $subproduct_id);
567 if ($result <= 0) {
568 throw new RestException(500, "Error while removing product child");
569 }
570 return $result;
571 }
572
573
587 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
588 {
589 if (!DolibarrApiAccess::$user->rights->categorie->lire) {
590 throw new RestException(401);
591 }
592
593 $categories = new Categorie($this->db);
594
595 $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page);
596
597 if (empty($result)) {
598 throw new RestException(404, 'No category found');
599 }
600
601 if ($result < 0) {
602 throw new RestException(503, 'Error when retrieve category list : '.join(',', array_merge(array($categories->error), $categories->errors)));
603 }
604
605 return $result;
606 }
607
617 public function getCustomerPricesPerSegment($id)
618 {
619 global $conf;
620
621 if (!DolibarrApiAccess::$user->rights->produit->lire) {
622 throw new RestException(401);
623 }
624
625 if (empty($conf->global->PRODUIT_MULTIPRICES)) {
626 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
627 }
628
629 $result = $this->product->fetch($id);
630 if (!$result) {
631 throw new RestException(404, 'Product not found');
632 }
633
634 if ($result < 0) {
635 throw new RestException(503, 'Error when retrieve prices list : '.join(',', array_merge(array($this->product->error), $this->product->errors)));
636 }
637
638 return array(
639 'multiprices'=>$this->product->multiprices,
640 'multiprices_inc_tax'=>$this->product->multiprices_ttc,
641 'multiprices_min'=>$this->product->multiprices_min,
642 'multiprices_min_inc_tax'=>$this->product->multiprices_min_ttc,
643 'multiprices_vat'=>$this->product->multiprices_tva_tx,
644 'multiprices_base_type'=>$this->product->multiprices_base_type,
645 //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code
646 );
647 }
648
659 public function getCustomerPricesPerCustomer($id, $thirdparty_id = '')
660 {
661 global $conf;
662
663 if (!DolibarrApiAccess::$user->rights->produit->lire) {
664 throw new RestException(401);
665 }
666
667 if (empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
668 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
669 }
670
671 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
672 if ($socid > 0 && $socid != $thirdparty_id) {
673 throw new RestException(401, 'Getting prices for all customers or for the customer ID '.$thirdparty_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
674 }
675
676 $result = $this->product->fetch($id);
677 if (!$result) {
678 throw new RestException(404, 'Product not found');
679 }
680
681 if ($result > 0) {
682 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
683 $prodcustprice = new Productcustomerprice($this->db);
684 $filter = array();
685 $filter['t.fk_product'] = $id;
686 if ($thirdparty_id) {
687 $filter['t.fk_soc'] = $thirdparty_id;
688 }
689 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
690 }
691
692 if (empty($prodcustprice->lines)) {
693 throw new RestException(404, 'Prices not found');
694 }
695
696 return $prodcustprice->lines;
697 }
698
708 public function getCustomerPricesPerQuantity($id)
709 {
710 global $conf;
711
712 if (!DolibarrApiAccess::$user->rights->produit->lire) {
713 throw new RestException(401);
714 }
715
716 if (empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
717 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
718 }
719
720 $result = $this->product->fetch($id);
721 if (!$result) {
722 throw new RestException(404, 'Product not found');
723 }
724
725 if ($result < 0) {
726 throw new RestException(503, 'Error when retrieve prices list : '.join(',', array_merge(array($this->product->error), $this->product->errors)));
727 }
728
729 return array(
730 'prices_by_qty'=>$this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product
731 'prices_by_qty_list'=>$this->product->prices_by_qty_list[0]
732 );
733 }
734
768 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)
769 {
770 if (!DolibarrApiAccess::$user->rights->produit->creer) {
771 throw new RestException(401);
772 }
773
774 $result = $this->productsupplier->fetch($id);
775 if (!$result) {
776 throw new RestException(404, 'Product not found');
777 }
778
779 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
780 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
781 }
782
783 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
784 if ($socid > 0 && $socid != $fourn_id) {
785 throw new RestException(401, 'Adding purchase price for the supplier ID '.$fourn_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
786 }
787
788 $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty);
789 if ($result < 0) {
790 throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror());
791 }
792
793 $fourn = new Fournisseur($this->db);
794 $result = $fourn->fetch($fourn_id);
795 if ($result <= 0) {
796 throw new RestException(404, 'Supplier not found');
797 }
798
799 // Clean data
800 $ref_fourn = sanitizeVal($ref_fourn, 'alphanohtml');
801 $desc_fourn = sanitizeVal($desc_fourn, 'restricthtml');
802 $barcode = sanitizeVal($barcode, 'alphanohtml');
803
804 $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);
805
806 if ($result <= 0) {
807 throw new RestException(500, "Error updating buy price : ".$this->db->lasterror());
808 }
809 return (int) $this->productsupplier->product_fourn_price_id;
810 }
811
826 public function deletePurchasePrice($id, $priceid)
827 {
828 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
829 throw new RestException(401);
830 }
831 $result = $this->productsupplier->fetch($id);
832 if (!$result) {
833 throw new RestException(404, 'Product not found');
834 }
835
836 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
837 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
838 }
839
840 $resultsupplier = 0;
841 if ($result > 0) {
842 $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid);
843 }
844
845 return $resultsupplier;
846 }
847
863 public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '')
864 {
865 global $db, $conf;
866
867 if (!DolibarrApiAccess::$user->rights->produit->lire) {
868 throw new RestException(401);
869 }
870
871 $obj_ret = array();
872
873 // Force id of company for external users
874 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
875 if ($socid > 0) {
876 if ($supplier != $socid || empty($supplier)) {
877 throw new RestException(401, 'As an external user, you can request only for your supplier id = '.$socid);
878 }
879 }
880
881 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
882 $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
883
884 if ($category > 0) {
885 $sql .= ", ".$this->db->prefix()."categorie_product as c";
886 }
887 $sql .= ", ".$this->db->prefix()."product_fournisseur_price as s";
888
889 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
890
891 if ($supplier > 0) {
892 $sql .= " AND s.fk_soc = ".((int) $supplier);
893 }
894 if ($socid > 0) { // if external user
895 $sql .= " AND s.fk_soc = ".((int) $socid);
896 }
897 $sql .= " AND s.fk_product = t.rowid";
898 // Select products of given category
899 if ($category > 0) {
900 $sql .= " AND c.fk_categorie = ".((int) $category);
901 $sql .= " AND c.fk_product = t.rowid";
902 }
903 if ($mode == 1) {
904 // Show only products
905 $sql .= " AND t.fk_product_type = 0";
906 } elseif ($mode == 2) {
907 // Show only services
908 $sql .= " AND t.fk_product_type = 1";
909 }
910 // Add sql filters
911 if ($sqlfilters) {
912 $errormessage = '';
913 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
914 if ($errormessage) {
915 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
916 }
917 }
918
919 $sql .= $this->db->order($sortfield, $sortorder);
920 if ($limit) {
921 if ($page < 0) {
922 $page = 0;
923 }
924 $offset = $limit * $page;
925 $sql .= $this->db->plimit($limit + 1, $offset);
926 }
927 $result = $this->db->query($sql);
928 if ($result) {
929 $num = $this->db->num_rows($result);
930 $min = min($num, ($limit <= 0 ? $num : $limit));
931 $i = 0;
932 while ($i < $min) {
933 $obj = $this->db->fetch_object($result);
934
935 $product_fourn = new ProductFournisseur($this->db);
936 $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0);
937 foreach ($product_fourn_list as $tmpobj) {
938 $this->_cleanObjectDatas($tmpobj);
939 }
940
941 //var_dump($product_fourn_list->db);exit;
942 $obj_ret[$obj->rowid] = $product_fourn_list;
943
944 $i++;
945 }
946 } else {
947 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
948 }
949 if (!count($obj_ret)) {
950 throw new RestException(404, 'No product found');
951 }
952 return $obj_ret;
953 }
954
974 public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '')
975 {
976 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
977 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
978 }
979
980 $id = (empty($id) ? 0 : $id);
981
982 if (!DolibarrApiAccess::$user->rights->produit->lire) {
983 throw new RestException(403);
984 }
985
986 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
987
988 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode);
989 if (!$result) {
990 throw new RestException(404, 'Product not found');
991 }
992
993 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
994 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
995 }
996
997 $product_fourn_list = array();
998
999 if ($result) {
1000 $product_fourn = new ProductFournisseur($this->db);
1001 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0, ($socid > 0 ? $socid : 0));
1002 }
1003
1004 foreach ($product_fourn_list as $tmpobj) {
1005 $this->_cleanObjectDatas($tmpobj);
1006 }
1007
1008 return $this->_cleanObjectDatas($product_fourn_list);
1009 }
1010
1027 public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
1028 {
1029 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1030 throw new RestException(401);
1031 }
1032
1033 $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.position, t.entity";
1034 $sql .= " FROM ".$this->db->prefix()."product_attribute as t";
1035 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
1036
1037 // Add sql filters
1038 if ($sqlfilters) {
1039 $errormessage = '';
1040 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
1041 if ($errormessage) {
1042 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
1043 }
1044 }
1045
1046 $sql .= $this->db->order($sortfield, $sortorder);
1047 if ($limit) {
1048 if ($page < 0) {
1049 $page = 0;
1050 }
1051 $offset = $limit * $page;
1052
1053 $sql .= $this->db->plimit($limit, $offset);
1054 }
1055
1056 $resql = $this->db->query($sql);
1057
1058 if (!$resql) {
1059 throw new RestException(503, 'Error when retrieving product attribute list : '.$this->db->lasterror());
1060 }
1061
1062 $return = array();
1063 while ($obj = $this->db->fetch_object($resql)) {
1064 $tmp = new ProductAttribute($this->db);
1065 $tmp->id = $obj->rowid;
1066 $tmp->ref = $obj->ref;
1067 $tmp->ref_ext = $obj->ref_ext;
1068 $tmp->label = $obj->label;
1069 $tmp->position = $obj->position;
1070 $tmp->entity = $obj->entity;
1071
1072 $return[] = $this->_cleanObjectDatas($tmp);
1073 }
1074
1075 if (!count($return)) {
1076 throw new RestException(404, 'No product attribute found');
1077 }
1078
1079 return $return;
1080 }
1081
1093 public function getAttributeById($id)
1094 {
1095 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1096 throw new RestException(401);
1097 }
1098
1099 $prodattr = new ProductAttribute($this->db);
1100 $result = $prodattr->fetch((int) $id);
1101
1102 if ($result < 0) {
1103 throw new RestException(404, "Product attribute not found");
1104 }
1105
1106 $fields = ["id", "ref", "ref_ext", "label", "position", "entity"];
1107
1108 foreach ($prodattr as $field => $value) {
1109 if (!in_array($field, $fields)) {
1110 unset($prodattr->{$field});
1111 }
1112 }
1113
1114 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1115 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1116 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")";
1117
1118 $resql = $this->db->query($sql);
1119 $obj = $this->db->fetch_object($resql);
1120 $prodattr->is_used_by_products = (int) $obj->nb;
1121
1122 return $this->_cleanObjectDatas($prodattr);
1123 }
1124
1136 public function getAttributesByRef($ref)
1137 {
1138 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1139 throw new RestException(401);
1140 }
1141
1142 $ref = trim($ref);
1143
1144 $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').")";
1145
1146 $query = $this->db->query($sql);
1147
1148 if (!$this->db->num_rows($query)) {
1149 throw new RestException(404);
1150 }
1151
1152 $result = $this->db->fetch_object($query);
1153
1154 $attr = array();
1155 $attr['id'] = $result->rowid;
1156 $attr['ref'] = $result->ref;
1157 $attr['ref_ext'] = $result->ref_ext;
1158 $attr['label'] = $result->label;
1159 $attr['rang'] = $result->position;
1160 $attr['position'] = $result->position;
1161 $attr['entity'] = $result->entity;
1162
1163 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1164 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1165 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1166
1167 $resql = $this->db->query($sql);
1168 $obj = $this->db->fetch_object($resql);
1169
1170 $attr["is_used_by_products"] = (int) $obj->nb;
1171
1172 return $attr;
1173 }
1174
1186 public function getAttributesByRefExt($ref_ext)
1187 {
1188 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1189 throw new RestException(401);
1190 }
1191
1192 $ref_ext = trim($ref_ext);
1193
1194 $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').")";
1195
1196 $query = $this->db->query($sql);
1197
1198 if (!$this->db->num_rows($query)) {
1199 throw new RestException(404);
1200 }
1201
1202 $result = $this->db->fetch_object($query);
1203
1204 $attr = array();
1205 $attr['id'] = $result->rowid;
1206 $attr['ref'] = $result->ref;
1207 $attr['ref_ext'] = $result->ref_ext;
1208 $attr['label'] = $result->label;
1209 $attr['rang'] = $result->position;
1210 $attr['position'] = $result->position;
1211 $attr['entity'] = $result->entity;
1212
1213 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1214 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1215 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1216
1217 $resql = $this->db->query($sql);
1218 $obj = $this->db->fetch_object($resql);
1219
1220 $attr["is_used_by_products"] = (int) $obj->nb;
1221
1222 return $attr;
1223 }
1224
1238 public function addAttributes($ref, $label, $ref_ext = '')
1239 {
1240 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1241 throw new RestException(401);
1242 }
1243
1244 $prodattr = new ProductAttribute($this->db);
1245 $prodattr->label = $label;
1246 $prodattr->ref = $ref;
1247 $prodattr->ref_ext = $ref_ext;
1248
1249 $resid = $prodattr->create(DolibarrApiAccess::$user);
1250 if ($resid <= 0) {
1251 throw new RestException(500, "Error creating new attribute");
1252 }
1253
1254 return $resid;
1255 }
1256
1270 public function putAttributes($id, $request_data = null)
1271 {
1272 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1273 throw new RestException(401);
1274 }
1275
1276 $prodattr = new ProductAttribute($this->db);
1277
1278 $result = $prodattr->fetch((int) $id);
1279 if ($result == 0) {
1280 throw new RestException(404, 'Attribute not found');
1281 } elseif ($result < 0) {
1282 throw new RestException(500, "Error fetching attribute");
1283 }
1284
1285 foreach ($request_data as $field => $value) {
1286 if ($field == 'rowid') {
1287 continue;
1288 }
1289 $prodattr->$field = $value;
1290 }
1291
1292 if ($prodattr->update(DolibarrApiAccess::$user) > 0) {
1293 $result = $prodattr->fetch((int) $id);
1294 if ($result == 0) {
1295 throw new RestException(404, 'Attribute not found');
1296 } elseif ($result < 0) {
1297 throw new RestException(500, "Error fetching attribute");
1298 } else {
1299 return $this->_cleanObjectDatas($prodattr);
1300 }
1301 }
1302 throw new RestException(500, "Error updating attribute");
1303 }
1304
1316 public function deleteAttributes($id)
1317 {
1318 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1319 throw new RestException(401);
1320 }
1321
1322 $prodattr = new ProductAttribute($this->db);
1323 $prodattr->id = (int) $id;
1324 $result = $prodattr->delete(DolibarrApiAccess::$user);
1325
1326 if ($result <= 0) {
1327 throw new RestException(500, "Error deleting attribute");
1328 }
1329
1330 return $result;
1331 }
1332
1344 public function getAttributeValueById($id)
1345 {
1346 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1347 throw new RestException(401);
1348 }
1349
1350 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")";
1351
1352 $query = $this->db->query($sql);
1353
1354 if (!$query) {
1355 throw new RestException(401);
1356 }
1357
1358 if (!$this->db->num_rows($query)) {
1359 throw new RestException(404, 'Attribute value not found');
1360 }
1361
1362 $result = $this->db->fetch_object($query);
1363
1364 $attrval = array();
1365 $attrval['id'] = $result->rowid;
1366 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1367 $attrval['ref'] = $result->ref;
1368 $attrval['value'] = $result->value;
1369
1370 return $attrval;
1371 }
1372
1385 public function getAttributeValueByRef($id, $ref)
1386 {
1387 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1388 throw new RestException(401);
1389 }
1390
1391 $ref = trim($ref);
1392
1393 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value";
1394 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1395
1396 $query = $this->db->query($sql);
1397
1398 if (!$query) {
1399 throw new RestException(401);
1400 }
1401
1402 if (!$this->db->num_rows($query)) {
1403 throw new RestException(404, 'Attribute value not found');
1404 }
1405
1406 $result = $this->db->fetch_object($query);
1407
1408 $attrval = array();
1409 $attrval['id'] = $result->rowid;
1410 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1411 $attrval['ref'] = $result->ref;
1412 $attrval['value'] = $result->value;
1413
1414 return $attrval;
1415 }
1416
1428 public function deleteAttributeValueByRef($id, $ref)
1429 {
1430 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1431 throw new RestException(401);
1432 }
1433
1434 $ref = trim($ref);
1435
1436 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_value";
1437 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1438 $query = $this->db->query($sql);
1439
1440 if (!$query) {
1441 throw new RestException(401);
1442 }
1443
1444 if (!$this->db->num_rows($query)) {
1445 throw new RestException(404, 'Attribute value not found');
1446 }
1447
1448 $result = $this->db->fetch_object($query);
1449
1450 $attrval = new ProductAttributeValue($this->db);
1451 $attrval->id = $result->rowid;
1452 $result = $attrval->delete(DolibarrApiAccess::$user);
1453 if ($result > 0) {
1454 return 1;
1455 }
1456
1457 throw new RestException(500, "Error deleting attribute value");
1458 }
1459
1471 public function getAttributeValues($id)
1472 {
1473 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1474 throw new RestException(401);
1475 }
1476
1477 $objectval = new ProductAttributeValue($this->db);
1478
1479 $return = $objectval->fetchAllByProductAttribute((int) $id);
1480
1481 if (count($return) == 0) {
1482 throw new RestException(404, 'Attribute values not found');
1483 }
1484
1485 foreach ($return as $key => $val) {
1486 $return[$key] = $this->_cleanObjectDatas($return[$key]);
1487 }
1488
1489 return $return;
1490 }
1491
1502 public function getAttributeValuesByRef($ref)
1503 {
1504 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1505 throw new RestException(401);
1506 }
1507
1508 $ref = trim($ref);
1509
1510 $return = array();
1511
1512 $sql = "SELECT ";
1513 $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM ".$this->db->prefix()."product_attribute_value as v";
1514 $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."')";
1515
1516 $resql = $this->db->query($sql);
1517
1518 while ($result = $this->db->fetch_object($resql)) {
1519 $tmp = new ProductAttributeValue($this->db);
1520 $tmp->fk_product_attribute = $result->fk_product_attribute;
1521 $tmp->id = $result->rowid;
1522 $tmp->ref = $result->ref;
1523 $tmp->value = $result->value;
1524
1525 $return[] = $this->_cleanObjectDatas($tmp);
1526 }
1527
1528 return $return;
1529 }
1530
1544 public function addAttributeValue($id, $ref, $value)
1545 {
1546 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1547 throw new RestException(401);
1548 }
1549
1550 if (empty($ref) || empty($value)) {
1551 throw new RestException(401);
1552 }
1553
1554 $objectval = new ProductAttributeValue($this->db);
1555 $objectval->fk_product_attribute = ((int) $id);
1556 $objectval->ref = $ref;
1557 $objectval->value = $value;
1558
1559 if ($objectval->create(DolibarrApiAccess::$user) > 0) {
1560 return $objectval->id;
1561 }
1562 throw new RestException(500, "Error creating new attribute value");
1563 }
1564
1577 public function putAttributeValue($id, $request_data)
1578 {
1579 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1580 throw new RestException(401);
1581 }
1582
1583 $objectval = new ProductAttributeValue($this->db);
1584 $result = $objectval->fetch((int) $id);
1585
1586 if ($result == 0) {
1587 throw new RestException(404, 'Attribute value not found');
1588 } elseif ($result < 0) {
1589 throw new RestException(500, "Error fetching attribute value");
1590 }
1591
1592 foreach ($request_data as $field => $value) {
1593 if ($field == 'rowid') {
1594 continue;
1595 }
1596 $objectval->$field = $value;
1597 }
1598
1599 if ($objectval->update(DolibarrApiAccess::$user) > 0) {
1600 $result = $objectval->fetch((int) $id);
1601 if ($result == 0) {
1602 throw new RestException(404, 'Attribute not found');
1603 } elseif ($result < 0) {
1604 throw new RestException(500, "Error fetching attribute");
1605 } else {
1606 return $this->_cleanObjectDatas($objectval);
1607 }
1608 }
1609 throw new RestException(500, "Error updating attribute");
1610 }
1611
1623 public function deleteAttributeValueById($id)
1624 {
1625 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1626 throw new RestException(401);
1627 }
1628
1629 $objectval = new ProductAttributeValue($this->db);
1630 $objectval->id = (int) $id;
1631
1632 if ($objectval->delete(DolibarrApiAccess::$user) > 0) {
1633 return 1;
1634 }
1635 throw new RestException(500, "Error deleting attribute value");
1636 }
1637
1650 public function getVariants($id, $includestock = 0)
1651 {
1652 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1653 throw new RestException(401);
1654 }
1655
1656 $prodcomb = new ProductCombination($this->db);
1657 $combinations = $prodcomb->fetchAllByFkProductParent((int) $id);
1658
1659 foreach ($combinations as $key => $combination) {
1660 $prodc2vp = new ProductCombination2ValuePair($this->db);
1661 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1662 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1663
1664 if (!empty($includestock) && DolibarrApiAccess::$user->rights->stock->lire) {
1665 $productModel = new Product($this->db);
1666 $productModel->fetch((int) $combination->fk_product_child);
1667 $productModel->load_stock($includestock);
1668 $combinations[$key]->stock_warehouse = $this->_cleanObjectDatas($productModel)->stock_warehouse;
1669 }
1670 }
1671
1672 return $combinations;
1673 }
1674
1686 public function getVariantsByProdRef($ref)
1687 {
1688 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1689 throw new RestException(401);
1690 }
1691
1692 $result = $this->product->fetch('', $ref);
1693 if (!$result) {
1694 throw new RestException(404, 'Product not found');
1695 }
1696
1697 $prodcomb = new ProductCombination($this->db);
1698 $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id);
1699
1700 foreach ($combinations as $key => $combination) {
1701 $prodc2vp = new ProductCombination2ValuePair($this->db);
1702 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1703 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1704 }
1705
1706 return $combinations;
1707 }
1708
1729 public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '')
1730 {
1731 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1732 throw new RestException(401);
1733 }
1734
1735 if (empty($id) || empty($features) || !is_array($features)) {
1736 throw new RestException(401);
1737 }
1738
1739 $weight_impact = price2num($weight_impact);
1740 $price_impact = price2num($price_impact);
1741
1742 $prodattr = new ProductAttribute($this->db);
1743 $prodattr_val = new ProductAttributeValue($this->db);
1744 foreach ($features as $id_attr => $id_value) {
1745 if ($prodattr->fetch((int) $id_attr) < 0) {
1746 throw new RestException(401);
1747 }
1748 if ($prodattr_val->fetch((int) $id_value) < 0) {
1749 throw new RestException(401);
1750 }
1751 }
1752
1753 $result = $this->product->fetch((int) $id);
1754 if (!$result) {
1755 throw new RestException(404, 'Product not found');
1756 }
1757
1758 $prodcomb = new ProductCombination($this->db);
1759
1760 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
1761 if ($result > 0) {
1762 return $result;
1763 } else {
1764 throw new RestException(500, "Error creating new product variant");
1765 }
1766 }
1767
1786 public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
1787 {
1788 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1789 throw new RestException(401);
1790 }
1791
1792 if (empty($ref) || empty($features) || !is_array($features)) {
1793 throw new RestException(401);
1794 }
1795
1796 $weight_impact = price2num($weight_impact);
1797 $price_impact = price2num($price_impact);
1798
1799 $prodattr = new ProductAttribute($this->db);
1800 $prodattr_val = new ProductAttributeValue($this->db);
1801 foreach ($features as $id_attr => $id_value) {
1802 if ($prodattr->fetch((int) $id_attr) < 0) {
1803 throw new RestException(404);
1804 }
1805 if ($prodattr_val->fetch((int) $id_value) < 0) {
1806 throw new RestException(404);
1807 }
1808 }
1809
1810 $result = $this->product->fetch('', trim($ref));
1811 if (!$result) {
1812 throw new RestException(404, 'Product not found');
1813 }
1814
1815 $prodcomb = new ProductCombination($this->db);
1816 if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
1817 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
1818 if ($result > 0) {
1819 return $result;
1820 } else {
1821 throw new RestException(500, "Error creating new product variant");
1822 }
1823 } else {
1824 return $prodcomb->id;
1825 }
1826 }
1827
1840 public function putVariant($id, $request_data = null)
1841 {
1842 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1843 throw new RestException(401);
1844 }
1845
1846 $prodcomb = new ProductCombination($this->db);
1847 $prodcomb->fetch((int) $id);
1848
1849 foreach ($request_data as $field => $value) {
1850 if ($field == 'rowid') {
1851 continue;
1852 }
1853 $prodcomb->$field = $value;
1854 }
1855
1856 $result = $prodcomb->update(DolibarrApiAccess::$user);
1857 if ($result > 0) {
1858 return 1;
1859 }
1860 throw new RestException(500, "Error editing variant");
1861 }
1862
1874 public function deleteVariant($id)
1875 {
1876 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1877 throw new RestException(401);
1878 }
1879
1880 $prodcomb = new ProductCombination($this->db);
1881 $prodcomb->id = (int) $id;
1882 $result = $prodcomb->delete(DolibarrApiAccess::$user);
1883 if ($result <= 0) {
1884 throw new RestException(500, "Error deleting variant");
1885 }
1886 return $result;
1887 }
1888
1903 public function getStock($id, $selected_warehouse_id = null)
1904 {
1905 if (!DolibarrApiAccess::$user->rights->produit->lire || !DolibarrApiAccess::$user->rights->stock->lire) {
1906 throw new RestException(401);
1907 }
1908
1909 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
1910 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1911 }
1912
1913 $product_model = new Product($this->db);
1914 $product_model->fetch($id);
1915 $product_model->load_stock();
1916
1917 $stockData = $this->_cleanObjectDatas($product_model)->stock_warehouse;
1918 if ($selected_warehouse_id) {
1919 foreach ($stockData as $warehouse_id => $warehouse) {
1920 if ($warehouse_id != $selected_warehouse_id) {
1921 unset($stockData[$warehouse_id]);
1922 }
1923 }
1924 }
1925
1926 if (empty($stockData)) {
1927 throw new RestException(404, 'No stock found');
1928 }
1929
1930 return array('stock_warehouses'=>$stockData);
1931 }
1932
1933 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1940 protected function _cleanObjectDatas($object)
1941 {
1942 // phpcs:enable
1943 $object = parent::_cleanObjectDatas($object);
1944
1945 unset($object->statut);
1946
1947 unset($object->regeximgext);
1948 unset($object->price_by_qty);
1949 unset($object->prices_by_qty_id);
1950 unset($object->libelle);
1951 unset($object->product_id_already_linked);
1952 unset($object->reputations);
1953 unset($object->db);
1954 unset($object->name);
1955 unset($object->firstname);
1956 unset($object->lastname);
1957 unset($object->civility_id);
1958 unset($object->contact);
1959 unset($object->contact_id);
1960 unset($object->thirdparty);
1961 unset($object->user);
1962 unset($object->origin);
1963 unset($object->origin_id);
1964 unset($object->fourn_pu);
1965 unset($object->fourn_price_base_type);
1966 unset($object->fourn_socid);
1967 unset($object->ref_fourn);
1968 unset($object->ref_supplier);
1969 unset($object->product_fourn_id);
1970 unset($object->fk_project);
1971
1972 unset($object->mode_reglement_id);
1973 unset($object->cond_reglement_id);
1974 unset($object->demand_reason_id);
1975 unset($object->transport_mode_id);
1976 unset($object->cond_reglement);
1977 unset($object->shipping_method_id);
1978 unset($object->model_pdf);
1979 unset($object->note);
1980
1981 unset($object->nbphoto);
1982 unset($object->recuperableonly);
1983 unset($object->multiprices_recuperableonly);
1984 unset($object->tva_npr);
1985 unset($object->lines);
1986 unset($object->fk_bank);
1987 unset($object->fk_account);
1988
1989 unset($object->supplierprices); // Mut use another API to get them
1990
1991 if (empty(DolibarrApiAccess::$user->rights->stock->lire)) {
1992 unset($object->stock_reel);
1993 unset($object->stock_theorique);
1994 unset($object->stock_warehouse);
1995 }
1996
1997 return $object;
1998 }
1999
2007 private function _validate($data)
2008 {
2009 $product = array();
2010 foreach (Products::$FIELDS as $field) {
2011 if (!isset($data[$field])) {
2012 throw new RestException(400, "$field field missing");
2013 }
2014 $product[$field] = $data[$field];
2015 }
2016 return $product;
2017 }
2018
2038 private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false, $includetrans = false)
2039 {
2040 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
2041 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
2042 }
2043
2044 $id = (empty($id) ? 0 : $id);
2045
2046 if (!DolibarrApiAccess::$user->rights->produit->lire) {
2047 throw new RestException(403);
2048 }
2049
2050 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode, 0, 0, ($includetrans ? 0 : 1));
2051 if (!$result) {
2052 throw new RestException(404, 'Product not found');
2053 }
2054
2055 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
2056 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2057 }
2058
2059 if (!empty($includestockdata) && DolibarrApiAccess::$user->rights->stock->lire) {
2060 $this->product->load_stock($includestockdata);
2061
2062 if (is_array($this->product->stock_warehouse)) {
2063 foreach ($this->product->stock_warehouse as $keytmp => $valtmp) {
2064 if (isset($this->product->stock_warehouse[$keytmp]->detail_batch) && is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) {
2065 foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
2066 unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
2067 }
2068 }
2069 }
2070 }
2071 }
2072
2073 if ($includesubproducts) {
2074 $childsArbo = $this->product->getChildsArbo($id, 1);
2075
2076 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
2077 $childs = array();
2078 foreach ($childsArbo as $values) {
2079 $childs[] = array_combine($keys, $values);
2080 }
2081
2082 $this->product->sousprods = $childs;
2083 }
2084
2085 if ($includeparentid) {
2086 $prodcomb = new ProductCombination($this->db);
2087 $this->product->fk_product_parent = null;
2088 if (($fk_product_parent = $prodcomb->fetchByFkProductChild($this->product->id)) > 0) {
2089 $this->product->fk_product_parent = $fk_product_parent;
2090 }
2091 }
2092
2093 if ($includeifobjectisused) {
2094 $this->product->is_object_used = ($this->product->isObjectUsed() > 0);
2095 }
2096
2097 return $this->_cleanObjectDatas($this->product);
2098 }
2099}
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.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:86
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.
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.