api_booking.class.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  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 . '/custom/booking/class/eventhelper.class.php';
  25. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  26. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  27. require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
  28. require_once DOL_DOCUMENT_ROOT . '/custom/booking/class/preorder.class.php';
  29. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
  30. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';
  31. /**
  32. * \file booking/class/api_booking.class.php
  33. * \ingroup booking
  34. * \brief File for API management of bookinglog.
  35. */
  36. /**
  37. * API class for booking bookinglog
  38. *
  39. * @class DolibarrApiAccess {@requires user,external}
  40. */
  41. class BookingApi extends DolibarrApi
  42. {
  43. use CurlApi;
  44. /**
  45. * @var BookingLog $bookinglog {@type BookingLog}
  46. */
  47. public $bookinglog;
  48. private User $user;
  49. /**
  50. * Constructor
  51. *
  52. * @url GET /
  53. *
  54. */
  55. public function __construct()
  56. {
  57. global $db, $user;
  58. $this->db = $db;
  59. $this->user = $user;
  60. // $this->bookinglog = new BookingLog($this->db);
  61. }
  62. //P4NR6zhWHage
  63. //!!!types:
  64. /**
  65. * Get types of a bookable events
  66. *
  67. * Return an array with bookable events type list
  68. *
  69. * @return array|mixed data without useless information
  70. *
  71. * @url GET types
  72. *
  73. * @throws RestException 401 Not allowed
  74. * @throws RestException 404 Not found
  75. */
  76. public function types()
  77. {
  78. dol_include_once('/eventwizard/class/eventdetails.class.php');
  79. $EventDetails = new EventDetails($this->db);
  80. return $EventDetails->fields['type']['arrayofkeyval'];
  81. if (!DolibarrApiAccess::$user->rights->booking->types->read) {
  82. throw new RestException(401);
  83. }
  84. // dol_include_once('/booking/class/bookinglog.class.php');
  85. // $result = $this->bookinglog->fetch($id);
  86. // if (!$result) {
  87. // throw new RestException(404, 'BookingLog not found');
  88. // }
  89. // if (!DolibarrApi::_checkAccessToResource('bookinglog', $this->bookinglog->id, 'booking_bookinglog')) {
  90. // throw new RestException(401, 'Access to instance id='.$this->bookinglog->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
  91. // }
  92. // return $this->_cleanObjectDatas($this->bookinglog);
  93. }
  94. /**
  95. * Get bookable events
  96. *
  97. * Return an array with bookable events list
  98. *
  99. * @return array|mixed data without useless information
  100. *
  101. * @param int $onlyBookable
  102. * @param int $withDetails
  103. * @param int $withDates
  104. * @param int $withAviability
  105. * @url GET events
  106. *
  107. * @throws RestException 401 Not allowed
  108. * @throws RestException 404 Not found
  109. */
  110. public function events($onlyBookable = 1, $withDetails = 0, $withDates = 0, $withAviability = 0)
  111. {
  112. global $db, $conf;
  113. // if (!DolibarrApiAccess::$user->rights->booking->events->read) {
  114. // throw new RestException(401);
  115. // }
  116. $obj_ret = [];
  117. // if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
  118. // throw new RestException(401, "Insufficient rights to read events");
  119. // }
  120. $sql = "SELECT DISTINCT ed.rowid as id";
  121. if (!empty($conf->societe->enabled)) {
  122. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  123. // $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)
  124. // }
  125. }
  126. $sql .= " ,ed.label ";
  127. $sql .= " ,eld.label as from"; //... ??
  128. $sql .= " ,ela.label as to"; //...
  129. $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as t";
  130. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventdetails ed ON ed.rowid = t.fk_element";
  131. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation eld ON eld.rowid = ed.fk_elventlocation_departure";
  132. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation ela ON ela.rowid = ed.fk_elventlocation_arrival";
  133. $sql .= " WHERE code = 'AC_EVENT' ";
  134. $sql .= " AND t.elementtype = 'eventdetails@eventwizard'";
  135. if ($onlyBookable) {
  136. $sql .= " AND t.datep > CURRENT_TIMESTAMP";
  137. }
  138. $result = $this->db->query($sql);
  139. if ($result) {
  140. $i = 0;
  141. // $num = $this->db->num_rows($result);
  142. // $min = min($num, ($limit <= 0 ? $num : $limit));
  143. while ($event = $this->db->fetch_object($result)) {
  144. if ($withDetails) {
  145. $event->details = $this->details($event->id);
  146. }
  147. if ($withDates) {
  148. //... $withAviability
  149. $event->dates = $this->dates($event->id);
  150. }
  151. $obj_ret[] = $event;
  152. }
  153. } else {
  154. throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
  155. }
  156. if (!count($obj_ret)) {
  157. throw new RestException(404, 'No Agenda Event found');
  158. }
  159. return $obj_ret;
  160. }
  161. /**
  162. * Get event dates
  163. *
  164. * Return an array with event dates list
  165. *
  166. * @return array|mixed data without useless information
  167. *
  168. * @param int $id
  169. * @param int $onlyBookable
  170. * @param string $json
  171. * @url GET dates
  172. *
  173. * @throws RestException 401 Not allowed
  174. * @throws RestException 404 Not found
  175. */
  176. public function dates($id, $onlyBookable = 1, $json = null)
  177. {
  178. global $db, $conf;
  179. // if (!DolibarrApiAccess::$user->rights->booking->events->read) {
  180. // throw new RestException(401);
  181. // }
  182. $obj_ret = [];
  183. // if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
  184. // throw new RestException(401, "Insufficient rights to read events");
  185. // }
  186. $sql = "SELECT t.id ";
  187. if (!empty($conf->societe->enabled)) {
  188. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  189. // $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)
  190. // }
  191. }
  192. $sql .= " ,ed.label, t.note ";
  193. $sql .= " ,t.datep as start, t.datep2 as end";
  194. $sql .= " ,eld.label as from"; //... ??
  195. $sql .= " ,ela.label as to"; //...
  196. $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as t";
  197. // if (!empty($conf->societe->enabled)) {
  198. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  199. // $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  200. // }
  201. // }
  202. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventdetails ed ON ed.rowid = t.fk_element";
  203. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation eld ON eld.rowid = ed.fk_elventlocation_departure";
  204. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation ela ON ela.rowid = ed.fk_elventlocation_arrival";
  205. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventoption eo ON el.rowid = ed.fk_element";
  206. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventproduct eo ON el.rowid = ed.fk_element";
  207. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_ eo ON el.rowid = ed.fk_element";
  208. // $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
  209. $sql .= " WHERE code = 'AC_EVENT' ";
  210. $sql .= " AND t.fk_element = " . (int) $this->db->escape($id);
  211. $sql .= " AND t.elementtype = 'eventdetails@eventwizard'";
  212. $sql .= " AND t.datep > CURRENT_TIMESTAMP";
  213. // if (!empty($conf->societe->enabled)) {
  214. // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
  215. // $sql .= " AND t.fk_soc = sc.fk_soc";
  216. // }
  217. // }
  218. // if ($user_ids) {
  219. // $sql .= " AND t.fk_user_action IN (".$this->db->sanitize($user_ids).")";
  220. // }
  221. // if ($socid > 0) {
  222. // $sql .= " AND t.fk_soc = ".((int) $socid);
  223. // }
  224. // Insert sale filter
  225. // if ($search_sale > 0) {
  226. // $sql .= " AND sc.fk_user = ".((int) $search_sale);
  227. // }
  228. // Add sql filters
  229. // if ($sqlfilters) {
  230. // $errormessage = '';
  231. // if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  232. // throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  233. // }
  234. // $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  235. // $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  236. // }
  237. // $sql .= $this->db->order($sortfield, $sortorder);
  238. // if ($limit) {
  239. // if ($page < 0) {
  240. // $page = 0;
  241. // }
  242. // $offset = $limit * $page;
  243. // $sql .= $this->db->plimit($limit + 1, $offset);
  244. // }
  245. $result = $this->db->query($sql);
  246. if ($result) {
  247. $i = 0;
  248. $num = $this->db->num_rows($result);
  249. // $min = min($num, ($limit <= 0 ? $num : $limit));
  250. while ($i < $num) {
  251. $obj_ret[] = $this->db->fetch_object($result);
  252. $i++;
  253. }
  254. } else {
  255. throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
  256. }
  257. if (!count($obj_ret)) {
  258. throw new RestException(404, 'No Agenda Event found');
  259. }
  260. return $obj_ret;
  261. }
  262. /**
  263. * Post booking (draft)
  264. *
  265. * Return an array with draft bookings list
  266. *
  267. * @return array|mixed data without useless information
  268. *
  269. * @param int $event
  270. * @param array $details
  271. * @url POST set
  272. *
  273. * @access protected
  274. * @throws RestException 401 Not allowed
  275. * @throws RestException 404 Not found
  276. */
  277. public function set($event, $details)
  278. {
  279. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  280. throw new RestException(401);
  281. }
  282. }
  283. /**
  284. * Post booking validation
  285. *
  286. * Return an array with bookings list
  287. *
  288. * @return array|mixed data without useless information
  289. *
  290. * @param int $event
  291. * @param array $drafts
  292. * @url POST validate
  293. *
  294. * @access protected
  295. * @throws RestException 401 Not allowed
  296. * @throws RestException 404 Not found
  297. */
  298. public function validate($event, $drafts)
  299. {
  300. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  301. throw new RestException(401);
  302. }
  303. }
  304. /**
  305. * Get bookings list
  306. *
  307. * Return an array with the user's bookings list
  308. *
  309. * @return array|mixed data without useless information
  310. *
  311. * @url POST bookings
  312. *
  313. * @access protected
  314. * @throws RestException 401 Not allowed
  315. * @throws RestException 404 Not found
  316. */
  317. public function bookings()
  318. {
  319. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  320. throw new RestException(401);
  321. }
  322. }
  323. /**
  324. * Get cron to clean booking draftInvoices
  325. *
  326. * Return an array with cleaned list
  327. *
  328. * @return array|mixed data without useless information
  329. *
  330. * @url GET cron
  331. *
  332. * @access protected
  333. * @throws RestException 401 Not allowed
  334. * @throws RestException 404 Not found
  335. */
  336. public function cron()
  337. {
  338. if (!DolibarrApiAccess::$user->rights->booking->events->write) {
  339. throw new RestException(401);
  340. }
  341. }
  342. /**
  343. * Get details of a bookable event
  344. *
  345. * Return an array with details
  346. *
  347. * @return array|mixed data without useless information
  348. *
  349. * @param int $id
  350. * @url GET details
  351. *
  352. * @access protected
  353. * @throws RestException 401 Not allowed
  354. * @throws RestException 404 Not found
  355. */
  356. public function details($id)
  357. {
  358. $details = [
  359. 'tmp' => [],
  360. 'product' => [],
  361. 'min' => 0,
  362. 'id_event' => $id,
  363. // 'variants' => []
  364. ];
  365. $variants = [];
  366. dol_include_once('/eventwizard/class/eventdetails.class.php');
  367. $EventDetails = new EventDetails($this->db);
  368. if ($EventDetails->fetch($id)) {
  369. $sql = "SELECT ep.rowid ,ep.fk_eventdetails, ep.fk_product, ep.type, ep.amount, ep.qty ";
  370. $sql .= " , p.label, p.price "; //price price_ttc price_min price_min_ttc
  371. $sql .= " FROM " . MAIN_DB_PREFIX . "eventwizard_eventproduct ep ";
  372. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product p ON p.rowid = ep.fk_product ";
  373. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination ac ON ac.fk_product_parent = ep.fk_product ";
  374. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventoption eo ON eo.rowid = ep.fk_eventoption ";
  375. // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventdetails ed ON ed.rowid = ep.fk_eventdetails ";
  376. $sql .= " WHERE ep.fk_eventdetails = " . (int) $this->db->escape($id);
  377. // return $sql;
  378. $result = $this->db->query($sql);
  379. if ($result) {
  380. $variants_ids = [];
  381. while ($d = $this->db->fetch_object($result)) {
  382. $variants_ids[] = $d->fk_product;
  383. // if(is_null($d->fk_product_child)){}
  384. $d->variants = [];
  385. // $d->minP = (is_null($d->amount))?(float)$d->price:(float)$d->amount;
  386. $details['tmp']['' . $d->fk_product] = $d;
  387. }
  388. $sql2 = "SELECT p.rowid, p.label, p.price ";
  389. $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
  390. $sql2 .= "FROM " . MAIN_DB_PREFIX . "product_attribute_combination ac ";
  391. $sql2 .= " LEFT JOIN " . MAIN_DB_PREFIX . "product p ON ac.fk_product_child = p.rowid ";
  392. $sql2 .= " WHERE ac.fk_product_parent IN (" . implode(",", $variants_ids) . ") ";
  393. $result2 = $this->db->query($sql2);
  394. if ($result2) {
  395. while ($v = $this->db->fetch_object($result2)) {
  396. $d = $details['tmp']['' . $v->fk_product_parent];
  397. $d->variants[] = $this->product2out($v);
  398. if (!is_null($d->amount)) { //... - ??? %?
  399. $d->minP = (float) $d->amount;
  400. } elseif (!isset($d->minP)) {
  401. $d->minP = $v->price;
  402. } elseif ($d->minP > $v->price) {
  403. $d->minP = $v->price;
  404. }
  405. $details['tmp']['' . $v->fk_product_parent] = $d;
  406. }
  407. }
  408. foreach ($details['tmp'] as $k => $v) {
  409. $p = $this->product2out($v);
  410. $p["minP"] = (is_null($v->amount)) ? (!isset($d->minP)) ? (float) $v->price : (float) $v->minP : (float) $v->amount;
  411. $p["variants"] = $v->variants;
  412. $details['product'][] = $p;
  413. if ($p["type"] == 1) {
  414. $details['min'] += $p["minP"];
  415. }
  416. }
  417. unset($details['tmp']);
  418. } else {
  419. throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
  420. }
  421. // $EventDetails->getLinesArray();
  422. // print_r($EventDetails->lines);
  423. return $details;
  424. //$variations
  425. // $variations =
  426. }
  427. }
  428. protected function product2out($product)
  429. {
  430. return [
  431. "id" => $product->fk_product,
  432. "type" => $product->type, //1,2,3
  433. "fixed_price" => $product->amount,
  434. "max" => $product->qty,
  435. "label" => $product->label,
  436. "price" => $product->price,
  437. ];
  438. }
  439. /**
  440. * Get all products by type
  441. *
  442. * Return an array with details
  443. *
  444. * @return array|mixed data without useless information
  445. *
  446. * @param int $type_id
  447. * @param string $from_date
  448. * @param string $to_date
  449. *
  450. * @url POST getallavailableproducts
  451. *
  452. * @throws RestException 401 Not allowed
  453. * @throws RestException 404 Not found
  454. */
  455. public function getAllAvailableProducts(int $type_id, string $from_date, string $to_date)
  456. {
  457. $date = new DateTime($to_date);
  458. $date->modify('+1 day');
  459. $to_date = $date->format('Y-m-d');
  460. $TMPArray = [];
  461. $productsArray = [];
  462. $sql = "SELECT
  463. pr.rowid
  464. from llx_actioncomm as ac
  465. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  466. INNER JOIN llx_eventwizard_eventdetails as ed ON ed.rowid = ac.fk_element
  467. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ed.rowid
  468. INNER JOIN llx_product as pr ON pr.rowid = ep.fk_product
  469. where ac.datep > '{$from_date} 00:00:00' AND ac.datep2 < '{$to_date} 00:00:00'
  470. AND ac.code = 'AC_EVENT'
  471. AND ed.type = {$type_id}
  472. AND ace.max_num - COALESCE(ace.participants, 0) > 1
  473. GROUP BY pr.rowid";
  474. $result = $this->db->query($sql);
  475. if ($this->db->num_rows($result) > 0) {
  476. while ($row = $this->db->fetch_object($result)) {
  477. $TMPArray[] = $row->rowid;
  478. }
  479. foreach ($TMPArray as $productItem) {
  480. $ApiProductListHelper = new ApiProductListHelper();
  481. $array = $ApiProductListHelper->list('t.ref', 'ASC', '', '', '', '', "(t.rowid:=:{$productItem})");
  482. $productsArray[] = $array[0];
  483. }
  484. }
  485. return $productsArray;
  486. }
  487. /**
  488. * First step of the eventhandling
  489. * {"invoice":{"array_options_app_facture":1,"array_options_customer_data_zip":6782,"multicurrency_code":"HUF","fk_multicurrency":3,"mode_reglement_id":14,"cond_reglement_id":14,"fk_account":4},"fk_event":82586,"reservations":1,"sendId":12121212,"product_id":155}
  490. *
  491. * Return an array with details
  492. *
  493. * @return array|mixed data without useless information
  494. *
  495. * @param array $invoice Invoice data
  496. * @param int $fk_event //selected evet from llx_event
  497. * @param int $reservations //numbers of reservations
  498. * @param int $product_id //Product
  499. * @param string $sendId //ID
  500. *
  501. * @url POST firsteventstepold
  502. * @access protected
  503. * @throws RestException 401 Not allowed
  504. * @throws RestException 404 Not found
  505. * @throws RestException 506 No available spaces
  506. *
  507. */
  508. public function firstEventStepOld(array $invoice, int $fk_event, int $reservations, int $product_id, string $sendId)
  509. {
  510. $eventHelper = new EventHelper;
  511. if ($eventHelper->noEmptySpaces($fk_event, $reservations)) {
  512. throw new RestException(506, 'No available spaces');
  513. }
  514. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  515. ApiBbusLog::eventLog("{$sendId} Insufficient rights");
  516. throw new RestException(401, 'Insufficient rights');
  517. }
  518. /**
  519. * LOG SECTION
  520. */
  521. ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
  522. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  523. ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
  524. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  525. ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  526. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  527. ApiBbusLog::eventLog("{$sendId} " . json_encode([
  528. 'invoice' => $invoice,
  529. 'fk_event' => $fk_event,
  530. 'reservations' => $reservations,
  531. 'product_id' => $product_id,
  532. 'sendId' => $sendId,
  533. ]));
  534. $apiInvoiceHelper = new ApiInvoiceHelper;
  535. $createdInvoicePROVs = [];
  536. for ($i = 1; $i <= $reservations; $i++) {
  537. dol_include_once('/comm/action/class/actioncomm.class.php');
  538. $apiInvoiceHelper->increaseParticipant($fk_event);
  539. $invoiceObj = $apiInvoiceHelper->createInvoicePROV($invoice, $sendId);
  540. $createdInvoicePROVs[] = [
  541. 'id' => $invoiceObj->id,
  542. 'ref' => $invoiceObj->ref,
  543. ];
  544. ApiBbusLog::eventLog("{$sendId} - Invoice PROV created - " . $invoiceObj->id . ' - ' . $invoiceObj->ref);
  545. $lines = $apiInvoiceHelper->getProductLines($product_id);
  546. foreach ($lines as $line) {
  547. $invoiceLineObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
  548. $this->saveEventData($fk_event, $invoiceObj->id, $fk_eventproduct = 1);
  549. }
  550. $invoiceLineObj->fetch_lines();
  551. }
  552. print_r($createdInvoicePROVs);
  553. exit;
  554. return $createdInvoicePROVs;
  555. }
  556. /**
  557. * First step of the eventhandling
  558. * {"fk_event":669,"reservations":1,"product_id":2,"sendId":"12121212"}
  559. *
  560. * Return an array with details
  561. *
  562. * @return array|mixed data without useless information
  563. *
  564. * @param int $fk_event //selected evet from llx_event
  565. * @param int $reservations //numbers of reservations
  566. * @param int $product_id //Product
  567. * @param string $sendId //ID
  568. *
  569. * @url POST firsteventstep
  570. * @access protected
  571. * @throws RestException 401 Not allowed
  572. * @throws RestException 404 Not found
  573. * @throws RestException 506 No available spaces
  574. *
  575. */
  576. public function firstEventStep(int $fk_event, int $reservations, int $product_id, string $sendId)
  577. {
  578. ApiBbusLog::eventLog("fk_event: {$fk_event}");
  579. ApiBbusLog::eventLog("reservations: {$reservations}");
  580. ApiBbusLog::eventLog("product_id: {$product_id}");
  581. ApiBbusLog::eventLog("sendId: {$sendId}");
  582. $eventHelper = new EventHelper;
  583. if ($eventHelper->noEmptySpaces($fk_event, $reservations)) {
  584. throw new RestException(506, 'No available spaces');
  585. }
  586. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  587. ApiBbusLog::eventLog("{$sendId} Insufficient rights");
  588. throw new RestException(401, 'Insufficient rights');
  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. $apiInvoiceHelper = new ApiInvoiceHelper;
  606. $createdPreOrderOBJ = [];
  607. for ($i = 1; $i <= $reservations; $i++) {
  608. dol_include_once('/comm/action/class/actioncomm.class.php');
  609. dol_include_once('/custom/booking/class/preorder.class.php');
  610. $apiInvoiceHelper->increaseParticipant($fk_event);
  611. $lines = $apiInvoiceHelper->getProductLines($product_id);
  612. foreach ($lines as $line) {
  613. $preOrderObj = new PreOrder($this->db);
  614. $preOrderObj->ref = $this->generateRandomString();
  615. $preOrderObj->fk_event = $fk_event;
  616. $preOrderObj->fk_product = $product_id;
  617. $result = $preOrderObj->create($this->user);
  618. if ($result > 0) {
  619. $createdPreOrderOBJ[] = [
  620. 'id' => $preOrderObj->id,
  621. 'ref' => $preOrderObj->ref,
  622. ];
  623. } else {
  624. ApiBbusLog::eventLog(json_encode(['error' => $preOrderObj->errors]));
  625. ApiBbusLog::eventLog("Unsaved event: " . $fk_event);
  626. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  627. }
  628. }
  629. }
  630. return $createdPreOrderOBJ;
  631. }
  632. function generateRandomString($length = 10)
  633. {
  634. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  635. $charactersLength = strlen($characters);
  636. $randomString = '';
  637. for ($i = 0; $i < $length; $i++) {
  638. $randomString .= $characters[rand(0, $charactersLength - 1)];
  639. }
  640. return $randomString;
  641. }
  642. /**
  643. * Save event data in Bookinghistory
  644. *
  645. * Return an array with details
  646. *
  647. * @return array|mixed data without useless information
  648. *
  649. * @param string $fk_event //selected evet from llx_event
  650. * @param string $fk_facture //facture rowid from llx_facture
  651. * @param string $fk_eventproduct //eventproduct rowid from llx_eventwizard_eventproduct
  652. * @param string $ref
  653. *
  654. * @url POST saveeventdata
  655. * @access protected
  656. * @throws RestException 401 Not allowed
  657. * @throws RestException 404 Not found
  658. */
  659. public function saveEventData(string $fk_event, string $ref, string $fk_facture = null, string $fk_eventproduct = null)
  660. {
  661. dol_include_once('/custom/booking/class/bookinghistory.class.php');
  662. dol_include_once('/comm/action/class/actioncomm.class.php');
  663. $actionCommObj = new ActionComm($this->db);
  664. $sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
  665. $result = $this->db->query($sql);
  666. if ($this->db->num_rows($result) > 0) {
  667. $row = $this->db->fetch_object($result);
  668. $BookingHistory = new BookingHistory($this->db);
  669. $BookingHistory->fk_event = (int)$fk_event;
  670. $BookingHistory->fk_facture = (int)$fk_facture;
  671. $BookingHistory->fk_event_detail = $row->fk_element;
  672. $BookingHistory->fk_eventproduct = (int)$fk_eventproduct;
  673. $BookingHistory->date_start = strtotime($row->datep);
  674. $BookingHistory->date_end = strtotime($row->datep2);
  675. $BookingHistory->invoice_number = $ref;
  676. $result = $BookingHistory->create($this->user);
  677. if ($result > 0) {
  678. return $BookingHistory->id;
  679. } else {
  680. throw new RestException(401, 'Unsaved');
  681. }
  682. } else {
  683. throw new RestException(401, 'No Event record');
  684. }
  685. }
  686. /**
  687. * Validate and save invoice
  688. * {"facture_id":41968,"cardPaymentLog":"","sendId":"K1pfFPlT","payment":{"datepaye":1716388707,"paymentid":14,"accountid":4,"closepaidinvoices":"yes"}}
  689. *
  690. * Return an array with details
  691. *
  692. * @return array|mixed data without useless information
  693. *
  694. * @param int $facture_id //facture_id
  695. * @param array $payment Invoice payment
  696. * @param string $cardPaymentLog Card payment log data
  697. * @param string $sendId //ID
  698. *
  699. * @url POST validateandsaveinvoiceold
  700. * @access protected
  701. * @throws RestException 401 Not allowed
  702. * @throws RestException 404 Not found
  703. * @throws RestException 506 No available spaces
  704. *
  705. */
  706. public function validateandsaveinvoiceOld(int $facture_id, array $payment, string $cardPaymentLog = '', string $sendId = '')
  707. {
  708. global $user;
  709. ApiBbusLog::eventLog("{$sendId} === VALIDATE INVOICE ===");
  710. dol_syslog("{$sendId} === VALIDATE INVOICE ===", LOG_INFO, 0);
  711. ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
  712. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  713. ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  714. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  715. ApiBbusLog::eventLog("{$sendId} " . json_encode([
  716. 'facture_id' => $facture_id,
  717. 'payement' => $payment,
  718. 'cardPayementLog' => $cardPaymentLog,
  719. 'sendId' => $sendId,
  720. ]));
  721. $products = [];
  722. $invoiceObj = new Facture($this->db);
  723. $apiInvoiceHelper = new ApiInvoiceHelper;
  724. $invoiceObj->fetch($facture_id);
  725. foreach ($invoiceObj->lines as $line) {
  726. $product = $apiInvoiceHelper->loadProductToResult(get_object_vars($line));
  727. if (!empty($product)) {
  728. $products[] = $product;
  729. }
  730. }
  731. foreach ($products as &$row) {
  732. foreach ($invoiceObj->lines as $line) {
  733. if ($line->product_ref == $row['ref']) {
  734. //$row['price'] = $line->total_ttc;
  735. $row['price'] = $line->multicurrency_total_ttc;
  736. $row['total_tva'] = $line->total_tva;
  737. //$row['total_tva'] = $line->multicurrency_total_tva;
  738. }
  739. }
  740. }
  741. $invoiceObj = $apiInvoiceHelper->validateInvoiceFromPROV($invoiceObj, $sendId, $facture_id);
  742. $apiInvoiceHelper->setPaymentFromPROV($invoiceObj, $payment, $sendId);
  743. if (!empty($cardPaymentLog)) {
  744. $invoiceObj = $apiInvoiceHelper->saveCardPaymentLog($invoiceObj, $cardPaymentLog, $sendId);
  745. }
  746. ApiBbusLog::eventLog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}");
  747. dol_syslog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}", LOG_INFO, 0);
  748. //$bbApiLock->delete($user);
  749. ApiBbusLog::eventLog("{$sendId}####################################################################");
  750. dol_syslog("{$sendId}####################################################################", LOG_INFO, 0);
  751. return [
  752. 'sendId' => $sendId,
  753. 'invoice' => [
  754. 'id' => $invoiceObj->id,
  755. 'ref' => $invoiceObj->ref,
  756. 'total' => $invoiceObj->multicurrency_total_ttc
  757. ],
  758. 'products' => $products,
  759. ];
  760. }
  761. /**
  762. * Validate and save invoice
  763. * {"cardPaymentLog": "","sendId": "Xune5nQb","payment": {"datepaye": 1720005853,"paymentid": 4,"accountid": 2,"closepaidinvoices": "yes"},"preorder": [23]}
  764. *
  765. * Return an array with details
  766. *
  767. * @return array|mixed data without useless information
  768. *
  769. * @param string $sendId sendID
  770. * @param array $payment Invoice payment
  771. * @param array $preorder preorder
  772. * @param array $invoice Invoice
  773. * @param string $cardPaymentLog Card payment log data
  774. *
  775. * @url POST validateandsaveinvoice
  776. * @access protected
  777. * @throws RestException 401 Not allowed
  778. * @throws RestException 404 Not found
  779. * @throws RestException 506 No available spaces
  780. *
  781. */
  782. public function validateandsaveinvoice(string $sendId, array $payment, array $preorder, array $invoice, string $cardPaymentLog = '')
  783. {
  784. global $user, $db;
  785. $createdInvoiceData = [];
  786. $apiInvoiceHelper = new ApiInvoiceHelper;
  787. $bbusApi = new BBus();
  788. foreach ($preorder as $order) {
  789. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$order}";
  790. //print $sql . "\r\n";
  791. $data = $db->query($sql);
  792. if ($db->num_rows($data) > 0) {
  793. while ($row = $db->fetch_object($data)) {
  794. //print_r($row);
  795. $lines = $apiInvoiceHelper->getProductLines($row->fk_product);
  796. $createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '');
  797. $createdInvoiceData[] = $createdInvoiceArray;
  798. $bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray['invoice']['ref'], $createdInvoiceArray['invoice']['id']);
  799. $this->updateBbticket($bookingHistory, $createdInvoiceArray['invoice']);
  800. $this->deletePreorder($preorder);
  801. }
  802. }
  803. }
  804. return $createdInvoiceData;
  805. }
  806. public function updateBbticket($fk_booking_history, $invoice)
  807. {
  808. global $user;
  809. $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE fk_facture = {$invoice['id']}";
  810. $data = $this->db->query($sql);
  811. if ($this->db->num_rows($data) > 0) {
  812. while ($row = $this->db->fetch_object($data)) {
  813. $sql = "UPDATE llx_bbus_bbticket
  814. SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
  815. WHERE rowid = {$row->rowid}";
  816. $this->db->query($sql);
  817. }
  818. }
  819. }
  820. public function deletePreorder($preorder)
  821. {
  822. foreach ($preorder as $item) {
  823. $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
  824. $this->db->query($sql);
  825. }
  826. }
  827. public function eventErasuer()
  828. {
  829. global $user;
  830. $limitDate = date("Y-m-d H:i:s", dol_now() - 1200);
  831. $sql = "SELECT * FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
  832. //print $sql;exit;
  833. $data = $this->db->query($sql);
  834. if ($this->db->num_rows($data) > 0) {
  835. while ($row = $this->db->fetch_object($data)) {
  836. //print_r($row);
  837. $actioncommObj = new ActionComm($this->db);
  838. $resultActionComm = $actioncommObj->fetch($row->fk_event);
  839. $actioncommObj->array_options['options_participants'] = $actioncommObj->array_options['options_participants'] - 1;
  840. $actioncommObj->update($user);
  841. }
  842. //exit;
  843. $sqlDelete = "DELETE FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
  844. $dataDelete = $this->db->query($sqlDelete);
  845. }
  846. }
  847. /**
  848. * Increase Participants
  849. *
  850. * Return an array with details
  851. *
  852. * @return array|mixed data without useless information
  853. *
  854. * @param int $event_id //rowid of evet from llx_event
  855. *
  856. * @url POST increaseparticipant
  857. *
  858. * @throws RestException 401 Not allowed
  859. * @throws RestException 404 Not found
  860. */
  861. public function increaseParticipant(int $event_id)
  862. {
  863. dol_include_once('/comm/action/class/actioncomm.class.php');
  864. global $user;
  865. $actionComObj = new ActionComm($this->db);
  866. $actionComObj->fetch($event_id);
  867. $max_num = (int) $actionComObj->array_options['options_max_num'];
  868. $buffer = (int) $actionComObj->array_options['options_buffer'];
  869. $participants = (int) $actionComObj->array_options['options_participants'];
  870. $increasedParticipants = $participants + 1;
  871. if ($increasedParticipants > ($max_num + $buffer)) {
  872. return 'full';
  873. } elseif (($increasedParticipants > $max_num) && ($increasedParticipants <= ($max_num + $buffer))) {
  874. $actionComObj->array_options['options_participants'] = $increasedParticipants;
  875. $actionComObj->update($user);
  876. return 'Buffer';
  877. } else {
  878. $actionComObj->array_options['options_participants'] = $increasedParticipants;
  879. $actionComObj->update($user);
  880. return 'OK';
  881. }
  882. }
  883. /**
  884. * Reduce Participants
  885. *
  886. * Return an array with details
  887. *
  888. * @return array|mixed data without useless information
  889. *
  890. * @param int $event_id //rowid of evet from llx_event
  891. *
  892. * @url POST reduceparticipant
  893. *
  894. *
  895. * @throws RestException 401 Not allowed
  896. * @throws RestException 404 Not found
  897. */
  898. public function reduceParticipant(int $event_id)
  899. {
  900. global $user;
  901. dol_include_once('/comm/action/class/actioncomm.class.php');
  902. $actionComObj = new ActionComm($this->db);
  903. $actionComObj->fetch($event_id);
  904. $participants = (int) $actionComObj->array_options['options_participants'];
  905. $reducedParticipants = $participants - 1;
  906. $actionComObj->array_options['options_participants'] = $reducedParticipants < 0 ? 0 : $reducedParticipants;
  907. $actionComObj->update($user);
  908. return 'OK';
  909. }
  910. /**
  911. * Create invoice
  912. *
  913. * @param array $invoice Invoice data
  914. * @param array $lines Invoice lines
  915. * @param array $payment Invoice payment
  916. * @param string $eventid Event ID
  917. * @param string $cardPaymentLog Card payment log data
  918. *
  919. * @access protected
  920. * @return array|mixed Data without useless information
  921. *
  922. * @url POST /invoice
  923. */
  924. public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $eventid = '', string $sendId = '')
  925. {
  926. if (empty($sendId)) {
  927. $sendId = substr(md5(rand()), 0, 8);
  928. }
  929. /**
  930. * LOG SECTION
  931. */
  932. ApiBbusLog::appLog("{$sendId} === NEW INVOICE ===");
  933. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  934. ApiBbusLog::appLog("{$sendId} REQUEST: {$sendId}");
  935. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  936. ApiBbusLog::appLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
  937. dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
  938. ApiBbusLog::appLog("{$sendId} " . json_encode([
  939. 'invoice' => $invoice,
  940. 'lines' => $lines,
  941. 'payment' => $payment,
  942. 'eventid' => $eventid,
  943. 'cardPaymentLog' => $cardPaymentLog
  944. ]));
  945. /**
  946. * CHECK RIGHTS
  947. */
  948. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  949. ApiBbusLog::appLog("{$sendId} Insufficient rights");
  950. throw new RestException(401, 'Insufficient rights');
  951. }
  952. $apiInvoiceHelper = new ApiInvoiceHelper;
  953. /**
  954. * handle invoice basic data
  955. */
  956. $invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId);
  957. /**
  958. * handle invoice line(s)
  959. */
  960. $products = [];
  961. //print $eventid;exit;
  962. foreach ($lines as $line) {
  963. $invoiceObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
  964. $this->increaseParticipant((int) $eventid);
  965. $product = $apiInvoiceHelper->loadProductToResult($line);
  966. if (!empty($product)) {
  967. $products[] = $product;
  968. }
  969. }
  970. $invoiceObj->fetch_lines();
  971. foreach ($products as &$row) {
  972. foreach ($invoiceObj->lines as $line) {
  973. if ($line->product_ref == $row['ref']) {
  974. //$row['price'] = $line->total_ttc;
  975. $row['price'] = $line->multicurrency_total_ttc;
  976. $row['total_tva'] = $line->total_tva;
  977. //$row['total_tva'] = $line->multicurrency_total_tva;
  978. }
  979. }
  980. }
  981. return [
  982. 'sendId' => $sendId,
  983. 'invoice' => [
  984. 'id' => $invoiceObj->id,
  985. 'ref' => $invoiceObj->ref,
  986. 'total' => $invoiceObj->multicurrency_total_ttc
  987. ],
  988. 'products' => $products,
  989. ];
  990. }
  991. /**
  992. * Get all free spaces on a selected date
  993. *
  994. * Return an array with details
  995. *
  996. * @return array|mixed data without useless information
  997. *
  998. * @param string date_from
  999. * @param string date_to
  1000. * @param int product_id
  1001. * @param int participant_number
  1002. *
  1003. * @url POST getavailablespaces
  1004. *
  1005. * @throws RestException 401 Not allowed
  1006. * @throws RestException 404 Not found
  1007. */
  1008. public function getAvailableSpaces(string $date_from, string $date_to, int $product_id, int $participant_number, string $type_id = null)
  1009. {
  1010. ApiBbusLog::appLog("getAvailableSpaces");
  1011. /* ApiBbusLog::appLog("type_id: {$type_id}");
  1012. ApiBbusLog::appLog("date_from: {$date_from}");
  1013. ApiBbusLog::appLog("date_to: {$date_to}");
  1014. ApiBbusLog::appLog("product_id: {$product_id}");
  1015. ApiBbusLog::appLog("participant_number: {$participant_number}"); */
  1016. $basicServices = new BasicServices($this->db);
  1017. $resultBS = $basicServices->fetch($type_id);
  1018. if ($basicServices->server_host == 'excelia') {
  1019. return $this->localAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
  1020. } else {
  1021. return $this->curlAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
  1022. }
  1023. }
  1024. /**
  1025. * Get all free spaces on a selected date
  1026. *
  1027. * Return an array with details
  1028. *
  1029. * @return array|mixed data without useless information
  1030. *
  1031. * @param string date_from
  1032. * @param string date_to
  1033. * @param int product_id
  1034. * @param int participant_number
  1035. *
  1036. * @url POST localavailableplaces
  1037. *
  1038. * @throws RestException 401 Not allowed
  1039. * @throws RestException 404 Not found
  1040. */
  1041. public function localAvailablePlaces($date_from, $date_to, $product_id, $participant_number)
  1042. {
  1043. $array = [];
  1044. $date = new DateTime($date_to);
  1045. $date->modify('+1 day');
  1046. $date_to = $date->format('Y-m-d');
  1047. $sql = "SELECT
  1048. ac.id,
  1049. ac.datep,
  1050. ace.max_num,
  1051. ace.participants,
  1052. ace.buffer
  1053. FROM llx_actioncomm as ac
  1054. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1055. INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
  1056. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
  1057. WHERE ac.code = 'AC_EVENT'
  1058. AND ep.fk_product = {$product_id}
  1059. AND ac.datep > '{$date_from} 00:00:00'
  1060. AND ac.datep2 < '{$date_to} 00:00:00'
  1061. ORDER BY ac.datep ASC";
  1062. $result = $this->db->query($sql);
  1063. while ($row = $this->db->fetch_object($result)) {
  1064. $max_num = $row->max_num;
  1065. $buffer = $row->buffer;
  1066. $participants = $row->participants;
  1067. $date = strtotime($row->datep);
  1068. $element['event_id'] = $row->id;
  1069. //$element['date'] = date("Y-m-d", $date);
  1070. //$element['time'] = date("H:i", $date);
  1071. $element['participants'] = is_null($participants) ? 0 : (int) $participants;
  1072. $element['max_num'] = $max_num;
  1073. $element['buffer'] = $buffer;
  1074. if ($max_num > $participants) {
  1075. if ($max_num + $buffer > $participants + $participant_number) {
  1076. $array[date("Y-m-d", $date)][date("H:i", $date)] = $element;
  1077. }
  1078. }
  1079. }
  1080. return $array;
  1081. }
  1082. /**
  1083. * Get all free spaces on a selected date
  1084. *
  1085. * Return an array with details
  1086. *
  1087. * @return array|mixed data without useless information
  1088. *
  1089. * @param string sendId
  1090. * @param int fk_event
  1091. * @param int reservations
  1092. * @param int product_id
  1093. *
  1094. * @url POST localcreatedpreorderobj
  1095. * @access protected
  1096. * @throws RestException 401 Not allowed
  1097. * @throws RestException 404 Not found
  1098. */
  1099. public function localcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
  1100. {
  1101. $apiInvoiceHelper = new ApiInvoiceHelper;
  1102. $createdPreOrderOBJ = [];
  1103. for ($i = 1; $i <= $reservations; $i++) {
  1104. dol_include_once('/comm/action/class/actioncomm.class.php');
  1105. dol_include_once('/custom/booking/class/preorder.class.php');
  1106. $apiInvoiceHelper->increaseParticipant($fk_event);
  1107. $lines = $apiInvoiceHelper->getProductLines($product_id);
  1108. foreach ($lines as $line) {
  1109. $preOrderObj = new PreOrder($this->db);
  1110. $preOrderObj->ref = $this->generateRandomString();
  1111. $preOrderObj->fk_event = $fk_event;
  1112. $preOrderObj->fk_product = $product_id;
  1113. $result = $preOrderObj->create($this->user);
  1114. if ($result > 0) {
  1115. $createdPreOrderOBJ[] = [
  1116. 'id' => $preOrderObj->id,
  1117. 'ref' => $preOrderObj->ref,
  1118. ];
  1119. } else {
  1120. ApiBbusLog::eventLog(json_encode(['error' => $preOrderObj->errors]));
  1121. ApiBbusLog::eventLog("Unsaved event: " . $fk_event);
  1122. throw new RestException(401, 'Unsaved event: ' . $fk_event);
  1123. }
  1124. }
  1125. }
  1126. return $createdPreOrderOBJ;
  1127. }
  1128. /**
  1129. * Get all free spaces on a selected date
  1130. *
  1131. * Return an array with details
  1132. *
  1133. * @return array|mixed data without useless information
  1134. *
  1135. * @param int fk_event
  1136. * @param int reservations
  1137. *
  1138. * @url POST nolocalemptyspaces
  1139. *
  1140. * @throws RestException 401 Not allowed
  1141. * @throws RestException 404 Not found
  1142. */
  1143. public function nolocalemptyspaces($fk_event, $reservations)
  1144. {
  1145. $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
  1146. INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1147. WHERE ac.id = {$fk_event}";
  1148. $result = $this->db->query($sql);
  1149. if ($this->db->num_rows($result) == 0) {
  1150. return '{"result":1}';
  1151. }
  1152. while ($row = $this->db->fetch_object($result)) {
  1153. if ($row->participants >= $row->max_num) {
  1154. return '{"result":1}';
  1155. }
  1156. if ($row->participants + $reservations > $row->max_num + $row->buffer) {
  1157. return '{"result":1}';
  1158. }
  1159. }
  1160. return '{"result":0}';
  1161. }
  1162. /**
  1163. * Validate and save invoice
  1164. *
  1165. * Return an array with details
  1166. *
  1167. * @return array|mixed data without useless information
  1168. *
  1169. * @param string $sendId sendID
  1170. * @param array $payment Invoice payment
  1171. * @param array $preorder preorder
  1172. * @param array $invoice Invoice
  1173. * @param string $cardPaymentLog Card payment log data
  1174. *
  1175. * @url POST localvalidateandsaveinvoice
  1176. * @access protected
  1177. * @throws RestException 401 Not allowed
  1178. * @throws RestException 404 Not found
  1179. * @throws RestException 506 No available spaces
  1180. *
  1181. */
  1182. public function localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId)
  1183. {
  1184. global $user, $db;
  1185. $createdInvoiceData = [];
  1186. $apiInvoiceHelper = new ApiInvoiceHelper;
  1187. $bbusApi = new BBus();
  1188. foreach ($preorder as $order) {
  1189. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$order}";
  1190. //print $sql . "\r\n";
  1191. $data = $db->query($sql);
  1192. if ($db->num_rows($data) > 0) {
  1193. while ($row = $db->fetch_object($data)) {
  1194. //print_r($row);
  1195. $lines = $apiInvoiceHelper->getProductLines($row->fk_product);
  1196. $createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '');
  1197. $createdInvoiceData[] = $createdInvoiceArray;
  1198. $bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray['invoice']['id']);
  1199. $this->updateBbticket($bookingHistory, $createdInvoiceArray['invoice']);
  1200. $this->deletePreorder($preorder);
  1201. }
  1202. }
  1203. }
  1204. return $createdInvoiceData;
  1205. }
  1206. /**
  1207. * Get back the product_id and event_id from llx_booking_preorder
  1208. *
  1209. * Return an array with details
  1210. *
  1211. * @return array|mixed data without useless information
  1212. *
  1213. * @param int $rowid preorder->rowid
  1214. *
  1215. * @url POST localpreorderarray
  1216. * @access protected
  1217. * @throws RestException 401 Not allowed
  1218. * @throws RestException 404 Not found
  1219. * @throws RestException 506 No available spaces
  1220. *
  1221. */
  1222. public function localpreorderarray(int $rowid)
  1223. {
  1224. global $user, $db;
  1225. $result = [];
  1226. $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
  1227. $data = $db->query($sql);
  1228. if ($db->num_rows($data) > 0) {
  1229. while ($row = $db->fetch_object($data)) {
  1230. $result = $row;
  1231. }
  1232. }
  1233. return $result;
  1234. }
  1235. /**
  1236. * Create BBticket record
  1237. *
  1238. * Return an array with details
  1239. *
  1240. * @return array|mixed data without useless information
  1241. *
  1242. * @param string $product_id
  1243. * @param string $datec
  1244. * @param string $facture_id
  1245. *
  1246. * @url POST createbbticket
  1247. * @access protected
  1248. * @throws RestException 401 Not allowed
  1249. * @throws RestException 404 Not found
  1250. * @throws RestException 506 No available spaces
  1251. *
  1252. */
  1253. public function createbbticket(string $product_id, string $datec, string $facture_id)
  1254. {
  1255. global $db;
  1256. $sql = "SELECT validperiod, occasions FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $product_id;
  1257. $result = $db->query($sql);
  1258. while ($sqlDataResult = $db->fetch_array($result)) {
  1259. $validperiod = $sqlDataResult['validperiod'] ? $sqlDataResult['validperiod'] : 366;
  1260. $occasions = $sqlDataResult['occasions'];
  1261. }
  1262. $curlGroup = 10000;
  1263. $ticket = new BbTicket($db);
  1264. $ticket->fk_facture = null;
  1265. $ticket->bundle_id = $product_id;
  1266. $ticket->usable_occasions = $occasions;
  1267. $ticket->usage = '0';
  1268. $ticket->available_at = $this->getAvailableAtDate($datec, $validperiod);
  1269. $ticket->ticket_id = $product_id;
  1270. $ticket->fk_settlements_group_id = $curlGroup;
  1271. $ticket->invoice_number = $facture_id;
  1272. if ($ticket->create($this->user) == -1) {
  1273. dol_syslog("Nem sikerult a ticketek mentese");
  1274. }
  1275. return true;
  1276. }
  1277. private function getAvailableAtDate($date, $validperiod)
  1278. {
  1279. $available_at = date('Y-m-d H:i:s', strtotime($date . ' +' . $validperiod . ' days'));
  1280. return $available_at;
  1281. }
  1282. #-------------------------------------------------
  1283. # CURL
  1284. #-------------------------------------------------
  1285. /**
  1286. * Update data in BBticket
  1287. *
  1288. * Return an array with details
  1289. *
  1290. * @return array|mixed data without useless information
  1291. *
  1292. * @param string $fk_booking_history //selected evet from llx_event
  1293. * @param array $invoice //facture rowid from llx_facture
  1294. *
  1295. * @url POST curlUpdateBbticket
  1296. * @throws RestException 401 Not allowed
  1297. * @throws RestException 404 Not found
  1298. */
  1299. public function curlUpdateBbticket($fk_booking_history, $invoice)
  1300. {
  1301. global $user;
  1302. $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE invoice_number = '{$invoice['id']}'";
  1303. $data = $this->db->query($sql);
  1304. if ($this->db->num_rows($data) > 0) {
  1305. while ($row = $this->db->fetch_object($data)) {
  1306. $sql = "UPDATE llx_bbus_bbticket
  1307. SET booking_history_id = {$fk_booking_history}, invoice_number = '{$invoice['ref']}'
  1308. WHERE rowid = {$row->rowid}";
  1309. $this->db->query($sql);
  1310. }
  1311. }
  1312. }
  1313. /**
  1314. * delete preorderrecord
  1315. *
  1316. * Return an array with details
  1317. *
  1318. * @return array|mixed data without useless information
  1319. *
  1320. * @param string $preorder_id //selected evet from llx_event
  1321. *
  1322. * @url POST curlDeletePreorder
  1323. * @throws RestException 401 Not allowed
  1324. * @throws RestException 404 Not found
  1325. */
  1326. public function curlDeletePreorder($preorder_id)
  1327. {
  1328. $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$preorder_id}";
  1329. $this->db->query($sql);
  1330. }
  1331. /**
  1332. * Create BBticket record
  1333. *
  1334. * Return an array with details
  1335. *
  1336. * @return array|mixed data without useless information
  1337. *
  1338. * @param string $product_id
  1339. * @param string $datec
  1340. * @param string $ref
  1341. *
  1342. * @url POST createbbticketmultiprinting
  1343. * @access protected
  1344. * @throws RestException 401 Not allowed
  1345. * @throws RestException 404 Not found
  1346. * @throws RestException 506 No available spaces
  1347. *
  1348. */
  1349. public function createbbticketmultiprinting(string $product_id, string $datec, string $ref)
  1350. {
  1351. global $db;
  1352. $sql = "SELECT validperiod, occasions FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $product_id;
  1353. $result = $db->query($sql);
  1354. while ($sqlDataResult = $db->fetch_array($result)) {
  1355. $validperiod = $sqlDataResult['validperiod'] ? $sqlDataResult['validperiod'] : 366;
  1356. $occasions = $sqlDataResult['occasions'];
  1357. }
  1358. $curlGroup = 10000;
  1359. $ticket = new BbTicket($db);
  1360. $ticket->fk_facture = null;
  1361. $ticket->bundle_id = $product_id;
  1362. $ticket->usable_occasions = $occasions;
  1363. $ticket->usage = '0';
  1364. $ticket->available_at = $this->getAvailableAtDate($datec, $validperiod);
  1365. $ticket->ticket_id = $product_id;
  1366. $ticket->fk_settlements_group_id = $curlGroup;
  1367. $ticket->invoice_number = $ref;
  1368. if ($ticket->create($this->user) == -1) {
  1369. dol_syslog("Nem sikerult a ticketek mentese");
  1370. }
  1371. $array['id'] = $ticket->id;
  1372. $array['ticket_id'] = $ticket->ticket_id;
  1373. return $array;
  1374. }
  1375. }