api_booking.class.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  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;
  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. if ($this->db->num_rows($data) > 0) {
  820. while ($row = $this->db->fetch_object($data)) {
  821. $sql = "UPDATE llx_bbus_bbticket
  822. SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
  823. WHERE rowid = {$row->rowid}";
  824. ApiBbusLog::appLog("{$sql}");
  825. $this->db->query($sql);
  826. }
  827. } else {
  828. ApiBbusLog::appLog("{$this->db->error()}");
  829. ApiBbusLog::appLog("api_booking (Excelia): updateBbticket error");
  830. throw new RestException(401, 'api_booking: 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. $result = $this->db->query($sql);
  1146. while ($row = $this->db->fetch_object($result)) {
  1147. $max_num = $row->max_num;
  1148. $buffer = $row->buffer;
  1149. $participants = $row->participants;
  1150. $date = strtotime($row->datep);
  1151. $element['event_id'] = $row->id;
  1152. //$element['date'] = date("Y-m-d", $date);
  1153. //$element['time'] = date("H:i", $date);
  1154. $element['participants'] = is_null($participants) ? 0 : (int) $participants;
  1155. $element['max_num'] = $max_num;
  1156. $element['buffer'] = $buffer;
  1157. if ($max_num > $participants) {
  1158. if ($max_num + $buffer > $participants + $participant_number) {
  1159. $array[date("Y-m-d", $date)][date("H:i", $date)] = $element;
  1160. }
  1161. }
  1162. }
  1163. return $array;
  1164. }
  1165. /**
  1166. * localCheckAvailablePlaces
  1167. * *
  1168. * @return array|mixed data without useless information
  1169. *
  1170. * @param int product_id
  1171. *
  1172. * @url POST localCheckAvailablePlaces
  1173. *
  1174. * @throws RestException 401 Not allowed
  1175. * @throws RestException 404 Not found
  1176. */
  1177. public function localCheckAvailablePlaces($product_id)
  1178. {
  1179. $date_from = $this->getCutOffTimeDate($product_id);
  1180. $sql = "SELECT
  1181. ac.id,
  1182. ac.datep,
  1183. ace.max_num,
  1184. ace.participants,
  1185. ace.buffer
  1186. FROM llx_actioncomm as ac
  1187. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1188. INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
  1189. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
  1190. WHERE ac.code = 'AC_EVENT'
  1191. AND ep.fk_product = {$product_id}
  1192. AND ac.datep > '{$date_from}'
  1193. ORDER BY ac.datep ASC";
  1194. $result = $this->db->query($sql);
  1195. return $this->db->num_rows($result) > 0;
  1196. }
  1197. private function getCutOffTimeDate($product_id)
  1198. {
  1199. $date = date("Y-m-d H:i:s");
  1200. ApiBbusLog::appLog("{$date}");
  1201. $sql = "SELECT cut_off_time_app FROM llx_product_extrafields WHERE fk_object = {$product_id}";
  1202. if ($result = $this->db->query($sql)) {
  1203. if ($this->db->num_rows($result) > 0) {
  1204. while ($row = $this->db->fetch_object($result)) {
  1205. $cutOffTime = $row->cut_off_time_app;
  1206. }
  1207. $dateTimestamp = strtotime($date);
  1208. $date = date("Y-m-d H:i:s", $dateTimestamp + $cutOffTime * 60);
  1209. }
  1210. }
  1211. ApiBbusLog::appLog("{$date}");
  1212. return $date;
  1213. }
  1214. private function noLocalEmptySpaces($event_id, $reservations)
  1215. {
  1216. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1217. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1218. WHERE ac.id = {$event_id}";
  1219. $result = $this->db->query($sql);
  1220. if ($this->db->num_rows($result) == 0) {
  1221. return true;
  1222. }
  1223. while ($row = $this->db->fetch_object($result)) {
  1224. if ($row->participants >= $row->max_num) {
  1225. return true;
  1226. }
  1227. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1228. return true;
  1229. }
  1230. }
  1231. return false;
  1232. }
  1233. /**
  1234. * curlnoLocalEmptySpaces
  1235. *
  1236. * Return an array with details
  1237. *
  1238. * @return array|mixed data without useless information
  1239. *
  1240. * @param int $fk_event
  1241. * @param int $reservations
  1242. *
  1243. * @url POST curlnoLocalEmptySpaces
  1244. * @access protected
  1245. * @throws RestException 401 Not allowed
  1246. * @throws RestException 404 Not found
  1247. * @throws RestException 506 No available spaces
  1248. *
  1249. */
  1250. public function curlnoLocalEmptySpaces($fk_event, $reservations)
  1251. {
  1252. ApiBbusLog::appLog("curlnoLocalEmptySpaces");
  1253. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1254. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1255. WHERE ac.id = {$fk_event}";
  1256. $result = $this->db->query($sql);
  1257. if ($this->db->num_rows($result) == 0) {
  1258. return true;
  1259. }
  1260. while ($row = $this->db->fetch_object($result)) {
  1261. if ($row->participants >= $row->max_num) {
  1262. return true;
  1263. }
  1264. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1265. return true;
  1266. }
  1267. }
  1268. return false;
  1269. }
  1270. /**
  1271. * curlcreatedpreorderobj
  1272. *
  1273. * Return an array with details
  1274. *
  1275. * @return array|mixed data without useless information
  1276. *
  1277. * @param string $sendId
  1278. * @param int $fk_event
  1279. * @param int $reservations
  1280. * @param int $product_id
  1281. *
  1282. * @url POST curlcreatedpreorderobj
  1283. * @access protected
  1284. * @throws RestException 401 Not allowed
  1285. * @throws RestException 404 Not found
  1286. * @throws RestException 506 No available spaces
  1287. *
  1288. */
  1289. function curlcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
  1290. {
  1291. ApiBbusLog::appLog("curlcreatedpreorderobj");
  1292. $apiInvoiceHelper = new ApiInvoiceHelper;
  1293. $createdPreOrderOBJ = [];
  1294. for ($i = 1; $i <= $reservations; $i++) {
  1295. dol_include_once('/comm/action/class/actioncomm.class.php');
  1296. dol_include_once('/custom/booking/class/preorder.class.php');
  1297. $apiInvoiceHelper->increaseParticipant($fk_event);
  1298. $lines = $apiInvoiceHelper->getProductLines($product_id);
  1299. foreach ($lines as $line) {
  1300. $preOrderObj = new PreOrder($this->db);
  1301. $preOrderObj->ref = $this->generateRandomString();
  1302. $preOrderObj->fk_event = $fk_event;
  1303. $preOrderObj->fk_product = $product_id;
  1304. $result = $preOrderObj->create($this->user);
  1305. if ($result > 0) {
  1306. $createdPreOrderOBJ[] = [
  1307. 'id' => $preOrderObj->id,
  1308. 'ref' => $preOrderObj->ref,
  1309. ];
  1310. } else {
  1311. ApiBbusLog::appLog(json_encode(['error' => $preOrderObj->errors]));
  1312. ApiBbusLog::appLog("Unsaved event: " . $fk_event);
  1313. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  1314. }
  1315. }
  1316. }
  1317. ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
  1318. return $createdPreOrderOBJ;
  1319. }
  1320. /**
  1321. * Create BBticket record
  1322. *
  1323. * Return an array with details
  1324. *
  1325. * @return array|mixed data without useless information
  1326. *
  1327. * @param string $product_id
  1328. * @param string $datec
  1329. * @param string $facture_id
  1330. *
  1331. * @url POST createbbticket
  1332. * @access protected
  1333. * @throws RestException 401 Not allowed
  1334. * @throws RestException 404 Not found
  1335. * @throws RestException 506 No available spaces
  1336. *
  1337. */
  1338. public function createbbticket(string $product_id, string $datec, string $facture_id)
  1339. {
  1340. global $db, $conf;
  1341. $sql = "SELECT validperiod, occasions FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $product_id;
  1342. $result = $db->query($sql);
  1343. while ($sqlDataResult = $db->fetch_array($result)) {
  1344. $validperiod = $sqlDataResult['validperiod'] ? $sqlDataResult['validperiod'] : 366;
  1345. $occasions = $sqlDataResult['occasions'];
  1346. }
  1347. $ticket = new BbTicket($db);
  1348. $ticket->fk_facture = null;
  1349. $ticket->bundle_id = $product_id;
  1350. $ticket->usable_occasions = $occasions;
  1351. $ticket->usage = '0';
  1352. $ticket->available_at = $this->getAvailableAtDate($datec, $validperiod);
  1353. $ticket->ticket_id = $product_id;
  1354. $ticket->fk_settlements_group_id = $conf->global->CURL_GROUP_ID;
  1355. $ticket->invoice_number = $facture_id;
  1356. if ($ticket->create($this->user) == -1) {
  1357. dol_syslog("Nem sikerult a ticketek mentese");
  1358. }
  1359. return true;
  1360. }
  1361. private function getAvailableAtDate($date, $validperiod)
  1362. {
  1363. $available_at = date('Y-m-d H:i:s', strtotime($date . ' +' . $validperiod . ' days'));
  1364. return $available_at;
  1365. }
  1366. /**
  1367. * Get printed factures refs
  1368. *
  1369. * Return an array with details
  1370. *
  1371. * @return array|mixed data without useless information
  1372. *
  1373. * @param string $from
  1374. * @param string $to
  1375. * @param string $factures
  1376. *
  1377. * @url POST getPrintedFacturesRefs
  1378. * @throws RestException 401 Not allowed
  1379. * @throws RestException 404 Not found
  1380. * @throws RestException 506 No available spaces
  1381. *
  1382. */
  1383. public function getPrintedFacturesRefs(string $from, string $to, string $factures = "")
  1384. {
  1385. $refs = "";
  1386. if ($factures != "") {
  1387. global $db, $conf;
  1388. $curluser_id = $conf->global->CURL_USER_ID;
  1389. $sql = "SELECT bbt.invoice_number
  1390. FROM llx_bbus_bbticket as bbt
  1391. INNER JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.ticket_id = bbt.rowid
  1392. 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";
  1393. $result = $db->query($sql);
  1394. if ($db->num_rows($result) > 0) {
  1395. while ($row = $db->fetch_object($result)) {
  1396. if ($refs == "") {
  1397. $refs .= "'" . $row->invoice_number . "'";
  1398. } else {
  1399. $refs .= ",'" . $row->invoice_number . "'";
  1400. }
  1401. }
  1402. }
  1403. }
  1404. return $refs;
  1405. }
  1406. /**
  1407. * Get printed factures refs in array
  1408. *
  1409. * Return an array with details
  1410. *
  1411. * @return array|mixed data without useless information
  1412. *
  1413. * @param string $from
  1414. * @param string $to
  1415. * @param string $factures
  1416. *
  1417. * @url POST getPrintedFacturesRefsArray
  1418. * @throws RestException 401 Not allowed
  1419. * @throws RestException 404 Not found
  1420. * @throws RestException 506 No available spaces
  1421. *
  1422. */
  1423. public function getPrintedFacturesRefsArray(string $from, string $to, string $factures)
  1424. {
  1425. $refs = [];
  1426. global $db, $conf;
  1427. $curluser_id = $conf->global->CURL_USER_ID;
  1428. $sql = "SELECT bbt.invoice_number
  1429. FROM llx_bbus_bbticket as bbt
  1430. INNER JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.ticket_id = bbt.rowid
  1431. 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";
  1432. $result = $db->query($sql);
  1433. if ($db->num_rows($result) > 0) {
  1434. while ($row = $db->fetch_object($result)) {
  1435. $refs[] = $row->invoice_number;
  1436. }
  1437. }
  1438. return $refs;
  1439. }
  1440. /**
  1441. * Get number of a facture's printer count
  1442. *
  1443. * Return an array with details
  1444. *
  1445. * @return array|mixed data without useless information
  1446. *
  1447. * @param string $invoice_number
  1448. *
  1449. * @url POST getFacturesNumberOfPrints
  1450. * @throws RestException 401 Not allowed
  1451. * @throws RestException 404 Not found
  1452. * @throws RestException 506 No available spaces
  1453. *
  1454. */
  1455. public function getFacturesNumberOfPrints(string $invoice_number)
  1456. {
  1457. $number = 0;
  1458. global $db;
  1459. $sql = "SELECT tip.fk_facture, tip.product_id, count(tip.product_id) FROM llx_bbus_bbticketinvoiceprinting as tip
  1460. WHERE tip.invoice_number = '{$invoice_number}'
  1461. GROUP BY tip.fk_facture, tip.product_id";
  1462. $result = $db->query($sql);
  1463. if ($db->num_rows($result) > 0) {
  1464. while ($row = $db->fetch_object($result)) {
  1465. $array[$row->fk_facture][$row->product_id] = $row->count;
  1466. }
  1467. $firstKey = array_key_first($array);
  1468. $firstValue = $array[$firstKey];
  1469. $number = reset($firstValue);
  1470. }
  1471. return $number;
  1472. }
  1473. }