dolibarr 19.0.4
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 if ($field == 'array_options' && is_array($value)) {
375 foreach ($value as $index => $val) {
376 $this->product->array_options[$index] = $this->_checkValForAPI($field, $val, $this->product);
377 }
378 continue;
379 }
380
381 $this->product->$field = $this->_checkValForAPI($field, $value, $this->product);
382 }
383
384 $updatetype = false;
385 if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) {
386 $updatetype = true;
387 }
388
389 $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype);
390
391 // If price mode is 1 price per product
392 if ($result > 0 && getDolGlobalString('PRODUCT_PRICE_UNIQ')) {
393 // We update price only if it was changed
394 $pricemodified = false;
395 if ($this->product->price_base_type != $oldproduct->price_base_type) {
396 $pricemodified = true;
397 } else {
398 if ($this->product->tva_tx != $oldproduct->tva_tx) {
399 $pricemodified = true;
400 }
401 if ($this->product->tva_npr != $oldproduct->tva_npr) {
402 $pricemodified = true;
403 }
404 if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
405 $pricemodified = true;
406 }
407
408 if ($this->product->price_base_type == 'TTC') {
409 if ($this->product->price_ttc != $oldproduct->price_ttc) {
410 $pricemodified = true;
411 }
412 if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
413 $pricemodified = true;
414 }
415 } else {
416 if ($this->product->price != $oldproduct->price) {
417 $pricemodified = true;
418 }
419 if ($this->product->price_min != $oldproduct->price_min) {
420 $pricemodified = true;
421 }
422 }
423 }
424
425 if ($pricemodified) {
426 $newvat = $this->product->tva_tx;
427 $newnpr = $this->product->tva_npr;
428 $newvatsrccode = $this->product->default_vat_code;
429
430 $newprice = $this->product->price;
431 $newpricemin = $this->product->price_min;
432 if ($this->product->price_base_type == 'TTC') {
433 $newprice = $this->product->price_ttc;
434 $newpricemin = $this->product->price_min_ttc;
435 }
436
437 $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode);
438 }
439 }
440
441 if ($result <= 0) {
442 throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors));
443 }
444
445 return $this->get($id);
446 }
447
454 public function delete($id)
455 {
456 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
457 throw new RestException(401);
458 }
459 $result = $this->product->fetch($id);
460 if (!$result) {
461 throw new RestException(404, 'Product not found');
462 }
463
464 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
465 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
466 }
467
468 // The Product::delete() method uses the global variable $user.
469 global $user;
470 $user = DolibarrApiAccess::$user;
471
472 $res = $this->product->delete(DolibarrApiAccess::$user);
473 if ($res < 0) {
474 throw new RestException(500, "Can't delete, error occurs");
475 } elseif ($res == 0) {
476 throw new RestException(409, "Can't delete, that product is probably used");
477 }
478
479 return array(
480 'success' => array(
481 'code' => 200,
482 'message' => 'Object deleted'
483 )
484 );
485 }
486
499 public function getSubproducts($id)
500 {
501 if (!DolibarrApiAccess::$user->rights->produit->lire) {
502 throw new RestException(401);
503 }
504
505 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
506 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
507 }
508
509 $childsArbo = $this->product->getChildsArbo($id, 1);
510
511 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
512 $childs = array();
513 foreach ($childsArbo as $values) {
514 $childs[] = array_combine($keys, $values);
515 }
516
517 return $childs;
518 }
519
537 public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1)
538 {
539 if (!DolibarrApiAccess::$user->rights->produit->creer) {
540 throw new RestException(401);
541 }
542
543 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
544 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
545 }
546
547 $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec);
548 if ($result <= 0) {
549 throw new RestException(500, "Error adding product child");
550 }
551 return $result;
552 }
553
567 public function delSubproducts($id, $subproduct_id)
568 {
569 if (!DolibarrApiAccess::$user->rights->produit->creer) {
570 throw new RestException(401);
571 }
572
573 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
574 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
575 }
576
577 $result = $this->product->del_sousproduit($id, $subproduct_id);
578 if ($result <= 0) {
579 throw new RestException(500, "Error while removing product child");
580 }
581 return $result;
582 }
583
584
598 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
599 {
600 if (!DolibarrApiAccess::$user->rights->categorie->lire) {
601 throw new RestException(401);
602 }
603
604 $categories = new Categorie($this->db);
605
606 $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page);
607
608 if ($result < 0) {
609 throw new RestException(503, 'Error when retrieve category list : '.join(',', array_merge(array($categories->error), $categories->errors)));
610 }
611
612 return $result;
613 }
614
624 public function getCustomerPricesPerSegment($id)
625 {
626 global $conf;
627
628 if (!DolibarrApiAccess::$user->rights->produit->lire) {
629 throw new RestException(401);
630 }
631
632 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
633 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
634 }
635
636 $result = $this->product->fetch($id);
637 if (!$result) {
638 throw new RestException(404, 'Product not found');
639 }
640
641 if ($result < 0) {
642 throw new RestException(503, 'Error when retrieve prices list : '.join(',', array_merge(array($this->product->error), $this->product->errors)));
643 }
644
645 return array(
646 'multiprices'=>$this->product->multiprices,
647 'multiprices_inc_tax'=>$this->product->multiprices_ttc,
648 'multiprices_min'=>$this->product->multiprices_min,
649 'multiprices_min_inc_tax'=>$this->product->multiprices_min_ttc,
650 'multiprices_vat'=>$this->product->multiprices_tva_tx,
651 'multiprices_base_type'=>$this->product->multiprices_base_type,
652 //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code
653 );
654 }
655
666 public function getCustomerPricesPerCustomer($id, $thirdparty_id = '')
667 {
668 global $conf;
669
670 if (!DolibarrApiAccess::$user->rights->produit->lire) {
671 throw new RestException(401);
672 }
673
674 if (!getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
675 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
676 }
677
678 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
679 if ($socid > 0 && $socid != $thirdparty_id) {
680 throw new RestException(401, 'Getting prices for all customers or for the customer ID '.$thirdparty_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
681 }
682
683 $result = $this->product->fetch($id);
684 if (!$result) {
685 throw new RestException(404, 'Product not found');
686 }
687
688 if ($result > 0) {
689 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
690 $prodcustprice = new ProductCustomerPrice($this->db);
691 $filter = array();
692 $filter['t.fk_product'] = $id;
693 if ($thirdparty_id) {
694 $filter['t.fk_soc'] = $thirdparty_id;
695 }
696 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
697 }
698
699 if (empty($prodcustprice->lines)) {
700 throw new RestException(404, 'Prices not found');
701 }
702
703 return $prodcustprice->lines;
704 }
705
715 public function getCustomerPricesPerQuantity($id)
716 {
717 global $conf;
718
719 if (!DolibarrApiAccess::$user->rights->produit->lire) {
720 throw new RestException(401);
721 }
722
723 if (!getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
724 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
725 }
726
727 $result = $this->product->fetch($id);
728 if (!$result) {
729 throw new RestException(404, 'Product not found');
730 }
731
732 if ($result < 0) {
733 throw new RestException(503, 'Error when retrieve prices list : '.join(',', array_merge(array($this->product->error), $this->product->errors)));
734 }
735
736 return array(
737 'prices_by_qty'=>$this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product
738 'prices_by_qty_list'=>$this->product->prices_by_qty_list[0]
739 );
740 }
741
775 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)
776 {
777 if (!DolibarrApiAccess::$user->rights->produit->creer) {
778 throw new RestException(401);
779 }
780
781 $result = $this->productsupplier->fetch($id);
782 if (!$result) {
783 throw new RestException(404, 'Product not found');
784 }
785
786 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
787 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
788 }
789
790 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
791 if ($socid > 0 && $socid != $fourn_id) {
792 throw new RestException(401, 'Adding purchase price for the supplier ID '.$fourn_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
793 }
794
795 $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty);
796 if ($result < 0) {
797 throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror());
798 }
799
800 $fourn = new Fournisseur($this->db);
801 $result = $fourn->fetch($fourn_id);
802 if ($result <= 0) {
803 throw new RestException(404, 'Supplier not found');
804 }
805
806 // Clean data
807 $ref_fourn = sanitizeVal($ref_fourn, 'alphanohtml');
808 $desc_fourn = sanitizeVal($desc_fourn, 'restricthtml');
809 $barcode = sanitizeVal($barcode, 'alphanohtml');
810
811 $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);
812
813 if ($result <= 0) {
814 throw new RestException(500, "Error updating buy price : ".$this->db->lasterror());
815 }
816 return (int) $this->productsupplier->product_fourn_price_id;
817 }
818
833 public function deletePurchasePrice($id, $priceid)
834 {
835 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
836 throw new RestException(401);
837 }
838 $result = $this->productsupplier->fetch($id);
839 if (!$result) {
840 throw new RestException(404, 'Product not found');
841 }
842
843 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
844 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
845 }
846
847 $resultsupplier = 0;
848 if ($result > 0) {
849 $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid);
850 }
851
852 return $resultsupplier;
853 }
854
870 public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '')
871 {
872 global $db, $conf;
873
874 if (!DolibarrApiAccess::$user->rights->produit->lire) {
875 throw new RestException(401);
876 }
877
878 $obj_ret = array();
879
880 // Force id of company for external users
881 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
882 if ($socid > 0) {
883 if ($supplier != $socid || empty($supplier)) {
884 throw new RestException(401, 'As an external user, you can request only for your supplier id = '.$socid);
885 }
886 }
887
888 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
889 $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
890
891 if ($category > 0) {
892 $sql .= ", ".$this->db->prefix()."categorie_product as c";
893 }
894 $sql .= ", ".$this->db->prefix()."product_fournisseur_price as s";
895
896 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
897
898 if ($supplier > 0) {
899 $sql .= " AND s.fk_soc = ".((int) $supplier);
900 }
901 if ($socid > 0) { // if external user
902 $sql .= " AND s.fk_soc = ".((int) $socid);
903 }
904 $sql .= " AND s.fk_product = t.rowid";
905 // Select products of given category
906 if ($category > 0) {
907 $sql .= " AND c.fk_categorie = ".((int) $category);
908 $sql .= " AND c.fk_product = t.rowid";
909 }
910 if ($mode == 1) {
911 // Show only products
912 $sql .= " AND t.fk_product_type = 0";
913 } elseif ($mode == 2) {
914 // Show only services
915 $sql .= " AND t.fk_product_type = 1";
916 }
917 // Add sql filters
918 if ($sqlfilters) {
919 $errormessage = '';
920 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
921 if ($errormessage) {
922 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
923 }
924 }
925
926 $sql .= $this->db->order($sortfield, $sortorder);
927 if ($limit) {
928 if ($page < 0) {
929 $page = 0;
930 }
931 $offset = $limit * $page;
932 $sql .= $this->db->plimit($limit + 1, $offset);
933 }
934 $result = $this->db->query($sql);
935 if ($result) {
936 $num = $this->db->num_rows($result);
937 $min = min($num, ($limit <= 0 ? $num : $limit));
938 $i = 0;
939 while ($i < $min) {
940 $obj = $this->db->fetch_object($result);
941
942 $product_fourn = new ProductFournisseur($this->db);
943 $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0);
944 foreach ($product_fourn_list as $tmpobj) {
945 $this->_cleanObjectDatas($tmpobj);
946 }
947
948 //var_dump($product_fourn_list->db);exit;
949 $obj_ret[$obj->rowid] = $product_fourn_list;
950
951 $i++;
952 }
953 } else {
954 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
955 }
956
957 return $obj_ret;
958 }
959
979 public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '')
980 {
981 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
982 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
983 }
984
985 $id = (empty($id) ? 0 : $id);
986
987 if (!DolibarrApiAccess::$user->rights->produit->lire) {
988 throw new RestException(403);
989 }
990
991 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
992
993 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode);
994 if (!$result) {
995 throw new RestException(404, 'Product not found');
996 }
997
998 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
999 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1000 }
1001
1002 $product_fourn_list = array();
1003
1004 if ($result) {
1005 $product_fourn = new ProductFournisseur($this->db);
1006 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0, ($socid > 0 ? $socid : 0));
1007 }
1008
1009 foreach ($product_fourn_list as $tmpobj) {
1010 $this->_cleanObjectDatas($tmpobj);
1011 }
1012
1013 return $this->_cleanObjectDatas($product_fourn_list);
1014 }
1015
1033 public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
1034 {
1035 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1036 throw new RestException(401);
1037 }
1038
1039 $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.position, t.entity";
1040 $sql .= " FROM ".$this->db->prefix()."product_attribute as t";
1041 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
1042
1043 // Add sql filters
1044 if ($sqlfilters) {
1045 $errormessage = '';
1046 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
1047 if ($errormessage) {
1048 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
1049 }
1050 }
1051
1052 $sql .= $this->db->order($sortfield, $sortorder);
1053 if ($limit) {
1054 if ($page < 0) {
1055 $page = 0;
1056 }
1057 $offset = $limit * $page;
1058
1059 $sql .= $this->db->plimit($limit, $offset);
1060 }
1061
1062 $resql = $this->db->query($sql);
1063
1064 if (!$resql) {
1065 throw new RestException(503, 'Error when retrieving product attribute list : '.$this->db->lasterror());
1066 }
1067
1068 $return = array();
1069 while ($obj = $this->db->fetch_object($resql)) {
1070 $tmp = new ProductAttribute($this->db);
1071 $tmp->id = $obj->rowid;
1072 $tmp->ref = $obj->ref;
1073 $tmp->ref_ext = $obj->ref_ext;
1074 $tmp->label = $obj->label;
1075 $tmp->position = $obj->position;
1076 $tmp->entity = $obj->entity;
1077
1078 $return[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp), $properties);
1079 }
1080
1081 return $return;
1082 }
1083
1095 public function getAttributeById($id)
1096 {
1097 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1098 throw new RestException(401);
1099 }
1100
1101 $prodattr = new ProductAttribute($this->db);
1102 $result = $prodattr->fetch((int) $id);
1103
1104 if ($result < 0) {
1105 throw new RestException(404, "Product attribute not found");
1106 }
1107
1108 $fields = ["id", "ref", "ref_ext", "label", "position", "entity"];
1109
1110 foreach ($prodattr as $field => $value) {
1111 if (!in_array($field, $fields)) {
1112 unset($prodattr->{$field});
1113 }
1114 }
1115
1116 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1117 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1118 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")";
1119
1120 $resql = $this->db->query($sql);
1121 $obj = $this->db->fetch_object($resql);
1122 $prodattr->is_used_by_products = (int) $obj->nb;
1123
1124 return $this->_cleanObjectDatas($prodattr);
1125 }
1126
1138 public function getAttributesByRef($ref)
1139 {
1140 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1141 throw new RestException(401);
1142 }
1143
1144 $ref = trim($ref);
1145
1146 $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').")";
1147
1148 $query = $this->db->query($sql);
1149
1150 if (!$this->db->num_rows($query)) {
1151 throw new RestException(404);
1152 }
1153
1154 $result = $this->db->fetch_object($query);
1155
1156 $attr = array();
1157 $attr['id'] = $result->rowid;
1158 $attr['ref'] = $result->ref;
1159 $attr['ref_ext'] = $result->ref_ext;
1160 $attr['label'] = $result->label;
1161 $attr['rang'] = $result->position;
1162 $attr['position'] = $result->position;
1163 $attr['entity'] = $result->entity;
1164
1165 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1166 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1167 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1168
1169 $resql = $this->db->query($sql);
1170 $obj = $this->db->fetch_object($resql);
1171
1172 $attr["is_used_by_products"] = (int) $obj->nb;
1173
1174 return $attr;
1175 }
1176
1188 public function getAttributesByRefExt($ref_ext)
1189 {
1190 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1191 throw new RestException(401);
1192 }
1193
1194 $ref_ext = trim($ref_ext);
1195
1196 $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').")";
1197
1198 $query = $this->db->query($sql);
1199
1200 if (!$this->db->num_rows($query)) {
1201 throw new RestException(404);
1202 }
1203
1204 $result = $this->db->fetch_object($query);
1205
1206 $attr = array();
1207 $attr['id'] = $result->rowid;
1208 $attr['ref'] = $result->ref;
1209 $attr['ref_ext'] = $result->ref_ext;
1210 $attr['label'] = $result->label;
1211 $attr['rang'] = $result->position;
1212 $attr['position'] = $result->position;
1213 $attr['entity'] = $result->entity;
1214
1215 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1216 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1217 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1218
1219 $resql = $this->db->query($sql);
1220 $obj = $this->db->fetch_object($resql);
1221
1222 $attr["is_used_by_products"] = (int) $obj->nb;
1223
1224 return $attr;
1225 }
1226
1240 public function addAttributes($ref, $label, $ref_ext = '')
1241 {
1242 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1243 throw new RestException(401);
1244 }
1245
1246 $prodattr = new ProductAttribute($this->db);
1247 $prodattr->label = $label;
1248 $prodattr->ref = $ref;
1249 $prodattr->ref_ext = $ref_ext;
1250
1251 $resid = $prodattr->create(DolibarrApiAccess::$user);
1252 if ($resid <= 0) {
1253 throw new RestException(500, "Error creating new attribute");
1254 }
1255
1256 return $resid;
1257 }
1258
1272 public function putAttributes($id, $request_data = null)
1273 {
1274 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1275 throw new RestException(401);
1276 }
1277
1278 $prodattr = new ProductAttribute($this->db);
1279
1280 $result = $prodattr->fetch((int) $id);
1281 if ($result == 0) {
1282 throw new RestException(404, 'Attribute not found');
1283 } elseif ($result < 0) {
1284 throw new RestException(500, "Error fetching attribute");
1285 }
1286
1287 foreach ($request_data as $field => $value) {
1288 if ($field == 'rowid') {
1289 continue;
1290 }
1291 if ($field === 'caller') {
1292 // 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
1293 $prodattr->context['caller'] = $request_data['caller'];
1294 continue;
1295 }
1296
1297 $prodattr->$field = $value;
1298 }
1299
1300 if ($prodattr->update(DolibarrApiAccess::$user) > 0) {
1301 $result = $prodattr->fetch((int) $id);
1302 if ($result == 0) {
1303 throw new RestException(404, 'Attribute not found');
1304 } elseif ($result < 0) {
1305 throw new RestException(500, "Error fetching attribute");
1306 } else {
1307 return $this->_cleanObjectDatas($prodattr);
1308 }
1309 }
1310 throw new RestException(500, "Error updating attribute");
1311 }
1312
1324 public function deleteAttributes($id)
1325 {
1326 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1327 throw new RestException(401);
1328 }
1329
1330 $prodattr = new ProductAttribute($this->db);
1331 $prodattr->id = (int) $id;
1332 $result = $prodattr->delete(DolibarrApiAccess::$user);
1333
1334 if ($result <= 0) {
1335 throw new RestException(500, "Error deleting attribute");
1336 }
1337
1338 return $result;
1339 }
1340
1352 public function getAttributeValueById($id)
1353 {
1354 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1355 throw new RestException(401);
1356 }
1357
1358 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")";
1359
1360 $query = $this->db->query($sql);
1361
1362 if (!$query) {
1363 throw new RestException(401);
1364 }
1365
1366 if (!$this->db->num_rows($query)) {
1367 throw new RestException(404, 'Attribute value not found');
1368 }
1369
1370 $result = $this->db->fetch_object($query);
1371
1372 $attrval = array();
1373 $attrval['id'] = $result->rowid;
1374 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1375 $attrval['ref'] = $result->ref;
1376 $attrval['value'] = $result->value;
1377
1378 return $attrval;
1379 }
1380
1393 public function getAttributeValueByRef($id, $ref)
1394 {
1395 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1396 throw new RestException(401);
1397 }
1398
1399 $ref = trim($ref);
1400
1401 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value";
1402 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1403
1404 $query = $this->db->query($sql);
1405
1406 if (!$query) {
1407 throw new RestException(401);
1408 }
1409
1410 if (!$this->db->num_rows($query)) {
1411 throw new RestException(404, 'Attribute value not found');
1412 }
1413
1414 $result = $this->db->fetch_object($query);
1415
1416 $attrval = array();
1417 $attrval['id'] = $result->rowid;
1418 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1419 $attrval['ref'] = $result->ref;
1420 $attrval['value'] = $result->value;
1421
1422 return $attrval;
1423 }
1424
1436 public function deleteAttributeValueByRef($id, $ref)
1437 {
1438 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1439 throw new RestException(401);
1440 }
1441
1442 $ref = trim($ref);
1443
1444 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_value";
1445 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1446 $query = $this->db->query($sql);
1447
1448 if (!$query) {
1449 throw new RestException(401);
1450 }
1451
1452 if (!$this->db->num_rows($query)) {
1453 throw new RestException(404, 'Attribute value not found');
1454 }
1455
1456 $result = $this->db->fetch_object($query);
1457
1458 $attrval = new ProductAttributeValue($this->db);
1459 $attrval->id = $result->rowid;
1460 $result = $attrval->delete(DolibarrApiAccess::$user);
1461 if ($result > 0) {
1462 return 1;
1463 }
1464
1465 throw new RestException(500, "Error deleting attribute value");
1466 }
1467
1479 public function getAttributeValues($id)
1480 {
1481 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1482 throw new RestException(401);
1483 }
1484
1485 $objectval = new ProductAttributeValue($this->db);
1486
1487 $return = $objectval->fetchAllByProductAttribute((int) $id);
1488
1489 if (count($return) == 0) {
1490 throw new RestException(404, 'Attribute values not found');
1491 }
1492
1493 foreach ($return as $key => $val) {
1494 $return[$key] = $this->_cleanObjectDatas($return[$key]);
1495 }
1496
1497 return $return;
1498 }
1499
1510 public function getAttributeValuesByRef($ref)
1511 {
1512 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1513 throw new RestException(401);
1514 }
1515
1516 $ref = trim($ref);
1517
1518 $return = array();
1519
1520 $sql = "SELECT ";
1521 $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM ".$this->db->prefix()."product_attribute_value as v";
1522 $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."')";
1523
1524 $resql = $this->db->query($sql);
1525
1526 while ($result = $this->db->fetch_object($resql)) {
1527 $tmp = new ProductAttributeValue($this->db);
1528 $tmp->fk_product_attribute = $result->fk_product_attribute;
1529 $tmp->id = $result->rowid;
1530 $tmp->ref = $result->ref;
1531 $tmp->value = $result->value;
1532
1533 $return[] = $this->_cleanObjectDatas($tmp);
1534 }
1535
1536 return $return;
1537 }
1538
1552 public function addAttributeValue($id, $ref, $value)
1553 {
1554 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1555 throw new RestException(401);
1556 }
1557
1558 if (empty($ref) || empty($value)) {
1559 throw new RestException(401);
1560 }
1561
1562 $objectval = new ProductAttributeValue($this->db);
1563 $objectval->fk_product_attribute = ((int) $id);
1564 $objectval->ref = $ref;
1565 $objectval->value = $value;
1566
1567 if ($objectval->create(DolibarrApiAccess::$user) > 0) {
1568 return $objectval->id;
1569 }
1570 throw new RestException(500, "Error creating new attribute value");
1571 }
1572
1585 public function putAttributeValue($id, $request_data)
1586 {
1587 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1588 throw new RestException(401);
1589 }
1590
1591 $objectval = new ProductAttributeValue($this->db);
1592 $result = $objectval->fetch((int) $id);
1593
1594 if ($result == 0) {
1595 throw new RestException(404, 'Attribute value not found');
1596 } elseif ($result < 0) {
1597 throw new RestException(500, "Error fetching attribute value");
1598 }
1599
1600 foreach ($request_data as $field => $value) {
1601 if ($field == 'rowid') {
1602 continue;
1603 }
1604 if ($field === 'caller') {
1605 // 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
1606 $objectval->context['caller'] = $request_data['caller'];
1607 continue;
1608 }
1609
1610 $objectval->$field = $value;
1611 }
1612
1613 if ($objectval->update(DolibarrApiAccess::$user) > 0) {
1614 $result = $objectval->fetch((int) $id);
1615 if ($result == 0) {
1616 throw new RestException(404, 'Attribute not found');
1617 } elseif ($result < 0) {
1618 throw new RestException(500, "Error fetching attribute");
1619 } else {
1620 return $this->_cleanObjectDatas($objectval);
1621 }
1622 }
1623 throw new RestException(500, "Error updating attribute");
1624 }
1625
1637 public function deleteAttributeValueById($id)
1638 {
1639 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1640 throw new RestException(401);
1641 }
1642
1643 $objectval = new ProductAttributeValue($this->db);
1644 $objectval->id = (int) $id;
1645
1646 if ($objectval->delete(DolibarrApiAccess::$user) > 0) {
1647 return 1;
1648 }
1649 throw new RestException(500, "Error deleting attribute value");
1650 }
1651
1664 public function getVariants($id, $includestock = 0)
1665 {
1666 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1667 throw new RestException(401);
1668 }
1669
1670 $prodcomb = new ProductCombination($this->db);
1671 $combinations = $prodcomb->fetchAllByFkProductParent((int) $id);
1672
1673 foreach ($combinations as $key => $combination) {
1674 $prodc2vp = new ProductCombination2ValuePair($this->db);
1675 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1676 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1677
1678 if (!empty($includestock) && DolibarrApiAccess::$user->rights->stock->lire) {
1679 $productModel = new Product($this->db);
1680 $productModel->fetch((int) $combination->fk_product_child);
1681 $productModel->load_stock($includestock);
1682 $combinations[$key]->stock_warehouse = $this->_cleanObjectDatas($productModel)->stock_warehouse;
1683 }
1684 }
1685
1686 return $combinations;
1687 }
1688
1700 public function getVariantsByProdRef($ref)
1701 {
1702 if (!DolibarrApiAccess::$user->rights->produit->lire) {
1703 throw new RestException(401);
1704 }
1705
1706 $result = $this->product->fetch('', $ref);
1707 if (!$result) {
1708 throw new RestException(404, 'Product not found');
1709 }
1710
1711 $prodcomb = new ProductCombination($this->db);
1712 $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id);
1713
1714 foreach ($combinations as $key => $combination) {
1715 $prodc2vp = new ProductCombination2ValuePair($this->db);
1716 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1717 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1718 }
1719
1720 return $combinations;
1721 }
1722
1743 public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '')
1744 {
1745 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1746 throw new RestException(401);
1747 }
1748
1749 if (empty($id) || empty($features) || !is_array($features)) {
1750 throw new RestException(401);
1751 }
1752
1753 $weight_impact = price2num($weight_impact);
1754 $price_impact = price2num($price_impact);
1755
1756 $prodattr = new ProductAttribute($this->db);
1757 $prodattr_val = new ProductAttributeValue($this->db);
1758 foreach ($features as $id_attr => $id_value) {
1759 if ($prodattr->fetch((int) $id_attr) < 0) {
1760 throw new RestException(401);
1761 }
1762 if ($prodattr_val->fetch((int) $id_value) < 0) {
1763 throw new RestException(401);
1764 }
1765 }
1766
1767 $result = $this->product->fetch((int) $id);
1768 if (!$result) {
1769 throw new RestException(404, 'Product not found');
1770 }
1771
1772 $prodcomb = new ProductCombination($this->db);
1773
1774 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
1775 if ($result > 0) {
1776 return $result;
1777 } else {
1778 throw new RestException(500, "Error creating new product variant");
1779 }
1780 }
1781
1800 public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
1801 {
1802 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1803 throw new RestException(401);
1804 }
1805
1806 if (empty($ref) || empty($features) || !is_array($features)) {
1807 throw new RestException(401);
1808 }
1809
1810 $weight_impact = price2num($weight_impact);
1811 $price_impact = price2num($price_impact);
1812
1813 $prodattr = new ProductAttribute($this->db);
1814 $prodattr_val = new ProductAttributeValue($this->db);
1815 foreach ($features as $id_attr => $id_value) {
1816 if ($prodattr->fetch((int) $id_attr) < 0) {
1817 throw new RestException(404);
1818 }
1819 if ($prodattr_val->fetch((int) $id_value) < 0) {
1820 throw new RestException(404);
1821 }
1822 }
1823
1824 $result = $this->product->fetch('', trim($ref));
1825 if (!$result) {
1826 throw new RestException(404, 'Product not found');
1827 }
1828
1829 $prodcomb = new ProductCombination($this->db);
1830 if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
1831 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
1832 if ($result > 0) {
1833 return $result;
1834 } else {
1835 throw new RestException(500, "Error creating new product variant");
1836 }
1837 } else {
1838 return $prodcomb->id;
1839 }
1840 }
1841
1854 public function putVariant($id, $request_data = null)
1855 {
1856 if (!DolibarrApiAccess::$user->rights->produit->creer) {
1857 throw new RestException(401);
1858 }
1859
1860 $prodcomb = new ProductCombination($this->db);
1861 $prodcomb->fetch((int) $id);
1862
1863 foreach ($request_data as $field => $value) {
1864 if ($field == 'rowid') {
1865 continue;
1866 }
1867 if ($field === 'caller') {
1868 // 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
1869 $prodcomb->context['caller'] = $request_data['caller'];
1870 continue;
1871 }
1872
1873 $prodcomb->$field = $value;
1874 }
1875
1876 $result = $prodcomb->update(DolibarrApiAccess::$user);
1877 if ($result > 0) {
1878 return 1;
1879 }
1880 throw new RestException(500, "Error editing variant");
1881 }
1882
1894 public function deleteVariant($id)
1895 {
1896 if (!DolibarrApiAccess::$user->rights->produit->supprimer) {
1897 throw new RestException(401);
1898 }
1899
1900 $prodcomb = new ProductCombination($this->db);
1901 $prodcomb->id = (int) $id;
1902 $result = $prodcomb->delete(DolibarrApiAccess::$user);
1903 if ($result <= 0) {
1904 throw new RestException(500, "Error deleting variant");
1905 }
1906 return $result;
1907 }
1908
1923 public function getStock($id, $selected_warehouse_id = null)
1924 {
1925 if (!DolibarrApiAccess::$user->rights->produit->lire || !DolibarrApiAccess::$user->rights->stock->lire) {
1926 throw new RestException(401);
1927 }
1928
1929 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
1930 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1931 }
1932
1933 $product_model = new Product($this->db);
1934 $product_model->fetch($id);
1935 $product_model->load_stock();
1936
1937 $stockData = $this->_cleanObjectDatas($product_model)->stock_warehouse;
1938 if ($selected_warehouse_id) {
1939 foreach ($stockData as $warehouse_id => $warehouse) {
1940 if ($warehouse_id != $selected_warehouse_id) {
1941 unset($stockData[$warehouse_id]);
1942 }
1943 }
1944 }
1945
1946 return array('stock_warehouses'=>$stockData);
1947 }
1948
1949 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1956 protected function _cleanObjectDatas($object)
1957 {
1958 // phpcs:enable
1959 $object = parent::_cleanObjectDatas($object);
1960
1961 unset($object->statut);
1962
1963 unset($object->regeximgext);
1964 unset($object->price_by_qty);
1965 unset($object->prices_by_qty_id);
1966 unset($object->libelle);
1967 unset($object->product_id_already_linked);
1968 unset($object->reputations);
1969 unset($object->db);
1970 unset($object->name);
1971 unset($object->firstname);
1972 unset($object->lastname);
1973 unset($object->civility_id);
1974 unset($object->contact);
1975 unset($object->contact_id);
1976 unset($object->thirdparty);
1977 unset($object->user);
1978 unset($object->origin);
1979 unset($object->origin_id);
1980 unset($object->fourn_pu);
1981 unset($object->fourn_price_base_type);
1982 unset($object->fourn_socid);
1983 unset($object->ref_fourn);
1984 unset($object->ref_supplier);
1985 unset($object->product_fourn_id);
1986 unset($object->fk_project);
1987
1988 unset($object->mode_reglement_id);
1989 unset($object->cond_reglement_id);
1990 unset($object->demand_reason_id);
1991 unset($object->transport_mode_id);
1992 unset($object->cond_reglement);
1993 unset($object->shipping_method_id);
1994 unset($object->model_pdf);
1995 unset($object->note);
1996
1997 unset($object->nbphoto);
1998 unset($object->recuperableonly);
1999 unset($object->multiprices_recuperableonly);
2000 unset($object->tva_npr);
2001 unset($object->lines);
2002 unset($object->fk_bank);
2003 unset($object->fk_account);
2004
2005 unset($object->supplierprices); // Mut use another API to get them
2006
2007 if (empty(DolibarrApiAccess::$user->rights->stock->lire)) {
2008 unset($object->stock_reel);
2009 unset($object->stock_theorique);
2010 unset($object->stock_warehouse);
2011 }
2012
2013 return $object;
2014 }
2015
2023 private function _validate($data)
2024 {
2025 $product = array();
2026 foreach (Products::$FIELDS as $field) {
2027 if (!isset($data[$field])) {
2028 throw new RestException(400, "$field field missing");
2029 }
2030 $product[$field] = $data[$field];
2031 }
2032 return $product;
2033 }
2034
2054 private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false, $includetrans = false)
2055 {
2056 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
2057 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
2058 }
2059
2060 $id = (empty($id) ? 0 : $id);
2061
2062 if (!DolibarrApiAccess::$user->rights->produit->lire) {
2063 throw new RestException(403);
2064 }
2065
2066 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode, 0, 0, ($includetrans ? 0 : 1));
2067 if (!$result) {
2068 throw new RestException(404, 'Product not found');
2069 }
2070
2071 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
2072 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2073 }
2074
2075 if (!empty($includestockdata) && DolibarrApiAccess::$user->rights->stock->lire) {
2076 $this->product->load_stock($includestockdata);
2077
2078 if (is_array($this->product->stock_warehouse)) {
2079 foreach ($this->product->stock_warehouse as $keytmp => $valtmp) {
2080 if (isset($this->product->stock_warehouse[$keytmp]->detail_batch) && is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) {
2081 foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
2082 unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
2083 }
2084 }
2085 }
2086 }
2087 }
2088
2089 if ($includesubproducts) {
2090 $childsArbo = $this->product->getChildsArbo($id, 1);
2091
2092 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
2093 $childs = array();
2094 foreach ($childsArbo as $values) {
2095 $childs[] = array_combine($keys, $values);
2096 }
2097
2098 $this->product->sousprods = $childs;
2099 }
2100
2101 if ($includeparentid) {
2102 $prodcomb = new ProductCombination($this->db);
2103 $this->product->fk_product_parent = null;
2104 if (($fk_product_parent = $prodcomb->fetchByFkProductChild($this->product->id)) > 0) {
2105 $this->product->fk_product_parent = $fk_product_parent;
2106 }
2107 }
2108
2109 if ($includeifobjectisused) {
2110 $this->product->is_object_used = ($this->product->isObjectUsed() > 0);
2111 }
2112
2113 return $this->_cleanObjectDatas($this->product);
2114 }
2115}
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.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:85
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.