api_booking.class.php 50 KB

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