api_booking.class.php 45 KB

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