apiproductlisthelper.class.php 18 KB

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