api_booking.class.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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("firstEventStep");
  507. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  508. ApiBbusLog::eventLog("{$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. $params = compact('fk_event', 'reservations');
  520. $postFields = json_encode($params);
  521. $noavailableSpaces = json_decode($this->curlRunner('bookingapi/nolocalemptyspaces', $postFields, 'POST', true))->result;
  522. if ($noavailableSpaces) {
  523. throw new RestException(506, 'No available spaces');
  524. }
  525. $params = compact('sendId', 'fk_event', 'reservations', 'product_id');
  526. $postFields = json_encode($params);
  527. $createdPreOrderOBJ = $this->curlRunner('bookingapi/localcreatedpreorderobj', $postFields, 'POST', true);
  528. }
  529. return $createdPreOrderOBJ;
  530. }
  531. function localcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
  532. {
  533. ApiBbusLog::appLog("{$sendId}: localcreatedpreorderobj");
  534. $apiInvoiceHelper = new ApiInvoiceHelper;
  535. $createdPreOrderOBJ = [];
  536. for ($i = 1; $i <= $reservations; $i++) {
  537. dol_include_once('/comm/action/class/actioncomm.class.php');
  538. dol_include_once('/custom/booking/class/preorder.class.php');
  539. $apiInvoiceHelper->increaseParticipant($fk_event);
  540. $lines = $apiInvoiceHelper->getProductLines($product_id);
  541. foreach ($lines as $line) {
  542. $preOrderObj = new PreOrder($this->db);
  543. $preOrderObj->ref = $this->generateRandomString();
  544. $preOrderObj->fk_event = $fk_event;
  545. $preOrderObj->fk_product = $product_id;
  546. $result = $preOrderObj->create($this->user);
  547. if ($result > 0) {
  548. $createdPreOrderOBJ[] = [
  549. 'id' => $preOrderObj->id,
  550. 'ref' => $preOrderObj->ref,
  551. ];
  552. } else {
  553. ApiBbusLog::appLog("{$sendId}: " . json_encode(['error' => $preOrderObj->errors]));
  554. ApiBbusLog::appLog("{$sendId}: Unsaved event: " . $fk_event);
  555. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  556. }
  557. }
  558. }
  559. ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
  560. return $createdPreOrderOBJ;
  561. }
  562. function createLog($sendId, $fk_event, $reservations, $product_id)
  563. {
  564. /**
  565. * LOG SECTION
  566. */
  567. ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
  568. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  569. ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
  570. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  571. ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  572. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  573. ApiBbusLog::eventLog("{$sendId} " . json_encode([
  574. 'fk_event' => $fk_event,
  575. 'reservations' => $reservations,
  576. 'product_id' => $product_id,
  577. 'sendId' => $sendId,
  578. ]));
  579. }
  580. function generateRandomString($length = 10)
  581. {
  582. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  583. $charactersLength = strlen($characters);
  584. $randomString = '';
  585. for ($i = 0; $i < $length; $i++) {
  586. $randomString .= $characters[rand(0, $charactersLength - 1)];
  587. }
  588. return $randomString;
  589. }
  590. /**
  591. * Save event data in Bookinghistory
  592. *
  593. * Return an array with details
  594. *
  595. * @return array|mixed data without useless information
  596. *
  597. * @param int $fk_event //selected evet from llx_event
  598. * @param int $fk_facture //facture rowid from llx_facture
  599. * @param int $fk_eventproduct //eventproduct rowid from llx_eventwizard_eventproduct
  600. * @param string $ref //ref
  601. *
  602. * @url POST saveeventdata
  603. * @access protected
  604. * @throws RestException 401 Not allowed
  605. * @throws RestException 404 Not found
  606. */
  607. public function saveEventData(int $fk_event, int $fk_facture = null, int $fk_eventproduct = null, string $ref = null )
  608. {
  609. dol_include_once('/custom/booking/class/bookinghistory.class.php');
  610. dol_include_once('/comm/action/class/actioncomm.class.php');
  611. $actionCommObj = new ActionComm($this->db);
  612. $sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
  613. $result = $this->db->query($sql);
  614. if ($this->db->num_rows($result) > 0) {
  615. $row = $this->db->fetch_object($result);
  616. $BookingHistory = new BookingHistory($this->db);
  617. $BookingHistory->fk_event = $fk_event;
  618. $BookingHistory->fk_facture = $fk_facture;
  619. $BookingHistory->fk_event_detail = $row->fk_element;
  620. $BookingHistory->fk_eventproduct = $fk_eventproduct;
  621. $BookingHistory->date_start = strtotime($row->datep);
  622. $BookingHistory->date_end = strtotime($row->datep2);
  623. $BookingHistory->invoice_number = $ref;
  624. $result = $BookingHistory->create($this->user);
  625. if ($result > 0) {
  626. return $BookingHistory->id;
  627. } else {
  628. throw new RestException(401, 'Unsaved');
  629. }
  630. } else {
  631. throw new RestException(401, 'No Event record');
  632. }
  633. }
  634. /**
  635. * Validate and save invoice
  636. *
  637. * Return an array with details
  638. *
  639. * @return array|mixed data without useless information
  640. *
  641. * @param int $type_id Type_id
  642. * @param string $sendId sendID
  643. * @param array $payment Invoice payment
  644. * @param array $preorder preorder
  645. * @param array $invoice Invoice
  646. * @param string $cardPaymentLog Card payment log data
  647. *
  648. * @url POST validateandsaveinvoice
  649. * @access protected
  650. * @throws RestException 401 Not allowed
  651. * @throws RestException 404 Not found
  652. * @throws RestException 506 No available spaces
  653. *
  654. */
  655. public function validateandsaveinvoice(int $type_id, string $sendId, array $payment, array $preorder, array $invoice, string $cardPaymentLog = '')
  656. {
  657. global $db;
  658. $server_host = $this->getServerHost($type_id);
  659. $createdInvoiceArray = $this->localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId, $server_host);
  660. //print_r($createdInvoiceArray);exit;
  661. if ($server_host == 'excelia') {
  662. ApiBbusLog::appLog("validateandsaveinvoice: Excelia");
  663. ApiBbusLog::appLog(json_encode($preorder));
  664. //exit;
  665. foreach ($preorder as $order) {
  666. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$order}";
  667. ApiBbusLog::appLog("{$sql}");
  668. $data = $db->query($sql);
  669. if ($db->num_rows($data) > 0) {
  670. while ($row = $db->fetch_object($data)) {
  671. $bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray[0]['invoice']['id']);
  672. $this->updateBbticket($bookingHistory, $createdInvoiceArray[0]['invoice']);
  673. $this->deletePreorder($preorder);
  674. }
  675. }
  676. }
  677. } else {
  678. foreach ($preorder as $rowid) {
  679. ApiBbusLog::appLog("validateandsaveinvoice: Buziiiiiiii");
  680. $params = compact('rowid');
  681. $postFields = json_encode($params);
  682. $preorderArray = $this->curlRunner('bookingapi/localpreorderarray', $postFields, 'POST', true);
  683. $saveEventdataPostFields = '{"fk_event":"' . (int)$preorderArray->fk_event . '","ref":"' . $createdInvoiceArray[0]['invoice']['ref'] . '","fk_facture":"' . null . '","fk_eventproduct":"' . null . '"}';
  684. $bookingHistory = $this->curlRunner('bookingapi/saveEventData', $saveEventdataPostFields, 'POST', true);
  685. $array['fk_booking_history'] = $bookingHistory;
  686. $array['invoice'] = $createdInvoiceArray[0]['invoice'];
  687. $updateBBticketPostFields = json_encode($array);
  688. $this->curlRunner('bookingapi/curlUpdateBbticket', $updateBBticketPostFields, 'POST', true);
  689. ApiBbusLog::appLog("validateandsaveinvoice: {$postFields}");
  690. $this->curlRunner('bookingapi/curlDeletePreorder', $postFields, 'POST', true);
  691. }
  692. }
  693. ApiBbusLog::appLog("validateandsaveinvoice: END");
  694. return $createdInvoiceArray;
  695. }
  696. public function localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId, $server_host)
  697. {
  698. global $user, $db;
  699. $createdInvoiceData = [];
  700. $apiInvoiceHelper = new ApiInvoiceHelper;
  701. $bbusApi = new BBus();
  702. foreach ($preorder as $rowid) {
  703. $params = compact('rowid');
  704. $postFields = json_encode($params);
  705. if ($server_host == 'excelia') {
  706. ApiBbusLog::appLog("localValidateAndSaveInvoice: Excelia");
  707. $preorderArray = $this->localpreorderarray($rowid);
  708. } else {
  709. $preorderArray = $this->curlRunner('bookingapi/localpreorderarray', $postFields, 'POST', true);
  710. }
  711. $lines = $apiInvoiceHelper->getProductLinesWithoutDiscount($preorderArray->fk_product);
  712. //$lines = $apiInvoiceHelper->createLinesForCrossShopping($preorderArray->fk_product);
  713. $createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '');
  714. $createdInvoiceData[] = $createdInvoiceArray;
  715. }
  716. ApiBbusLog::appLog("Visszaküld");
  717. $asd = json_encode($createdInvoiceData);
  718. ApiBbusLog::appLog("{$asd}");
  719. return $createdInvoiceData;
  720. }
  721. public function localpreorderarray(int $rowid)
  722. {
  723. global $user, $db;
  724. $result = [];
  725. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
  726. $data = $db->query($sql);
  727. if ($db->num_rows($data) > 0) {
  728. while ($row = $db->fetch_object($data)) {
  729. $result = $row;
  730. }
  731. }
  732. return $result;
  733. }
  734. /**
  735. * curllocalpreorderarray
  736. *
  737. * Return an array with details
  738. *
  739. * @return array|mixed data without useless information
  740. *
  741. * @param int $rowid
  742. *
  743. * @url POST curllocalpreorderarray
  744. * @access protected
  745. * @throws RestException 401 Not allowed
  746. * @throws RestException 404 Not found
  747. * @throws RestException 506 No available spaces
  748. *
  749. */
  750. public function curllocalpreorderarray(int $rowid)
  751. {
  752. global $user, $db;
  753. $result = [];
  754. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
  755. $data = $db->query($sql);
  756. if ($db->num_rows($data) > 0) {
  757. while ($row = $db->fetch_object($data)) {
  758. $result = $row;
  759. }
  760. }
  761. return $result;
  762. }
  763. public function updateBbticket($fk_booking_history, $invoice)
  764. {
  765. global $user;
  766. $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE fk_facture = {$invoice['id']}";
  767. //print $sql;exit;
  768. $data = $this->db->query($sql);
  769. if (!empty($this->db->error())) {
  770. ApiBbusLog::appLog("{$this->db->error()}");
  771. throw new RestException(401, "{$this->db->error()}");
  772. }
  773. if ($this->db->num_rows($data) > 0) {
  774. while ($row = $this->db->fetch_object($data)) {
  775. $sql = "UPDATE llx_bbus_bbticket
  776. SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
  777. WHERE rowid = {$row->rowid}";
  778. $this->db->query($sql);
  779. }
  780. } else {
  781. ApiBbusLog::appLog("api_booking: updateBbticket error");
  782. throw new RestException(401, 'api_booking: updateBbticket error');
  783. }
  784. }
  785. /**
  786. * curlupdateBbticket
  787. *
  788. * Return an array with details
  789. *
  790. *
  791. * @param int $fk_booking_history preorder
  792. * @param array $invoice invoice
  793. *
  794. * @url POST curlupdateBbticket
  795. * @access protected
  796. * @throws RestException 401 Not allowed
  797. * @throws RestException 404 Not found
  798. * @throws RestException 506 No available spaces
  799. *
  800. */
  801. public function curlupdateBbticket(int $fk_booking_history, array $invoice)
  802. {
  803. global $user;
  804. $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE invoice_number = '{$invoice['id']}'";
  805. $data = $this->db->query($sql);
  806. if (!empty($this->db->error())) {
  807. ApiBbusLog::appLog("{$this->db->error()}");
  808. throw new RestException(401, "{$this->db->error()}");
  809. }
  810. $data = $this->db->query($sql);
  811. if ($this->db->num_rows($data) > 0) {
  812. while ($row = $this->db->fetch_object($data)) {
  813. $sql = "UPDATE llx_bbus_bbticket
  814. SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
  815. WHERE rowid = {$row->rowid}";
  816. $this->db->query($sql);
  817. }
  818. } else {
  819. ApiBbusLog::appLog("api_booking: updateBbticket error");
  820. throw new RestException(401, 'api_booking: updateBbticket error');
  821. }
  822. }
  823. public function deletePreorder($preorder)
  824. {
  825. foreach ($preorder as $item) {
  826. $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
  827. $this->db->query($sql);
  828. }
  829. }
  830. /**
  831. * curldeletePreorder
  832. *
  833. * Return an array with details
  834. *
  835. *
  836. * @param array $preorder preorder
  837. *
  838. * @url POST curldeletePreorder
  839. * @access protected
  840. * @throws RestException 401 Not allowed
  841. * @throws RestException 404 Not found
  842. * @throws RestException 506 No available spaces
  843. *
  844. */
  845. public function curldeletePreorder($preorder)
  846. {
  847. foreach ($preorder as $item) {
  848. $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
  849. $this->db->query($sql);
  850. }
  851. }
  852. public function eventErasuer()
  853. {
  854. global $user;
  855. $limitDate = date("Y-m-d H:i:s", dol_now() - 1200);
  856. $sql = "SELECT * FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
  857. //print $sql;exit;
  858. $data = $this->db->query($sql);
  859. if ($this->db->num_rows($data) > 0) {
  860. while ($row = $this->db->fetch_object($data)) {
  861. //print_r($row);
  862. $actioncommObj = new ActionComm($this->db);
  863. $resultActionComm = $actioncommObj->fetch($row->fk_event);
  864. $actioncommObj->array_options['options_participants'] = $actioncommObj->array_options['options_participants'] - 1;
  865. $actioncommObj->update($user);
  866. }
  867. //exit;
  868. $sqlDelete = "DELETE FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
  869. $dataDelete = $this->db->query($sqlDelete);
  870. }
  871. }
  872. /**
  873. * Increase Participants
  874. *
  875. * Return an array with details
  876. *
  877. * @return array|mixed data without useless information
  878. *
  879. * @param int $event_id //rowid of evet from llx_event
  880. *
  881. * @url POST increaseparticipant
  882. *
  883. * @throws RestException 401 Not allowed
  884. * @throws RestException 404 Not found
  885. */
  886. public function increaseParticipant(int $event_id)
  887. {
  888. dol_include_once('/comm/action/class/actioncomm.class.php');
  889. global $user;
  890. $actionComObj = new ActionComm($this->db);
  891. $actionComObj->fetch($event_id);
  892. $max_num = (int) $actionComObj->array_options['options_max_num'];
  893. $buffer = (int) $actionComObj->array_options['options_buffer'];
  894. $participants = (int) $actionComObj->array_options['options_participants'];
  895. $increasedParticipants = $participants + 1;
  896. if ($increasedParticipants > ($max_num + $buffer)) {
  897. return 'full';
  898. } elseif (($increasedParticipants > $max_num) && ($increasedParticipants <= ($max_num + $buffer))) {
  899. $actionComObj->array_options['options_participants'] = $increasedParticipants;
  900. $actionComObj->update($user);
  901. return 'Buffer';
  902. } else {
  903. $actionComObj->array_options['options_participants'] = $increasedParticipants;
  904. $actionComObj->update($user);
  905. return 'OK';
  906. }
  907. }
  908. /**
  909. * Reduce Participants
  910. *
  911. * Return an array with details
  912. *
  913. * @return array|mixed data without useless information
  914. *
  915. * @param int $event_id //rowid of evet from llx_event
  916. *
  917. * @url POST reduceparticipant
  918. *
  919. *
  920. * @throws RestException 401 Not allowed
  921. * @throws RestException 404 Not found
  922. */
  923. public function reduceParticipant(int $event_id)
  924. {
  925. global $user;
  926. dol_include_once('/comm/action/class/actioncomm.class.php');
  927. $actionComObj = new ActionComm($this->db);
  928. $actionComObj->fetch($event_id);
  929. $participants = (int) $actionComObj->array_options['options_participants'];
  930. $reducedParticipants = $participants - 1;
  931. $actionComObj->array_options['options_participants'] = $reducedParticipants < 0 ? 0 : $reducedParticipants;
  932. $actionComObj->update($user);
  933. return 'OK';
  934. }
  935. /**
  936. * Create invoice
  937. *
  938. * @param array $invoice Invoice data
  939. * @param array $lines Invoice lines
  940. * @param array $payment Invoice payment
  941. * @param string $eventid Event ID
  942. * @param string $cardPaymentLog Card payment log data
  943. *
  944. * @access protected
  945. * @return array|mixed Data without useless information
  946. *
  947. * @url POST /invoice
  948. */
  949. public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $eventid = '', string $sendId = '')
  950. {
  951. if (empty($sendId)) {
  952. $sendId = substr(md5(rand()), 0, 8);
  953. }
  954. /**
  955. * LOG SECTION
  956. */
  957. ApiBbusLog::appLog("{$sendId} === NEW INVOICE ===");
  958. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  959. ApiBbusLog::appLog("{$sendId} REQUEST: {$sendId}");
  960. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  961. ApiBbusLog::appLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  962. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  963. ApiBbusLog::appLog("{$sendId} " . json_encode([
  964. 'invoice' => $invoice,
  965. 'lines' => $lines,
  966. 'payment' => $payment,
  967. 'eventid' => $eventid,
  968. 'cardPaymentLog' => $cardPaymentLog
  969. ]));
  970. /**
  971. * CHECK RIGHTS
  972. */
  973. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  974. ApiBbusLog::appLog("{$sendId} Insufficient rights");
  975. throw new RestException(401, 'Insufficient rights');
  976. }
  977. $apiInvoiceHelper = new ApiInvoiceHelper;
  978. /**
  979. * handle invoice basic data
  980. */
  981. $invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId);
  982. /**
  983. * handle invoice line(s)
  984. */
  985. $products = [];
  986. //print $eventid;exit;
  987. foreach ($lines as $line) {
  988. $invoiceObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
  989. $this->increaseParticipant((int) $eventid);
  990. $product = $apiInvoiceHelper->loadProductToResult($line);
  991. if (!empty($product)) {
  992. $products[] = $product;
  993. }
  994. }
  995. $invoiceObj->fetch_lines();
  996. foreach ($products as &$row) {
  997. foreach ($invoiceObj->lines as $line) {
  998. if ($line->product_ref == $row['ref']) {
  999. //$row['price'] = $line->total_ttc;
  1000. $row['price'] = $line->multicurrency_total_ttc;
  1001. $row['total_tva'] = $line->total_tva;
  1002. //$row['total_tva'] = $line->multicurrency_total_tva;
  1003. }
  1004. }
  1005. }
  1006. return [
  1007. 'sendId' => $sendId,
  1008. 'invoice' => [
  1009. 'id' => $invoiceObj->id,
  1010. 'ref' => $invoiceObj->ref,
  1011. 'total' => $invoiceObj->multicurrency_total_ttc
  1012. ],
  1013. 'products' => $products,
  1014. ];
  1015. }
  1016. /**
  1017. * Get all free spaces on a selected date
  1018. *
  1019. * Return an array with details
  1020. *
  1021. * @return array|mixed data without useless information
  1022. *
  1023. * @param int type_id
  1024. * @param string date_from
  1025. * @param string date_to
  1026. * @param int product_id
  1027. * @param int participant_number
  1028. *
  1029. * @url POST getavailablespaces
  1030. *
  1031. * @throws RestException 401 Not allowed
  1032. * @throws RestException 404 Not found
  1033. */
  1034. public function getAvailableSpaces(int $type_id, string $date_from, string $date_to, int $product_id, int $participant_number)
  1035. {
  1036. $server_host = $this->getServerHost($type_id);
  1037. if ($server_host == 'excelia') {
  1038. ApiBbusLog::appLog("getAvailableSpaces");
  1039. return $this->localAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
  1040. } else {
  1041. $params = compact('date_from', 'date_to', 'product_id', 'participant_number');
  1042. $postFields = json_encode($params);
  1043. return $this->curlRunner('bookingapi/localavailableplaces', $postFields, 'POST', true);
  1044. }
  1045. }
  1046. /* private function getServerHost($type_id)
  1047. {
  1048. $basicServices = new BasicServices($this->db);
  1049. $resultBS = $basicServices->fetch($type_id);
  1050. return $basicServices->server_host;
  1051. } */
  1052. /**
  1053. * Get all free spaces on a selected date
  1054. *
  1055. * Return an array with details
  1056. *
  1057. * @return array|mixed data without useless information
  1058. *
  1059. * @param string date_from
  1060. * @param string date_to
  1061. * @param int product_id
  1062. * @param int participant_number
  1063. *
  1064. * @url POST localavailableplaces
  1065. *
  1066. * @throws RestException 401 Not allowed
  1067. * @throws RestException 404 Not found
  1068. */
  1069. public function localavailableplaces($date_from, $date_to, $product_id, $participant_number)
  1070. {
  1071. ApiBbusLog::appLog("localAvailablePlaces");
  1072. $array = [];
  1073. $date = new DateTime($date_to);
  1074. $date->modify('+1 day');
  1075. $date_to = $date->format('Y-m-d');
  1076. $sql = "SELECT
  1077. ac.id,
  1078. ac.datep,
  1079. ace.max_num,
  1080. ace.participants,
  1081. ace.buffer
  1082. FROM llx_actioncomm as ac
  1083. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1084. INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
  1085. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
  1086. WHERE ac.code = 'AC_EVENT'
  1087. AND ep.fk_product = {$product_id}
  1088. AND ac.datep > '{$date_from} 00:00:00'
  1089. AND ac.datep2 < '{$date_to} 00:00:00'
  1090. ORDER BY ac.datep ASC";
  1091. $result = $this->db->query($sql);
  1092. while ($row = $this->db->fetch_object($result)) {
  1093. $max_num = $row->max_num;
  1094. $buffer = $row->buffer;
  1095. $participants = $row->participants;
  1096. $date = strtotime($row->datep);
  1097. $element['event_id'] = $row->id;
  1098. //$element['date'] = date("Y-m-d", $date);
  1099. //$element['time'] = date("H:i", $date);
  1100. $element['participants'] = is_null($participants) ? 0 : (int) $participants;
  1101. $element['max_num'] = $max_num;
  1102. $element['buffer'] = $buffer;
  1103. if ($max_num > $participants) {
  1104. if ($max_num + $buffer > $participants + $participant_number) {
  1105. $array[date("Y-m-d", $date)][date("H:i", $date)] = $element;
  1106. }
  1107. }
  1108. }
  1109. return $array;
  1110. }
  1111. private function noLocalEmptySpaces($event_id, $reservations)
  1112. {
  1113. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1114. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1115. WHERE ac.id = {$event_id}";
  1116. $result = $this->db->query($sql);
  1117. if ($this->db->num_rows($result) == 0) {
  1118. return true;
  1119. }
  1120. while ($row = $this->db->fetch_object($result)) {
  1121. if ($row->participants >= $row->max_num) {
  1122. return true;
  1123. }
  1124. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1125. return true;
  1126. }
  1127. }
  1128. return false;
  1129. }
  1130. /**
  1131. * curlnoLocalEmptySpaces
  1132. *
  1133. * Return an array with details
  1134. *
  1135. * @return array|mixed data without useless information
  1136. *
  1137. * @param int $fk_event
  1138. * @param int $reservations
  1139. *
  1140. * @url POST curlnoLocalEmptySpaces
  1141. * @access protected
  1142. * @throws RestException 401 Not allowed
  1143. * @throws RestException 404 Not found
  1144. * @throws RestException 506 No available spaces
  1145. *
  1146. */
  1147. public function curlnoLocalEmptySpaces($fk_event, $reservations)
  1148. {
  1149. ApiBbusLog::appLog("curlnoLocalEmptySpaces");
  1150. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1151. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1152. WHERE ac.id = {$fk_event}";
  1153. $result = $this->db->query($sql);
  1154. if ($this->db->num_rows($result) == 0) {
  1155. return true;
  1156. }
  1157. while ($row = $this->db->fetch_object($result)) {
  1158. if ($row->participants >= $row->max_num) {
  1159. return true;
  1160. }
  1161. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1162. return true;
  1163. }
  1164. }
  1165. return false;
  1166. }
  1167. /**
  1168. * curlcreatedpreorderobj
  1169. *
  1170. * Return an array with details
  1171. *
  1172. * @return array|mixed data without useless information
  1173. *
  1174. * @param string $sendId
  1175. * @param int $fk_event
  1176. * @param int $reservations
  1177. * @param int $product_id
  1178. *
  1179. * @url POST curlcreatedpreorderobj
  1180. * @access protected
  1181. * @throws RestException 401 Not allowed
  1182. * @throws RestException 404 Not found
  1183. * @throws RestException 506 No available spaces
  1184. *
  1185. */
  1186. function curlcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
  1187. {
  1188. ApiBbusLog::appLog("curlcreatedpreorderobj");
  1189. $apiInvoiceHelper = new ApiInvoiceHelper;
  1190. $createdPreOrderOBJ = [];
  1191. for ($i = 1; $i <= $reservations; $i++) {
  1192. dol_include_once('/comm/action/class/actioncomm.class.php');
  1193. dol_include_once('/custom/booking/class/preorder.class.php');
  1194. $apiInvoiceHelper->increaseParticipant($fk_event);
  1195. $lines = $apiInvoiceHelper->getProductLines($product_id);
  1196. foreach ($lines as $line) {
  1197. $preOrderObj = new PreOrder($this->db);
  1198. $preOrderObj->ref = $this->generateRandomString();
  1199. $preOrderObj->fk_event = $fk_event;
  1200. $preOrderObj->fk_product = $product_id;
  1201. $result = $preOrderObj->create($this->user);
  1202. if ($result > 0) {
  1203. $createdPreOrderOBJ[] = [
  1204. 'id' => $preOrderObj->id,
  1205. 'ref' => $preOrderObj->ref,
  1206. ];
  1207. } else {
  1208. ApiBbusLog::appLog(json_encode(['error' => $preOrderObj->errors]));
  1209. ApiBbusLog::appLog("Unsaved event: " . $fk_event);
  1210. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  1211. }
  1212. }
  1213. }
  1214. ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
  1215. return $createdPreOrderOBJ;
  1216. }
  1217. /**
  1218. * Create BBticket record
  1219. *
  1220. * Return an array with details
  1221. *
  1222. * @return array|mixed data without useless information
  1223. *
  1224. * @param string $product_id
  1225. * @param string $datec
  1226. * @param string $facture_id
  1227. *
  1228. * @url POST createbbticket
  1229. * @access protected
  1230. * @throws RestException 401 Not allowed
  1231. * @throws RestException 404 Not found
  1232. * @throws RestException 506 No available spaces
  1233. *
  1234. */
  1235. public function createbbticket(string $product_id, string $datec, string $facture_id)
  1236. {
  1237. global $db, $conf;
  1238. $sql = "SELECT validperiod, occasions FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $product_id;
  1239. $result = $db->query($sql);
  1240. while ($sqlDataResult = $db->fetch_array($result)) {
  1241. $validperiod = $sqlDataResult['validperiod'] ? $sqlDataResult['validperiod'] : 366;
  1242. $occasions = $sqlDataResult['occasions'];
  1243. }
  1244. $ticket = new BbTicket($db);
  1245. $ticket->fk_facture = null;
  1246. $ticket->bundle_id = $product_id;
  1247. $ticket->usable_occasions = $occasions;
  1248. $ticket->usage = '0';
  1249. $ticket->available_at = $this->getAvailableAtDate($datec, $validperiod);
  1250. $ticket->ticket_id = $product_id;
  1251. $ticket->fk_settlements_group_id = $conf->global->CURL_GROUP_ID;
  1252. $ticket->invoice_number = $facture_id;
  1253. if ($ticket->create($this->user) == -1) {
  1254. dol_syslog("Nem sikerult a ticketek mentese");
  1255. }
  1256. return true;
  1257. }
  1258. private function getAvailableAtDate($date, $validperiod)
  1259. {
  1260. $available_at = date('Y-m-d H:i:s', strtotime($date . ' +' . $validperiod . ' days'));
  1261. return $available_at;
  1262. }
  1263. }