apiproductlisthelper.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. <?php
  2. use Luracast\Restler\RestException;
  3. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4. require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
  5. class ApiProductListProduct extends Product
  6. {
  7. public $sub_products;
  8. }
  9. class ApiProductListHelper
  10. {
  11. public $db;
  12. /**
  13. *
  14. */
  15. public function __construct()
  16. {
  17. global $db;
  18. $this->db = $db;
  19. }
  20. /**
  21. *
  22. */
  23. public function list($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): array
  24. {
  25. $obj_ret = array();
  26. //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
  27. $sql = "SELECT t.rowid, t.ref, t.ref_ext";
  28. $sql .= " FROM ".$this->db->prefix()."product as t";
  29. $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
  30. if ($category > 0) {
  31. $sql .= ", ".$this->db->prefix()."categorie_product as c";
  32. }
  33. $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
  34. $sql .= ' AND ef.hotelsales IS NULL';
  35. if ($variant_filter == 1) {
  36. $sql .= ' AND t.rowid not in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
  37. $sql .= ' AND t.rowid not in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
  38. }
  39. if ($variant_filter == 2) {
  40. $sql .= ' AND t.rowid in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
  41. }
  42. if ($variant_filter == 3) {
  43. $sql .= ' AND t.rowid in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
  44. }
  45. // Select products of given category
  46. if ($category > 0) {
  47. $sql .= " AND c.fk_categorie = ".((int) $category);
  48. $sql .= " AND c.fk_product = t.rowid";
  49. }
  50. if ($mode == 1) {
  51. // Show only products
  52. $sql .= " AND t.fk_product_type = 0";
  53. } elseif ($mode == 2) {
  54. // Show only services
  55. $sql .= " AND t.fk_product_type = 1";
  56. }
  57. // Add sql filters
  58. if ($sqlfilters) {
  59. $errormessage = '';
  60. if (!$this->_checkFilters($sqlfilters, $errormessage)) {
  61. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  62. }
  63. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)'; // We must accept datc:<:2020-01-01 10:10:10
  64. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'ApiProductListHelper::_forge_criteria_callback', $sqlfilters).")";
  65. }
  66. //print $sql;exit;
  67. //this query will return total products with the filters given
  68. $sqlTotals = str_replace('SELECT t.rowid, t.ref, t.ref_ext', 'SELECT count(t.rowid) as total', $sql);
  69. $sql .= $this->db->order($sortfield, $sortorder);
  70. if ($limit) {
  71. if ($page < 0) {
  72. $page = 0;
  73. }
  74. $offset = $limit * $page;
  75. $sql .= $this->db->plimit($limit + 1, $offset);
  76. }
  77. $result = $this->db->query($sql);
  78. if ($result) {
  79. $num = $this->db->num_rows($result);
  80. $min = min($num, ($limit <= 0 ? $num : $limit));
  81. $i = 0;
  82. while ($i < $min) {
  83. $obj = $this->db->fetch_object($result);
  84. if (!$ids_only) {
  85. $product_static = new ApiProductListProduct($this->db);
  86. if ($product_static->fetch($obj->rowid)) {
  87. if ($includestockdata && DolibarrApiAccess::$user->rights->stock->lire) {
  88. $product_static->load_stock();
  89. if (is_array($product_static->stock_warehouse)) {
  90. foreach ($product_static->stock_warehouse as $keytmp => $valtmp) {
  91. if (isset($product_static->stock_warehouse[$keytmp]->detail_batch) && is_array($product_static->stock_warehouse[$keytmp]->detail_batch)) {
  92. foreach ($product_static->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
  93. unset($product_static->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
  94. }
  95. }
  96. }
  97. }
  98. }
  99. // get child details
  100. $product_static->sub_products = $this->_getSubproducts($product_static);
  101. $obj_ret[] = $this->_cleanObjectDatas($product_static);
  102. }
  103. } else {
  104. $obj_ret[] = $obj->rowid;
  105. }
  106. $i++;
  107. }
  108. } else {
  109. throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
  110. }
  111. if (!count($obj_ret)) {
  112. throw new RestException(404, 'No product found');
  113. }
  114. //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
  115. if ($pagination_data) {
  116. $totalsResult = $this->db->query($sqlTotals);
  117. $total = $this->db->fetch_object($totalsResult)->total;
  118. $tmp = $obj_ret;
  119. $obj_ret = array();
  120. $obj_ret['data'] = $tmp;
  121. $obj_ret['pagination'] = array(
  122. 'total' => (int) $total,
  123. 'page' => $page, //count starts from 0
  124. 'page_count' => ceil((int) $total/$limit),
  125. 'limit' => $limit
  126. );
  127. }
  128. return $obj_ret;
  129. }
  130. /**
  131. *
  132. */
  133. public function listhotel($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): array
  134. {
  135. $obj_ret = array();
  136. //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
  137. $sql = "SELECT t.rowid, t.ref, t.ref_ext";
  138. $sql .= " FROM ".$this->db->prefix()."product as t";
  139. $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
  140. if ($category > 0) {
  141. $sql .= ", ".$this->db->prefix()."categorie_product as c";
  142. }
  143. $sql .= ' WHERE t.entity IN ('.getEntity('product').')';
  144. if ($variant_filter == 1) {
  145. $sql .= ' AND t.rowid not in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
  146. $sql .= ' AND t.rowid not in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
  147. }
  148. if ($variant_filter == 2) {
  149. $sql .= ' AND t.rowid in (select distinct fk_product_parent from '.$this->db->prefix().'product_attribute_combination)';
  150. }
  151. if ($variant_filter == 3) {
  152. $sql .= ' AND t.rowid in (select distinct fk_product_child from '.$this->db->prefix().'product_attribute_combination)';
  153. }
  154. // Select products of given category
  155. if ($category > 0) {
  156. $sql .= " AND c.fk_categorie = ".((int) $category);
  157. $sql .= " AND c.fk_product = t.rowid";
  158. }
  159. if ($mode == 1) {
  160. // Show only products
  161. $sql .= " AND t.fk_product_type = 0";
  162. } elseif ($mode == 2) {
  163. // Show only services
  164. $sql .= " AND t.fk_product_type = 1";
  165. }
  166. // Add sql filters
  167. if ($sqlfilters) {
  168. $errormessage = '';
  169. if (!$this->_checkFilters($sqlfilters, $errormessage)) {
  170. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  171. }
  172. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)'; // We must accept datc:<:2020-01-01 10:10:10
  173. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'ApiProductListHelper::_forge_criteria_callback', $sqlfilters).")";
  174. }
  175. //this query will return total products with the filters given
  176. $sqlTotals = str_replace('SELECT t.rowid, t.ref, t.ref_ext', 'SELECT count(t.rowid) as total', $sql);
  177. $sql .= $this->db->order($sortfield, $sortorder);
  178. if ($limit) {
  179. if ($page < 0) {
  180. $page = 0;
  181. }
  182. $offset = $limit * $page;
  183. $sql .= $this->db->plimit($limit + 1, $offset);
  184. }
  185. //print $sql;exit;
  186. $result = $this->db->query($sql);
  187. if ($result) {
  188. $num = $this->db->num_rows($result);
  189. $min = min($num, ($limit <= 0 ? $num : $limit));
  190. $i = 0;
  191. while ($i < $min) {
  192. $obj = $this->db->fetch_object($result);
  193. if (!$ids_only) {
  194. $product_static = new ApiProductListProduct($this->db);
  195. if ($product_static->fetch($obj->rowid)) {
  196. if ($includestockdata && DolibarrApiAccess::$user->rights->stock->lire) {
  197. $product_static->load_stock();
  198. if (is_array($product_static->stock_warehouse)) {
  199. foreach ($product_static->stock_warehouse as $keytmp => $valtmp) {
  200. if (isset($product_static->stock_warehouse[$keytmp]->detail_batch) && is_array($product_static->stock_warehouse[$keytmp]->detail_batch)) {
  201. foreach ($product_static->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) {
  202. unset($product_static->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db);
  203. }
  204. }
  205. }
  206. }
  207. }
  208. // get child details
  209. $product_static->sub_products = $this->_getSubproducts($product_static);
  210. $obj_ret[] = $this->_cleanObjectDatas($product_static);
  211. }
  212. } else {
  213. $obj_ret[] = $obj->rowid;
  214. }
  215. $i++;
  216. }
  217. } else {
  218. throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror());
  219. }
  220. if (!count($obj_ret)) {
  221. throw new RestException(404, 'No product found');
  222. }
  223. //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
  224. if ($pagination_data) {
  225. $totalsResult = $this->db->query($sqlTotals);
  226. $total = $this->db->fetch_object($totalsResult)->total;
  227. $tmp = $obj_ret;
  228. $obj_ret = array();
  229. $obj_ret['data'] = $tmp;
  230. $obj_ret['pagination'] = array(
  231. 'total' => (int) $total,
  232. 'page' => $page, //count starts from 0
  233. 'page_count' => ceil((int) $total/$limit),
  234. 'limit' => $limit
  235. );
  236. }
  237. return $obj_ret;
  238. }
  239. /**
  240. * Return subproducts
  241. *
  242. * @param ApiProductListProduct $product Product
  243. *
  244. * @return array
  245. */
  246. protected function _getSubproducts(ApiProductListProduct $product): array
  247. {
  248. $children = [];
  249. $subProducts = $product->getChildsArbo($product->id, 1);
  250. $keys = ['rowid', 'qty', 'fk_product_type', 'label', 'incdec', 'ref', 'fk_association', 'rang'];
  251. foreach ($subProducts as $values) {
  252. $subProductData = array_combine($keys, $values);
  253. $subProduct = new Product($this->db);
  254. if ($subProduct->fetch($subProductData['rowid']) > 0) {
  255. $children[] = $this->_cleanObjectDatas($subProduct);
  256. }
  257. }
  258. return $children;
  259. }
  260. /**
  261. * Return if a $sqlfilters parameter is valid
  262. *
  263. * @param string $sqlfilters sqlfilter string
  264. * @param string $error Error message
  265. * @return boolean|string True if valid, False if not valid
  266. */
  267. protected function _checkFilters($sqlfilters, &$error = '')
  268. {
  269. // phpcs:enable
  270. return dolCheckFilters($sqlfilters, $error);
  271. }
  272. /**
  273. * Clean sensible object datas
  274. *
  275. * @param Object $object Object to clean
  276. * @return Object Object with cleaned properties
  277. */
  278. protected function _cleanObjectDatas($object)
  279. {
  280. // phpcs:enable
  281. // Remove $db object property for object
  282. unset($object->db);
  283. unset($object->isextrafieldmanaged);
  284. unset($object->ismultientitymanaged);
  285. unset($object->restrictiononfksoc);
  286. unset($object->table_rowid);
  287. unset($object->pass);
  288. unset($object->pass_indatabase);
  289. // Remove linkedObjects. We should already have linkedObjectsIds that avoid huge responses
  290. unset($object->linkedObjects);
  291. unset($object->fields);
  292. unset($object->oldline);
  293. unset($object->error);
  294. unset($object->errors);
  295. unset($object->errorhidden);
  296. unset($object->ref_previous);
  297. unset($object->ref_next);
  298. unset($object->ref_int);
  299. unset($object->imgWidth);
  300. unset($object->imgHeight);
  301. unset($object->barcode_type_code);
  302. unset($object->barcode_type_label);
  303. unset($object->mode_reglement); // We use mode_reglement_id now
  304. unset($object->cond_reglement); // We use cond_reglement_id now
  305. unset($object->note); // We use note_public or note_private now
  306. unset($object->contact); // We use contact_id now
  307. unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
  308. unset($object->projet); // Should be fk_project
  309. unset($object->project); // Should be fk_project
  310. unset($object->author); // Should be fk_user_author
  311. unset($object->timespent_old_duration);
  312. unset($object->timespent_id);
  313. unset($object->timespent_duration);
  314. unset($object->timespent_date);
  315. unset($object->timespent_datehour);
  316. unset($object->timespent_withhour);
  317. unset($object->timespent_fk_user);
  318. unset($object->timespent_note);
  319. unset($object->fk_delivery_address);
  320. unset($object->modelpdf);
  321. unset($object->sendtoid);
  322. unset($object->name_bis);
  323. unset($object->newref);
  324. unset($object->alreadypaid);
  325. unset($object->openid);
  326. unset($object->statuts);
  327. unset($object->statuts_short);
  328. unset($object->statuts_logo);
  329. unset($object->statuts_long);
  330. unset($object->statutshorts);
  331. unset($object->statutshort);
  332. unset($object->labelStatus);
  333. unset($object->labelStatusShort);
  334. unset($object->stats_propale);
  335. unset($object->stats_commande);
  336. unset($object->stats_contrat);
  337. unset($object->stats_facture);
  338. unset($object->stats_commande_fournisseur);
  339. unset($object->stats_reception);
  340. unset($object->stats_mrptoconsume);
  341. unset($object->stats_mrptoproduce);
  342. unset($object->element);
  343. unset($object->element_for_permission);
  344. unset($object->fk_element);
  345. unset($object->table_element);
  346. unset($object->table_element_line);
  347. unset($object->class_element_line);
  348. unset($object->picto);
  349. unset($object->fieldsforcombobox);
  350. unset($object->regeximgext);
  351. unset($object->skip_update_total);
  352. unset($object->context);
  353. unset($object->next_prev_filter);
  354. unset($object->region);
  355. unset($object->region_code);
  356. unset($object->country);
  357. unset($object->state);
  358. unset($object->state_code);
  359. unset($object->departement);
  360. unset($object->departement_code);
  361. unset($object->libelle_statut);
  362. unset($object->libelle_paiement);
  363. unset($object->prefix_comm);
  364. if (!isset($object->table_element) || $object->table_element != 'ticket') {
  365. unset($object->comments);
  366. }
  367. // Remove the $oldcopy property because it is not supported by the JSON
  368. // encoder. The following error is generated when trying to serialize
  369. // it: "Error encoding/decoding JSON: Type is not supported"
  370. // Note: Event if this property was correctly handled by the JSON
  371. // encoder, it should be ignored because keeping it would let the API
  372. // have a very strange behavior: calling PUT and then GET on the same
  373. // resource would give different results:
  374. // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
  375. // GET /objects/{id} -> returns object with oldcopy empty
  376. unset($object->oldcopy);
  377. // If object has lines, remove $db property
  378. if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
  379. $nboflines = count($object->lines);
  380. for ($i = 0; $i < $nboflines; $i++) {
  381. $this->_cleanObjectDatas($object->lines[$i]);
  382. unset($object->lines[$i]->contact);
  383. unset($object->lines[$i]->contact_id);
  384. unset($object->lines[$i]->country);
  385. unset($object->lines[$i]->country_id);
  386. unset($object->lines[$i]->country_code);
  387. unset($object->lines[$i]->mode_reglement_id);
  388. unset($object->lines[$i]->mode_reglement_code);
  389. unset($object->lines[$i]->mode_reglement);
  390. unset($object->lines[$i]->cond_reglement_id);
  391. unset($object->lines[$i]->cond_reglement_code);
  392. unset($object->lines[$i]->cond_reglement);
  393. unset($object->lines[$i]->fk_delivery_address);
  394. unset($object->lines[$i]->fk_projet);
  395. unset($object->lines[$i]->fk_project);
  396. unset($object->lines[$i]->thirdparty);
  397. unset($object->lines[$i]->user);
  398. unset($object->lines[$i]->model_pdf);
  399. unset($object->lines[$i]->modelpdf);
  400. unset($object->lines[$i]->note_public);
  401. unset($object->lines[$i]->note_private);
  402. unset($object->lines[$i]->fk_incoterms);
  403. unset($object->lines[$i]->label_incoterms);
  404. unset($object->lines[$i]->location_incoterms);
  405. unset($object->lines[$i]->name);
  406. unset($object->lines[$i]->lastname);
  407. unset($object->lines[$i]->firstname);
  408. unset($object->lines[$i]->civility_id);
  409. unset($object->lines[$i]->fk_multicurrency);
  410. unset($object->lines[$i]->multicurrency_code);
  411. unset($object->lines[$i]->shipping_method_id);
  412. }
  413. }
  414. if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
  415. $this->_cleanObjectDatas($object->thirdparty);
  416. }
  417. if (!empty($object->product) && is_object($object->product)) {
  418. $this->_cleanObjectDatas($object->product);
  419. }
  420. return $object;
  421. }
  422. /**
  423. * Function to forge a SQL criteria from a Generic filter string
  424. *
  425. * @param array $matches Array of found string by regex search.
  426. * Each entry is 1 and only 1 criteria.
  427. * Example: "t.ref:like:'SO-%'", "t.date_creation:<:'20160101'", "t.date_creation:<:'2016-01-01 12:30:00'", "t.nature:is:NULL", "t.field2:isnot:NULL"
  428. * @return string Forged criteria. Example: "t.field like 'abc%'"
  429. */
  430. protected static function _forge_criteria_callback($matches)
  431. {
  432. return dolForgeCriteriaCallback($matches);
  433. }
  434. }