dolibarr 21.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 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2025 William Mead <william@m34d.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
25require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
26require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
27require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
28require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
29require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
30require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
31
38class Products extends DolibarrApi
39{
43 public static $FIELDS = array(
44 'ref',
45 'label'
46 );
47
51 public $product;
52
56 public $productsupplier;
57
61 public function __construct()
62 {
63 global $db, $conf;
64
65 $this->db = $db;
66 $this->product = new Product($this->db);
67 $this->productsupplier = new ProductFournisseur($this->db);
68 }
69
86 public function get($id, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
87 {
88 return $this->_fetch($id, '', '', '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
89 }
90
110 public function getByRef($ref, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
111 {
112 return $this->_fetch(0, $ref, '', '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
113 }
114
134 public function getByRefExt($ref_ext, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
135 {
136 return $this->_fetch(0, '', $ref_ext, '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
137 }
138
158 public function getByBarcode($barcode, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
159 {
160 return $this->_fetch(0, '', '', $barcode, $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
161 }
162
182 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 = '')
183 {
184 global $db, $conf;
185
186 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
187 throw new RestException(403);
188 }
189
190 $obj_ret = array();
191
192 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
193
194 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
195 $sql .= " FROM ".$this->db->prefix()."product as t";
196 $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
197 if ($category > 0) {
198 $sql .= ", ".$this->db->prefix()."categorie_product as c";
199 }
200 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
201
202 if ($variant_filter == 1) {
203 $sql .= ' AND t.rowid not in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
204 $sql .= ' AND t.rowid not in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
205 }
206 if ($variant_filter == 2) {
207 $sql .= ' AND t.rowid in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
208 }
209 if ($variant_filter == 3) {
210 $sql .= ' AND t.rowid in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
211 }
212
213 // Select products of given category
214 if ($category > 0) {
215 $sql .= " AND c.fk_categorie = ".((int) $category);
216 $sql .= " AND c.fk_product = t.rowid";
217 }
218 if ($mode == 1) {
219 // Show only products
220 $sql .= " AND t.fk_product_type = 0";
221 } elseif ($mode == 2) {
222 // Show only services
223 $sql .= " AND t.fk_product_type = 1";
224 }
225
226 // Add sql filters
227 if ($sqlfilters) {
228 $errormessage = '';
229 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
230 if ($errormessage) {
231 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
232 }
233 }
234
235 //this query will return total products with the filters given
236 $sqlTotals = str_replace('SELECT t.rowid, t.ref, t.ref_ext', 'SELECT count(t.rowid) as total', $sql);
237
238 $sql .= $this->db->order($sortfield, $sortorder);
239 if ($limit) {
240 if ($page < 0) {
241 $page = 0;
242 }
243 $offset = $limit * $page;
244
245 $sql .= $this->db->plimit($limit + 1, $offset);
246 }
247
248 $result = $this->db->query($sql);
249 if ($result) {
250 $num = $this->db->num_rows($result);
251 $min = min($num, ($limit <= 0 ? $num : $limit));
252 $i = 0;
253 while ($i < $min) {
254 $obj = $this->db->fetch_object($result);
255 if (!$ids_only) {
256 $product_static = new Product($this->db);
257 if ($product_static->fetch($obj->rowid)) {
258 if (!empty($includestockdata) && DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
259 $product_static->load_stock();
260
261 if (is_array($product_static->stock_warehouse)) {
262 foreach ($product_static->stock_warehouse as $keytmp => $valtmp) {
263 if (isset($product_static->stock_warehouse[$keytmp]->detail_batch) && is_array($product_static->stock_warehouse[$keytmp]->detail_batch)) {
264 foreach ($product_static->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
265 unset($product_static->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
266 }
267 }
268 }
269 }
270 }
271
272
273 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($product_static), $properties);
274 }
275 } else {
276 $obj_ret[] = $obj->rowid;
277 }
278 $i++;
279 }
280 } else {
281 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
282 }
283
284 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
285 if ($pagination_data) {
286 $totalsResult = $this->db->query($sqlTotals);
287 $total = $this->db->fetch_object($totalsResult)->total;
288
289 $tmp = $obj_ret;
290 $obj_ret = array();
291
292 $obj_ret['data'] = $tmp;
293 $obj_ret['pagination'] = array(
294 'total' => (int) $total,
295 'page' => $page, //count starts from 0
296 'page_count' => ceil((int) $total / $limit),
297 'limit' => $limit
298 );
299 }
300
301 return $obj_ret;
302 }
303
310 public function post($request_data = null)
311 {
312 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
313 throw new RestException(403);
314 }
315 // Check mandatory fields
316 $result = $this->_validate($request_data);
317
318 foreach ($request_data as $field => $value) {
319 if ($field === 'caller') {
320 // 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 with the caller
321 $this->product->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
322 continue;
323 }
324
325 $this->product->$field = $this->_checkValForAPI($field, $value, $this->product);
326 }
327 if ($this->product->create(DolibarrApiAccess::$user) < 0) {
328 throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors));
329 }
330
331 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
332 $key_max = getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT');
333 for ($key = 1; $key <= $key_max ; $key++) {
334 $newvat = $this->product->multiprices_tva_tx[$key];
335 $newnpr = 0;
336 $newvatsrccode = $this->product->default_vat_code;
337 $newprice = $this->product->multiprices[$key];
338 $newpricemin = $this->product->multiprices_min[$key];
339 $newbasetype = $this->product->multiprices_base_type[$key];
340 if (empty($newbasetype) || $newbasetype == '') {
341 $newbasetype = $this->product->price_base_type;
342 }
343 if ($newbasetype == 'TTC') {
344 $newprice = $this->product->multiprices_ttc[$key];
345 $newpricemin = $this->product->multiprices_min_ttc[$key];
346 }
347 if ($newprice > 0) {
348 $result = $this->product->updatePrice($newprice, $newbasetype, DolibarrApiAccess::$user, $newvat, $newpricemin, $key, $newnpr, 0, 0, array(), $newvatsrccode);
349 }
350 }
351 }
352
353 return $this->product->id;
354 }
355
369 public function put($id, $request_data = null)
370 {
371 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
372 throw new RestException(403);
373 }
374
375 $result = $this->product->fetch($id);
376 if (!$result) {
377 throw new RestException(404, 'Product not found');
378 }
379
380 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
381 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
382 }
383
384 $oldproduct = dol_clone($this->product, 2);
385
386 foreach ($request_data as $field => $value) {
387 if ($field == 'id') {
388 continue;
389 }
390 if ($field == 'stock_reel') {
391 throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead');
392 }
393 if ($field === 'caller') {
394 // 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 with the caller
395 $this->product->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
396 continue;
397 }
398 if ($field == 'array_options' && is_array($value)) {
399 foreach ($value as $index => $val) {
400 $this->product->array_options[$index] = $this->_checkValForAPI($field, $val, $this->product);
401 }
402 continue;
403 }
404
405 $this->product->$field = $this->_checkValForAPI($field, $value, $this->product);
406 }
407
408 $updatetype = false;
409 if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) {
410 $updatetype = true;
411 }
412
413 $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype);
414
415 // If price mode is 1 price per product
416 if ($result > 0 && getDolGlobalString('PRODUCT_PRICE_UNIQ')) {
417 // We update price only if it was changed
418 $pricemodified = false;
419 if ($this->product->price_base_type != $oldproduct->price_base_type) {
420 $pricemodified = true;
421 } else {
422 if ($this->product->tva_tx != $oldproduct->tva_tx) {
423 $pricemodified = true;
424 }
425 if ($this->product->tva_npr != $oldproduct->tva_npr) {
426 $pricemodified = true;
427 }
428 if (!empty($this->product->default_vat_code)) {
429 if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
430 $pricemodified = true;
431 }
432 }
433
434 if ($this->product->price_base_type == 'TTC') {
435 if ($this->product->price_ttc != $oldproduct->price_ttc) {
436 $pricemodified = true;
437 }
438 if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
439 $pricemodified = true;
440 }
441 } else {
442 if ($this->product->price != $oldproduct->price) {
443 $pricemodified = true;
444 }
445 if ($this->product->price_min != $oldproduct->price_min) {
446 $pricemodified = true;
447 }
448 }
449 }
450
451 if ($pricemodified) {
452 $newvat = $this->product->tva_tx;
453 $newnpr = $this->product->tva_npr;
454 $newvatsrccode = $this->product->default_vat_code;
455
456 $newprice = $this->product->price;
457 $newpricemin = $this->product->price_min;
458 if ($this->product->price_base_type == 'TTC') {
459 $newprice = $this->product->price_ttc;
460 $newpricemin = $this->product->price_min_ttc;
461 }
462
463 $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode);
464 }
465 }
466
467 if ($result > 0 && getDolGlobalString('PRODUIT_MULTIPRICES')) {
468 $key_max = getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT');
469 for ($key = 1; $key <= $key_max ; $key++) {
470 $pricemodified = false;
471 if ($this->product->multiprices_base_type[$key] != $oldproduct->multiprices_base_type[$key]) {
472 $pricemodified = true;
473 } else {
474 if ($this->product->multiprices_tva_tx[$key] != $oldproduct->multiprices_tva_tx[$key]) {
475 $pricemodified = true;
476 }
477 if ($this->product->multiprices_base_type[$key] == 'TTC') {
478 if ($this->product->multiprices_ttc[$key] != $oldproduct->multiprices_ttc[$key]) {
479 $pricemodified = true;
480 }
481 if ($this->product->multiprices_min_ttc[$key] != $oldproduct->multiprices_min_ttc[$key]) {
482 $pricemodified = true;
483 }
484 } else {
485 if ($this->product->multiprices[$key] != $oldproduct->multiprices[$key]) {
486 $pricemodified = true;
487 }
488 if ($this->product->multiprices_min[$key] != $oldproduct->multiprices[$key]) {
489 $pricemodified = true;
490 }
491 }
492 }
493 if ($pricemodified && $result > 0) {
494 $newvat = $this->product->multiprices_tva_tx[$key];
495 $newnpr = 0;
496 $newvatsrccode = $this->product->default_vat_code;
497 $newprice = $this->product->multiprices[$key];
498 $newpricemin = $this->product->multiprices_min[$key];
499 $newbasetype = $this->product->multiprices_base_type[$key];
500 if (empty($newbasetype) || $newbasetype == '') {
501 $newbasetype = $this->product->price_base_type;
502 }
503 if ($newbasetype == 'TTC') {
504 $newprice = $this->product->multiprices_ttc[$key];
505 $newpricemin = $this->product->multiprices_min_ttc[$key];
506 }
507
508 $result = $this->product->updatePrice($newprice, $newbasetype, DolibarrApiAccess::$user, $newvat, $newpricemin, $key, $newnpr, 0, 0, array(), $newvatsrccode);
509 }
510 }
511 }
512
513 if ($result <= 0) {
514 throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors));
515 }
516
517 return $this->get($id);
518 }
519
526 public function delete($id)
527 {
528 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
529 throw new RestException(403);
530 }
531 $result = $this->product->fetch($id);
532 if (!$result) {
533 throw new RestException(404, 'Product not found');
534 }
535
536 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
537 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
538 }
539
540 // The Product::delete() method uses the global variable $user.
541 global $user;
542 $user = DolibarrApiAccess::$user;
543
544 $res = $this->product->delete(DolibarrApiAccess::$user);
545 if ($res < 0) {
546 throw new RestException(500, "Can't delete, error occurs");
547 } elseif ($res == 0) {
548 throw new RestException(409, "Can't delete, that product is probably used");
549 }
550
551 return array(
552 'success' => array(
553 'code' => 200,
554 'message' => 'Object deleted'
555 )
556 );
557 }
558
571 public function getSubproducts($id)
572 {
573 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
574 throw new RestException(403);
575 }
576
577 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
578 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
579 }
580
581 $childrenArbo = $this->product->getChildsArbo($id, 1);
582
583 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
584 $children = array();
585 foreach ($childrenArbo as $values) {
586 $children[] = array_combine($keys, $values);
587 }
588
589 return $children;
590 }
591
609 public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1)
610 {
611 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
612 throw new RestException(403);
613 }
614
615 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
616 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
617 }
618
619 $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec);
620 if ($result <= 0) {
621 throw new RestException(500, "Error adding product child");
622 }
623 return $result;
624 }
625
639 public function delSubproducts($id, $subproduct_id)
640 {
641 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
642 throw new RestException(403);
643 }
644
645 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
646 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
647 }
648
649 $result = $this->product->del_sousproduit($id, $subproduct_id);
650 if ($result <= 0) {
651 throw new RestException(500, "Error while removing product child");
652 }
653 return $result;
654 }
655
656
670 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
671 {
672 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
673 throw new RestException(403);
674 }
675
676 $categories = new Categorie($this->db);
677
678 $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page);
679
680 if ($result < 0) {
681 throw new RestException(503, 'Error when retrieve category list : '.implode(',', array_merge(array($categories->error), $categories->errors)));
682 }
683
684 return $result;
685 }
686
697 {
698 global $conf;
699
700 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
701 throw new RestException(403);
702 }
703
704 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
705 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
706 }
707
708 $result = $this->product->fetch($id);
709 if (!$result) {
710 throw new RestException(404, 'Product not found');
711 }
712
713 if ($result < 0) {
714 throw new RestException(503, 'Error when retrieve prices list : '.implode(',', array_merge(array($this->product->error), $this->product->errors)));
715 }
716
717 return array(
718 'multiprices' => $this->product->multiprices,
719 'multiprices_inc_tax' => $this->product->multiprices_ttc,
720 'multiprices_min' => $this->product->multiprices_min,
721 'multiprices_min_inc_tax' => $this->product->multiprices_min_ttc,
722 'multiprices_vat' => $this->product->multiprices_tva_tx,
723 'multiprices_base_type' => $this->product->multiprices_base_type,
724 //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code
725 );
726 }
727
738 public function getCustomerPricesPerCustomer($id, $thirdparty_id = '')
739 {
740 global $conf;
741
742 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
743 throw new RestException(403);
744 }
745
746 if (!getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
747 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
748 }
749
750 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
751 if ($socid > 0 && $socid != $thirdparty_id) {
752 throw new RestException(403, 'Getting prices for all customers or for the customer ID '.$thirdparty_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
753 }
754
755 $result = $this->product->fetch($id);
756 if (!$result) {
757 throw new RestException(404, 'Product not found');
758 }
759
760 if ($result > 0) {
761 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
762 $prodcustprice = new ProductCustomerPrice($this->db);
763 $filter = array();
764 $filter['t.fk_product'] = $id;
765 if ($thirdparty_id) {
766 $filter['t.fk_soc'] = $thirdparty_id;
767 }
768 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
769 }
770
771 if (empty($prodcustprice->lines)) {
772 throw new RestException(404, 'Prices not found');
773 }
774
775 return $prodcustprice->lines;
776 }
777
788 {
789 global $conf;
790
791 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
792 throw new RestException(403);
793 }
794
795 if (!getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
796 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
797 }
798
799 $result = $this->product->fetch($id);
800 if (!$result) {
801 throw new RestException(404, 'Product not found');
802 }
803
804 if ($result < 0) {
805 throw new RestException(503, 'Error when retrieve prices list : '.implode(',', array_merge(array($this->product->error), $this->product->errors)));
806 }
807
808 return array(
809 'prices_by_qty' => $this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product
810 'prices_by_qty_list' => $this->product->prices_by_qty_list[0]
811 );
812 }
813
847 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)
848 {
849 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
850 throw new RestException(403);
851 }
852
853 $result = $this->productsupplier->fetch($id);
854 if (!$result) {
855 throw new RestException(404, 'Product not found');
856 }
857
858 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
859 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
860 }
861
862 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
863 if ($socid > 0 && $socid != $fourn_id) {
864 throw new RestException(403, 'Adding purchase price for the supplier ID '.$fourn_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
865 }
866
867 $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty);
868 if ($result < 0) {
869 throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror());
870 }
871
872 $fourn = new Fournisseur($this->db);
873 $result = $fourn->fetch($fourn_id);
874 if ($result <= 0) {
875 throw new RestException(404, 'Supplier not found');
876 }
877
878 // Clean data
879 $ref_fourn = sanitizeVal($ref_fourn, 'alphanohtml');
880 $desc_fourn = sanitizeVal($desc_fourn, 'restricthtml');
881 $barcode = sanitizeVal($barcode, 'alphanohtml');
882
883 $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);
884
885 if ($result <= 0) {
886 throw new RestException(500, "Error updating buy price : ".$this->db->lasterror());
887 }
888 return (int) $this->productsupplier->product_fourn_price_id;
889 }
890
905 public function deletePurchasePrice($id, $priceid)
906 {
907 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
908 throw new RestException(403);
909 }
910 $result = $this->productsupplier->fetch($id);
911 if (!$result) {
912 throw new RestException(404, 'Product not found');
913 }
914
915 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
916 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
917 }
918
919 $resultsupplier = 0;
920 if ($result > 0) {
921 $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid);
922 }
923
924 return $resultsupplier;
925 }
926
942 public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '')
943 {
944 global $db, $conf;
945
946 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
947 throw new RestException(403);
948 }
949
950 $obj_ret = array();
951
952 // Force id of company for external users
953 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
954 if ($socid > 0) {
955 if ($supplier != $socid || empty($supplier)) {
956 throw new RestException(403, 'As an external user, you can request only for your supplier id = '.$socid);
957 }
958 }
959
960 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
961 $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
962
963 if ($category > 0) {
964 $sql .= ", ".$this->db->prefix()."categorie_product as c";
965 }
966 $sql .= ", ".$this->db->prefix()."product_fournisseur_price as s";
967
968 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
969
970 if ($supplier > 0) {
971 $sql .= " AND s.fk_soc = ".((int) $supplier);
972 }
973 if ($socid > 0) { // if external user
974 $sql .= " AND s.fk_soc = ".((int) $socid);
975 }
976 $sql .= " AND s.fk_product = t.rowid";
977 // Select products of given category
978 if ($category > 0) {
979 $sql .= " AND c.fk_categorie = ".((int) $category);
980 $sql .= " AND c.fk_product = t.rowid";
981 }
982 if ($mode == 1) {
983 // Show only products
984 $sql .= " AND t.fk_product_type = 0";
985 } elseif ($mode == 2) {
986 // Show only services
987 $sql .= " AND t.fk_product_type = 1";
988 }
989 // Add sql filters
990 if ($sqlfilters) {
991 $errormessage = '';
992 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
993 if ($errormessage) {
994 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
995 }
996 }
997
998 $sql .= $this->db->order($sortfield, $sortorder);
999 if ($limit) {
1000 if ($page < 0) {
1001 $page = 0;
1002 }
1003 $offset = $limit * $page;
1004 $sql .= $this->db->plimit($limit + 1, $offset);
1005 }
1006 $result = $this->db->query($sql);
1007 if ($result) {
1008 $num = $this->db->num_rows($result);
1009 $min = min($num, ($limit <= 0 ? $num : $limit));
1010 $i = 0;
1011 while ($i < $min) {
1012 $obj = $this->db->fetch_object($result);
1013
1014 $product_fourn = new ProductFournisseur($this->db);
1015 $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0);
1016 foreach ($product_fourn_list as $tmpobj) {
1017 $this->_cleanObjectDatas($tmpobj);
1018 }
1019
1020 //var_dump($product_fourn_list->db);exit;
1021 $obj_ret[$obj->rowid] = $product_fourn_list;
1022
1023 $i++;
1024 }
1025 } else {
1026 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
1027 }
1028
1029 return $obj_ret;
1030 }
1031
1051 public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '')
1052 {
1053 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
1054 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
1055 }
1056
1057 $id = (empty($id) ? 0 : $id);
1058
1059 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1060 throw new RestException(403);
1061 }
1062
1063 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
1064
1065 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode);
1066 if (!$result) {
1067 throw new RestException(404, 'Product not found');
1068 }
1069
1070 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
1071 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1072 }
1073
1074 $product_fourn_list = array();
1075
1076 if ($result) {
1077 $product_fourn = new ProductFournisseur($this->db);
1078 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0, ($socid > 0 ? $socid : 0));
1079 }
1080
1081 foreach ($product_fourn_list as $tmpobj) {
1082 $this->_cleanObjectDatas($tmpobj);
1083 }
1084
1085 return $this->_cleanObjectDatas($product_fourn_list);
1086 }
1087
1105 public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
1106 {
1107 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1108 throw new RestException(403);
1109 }
1110
1111 $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.position, t.entity";
1112 $sql .= " FROM ".$this->db->prefix()."product_attribute as t";
1113 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
1114
1115 // Add sql filters
1116 if ($sqlfilters) {
1117 $errormessage = '';
1118 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
1119 if ($errormessage) {
1120 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
1121 }
1122 }
1123
1124 $sql .= $this->db->order($sortfield, $sortorder);
1125 if ($limit) {
1126 if ($page < 0) {
1127 $page = 0;
1128 }
1129 $offset = $limit * $page;
1130
1131 $sql .= $this->db->plimit($limit, $offset);
1132 }
1133
1134 $resql = $this->db->query($sql);
1135
1136 if (!$resql) {
1137 throw new RestException(503, 'Error when retrieving product attribute list : '.$this->db->lasterror());
1138 }
1139
1140 $return = array();
1141 while ($obj = $this->db->fetch_object($resql)) {
1142 $tmp = new ProductAttribute($this->db);
1143 $tmp->id = $obj->rowid;
1144 $tmp->ref = $obj->ref;
1145 $tmp->ref_ext = $obj->ref_ext;
1146 $tmp->label = $obj->label;
1147 $tmp->position = $obj->position;
1148 $tmp->entity = $obj->entity;
1149
1150 $return[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp), $properties);
1151 }
1152
1153 return $return;
1154 }
1155
1167 public function getAttributeById($id)
1168 {
1169 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1170 throw new RestException(403);
1171 }
1172
1173 $prodattr = new ProductAttribute($this->db);
1174 $result = $prodattr->fetch((int) $id);
1175
1176 if ($result < 0) {
1177 throw new RestException(404, "Product attribute not found");
1178 }
1179
1180 $fields = ["id", "ref", "ref_ext", "label", "position", "entity"];
1181
1182 foreach ($prodattr as $field => $value) {
1183 if (!in_array($field, $fields)) {
1184 unset($prodattr->{$field});
1185 }
1186 }
1187
1188 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1189 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1190 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")";
1191
1192 $resql = $this->db->query($sql);
1193 $obj = $this->db->fetch_object($resql);
1194 $prodattr->is_used_by_products = (int) $obj->nb;
1195
1196 return $this->_cleanObjectDatas($prodattr);
1197 }
1198
1210 public function getAttributesByRef($ref)
1211 {
1212 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1213 throw new RestException(403);
1214 }
1215
1216 $ref = trim($ref);
1217
1218 $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').")";
1219
1220 $query = $this->db->query($sql);
1221
1222 if (!$this->db->num_rows($query)) {
1223 throw new RestException(404);
1224 }
1225
1226 $result = $this->db->fetch_object($query);
1227
1228 $attr = array();
1229 $attr['id'] = $result->rowid;
1230 $attr['ref'] = $result->ref;
1231 $attr['ref_ext'] = $result->ref_ext;
1232 $attr['label'] = $result->label;
1233 $attr['rang'] = $result->position;
1234 $attr['position'] = $result->position;
1235 $attr['entity'] = $result->entity;
1236
1237 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1238 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1239 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1240
1241 $resql = $this->db->query($sql);
1242 $obj = $this->db->fetch_object($resql);
1243
1244 $attr["is_used_by_products"] = (int) $obj->nb;
1245
1246 return $attr;
1247 }
1248
1260 public function getAttributesByRefExt($ref_ext)
1261 {
1262 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1263 throw new RestException(403);
1264 }
1265
1266 $ref_ext = trim($ref_ext);
1267
1268 $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').")";
1269
1270 $query = $this->db->query($sql);
1271
1272 if (!$this->db->num_rows($query)) {
1273 throw new RestException(404);
1274 }
1275
1276 $result = $this->db->fetch_object($query);
1277
1278 $attr = array();
1279 $attr['id'] = $result->rowid;
1280 $attr['ref'] = $result->ref;
1281 $attr['ref_ext'] = $result->ref_ext;
1282 $attr['label'] = $result->label;
1283 $attr['rang'] = $result->position;
1284 $attr['position'] = $result->position;
1285 $attr['entity'] = $result->entity;
1286
1287 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1288 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1289 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1290
1291 $resql = $this->db->query($sql);
1292 $obj = $this->db->fetch_object($resql);
1293
1294 $attr["is_used_by_products"] = (int) $obj->nb;
1295
1296 return $attr;
1297 }
1298
1312 public function addAttributes($ref, $label, $ref_ext = '')
1313 {
1314 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1315 throw new RestException(403);
1316 }
1317
1318 $prodattr = new ProductAttribute($this->db);
1319 $prodattr->label = $label;
1320 $prodattr->ref = $ref;
1321 $prodattr->ref_ext = $ref_ext;
1322
1323 $resid = $prodattr->create(DolibarrApiAccess::$user);
1324 if ($resid <= 0) {
1325 throw new RestException(500, "Error creating new attribute");
1326 }
1327
1328 return $resid;
1329 }
1330
1344 public function putAttributes($id, $request_data = null)
1345 {
1346 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1347 throw new RestException(403);
1348 }
1349
1350 $prodattr = new ProductAttribute($this->db);
1351
1352 $result = $prodattr->fetch((int) $id);
1353 if ($result == 0) {
1354 throw new RestException(404, 'Attribute not found');
1355 } elseif ($result < 0) {
1356 throw new RestException(500, "Error fetching attribute");
1357 }
1358
1359 foreach ($request_data as $field => $value) {
1360 if ($field == 'rowid') {
1361 continue;
1362 }
1363 if ($field === 'caller') {
1364 // 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 with the caller
1365 $prodattr->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1366 continue;
1367 }
1368
1369 $prodattr->$field = $this->_checkValForAPI($field, $value, $prodattr);
1370 }
1371
1372 if ($prodattr->update(DolibarrApiAccess::$user) > 0) {
1373 $result = $prodattr->fetch((int) $id);
1374 if ($result == 0) {
1375 throw new RestException(404, 'Attribute not found');
1376 } elseif ($result < 0) {
1377 throw new RestException(500, "Error fetching attribute");
1378 } else {
1379 return $this->_cleanObjectDatas($prodattr);
1380 }
1381 }
1382 throw new RestException(500, "Error updating attribute");
1383 }
1384
1396 public function deleteAttributes($id)
1397 {
1398 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1399 throw new RestException(403);
1400 }
1401
1402 $prodattr = new ProductAttribute($this->db);
1403 $prodattr->id = (int) $id;
1404 $result = $prodattr->delete(DolibarrApiAccess::$user);
1405
1406 if ($result <= 0) {
1407 throw new RestException(500, "Error deleting attribute");
1408 }
1409
1410 return $result;
1411 }
1412
1425 {
1426 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1427 throw new RestException(403);
1428 }
1429
1430 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")";
1431
1432 $query = $this->db->query($sql);
1433
1434 if (!$query) {
1435 throw new RestException(403);
1436 }
1437
1438 if (!$this->db->num_rows($query)) {
1439 throw new RestException(404, 'Attribute value not found');
1440 }
1441
1442 $result = $this->db->fetch_object($query);
1443
1444 $attrval = array();
1445 $attrval['id'] = $result->rowid;
1446 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1447 $attrval['ref'] = $result->ref;
1448 $attrval['value'] = $result->value;
1449
1450 return $attrval;
1451 }
1452
1465 public function getAttributeValueByRef($id, $ref)
1466 {
1467 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1468 throw new RestException(403);
1469 }
1470
1471 $ref = trim($ref);
1472
1473 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value";
1474 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1475
1476 $query = $this->db->query($sql);
1477
1478 if (!$query) {
1479 throw new RestException(403);
1480 }
1481
1482 if (!$this->db->num_rows($query)) {
1483 throw new RestException(404, 'Attribute value not found');
1484 }
1485
1486 $result = $this->db->fetch_object($query);
1487
1488 $attrval = array();
1489 $attrval['id'] = $result->rowid;
1490 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1491 $attrval['ref'] = $result->ref;
1492 $attrval['value'] = $result->value;
1493
1494 return $attrval;
1495 }
1496
1508 public function deleteAttributeValueByRef($id, $ref)
1509 {
1510 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1511 throw new RestException(403);
1512 }
1513
1514 $ref = trim($ref);
1515
1516 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_value";
1517 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1518 $query = $this->db->query($sql);
1519
1520 if (!$query) {
1521 throw new RestException(403);
1522 }
1523
1524 if (!$this->db->num_rows($query)) {
1525 throw new RestException(404, 'Attribute value not found');
1526 }
1527
1528 $result = $this->db->fetch_object($query);
1529
1530 $attrval = new ProductAttributeValue($this->db);
1531 $attrval->id = $result->rowid;
1532 $result = $attrval->delete(DolibarrApiAccess::$user);
1533 if ($result > 0) {
1534 return 1;
1535 }
1536
1537 throw new RestException(500, "Error deleting attribute value");
1538 }
1539
1551 public function getAttributeValues($id)
1552 {
1553 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1554 throw new RestException(403);
1555 }
1556
1557 $objectval = new ProductAttributeValue($this->db);
1558
1559 $return = $objectval->fetchAllByProductAttribute((int) $id);
1560
1561 if (count($return) == 0) {
1562 throw new RestException(404, 'Attribute values not found');
1563 }
1564
1565 foreach ($return as $key => $val) {
1566 $return[$key] = $this->_cleanObjectDatas($return[$key]);
1567 }
1568
1569 return $return;
1570 }
1571
1582 public function getAttributeValuesByRef($ref)
1583 {
1584 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1585 throw new RestException(403);
1586 }
1587
1588 $ref = trim($ref);
1589
1590 $return = array();
1591
1592 $sql = "SELECT ";
1593 $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM ".$this->db->prefix()."product_attribute_value as v";
1594 $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."')";
1595
1596 $resql = $this->db->query($sql);
1597
1598 while ($result = $this->db->fetch_object($resql)) {
1599 $tmp = new ProductAttributeValue($this->db);
1600 $tmp->fk_product_attribute = $result->fk_product_attribute;
1601 $tmp->id = $result->rowid;
1602 $tmp->ref = $result->ref;
1603 $tmp->value = $result->value;
1604
1605 $return[] = $this->_cleanObjectDatas($tmp);
1606 }
1607
1608 return $return;
1609 }
1610
1624 public function addAttributeValue($id, $ref, $value)
1625 {
1626 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1627 throw new RestException(403);
1628 }
1629
1630 if (empty($ref) || empty($value)) {
1631 throw new RestException(403);
1632 }
1633
1634 $objectval = new ProductAttributeValue($this->db);
1635 $objectval->fk_product_attribute = ((int) $id);
1636 $objectval->ref = $ref;
1637 $objectval->value = $value;
1638
1639 if ($objectval->create(DolibarrApiAccess::$user) > 0) {
1640 return $objectval->id;
1641 }
1642 throw new RestException(500, "Error creating new attribute value");
1643 }
1644
1657 public function putAttributeValue($id, $request_data)
1658 {
1659 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1660 throw new RestException(403);
1661 }
1662
1663 $objectval = new ProductAttributeValue($this->db);
1664 $result = $objectval->fetch((int) $id);
1665
1666 if ($result == 0) {
1667 throw new RestException(404, 'Attribute value not found');
1668 } elseif ($result < 0) {
1669 throw new RestException(500, "Error fetching attribute value");
1670 }
1671
1672 foreach ($request_data as $field => $value) {
1673 if ($field == 'rowid') {
1674 continue;
1675 }
1676 if ($field === 'caller') {
1677 // 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 with the caller
1678 $objectval->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1679 continue;
1680 }
1681
1682 $objectval->$field = $this->_checkValForAPI($field, $value, $objectval);
1683 }
1684
1685 if ($objectval->update(DolibarrApiAccess::$user) > 0) {
1686 $result = $objectval->fetch((int) $id);
1687 if ($result == 0) {
1688 throw new RestException(404, 'Attribute not found');
1689 } elseif ($result < 0) {
1690 throw new RestException(500, "Error fetching attribute");
1691 } else {
1692 return $this->_cleanObjectDatas($objectval);
1693 }
1694 }
1695 throw new RestException(500, "Error updating attribute");
1696 }
1697
1710 {
1711 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1712 throw new RestException(403);
1713 }
1714
1715 $objectval = new ProductAttributeValue($this->db);
1716 $objectval->id = (int) $id;
1717
1718 if ($objectval->delete(DolibarrApiAccess::$user) > 0) {
1719 return 1;
1720 }
1721 throw new RestException(500, "Error deleting attribute value");
1722 }
1723
1736 public function getVariants($id, $includestock = 0)
1737 {
1738 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1739 throw new RestException(403);
1740 }
1741
1742 $prodcomb = new ProductCombination($this->db);
1743 $combinations = $prodcomb->fetchAllByFkProductParent((int) $id);
1744
1745 foreach ($combinations as $key => $combination) {
1746 $prodc2vp = new ProductCombination2ValuePair($this->db);
1747 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1748 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1749
1750 if (!empty($includestock) && DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
1751 $productModel = new Product($this->db);
1752 $productModel->fetch((int) $combination->fk_product_child);
1753 $productModel->load_stock($includestock);
1754 $combinations[$key]->stock_warehouse = $this->_cleanObjectDatas($productModel)->stock_warehouse;
1755 }
1756 }
1757
1758 return $combinations;
1759 }
1760
1772 public function getVariantsByProdRef($ref)
1773 {
1774 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1775 throw new RestException(403);
1776 }
1777
1778 $result = $this->product->fetch(0, $ref);
1779 if (!$result) {
1780 throw new RestException(404, 'Product not found');
1781 }
1782
1783 $prodcomb = new ProductCombination($this->db);
1784 $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id);
1785
1786 foreach ($combinations as $key => $combination) {
1787 $prodc2vp = new ProductCombination2ValuePair($this->db);
1788 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1789 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1790 }
1791
1792 return $combinations;
1793 }
1794
1815 public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '')
1816 {
1817 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1818 throw new RestException(403);
1819 }
1820
1821 if (empty($id)) {
1822 throw new RestException(400, 'Product ID is mandatory');
1823 }
1824
1825 if (empty($features) || !is_array($features)) {
1826 throw new RestException(400, 'Features is mandatory and should be IDs of attribute values indexed by IDs of attributes');
1827 }
1828
1829 $weight_impact = price2num($weight_impact);
1830 $price_impact = price2num($price_impact);
1831
1832 $prodattr = new ProductAttribute($this->db);
1833 $prodattr_val = new ProductAttributeValue($this->db);
1834 foreach ($features as $id_attr => $id_value) {
1835 if ($prodattr->fetch((int) $id_attr) < 0) {
1836 throw new RestException(400, 'Invalid attribute ID: '.$id_attr);
1837 }
1838 if ($prodattr_val->fetch((int) $id_value) < 0) {
1839 throw new RestException(400, 'Invalid attribute value ID: '.$id_value);
1840 }
1841 }
1842
1843 $result = $this->product->fetch((int) $id);
1844 if (!$result) {
1845 throw new RestException(404, 'Product not found');
1846 }
1847
1848 $prodcomb = new ProductCombination($this->db);
1849
1850 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
1851 if ($result > 0) {
1852 return $result;
1853 } else {
1854 throw new RestException(500, "Error creating new product variant");
1855 }
1856 }
1857
1876 public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
1877 {
1878 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1879 throw new RestException(403);
1880 }
1881
1882 if (empty($ref) || empty($features) || !is_array($features)) {
1883 throw new RestException(403);
1884 }
1885
1886 $weight_impact = price2num($weight_impact);
1887 $price_impact = price2num($price_impact);
1888
1889 $prodattr = new ProductAttribute($this->db);
1890 $prodattr_val = new ProductAttributeValue($this->db);
1891 foreach ($features as $id_attr => $id_value) {
1892 if ($prodattr->fetch((int) $id_attr) < 0) {
1893 throw new RestException(404);
1894 }
1895 if ($prodattr_val->fetch((int) $id_value) < 0) {
1896 throw new RestException(404);
1897 }
1898 }
1899
1900 $result = $this->product->fetch(0, trim($ref));
1901 if (!$result) {
1902 throw new RestException(404, 'Product not found');
1903 }
1904
1905 $prodcomb = new ProductCombination($this->db);
1906 if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
1907 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
1908 if ($result > 0) {
1909 return $result;
1910 } else {
1911 throw new RestException(500, "Error creating new product variant");
1912 }
1913 } else {
1914 return $prodcomb->id;
1915 }
1916 }
1917
1930 public function putVariant($id, $request_data = null)
1931 {
1932 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1933 throw new RestException(403);
1934 }
1935
1936 $prodcomb = new ProductCombination($this->db);
1937 $prodcomb->fetch((int) $id);
1938
1939 foreach ($request_data as $field => $value) {
1940 if ($field == 'rowid') {
1941 continue;
1942 }
1943 if ($field === 'caller') {
1944 // 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 with the caller
1945 $prodcomb->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1946 continue;
1947 }
1948
1949 $prodcomb->$field = $this->_checkValForAPI($field, $value, $prodcomb);
1950 }
1951
1952 $result = $prodcomb->update(DolibarrApiAccess::$user);
1953 if ($result > 0) {
1954 return 1;
1955 }
1956 throw new RestException(500, "Error editing variant");
1957 }
1958
1970 public function deleteVariant($id)
1971 {
1972 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1973 throw new RestException(403);
1974 }
1975
1976 $prodcomb = new ProductCombination($this->db);
1977 $prodcomb->id = (int) $id;
1978 $result = $prodcomb->delete(DolibarrApiAccess::$user);
1979 if ($result <= 0) {
1980 throw new RestException(500, "Error deleting variant");
1981 }
1982 return $result;
1983 }
1984
1999 public function getStock($id, $selected_warehouse_id = null)
2000 {
2001 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire') || !DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
2002 throw new RestException(403);
2003 }
2004
2005 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
2006 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2007 }
2008
2009 $product_model = new Product($this->db);
2010 $product_model->fetch($id);
2011 $product_model->load_stock();
2012
2013 $stockData = $this->_cleanObjectDatas($product_model)->stock_warehouse;
2014
2015 if ($selected_warehouse_id) {
2016 foreach ($stockData as $warehouse_id => $warehouse) {
2017 if ($warehouse_id != $selected_warehouse_id) {
2018 unset($stockData[$warehouse_id]);
2019 }
2020 }
2021 }
2022 $obj_ret = $this->_filterObjectProperties($this->_cleanObjectDatas($product_model), 'stock_warehouses,stock_reel,stock_theorique');
2023 $obj_ret->stock_warehouses = $stockData;
2024
2025 return $obj_ret;
2026 }
2027
2028 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2035 protected function _cleanObjectDatas($object)
2036 {
2037 // phpcs:enable
2038 $object = parent::_cleanObjectDatas($object);
2039
2040 unset($object->statut);
2041
2042 unset($object->regeximgext);
2043 unset($object->price_by_qty);
2044 unset($object->prices_by_qty_id);
2045 unset($object->libelle);
2046 unset($object->product_id_already_linked);
2047 unset($object->reputations);
2048 unset($object->db);
2049 unset($object->name);
2050 unset($object->firstname);
2051 unset($object->lastname);
2052 unset($object->civility_id);
2053 unset($object->contact);
2054 unset($object->contact_id);
2055 unset($object->thirdparty);
2056 unset($object->user);
2057 unset($object->origin);
2058 unset($object->origin_id);
2059 unset($object->fourn_pu);
2060 unset($object->fourn_price_base_type);
2061 unset($object->fourn_socid);
2062 unset($object->ref_fourn);
2063 unset($object->ref_supplier);
2064 unset($object->product_fourn_id);
2065 unset($object->fk_project);
2066
2067 unset($object->mode_reglement_id);
2068 unset($object->cond_reglement_id);
2069 unset($object->demand_reason_id);
2070 unset($object->transport_mode_id);
2071 unset($object->cond_reglement);
2072 unset($object->shipping_method_id);
2073 unset($object->model_pdf);
2074 unset($object->note);
2075
2076 unset($object->nbphoto);
2077 unset($object->recuperableonly);
2078 unset($object->multiprices_recuperableonly);
2079 unset($object->tva_npr);
2080 unset($object->lines);
2081 unset($object->fk_bank);
2082 unset($object->fk_account);
2083
2084 unset($object->supplierprices); // Must use another API to get them
2085
2086 if (!DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
2087 unset($object->stock_reel);
2088 unset($object->stock_theorique);
2089 unset($object->stock_warehouse);
2090 }
2091
2092 return $object;
2093 }
2094
2102 private function _validate($data)
2103 {
2104 $product = array();
2105 foreach (Products::$FIELDS as $field) {
2106 if (!isset($data[$field])) {
2107 throw new RestException(400, "$field field missing");
2108 }
2109 $product[$field] = $data[$field];
2110 }
2111 return $product;
2112 }
2113
2133 private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false, $includetrans = false)
2134 {
2135 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
2136 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
2137 }
2138
2139 $id = (empty($id) ? 0 : $id);
2140
2141 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
2142 throw new RestException(403);
2143 }
2144
2145 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode, 0, 0, ($includetrans ? 0 : 1));
2146 if (!$result) {
2147 throw new RestException(404, 'Product not found');
2148 }
2149
2150 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
2151 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2152 }
2153
2154 if (!empty($includestockdata) && DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
2155 $this->product->load_stock($includestockdata);
2156
2157 if (is_array($this->product->stock_warehouse)) {
2158 foreach ($this->product->stock_warehouse as $keytmp => $valtmp) {
2159 if (isset($this->product->stock_warehouse[$keytmp]->detail_batch) && is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) {
2160 foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
2161 unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
2162 }
2163 }
2164 }
2165 }
2166 }
2167
2168 if ($includesubproducts) {
2169 $childrenArbo = $this->product->getChildsArbo($id, 1);
2170
2171 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
2172 $children = array();
2173 foreach ($childrenArbo as $values) {
2174 $children[] = array_combine($keys, $values);
2175 }
2176
2177 $this->product->sousprods = $children; // @phpstan-ignore-line
2178 }
2179
2180 if ($includeparentid) {
2181 $prodcomb = new ProductCombination($this->db);
2182 $this->product->fk_product_parent = null;
2183 if (($fk_product_parent = $prodcomb->fetchByFkProductChild($this->product->id)) > 0) {
2184 $this->product->fk_product_parent = $fk_product_parent;
2185 }
2186 }
2187
2188 if ($includeifobjectisused) {
2189 $this->product->is_object_used = ($this->product->isObjectUsed() > 0);
2190 }
2191
2192 return $this->_cleanObjectDatas($this->product);
2193 }
2194}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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:96
Class to manage suppliers.
Class ProductAttribute Used to represent a Product attribute Examples:
Class ProductAttributeValue Used to represent a product attribute value.
Class ProductCombination2ValuePair Used to represent the relation between a variant and its attribute...
Class ProductCombination Used to represent the relation between a product and one of its variants.
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=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
getDolGlobalString($key, $default='')
Return a 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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79