dolibarr 20.0.5
api_products.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
22require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
23require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
24require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
25require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
26require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
27require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
28
35class Products extends DolibarrApi
36{
40 public static $FIELDS = array(
41 'ref',
42 'label'
43 );
44
48 public $product;
49
53 public $productsupplier;
54
58 public function __construct()
59 {
60 global $db, $conf;
61
62 $this->db = $db;
63 $this->product = new Product($this->db);
64 $this->productsupplier = new ProductFournisseur($this->db);
65 }
66
83 public function get($id, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
84 {
85 return $this->_fetch($id, '', '', '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
86 }
87
107 public function getByRef($ref, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
108 {
109 return $this->_fetch('', $ref, '', '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
110 }
111
131 public function getByRefExt($ref_ext, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
132 {
133 return $this->_fetch('', '', $ref_ext, '', $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
134 }
135
155 public function getByBarcode($barcode, $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includetrans = false)
156 {
157 return $this->_fetch('', '', '', $barcode, $includestockdata, $includesubproducts, $includeparentid, false, $includetrans);
158 }
159
179 public function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false, $variant_filter = 0, $pagination_data = false, $includestockdata = 0, $properties = '')
180 {
181 global $db, $conf;
182
183 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
184 throw new RestException(403);
185 }
186
187 $obj_ret = array();
188
189 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
190
191 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
192 $sql .= " FROM ".$this->db->prefix()."product as t";
193 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields AS ef ON ef.fk_object = t.rowid"; // So we will be able to filter on extrafields
194 if ($category > 0) {
195 $sql .= ", ".$this->db->prefix()."categorie_product as c";
196 }
197 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
198
199 if ($variant_filter == 1) {
200 $sql .= ' AND t.rowid not in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
201 $sql .= ' AND t.rowid not in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
202 }
203 if ($variant_filter == 2) {
204 $sql .= ' AND t.rowid in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
205 }
206 if ($variant_filter == 3) {
207 $sql .= ' AND t.rowid in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
208 }
209
210 // Select products of given category
211 if ($category > 0) {
212 $sql .= " AND c.fk_categorie = ".((int) $category);
213 $sql .= " AND c.fk_product = t.rowid";
214 }
215 if ($mode == 1) {
216 // Show only products
217 $sql .= " AND t.fk_product_type = 0";
218 } elseif ($mode == 2) {
219 // Show only services
220 $sql .= " AND t.fk_product_type = 1";
221 }
222
223 // Add sql filters
224 if ($sqlfilters) {
225 $errormessage = '';
226 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
227 if ($errormessage) {
228 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
229 }
230 }
231
232 //this query will return total products with the filters given
233 $sqlTotals = str_replace('SELECT t.rowid, t.ref, t.ref_ext', 'SELECT count(t.rowid) as total', $sql);
234
235 $sql .= $this->db->order($sortfield, $sortorder);
236 if ($limit) {
237 if ($page < 0) {
238 $page = 0;
239 }
240 $offset = $limit * $page;
241
242 $sql .= $this->db->plimit($limit + 1, $offset);
243 }
244
245 $result = $this->db->query($sql);
246 if ($result) {
247 $num = $this->db->num_rows($result);
248 $min = min($num, ($limit <= 0 ? $num : $limit));
249 $i = 0;
250 while ($i < $min) {
251 $obj = $this->db->fetch_object($result);
252 if (!$ids_only) {
253 $product_static = new Product($this->db);
254 if ($product_static->fetch($obj->rowid)) {
255 if (!empty($includestockdata) && DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
256 $product_static->load_stock();
257
258 if (is_array($product_static->stock_warehouse)) {
259 foreach ($product_static->stock_warehouse as $keytmp => $valtmp) {
260 if (isset($product_static->stock_warehouse[$keytmp]->detail_batch) && is_array($product_static->stock_warehouse[$keytmp]->detail_batch)) {
261 foreach ($product_static->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
262 unset($product_static->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
263 }
264 }
265 }
266 }
267 }
268
269
270 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($product_static), $properties);
271 }
272 } else {
273 $obj_ret[] = $obj->rowid;
274 }
275 $i++;
276 }
277 } else {
278 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
279 }
280
281 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
282 if ($pagination_data) {
283 $totalsResult = $this->db->query($sqlTotals);
284 $total = $this->db->fetch_object($totalsResult)->total;
285
286 $tmp = $obj_ret;
287 $obj_ret = array();
288
289 $obj_ret['data'] = $tmp;
290 $obj_ret['pagination'] = array(
291 'total' => (int) $total,
292 'page' => $page, //count starts from 0
293 'page_count' => ceil((int) $total/$limit),
294 'limit' => $limit
295 );
296 }
297
298 return $obj_ret;
299 }
300
307 public function post($request_data = null)
308 {
309 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
310 throw new RestException(403);
311 }
312 // Check mandatory fields
313 $result = $this->_validate($request_data);
314
315 foreach ($request_data as $field => $value) {
316 if ($field === 'caller') {
317 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
318 $this->product->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
319 continue;
320 }
321
322 $this->product->$field = $this->_checkValForAPI($field, $value, $this->product);
323 }
324 if ($this->product->create(DolibarrApiAccess::$user) < 0) {
325 throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors));
326 }
327
328 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
329 $key_max = getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT');
330 for ($key = 1; $key <= $key_max ; $key++) {
331 $newvat = $this->product->multiprices_tva_tx[$key];
332 $newnpr = 0;
333 $newvatsrccode = $this->product->default_vat_code;
334 $newprice = $this->product->multiprices[$key];
335 $newpricemin = $this->product->multiprices_min[$key];
336 $newbasetype = $this->product->multiprices_base_type[$key];
337 if (empty($newbasetype) || $newbasetype == '') {
338 $newbasetype = $this->product->price_base_type;
339 }
340 if ($newbasetype == 'TTC') {
341 $newprice = $this->product->multiprices_ttc[$key];
342 $newpricemin = $this->product->multiprices_min_ttc[$key];
343 }
344 if ($newprice > 0) {
345 $result = $this->product->updatePrice($newprice, $newbasetype, DolibarrApiAccess::$user, $newvat, $newpricemin, $key, $newnpr, 0, 0, array(), $newvatsrccode);
346 }
347 }
348 }
349
350 return $this->product->id;
351 }
352
366 public function put($id, $request_data = null)
367 {
368 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
369 throw new RestException(403);
370 }
371
372 $result = $this->product->fetch($id);
373 if (!$result) {
374 throw new RestException(404, 'Product not found');
375 }
376
377 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
378 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
379 }
380
381 $oldproduct = dol_clone($this->product, 2);
382
383 foreach ($request_data as $field => $value) {
384 if ($field == 'id') {
385 continue;
386 }
387 if ($field == 'stock_reel') {
388 throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead');
389 }
390 if ($field === 'caller') {
391 // 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
392 $this->product->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
393 continue;
394 }
395 if ($field == 'array_options' && is_array($value)) {
396 foreach ($value as $index => $val) {
397 $this->product->array_options[$index] = $this->_checkValForAPI($field, $val, $this->product);
398 }
399 continue;
400 }
401
402 $this->product->$field = $this->_checkValForAPI($field, $value, $this->product);
403 }
404
405 $updatetype = false;
406 if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) {
407 $updatetype = true;
408 }
409
410 $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype);
411
412 // If price mode is 1 price per product
413 if ($result > 0 && getDolGlobalString('PRODUCT_PRICE_UNIQ')) {
414 // We update price only if it was changed
415 $pricemodified = false;
416 if ($this->product->price_base_type != $oldproduct->price_base_type) {
417 $pricemodified = true;
418 } else {
419 if ($this->product->tva_tx != $oldproduct->tva_tx) {
420 $pricemodified = true;
421 }
422 if ($this->product->tva_npr != $oldproduct->tva_npr) {
423 $pricemodified = true;
424 }
425 if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
426 $pricemodified = true;
427 }
428
429 if ($this->product->price_base_type == 'TTC') {
430 if ($this->product->price_ttc != $oldproduct->price_ttc) {
431 $pricemodified = true;
432 }
433 if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
434 $pricemodified = true;
435 }
436 } else {
437 if ($this->product->price != $oldproduct->price) {
438 $pricemodified = true;
439 }
440 if ($this->product->price_min != $oldproduct->price_min) {
441 $pricemodified = true;
442 }
443 }
444 }
445
446 if ($pricemodified) {
447 $newvat = $this->product->tva_tx;
448 $newnpr = $this->product->tva_npr;
449 $newvatsrccode = $this->product->default_vat_code;
450
451 $newprice = $this->product->price;
452 $newpricemin = $this->product->price_min;
453 if ($this->product->price_base_type == 'TTC') {
454 $newprice = $this->product->price_ttc;
455 $newpricemin = $this->product->price_min_ttc;
456 }
457
458 $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode);
459 }
460 }
461
462 if ($result > 0 && getDolGlobalString('PRODUIT_MULTIPRICES')) {
463 $key_max = getDolGlobalString('PRODUIT_MULTIPRICES_LIMIT');
464 for ($key = 1; $key <= $key_max ; $key++) {
465 $pricemodified = false;
466 if ($this->product->multiprices_base_type[$key] != $oldproduct->multiprices_base_type[$key]) {
467 $pricemodified = true;
468 } else {
469 if ($this->product->multiprices_tva_tx[$key] != $oldproduct->multiprices_tva_tx[$key]) $pricemodified = true;
470 if ($this->product->multiprices_base_type[$key] == 'TTC') {
471 if ($this->product->multiprices_ttc[$key] != $oldproduct->multiprices_ttc[$key]) $pricemodified = true;
472 if ($this->product->multiprices_min_ttc[$key] != $oldproduct->multiprices_min_ttc[$key]) $pricemodified = true;
473 } else {
474 if ($this->product->multiprices[$key] != $oldproduct->multiprices[$key]) $pricemodified = true;
475 if ($this->product->multiprices_min[$key] != $oldproduct->multiprices[$key]) $pricemodified = true;
476 }
477 }
478 if ($pricemodified && $result > 0) {
479 $newvat = $this->product->multiprices_tva_tx[$key];
480 $newnpr = 0;
481 $newvatsrccode = $this->product->default_vat_code;
482 $newprice = $this->product->multiprices[$key];
483 $newpricemin = $this->product->multiprices_min[$key];
484 $newbasetype = $this->product->multiprices_base_type[$key];
485 if (empty($newbasetype) || $newbasetype == '') {
486 $newbasetype = $this->product->price_base_type;
487 }
488 if ($newbasetype == 'TTC') {
489 $newprice = $this->product->multiprices_ttc[$key];
490 $newpricemin = $this->product->multiprices_min_ttc[$key];
491 }
492
493 $result = $this->product->updatePrice($newprice, $newbasetype, DolibarrApiAccess::$user, $newvat, $newpricemin, $key, $newnpr, 0, 0, array(), $newvatsrccode);
494 }
495 }
496 }
497
498 if ($result <= 0) {
499 throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors));
500 }
501
502 return $this->get($id);
503 }
504
511 public function delete($id)
512 {
513 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
514 throw new RestException(403);
515 }
516 $result = $this->product->fetch($id);
517 if (!$result) {
518 throw new RestException(404, 'Product not found');
519 }
520
521 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
522 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
523 }
524
525 // The Product::delete() method uses the global variable $user.
526 global $user;
527 $user = DolibarrApiAccess::$user;
528
529 $res = $this->product->delete(DolibarrApiAccess::$user);
530 if ($res < 0) {
531 throw new RestException(500, "Can't delete, error occurs");
532 } elseif ($res == 0) {
533 throw new RestException(409, "Can't delete, that product is probably used");
534 }
535
536 return array(
537 'success' => array(
538 'code' => 200,
539 'message' => 'Object deleted'
540 )
541 );
542 }
543
556 public function getSubproducts($id)
557 {
558 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
559 throw new RestException(403);
560 }
561
562 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
563 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
564 }
565
566 $childrenArbo = $this->product->getChildsArbo($id, 1);
567
568 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
569 $children = array();
570 foreach ($childrenArbo as $values) {
571 $children[] = array_combine($keys, $values);
572 }
573
574 return $children;
575 }
576
594 public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1)
595 {
596 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
597 throw new RestException(403);
598 }
599
600 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
601 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
602 }
603
604 $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec);
605 if ($result <= 0) {
606 throw new RestException(500, "Error adding product child");
607 }
608 return $result;
609 }
610
624 public function delSubproducts($id, $subproduct_id)
625 {
626 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
627 throw new RestException(403);
628 }
629
630 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
631 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
632 }
633
634 $result = $this->product->del_sousproduit($id, $subproduct_id);
635 if ($result <= 0) {
636 throw new RestException(500, "Error while removing product child");
637 }
638 return $result;
639 }
640
641
655 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
656 {
657 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
658 throw new RestException(403);
659 }
660
661 $categories = new Categorie($this->db);
662
663 $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page);
664
665 if ($result < 0) {
666 throw new RestException(503, 'Error when retrieve category list : '.implode(',', array_merge(array($categories->error), $categories->errors)));
667 }
668
669 return $result;
670 }
671
681 public function getCustomerPricesPerSegment($id)
682 {
683 global $conf;
684
685 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
686 throw new RestException(403);
687 }
688
689 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
690 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
691 }
692
693 $result = $this->product->fetch($id);
694 if (!$result) {
695 throw new RestException(404, 'Product not found');
696 }
697
698 if ($result < 0) {
699 throw new RestException(503, 'Error when retrieve prices list : '.implode(',', array_merge(array($this->product->error), $this->product->errors)));
700 }
701
702 return array(
703 'multiprices'=>$this->product->multiprices,
704 'multiprices_inc_tax'=>$this->product->multiprices_ttc,
705 'multiprices_min'=>$this->product->multiprices_min,
706 'multiprices_min_inc_tax'=>$this->product->multiprices_min_ttc,
707 'multiprices_vat'=>$this->product->multiprices_tva_tx,
708 'multiprices_base_type'=>$this->product->multiprices_base_type,
709 //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code
710 );
711 }
712
723 public function getCustomerPricesPerCustomer($id, $thirdparty_id = '')
724 {
725 global $conf;
726
727 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
728 throw new RestException(403);
729 }
730
731 if (!getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
732 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
733 }
734
735 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
736 if ($socid > 0 && $socid != $thirdparty_id) {
737 throw new RestException(403, 'Getting prices for all customers or for the customer ID '.$thirdparty_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
738 }
739
740 $result = $this->product->fetch($id);
741 if (!$result) {
742 throw new RestException(404, 'Product not found');
743 }
744
745 if ($result > 0) {
746 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
747 $prodcustprice = new ProductCustomerPrice($this->db);
748 $filter = array();
749 $filter['t.fk_product'] = $id;
750 if ($thirdparty_id) {
751 $filter['t.fk_soc'] = $thirdparty_id;
752 }
753 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
754 }
755
756 if (empty($prodcustprice->lines)) {
757 throw new RestException(404, 'Prices not found');
758 }
759
760 return $prodcustprice->lines;
761 }
762
772 public function getCustomerPricesPerQuantity($id)
773 {
774 global $conf;
775
776 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
777 throw new RestException(403);
778 }
779
780 if (!getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
781 throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup');
782 }
783
784 $result = $this->product->fetch($id);
785 if (!$result) {
786 throw new RestException(404, 'Product not found');
787 }
788
789 if ($result < 0) {
790 throw new RestException(503, 'Error when retrieve prices list : '.implode(',', array_merge(array($this->product->error), $this->product->errors)));
791 }
792
793 return array(
794 'prices_by_qty'=>$this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product
795 'prices_by_qty_list'=>$this->product->prices_by_qty_list[0]
796 );
797 }
798
832 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)
833 {
834 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
835 throw new RestException(403);
836 }
837
838 $result = $this->productsupplier->fetch($id);
839 if (!$result) {
840 throw new RestException(404, 'Product not found');
841 }
842
843 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
844 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
845 }
846
847 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
848 if ($socid > 0 && $socid != $fourn_id) {
849 throw new RestException(403, 'Adding purchase price for the supplier ID '.$fourn_id.' is not allowed for login '.DolibarrApiAccess::$user->login);
850 }
851
852 $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty);
853 if ($result < 0) {
854 throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror());
855 }
856
857 $fourn = new Fournisseur($this->db);
858 $result = $fourn->fetch($fourn_id);
859 if ($result <= 0) {
860 throw new RestException(404, 'Supplier not found');
861 }
862
863 // Clean data
864 $ref_fourn = sanitizeVal($ref_fourn, 'alphanohtml');
865 $desc_fourn = sanitizeVal($desc_fourn, 'restricthtml');
866 $barcode = sanitizeVal($barcode, 'alphanohtml');
867
868 $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);
869
870 if ($result <= 0) {
871 throw new RestException(500, "Error updating buy price : ".$this->db->lasterror());
872 }
873 return (int) $this->productsupplier->product_fourn_price_id;
874 }
875
890 public function deletePurchasePrice($id, $priceid)
891 {
892 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
893 throw new RestException(403);
894 }
895 $result = $this->productsupplier->fetch($id);
896 if (!$result) {
897 throw new RestException(404, 'Product not found');
898 }
899
900 if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) {
901 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
902 }
903
904 $resultsupplier = 0;
905 if ($result > 0) {
906 $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid);
907 }
908
909 return $resultsupplier;
910 }
911
927 public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '')
928 {
929 global $db, $conf;
930
931 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
932 throw new RestException(403);
933 }
934
935 $obj_ret = array();
936
937 // Force id of company for external users
938 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
939 if ($socid > 0) {
940 if ($supplier != $socid || empty($supplier)) {
941 throw new RestException(403, 'As an external user, you can request only for your supplier id = '.$socid);
942 }
943 }
944
945 $sql = "SELECT t.rowid, t.ref, t.ref_ext";
946 $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
947
948 if ($category > 0) {
949 $sql .= ", ".$this->db->prefix()."categorie_product as c";
950 }
951 $sql .= ", ".$this->db->prefix()."product_fournisseur_price as s";
952
953 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
954
955 if ($supplier > 0) {
956 $sql .= " AND s.fk_soc = ".((int) $supplier);
957 }
958 if ($socid > 0) { // if external user
959 $sql .= " AND s.fk_soc = ".((int) $socid);
960 }
961 $sql .= " AND s.fk_product = t.rowid";
962 // Select products of given category
963 if ($category > 0) {
964 $sql .= " AND c.fk_categorie = ".((int) $category);
965 $sql .= " AND c.fk_product = t.rowid";
966 }
967 if ($mode == 1) {
968 // Show only products
969 $sql .= " AND t.fk_product_type = 0";
970 } elseif ($mode == 2) {
971 // Show only services
972 $sql .= " AND t.fk_product_type = 1";
973 }
974 // Add sql filters
975 if ($sqlfilters) {
976 $errormessage = '';
977 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
978 if ($errormessage) {
979 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
980 }
981 }
982
983 $sql .= $this->db->order($sortfield, $sortorder);
984 if ($limit) {
985 if ($page < 0) {
986 $page = 0;
987 }
988 $offset = $limit * $page;
989 $sql .= $this->db->plimit($limit + 1, $offset);
990 }
991 $result = $this->db->query($sql);
992 if ($result) {
993 $num = $this->db->num_rows($result);
994 $min = min($num, ($limit <= 0 ? $num : $limit));
995 $i = 0;
996 while ($i < $min) {
997 $obj = $this->db->fetch_object($result);
998
999 $product_fourn = new ProductFournisseur($this->db);
1000 $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0);
1001 foreach ($product_fourn_list as $tmpobj) {
1002 $this->_cleanObjectDatas($tmpobj);
1003 }
1004
1005 //var_dump($product_fourn_list->db);exit;
1006 $obj_ret[$obj->rowid] = $product_fourn_list;
1007
1008 $i++;
1009 }
1010 } else {
1011 throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
1012 }
1013
1014 return $obj_ret;
1015 }
1016
1036 public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '')
1037 {
1038 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
1039 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
1040 }
1041
1042 $id = (empty($id) ? 0 : $id);
1043
1044 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1045 throw new RestException(403);
1046 }
1047
1048 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
1049
1050 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode);
1051 if (!$result) {
1052 throw new RestException(404, 'Product not found');
1053 }
1054
1055 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
1056 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1057 }
1058
1059 $product_fourn_list = array();
1060
1061 if ($result) {
1062 $product_fourn = new ProductFournisseur($this->db);
1063 $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0, ($socid > 0 ? $socid : 0));
1064 }
1065
1066 foreach ($product_fourn_list as $tmpobj) {
1067 $this->_cleanObjectDatas($tmpobj);
1068 }
1069
1070 return $this->_cleanObjectDatas($product_fourn_list);
1071 }
1072
1090 public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
1091 {
1092 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1093 throw new RestException(403);
1094 }
1095
1096 $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.position, t.entity";
1097 $sql .= " FROM ".$this->db->prefix()."product_attribute as t";
1098 $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
1099
1100 // Add sql filters
1101 if ($sqlfilters) {
1102 $errormessage = '';
1103 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
1104 if ($errormessage) {
1105 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
1106 }
1107 }
1108
1109 $sql .= $this->db->order($sortfield, $sortorder);
1110 if ($limit) {
1111 if ($page < 0) {
1112 $page = 0;
1113 }
1114 $offset = $limit * $page;
1115
1116 $sql .= $this->db->plimit($limit, $offset);
1117 }
1118
1119 $resql = $this->db->query($sql);
1120
1121 if (!$resql) {
1122 throw new RestException(503, 'Error when retrieving product attribute list : '.$this->db->lasterror());
1123 }
1124
1125 $return = array();
1126 while ($obj = $this->db->fetch_object($resql)) {
1127 $tmp = new ProductAttribute($this->db);
1128 $tmp->id = $obj->rowid;
1129 $tmp->ref = $obj->ref;
1130 $tmp->ref_ext = $obj->ref_ext;
1131 $tmp->label = $obj->label;
1132 $tmp->position = $obj->position;
1133 $tmp->entity = $obj->entity;
1134
1135 $return[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp), $properties);
1136 }
1137
1138 return $return;
1139 }
1140
1152 public function getAttributeById($id)
1153 {
1154 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1155 throw new RestException(403);
1156 }
1157
1158 $prodattr = new ProductAttribute($this->db);
1159 $result = $prodattr->fetch((int) $id);
1160
1161 if ($result < 0) {
1162 throw new RestException(404, "Product attribute not found");
1163 }
1164
1165 $fields = ["id", "ref", "ref_ext", "label", "position", "entity"];
1166
1167 foreach ($prodattr as $field => $value) {
1168 if (!in_array($field, $fields)) {
1169 unset($prodattr->{$field});
1170 }
1171 }
1172
1173 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1174 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1175 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")";
1176
1177 $resql = $this->db->query($sql);
1178 $obj = $this->db->fetch_object($resql);
1179 $prodattr->is_used_by_products = (int) $obj->nb;
1180
1181 return $this->_cleanObjectDatas($prodattr);
1182 }
1183
1195 public function getAttributesByRef($ref)
1196 {
1197 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1198 throw new RestException(403);
1199 }
1200
1201 $ref = trim($ref);
1202
1203 $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').")";
1204
1205 $query = $this->db->query($sql);
1206
1207 if (!$this->db->num_rows($query)) {
1208 throw new RestException(404);
1209 }
1210
1211 $result = $this->db->fetch_object($query);
1212
1213 $attr = array();
1214 $attr['id'] = $result->rowid;
1215 $attr['ref'] = $result->ref;
1216 $attr['ref_ext'] = $result->ref_ext;
1217 $attr['label'] = $result->label;
1218 $attr['rang'] = $result->position;
1219 $attr['position'] = $result->position;
1220 $attr['entity'] = $result->entity;
1221
1222 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1223 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1224 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1225
1226 $resql = $this->db->query($sql);
1227 $obj = $this->db->fetch_object($resql);
1228
1229 $attr["is_used_by_products"] = (int) $obj->nb;
1230
1231 return $attr;
1232 }
1233
1245 public function getAttributesByRefExt($ref_ext)
1246 {
1247 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1248 throw new RestException(403);
1249 }
1250
1251 $ref_ext = trim($ref_ext);
1252
1253 $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').")";
1254
1255 $query = $this->db->query($sql);
1256
1257 if (!$this->db->num_rows($query)) {
1258 throw new RestException(404);
1259 }
1260
1261 $result = $this->db->fetch_object($query);
1262
1263 $attr = array();
1264 $attr['id'] = $result->rowid;
1265 $attr['ref'] = $result->ref;
1266 $attr['ref_ext'] = $result->ref_ext;
1267 $attr['label'] = $result->label;
1268 $attr['rang'] = $result->position;
1269 $attr['position'] = $result->position;
1270 $attr['entity'] = $result->entity;
1271
1272 $sql = "SELECT COUNT(*) as nb FROM ".$this->db->prefix()."product_attribute_combination2val as pac2v";
1273 $sql .= " JOIN ".$this->db->prefix()."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid";
1274 $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")";
1275
1276 $resql = $this->db->query($sql);
1277 $obj = $this->db->fetch_object($resql);
1278
1279 $attr["is_used_by_products"] = (int) $obj->nb;
1280
1281 return $attr;
1282 }
1283
1297 public function addAttributes($ref, $label, $ref_ext = '')
1298 {
1299 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1300 throw new RestException(403);
1301 }
1302
1303 $prodattr = new ProductAttribute($this->db);
1304 $prodattr->label = $label;
1305 $prodattr->ref = $ref;
1306 $prodattr->ref_ext = $ref_ext;
1307
1308 $resid = $prodattr->create(DolibarrApiAccess::$user);
1309 if ($resid <= 0) {
1310 throw new RestException(500, "Error creating new attribute");
1311 }
1312
1313 return $resid;
1314 }
1315
1329 public function putAttributes($id, $request_data = null)
1330 {
1331 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1332 throw new RestException(403);
1333 }
1334
1335 $prodattr = new ProductAttribute($this->db);
1336
1337 $result = $prodattr->fetch((int) $id);
1338 if ($result == 0) {
1339 throw new RestException(404, 'Attribute not found');
1340 } elseif ($result < 0) {
1341 throw new RestException(500, "Error fetching attribute");
1342 }
1343
1344 foreach ($request_data as $field => $value) {
1345 if ($field == 'rowid') {
1346 continue;
1347 }
1348 if ($field === 'caller') {
1349 // 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
1350 $prodattr->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1351 continue;
1352 }
1353
1354 $prodattr->$field = $this->_checkValForAPI($field, $value, $prodattr);
1355 }
1356
1357 if ($prodattr->update(DolibarrApiAccess::$user) > 0) {
1358 $result = $prodattr->fetch((int) $id);
1359 if ($result == 0) {
1360 throw new RestException(404, 'Attribute not found');
1361 } elseif ($result < 0) {
1362 throw new RestException(500, "Error fetching attribute");
1363 } else {
1364 return $this->_cleanObjectDatas($prodattr);
1365 }
1366 }
1367 throw new RestException(500, "Error updating attribute");
1368 }
1369
1381 public function deleteAttributes($id)
1382 {
1383 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1384 throw new RestException(403);
1385 }
1386
1387 $prodattr = new ProductAttribute($this->db);
1388 $prodattr->id = (int) $id;
1389 $result = $prodattr->delete(DolibarrApiAccess::$user);
1390
1391 if ($result <= 0) {
1392 throw new RestException(500, "Error deleting attribute");
1393 }
1394
1395 return $result;
1396 }
1397
1409 public function getAttributeValueById($id)
1410 {
1411 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1412 throw new RestException(403);
1413 }
1414
1415 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")";
1416
1417 $query = $this->db->query($sql);
1418
1419 if (!$query) {
1420 throw new RestException(403);
1421 }
1422
1423 if (!$this->db->num_rows($query)) {
1424 throw new RestException(404, 'Attribute value not found');
1425 }
1426
1427 $result = $this->db->fetch_object($query);
1428
1429 $attrval = array();
1430 $attrval['id'] = $result->rowid;
1431 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1432 $attrval['ref'] = $result->ref;
1433 $attrval['value'] = $result->value;
1434
1435 return $attrval;
1436 }
1437
1450 public function getAttributeValueByRef($id, $ref)
1451 {
1452 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1453 throw new RestException(403);
1454 }
1455
1456 $ref = trim($ref);
1457
1458 $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".$this->db->prefix()."product_attribute_value";
1459 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1460
1461 $query = $this->db->query($sql);
1462
1463 if (!$query) {
1464 throw new RestException(403);
1465 }
1466
1467 if (!$this->db->num_rows($query)) {
1468 throw new RestException(404, 'Attribute value not found');
1469 }
1470
1471 $result = $this->db->fetch_object($query);
1472
1473 $attrval = array();
1474 $attrval['id'] = $result->rowid;
1475 $attrval['fk_product_attribute'] = $result->fk_product_attribute;
1476 $attrval['ref'] = $result->ref;
1477 $attrval['value'] = $result->value;
1478
1479 return $attrval;
1480 }
1481
1493 public function deleteAttributeValueByRef($id, $ref)
1494 {
1495 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1496 throw new RestException(403);
1497 }
1498
1499 $ref = trim($ref);
1500
1501 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_value";
1502 $sql .= " WHERE ref LIKE '".$this->db->escape($ref)."' AND fk_product_attribute = ".((int) $id)." AND entity IN (".getEntity('product').")";
1503 $query = $this->db->query($sql);
1504
1505 if (!$query) {
1506 throw new RestException(403);
1507 }
1508
1509 if (!$this->db->num_rows($query)) {
1510 throw new RestException(404, 'Attribute value not found');
1511 }
1512
1513 $result = $this->db->fetch_object($query);
1514
1515 $attrval = new ProductAttributeValue($this->db);
1516 $attrval->id = $result->rowid;
1517 $result = $attrval->delete(DolibarrApiAccess::$user);
1518 if ($result > 0) {
1519 return 1;
1520 }
1521
1522 throw new RestException(500, "Error deleting attribute value");
1523 }
1524
1536 public function getAttributeValues($id)
1537 {
1538 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1539 throw new RestException(403);
1540 }
1541
1542 $objectval = new ProductAttributeValue($this->db);
1543
1544 $return = $objectval->fetchAllByProductAttribute((int) $id);
1545
1546 if (count($return) == 0) {
1547 throw new RestException(404, 'Attribute values not found');
1548 }
1549
1550 foreach ($return as $key => $val) {
1551 $return[$key] = $this->_cleanObjectDatas($return[$key]);
1552 }
1553
1554 return $return;
1555 }
1556
1567 public function getAttributeValuesByRef($ref)
1568 {
1569 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1570 throw new RestException(403);
1571 }
1572
1573 $ref = trim($ref);
1574
1575 $return = array();
1576
1577 $sql = "SELECT ";
1578 $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM ".$this->db->prefix()."product_attribute_value as v";
1579 $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".$this->db->prefix()."product_attribute WHERE ref LIKE '".$this->db->escape($ref)."')";
1580
1581 $resql = $this->db->query($sql);
1582
1583 while ($result = $this->db->fetch_object($resql)) {
1584 $tmp = new ProductAttributeValue($this->db);
1585 $tmp->fk_product_attribute = $result->fk_product_attribute;
1586 $tmp->id = $result->rowid;
1587 $tmp->ref = $result->ref;
1588 $tmp->value = $result->value;
1589
1590 $return[] = $this->_cleanObjectDatas($tmp);
1591 }
1592
1593 return $return;
1594 }
1595
1609 public function addAttributeValue($id, $ref, $value)
1610 {
1611 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1612 throw new RestException(403);
1613 }
1614
1615 if (empty($ref) || empty($value)) {
1616 throw new RestException(403);
1617 }
1618
1619 $objectval = new ProductAttributeValue($this->db);
1620 $objectval->fk_product_attribute = ((int) $id);
1621 $objectval->ref = $ref;
1622 $objectval->value = $value;
1623
1624 if ($objectval->create(DolibarrApiAccess::$user) > 0) {
1625 return $objectval->id;
1626 }
1627 throw new RestException(500, "Error creating new attribute value");
1628 }
1629
1642 public function putAttributeValue($id, $request_data)
1643 {
1644 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1645 throw new RestException(403);
1646 }
1647
1648 $objectval = new ProductAttributeValue($this->db);
1649 $result = $objectval->fetch((int) $id);
1650
1651 if ($result == 0) {
1652 throw new RestException(404, 'Attribute value not found');
1653 } elseif ($result < 0) {
1654 throw new RestException(500, "Error fetching attribute value");
1655 }
1656
1657 foreach ($request_data as $field => $value) {
1658 if ($field == 'rowid') {
1659 continue;
1660 }
1661 if ($field === 'caller') {
1662 // 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
1663 $objectval->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1664 continue;
1665 }
1666
1667 $objectval->$field = $this->_checkValForAPI($field, $value, $objectval);
1668 }
1669
1670 if ($objectval->update(DolibarrApiAccess::$user) > 0) {
1671 $result = $objectval->fetch((int) $id);
1672 if ($result == 0) {
1673 throw new RestException(404, 'Attribute not found');
1674 } elseif ($result < 0) {
1675 throw new RestException(500, "Error fetching attribute");
1676 } else {
1677 return $this->_cleanObjectDatas($objectval);
1678 }
1679 }
1680 throw new RestException(500, "Error updating attribute");
1681 }
1682
1694 public function deleteAttributeValueById($id)
1695 {
1696 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1697 throw new RestException(403);
1698 }
1699
1700 $objectval = new ProductAttributeValue($this->db);
1701 $objectval->id = (int) $id;
1702
1703 if ($objectval->delete(DolibarrApiAccess::$user) > 0) {
1704 return 1;
1705 }
1706 throw new RestException(500, "Error deleting attribute value");
1707 }
1708
1721 public function getVariants($id, $includestock = 0)
1722 {
1723 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1724 throw new RestException(403);
1725 }
1726
1727 $prodcomb = new ProductCombination($this->db);
1728 $combinations = $prodcomb->fetchAllByFkProductParent((int) $id);
1729
1730 foreach ($combinations as $key => $combination) {
1731 $prodc2vp = new ProductCombination2ValuePair($this->db);
1732 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1733 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1734
1735 if (!empty($includestock) && DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
1736 $productModel = new Product($this->db);
1737 $productModel->fetch((int) $combination->fk_product_child);
1738 $productModel->load_stock($includestock);
1739 $combinations[$key]->stock_warehouse = $this->_cleanObjectDatas($productModel)->stock_warehouse;
1740 }
1741 }
1742
1743 return $combinations;
1744 }
1745
1757 public function getVariantsByProdRef($ref)
1758 {
1759 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
1760 throw new RestException(403);
1761 }
1762
1763 $result = $this->product->fetch(0, $ref);
1764 if (!$result) {
1765 throw new RestException(404, 'Product not found');
1766 }
1767
1768 $prodcomb = new ProductCombination($this->db);
1769 $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id);
1770
1771 foreach ($combinations as $key => $combination) {
1772 $prodc2vp = new ProductCombination2ValuePair($this->db);
1773 $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id);
1774 $combinations[$key] = $this->_cleanObjectDatas($combinations[$key]);
1775 }
1776
1777 return $combinations;
1778 }
1779
1800 public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '')
1801 {
1802 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1803 throw new RestException(403);
1804 }
1805
1806 if (empty($id)) {
1807 throw new RestException(400, 'Product ID is mandatory');
1808 }
1809
1810 if (empty($features) || !is_array($features)) {
1811 throw new RestException(400, 'Features is mandatory and should be IDs of attribute values indexed by IDs of attributes');
1812 }
1813
1814 $weight_impact = price2num($weight_impact);
1815 $price_impact = price2num($price_impact);
1816
1817 $prodattr = new ProductAttribute($this->db);
1818 $prodattr_val = new ProductAttributeValue($this->db);
1819 foreach ($features as $id_attr => $id_value) {
1820 if ($prodattr->fetch((int) $id_attr) < 0) {
1821 throw new RestException(400, 'Invalid attribute ID: '.$id_attr);
1822 }
1823 if ($prodattr_val->fetch((int) $id_value) < 0) {
1824 throw new RestException(400, 'Invalid attribute value ID: '.$id_value);
1825 }
1826 }
1827
1828 $result = $this->product->fetch((int) $id);
1829 if (!$result) {
1830 throw new RestException(404, 'Product not found');
1831 }
1832
1833 $prodcomb = new ProductCombination($this->db);
1834
1835 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
1836 if ($result > 0) {
1837 return $result;
1838 } else {
1839 throw new RestException(500, "Error creating new product variant");
1840 }
1841 }
1842
1861 public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features)
1862 {
1863 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1864 throw new RestException(403);
1865 }
1866
1867 if (empty($ref) || empty($features) || !is_array($features)) {
1868 throw new RestException(403);
1869 }
1870
1871 $weight_impact = price2num($weight_impact);
1872 $price_impact = price2num($price_impact);
1873
1874 $prodattr = new ProductAttribute($this->db);
1875 $prodattr_val = new ProductAttributeValue($this->db);
1876 foreach ($features as $id_attr => $id_value) {
1877 if ($prodattr->fetch((int) $id_attr) < 0) {
1878 throw new RestException(404);
1879 }
1880 if ($prodattr_val->fetch((int) $id_value) < 0) {
1881 throw new RestException(404);
1882 }
1883 }
1884
1885 $result = $this->product->fetch(0, trim($ref));
1886 if (!$result) {
1887 throw new RestException(404, 'Product not found');
1888 }
1889
1890 $prodcomb = new ProductCombination($this->db);
1891 if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
1892 $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
1893 if ($result > 0) {
1894 return $result;
1895 } else {
1896 throw new RestException(500, "Error creating new product variant");
1897 }
1898 } else {
1899 return $prodcomb->id;
1900 }
1901 }
1902
1915 public function putVariant($id, $request_data = null)
1916 {
1917 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
1918 throw new RestException(403);
1919 }
1920
1921 $prodcomb = new ProductCombination($this->db);
1922 $prodcomb->fetch((int) $id);
1923
1924 foreach ($request_data as $field => $value) {
1925 if ($field == 'rowid') {
1926 continue;
1927 }
1928 if ($field === 'caller') {
1929 // 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
1930 $prodcomb->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
1931 continue;
1932 }
1933
1934 $prodcomb->$field = $this->_checkValForAPI($field, $value, $prodcomb);
1935 }
1936
1937 $result = $prodcomb->update(DolibarrApiAccess::$user);
1938 if ($result > 0) {
1939 return 1;
1940 }
1941 throw new RestException(500, "Error editing variant");
1942 }
1943
1955 public function deleteVariant($id)
1956 {
1957 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
1958 throw new RestException(403);
1959 }
1960
1961 $prodcomb = new ProductCombination($this->db);
1962 $prodcomb->id = (int) $id;
1963 $result = $prodcomb->delete(DolibarrApiAccess::$user);
1964 if ($result <= 0) {
1965 throw new RestException(500, "Error deleting variant");
1966 }
1967 return $result;
1968 }
1969
1984 public function getStock($id, $selected_warehouse_id = null)
1985 {
1986 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire') || !DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
1987 throw new RestException(403);
1988 }
1989
1990 if (!DolibarrApi::_checkAccessToResource('product', $id)) {
1991 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1992 }
1993
1994 $product_model = new Product($this->db);
1995 $product_model->fetch($id);
1996 $product_model->load_stock();
1997
1998 $stockData = $this->_cleanObjectDatas($product_model)->stock_warehouse;
1999 if ($selected_warehouse_id) {
2000 foreach ($stockData as $warehouse_id => $warehouse) {
2001 if ($warehouse_id != $selected_warehouse_id) {
2002 unset($stockData[$warehouse_id]);
2003 }
2004 }
2005 }
2006
2007 return array('stock_warehouses'=>$stockData);
2008 }
2009
2010 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2017 protected function _cleanObjectDatas($object)
2018 {
2019 // phpcs:enable
2020 $object = parent::_cleanObjectDatas($object);
2021
2022 unset($object->statut);
2023
2024 unset($object->regeximgext);
2025 unset($object->price_by_qty);
2026 unset($object->prices_by_qty_id);
2027 unset($object->libelle);
2028 unset($object->product_id_already_linked);
2029 unset($object->reputations);
2030 unset($object->db);
2031 unset($object->name);
2032 unset($object->firstname);
2033 unset($object->lastname);
2034 unset($object->civility_id);
2035 unset($object->contact);
2036 unset($object->contact_id);
2037 unset($object->thirdparty);
2038 unset($object->user);
2039 unset($object->origin);
2040 unset($object->origin_id);
2041 unset($object->fourn_pu);
2042 unset($object->fourn_price_base_type);
2043 unset($object->fourn_socid);
2044 unset($object->ref_fourn);
2045 unset($object->ref_supplier);
2046 unset($object->product_fourn_id);
2047 unset($object->fk_project);
2048
2049 unset($object->mode_reglement_id);
2050 unset($object->cond_reglement_id);
2051 unset($object->demand_reason_id);
2052 unset($object->transport_mode_id);
2053 unset($object->cond_reglement);
2054 unset($object->shipping_method_id);
2055 unset($object->model_pdf);
2056 unset($object->note);
2057
2058 unset($object->nbphoto);
2059 unset($object->recuperableonly);
2060 unset($object->multiprices_recuperableonly);
2061 unset($object->tva_npr);
2062 unset($object->lines);
2063 unset($object->fk_bank);
2064 unset($object->fk_account);
2065
2066 unset($object->supplierprices); // Must use another API to get them
2067
2068 if (!DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
2069 unset($object->stock_reel);
2070 unset($object->stock_theorique);
2071 unset($object->stock_warehouse);
2072 }
2073
2074 return $object;
2075 }
2076
2084 private function _validate($data)
2085 {
2086 $product = array();
2087 foreach (Products::$FIELDS as $field) {
2088 if (!isset($data[$field])) {
2089 throw new RestException(400, "$field field missing");
2090 }
2091 $product[$field] = $data[$field];
2092 }
2093 return $product;
2094 }
2095
2115 private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false, $includeifobjectisused = false, $includetrans = false)
2116 {
2117 if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) {
2118 throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode');
2119 }
2120
2121 $id = (empty($id) ? 0 : $id);
2122
2123 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
2124 throw new RestException(403);
2125 }
2126
2127 $result = $this->product->fetch($id, $ref, $ref_ext, $barcode, 0, 0, ($includetrans ? 0 : 1));
2128 if (!$result) {
2129 throw new RestException(404, 'Product not found');
2130 }
2131
2132 if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) {
2133 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2134 }
2135
2136 if (!empty($includestockdata) && DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
2137 $this->product->load_stock($includestockdata);
2138
2139 if (is_array($this->product->stock_warehouse)) {
2140 foreach ($this->product->stock_warehouse as $keytmp => $valtmp) {
2141 if (isset($this->product->stock_warehouse[$keytmp]->detail_batch) && is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) {
2142 foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
2143 unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
2144 }
2145 }
2146 }
2147 }
2148 }
2149
2150 if ($includesubproducts) {
2151 $childrenArbo = $this->product->getChildsArbo($id, 1);
2152
2153 $keys = array('rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang');
2154 $children = array();
2155 foreach ($childrenArbo as $values) {
2156 $children[] = array_combine($keys, $values);
2157 }
2158
2159 $this->product->sousprods = $children;
2160 }
2161
2162 if ($includeparentid) {
2163 $prodcomb = new ProductCombination($this->db);
2164 $this->product->fk_product_parent = null;
2165 if (($fk_product_parent = $prodcomb->fetchByFkProductChild($this->product->id)) > 0) {
2166 $this->product->fk_product_parent = $fk_product_parent;
2167 }
2168 }
2169
2170 if ($includeifobjectisused) {
2171 $this->product->is_object_used = ($this->product->isObjectUsed() > 0);
2172 }
2173
2174 return $this->_cleanObjectDatas($this->product);
2175 }
2176}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.