dolibarr 19.0.3
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
179 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, $properties = '')
180 {
181 global $db, $conf;
182
183 if (!DolibarrApiAccess::$user->rights->produit->lire) {
184 throw new RestException(403);
185 }
186
187 $obj_ret = array();
188
189 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
190
191 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
192 $sql .= " FROM ".$this->db->prefix()."product as t";
193 $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
194 if ($category > 0) {
195 $sql .= ", ".$this->db->prefix()."categorie_product as c";
196 }
197 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
198
199 if ($variant_filter == 1) {
200 $sql .= ' AND t.rowid not in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
201 $sql .= ' AND t.rowid not in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
202 }
203 if ($variant_filter == 2) {
204 $sql .= ' AND t.rowid in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
205 }
206 if ($variant_filter == 3) {
207 $sql .= ' AND t.rowid in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
208 }
209
210 // Select products of given category
211 if ($category > 0) {
212 $sql .= " AND c.fk_categorie = ".((int) $category);
213 $sql .= " AND c.fk_product = t.rowid";
214 }
215 if ($mode == 1) {
216 // Show only products
217 $sql .= " AND t.fk_product_type = 0";
218 } elseif ($mode == 2) {
219 // Show only services
220 $sql .= " AND t.fk_product_type = 1";
221 }
222
223 // Add sql filters
224 if ($sqlfilters) {
225 $errormessage = '';
226 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
227 if ($errormessage) {
228 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
229 }
230 }
231
232 //this query will return total products with the filters given
233 $sqlTotals = str_replace('SELECT t.rowid, t.ref, t.ref_ext', 'SELECT count(t.rowid) as total', $sql);
234
235 $sql .= $this->db->order($sortfield, $sortorder);
236 if ($limit) {
237 if ($page < 0) {
238 $page = 0;
239 }
240 $offset = $limit * $page;
241
242 $sql .= $this->db->plimit($limit + 1, $offset);
243 }
244
245 $result = $this->db->query($sql);
246 if ($result) {
247 $num = $this->db->num_rows($result);
248 $min = min($num, ($limit <= 0 ? $num : $limit));
249 $i = 0;
250 while ($i < $min) {
251 $obj = $this->db->fetch_object($result);
252 if (!$ids_only) {
253 $product_static = new Product($this->db);
254 if ($product_static->fetch($obj->rowid)) {
255 if (!empty($includestockdata) && DolibarrApiAccess::$user->rights->stock->lire) {
256 $product_static->load_stock();
257
258 if (is_array($product_static->stock_warehouse)) {
259 foreach ($product_static->stock_warehouse as $keytmp => $valtmp) {
260 if (isset($product_static->stock_warehouse[$keytmp]->detail_batch) && is_array($product_static->stock_warehouse[$keytmp]->detail_batch)) {
261 foreach ($product_static->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
262 unset($product_static->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
263 }
264 }
265 }
266 }
267 }
268
269
270 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($product_static), $properties);
271 }
272 } else {
273 $obj_ret[] = $obj->rowid;
274 }
275 $i++;
276 }
277 } else {
278 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
279 }
280
281 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
282 if ($pagination_data) {
283 $totalsResult = $this->db->query($sqlTotals);
284 $total = $this->db->fetch_object($totalsResult)->total;
285
286 $tmp = $obj_ret;
287 $obj_ret = array();
288
289 $obj_ret['data'] = $tmp;
290 $obj_ret['pagination'] = array(
291 'total' => (int) $total,
292 'page' => $page, //count starts from 0
293 'page_count' => ceil((int) $total/$limit),
294 'limit' => $limit
295 );
296 }
297
298 return $obj_ret;
299 }
300
307 public function post($request_data = null)
308 {
309 if (!DolibarrApiAccess::$user->rights->produit->creer) {
310 throw new RestException(401);
311 }
312 // Check mandatory fields
313 $result = $this->_validate($request_data);
314
315 foreach ($request_data as $field => $value) {
316 if ($field === 'caller') {
317 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
318 $this->product->context['caller'] = $request_data['caller'];
319 continue;
320 }
321
322 $this->product->$field = $value;
323 }
324 if ($this->product->create(DolibarrApiAccess::$user) < 0) {
325 throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors));
326 }
327
328 return $this->product->id;
329 }
330
342 public function put($id, $request_data = null)
343 {
344 global $conf;
345
346 if (!DolibarrApiAccess::$user->rights->produit->creer) {
347 throw new RestException(401);
348 }
349
350 $result = $this->product->fetch($id);
351 if (!$result) {
352 throw new RestException(404, 'Product not found');
353 }
354
355 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
356 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
357 }
358
359 $oldproduct = dol_clone($this->product);
360
361 foreach ($request_data as $field => $value) {
362 if ($field == 'id') {
363 continue;
364 }
365 if ($field == 'stock_reel') {
366 throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead');
367 }
368 if ($field === 'caller') {
369 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
370 $this->product->context['caller'] = $request_data['caller'];
371 continue;
372 }
373
374 $this->product->$field = $value;
375 }
376
377 $updatetype = false;
378 if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) {
379 $updatetype = true;
380 }
381
382 $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype);
383
384 // If price mode is 1 price per product
385 if ($result > 0 && getDolGlobalString('PRODUCT_PRICE_UNIQ')) {
386 // We update price only if it was changed
387 $pricemodified = false;
388 if ($this->product->price_base_type != $oldproduct->price_base_type) {
389 $pricemodified = true;
390 } else {
391 if ($this->product->tva_tx != $oldproduct->tva_tx) {
392 $pricemodified = true;
393 }
394 if ($this->product->tva_npr != $oldproduct->tva_npr) {
395 $pricemodified = true;
396 }
397 if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
398 $pricemodified = true;
399 }
400
401 if ($this->product->price_base_type == 'TTC') {
402 if ($this->product->price_ttc != $oldproduct->price_ttc) {
403 $pricemodified = true;
404 }
405 if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
406 $pricemodified = true;
407 }
408 } else {
409 if ($this->product->price != $oldproduct->price) {
410 $pricemodified = true;
411 }
412 if ($this->product->price_min != $oldproduct->price_min) {
413 $pricemodified = true;
414 }
415 }
416 }
417
418 if ($pricemodified) {
419 $newvat = $this->product->tva_tx;
420 $newnpr = $this->product->tva_npr;
421 $newvatsrccode = $this->product->default_vat_code;
422
423 $newprice = $this->product->price;
424 $newpricemin = $this->product->price_min;
425 if ($this->product->price_base_type == 'TTC') {
426 $newprice = $this->product->price_ttc;
427 $newpricemin = $this->product->price_min_ttc;
428 }
429
430 $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode);
431 }
432 }
433
434 if ($result <= 0) {
435 throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors));
436 }
437
438 return $this->get($id);
439 }
440
447 public function delete($id)
448 {
449 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
450 throw new RestException(401);
451 }
452 $result = $this->product->fetch($id);
453 if (!$result) {
454 throw new RestException(404, 'Product not found');
455 }
456
457 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
458 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
459 }
460
461 // The Product::delete() method uses the global variable $user.
462 global $user;
463 $user = DolibarrApiAccess::$user;
464
465 $res = $this->product->delete(DolibarrApiAccess::$user);
466 if ($res < 0) {
467 throw new RestException(500, "Can't delete, error occurs");
468 } elseif ($res == 0) {
469 throw new RestException(409, "Can't delete, that product is probably used");
470 }
471
472 return array(
473 'success' => array(
474 'code' => 200,
475 'message' => 'Object deleted'
476 )
477 );
478 }
479
492 public function getSubproducts($id)
493 {
494 if (!DolibarrApiAccess::$user->rights->produit->lire) {
495 throw new RestException(401);
496 }
497
498 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
499 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
500 }
501
502 $childsArbo = $this->product->getChildsArbo($id, 1);
503
504 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
505 $childs = array();
506 foreach ($childsArbo as $values) {
507 $childs[] = array_combine($keys, $values);
508 }
509
510 return $childs;
511 }
512
530 public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1)
531 {
532 if (!DolibarrApiAccess::$user->rights->produit->creer) {
533 throw new RestException(401);
534 }
535
536 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
537 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
538 }
539
540 $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec);
541 if ($result <= 0) {
542 throw new RestException(500, "Error adding product child");
543 }
544 return $result;
545 }
546
560 public function delSubproducts($id, $subproduct_id)
561 {
562 if (!DolibarrApiAccess::$user->rights->produit->creer) {
563 throw new RestException(401);
564 }
565
566 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
567 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
568 }
569
570 $result = $this->product->del_sousproduit($id, $subproduct_id);
571 if ($result <= 0) {
572 throw new RestException(500, "Error while removing product child");
573 }
574 return $result;
575 }
576
577
591 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
592 {
593 if (!DolibarrApiAccess::$user->rights->categorie->lire) {
594 throw new RestException(401);
595 }
596
597 $categories = new Categorie($this->db);
598
599 $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page);
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 (!getDolGlobalString('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 (!getDolGlobalString('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 (!getDolGlobalString('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
950 return $obj_ret;
951 }
952
972 public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '')
973 {
974 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
975 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
976 }
977
978 $id = (empty($id) ? 0 : $id);
979
980 if (!DolibarrApiAccess::$user->rights->produit->lire) {
981 throw new RestException(403);
982 }
983
984 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
985
986 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode);
987 if (!$result) {
988 throw new RestException(404, 'Product not found');
989 }
990
991 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
992 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
993 }
994
995 $product_fourn_list = array();
996
997 if ($result) {
998 $product_fourn = new ProductFournisseur($this->db);
999 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0, ($socid > 0 ? $socid : 0));
1000 }
1001
1002 foreach ($product_fourn_list as $tmpobj) {
1003 $this->_cleanObjectDatas($tmpobj);
1004 }
1005
1006 return $this->_cleanObjectDatas($product_fourn_list);
1007 }
1008
1026 public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
1027 {
1028 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1029 throw new RestException(401);
1030 }
1031
1032 $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.position, t.entity";
1033 $sql .= " FROM ".$this->db->prefix()."product_attribute as t";
1034 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
1035
1036 // Add sql filters
1037 if ($sqlfilters) {
1038 $errormessage = '';
1039 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
1040 if ($errormessage) {
1041 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
1042 }
1043 }
1044
1045 $sql .= $this->db->order($sortfield, $sortorder);
1046 if ($limit) {
1047 if ($page < 0) {
1048 $page = 0;
1049 }
1050 $offset = $limit * $page;
1051
1052 $sql .= $this->db->plimit($limit, $offset);
1053 }
1054
1055 $resql = $this->db->query($sql);
1056
1057 if (!$resql) {
1058 throw new RestException(503, 'Error when retrieving product attribute list : '.$this->db->lasterror());
1059 }
1060
1061 $return = array();
1062 while ($obj = $this->db->fetch_object($resql)) {
1063 $tmp = new ProductAttribute($this->db);
1064 $tmp->id = $obj->rowid;
1065 $tmp->ref = $obj->ref;
1066 $tmp->ref_ext = $obj->ref_ext;
1067 $tmp->label = $obj->label;
1068 $tmp->position = $obj->position;
1069 $tmp->entity = $obj->entity;
1070
1071 $return[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp), $properties);
1072 }
1073
1074 return $return;
1075 }
1076
1088 public function getAttributeById($id)
1089 {
1090 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1091 throw new RestException(401);
1092 }
1093
1094 $prodattr = new ProductAttribute($this->db);
1095 $result = $prodattr->fetch((int) $id);
1096
1097 if ($result < 0) {
1098 throw new RestException(404, "Product attribute not found");
1099 }
1100
1101 $fields = ["id", "ref", "ref_ext", "label", "position", "entity"];
1102
1103 foreach ($prodattr as $field => $value) {
1104 if (!in_array($field, $fields)) {
1105 unset($prodattr->{$field});
1106 }
1107 }
1108
1109 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1110 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1111 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")";
1112
1113 $resql = $this->db->query($sql);
1114 $obj = $this->db->fetch_object($resql);
1115 $prodattr->is_used_by_products = (int) $obj->nb;
1116
1117 return $this->_cleanObjectDatas($prodattr);
1118 }
1119
1131 public function getAttributesByRef($ref)
1132 {
1133 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1134 throw new RestException(401);
1135 }
1136
1137 $ref = trim($ref);
1138
1139 $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').")";
1140
1141 $query = $this->db->query($sql);
1142
1143 if (!$this->db->num_rows($query)) {
1144 throw new RestException(404);
1145 }
1146
1147 $result = $this->db->fetch_object($query);
1148
1149 $attr = array();
1150 $attr['id'] = $result->rowid;
1151 $attr['ref'] = $result->ref;
1152 $attr['ref_ext'] = $result->ref_ext;
1153 $attr['label'] = $result->label;
1154 $attr['rang'] = $result->position;
1155 $attr['position'] = $result->position;
1156 $attr['entity'] = $result->entity;
1157
1158 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1159 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1160 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1161
1162 $resql = $this->db->query($sql);
1163 $obj = $this->db->fetch_object($resql);
1164
1165 $attr["is_used_by_products"] = (int) $obj->nb;
1166
1167 return $attr;
1168 }
1169
1181 public function getAttributesByRefExt($ref_ext)
1182 {
1183 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1184 throw new RestException(401);
1185 }
1186
1187 $ref_ext = trim($ref_ext);
1188
1189 $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').")";
1190
1191 $query = $this->db->query($sql);
1192
1193 if (!$this->db->num_rows($query)) {
1194 throw new RestException(404);
1195 }
1196
1197 $result = $this->db->fetch_object($query);
1198
1199 $attr = array();
1200 $attr['id'] = $result->rowid;
1201 $attr['ref'] = $result->ref;
1202 $attr['ref_ext'] = $result->ref_ext;
1203 $attr['label'] = $result->label;
1204 $attr['rang'] = $result->position;
1205 $attr['position'] = $result->position;
1206 $attr['entity'] = $result->entity;
1207
1208 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1209 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1210 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1211
1212 $resql = $this->db->query($sql);
1213 $obj = $this->db->fetch_object($resql);
1214
1215 $attr["is_used_by_products"] = (int) $obj->nb;
1216
1217 return $attr;
1218 }
1219
1233 public function addAttributes($ref, $label, $ref_ext = '')
1234 {
1235 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1236 throw new RestException(401);
1237 }
1238
1239 $prodattr = new ProductAttribute($this->db);
1240 $prodattr->label = $label;
1241 $prodattr->ref = $ref;
1242 $prodattr->ref_ext = $ref_ext;
1243
1244 $resid = $prodattr->create(DolibarrApiAccess::$user);
1245 if ($resid <= 0) {
1246 throw new RestException(500, "Error creating new attribute");
1247 }
1248
1249 return $resid;
1250 }
1251
1265 public function putAttributes($id, $request_data = null)
1266 {
1267 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1268 throw new RestException(401);
1269 }
1270
1271 $prodattr = new ProductAttribute($this->db);
1272
1273 $result = $prodattr->fetch((int) $id);
1274 if ($result == 0) {
1275 throw new RestException(404, 'Attribute not found');
1276 } elseif ($result < 0) {
1277 throw new RestException(500, "Error fetching attribute");
1278 }
1279
1280 foreach ($request_data as $field => $value) {
1281 if ($field == 'rowid') {
1282 continue;
1283 }
1284 if ($field === 'caller') {
1285 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
1286 $prodattr->context['caller'] = $request_data['caller'];
1287 continue;
1288 }
1289
1290 $prodattr->$field = $value;
1291 }
1292
1293 if ($prodattr->update(DolibarrApiAccess::$user) > 0) {
1294 $result = $prodattr->fetch((int) $id);
1295 if ($result == 0) {
1296 throw new RestException(404, 'Attribute not found');
1297 } elseif ($result < 0) {
1298 throw new RestException(500, "Error fetching attribute");
1299 } else {
1300 return $this->_cleanObjectDatas($prodattr);
1301 }
1302 }
1303 throw new RestException(500, "Error updating attribute");
1304 }
1305
1317 public function deleteAttributes($id)
1318 {
1319 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1320 throw new RestException(401);
1321 }
1322
1323 $prodattr = new ProductAttribute($this->db);
1324 $prodattr->id = (int) $id;
1325 $result = $prodattr->delete(DolibarrApiAccess::$user);
1326
1327 if ($result <= 0) {
1328 throw new RestException(500, "Error deleting attribute");
1329 }
1330
1331 return $result;
1332 }
1333
1345 public function getAttributeValueById($id)
1346 {
1347 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1348 throw new RestException(401);
1349 }
1350
1351 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")";
1352
1353 $query = $this->db->query($sql);
1354
1355 if (!$query) {
1356 throw new RestException(401);
1357 }
1358
1359 if (!$this->db->num_rows($query)) {
1360 throw new RestException(404, 'Attribute value not found');
1361 }
1362
1363 $result = $this->db->fetch_object($query);
1364
1365 $attrval = array();
1366 $attrval['id'] = $result->rowid;
1367 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1368 $attrval['ref'] = $result->ref;
1369 $attrval['value'] = $result->value;
1370
1371 return $attrval;
1372 }
1373
1386 public function getAttributeValueByRef($id, $ref)
1387 {
1388 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1389 throw new RestException(401);
1390 }
1391
1392 $ref = trim($ref);
1393
1394 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value";
1395 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1396
1397 $query = $this->db->query($sql);
1398
1399 if (!$query) {
1400 throw new RestException(401);
1401 }
1402
1403 if (!$this->db->num_rows($query)) {
1404 throw new RestException(404, 'Attribute value not found');
1405 }
1406
1407 $result = $this->db->fetch_object($query);
1408
1409 $attrval = array();
1410 $attrval['id'] = $result->rowid;
1411 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1412 $attrval['ref'] = $result->ref;
1413 $attrval['value'] = $result->value;
1414
1415 return $attrval;
1416 }
1417
1429 public function deleteAttributeValueByRef($id, $ref)
1430 {
1431 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1432 throw new RestException(401);
1433 }
1434
1435 $ref = trim($ref);
1436
1437 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_value";
1438 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1439 $query = $this->db->query($sql);
1440
1441 if (!$query) {
1442 throw new RestException(401);
1443 }
1444
1445 if (!$this->db->num_rows($query)) {
1446 throw new RestException(404, 'Attribute value not found');
1447 }
1448
1449 $result = $this->db->fetch_object($query);
1450
1451 $attrval = new ProductAttributeValue($this->db);
1452 $attrval->id = $result->rowid;
1453 $result = $attrval->delete(DolibarrApiAccess::$user);
1454 if ($result > 0) {
1455 return 1;
1456 }
1457
1458 throw new RestException(500, "Error deleting attribute value");
1459 }
1460
1472 public function getAttributeValues($id)
1473 {
1474 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1475 throw new RestException(401);
1476 }
1477
1478 $objectval = new ProductAttributeValue($this->db);
1479
1480 $return = $objectval->fetchAllByProductAttribute((int) $id);
1481
1482 if (count($return) == 0) {
1483 throw new RestException(404, 'Attribute values not found');
1484 }
1485
1486 foreach ($return as $key => $val) {
1487 $return[$key] = $this->_cleanObjectDatas($return[$key]);
1488 }
1489
1490 return $return;
1491 }
1492
1503 public function getAttributeValuesByRef($ref)
1504 {
1505 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1506 throw new RestException(401);
1507 }
1508
1509 $ref = trim($ref);
1510
1511 $return = array();
1512
1513 $sql = "SELECT ";
1514 $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM ".$this->db->prefix()."product_attribute_value as v";
1515 $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."')";
1516
1517 $resql = $this->db->query($sql);
1518
1519 while ($result = $this->db->fetch_object($resql)) {
1520 $tmp = new ProductAttributeValue($this->db);
1521 $tmp->fk_product_attribute = $result->fk_product_attribute;
1522 $tmp->id = $result->rowid;
1523 $tmp->ref = $result->ref;
1524 $tmp->value = $result->value;
1525
1526 $return[] = $this->_cleanObjectDatas($tmp);
1527 }
1528
1529 return $return;
1530 }
1531
1545 public function addAttributeValue($id, $ref, $value)
1546 {
1547 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1548 throw new RestException(401);
1549 }
1550
1551 if (empty($ref) || empty($value)) {
1552 throw new RestException(401);
1553 }
1554
1555 $objectval = new ProductAttributeValue($this->db);
1556 $objectval->fk_product_attribute = ((int) $id);
1557 $objectval->ref = $ref;
1558 $objectval->value = $value;
1559
1560 if ($objectval->create(DolibarrApiAccess::$user) > 0) {
1561 return $objectval->id;
1562 }
1563 throw new RestException(500, "Error creating new attribute value");
1564 }
1565
1578 public function putAttributeValue($id, $request_data)
1579 {
1580 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1581 throw new RestException(401);
1582 }
1583
1584 $objectval = new ProductAttributeValue($this->db);
1585 $result = $objectval->fetch((int) $id);
1586
1587 if ($result == 0) {
1588 throw new RestException(404, 'Attribute value not found');
1589 } elseif ($result < 0) {
1590 throw new RestException(500, "Error fetching attribute value");
1591 }
1592
1593 foreach ($request_data as $field => $value) {
1594 if ($field == 'rowid') {
1595 continue;
1596 }
1597 if ($field === 'caller') {
1598 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
1599 $objectval->context['caller'] = $request_data['caller'];
1600 continue;
1601 }
1602
1603 $objectval->$field = $value;
1604 }
1605
1606 if ($objectval->update(DolibarrApiAccess::$user) > 0) {
1607 $result = $objectval->fetch((int) $id);
1608 if ($result == 0) {
1609 throw new RestException(404, 'Attribute not found');
1610 } elseif ($result < 0) {
1611 throw new RestException(500, "Error fetching attribute");
1612 } else {
1613 return $this->_cleanObjectDatas($objectval);
1614 }
1615 }
1616 throw new RestException(500, "Error updating attribute");
1617 }
1618
1630 public function deleteAttributeValueById($id)
1631 {
1632 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1633 throw new RestException(401);
1634 }
1635
1636 $objectval = new ProductAttributeValue($this->db);
1637 $objectval->id = (int) $id;
1638
1639 if ($objectval->delete(DolibarrApiAccess::$user) > 0) {
1640 return 1;
1641 }
1642 throw new RestException(500, "Error deleting attribute value");
1643 }
1644
1657 public function getVariants($id, $includestock = 0)
1658 {
1659 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1660 throw new RestException(401);
1661 }
1662
1663 $prodcomb = new ProductCombination($this->db);
1664 $combinations = $prodcomb->fetchAllByFkProductParent((int) $id);
1665
1666 foreach ($combinations as $key => $combination) {
1667 $prodc2vp = new ProductCombination2ValuePair($this->db);
1668 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1669 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1670
1671 if (!empty($includestock) && DolibarrApiAccess::$user->rights->stock->lire) {
1672 $productModel = new Product($this->db);
1673 $productModel->fetch((int) $combination->fk_product_child);
1674 $productModel->load_stock($includestock);
1675 $combinations[$key]->stock_warehouse = $this->_cleanObjectDatas($productModel)->stock_warehouse;
1676 }
1677 }
1678
1679 return $combinations;
1680 }
1681
1693 public function getVariantsByProdRef($ref)
1694 {
1695 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1696 throw new RestException(401);
1697 }
1698
1699 $result = $this->product->fetch('', $ref);
1700 if (!$result) {
1701 throw new RestException(404, 'Product not found');
1702 }
1703
1704 $prodcomb = new ProductCombination($this->db);
1705 $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id);
1706
1707 foreach ($combinations as $key => $combination) {
1708 $prodc2vp = new ProductCombination2ValuePair($this->db);
1709 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1710 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1711 }
1712
1713 return $combinations;
1714 }
1715
1736 public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '')
1737 {
1738 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1739 throw new RestException(401);
1740 }
1741
1742 if (empty($id) || empty($features) || !is_array($features)) {
1743 throw new RestException(401);
1744 }
1745
1746 $weight_impact = price2num($weight_impact);
1747 $price_impact = price2num($price_impact);
1748
1749 $prodattr = new ProductAttribute($this->db);
1750 $prodattr_val = new ProductAttributeValue($this->db);
1751 foreach ($features as $id_attr => $id_value) {
1752 if ($prodattr->fetch((int) $id_attr) < 0) {
1753 throw new RestException(401);
1754 }
1755 if ($prodattr_val->fetch((int) $id_value) < 0) {
1756 throw new RestException(401);
1757 }
1758 }
1759
1760 $result = $this->product->fetch((int) $id);
1761 if (!$result) {
1762 throw new RestException(404, 'Product not found');
1763 }
1764
1765 $prodcomb = new ProductCombination($this->db);
1766
1767 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
1768 if ($result > 0) {
1769 return $result;
1770 } else {
1771 throw new RestException(500, "Error creating new product variant");
1772 }
1773 }
1774
1793 public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
1794 {
1795 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1796 throw new RestException(401);
1797 }
1798
1799 if (empty($ref) || empty($features) || !is_array($features)) {
1800 throw new RestException(401);
1801 }
1802
1803 $weight_impact = price2num($weight_impact);
1804 $price_impact = price2num($price_impact);
1805
1806 $prodattr = new ProductAttribute($this->db);
1807 $prodattr_val = new ProductAttributeValue($this->db);
1808 foreach ($features as $id_attr => $id_value) {
1809 if ($prodattr->fetch((int) $id_attr) < 0) {
1810 throw new RestException(404);
1811 }
1812 if ($prodattr_val->fetch((int) $id_value) < 0) {
1813 throw new RestException(404);
1814 }
1815 }
1816
1817 $result = $this->product->fetch('', trim($ref));
1818 if (!$result) {
1819 throw new RestException(404, 'Product not found');
1820 }
1821
1822 $prodcomb = new ProductCombination($this->db);
1823 if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
1824 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
1825 if ($result > 0) {
1826 return $result;
1827 } else {
1828 throw new RestException(500, "Error creating new product variant");
1829 }
1830 } else {
1831 return $prodcomb->id;
1832 }
1833 }
1834
1847 public function putVariant($id, $request_data = null)
1848 {
1849 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1850 throw new RestException(401);
1851 }
1852
1853 $prodcomb = new ProductCombination($this->db);
1854 $prodcomb->fetch((int) $id);
1855
1856 foreach ($request_data as $field => $value) {
1857 if ($field == 'rowid') {
1858 continue;
1859 }
1860 if ($field === 'caller') {
1861 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
1862 $prodcomb->context['caller'] = $request_data['caller'];
1863 continue;
1864 }
1865
1866 $prodcomb->$field = $value;
1867 }
1868
1869 $result = $prodcomb->update(DolibarrApiAccess::$user);
1870 if ($result > 0) {
1871 return 1;
1872 }
1873 throw new RestException(500, "Error editing variant");
1874 }
1875
1887 public function deleteVariant($id)
1888 {
1889 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1890 throw new RestException(401);
1891 }
1892
1893 $prodcomb = new ProductCombination($this->db);
1894 $prodcomb->id = (int) $id;
1895 $result = $prodcomb->delete(DolibarrApiAccess::$user);
1896 if ($result <= 0) {
1897 throw new RestException(500, "Error deleting variant");
1898 }
1899 return $result;
1900 }
1901
1916 public function getStock($id, $selected_warehouse_id = null)
1917 {
1918 if (!DolibarrApiAccess::$user->rights->produit->lire || !DolibarrApiAccess::$user->rights->stock->lire) {
1919 throw new RestException(401);
1920 }
1921
1922 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
1923 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1924 }
1925
1926 $product_model = new Product($this->db);
1927 $product_model->fetch($id);
1928 $product_model->load_stock();
1929
1930 $stockData = $this->_cleanObjectDatas($product_model)->stock_warehouse;
1931 if ($selected_warehouse_id) {
1932 foreach ($stockData as $warehouse_id => $warehouse) {
1933 if ($warehouse_id != $selected_warehouse_id) {
1934 unset($stockData[$warehouse_id]);
1935 }
1936 }
1937 }
1938
1939 return array('stock_warehouses'=>$stockData);
1940 }
1941
1942 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1949 protected function _cleanObjectDatas($object)
1950 {
1951 // phpcs:enable
1952 $object = parent::_cleanObjectDatas($object);
1953
1954 unset($object->statut);
1955
1956 unset($object->regeximgext);
1957 unset($object->price_by_qty);
1958 unset($object->prices_by_qty_id);
1959 unset($object->libelle);
1960 unset($object->product_id_already_linked);
1961 unset($object->reputations);
1962 unset($object->db);
1963 unset($object->name);
1964 unset($object->firstname);
1965 unset($object->lastname);
1966 unset($object->civility_id);
1967 unset($object->contact);
1968 unset($object->contact_id);
1969 unset($object->thirdparty);
1970 unset($object->user);
1971 unset($object->origin);
1972 unset($object->origin_id);
1973 unset($object->fourn_pu);
1974 unset($object->fourn_price_base_type);
1975 unset($object->fourn_socid);
1976 unset($object->ref_fourn);
1977 unset($object->ref_supplier);
1978 unset($object->product_fourn_id);
1979 unset($object->fk_project);
1980
1981 unset($object->mode_reglement_id);
1982 unset($object->cond_reglement_id);
1983 unset($object->demand_reason_id);
1984 unset($object->transport_mode_id);
1985 unset($object->cond_reglement);
1986 unset($object->shipping_method_id);
1987 unset($object->model_pdf);
1988 unset($object->note);
1989
1990 unset($object->nbphoto);
1991 unset($object->recuperableonly);
1992 unset($object->multiprices_recuperableonly);
1993 unset($object->tva_npr);
1994 unset($object->lines);
1995 unset($object->fk_bank);
1996 unset($object->fk_account);
1997
1998 unset($object->supplierprices); // Mut use another API to get them
1999
2000 if (empty(DolibarrApiAccess::$user->rights->stock->lire)) {
2001 unset($object->stock_reel);
2002 unset($object->stock_theorique);
2003 unset($object->stock_warehouse);
2004 }
2005
2006 return $object;
2007 }
2008
2016 private function _validate($data)
2017 {
2018 $product = array();
2019 foreach (Products::$FIELDS as $field) {
2020 if (!isset($data[$field])) {
2021 throw new RestException(400, "$field field missing");
2022 }
2023 $product[$field] = $data[$field];
2024 }
2025 return $product;
2026 }
2027
2047 private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false, $includetrans = false)
2048 {
2049 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
2050 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
2051 }
2052
2053 $id = (empty($id) ? 0 : $id);
2054
2055 if (!DolibarrApiAccess::$user->rights->produit->lire) {
2056 throw new RestException(403);
2057 }
2058
2059 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode, 0, 0, ($includetrans ? 0 : 1));
2060 if (!$result) {
2061 throw new RestException(404, 'Product not found');
2062 }
2063
2064 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
2065 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2066 }
2067
2068 if (!empty($includestockdata) && DolibarrApiAccess::$user->rights->stock->lire) {
2069 $this->product->load_stock($includestockdata);
2070
2071 if (is_array($this->product->stock_warehouse)) {
2072 foreach ($this->product->stock_warehouse as $keytmp => $valtmp) {
2073 if (isset($this->product->stock_warehouse[$keytmp]->detail_batch) && is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) {
2074 foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
2075 unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
2076 }
2077 }
2078 }
2079 }
2080 }
2081
2082 if ($includesubproducts) {
2083 $childsArbo = $this->product->getChildsArbo($id, 1);
2084
2085 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
2086 $childs = array();
2087 foreach ($childsArbo as $values) {
2088 $childs[] = array_combine($keys, $values);
2089 }
2090
2091 $this->product->sousprods = $childs;
2092 }
2093
2094 if ($includeparentid) {
2095 $prodcomb = new ProductCombination($this->db);
2096 $this->product->fk_product_parent = null;
2097 if (($fk_product_parent = $prodcomb->fetchByFkProductChild($this->product->id)) > 0) {
2098 $this->product->fk_product_parent = $fk_product_parent;
2099 }
2100 }
2101
2102 if ($includeifobjectisused) {
2103 $this->product->is_object_used = ($this->product->isObjectUsed() > 0);
2104 }
2105
2106 return $this->_cleanObjectDatas($this->product);
2107 }
2108}
Class to manage categories.
Class for API REST v1.
Definition api.class.php:31
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
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.
File of class to manage predefined price products or services by customer.
Class to manage predefined suppliers products.
Class to manage products or services.
_cleanObjectDatas($object)
Clean sensible object datas.
getAttributes($sortfield="t.ref", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
Get attributes.
putAttributeValue($id, $request_data)
Update attribute value.
deleteAttributes($id)
Delete attributes by id.
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.
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, $properties='')
List products.
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.
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 =...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
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.