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