apiproductlisthelper.class.php 18 KB

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