api_booking.class.php.bak 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2023 Deák Ferenc
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use Luracast\Restler\RestException;
  19. // dol_include_once('/booking/class/bookinglog.class.php');
  20. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus.class.php';
  21. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
  22. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiinvoicehelper.class.php';
  23. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiproductlisthelper.class.php';
  24. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  25. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  26. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
  27. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';
  28. /**
  29. * \file booking/class/api_booking.class.php
  30. * \ingroup booking
  31. * \brief File for API management of bookinglog.
  32. */
  33. /**
  34. * API class for booking bookinglog
  35. *
  36. * @class DolibarrApiAccess {@requires user,external}
  37. */
  38. class BookingApi extends DolibarrApi
  39. {
  40. use CurlApi;
  41. /**
  42. * @var BookingLog $bookinglog {@type BookingLog}
  43. */
  44. public $bookinglog;
  45. private User $user;
  46. /**
  47. * Constructor
  48. *
  49. * @url GET /
  50. *
  51. */
  52. public function __construct()
  53. {
  54. global $db, $user;
  55. $this->db = $db;
  56. $this->user = $user;
  57. // $this->bookinglog = new BookingLog($this->db);
  58. }
  59. //P4NR6zhWHage
  60. //!!!types:
  61. /**
  62. * Get types of a bookable events
  63. *
  64. * Return an array with bookable events type list
  65. *
  66. * @return array|mixed data without useless information
  67. *
  68. * @url GET types
  69. *
  70. * @throws RestException 401 Not allowed
  71. * @throws RestException 404 Not found
  72. */
  73. public function types()
  74. {
  75. dol_include_once('/eventwizard/class/eventdetails.class.php');
  76. $EventDetails = new EventDetails($this->db);
  77. return $EventDetails->fields['type']['arrayofkeyval'];
  78. if (!DolibarrApiAccess::$user->rights->booking->types->read) {
  79. throw new RestException(401);
  80. }
  81. // dol_include_once('/booking/class/bookinglog.class.php');
  82. // $result = $this->bookinglog->fetch($id);
  83. // if (!$result) {
  84. // throw new RestException(404, 'BookingLog not found');
  85. // }
  86. // if (!DolibarrApi::_checkAccessToResource('bookinglog', $this->bookinglog->id, 'booking_bookinglog')) {
  87. // throw new RestException(401, 'Access to instance id='.$this->bookinglog->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
  88. // }
  89. // return $this->_cleanObjectDatas($this->bookinglog);
  90. }
  91. /**
  92. * Get bookable events
  93. *
  94. * Return an array with bookable events list
  95. *
  96. * @return array|mixed data without useless information
  97. *
  98. * @param int $onlyBookable
  99. * @param int $withDetails
  100. * @param int $withDates
  101. * @param int $withAviability
  102. * @url GET events
  103. *
  104. * @throws RestException 401 Not allowed
  105. * @throws RestException 404 Not found
  106. */
  107. public function events($onlyBookable = 1, $withDetails = 0, $withDates = 0, $withAviability = 0)
  108. {
  109. global $db, $conf;
  110. // if (!DolibarrApiAccess::$user->rights->booking->events->read) {
  111. // throw new RestException(401);
  112. // }
  113. $obj_ret = [];
  114. // if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
  115. // throw new RestException(401, "Insufficient rights to read events");
  116. // }
  117. $sql = "SELECT DISTINCT ed.rowid as id";
  118. if (!empty($conf->societe->enabled)) {
  119. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  120. // $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
  121. // }
  122. }
  123. $sql .= " ,ed.label ";
  124. $sql .= " ,eld.label as from"; //... ??
  125. $sql .= " ,ela.label as to"; //...
  126. $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as t";
  127. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventdetails ed ON ed.rowid = t.fk_element";
  128. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation eld ON eld.rowid = ed.fk_elventlocation_departure";
  129. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation ela ON ela.rowid = ed.fk_elventlocation_arrival";
  130. $sql .= " WHERE code = 'AC_EVENT' ";
  131. $sql .= " AND t.elementtype = 'eventdetails@eventwizard'";
  132. if ($onlyBookable) {
  133. $sql .= " AND t.datep > CURRENT_TIMESTAMP";
  134. }
  135. $result = $this->db->query($sql);
  136. if ($result) {
  137. $i = 0;
  138. // $num = $this->db->num_rows($result);
  139. // $min = min($num, ($limit <= 0 ? $num : $limit));
  140. while ($event = $this->db->fetch_object($result)) {
  141. if ($withDetails) {
  142. $event->details = $this->details($event->id);
  143. }
  144. if ($withDates) {
  145. //... $withAviability
  146. $event->dates = $this->dates($event->id);
  147. }
  148. $obj_ret[] = $event;
  149. }
  150. } else {
  151. throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
  152. }
  153. if (!count($obj_ret)) {
  154. throw new RestException(404, 'No Agenda Event found');
  155. }
  156. return $obj_ret;
  157. }
  158. /**
  159. * Get event dates
  160. *
  161. * Return an array with event dates list
  162. *
  163. * @return array|mixed data without useless information
  164. *
  165. * @param int $id
  166. * @param int $onlyBookable
  167. * @param string $json
  168. * @url GET dates
  169. *
  170. * @throws RestException 401 Not allowed
  171. * @throws RestException 404 Not found
  172. */
  173. public function dates($id, $onlyBookable = 1, $json = null)
  174. {
  175. global $db, $conf;
  176. // if (!DolibarrApiAccess::$user->rights->booking->events->read) {
  177. // throw new RestException(401);
  178. // }
  179. $obj_ret = [];
  180. // if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
  181. // throw new RestException(401, "Insufficient rights to read events");
  182. // }
  183. $sql = "SELECT t.id ";
  184. if (!empty($conf->societe->enabled)) {
  185. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  186. // $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
  187. // }
  188. }
  189. $sql .= " ,ed.label, t.note ";
  190. $sql .= " ,t.datep as start, t.datep2 as end";
  191. $sql .= " ,eld.label as from"; //... ??
  192. $sql .= " ,ela.label as to"; //...
  193. $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as t";
  194. // if (!empty($conf->societe->enabled)) {
  195. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  196. // $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  197. // }
  198. // }
  199. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventdetails ed ON ed.rowid = t.fk_element";
  200. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation eld ON eld.rowid = ed.fk_elventlocation_departure";
  201. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation ela ON ela.rowid = ed.fk_elventlocation_arrival";
  202. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventoption eo ON el.rowid = ed.fk_element";
  203. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventproduct eo ON el.rowid = ed.fk_element";
  204. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_ eo ON el.rowid = ed.fk_element";
  205. // $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
  206. $sql .= " WHERE code = 'AC_EVENT' ";
  207. $sql .= " AND t.fk_element = " . (int) $this->db->escape($id);
  208. $sql .= " AND t.elementtype = 'eventdetails@eventwizard'";
  209. $sql .= " AND t.datep > CURRENT_TIMESTAMP";
  210. // if (!empty($conf->societe->enabled)) {
  211. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  212. // $sql .= " AND t.fk_soc = sc.fk_soc";
  213. // }
  214. // }
  215. // if ($user_ids) {
  216. // $sql .= " AND t.fk_user_action IN (".$this->db->sanitize($user_ids).")";
  217. // }
  218. // if ($socid > 0) {
  219. // $sql .= " AND t.fk_soc = ".((int) $socid);
  220. // }
  221. // Insert sale filter
  222. // if ($search_sale > 0) {
  223. // $sql .= " AND sc.fk_user = ".((int) $search_sale);
  224. // }
  225. // Add sql filters
  226. // if ($sqlfilters) {
  227. // $errormessage = '';
  228. // if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  229. // throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  230. // }
  231. // $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  232. // $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  233. // }
  234. // $sql .= $this->db->order($sortfield, $sortorder);
  235. // if ($limit) {
  236. // if ($page < 0) {
  237. // $page = 0;
  238. // }
  239. // $offset = $limit * $page;
  240. // $sql .= $this->db->plimit($limit + 1, $offset);
  241. // }
  242. $result = $this->db->query($sql);
  243. if ($result) {
  244. $i = 0;
  245. $num = $this->db->num_rows($result);
  246. // $min = min($num, ($limit <= 0 ? $num : $limit));
  247. while ($i < $num) {
  248. $obj_ret[] = $this->db->fetch_object($result);
  249. $i++;
  250. }
  251. } else {
  252. throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
  253. }
  254. if (!count($obj_ret)) {
  255. throw new RestException(404, 'No Agenda Event found');
  256. }
  257. return $obj_ret;
  258. }
  259. /**
  260. * Post booking (draft)
  261. *
  262. * Return an array with draft bookings list
  263. *
  264. * @return array|mixed data without useless information
  265. *
  266. * @param int $event
  267. * @param array $details
  268. * @url POST set
  269. *
  270. * @access protected
  271. * @throws RestException 401 Not allowed
  272. * @throws RestException 404 Not found
  273. */
  274. public function set($event, $details)
  275. {
  276. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  277. throw new RestException(401);
  278. }
  279. }
  280. /**
  281. * Post booking validation
  282. *
  283. * Return an array with bookings list
  284. *
  285. * @return array|mixed data without useless information
  286. *
  287. * @param int $event
  288. * @param array $drafts
  289. * @url POST validate
  290. *
  291. * @access protected
  292. * @throws RestException 401 Not allowed
  293. * @throws RestException 404 Not found
  294. */
  295. public function validate($event, $drafts)
  296. {
  297. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  298. throw new RestException(401);
  299. }
  300. }
  301. /**
  302. * Get bookings list
  303. *
  304. * Return an array with the user's bookings list
  305. *
  306. * @return array|mixed data without useless information
  307. *
  308. * @url POST bookings
  309. *
  310. * @access protected
  311. * @throws RestException 401 Not allowed
  312. * @throws RestException 404 Not found
  313. */
  314. public function bookings()
  315. {
  316. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  317. throw new RestException(401);
  318. }
  319. }
  320. /**
  321. * Get cron to clean booking draftInvoices
  322. *
  323. * Return an array with cleaned list
  324. *
  325. * @return array|mixed data without useless information
  326. *
  327. * @url GET cron
  328. *
  329. * @access protected
  330. * @throws RestException 401 Not allowed
  331. * @throws RestException 404 Not found
  332. */
  333. public function cron()
  334. {
  335. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  336. throw new RestException(401);
  337. }
  338. }
  339. /**
  340. * Get details of a bookable event
  341. *
  342. * Return an array with details
  343. *
  344. * @return array|mixed data without useless information
  345. *
  346. * @param int $id
  347. * @url GET details
  348. *
  349. * @access protected
  350. * @throws RestException 401 Not allowed
  351. * @throws RestException 404 Not found
  352. */
  353. public function details($id)
  354. {
  355. $details = [
  356. 'tmp' => [],
  357. 'product' => [],
  358. 'min' => 0,
  359. 'id_event' => $id,
  360. // 'variants' => []
  361. ];
  362. $variants = [];
  363. dol_include_once('/eventwizard/class/eventdetails.class.php');
  364. $EventDetails = new EventDetails($this->db);
  365. if ($EventDetails->fetch($id)) {
  366. $sql = "SELECT ep.rowid ,ep.fk_eventdetails, ep.fk_product, ep.type, ep.amount, ep.qty ";
  367. $sql .= " , p.label, p.price "; //price price_ttc price_min price_min_ttc
  368. $sql .= " FROM " . MAIN_DB_PREFIX . "eventwizard_eventproduct ep ";
  369. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product p ON p.rowid = ep.fk_product ";
  370. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination ac ON ac.fk_product_parent = ep.fk_product ";
  371. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventoption eo ON eo.rowid = ep.fk_eventoption ";
  372. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventdetails ed ON ed.rowid = ep.fk_eventdetails ";
  373. $sql .= " WHERE ep.fk_eventdetails = " . (int) $this->db->escape($id);
  374. // return $sql;
  375. $result = $this->db->query($sql);
  376. if ($result) {
  377. $variants_ids = [];
  378. while ($d = $this->db->fetch_object($result)) {
  379. $variants_ids[] = $d->fk_product;
  380. // if(is_null($d->fk_product_child)){}
  381. $d->variants = [];
  382. // $d->minP = (is_null($d->amount))?(float)$d->price:(float)$d->amount;
  383. $details['tmp']['' . $d->fk_product] = $d;
  384. }
  385. $sql2 = "SELECT p.rowid, p.label, p.price ";
  386. $sql2 .= ", ac.fk_product_parent, ac.fk_product_child, ac.variation_price, ac.variation_price_percentage "; // variation_price variation_price_percentage variation_weight variation_ref_ext entity
  387. $sql2 .= "FROM " . MAIN_DB_PREFIX . "product_attribute_combination ac ";
  388. $sql2 .= " LEFT JOIN " . MAIN_DB_PREFIX . "product p ON ac.fk_product_child = p.rowid ";
  389. $sql2 .= " WHERE ac.fk_product_parent IN (" . implode(",", $variants_ids) . ") ";
  390. $result2 = $this->db->query($sql2);
  391. if ($result2) {
  392. while ($v = $this->db->fetch_object($result2)) {
  393. $d = $details['tmp']['' . $v->fk_product_parent];
  394. $d->variants[] = $this->product2out($v);
  395. if (!is_null($d->amount)) { //... - ??? %?
  396. $d->minP = (float) $d->amount;
  397. } elseif (!isset($d->minP)) {
  398. $d->minP = $v->price;
  399. } elseif ($d->minP > $v->price) {
  400. $d->minP = $v->price;
  401. }
  402. $details['tmp']['' . $v->fk_product_parent] = $d;
  403. }
  404. }
  405. foreach ($details['tmp'] as $k => $v) {
  406. $p = $this->product2out($v);
  407. $p["minP"] = (is_null($v->amount)) ? (!isset($d->minP)) ? (float) $v->price : (float) $v->minP : (float) $v->amount;
  408. $p["variants"] = $v->variants;
  409. $details['product'][] = $p;
  410. if ($p["type"] == 1) {
  411. $details['min'] += $p["minP"];
  412. }
  413. }
  414. unset($details['tmp']);
  415. } else {
  416. throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
  417. }
  418. // $EventDetails->getLinesArray();
  419. // print_r($EventDetails->lines);
  420. return $details;
  421. //$variations
  422. // $variations =
  423. }
  424. }
  425. protected function product2out($product)
  426. {
  427. return [
  428. "id" => $product->fk_product,
  429. "type" => $product->type, //1,2,3
  430. "fixed_price" => $product->amount,
  431. "max" => $product->qty,
  432. "label" => $product->label,
  433. "price" => $product->price,
  434. ];
  435. }
  436. /**
  437. * Get all products by type
  438. *
  439. * Return an array with details
  440. *
  441. * @return array|mixed data without useless information
  442. *
  443. * @param int $type_id
  444. * @param string $from_date
  445. * @param string $to_date
  446. *
  447. * @url POST getallavailableproducts
  448. *
  449. * @throws RestException 401 Not allowed
  450. * @throws RestException 404 Not found
  451. */
  452. public function getAllAvailableProducts(int $type_id, string $from_date, string $to_date)
  453. {
  454. $date = new DateTime($to_date);
  455. $date->modify('+1 day');
  456. $to_date = $date->format('Y-m-d');
  457. $TMPArray = [];
  458. $productsArray = [];
  459. $sql = "SELECT
  460. pr.rowid
  461. from llx_actioncomm as ac
  462. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  463. INNER JOIN llx_eventwizard_eventdetails as ed ON ed.rowid = ac.fk_element
  464. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ed.rowid
  465. INNER JOIN llx_product as pr ON pr.rowid = ep.fk_product
  466. where ac.datep > '{$from_date} 00:00:00' AND ac.datep2 < '{$to_date} 00:00:00'
  467. AND ac.code = 'AC_EVENT'
  468. AND ed.type = {$type_id}
  469. AND ace.max_num - COALESCE(ace.participants, 0) > 1
  470. GROUP BY pr.rowid";
  471. $result = $this->db->query($sql);
  472. if ($this->db->num_rows($result) > 0) {
  473. while ($row = $this->db->fetch_object($result)) {
  474. $TMPArray[] = $row->rowid;
  475. }
  476. foreach ($TMPArray as $productItem) {
  477. $ApiProductListHelper = new ApiProductListHelper();
  478. $array = $ApiProductListHelper->list('t.ref', 'ASC', '', '', '', '', "(t.rowid:=:{$productItem})");
  479. $productsArray[] = $array[0];
  480. }
  481. }
  482. return $productsArray;
  483. }
  484. /**
  485. * First step of the eventhandling
  486. *
  487. * Return an array with details
  488. *
  489. * @return array|mixed data without useless information
  490. *
  491. * @param int $type_id //selected evet from llx_event
  492. * @param int $fk_event //selected evet from llx_event
  493. * @param int $reservations //numbers of reservations
  494. * @param int $product_id //Product
  495. * @param string $sendId //ID
  496. *
  497. * @url POST firsteventstep
  498. * @access protected
  499. * @throws RestException 401 Not allowed
  500. * @throws RestException 404 Not found
  501. * @throws RestException 506 No available spaces
  502. *
  503. */
  504. public function firstEventStep(int $type_id, int $fk_event, int $reservations, int $product_id, string $sendId)
  505. {
  506. ApiBbusLog::appLog("{$sendId}: firstEventStep");
  507. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  508. ApiBbusLog::appLog("{$sendId} Insufficient rights");
  509. throw new RestException(401, 'Insufficient rights');
  510. }
  511. $this->createLog($sendId, $fk_event, $reservations, $product_id);
  512. $server_host = $this->getServerHost($type_id);
  513. if ($server_host == 'excelia') {
  514. if ($this->noLocalEmptySpaces($fk_event, $reservations)) {
  515. throw new RestException(506, 'No available spaces');
  516. }
  517. $createdPreOrderOBJ = $this->localcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id);
  518. } else {
  519. ApiBbusLog::appLog("{$sendId}: firstEventStep: Bbus");
  520. $params = compact('fk_event', 'reservations');
  521. $postFields = json_encode($params);
  522. $noavailableSpaces = json_decode($this->curlRunner('bookingapi/curlnoLocalEmptySpaces', $postFields, 'POST', true))->result;
  523. if ($noavailableSpaces) {
  524. ApiBbusLog::appLog("{$sendId}: firstEventStep: No available spaces");
  525. throw new RestException(506, 'No available spaces');
  526. }
  527. $params = compact('sendId', 'fk_event', 'reservations', 'product_id');
  528. $postFields = json_encode($params);
  529. $createdPreOrderOBJ = $this->curlRunner('bookingapi/localcreatedpreorderobj', $postFields, 'POST', true);
  530. }
  531. ApiBbusLog::appLog("{$sendId}: " . json_encode($createdPreOrderOBJ));
  532. return $createdPreOrderOBJ;
  533. }
  534. function localcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
  535. {
  536. ApiBbusLog::appLog("{$sendId}: localcreatedpreorderobj");
  537. $apiInvoiceHelper = new ApiInvoiceHelper;
  538. $createdPreOrderOBJ = [];
  539. for ($i = 1; $i <= $reservations; $i++) {
  540. dol_include_once('/comm/action/class/actioncomm.class.php');
  541. dol_include_once('/custom/booking/class/preorder.class.php');
  542. $apiInvoiceHelper->increaseParticipant($fk_event);
  543. $lines = $apiInvoiceHelper->getProductLines($product_id);
  544. foreach ($lines as $line) {
  545. $preOrderObj = new PreOrder($this->db);
  546. $preOrderObj->ref = $this->generateRandomString();
  547. $preOrderObj->fk_event = $fk_event;
  548. $preOrderObj->fk_product = $product_id;
  549. $result = $preOrderObj->create($this->user);
  550. if ($result > 0) {
  551. $createdPreOrderOBJ[] = [
  552. 'id' => $preOrderObj->id,
  553. 'ref' => $preOrderObj->ref,
  554. ];
  555. } else {
  556. ApiBbusLog::appLog("{$sendId}: " . json_encode(['error' => $preOrderObj->errors]));
  557. ApiBbusLog::appLog("{$sendId}: Unsaved event: " . $fk_event);
  558. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  559. }
  560. }
  561. }
  562. ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
  563. return $createdPreOrderOBJ;
  564. }
  565. function createLog($sendId, $fk_event, $reservations, $product_id)
  566. {
  567. /**
  568. * LOG SECTION
  569. */
  570. ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
  571. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  572. ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
  573. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  574. ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  575. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  576. ApiBbusLog::eventLog("{$sendId} " . json_encode([
  577. 'fk_event' => $fk_event,
  578. 'reservations' => $reservations,
  579. 'product_id' => $product_id,
  580. 'sendId' => $sendId,
  581. ]));
  582. }
  583. function generateRandomString($length = 10)
  584. {
  585. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  586. $charactersLength = strlen($characters);
  587. $randomString = '';
  588. for ($i = 0; $i < $length; $i++) {
  589. $randomString .= $characters[rand(0, $charactersLength - 1)];
  590. }
  591. return $randomString;
  592. }
  593. /**
  594. * Save event data in Bookinghistory
  595. *
  596. * Return an array with details
  597. *
  598. * @return array|mixed data without useless information
  599. *
  600. * @param int $fk_event //selected evet from llx_event
  601. * @param int $fk_facture //facture rowid from llx_facture
  602. * @param int $fk_eventproduct //eventproduct rowid from llx_eventwizard_eventproduct
  603. * @param string $ref //ref
  604. *
  605. * @url POST saveeventdata
  606. * @access protected
  607. * @throws RestException 401 Not allowed
  608. * @throws RestException 404 Not found
  609. */
  610. public function saveEventData(int $fk_event, int $fk_facture = null, int $fk_eventproduct = null, string $ref = null)
  611. {
  612. ApiBbusLog::appLog("saveEventData");
  613. dol_include_once('/custom/booking/class/bookinghistory.class.php');
  614. dol_include_once('/comm/action/class/actioncomm.class.php');
  615. $actionCommObj = new ActionComm($this->db);
  616. $sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
  617. ApiBbusLog::appLog("{$sql}");
  618. $result = $this->db->query($sql);
  619. if ($this->db->num_rows($result) > 0) {
  620. $row = $this->db->fetch_object($result);
  621. $BookingHistory = new BookingHistory($this->db);
  622. $BookingHistory->fk_event = $fk_event;
  623. $BookingHistory->fk_facture = $fk_facture;
  624. $BookingHistory->fk_event_detail = $row->fk_element;
  625. $BookingHistory->fk_eventproduct = $fk_eventproduct;
  626. $BookingHistory->date_start = strtotime($row->datep);
  627. $BookingHistory->date_end = strtotime($row->datep2);
  628. $BookingHistory->invoice_number = $ref;
  629. $result = $BookingHistory->create($this->user);
  630. if ($result > 0) {
  631. ApiBbusLog::appLog("saveEventData: OK {$BookingHistory->id}");
  632. return $BookingHistory->id;
  633. } else {
  634. foreach ($BookingHistory->errors as $error) {
  635. ApiBbusLog::appLog("saveEventData: {$error}");
  636. }
  637. ApiBbusLog::appLog("saveEventData: ERROR");
  638. throw new RestException(401, 'Unsaved');
  639. }
  640. } else {
  641. throw new RestException(401, 'No Event record');
  642. }
  643. }
  644. /**
  645. * Validate and save invoice
  646. *
  647. * Return an array with details
  648. *
  649. * @return array|mixed data without useless information
  650. *
  651. * @param int $type_id Type_id
  652. * @param string $sendId sendID
  653. * @param array $payment Invoice payment
  654. * @param array $preorder preorder
  655. * @param array $invoice Invoice
  656. * @param string $cardPaymentLog Card payment log data
  657. *
  658. * @url POST validateandsaveinvoice
  659. * @access protected
  660. * @throws RestException 401 Not allowed
  661. * @throws RestException 404 Not found
  662. * @throws RestException 506 No available spaces
  663. *
  664. */
  665. public function validateandsaveinvoice(int $type_id, string $sendId, array $payment, array $preorder, array $invoice, string $cardPaymentLog = '')
  666. {
  667. ApiBbusLog::appLog("validateandsaveinvoice");
  668. global $db;
  669. $server_host = $this->getServerHost($type_id);
  670. $createdInvoiceArray = $this->localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId, $server_host);
  671. if ($server_host == 'excelia') {
  672. ApiBbusLog::appLog("validateandsaveinvoice: Excelia");
  673. ApiBbusLog::appLog(json_encode($preorder));
  674. foreach ($preorder as $order) {
  675. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$order}";
  676. ApiBbusLog::appLog("{$sql}");
  677. $data = $db->query($sql);
  678. if ($db->num_rows($data) > 0) {
  679. while ($row = $db->fetch_object($data)) {
  680. ApiBbusLog::appLog("while");
  681. $bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray[0]['invoice']['id']);
  682. $this->updateBbticket($bookingHistory, $createdInvoiceArray[0]['invoice']);
  683. $this->deletePreorder($preorder);
  684. }
  685. }
  686. }
  687. } else {
  688. ApiBbusLog::appLog("validateandsaveinvoice: bbus");
  689. foreach ($preorder as $rowid) {
  690. $params = compact('rowid');
  691. $postFields = json_encode($params);
  692. $preorderArray = $this->curlRunner('bookingapi/localpreorderarray', $postFields, 'POST', true);
  693. $saveEventdataPostFields = '{"fk_event":"' . (int)$preorderArray->fk_event . '","ref":"' . $createdInvoiceArray[0]['invoice']['ref'] . '","fk_facture":"' . null . '","fk_eventproduct":"' . null . '"}';
  694. $bookingHistory = $this->curlRunner('bookingapi/saveEventData', $saveEventdataPostFields, 'POST', true);
  695. $array['fk_booking_history'] = $bookingHistory;
  696. $array['invoice'] = $createdInvoiceArray[0]['invoice'];
  697. $updateBBticketPostFields = json_encode($array);
  698. $this->curlRunner('bookingapi/curlUpdateBbticket', $updateBBticketPostFields, 'POST', true);
  699. ApiBbusLog::appLog("validateandsaveinvoice: {$postFields}");
  700. $this->curlRunner('bookingapi/curlDeletePreorder', $postFields, 'POST', true);
  701. }
  702. }
  703. ApiBbusLog::appLog("validateandsaveinvoice: END");
  704. return $createdInvoiceArray;
  705. }
  706. public function localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId, $server_host)
  707. {
  708. ApiBbusLog::eventLog("localValidateAndSaveInvoice");
  709. global $user, $db;
  710. $server_host_curl = false;
  711. $createdInvoiceData = [];
  712. $apiInvoiceHelper = new ApiInvoiceHelper;
  713. $bbusApi = new BBus();
  714. foreach ($preorder as $rowid) {
  715. $params = compact('rowid');
  716. $postFields = json_encode($params);
  717. if ($server_host == 'excelia') {
  718. ApiBbusLog::appLog("localValidateAndSaveInvoice: Excelia");
  719. $preorderArray = $this->localpreorderarray($rowid);
  720. } else {
  721. ApiBbusLog::appLog("localValidateAndSaveInvoice: bbus");
  722. $server_host_curl = true;
  723. $preorderArray = $this->curlRunner('bookingapi/localpreorderarray', $postFields, 'POST', true);
  724. }
  725. $lines = $apiInvoiceHelper->getProductLinesWithoutDiscount($preorderArray->fk_product);
  726. //$lines = $apiInvoiceHelper->createLinesForCrossShopping($preorderArray->fk_product);
  727. $createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '', $server_host_curl);
  728. $createdInvoiceData[] = $createdInvoiceArray;
  729. }
  730. ApiBbusLog::appLog("Visszaküld");
  731. $asd = json_encode($createdInvoiceData);
  732. ApiBbusLog::appLog("{$asd}");
  733. return $createdInvoiceData;
  734. }
  735. public function localpreorderarray(int $rowid)
  736. {
  737. global $user, $db;
  738. $result = [];
  739. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
  740. $data = $db->query($sql);
  741. if ($db->num_rows($data) > 0) {
  742. while ($row = $db->fetch_object($data)) {
  743. $result = $row;
  744. }
  745. }
  746. return $result;
  747. }
  748. /**
  749. * curllocalpreorderarray
  750. *
  751. * Return an array with details
  752. *
  753. * @return array|mixed data without useless information
  754. *
  755. * @param int $rowid
  756. *
  757. * @url POST curllocalpreorderarray
  758. * @access protected
  759. * @throws RestException 401 Not allowed
  760. * @throws RestException 404 Not found
  761. * @throws RestException 506 No available spaces
  762. *
  763. */
  764. public function curllocalpreorderarray(int $rowid)
  765. {
  766. global $user, $db;
  767. $result = [];
  768. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
  769. $data = $db->query($sql);
  770. if ($db->num_rows($data) > 0) {
  771. while ($row = $db->fetch_object($data)) {
  772. $result = $row;
  773. }
  774. }
  775. return $result;
  776. }
  777. public function updateBbticket($invoice, $fk_booking_history = null)
  778. {
  779. ApiBbusLog::appLog("updateBbticket_________START");
  780. global $user;
  781. $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE fk_facture = {$invoice['id']}";
  782. $data = $this->db->query($sql);
  783. if (!empty($this->db->error())) {
  784. ApiBbusLog::appLog("{$this->db->error()}");
  785. throw new RestException(401, "{$this->db->error()}");
  786. }
  787. if ($this->db->num_rows($data) > 0) {
  788. while ($row = $this->db->fetch_object($data)) {
  789. $sql = "UPDATE llx_bbus_bbticket
  790. SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
  791. WHERE rowid = {$row->rowid}";
  792. ApiBbusLog::appLog("{$sql}");
  793. $this->db->query($sql);
  794. }
  795. } else {
  796. ApiBbusLog::appLog("{$this->db->error()}");
  797. ApiBbusLog::appLog("api_booking (Excelia): updateBbticket error");
  798. throw new RestException(401, 'api_booking: updateBbticket error');
  799. }
  800. }
  801. /**
  802. * curlupdateBbticket
  803. *
  804. * Return an array with details
  805. *
  806. *
  807. * @param array $invoice invoice
  808. *
  809. * @url POST curlupdateBbticket
  810. * @access protected
  811. * @throws RestException 401 Not allowed
  812. * @throws RestException 404 Not found
  813. * @throws RestException 506 No available spaces
  814. *
  815. */
  816. public function curlupdateBbticket(array $invoice, string $fk_booking_history = null)
  817. {
  818. ApiBbusLog::appLog("curlupdateBbticket______START");
  819. global $user;
  820. $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE invoice_number = '{$invoice['id']}'";
  821. $data = $this->db->query($sql);
  822. if (!empty($this->db->error())) {
  823. ApiBbusLog::appLog("{$this->db->error()}");
  824. throw new RestException(401, "{$this->db->error()}");
  825. }
  826. $data = $this->db->query($sql);
  827. if ($this->db->num_rows($data) > 0) {
  828. while ($row = $this->db->fetch_object($data)) {
  829. $booking_history_id = is_null($fk_booking_history) ? 'booking_history_id = null,' : '';
  830. $sql = "UPDATE llx_bbus_bbticket
  831. SET {$booking_history_id} invoice_number = '{$invoice['ref']}'
  832. WHERE rowid = {$row->rowid}";
  833. ApiBbusLog::appLog("{$sql}");
  834. $this->db->query($sql);
  835. }
  836. } else {
  837. ApiBbusLog::appLog("api_booking: curlupdateBbticket error");
  838. ApiBbusLog::appLog("{$this->db->error()}");
  839. throw new RestException(401, 'api_booking: curlupdateBbticket error');
  840. }
  841. }
  842. public function deletePreorder($preorder)
  843. {
  844. foreach ($preorder as $item) {
  845. $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
  846. $this->db->query($sql);
  847. }
  848. }
  849. /**
  850. * curldeletePreorder
  851. *
  852. * Return an array with details
  853. *
  854. *
  855. * @param array $preorder preorder
  856. *
  857. * @url POST curldeletePreorder
  858. * @access protected
  859. * @throws RestException 401 Not allowed
  860. * @throws RestException 404 Not found
  861. * @throws RestException 506 No available spaces
  862. *
  863. */
  864. public function curldeletePreorder($preorder)
  865. {
  866. foreach ($preorder as $item) {
  867. $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
  868. $this->db->query($sql);
  869. }
  870. }
  871. public function eventErasuer()
  872. {
  873. global $user;
  874. $limitDate = date("Y-m-d H:i:s", dol_now() - 1200);
  875. $sql = "SELECT * FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
  876. //print $sql;exit;
  877. $data = $this->db->query($sql);
  878. if ($this->db->num_rows($data) > 0) {
  879. while ($row = $this->db->fetch_object($data)) {
  880. //print_r($row);
  881. $actioncommObj = new ActionComm($this->db);
  882. $resultActionComm = $actioncommObj->fetch($row->fk_event);
  883. $actioncommObj->array_options['options_participants'] = $actioncommObj->array_options['options_participants'] - 1;
  884. $actioncommObj->update($user);
  885. }
  886. //exit;
  887. $sqlDelete = "DELETE FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
  888. $dataDelete = $this->db->query($sqlDelete);
  889. }
  890. }
  891. /**
  892. * Increase Participants
  893. *
  894. * Return an array with details
  895. *
  896. * @return array|mixed data without useless information
  897. *
  898. * @param int $event_id //rowid of evet from llx_event
  899. *
  900. * @url POST increaseparticipant
  901. *
  902. * @throws RestException 401 Not allowed
  903. * @throws RestException 404 Not found
  904. */
  905. public function increaseParticipant(int $event_id)
  906. {
  907. dol_include_once('/comm/action/class/actioncomm.class.php');
  908. global $user;
  909. $actionComObj = new ActionComm($this->db);
  910. $actionComObj->fetch($event_id);
  911. $max_num = (int) $actionComObj->array_options['options_max_num'];
  912. $buffer = (int) $actionComObj->array_options['options_buffer'];
  913. $participants = (int) $actionComObj->array_options['options_participants'];
  914. $increasedParticipants = $participants + 1;
  915. if ($increasedParticipants > ($max_num + $buffer)) {
  916. return 'full';
  917. } elseif (($increasedParticipants > $max_num) && ($increasedParticipants <= ($max_num + $buffer))) {
  918. $actionComObj->array_options['options_participants'] = $increasedParticipants;
  919. $actionComObj->update($user);
  920. return 'Buffer';
  921. } else {
  922. $actionComObj->array_options['options_participants'] = $increasedParticipants;
  923. $actionComObj->update($user);
  924. return 'OK';
  925. }
  926. }
  927. /**
  928. * Reduce Participants
  929. *
  930. * Return an array with details
  931. *
  932. * @return array|mixed data without useless information
  933. *
  934. * @param int $event_id //rowid of evet from llx_event
  935. *
  936. * @url POST reduceparticipant
  937. *
  938. *
  939. * @throws RestException 401 Not allowed
  940. * @throws RestException 404 Not found
  941. */
  942. public function reduceParticipant(int $event_id)
  943. {
  944. global $user;
  945. dol_include_once('/comm/action/class/actioncomm.class.php');
  946. $actionComObj = new ActionComm($this->db);
  947. $actionComObj->fetch($event_id);
  948. $participants = (int) $actionComObj->array_options['options_participants'];
  949. $reducedParticipants = $participants - 1;
  950. $actionComObj->array_options['options_participants'] = $reducedParticipants < 0 ? 0 : $reducedParticipants;
  951. $actionComObj->update($user);
  952. return 'OK';
  953. }
  954. /**
  955. * Create invoice
  956. *
  957. * @param array $invoice Invoice data
  958. * @param array $lines Invoice lines
  959. * @param array $payment Invoice payment
  960. * @param string $eventid Event ID
  961. * @param string $cardPaymentLog Card payment log data
  962. *
  963. * @access protected
  964. * @return array|mixed Data without useless information
  965. *
  966. * @url POST /invoice
  967. */
  968. public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $eventid = '', string $sendId = '')
  969. {
  970. if (empty($sendId)) {
  971. $sendId = substr(md5(rand()), 0, 8);
  972. }
  973. /**
  974. * LOG SECTION
  975. */
  976. ApiBbusLog::appLog("{$sendId} === NEW INVOICE ===");
  977. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  978. ApiBbusLog::appLog("{$sendId} REQUEST: {$sendId}");
  979. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  980. ApiBbusLog::appLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  981. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  982. ApiBbusLog::appLog("{$sendId} " . json_encode([
  983. 'invoice' => $invoice,
  984. 'lines' => $lines,
  985. 'payment' => $payment,
  986. 'eventid' => $eventid,
  987. 'cardPaymentLog' => $cardPaymentLog
  988. ]));
  989. /**
  990. * CHECK RIGHTS
  991. */
  992. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  993. ApiBbusLog::appLog("{$sendId} Insufficient rights");
  994. throw new RestException(401, 'Insufficient rights');
  995. }
  996. $apiInvoiceHelper = new ApiInvoiceHelper;
  997. /**
  998. * handle invoice basic data
  999. */
  1000. $invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId);
  1001. /**
  1002. * handle invoice line(s)
  1003. */
  1004. $products = [];
  1005. //print $eventid;exit;
  1006. foreach ($lines as $line) {
  1007. $invoiceObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
  1008. $this->increaseParticipant((int) $eventid);
  1009. $product = $apiInvoiceHelper->loadProductToResult($line);
  1010. if (!empty($product)) {
  1011. $products[] = $product;
  1012. }
  1013. }
  1014. $invoiceObj->fetch_lines();
  1015. foreach ($products as &$row) {
  1016. foreach ($invoiceObj->lines as $line) {
  1017. if ($line->product_ref == $row['ref']) {
  1018. //$row['price'] = $line->total_ttc;
  1019. $row['price'] = $line->multicurrency_total_ttc;
  1020. $row['total_tva'] = $line->total_tva;
  1021. //$row['total_tva'] = $line->multicurrency_total_tva;
  1022. }
  1023. }
  1024. }
  1025. return [
  1026. 'sendId' => $sendId,
  1027. 'invoice' => [
  1028. 'id' => $invoiceObj->id,
  1029. 'ref' => $invoiceObj->ref,
  1030. 'total' => $invoiceObj->multicurrency_total_ttc
  1031. ],
  1032. 'products' => $products,
  1033. ];
  1034. }
  1035. /**
  1036. * Get all free spaces on a selected date
  1037. *
  1038. * Return an array with details
  1039. *
  1040. * @return array|mixed data without useless information
  1041. *
  1042. * @param int type_id
  1043. * @param string date_from
  1044. * @param string date_to
  1045. * @param int product_id
  1046. * @param int participant_number
  1047. *
  1048. * @url POST getavailablespaces
  1049. *
  1050. * @throws RestException 401 Not allowed
  1051. * @throws RestException 404 Not found
  1052. */
  1053. public function getAvailableSpaces(int $type_id, string $date_from, string $date_to, int $product_id, int $participant_number)
  1054. {
  1055. $server_host = $this->getServerHost($type_id);
  1056. if ($server_host == 'excelia') {
  1057. ApiBbusLog::appLog("getAvailableSpaces: bbus");
  1058. return $this->localAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
  1059. } else {
  1060. $params = compact('date_from', 'date_to', 'product_id', 'participant_number');
  1061. $postFields = json_encode($params);
  1062. return $this->curlRunner('bookingapi/localavailableplaces', $postFields, 'POST', true);
  1063. }
  1064. }
  1065. /* private function getServerHost($type_id)
  1066. {
  1067. $basicServices = new BasicServices($this->db);
  1068. $resultBS = $basicServices->fetch($type_id);
  1069. return $basicServices->server_host;
  1070. } */
  1071. /**
  1072. * Get all free spaces on a selected date
  1073. *
  1074. * Return an array with details
  1075. *
  1076. * @return array|mixed data without useless information
  1077. *
  1078. * @param string date_from
  1079. * @param string date_to
  1080. * @param int product_id
  1081. * @param int participant_number
  1082. *
  1083. * @url POST localavailableplaces
  1084. *
  1085. * @throws RestException 401 Not allowed
  1086. * @throws RestException 404 Not found
  1087. */
  1088. public function localavailableplaces($date_from, $date_to, $product_id, $participant_number)
  1089. {
  1090. ApiBbusLog::appLog("localAvailablePlaces");
  1091. $array = [];
  1092. $date = new DateTime($date_to);
  1093. $date->modify('+1 day');
  1094. $date_to = $date->format('Y-m-d');
  1095. $sql = "SELECT
  1096. ac.id,
  1097. ac.datep,
  1098. ace.max_num,
  1099. ace.participants,
  1100. ace.buffer
  1101. FROM llx_actioncomm as ac
  1102. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1103. INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
  1104. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
  1105. WHERE ac.code = 'AC_EVENT'
  1106. AND ep.fk_product = {$product_id}
  1107. AND ac.datep > '{$date_from} 00:00:00'
  1108. AND ac.datep2 < '{$date_to} 00:00:00'
  1109. ORDER BY ac.datep ASC";
  1110. $result = $this->db->query($sql);
  1111. while ($row = $this->db->fetch_object($result)) {
  1112. $max_num = $row->max_num;
  1113. $buffer = $row->buffer;
  1114. $participants = $row->participants;
  1115. $date = strtotime($row->datep);
  1116. $element['event_id'] = $row->id;
  1117. //$element['date'] = date("Y-m-d", $date);
  1118. //$element['time'] = date("H:i", $date);
  1119. $element['participants'] = is_null($participants) ? 0 : (int) $participants;
  1120. $element['max_num'] = $max_num;
  1121. $element['buffer'] = $buffer;
  1122. if ($max_num > $participants) {
  1123. if ($max_num + $buffer > $participants + $participant_number) {
  1124. $array[date("Y-m-d", $date)][date("H:i", $date)] = $element;
  1125. }
  1126. }
  1127. }
  1128. return $array;
  1129. }
  1130. private function noLocalEmptySpaces($event_id, $reservations)
  1131. {
  1132. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1133. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1134. WHERE ac.id = {$event_id}";
  1135. $result = $this->db->query($sql);
  1136. if ($this->db->num_rows($result) == 0) {
  1137. return true;
  1138. }
  1139. while ($row = $this->db->fetch_object($result)) {
  1140. if ($row->participants >= $row->max_num) {
  1141. return true;
  1142. }
  1143. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1144. return true;
  1145. }
  1146. }
  1147. return false;
  1148. }
  1149. /**
  1150. * curlnoLocalEmptySpaces
  1151. *
  1152. * Return an array with details
  1153. *
  1154. * @return array|mixed data without useless information
  1155. *
  1156. * @param int $fk_event
  1157. * @param int $reservations
  1158. *
  1159. * @url POST curlnoLocalEmptySpaces
  1160. * @access protected
  1161. * @throws RestException 401 Not allowed
  1162. * @throws RestException 404 Not found
  1163. * @throws RestException 506 No available spaces
  1164. *
  1165. */
  1166. public function curlnoLocalEmptySpaces($fk_event, $reservations)
  1167. {
  1168. ApiBbusLog::appLog("curlnoLocalEmptySpaces");
  1169. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1170. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1171. WHERE ac.id = {$fk_event}";
  1172. $result = $this->db->query($sql);
  1173. if ($this->db->num_rows($result) == 0) {
  1174. return true;
  1175. }
  1176. while ($row = $this->db->fetch_object($result)) {
  1177. if ($row->participants >= $row->max_num) {
  1178. return true;
  1179. }
  1180. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1181. return true;
  1182. }
  1183. }
  1184. return false;
  1185. }
  1186. /**
  1187. * curlcreatedpreorderobj
  1188. *
  1189. * Return an array with details
  1190. *
  1191. * @return array|mixed data without useless information
  1192. *
  1193. * @param string $sendId
  1194. * @param int $fk_event
  1195. * @param int $reservations
  1196. * @param int $product_id
  1197. *
  1198. * @url POST curlcreatedpreorderobj
  1199. * @access protected
  1200. * @throws RestException 401 Not allowed
  1201. * @throws RestException 404 Not found
  1202. * @throws RestException 506 No available spaces
  1203. *
  1204. */
  1205. function curlcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
  1206. {
  1207. ApiBbusLog::appLog("curlcreatedpreorderobj");
  1208. $apiInvoiceHelper = new ApiInvoiceHelper;
  1209. $createdPreOrderOBJ = [];
  1210. for ($i = 1; $i <= $reservations; $i++) {
  1211. dol_include_once('/comm/action/class/actioncomm.class.php');
  1212. dol_include_once('/custom/booking/class/preorder.class.php');
  1213. $apiInvoiceHelper->increaseParticipant($fk_event);
  1214. $lines = $apiInvoiceHelper->getProductLines($product_id);
  1215. foreach ($lines as $line) {
  1216. $preOrderObj = new PreOrder($this->db);
  1217. $preOrderObj->ref = $this->generateRandomString();
  1218. $preOrderObj->fk_event = $fk_event;
  1219. $preOrderObj->fk_product = $product_id;
  1220. $result = $preOrderObj->create($this->user);
  1221. if ($result > 0) {
  1222. $createdPreOrderOBJ[] = [
  1223. 'id' => $preOrderObj->id,
  1224. 'ref' => $preOrderObj->ref,
  1225. ];
  1226. } else {
  1227. ApiBbusLog::appLog(json_encode(['error' => $preOrderObj->errors]));
  1228. ApiBbusLog::appLog("Unsaved event: " . $fk_event);
  1229. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  1230. }
  1231. }
  1232. }
  1233. ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
  1234. return $createdPreOrderOBJ;
  1235. }
  1236. /**
  1237. * Create BBticket record
  1238. *
  1239. * Return an array with details
  1240. *
  1241. * @return array|mixed data without useless information
  1242. *
  1243. * @param string $product_id
  1244. * @param string $datec
  1245. * @param string $facture_id
  1246. *
  1247. * @url POST createbbticket
  1248. * @access protected
  1249. * @throws RestException 401 Not allowed
  1250. * @throws RestException 404 Not found
  1251. * @throws RestException 506 No available spaces
  1252. *
  1253. */
  1254. public function createbbticket(string $product_id, string $datec, string $facture_id)
  1255. {
  1256. global $db, $conf;
  1257. $sql = "SELECT validperiod, occasions FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $product_id;
  1258. $result = $db->query($sql);
  1259. while ($sqlDataResult = $db->fetch_array($result)) {
  1260. $validperiod = $sqlDataResult['validperiod'] ? $sqlDataResult['validperiod'] : 366;
  1261. $occasions = $sqlDataResult['occasions'];
  1262. }
  1263. $ticket = new BbTicket($db);
  1264. $ticket->fk_facture = null;
  1265. $ticket->bundle_id = $product_id;
  1266. $ticket->usable_occasions = $occasions;
  1267. $ticket->usage = '0';
  1268. $ticket->available_at = $this->getAvailableAtDate($datec, $validperiod);
  1269. $ticket->ticket_id = $product_id;
  1270. $ticket->fk_settlements_group_id = $conf->global->CURL_GROUP_ID;
  1271. $ticket->invoice_number = $facture_id;
  1272. if ($ticket->create($this->user) == -1) {
  1273. dol_syslog("Nem sikerult a ticketek mentese");
  1274. }
  1275. return true;
  1276. }
  1277. private function getAvailableAtDate($date, $validperiod)
  1278. {
  1279. $available_at = date('Y-m-d H:i:s', strtotime($date . ' +' . $validperiod . ' days'));
  1280. return $available_at;
  1281. }
  1282. }