| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580 |
- <?php
- /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
- * Copyright (C) 2023 Deák Ferenc
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- use Luracast\Restler\RestException;
- // dol_include_once('/booking/class/bookinglog.class.php');
- require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus.class.php';
- require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
- require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiinvoicehelper.class.php';
- require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiproductlisthelper.class.php';
- require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
- require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
- require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
- require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';
- /**
- * \file booking/class/api_booking.class.php
- * \ingroup booking
- * \brief File for API management of bookinglog.
- */
- /**
- * API class for booking bookinglog
- *
- * @class DolibarrApiAccess {@requires user,external}
- */
- class BookingApi extends DolibarrApi
- {
- use CurlApi;
- /**
- * @var BookingLog $bookinglog {@type BookingLog}
- */
- public $bookinglog;
- private User $user;
- /**
- * Constructor
- *
- * @url GET /
- *
- */
- public function __construct()
- {
- global $db, $user;
- $this->db = $db;
- $this->user = $user;
- // $this->bookinglog = new BookingLog($this->db);
- }
- //P4NR6zhWHage
- //!!!types:
- /**
- * Get types of a bookable events
- *
- * Return an array with bookable events type list
- *
- * @return array|mixed data without useless information
- *
- * @url GET types
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function types()
- {
- dol_include_once('/eventwizard/class/eventdetails.class.php');
- $EventDetails = new EventDetails($this->db);
- return $EventDetails->fields['type']['arrayofkeyval'];
- if (!DolibarrApiAccess::$user->rights->booking->types->read) {
- throw new RestException(401);
- }
- // dol_include_once('/booking/class/bookinglog.class.php');
- // $result = $this->bookinglog->fetch($id);
- // if (!$result) {
- // throw new RestException(404, 'BookingLog not found');
- // }
- // if (!DolibarrApi::_checkAccessToResource('bookinglog', $this->bookinglog->id, 'booking_bookinglog')) {
- // throw new RestException(401, 'Access to instance id='.$this->bookinglog->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
- // }
- // return $this->_cleanObjectDatas($this->bookinglog);
- }
- /**
- * Get bookable events
- *
- * Return an array with bookable events list
- *
- * @return array|mixed data without useless information
- *
- * @param int $onlyBookable
- * @param int $withDetails
- * @param int $withDates
- * @param int $withAviability
- * @url GET events
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function events($onlyBookable = 1, $withDetails = 0, $withDates = 0, $withAviability = 0)
- {
- global $db, $conf;
- // if (!DolibarrApiAccess::$user->rights->booking->events->read) {
- // throw new RestException(401);
- // }
- $obj_ret = [];
- // if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
- // throw new RestException(401, "Insufficient rights to read events");
- // }
- $sql = "SELECT DISTINCT ed.rowid as id";
- if (!empty($conf->societe->enabled)) {
- // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
- // $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)
- // }
- }
- $sql .= " ,ed.label ";
- $sql .= " ,eld.label as from"; //... ??
- $sql .= " ,ela.label as to"; //...
- $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as t";
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventdetails ed ON ed.rowid = t.fk_element";
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation eld ON eld.rowid = ed.fk_elventlocation_departure";
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation ela ON ela.rowid = ed.fk_elventlocation_arrival";
- $sql .= " WHERE code = 'AC_EVENT' ";
- $sql .= " AND t.elementtype = 'eventdetails@eventwizard'";
- if ($onlyBookable) {
- $sql .= " AND t.datep > CURRENT_TIMESTAMP";
- }
- $result = $this->db->query($sql);
- if ($result) {
- $i = 0;
- // $num = $this->db->num_rows($result);
- // $min = min($num, ($limit <= 0 ? $num : $limit));
- while ($event = $this->db->fetch_object($result)) {
- if ($withDetails) {
- $event->details = $this->details($event->id);
- }
- if ($withDates) {
- //... $withAviability
- $event->dates = $this->dates($event->id);
- }
- $obj_ret[] = $event;
- }
- } else {
- throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
- }
- if (!count($obj_ret)) {
- throw new RestException(404, 'No Agenda Event found');
- }
- return $obj_ret;
- }
- /**
- * Get event dates
- *
- * Return an array with event dates list
- *
- * @return array|mixed data without useless information
- *
- * @param int $id
- * @param int $onlyBookable
- * @param string $json
- * @url GET dates
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function dates($id, $onlyBookable = 1, $json = null)
- {
- global $db, $conf;
- // if (!DolibarrApiAccess::$user->rights->booking->events->read) {
- // throw new RestException(401);
- // }
- $obj_ret = [];
- // if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
- // throw new RestException(401, "Insufficient rights to read events");
- // }
- $sql = "SELECT t.id ";
- if (!empty($conf->societe->enabled)) {
- // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
- // $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)
- // }
- }
- $sql .= " ,ed.label, t.note ";
- $sql .= " ,t.datep as start, t.datep2 as end";
- $sql .= " ,eld.label as from"; //... ??
- $sql .= " ,ela.label as to"; //...
- $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as t";
- // if (!empty($conf->societe->enabled)) {
- // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
- // $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
- // }
- // }
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventdetails ed ON ed.rowid = t.fk_element";
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation eld ON eld.rowid = ed.fk_elventlocation_departure";
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "eventwizard_eventlocation ela ON ela.rowid = ed.fk_elventlocation_arrival";
- // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventoption eo ON el.rowid = ed.fk_element";
- // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventproduct eo ON el.rowid = ed.fk_element";
- // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_ eo ON el.rowid = ed.fk_element";
- // $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
- $sql .= " WHERE code = 'AC_EVENT' ";
- $sql .= " AND t.fk_element = " . (int) $this->db->escape($id);
- $sql .= " AND t.elementtype = 'eventdetails@eventwizard'";
- $sql .= " AND t.datep > CURRENT_TIMESTAMP";
- // if (!empty($conf->societe->enabled)) {
- // if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
- // $sql .= " AND t.fk_soc = sc.fk_soc";
- // }
- // }
- // if ($user_ids) {
- // $sql .= " AND t.fk_user_action IN (".$this->db->sanitize($user_ids).")";
- // }
- // if ($socid > 0) {
- // $sql .= " AND t.fk_soc = ".((int) $socid);
- // }
- // Insert sale filter
- // if ($search_sale > 0) {
- // $sql .= " AND sc.fk_user = ".((int) $search_sale);
- // }
- // Add sql filters
- // if ($sqlfilters) {
- // $errormessage = '';
- // if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
- // throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
- // }
- // $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
- // $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
- // }
- // $sql .= $this->db->order($sortfield, $sortorder);
- // if ($limit) {
- // if ($page < 0) {
- // $page = 0;
- // }
- // $offset = $limit * $page;
- // $sql .= $this->db->plimit($limit + 1, $offset);
- // }
- $result = $this->db->query($sql);
- if ($result) {
- $i = 0;
- $num = $this->db->num_rows($result);
- // $min = min($num, ($limit <= 0 ? $num : $limit));
- while ($i < $num) {
- $obj_ret[] = $this->db->fetch_object($result);
- $i++;
- }
- } else {
- throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
- }
- if (!count($obj_ret)) {
- throw new RestException(404, 'No Agenda Event found');
- }
- return $obj_ret;
- }
- /**
- * Post booking (draft)
- *
- * Return an array with draft bookings list
- *
- * @return array|mixed data without useless information
- *
- * @param int $event
- * @param array $details
- * @url POST set
- *
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function set($event, $details)
- {
- if (!DolibarrApiAccess::$user->rights->booking->events->write) {
- throw new RestException(401);
- }
- }
- /**
- * Post booking validation
- *
- * Return an array with bookings list
- *
- * @return array|mixed data without useless information
- *
- * @param int $event
- * @param array $drafts
- * @url POST validate
- *
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function validate($event, $drafts)
- {
- if (!DolibarrApiAccess::$user->rights->booking->events->write) {
- throw new RestException(401);
- }
- }
- /**
- * Get bookings list
- *
- * Return an array with the user's bookings list
- *
- * @return array|mixed data without useless information
- *
- * @url POST bookings
- *
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function bookings()
- {
- if (!DolibarrApiAccess::$user->rights->booking->events->write) {
- throw new RestException(401);
- }
- }
- /**
- * Get cron to clean booking draftInvoices
- *
- * Return an array with cleaned list
- *
- * @return array|mixed data without useless information
- *
- * @url GET cron
- *
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function cron()
- {
- if (!DolibarrApiAccess::$user->rights->booking->events->write) {
- throw new RestException(401);
- }
- }
- /**
- * Get details of a bookable event
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $id
- * @url GET details
- *
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function details($id)
- {
- $details = [
- 'tmp' => [],
- 'product' => [],
- 'min' => 0,
- 'id_event' => $id,
- // 'variants' => []
- ];
- $variants = [];
- dol_include_once('/eventwizard/class/eventdetails.class.php');
- $EventDetails = new EventDetails($this->db);
- if ($EventDetails->fetch($id)) {
- $sql = "SELECT ep.rowid ,ep.fk_eventdetails, ep.fk_product, ep.type, ep.amount, ep.qty ";
- $sql .= " , p.label, p.price "; //price price_ttc price_min price_min_ttc
- $sql .= " FROM " . MAIN_DB_PREFIX . "eventwizard_eventproduct ep ";
- $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product p ON p.rowid = ep.fk_product ";
- // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination ac ON ac.fk_product_parent = ep.fk_product ";
- // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventoption eo ON eo.rowid = ep.fk_eventoption ";
- // $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."eventwizard_eventdetails ed ON ed.rowid = ep.fk_eventdetails ";
- $sql .= " WHERE ep.fk_eventdetails = " . (int) $this->db->escape($id);
- // return $sql;
- $result = $this->db->query($sql);
- if ($result) {
- $variants_ids = [];
- while ($d = $this->db->fetch_object($result)) {
- $variants_ids[] = $d->fk_product;
- // if(is_null($d->fk_product_child)){}
- $d->variants = [];
- // $d->minP = (is_null($d->amount))?(float)$d->price:(float)$d->amount;
- $details['tmp']['' . $d->fk_product] = $d;
- }
- $sql2 = "SELECT p.rowid, p.label, p.price ";
- $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
- $sql2 .= "FROM " . MAIN_DB_PREFIX . "product_attribute_combination ac ";
- $sql2 .= " LEFT JOIN " . MAIN_DB_PREFIX . "product p ON ac.fk_product_child = p.rowid ";
- $sql2 .= " WHERE ac.fk_product_parent IN (" . implode(",", $variants_ids) . ") ";
- $result2 = $this->db->query($sql2);
- if ($result2) {
- while ($v = $this->db->fetch_object($result2)) {
- $d = $details['tmp']['' . $v->fk_product_parent];
- $d->variants[] = $this->product2out($v);
- if (!is_null($d->amount)) { //... - ??? %?
- $d->minP = (float) $d->amount;
- } elseif (!isset($d->minP)) {
- $d->minP = $v->price;
- } elseif ($d->minP > $v->price) {
- $d->minP = $v->price;
- }
- $details['tmp']['' . $v->fk_product_parent] = $d;
- }
- }
- foreach ($details['tmp'] as $k => $v) {
- $p = $this->product2out($v);
- $p["minP"] = (is_null($v->amount)) ? (!isset($d->minP)) ? (float) $v->price : (float) $v->minP : (float) $v->amount;
- $p["variants"] = $v->variants;
- $details['product'][] = $p;
- if ($p["type"] == 1) {
- $details['min'] += $p["minP"];
- }
- }
- unset($details['tmp']);
- } else {
- throw new RestException(503, 'Error when retrieve Agenda Event list : ' . $this->db->lasterror());
- }
- // $EventDetails->getLinesArray();
- // print_r($EventDetails->lines);
- return $details;
- //$variations
- // $variations =
- }
- }
- protected function product2out($product)
- {
- return [
- "id" => $product->fk_product,
- "type" => $product->type, //1,2,3
- "fixed_price" => $product->amount,
- "max" => $product->qty,
- "label" => $product->label,
- "price" => $product->price,
- ];
- }
- /**
- * Get all products by type
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $type_id
- * @param string $from_date
- * @param string $to_date
- *
- * @url POST getallavailableproducts
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function getAllAvailableProducts(int $type_id, string $from_date, string $to_date)
- {
- $date = new DateTime($to_date);
- $date->modify('+1 day');
- $to_date = $date->format('Y-m-d');
- $TMPArray = [];
- $productsArray = [];
- $sql = "SELECT
- pr.rowid
- from llx_actioncomm as ac
- LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
- INNER JOIN llx_eventwizard_eventdetails as ed ON ed.rowid = ac.fk_element
- INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ed.rowid
- INNER JOIN llx_product as pr ON pr.rowid = ep.fk_product
- where ac.datep > '{$from_date} 00:00:00' AND ac.datep2 < '{$to_date} 00:00:00'
- AND ac.code = 'AC_EVENT'
- AND ed.type = {$type_id}
- AND ace.max_num - COALESCE(ace.participants, 0) > 1
- GROUP BY pr.rowid";
- $result = $this->db->query($sql);
- if ($this->db->num_rows($result) > 0) {
- while ($row = $this->db->fetch_object($result)) {
- $TMPArray[] = $row->rowid;
- }
- foreach ($TMPArray as $productItem) {
- $ApiProductListHelper = new ApiProductListHelper();
- $array = $ApiProductListHelper->list('t.ref', 'ASC', '', '', '', '', "(t.rowid:=:{$productItem})");
- $productsArray[] = $array[0];
- }
- }
- return $productsArray;
- }
- /**
- * First step of the eventhandling
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $type_id //selected evet from llx_event
- * @param int $fk_event //selected evet from llx_event
- * @param int $reservations //numbers of reservations
- * @param int $product_id //Product
- * @param string $sendId //ID
- *
- * @url POST firsteventstep
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function firstEventStep(int $type_id, int $fk_event, int $reservations, int $product_id, string $sendId)
- {
- global $conf;
- ApiBbusLog::appLog("{$sendId}: firstEventStep");
- if (!DolibarrApiAccess::$user->rights->facture->creer) {
- ApiBbusLog::appLog("{$sendId} Insufficient rights");
- throw new RestException(401, 'Insufficient rights');
- }
- $this->createLog($sendId, $fk_event, $reservations, $product_id);
- $server_host = $this->getServerHost($type_id);
- if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
- if ($this->noLocalEmptySpaces($fk_event, $reservations)) {
- throw new RestException(506, 'No available spaces');
- }
- ApiBbusLog::appLog("{$sendId}: firstEventStep: local");
- $createdPreOrderOBJ = $this->localcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id);
- } else {
- ApiBbusLog::appLog("{$sendId}: firstEventStep: curl");
- $params = compact('fk_event', 'reservations');
- $postFields = json_encode($params);
- $noavailableSpaces = json_decode($this->curlRunner('bookingapi/curlnoLocalEmptySpaces', $postFields, 'POST', true))->result;
- if ($noavailableSpaces) {
- ApiBbusLog::appLog("{$sendId}: firstEventStep: No available spaces");
- throw new RestException(506, 'No available spaces');
- }
- $params = compact('sendId', 'fk_event', 'reservations', 'product_id');
- $postFields = json_encode($params);
- $createdPreOrderOBJ = $this->curlRunner('bookingapi/localcreatedpreorderobj', $postFields, 'POST', true);
- }
- ApiBbusLog::appLog("{$sendId}: " . json_encode($createdPreOrderOBJ));
- return $createdPreOrderOBJ;
- }
- /**
- * Get all preorders
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string sendId
- * @param int fk_event
- * @param int reservations
- * @param int product_id
- *
- * @url POST localcreatedpreorderobj
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- function localcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
- {
- global $user;
- ApiBbusLog::appLog("{$sendId}: localcreatedpreorderobj");
- $apiInvoiceHelper = new ApiInvoiceHelper;
- $createdPreOrderOBJ = [];
- for ($i = 1; $i <= $reservations; $i++) {
- dol_include_once('/comm/action/class/actioncomm.class.php');
- dol_include_once('/custom/booking/class/preorder.class.php');
- $apiInvoiceHelper->increaseParticipant($fk_event);
- $lines = $apiInvoiceHelper->getProductLines($product_id);
- foreach ($lines as $line) {
- $preOrderObj = new PreOrder($this->db);
- $preOrderObj->ref = $this->generateRandomString();
- $preOrderObj->fk_event = $fk_event;
- $preOrderObj->fk_product = $product_id;
- $result = $preOrderObj->create($user);
- if ($result > 0) {
- $createdPreOrderOBJ[] = [
- 'id' => $preOrderObj->id,
- 'ref' => $preOrderObj->ref,
- ];
- } else {
- foreach ($preOrderObj->errors as $error) {
- ApiBbusLog::appLog("Error: " . $error);
- }
- ApiBbusLog::appLog("{$sendId}: Unsaved event: " . $fk_event);
- throw new RestException(401, 'Unsaved event: ' . $fk_event);
- }
- }
- }
- ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
- return $createdPreOrderOBJ;
- }
- function createLog($sendId, $fk_event, $reservations, $product_id)
- {
- /**
- * LOG SECTION
- */
- ApiBbusLog::eventLog("{$sendId} === NEW INVOICE ===");
- dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
- ApiBbusLog::eventLog("{$sendId} REQUEST: {$sendId}");
- dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
- ApiBbusLog::eventLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
- dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
- ApiBbusLog::eventLog("{$sendId} " . json_encode([
- 'fk_event' => $fk_event,
- 'reservations' => $reservations,
- 'product_id' => $product_id,
- 'sendId' => $sendId,
- ]));
- }
- function generateRandomString($length = 10)
- {
- $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $charactersLength = strlen($characters);
- $randomString = '';
- for ($i = 0; $i < $length; $i++) {
- $randomString .= $characters[rand(0, $charactersLength - 1)];
- }
- return $randomString;
- }
- /**
- * Save event data in Bookinghistory
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $fk_event //selected evet from llx_event
- *
- * @url POST saveeventdata
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function saveEventData($fk_event, $fk_facture = null, $fk_eventproduct = null, $ref = null)
- {
- ApiBbusLog::appLog("saveEventData");
- dol_include_once('/custom/booking/class/bookinghistory.class.php');
- dol_include_once('/comm/action/class/actioncomm.class.php');
- $actionCommObj = new ActionComm($this->db);
- $sql = "SELECT fk_element, datep, datep2 FROM " . MAIN_DB_PREFIX . $actionCommObj->table_element . " WHERE id = {$fk_event}";
- ApiBbusLog::appLog("{$sql}");
- $result = $this->db->query($sql);
- if ($this->db->num_rows($result) > 0) {
- $row = $this->db->fetch_object($result);
- $BookingHistory = new BookingHistory($this->db);
- $BookingHistory->fk_event = $fk_event;
- $BookingHistory->fk_facture = $fk_facture;
- $BookingHistory->fk_event_detail = $row->fk_element;
- $BookingHistory->fk_eventproduct = $fk_eventproduct;
- $BookingHistory->date_start = strtotime($row->datep);
- $BookingHistory->date_end = strtotime($row->datep2);
- $BookingHistory->invoice_number = $ref;
- $result = $BookingHistory->create($this->user);
- if ($result > 0) {
- ApiBbusLog::appLog("saveEventData: OK {$BookingHistory->id}");
- return $BookingHistory->id;
- } else {
- foreach ($BookingHistory->errors as $error) {
- ApiBbusLog::appLog("saveEventData: {$error}");
- }
- ApiBbusLog::appLog("saveEventData: ERROR");
- throw new RestException(401, 'Unsaved');
- }
- } else {
- throw new RestException(401, 'No Event record');
- }
- }
- /**
- * Validate and save invoice
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $type_id Type_id
- * @param string $sendId sendID
- * @param array $payment Invoice payment
- * @param array $preorder preorder
- * @param array $invoice Invoice
- * @param string $cardPaymentLog Card payment log data
- *
- * @url POST validateandsaveinvoice
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function validateandsaveinvoice(int $type_id, string $sendId, array $payment, array $preorder, array $invoice, string $cardPaymentLog = '')
- {
- ApiBbusLog::appLog("validateandsaveinvoice");
- global $db, $conf;
- $server_host = $this->getServerHost($type_id);
- $createdInvoiceArray = $this->localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId, $server_host, $type_id);
- if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
- ApiBbusLog::appLog("validateandsaveinvoice: local");
- ApiBbusLog::appLog(json_encode($preorder));
- foreach ($preorder as $order) {
- $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$order}";
- ApiBbusLog::appLog("{$sql}");
- $data = $db->query($sql);
- if ($db->num_rows($data) > 0) {
- while ($row = $db->fetch_object($data)) {
- ApiBbusLog::appLog("while");
- $bookingHistory = $this->saveEventData((int)$row->fk_event, $createdInvoiceArray[0]['invoice']['id'], null, $createdInvoiceArray[0]['invoice']['ref']);
- ApiBbusLog::appLog("______________________________________________________________________________");
- $this->updateBbticket($createdInvoiceArray[0]['invoice'], $bookingHistory);
- $this->deletePreorder($preorder);
- }
- }
- }
- } else {
- ApiBbusLog::appLog("validateandsaveinvoice: curl");
- /* #-------------- UPDATE BTICKET --------------
- ApiBbusLog::appLog("{$sendId}: Update bbticket with curl");
- $invoiceForCurl['id'] = $createdInvoiceArray[0]['invoice']['id'];
- $invoiceForCurl['ref'] = $createdInvoiceArray[0]['invoice']['ref'];
- $array['fk_booking_history'] = null;
- $array['invoice'] = $invoiceForCurl;
- $updateBBticketPostFields = json_encode($array);
- ApiBbusLog::appLog("{$updateBBticketPostFields}");
- $this->curlRunner('bookingapi/curlUpdateBbticket', $updateBBticketPostFields, 'POST', true); */
- foreach ($preorder as $rowid) {
- $params = compact('rowid');
- $postFields = json_encode($params);
- $preorderArray = $this->curlRunner('bookingapi/curllocalpreorderarray', $postFields, 'POST', true);
- $saveEventdataPostFields = '{"fk_event":"' . (int)$preorderArray->fk_event . '","ref":"' . $createdInvoiceArray[0]['invoice']['ref'] . '","fk_facture":"' . null . '","fk_eventproduct":"' . null . '"}';
- $bookingHistory = $this->curlRunner('bookingapi/saveEventData', $saveEventdataPostFields, 'POST', true);
- $array['fk_booking_history'] = $bookingHistory;
- $array['invoice'] = $createdInvoiceArray[0]['invoice'];
- $updateBBticketPostFields = json_encode($array);
- $this->curlRunner('bookingapi/curlUpdateBbticket', $updateBBticketPostFields, 'POST', true);
- ApiBbusLog::appLog("validateandsaveinvoice: {$postFields}");
- $this->curlRunner('bookingapi/curlDeletePreorder', $postFields, 'POST', true);
- }
- }
- ApiBbusLog::appLog("validateandsaveinvoice: END");
- return $createdInvoiceArray;
- }
- public function localValidateAndSaveInvoice($invoice, $preorder, $payment, $cardPaymentLog, $sendId, $server_host, $type_id)
- {
- ApiBbusLog::appLog("localValidateAndSaveInvoice");
- global $user, $db, $conf;
- $server_host_curl = false;
- $createdInvoiceData = [];
- $apiInvoiceHelper = new ApiInvoiceHelper;
- $bbusApi = new BBus();
- foreach ($preorder as $rowid) {
- $params = compact('rowid');
- $postFields = json_encode($params);
- if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
- ApiBbusLog::appLog("localValidateAndSaveInvoice: local");
- $preorderArray = $this->localpreorderarray($rowid);
- } else {
- ApiBbusLog::appLog("localValidateAndSaveInvoice: curl");
- if ($type_id != 5 || $type_id != 3 || $type_id != 4) {
- $server_host_curl = true;
- }
- $preorderArray = $this->curlRunner('bookingapi/curllocalpreorderarray', $postFields, 'POST', true);
- }
- $lines = $apiInvoiceHelper->getProductLinesWithoutDiscount($preorderArray->fk_product);
- //$lines = $apiInvoiceHelper->createLinesForCrossShopping($preorderArray->fk_product);
- $createdInvoiceArray = $bbusApi->invoice($invoice, $lines, $payment, $cardPaymentLog = '', $sendId = '', $server_host_curl);
- $createdInvoiceData[] = $createdInvoiceArray;
- }
- ApiBbusLog::appLog("Visszaküld");
- $asd = json_encode($createdInvoiceData);
- ApiBbusLog::appLog("{$asd}");
- return $createdInvoiceData;
- }
- public function localpreorderarray(int $rowid)
- {
- global $user, $db;
- $result = [];
- $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
- $data = $db->query($sql);
- if ($db->num_rows($data) > 0) {
- while ($row = $db->fetch_object($data)) {
- $result = $row;
- }
- }
- return $result;
- }
- /**
- * curllocalpreorderarray
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $rowid
- *
- * @url POST curllocalpreorderarray
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function curllocalpreorderarray(int $rowid)
- {
- global $user, $db;
- $result = [];
- $sql = "SELECT fk_product, fk_event FROM llx_booking_preorder WHERE rowid = {$rowid}";
- $data = $db->query($sql);
- if ($db->num_rows($data) > 0) {
- while ($row = $db->fetch_object($data)) {
- $result = $row;
- }
- }
- return $result;
- }
- public function updateBbticket($invoice, $fk_booking_history = null)
- {
- ApiBbusLog::appLog("updateBbticket_________START");
- global $user;
- $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE fk_facture = {$invoice['id']}";
- ApiBbusLog::appLog("{$sql}");
- $data = $this->db->query($sql);
- if (!empty($this->db->error())) {
- ApiBbusLog::appLog("{$this->db->error()}");
- throw new RestException(401, "{$this->db->error()}");
- }
- $addedsql = $fk_booking_history == null ? "" : " booking_history_id = {$fk_booking_history},";
- if ($this->db->num_rows($data) > 0) {
- while ($row = $this->db->fetch_object($data)) {
- $sql = "UPDATE llx_bbus_bbticket
- SET {$addedsql} invoice_number = '{$invoice['ref']}'
- WHERE rowid = {$row->rowid}";
- ApiBbusLog::appLog("{$sql}");
- $this->db->query($sql);
- }
- } else {
- ApiBbusLog::appLog("{$this->db->error()}");
- ApiBbusLog::appLog("api_booking (Excelia): updateBbticket error");
- }
- }
- /**
- * curlupdateBbticket
- *
- * Return an array with details
- *
- *
- * @param array $invoice invoice
- *
- * @url POST curlupdateBbticket
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function curlupdateBbticket(array $invoice, $fk_booking_history = null)
- {
- global $user;
- ApiBbusLog::appLog("curlupdateBbticket______START");
- $sql = "SELECT rowid FROM llx_bbus_bbticket WHERE invoice_number = '{$invoice['id']}' OR invoice_number = '{$invoice['ref']}'";
- ApiBbusLog::appLog("{$sql}");
- $data = $this->db->query($sql);
- if (!empty($this->db->error())) {
- ApiBbusLog::appLog("{$this->db->error()}");
- throw new RestException(401, "{$this->db->error()}");
- }
- if ($this->db->num_rows($data) > 0) {
- while ($row = $this->db->fetch_object($data)) {
- $booking_history_id = is_null($fk_booking_history) ? 'booking_history_id = null,' : 'booking_history_id = ' . $fk_booking_history . ',';
- $sql = "UPDATE llx_bbus_bbticket
- SET {$booking_history_id} invoice_number = '{$invoice['ref']}'
- WHERE rowid = {$row->rowid}";
- ApiBbusLog::appLog("{$sql}");
- $this->db->query($sql);
- }
- } else {
- ApiBbusLog::appLog("api_booking: curlupdateBbticket error");
- ApiBbusLog::appLog("{$this->db->error()}");
- throw new RestException(401, 'api_booking: curlupdateBbticket error');
- }
- }
- public function deletePreorder($preorder)
- {
- foreach ($preorder as $item) {
- $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
- $this->db->query($sql);
- }
- }
- /**
- * curldeletePreorder
- *
- * Return an array with details
- *
- *
- * @param array $preorder preorder
- *
- * @url POST curldeletePreorder
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function curldeletePreorder($preorder)
- {
- foreach ($preorder as $item) {
- $sql = "DELETE FROM llx_booking_preorder WHERE rowid = {$item}";
- $this->db->query($sql);
- }
- }
- public function eventErasuer()
- {
- global $user;
- $limitDate = date("Y-m-d H:i:s", dol_now() - 1200);
- $sql = "SELECT * FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
- //print $sql;exit;
- $data = $this->db->query($sql);
- if ($this->db->num_rows($data) > 0) {
- while ($row = $this->db->fetch_object($data)) {
- //print_r($row);
- $actioncommObj = new ActionComm($this->db);
- $resultActionComm = $actioncommObj->fetch($row->fk_event);
- $actioncommObj->array_options['options_participants'] = $actioncommObj->array_options['options_participants'] - 1;
- $actioncommObj->update($user);
- }
- //exit;
- $sqlDelete = "DELETE FROM llx_booking_preorder WHERE date_creation < '{$limitDate}'";
- $dataDelete = $this->db->query($sqlDelete);
- }
- }
- /**
- * Increase Participants
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $event_id //rowid of evet from llx_event
- *
- * @url POST increaseparticipant
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function increaseParticipant(int $event_id)
- {
- dol_include_once('/comm/action/class/actioncomm.class.php');
- global $user;
- $actionComObj = new ActionComm($this->db);
- $actionComObj->fetch($event_id);
- $max_num = (int) $actionComObj->array_options['options_max_num'];
- $buffer = (int) $actionComObj->array_options['options_buffer'];
- $participants = (int) $actionComObj->array_options['options_participants'];
- $increasedParticipants = $participants + 1;
- if ($increasedParticipants > ($max_num + $buffer)) {
- return 'full';
- } elseif (($increasedParticipants > $max_num) && ($increasedParticipants <= ($max_num + $buffer))) {
- $actionComObj->array_options['options_participants'] = $increasedParticipants;
- $actionComObj->update($user);
- return 'Buffer';
- } else {
- $actionComObj->array_options['options_participants'] = $increasedParticipants;
- $actionComObj->update($user);
- return 'OK';
- }
- }
- /**
- * Reduce Participants
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $event_id //rowid of evet from llx_event
- *
- * @url POST reduceparticipant
- *
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function reduceParticipant(int $event_id)
- {
- global $user;
- dol_include_once('/comm/action/class/actioncomm.class.php');
- $actionComObj = new ActionComm($this->db);
- $actionComObj->fetch($event_id);
- $participants = (int) $actionComObj->array_options['options_participants'];
- $reducedParticipants = $participants - 1;
- $actionComObj->array_options['options_participants'] = $reducedParticipants < 0 ? 0 : $reducedParticipants;
- $actionComObj->update($user);
- return 'OK';
- }
- /**
- * Create invoice
- *
- * @param array $invoice Invoice data
- * @param array $lines Invoice lines
- * @param array $payment Invoice payment
- * @param string $eventid Event ID
- * @param string $cardPaymentLog Card payment log data
- *
- * @access protected
- * @return array|mixed Data without useless information
- *
- * @url POST /invoice
- */
- public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $eventid = '', string $sendId = '')
- {
- if (empty($sendId)) {
- $sendId = substr(md5(rand()), 0, 8);
- }
- /**
- * LOG SECTION
- */
- ApiBbusLog::appLog("{$sendId} === NEW INVOICE ===");
- dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
- ApiBbusLog::appLog("{$sendId} REQUEST: {$sendId}");
- dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
- ApiBbusLog::appLog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})");
- dol_syslog("{$sendId} User: {$this->user->firstname} {$this->user->lastname} (ID: {$this->user->id})", LOG_INFO, 0);
- ApiBbusLog::appLog("{$sendId} " . json_encode([
- 'invoice' => $invoice,
- 'lines' => $lines,
- 'payment' => $payment,
- 'eventid' => $eventid,
- 'cardPaymentLog' => $cardPaymentLog
- ]));
- /**
- * CHECK RIGHTS
- */
- if (!DolibarrApiAccess::$user->rights->facture->creer) {
- ApiBbusLog::appLog("{$sendId} Insufficient rights");
- throw new RestException(401, 'Insufficient rights');
- }
- $apiInvoiceHelper = new ApiInvoiceHelper;
- /**
- * handle invoice basic data
- */
- $invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId);
- /**
- * handle invoice line(s)
- */
- $products = [];
- //print $eventid;exit;
- foreach ($lines as $line) {
- $invoiceObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
- $this->increaseParticipant((int) $eventid);
- $product = $apiInvoiceHelper->loadProductToResult($line);
- if (!empty($product)) {
- $products[] = $product;
- }
- }
- $invoiceObj->fetch_lines();
- foreach ($products as &$row) {
- foreach ($invoiceObj->lines as $line) {
- if ($line->product_ref == $row['ref']) {
- //$row['price'] = $line->total_ttc;
- $row['price'] = $line->multicurrency_total_ttc;
- $row['total_tva'] = $line->total_tva;
- //$row['total_tva'] = $line->multicurrency_total_tva;
- }
- }
- }
- return [
- 'sendId' => $sendId,
- 'invoice' => [
- 'id' => $invoiceObj->id,
- 'ref' => $invoiceObj->ref,
- 'total' => $invoiceObj->multicurrency_total_ttc
- ],
- 'products' => $products,
- ];
- }
- /**
- * Get all free spaces on a selected date
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int type_id
- * @param string date_from
- * @param string date_to
- * @param int product_id
- * @param int participant_number
- *
- * @url POST getavailablespaces
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function getAvailableSpaces(int $type_id, string $date_from, string $date_to, int $product_id, int $participant_number)
- {
- global $conf;
- $server_host = $this->getServerHost($type_id);
- if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
- ApiBbusLog::appLog("getAvailableSpaces: local");
- return $this->localAvailablePlaces($date_from, $date_to, $product_id, $participant_number);
- } else {
- ApiBbusLog::appLog("getAvailableSpaces: curl");
- $params = compact('date_from', 'date_to', 'product_id', 'participant_number');
- $postFields = json_encode($params);
- return $this->curlRunner('bookingapi/localavailableplaces', $postFields, 'POST', true);
- }
- }
- /* private function getServerHost($type_id)
- {
- $basicServices = new BasicServices($this->db);
- $resultBS = $basicServices->fetch($type_id);
- return $basicServices->server_host;
- } */
- /**
- * Get all free spaces on a selected date
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string date_from
- * @param string date_to
- * @param int product_id
- * @param int participant_number
- *
- * @url POST localavailableplaces
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function localavailableplaces($date_from, $date_to, $product_id, $participant_number)
- {
- ApiBbusLog::appLog("localAvailablePlaces");
- $array = [];
- $date = new DateTime($date_to);
- $date->modify('+1 day');
- $date_to = $date->format('Y-m-d');
- $date_from = $this->getCutOffTimeDate($product_id);
- $sql = "SELECT
- ac.id,
- ac.datep,
- ace.max_num,
- ace.participants,
- ace.buffer
- FROM llx_actioncomm as ac
- LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
- INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
- INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
- WHERE ac.code = 'AC_EVENT'
- AND ep.fk_product = {$product_id}
- AND ac.datep > '{$date_from}'
- AND ac.datep2 < '{$date_to} 00:00:00'
- ORDER BY ac.datep ASC";
- $result = $this->db->query($sql);
- while ($row = $this->db->fetch_object($result)) {
- $max_num = $row->max_num;
- $buffer = $row->buffer;
- $participants = $row->participants;
- $date = strtotime($row->datep);
- $element['event_id'] = $row->id;
- //$element['date'] = date("Y-m-d", $date);
- //$element['time'] = date("H:i", $date);
- $element['participants'] = is_null($participants) ? 0 : (int) $participants;
- $element['max_num'] = $max_num;
- $element['buffer'] = $buffer;
- if ($max_num > $participants) {
- if ($max_num + $buffer > $participants + $participant_number) {
- $array[date("Y-m-d", $date)][date("H:i", $date)] = $element;
- }
- }
- }
- return $array;
- }
- /**
- * localCheckAvailablePlaces
- * *
- * @return array|mixed data without useless information
- *
- * @param int product_id
- *
- * @url POST localCheckAvailablePlaces
- *
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- */
- public function localCheckAvailablePlaces($product_id)
- {
- $date_from = $this->getCutOffTimeDate($product_id);
- $sql = "SELECT
- ac.id,
- ac.datep,
- ace.max_num,
- ace.participants,
- ace.buffer
- FROM llx_actioncomm as ac
- LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
- INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
- INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
- WHERE ac.code = 'AC_EVENT'
- AND ep.fk_product = {$product_id}
- AND ac.datep > '{$date_from}'
- ORDER BY ac.datep ASC";
- $result = $this->db->query($sql);
- return $this->db->num_rows($result) > 0;
- }
- private function getCutOffTimeDate($product_id)
- {
- $date = date("Y-m-d H:i:s");
- ApiBbusLog::appLog("{$date}");
- $sql = "SELECT cut_off_time_app FROM llx_product_extrafields WHERE fk_object = {$product_id}";
- if ($result = $this->db->query($sql)) {
- if ($this->db->num_rows($result) > 0) {
- while ($row = $this->db->fetch_object($result)) {
- $cutOffTime = $row->cut_off_time_app;
- }
- $dateTimestamp = strtotime($date);
- $date = date("Y-m-d H:i:s", $dateTimestamp + $cutOffTime * 60);
- }
- }
- ApiBbusLog::appLog("{$date}");
- return $date;
- }
- private function noLocalEmptySpaces($event_id, $reservations)
- {
- $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
- INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
- WHERE ac.id = {$event_id}";
- $result = $this->db->query($sql);
- if ($this->db->num_rows($result) == 0) {
- return true;
- }
- while ($row = $this->db->fetch_object($result)) {
- if ($row->participants >= $row->max_num) {
- return true;
- }
- if ($row->participants + $reservations > $row->max_num + $row->buffer) {
- return true;
- }
- }
- return false;
- }
- /**
- * curlnoLocalEmptySpaces
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param int $fk_event
- * @param int $reservations
- *
- * @url POST curlnoLocalEmptySpaces
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function curlnoLocalEmptySpaces($fk_event, $reservations)
- {
- ApiBbusLog::appLog("curlnoLocalEmptySpaces");
- $sql = "SELECT ace.max_num, ace.buffer, ace.participants FROM llx_actioncomm as ac
- INNER JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
- WHERE ac.id = {$fk_event}";
- $result = $this->db->query($sql);
- if ($this->db->num_rows($result) == 0) {
- return true;
- }
- while ($row = $this->db->fetch_object($result)) {
- if ($row->participants >= $row->max_num) {
- return true;
- }
- if ($row->participants + $reservations > $row->max_num + $row->buffer) {
- return true;
- }
- }
- return false;
- }
- /**
- * curlcreatedpreorderobj
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string $sendId
- * @param int $fk_event
- * @param int $reservations
- * @param int $product_id
- *
- * @url POST curlcreatedpreorderobj
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- function curlcreatedpreorderobj($sendId, $fk_event, $reservations, $product_id)
- {
- ApiBbusLog::appLog("curlcreatedpreorderobj");
- $apiInvoiceHelper = new ApiInvoiceHelper;
- $createdPreOrderOBJ = [];
- for ($i = 1; $i <= $reservations; $i++) {
- dol_include_once('/comm/action/class/actioncomm.class.php');
- dol_include_once('/custom/booking/class/preorder.class.php');
- $apiInvoiceHelper->increaseParticipant($fk_event);
- $lines = $apiInvoiceHelper->getProductLines($product_id);
- foreach ($lines as $line) {
- $preOrderObj = new PreOrder($this->db);
- $preOrderObj->ref = $this->generateRandomString();
- $preOrderObj->fk_event = $fk_event;
- $preOrderObj->fk_product = $product_id;
- $result = $preOrderObj->create($this->user);
- if ($result > 0) {
- $createdPreOrderOBJ[] = [
- 'id' => $preOrderObj->id,
- 'ref' => $preOrderObj->ref,
- ];
- } else {
- ApiBbusLog::appLog(json_encode(['error' => $preOrderObj->errors]));
- ApiBbusLog::appLog("Unsaved event: " . $fk_event);
- throw new RestException(401, 'Unsaved event: ' . $fk_event);
- }
- }
- }
- ApiBbusLog::appLog(json_encode($createdPreOrderOBJ));
- return $createdPreOrderOBJ;
- }
- /**
- * Create BBticket record
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string $product_id
- * @param string $datec
- * @param string $facture_id
- *
- * @url POST createbbticket
- * @access protected
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function createbbticket(string $product_id, string $datec, string $facture_id)
- {
- global $db, $conf;
- $sql = "SELECT validperiod, occasions FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $product_id;
- $result = $db->query($sql);
- while ($sqlDataResult = $db->fetch_array($result)) {
- $validperiod = $sqlDataResult['validperiod'] ? $sqlDataResult['validperiod'] : 366;
- $occasions = $sqlDataResult['occasions'];
- }
- $ticket = new BbTicket($db);
- $ticket->fk_facture = null;
- $ticket->bundle_id = $product_id;
- $ticket->usable_occasions = $occasions;
- $ticket->usage = '0';
- $ticket->available_at = $this->getAvailableAtDate($datec, $validperiod);
- $ticket->ticket_id = $product_id;
- $ticket->fk_settlements_group_id = $conf->global->CURL_GROUP_ID;
- $ticket->invoice_number = $facture_id;
- if ($ticket->create($this->user) == -1) {
- dol_syslog("Nem sikerult a ticketek mentese");
- }
- return true;
- }
- private function getAvailableAtDate($date, $validperiod)
- {
- $available_at = date('Y-m-d H:i:s', strtotime($date . ' +' . $validperiod . ' days'));
- return $available_at;
- }
- /**
- * Get printed factures refs
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string $from
- * @param string $to
- * @param string $factures
- *
- * @url POST getPrintedFacturesRefs
-
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function getPrintedFacturesRefs(string $from, string $to, string $factures = "")
- {
- $refs = "";
- if ($factures != "") {
- global $db, $conf;
- $curluser_id = $conf->global->CURL_USER_ID;
- $sql = "SELECT bbt.invoice_number
- FROM llx_bbus_bbticket as bbt
- INNER JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.ticket_id = bbt.rowid
- WHERE bbt.fk_user_creat = {$curluser_id} AND bbt.invoice_number IN ({$factures}) AND bbt.date_creation BETWEEN '{$from}' AND '{$to}' ORDER BY bbt.rowid DESC";
- $result = $db->query($sql);
- if ($db->num_rows($result) > 0) {
- while ($row = $db->fetch_object($result)) {
- if ($refs == "") {
- $refs .= "'" . $row->invoice_number . "'";
- } else {
- $refs .= ",'" . $row->invoice_number . "'";
- }
- }
- }
- }
- return $refs;
- }
- /**
- * Get printed factures refs in array
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string $from
- * @param string $to
- *
- * @url POST getPrintedFacturesRefsArray
-
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function getPrintedFacturesRefsArray(string $from, string $to, string $factures = '')
- {
- $refs = [];
- if ($factures !== '') {
- global $db, $conf;
- $curluser_id = $conf->global->CURL_USER_ID;
- $sql = "SELECT bbt.invoice_number
- FROM llx_bbus_bbticket as bbt
- INNER JOIN llx_bbus_bbticketinvoiceprinting as bbtip ON bbtip.ticket_id = bbt.rowid
- WHERE bbt.fk_user_creat = {$curluser_id} AND bbt.invoice_number IN ({$factures}) AND bbt.date_creation BETWEEN '{$from}' AND '{$to}' ORDER BY bbt.rowid DESC";
- $result = $db->query($sql);
- if ($db->num_rows($result) > 0) {
- while ($row = $db->fetch_object($result)) {
- $refs[] = $row->invoice_number;
- }
- }
- }
- return $refs;
- }
- /**
- * Get number of a facture's printer count
- *
- * Return an array with details
- *
- * @return array|mixed data without useless information
- *
- * @param string $invoice_number
- *
- * @url POST getFacturesNumberOfPrints
-
- * @throws RestException 401 Not allowed
- * @throws RestException 404 Not found
- * @throws RestException 506 No available spaces
- *
- */
- public function getFacturesNumberOfPrints(string $invoice_number)
- {
- $number = 0;
- global $db;
- $sql = "SELECT tip.fk_facture, tip.product_id, count(tip.product_id) FROM llx_bbus_bbticketinvoiceprinting as tip
- WHERE tip.invoice_number = '{$invoice_number}'
- GROUP BY tip.fk_facture, tip.product_id";
- $result = $db->query($sql);
- if ($db->num_rows($result) > 0) {
- while ($row = $db->fetch_object($result)) {
- $array[$row->fk_facture][$row->product_id] = $row->count;
- }
- $firstKey = array_key_first($array);
- $firstValue = $array[$firstKey];
- $number = reset($firstValue);
- }
- return $number;
- }
- }
|