apiproductlisthelper.class.php 17 KB

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