apiproductlisthelper.class.php 18 KB

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