api_booking.class.php 47 KB

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