api_bbus.class.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2019 Cedric Ancelin <icedo.anc@gmail.com>
  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. 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. use Sabre\Xml\Element;
  20. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  21. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php';
  22. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  23. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  24. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php';
  25. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttributeValue.class.php';
  26. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination.class.php';
  27. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination2ValuePair.class.php';
  28. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/sellproduct.class.php';
  29. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiuserhandler.class.php';
  30. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  31. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/jegy.class.php';
  32. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbloginlog.class.php';
  33. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbexchangerate.class.php';
  34. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticket.class.php';
  35. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbdevices.class.php';
  36. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbdevicesservicelocation.class.php';
  37. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbdevicesservicelocationproduct.class.php';
  38. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketinvoiceprinting.class.php';
  39. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/globalconst.class.php';
  40. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/emailtemplatehandler.php';
  41. include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
  42. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketnaplo.class.php';
  43. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbtickethandler.class.php';
  44. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/gpsposition.class.php';
  45. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/userloginnaplo.class.php';
  46. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/countryhandler.class.php';
  47. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/utils/entityhandler.class.php';
  48. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/discountnaplo.class.php';
  49. require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
  50. require_once DOL_DOCUMENT_ROOT . '/custom/rollerstorage/class/packagehistory.class.php';
  51. require_once DOL_DOCUMENT_ROOT . '/product/inventory/class/inventory.class.php';
  52. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiproductlisthelper.class.php';
  53. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/apiinvoicehelper.class.php';
  54. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/ticket_checker.class.php';
  55. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_helper.class.php';
  56. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_bbus_log.class.php';
  57. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbapilock.class.php';
  58. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/exchangerateupdater.class.php';
  59. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketvalidationcoords.class.php';
  60. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
  61. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/roller_handling.class.php';
  62. /**
  63. * API class for products
  64. *
  65. * @access protected
  66. * @class DolibarrApiAccess {@requires user,external}
  67. */
  68. class BBus extends DolibarrApi
  69. {
  70. use CurlApi;
  71. use RollerHandling;
  72. private $code;
  73. private $printingTime;
  74. private $status = 0;
  75. private $device_id;
  76. private $service_location_id;
  77. private $bbTicketRowId;
  78. private $facture_id;
  79. private $isValid = true;
  80. private User $user;
  81. const EMAIL_TEMPLATE = 'multiticketprinting';
  82. const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
  83. const GLOBAL_CONF_EMAIL_FROM = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL_FROM';
  84. public function __construct()
  85. {
  86. global $db, $conf, $user;
  87. $this->db = $db;
  88. $this->user = $user;
  89. }
  90. /**
  91. * First ticket validation
  92. *
  93. * @param string $code
  94. *
  95. * @return array|mixed Data without useless information
  96. *
  97. * @url POST search
  98. */
  99. public function search($code)
  100. {
  101. $this->checkUserReadPermission();
  102. global $user;
  103. $this->code = $code;
  104. $this->facture_id = $this->getFactureRowIdByFactureId();
  105. $sql = "SELECT bt.*, pr.ref as product_ref, pr.label as product_label, btp.printing_date, btp.printing_date_timestamp
  106. FROM llx_bbus_bbticketinvoiceprinting as btp
  107. INNER JOIN llx_bbus_bbticket AS bt ON bt.rowid = btp.ticket_id
  108. INNER JOIN llx_product AS pr ON pr.rowid = bt.ticket_id
  109. WHERE btp.fk_facture = {$this->facture_id}
  110. AND btp.printing_date = (
  111. SELECT MIN(printing_date)
  112. FROM llx_bbus_bbticketinvoiceprinting AS btp2
  113. WHERE btp2.fk_facture = {$this->facture_id}
  114. )";
  115. $ticketsData = $this->db->query($sql);
  116. while ($row = pg_fetch_assoc($ticketsData)) {
  117. $now = date("Y-m-d H:i:s");
  118. if ($row['usage'] == $row['usable_occasions'] && $row['usable_occasions'] != 0) {
  119. $this->isValid = false;
  120. }
  121. if ($row['available_at'] < $now || ((!is_null($row['expire_at']) && !empty($row['expire_at'])) && $row['expire_at'] < $now)) {
  122. $this->isValid = false;
  123. }
  124. $row['facture_ref'] = $code;
  125. $row['isValid'] = $this->isValid;
  126. $sub = [];
  127. foreach ($row as $key => $value) {
  128. $sub[$key] = $value;
  129. }
  130. $json[] = $sub;
  131. }
  132. return $json;
  133. }
  134. /**
  135. * Értékesítések
  136. *
  137. * @param date $date Date
  138. *
  139. *
  140. * @return array|mixed Data without useless information
  141. *
  142. * @url POST getsaleditems
  143. */
  144. public function getsaleditems($date = null)
  145. {
  146. global $user;
  147. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  148. throw new RestException(403);
  149. }
  150. //$date = isset($date) ? $date : date("Y-m-d");
  151. $date = date("Y-m-d");
  152. $apiBbusHelper = new ApiBBusHelper();
  153. $facturesArray = $apiBbusHelper->getSaledItems($date);
  154. return $apiBbusHelper->getSaledItemsArray($facturesArray);
  155. }
  156. /** LOG OK
  157. * Get properties of a product object by barcode
  158. *
  159. * Return an array with product information.
  160. *
  161. * @param string $code Facture ID and timestamp of printing
  162. *
  163. * @return array|mixed Data without useless information
  164. *
  165. * @url POST ticketinfos
  166. */
  167. public function getinfos($code)
  168. {
  169. global $user;
  170. $ticketChecker = new TicketChecker();
  171. ApiBbusLog::getinfosLog('=== NEW TICKETINFOS ===');
  172. ApiBbusLog::getinfosLog("User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  173. ApiBbusLog::getinfosLog("DOLAPIKEY: {$user->api_key}");
  174. $ticketsFromBbticketinvoiceprinting = [];
  175. $code_and_timstamp = explode('_', $code);
  176. $this->code = $code_and_timstamp[0];
  177. if (empty($this->code)) {
  178. ApiBbusLog::getinfosLog('Code or mac is empty!');
  179. ApiBbusLog::getinfosLog('=================');
  180. throw new RestException(404, 'Code or mac is empty!');
  181. }
  182. $this->printingTime = $code_and_timstamp[1];
  183. if (empty($this->printingTime)) {
  184. ApiBbusLog::getinfosLog('Timestamp is empty!');
  185. ApiBbusLog::getinfosLog('=================');
  186. throw new RestException(404, 'Timestamp is empty!');
  187. }
  188. if (!DolibarrApiAccess::$user->rights->bbus->ticket->validation) {
  189. ApiBbusLog::getinfosLog('No access: Ticket Validation!');
  190. ApiBbusLog::getinfosLog('=================');
  191. throw new RestException(403);
  192. }
  193. ApiBbusLog::getinfosLog("Code: {$this->code}");
  194. ApiBbusLog::getinfosLog("Code: {$this->printingTime}");
  195. //Kikeresem a facture_id-t
  196. $facture = new Facture($this->db);
  197. $sql = "SELECT * FROM " . $this->db->prefix() . $facture->table_element . " WHERE ref ILIKE '{$this->code}'";
  198. $factureResult = $this->db->query($sql);
  199. if (pg_num_rows($factureResult) < 1) {
  200. ApiBbusLog::getinfosLog('Invoice not found!');
  201. ApiBbusLog::getinfosLog('=================');
  202. throw new RestException(404, 'Invoice not found!');
  203. }
  204. while ($row = pg_fetch_assoc($factureResult)) {
  205. $selectedFacture_id = $row['rowid'];
  206. }
  207. ApiBbusLog::getinfosLog('Facture ID: ' . (string) $selectedFacture_id);
  208. $sql = "SELECT rowid FROM " . $this->db->prefix() . $facture->table_element . " WHERE fk_facture_source = {$selectedFacture_id} AND type = 2";
  209. $res = $this->db->query($sql);
  210. if (pg_num_rows($res) > 0) {
  211. ApiBbusLog::getinfosLog('Invoice has a Credit account!');
  212. ApiBbusLog::getinfosLog('=================');
  213. throw new RestException(404, 'Invoice has a Credit account.');
  214. }
  215. // Kikeresem az llx_bbus_bbticketinvoiceprinting táblából a timestamp-hez tartozo jegy Id(ka)t
  216. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  217. $result = $bbticketinvoiceprinting->fetchAll('', '', 0, 0, ['customsql' => "printing_date_timestamp = '{$this->printingTime}' AND fk_facture = {$selectedFacture_id}"]);
  218. $this->checkResult($result, 'bbticketinvoiceprinting');
  219. foreach ($result as $device) {
  220. $ticketsFromBbticketinvoiceprinting[] = $device->ticket_id;
  221. }
  222. $inString = implode(', ', $ticketsFromBbticketinvoiceprinting);
  223. //echo $inString;exit;
  224. // A ticket_id alapjan, hogy a jegyek kozott szerepel-e es ervenyes-e
  225. $bbticket = new BbTicket($this->db);
  226. $sql = "SELECT tic.rowid as ticketrowid, tic.*, bbd.*, fac.* FROM " . $this->db->prefix() . $bbticket->table_element . " AS tic
  227. INNER JOIN public.llx_product as bbd ON tic.ticket_id = bbd.rowid
  228. INNER JOIN public.llx_facture as fac ON tic.fk_facture = fac.rowid
  229. WHERE tic.rowid IN ({$inString})";
  230. $statement = $this->db->query($sql);
  231. while ($row = pg_fetch_assoc($statement)) {
  232. $sub = [];
  233. foreach ($row as $key => $value) {
  234. $sub[$key] = $value;
  235. //print $key . ' - ' . $value . "\r\n";
  236. }
  237. $sub['ticket_type'] = $ticketChecker->getTicketTypeByProductId($row['ticket_id']);
  238. $json[] = $sub;
  239. }
  240. ApiBbusLog::getinfosLog(json_encode($json));
  241. ApiBbusLog::getinfosLog('Status: OK!');
  242. ApiBbusLog::getinfosLog('=====================');
  243. return $json;
  244. }
  245. /**
  246. * Get properties of a product object by barcode
  247. *
  248. * Return an array with product information.
  249. *
  250. *
  251. * @return array|mixed Data without useless information
  252. *
  253. * @url GET product
  254. */
  255. public function getProducts()
  256. {
  257. global $user;
  258. $productsArray = [];
  259. $products = new Product($this->db);
  260. $sql = "SELECT price, default_vat_code, rowid FROM " . $this->db->prefix() . $products->table_element . " WHERE fk_product_type = 1 ORDER BY rowid ASC";
  261. $res = $this->db->query($sql);
  262. while ($row = pg_fetch_assoc($res)) {
  263. $productsArray[$row['rowid']] = $row;
  264. }
  265. return 'OK';
  266. }
  267. /** LOG OK
  268. * Validate a product bbticket id.
  269. *
  270. * Return an array with product validation data.
  271. *
  272. * @param string $code Facture ID and timestamp of printing
  273. * @param string $ticketid Ticketid (bbticket rowid)
  274. * @param string $imei IMEI (Mobile IMEI number)
  275. *
  276. * @return array|mixed Data without useless information
  277. *
  278. * @url POST ticketvalidationbyphone
  279. */
  280. public function validateTicket($code, $ticketid, $imei)
  281. {
  282. global $user;
  283. $logId = ApiBbusLog::getLogId();
  284. ApiBbusLog::ticketvalidationByPhone("{$logId} === NEW TICKETVALIDATION BY PHONE ===");
  285. ApiBbusLog::ticketvalidationByPhone("{$logId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  286. ApiBbusLog::ticketvalidationByPhone("{$logId} DOLAPIKEY: {$user->api_key}");
  287. ApiBbusLog::ticketvalidationByPhone("{$logId} code: {$code}");
  288. $ticketChecker = new TicketChecker();
  289. $ticketChecker->setCode($code);
  290. $ticketChecker->setTimestamp($code, 'ticketvalidationByPhone', $logId);
  291. $ticketChecker->SetTicketidFromPhone($ticketid, $logId);
  292. $ticketChecker->setImei($imei, $logId);
  293. $this->checkUserValidatePermission();
  294. $ticketChecker->setFactureId('ticketvalidationByPhone', $logId);
  295. $ticketChecker->checkBbTicketInvoicePrinting();
  296. $selectedTicket = $ticketChecker->getDataOfTheSelectedTicket();
  297. $ticketChecker->setBbTicketRowId($selectedTicket->id);
  298. $ticketChecker->checkExceptionHandlers($selectedTicket, 'ticketvalidationByPhone', $logId);
  299. $ticketChecker->setMergedTickets($selectedTicket, 'ticketvalidationByPhone', $logId);
  300. $ticketChecker->saveData($selectedTicket);
  301. ApiBbusLog::ticketvalidationByPhone("{$logId} Status: OK!");
  302. ApiBbusLog::ticketvalidationByPhone("{$logId} =================");
  303. return 'OK';
  304. }
  305. /** LOG OK
  306. * Get properties of a product object by barcode
  307. *
  308. * Return an array with product information.
  309. *
  310. * @param string $code Facture ID and timestamp of printing
  311. * @param string $mac MAC adress of the device
  312. *
  313. * @return array|mixed Data without useless information
  314. *
  315. * @url POST barcode
  316. *
  317. * @throws RestException 401
  318. * @throws RestException 403
  319. * @throws RestException 404
  320. */
  321. public function getByBarcode(string $code, string $mac, string $lat = null, string $lon = null)
  322. {
  323. global $user;
  324. $logId = ApiBbusLog::getLogId();
  325. ApiBbusLog::getByBarcode("{$logId} === NEW OBU validation ===");
  326. ApiBbusLog::getByBarcode("{$logId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  327. ApiBbusLog::getByBarcode("{$logId} DOLAPIKEY: {$user->api_key}");
  328. $bbticket = new BbTicket($this->db);
  329. $ticketChecker = new TicketChecker();
  330. if (empty($code) || empty($mac)) {
  331. ApiBbusLog::getByBarcode("{$logId} Code or mac is empty!");
  332. throw new RestException(404, 'Code or mac is empty!');
  333. }
  334. ApiBbusLog::getByBarcode("{$logId} Code: " . $code);
  335. ApiBbusLog::getByBarcode("{$logId} MAC: " . $mac);
  336. ApiBbusLog::getByBarcode("{$logId} Latitude: " . $lat);
  337. ApiBbusLog::getByBarcode("{$logId} Longitude: " . $lon);
  338. $ticketChecker->setMac($mac);
  339. $ticketChecker->setCode($code);
  340. $ticketChecker->setLat($lat);
  341. $ticketChecker->setLon($lon);
  342. $ticketChecker->setTimestamp($code, 'getByBarcode', $logId);
  343. $this->checkUserReadPermission();
  344. $ticketChecker->setFactureId('getByBarcode', $logId);
  345. $ticketChecker->setFilsArray();
  346. $ticketChecker->setTicketId($logId);
  347. $selectedTicket = $ticketChecker->getDataOfTheSelectedTicket();
  348. $ticketChecker->setBbTicketRowId($selectedTicket->id);
  349. $ticketChecker->check5Minutes($logId);
  350. $ticketChecker->checkExceptionHandlers($selectedTicket, 'getByBarcode', $logId);
  351. $ticketChecker->setMergedTickets($selectedTicket, 'getByBarcode', $logId);
  352. $ticketChecker->saveCoordinates($logId);
  353. $ticketChecker->saveData($selectedTicket);
  354. ApiBbusLog::getByBarcode("{$logId} Status: OK!");
  355. ApiBbusLog::getByBarcode("{$logId} =================");
  356. return 'OK';
  357. }
  358. /**
  359. * curlGetFilsArray
  360. *
  361. * Return an array with success information.
  362. *
  363. * @param string $ref
  364. *
  365. * @return array|mixed Data without useless information
  366. *
  367. * @url POST curlGetFilsArray
  368. *
  369. * @throws RestException 401
  370. * @throws RestException 403
  371. * @throws RestException 404
  372. */
  373. public function curlGetFilsArray($ref)
  374. {
  375. $fils = [];
  376. $sqlFAC = "SELECT rowid FROM llx_facture WHERE ref = '{$ref}'";
  377. $resultFAC = $this->db->query($sqlFAC);
  378. if ($this->db->num_rows($resultFAC)) {
  379. while ($facture = $this->db->fetch_object($resultFAC)) {
  380. $sql = "SELECT fdet.fk_product FROM llx_facture AS f
  381. INNER JOIN llx_facturedet as fdet ON fdet.fk_facture = f.rowid
  382. WHERE f.rowid = {$facture->rowid}";
  383. $result = $this->db->query($sql);
  384. while ($sqlDataResult = pg_fetch_assoc($result)) {
  385. $fils[] = $sqlDataResult['fk_product'];
  386. }
  387. }
  388. }
  389. return $fils;
  390. }
  391. /**
  392. * Post invoice ref and creation date for data recording
  393. *
  394. * Return an array with success information.
  395. *
  396. * @param string $type_id Type id
  397. * @param string $ref Facture ref
  398. * @param string $datetime invoice creation date
  399. *
  400. * @return array|mixed Data without useless information
  401. *
  402. * @url POST printdate
  403. *
  404. * @throws RestException 401
  405. * @throws RestException 403
  406. * @throws RestException 404
  407. */
  408. public function dateHandler(string $type_id, string $ref, string $datetime)
  409. {
  410. global $user, $conf;
  411. ApiBbusLog::appLog("dateHandler");
  412. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  413. throw new RestException(403);
  414. }
  415. if (empty($ref)) {
  416. throw new RestException(401, 'Empty ref!');
  417. }
  418. if (empty($datetime)) {
  419. throw new RestException(401, 'Empty datetime!');
  420. }
  421. ApiBbusLog::appLog("dateHandler: Access granted");
  422. $printDate = DateTime::createFromFormat('Y-m-d H:i:s', $datetime);
  423. $now = new DateTime('now');
  424. $now = (clone $now)->modify('+2 minutes');
  425. $validDate = (clone $now)->modify('-5 minutes');
  426. $datetime = $printDate->format('Y-m-d H:i:s');
  427. $datetime_timestamp = strtotime($datetime);
  428. dol_syslog('printDate: ' . print_r($printDate, true), LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  429. dol_syslog('now: ' . print_r($now, true), LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  430. dol_syslog('validDate: ' . print_r($validDate, true), LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  431. //print_r($validDate);
  432. //print_r($printDate);
  433. //print_r($now);
  434. if ($validDate <= $printDate && $printDate <= $now) {
  435. $server_host = $this->getServerHost($type_id);
  436. # Keresztvásárlás
  437. if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
  438. ApiBbusLog::appLog("dateHandler: local");
  439. ApiBbusLog::appLog("dateHandler: {$datetime_timestamp}");
  440. $this->localDateHandler($ref, $datetime, $datetime_timestamp, $now, $type_id);
  441. } else {
  442. ApiBbusLog::appLog("dateHandler: curl");
  443. $this->curlDateHandler($ref, $datetime, $type_id);
  444. }
  445. } else {
  446. ApiBbusLog::appLog("dateHandler: Invalid date");
  447. throw new RestException(401, 'Invalid date');
  448. }
  449. return 'OK';
  450. }
  451. private function localDateHandler($ref, $datetime, $datetime_timestamp, $now)
  452. {
  453. global $user;
  454. $helper = new ApiBBusHelper();
  455. $facture_id = $helper->getFactureIdForInvoicePrinting($ref);
  456. if (empty($facture_id)) {
  457. ApiBbusLog::appLog("localDateHandler: no facture_id because cross-shopping");
  458. $printedCopies = $this->checkPrintedCopiesWithRef($ref);
  459. } else {
  460. $printedCopies = $this->checkPrintedCopies($facture_id);
  461. }
  462. // Leellenőrzöm, hogy a számla volt-e már nyomtatva
  463. ApiBbusLog::appLog("printedCopies: {$printedCopies}");
  464. if ($printedCopies == 0) {
  465. ApiBbusLog::appLog("printedCopies: no copies");
  466. if (empty($facture_id)) {
  467. $bbTicketsByFacture = $this->getTicketsByInvoiceNumber($ref);
  468. } else {
  469. $bbTicketsByFacture = $this->getTicketsByFactureId($facture_id);
  470. }
  471. foreach ($bbTicketsByFacture as $ticket) {
  472. ApiBbusLog::appLog("Create BBticketInvoiceprinting record");
  473. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  474. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref);
  475. }
  476. } else {
  477. ApiBbusLog::appLog("printedCopies: MULTIPRINT");
  478. if (empty($facture_id)) {
  479. $ticketIds = $helper->getTicketIdsForCrossShopping($ref);
  480. } else {
  481. $ticketIds = $helper->getTicketIdsByFactureId($facture_id, $ref);
  482. }
  483. $ticketObj = new stdClass();
  484. foreach ($ticketIds as $key => $value) {
  485. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  486. $ticketObj->id = $key;
  487. $ticketObj->ticket_id = $value;
  488. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticketObj, $ref);
  489. }
  490. // e-mail küldése
  491. $helper->sendMail($facture_id, $datetime, $now->format('Y-m-d H:i:s'));
  492. return 'Multiprinting';
  493. }
  494. }
  495. /* private function localDateHandler($ref, $datetime, $datetime_timestamp, $now)
  496. {
  497. global $user;
  498. $helper = new ApiBBusHelper();
  499. $facture_id = $helper->getFactureIdForInvoicePrinting($ref);
  500. // Leellenőrzöm, hogy a számla volt-e már nyomtatva
  501. $printedCopies = $this->checkPrintedCopies($facture_id);
  502. if ($printedCopies == 0) {
  503. $bbTicketsByFacture = $this->getTicketsByFactureId($facture_id);
  504. foreach ($bbTicketsByFacture as $ticket) {
  505. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  506. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref);
  507. }
  508. } else {
  509. $ticketIds = $helper->getTicketIdsByFactureId($facture_id);
  510. $ticketObj = new stdClass();
  511. foreach ($ticketIds as $key => $value) {
  512. // Rogzitem a bbticketinvoiceprinting tablaba a rekordot
  513. $ticketObj->id = $key;
  514. $ticketObj->ticket_id = $value;
  515. $helper->setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticketObj, $ref);
  516. }
  517. // e-mail küldése
  518. $helper->sendMail($facture_id, $datetime, $now->format('Y-m-d H:i:s'));
  519. //return 'Multiprinting';
  520. }
  521. } */
  522. public function curlDateHandler($ref, $datetime, $type_id)
  523. {
  524. $params = compact('ref', 'datetime', 'type_id');
  525. $datehandlerPostFields = json_encode($params);
  526. ApiBbusLog::appLog("dateHandler: {$datehandlerPostFields}");
  527. $this->curlRunner('bbus/printdate', $datehandlerPostFields, 'POST', true);
  528. }
  529. /**
  530. * Save customer data (zip or countrycode) in facture table
  531. *
  532. * Return a result.
  533. *
  534. * @param string $facture_id Facture rowid
  535. * @param string $customerdatazip Customer data ZIP
  536. * @param string $customerdatacountrycode Customer data Countrycode
  537. *
  538. * @return array|mixed Data without useless information
  539. *
  540. * @url POST customerDataHandler
  541. *
  542. * @throws RestException 401
  543. * @throws RestException 403
  544. * @throws RestException 404
  545. */
  546. public function customerDataHandler(string $facture_id, string $customerdatazip = null, string $customerdatacountrycode = null)
  547. {
  548. if (is_null($customerdatazip) && is_null($customerdatacountrycode)) {
  549. dol_syslog("Nem sikerult a facture updateje. Ref: " . $this->facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  550. throw new RestException(404, 'Empty params');
  551. }
  552. $sql = "UPDATE " . $this->db->prefix() . "facture_extrafields SET ";
  553. $sql .= !is_null($customerdatazip) ? "customer_data_zip = '{$customerdatazip}' " : "customer_data_countrycode = '{$customerdatacountrycode}' ";
  554. $sql .= "WHERE fk_object = '{$facture_id}'";
  555. $this->factureUpdate($sql, $facture_id);
  556. return "OK";
  557. }
  558. /**
  559. * Check user and eventdetail type permissions
  560. *
  561. * Return a result.
  562. *
  563. * @return array|mixed Data without useless information
  564. *
  565. * @url GET checkPermission
  566. */
  567. public function checkPermission()
  568. {
  569. global $user, $db;
  570. ApiBbusLog::appLog("checkPermission_START");
  571. $memcached = new Memcached();
  572. $memcached->addServer("szollosil-excelia-urbanms-memcached", 11211);
  573. $key = '"' . $user->api_key . '"';
  574. $cacheValue = $memcached->get($key);
  575. if ($cacheValue === false) {
  576. $permissionArray = [];
  577. $groupUsersObj = new GroupUsers($db);
  578. $result = $groupUsersObj->fetchAll('desc', 'rowid', 1, 0, ["customsql" => "fk_user = {$user->id}"]);
  579. if ($result == -1 || empty($result)) {
  580. return $permissionArray;
  581. }
  582. dol_include_once('/eventwizard/class/eventdetails.class.php');
  583. $sqlBasicService = "SELECT pe.basic_service FROM llx_product as p
  584. INNER JOIN llx_product_extrafields as pe ON pe.fk_object = p.rowid
  585. GROUP BY pe.basic_service";
  586. $resultBasicServices = $db->query($sqlBasicService);
  587. if ($db->num_rows($resultBasicServices) > 0) {
  588. while ($row = $db->fetch_object($resultBasicServices)) {
  589. $basicServices[] = $row->basic_service;
  590. }
  591. }
  592. $sqlBasicServicesTable = "SELECT basic_service_id, ref, is_event FROM llx_bbus_basicServices ORDER BY basic_service_id ASC";
  593. $resultBasicServicesObj = $db->query($sqlBasicServicesTable);
  594. if ($db->num_rows($resultBasicServicesObj) > 0) {
  595. while ($bsrow = $db->fetch_object($resultBasicServicesObj)) {
  596. foreach ($basicServices as $item) {
  597. if ($bsrow->basic_service_id == $item && $item != 2) {
  598. if ($bsrow->is_event == '1' && $this->isAvailablePlaces($item)) {
  599. $permissionArray[$item] = $bsrow->ref;
  600. } elseif ($bsrow->is_event != '1') {
  601. $permissionArray[$item] = $bsrow->ref;
  602. }
  603. }
  604. }
  605. }
  606. }
  607. $cacheValue = json_encode($permissionArray);
  608. $memcached->set($key, $cacheValue, 600); // 5 percig tároljuk
  609. ApiBbusLog::appLog("Adat betöltve a adatbázis-ból: " . $cacheValue);
  610. } else {
  611. ApiBbusLog::appLog("Adat betöltve a cache-ből: " . $cacheValue);
  612. }
  613. //$curlPermissionArray = $this->curlRunner('rollerstorageapi/checkPermission', '');
  614. //$permissionArray = $permissionArray + (array)json_decode($curlPermissionArray);
  615. //return $permissionArray;
  616. return json_decode($cacheValue, true);
  617. }
  618. private function isAvailablePlaces($item)
  619. {
  620. global $conf;
  621. $available = false;
  622. $server_host = $this->getServerHost($item);
  623. $sqlProducts = "SELECT fk_object, basic_service FROM llx_product_extrafields WHERE basic_service = '{$item}'";
  624. $resultProducts = $this->db->query($sqlProducts);
  625. if ($this->db->num_rows($resultProducts) > 0) {
  626. while ($prodductsRow = $this->db->fetch_object($resultProducts)) {
  627. $productsArray[$prodductsRow->fk_object] = $prodductsRow->basic_service;
  628. }
  629. if (!empty($productsArray)) {
  630. foreach ($productsArray as $key => $value) {
  631. ApiBbusLog::appLog("SERVER_HOST: " . $server_host);
  632. ApiBbusLog::appLog("CONF_SERVER_HOST: " . $conf->global->LOCAL_SERVER_HOST);
  633. if ($server_host == $conf->global->LOCAL_SERVER_HOST) {
  634. ApiBbusLog::appLog($conf->global->LOCAL_SERVER_HOST);
  635. $availableResult = $this->localCheckAvailablePlacesForCheckPermission($key);
  636. } elseif ($server_host == $conf->global->CURL_SERVER_HOST) {
  637. ApiBbusLog::appLog($conf->global->CURL_SERVER_HOST);
  638. $postFields = '{"product_id":"' . $key . '"}';
  639. $availableResult = $this->curlRunner('bbus/localCheckAvailablePlacesForCheckPermission', $postFields, 'POST', false);
  640. }
  641. if ($availableResult == 1) {
  642. $available = true;
  643. }
  644. }
  645. }
  646. };
  647. return $available;
  648. }
  649. /**
  650. * localCheckAvailablePlacesForCheckPermission
  651. *
  652. * @param int $product_id Product rowid
  653. *
  654. * @return array|mixed Data without useless information
  655. *
  656. * @url POST localCheckAvailablePlacesForCheckPermission
  657. *
  658. * @throws RestException 401
  659. * @throws RestException 403
  660. * @throws RestException 404
  661. */
  662. public function localCheckAvailablePlacesForCheckPermission($product_id)
  663. {
  664. $date_from = $this->getCutOffTimeDate($product_id);
  665. $sql = "SELECT
  666. ac.id
  667. FROM llx_actioncomm as ac
  668. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  669. INNER JOIN llx_eventwizard_eventdetails as ed ON ac.fk_element = ed.rowid
  670. INNER JOIN llx_eventwizard_eventproduct as ep ON ep.fk_eventdetails = ac.fk_element
  671. WHERE ac.code = 'AC_EVENT'
  672. AND ep.fk_product = {$product_id}
  673. AND ac.datep > '{$date_from}'
  674. ORDER BY ac.datep ASC";
  675. //ApiBbusLog::appLog($sql);
  676. $result = $this->db->query($sql);
  677. return $this->db->num_rows($result) > 0 ? 1 : 0;
  678. }
  679. private function getCutOffTimeDate($product_id)
  680. {
  681. $date = date("Y-m-d H:i:s");
  682. $sql = "SELECT cut_off_time_app FROM llx_product_extrafields WHERE fk_object = {$product_id}";
  683. if ($result = $this->db->query($sql)) {
  684. if ($this->db->num_rows($result) > 0) {
  685. while ($row = $this->db->fetch_object($result)) {
  686. $cutOffTime = $row->cut_off_time_app;
  687. }
  688. $dateTimestamp = strtotime($date);
  689. $date = date("Y-m-d H:i:s", $dateTimestamp + $cutOffTime * 60);
  690. }
  691. }
  692. return $date;
  693. }
  694. /**
  695. * Create naplo for userlogout
  696. *
  697. * Return a result.
  698. *
  699. * @return array|mixed Data without useless information
  700. *
  701. * @url POST logoutNaploCreator
  702. *
  703. * @throws RestException 401
  704. * @throws RestException 403
  705. * @throws RestException 404
  706. */
  707. public function logoutNaploCreator()
  708. {
  709. global $user, $db;
  710. $error = 0;
  711. $db->begin();
  712. $group_user_id = $this->getGroupUserIdByUserId($user->id);
  713. if ($group_user_id == -1) {
  714. $error++;
  715. }
  716. $result = $this->isLastStatusLogout($user);
  717. if ($result !== '') {
  718. return date('Y-m-d H:i:s', $result);
  719. }
  720. $userLoginNaplo = new UserLoginNaplo($db);
  721. $userLoginNaplo->login_logout_status = 1;
  722. $userLoginNaplo->user_id = $user->id;
  723. $result = $userLoginNaplo->create($user);
  724. if ($result < 0) {
  725. $error++;
  726. }
  727. $userNaploObj = new UserNaplo($db);
  728. $userNaploObj->user_id = $user->id;
  729. $userNaploObj->group_user_id = $group_user_id;
  730. $userNaploObj->status = 0;
  731. $result = $userNaploObj->create($user);
  732. if ($result < 0) {
  733. $error++;
  734. }
  735. $groupUsersObj = new GroupUsers($db);
  736. $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "settlements_groupusers WHERE fk_user = {$user->id}";
  737. $data = $db->query($sql);
  738. $dataArray = pg_fetch_assoc($data);
  739. $selectedGroupId = $dataArray['rowid'];
  740. if (isset($selectedGroupId)) {
  741. $resultKickOff = $groupUsersObj->deleteLine($user, $selectedGroupId);
  742. if (!$resultKickOff) {
  743. $error++;
  744. }
  745. }
  746. if ($error) {
  747. $db->rollback();
  748. }
  749. $db->commit();
  750. return 'OK';
  751. }
  752. /**
  753. * Get the discount unit From Product
  754. *
  755. * Return a result.
  756. *
  757. * @param int $product_id Product rowid
  758. *
  759. * @return string discount unit
  760. *
  761. * @url POST getDiscountUnit
  762. *
  763. * @throws RestException 401
  764. * @throws RestException 403
  765. * @throws RestException 404
  766. */
  767. public function getDiscountUnit(int $product_id)
  768. {
  769. global $db, $user;
  770. $ProductObj = new Product($db);
  771. $ProductObj->fetch($product_id);
  772. return $ProductObj->array_options['discount_period'];
  773. }
  774. /**
  775. * Create naplo for Discount
  776. *
  777. * Return a result.
  778. *
  779. * @param int $facture_id Facture rowid
  780. * @param int $product_id Product rowid
  781. * @param int $discount Discount
  782. * @param string $discount_unit Discount unit
  783. *
  784. * @return array|mixed Data without useless information
  785. *
  786. * @url POST createDiscountNaplo
  787. *
  788. * @throws RestException 401
  789. * @throws RestException 403
  790. * @throws RestException 404
  791. */
  792. public function createDiscountNaplo(int $facture_id, int $product_id, int $discount, string $discount_unit)
  793. {
  794. global $db, $user;
  795. $discountNaploObj = new DiscountNaplo($db);
  796. $discountNaploObj->fk_facture = $facture_id;
  797. $discountNaploObj->fk_product = $product_id;
  798. $discountNaploObj->discount = $discount;
  799. $discountNaploObj->discount_unit = $discount_unit;
  800. $result = $discountNaploObj->create($user);
  801. if ($result < 0) {
  802. return false;
  803. }
  804. return $result;
  805. }
  806. /**
  807. * Get the products from Product
  808. *
  809. * Return a result.
  810. *
  811. * @param int $entity entity
  812. *
  813. * @return array|mixed Data without useless information
  814. *
  815. * @url POST getHotelSalesProducts
  816. *
  817. * @throws RestException 401
  818. * @throws RestException 403
  819. * @throws RestException 404
  820. */
  821. public function getHotelSalesProducts(int $entity)
  822. {
  823. global $db, $user;
  824. $sql = "SELECT p.* FROM public.llx_product AS p
  825. INNER JOIN public.llx_product_extrafields as pe ON pe.fk_object = p.rowid
  826. WHERE p.entity = {$entity} AND pe.hotelsales = 1";
  827. $products = $this->db->query($sql);
  828. $row = pg_fetch_all($products);
  829. return $row;
  830. }
  831. private function getGroupUserIdByUserId($user_id)
  832. {
  833. global $db;
  834. $groupUsersObj = new GroupUsers($db);
  835. $result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
  836. if (!empty($result)) {
  837. foreach ($result as $record) {
  838. return $record->fk_settlements_group;
  839. }
  840. }
  841. return -1;
  842. }
  843. private function isLastStatusLogout($user)
  844. {
  845. global $db;
  846. $userLoginNaplo = new UserLoginNaplo($db);
  847. $result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
  848. foreach ($result as $lastrecord) {
  849. return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
  850. }
  851. }
  852. private function factureUpdate($sql, $facture_id)
  853. {
  854. $updated = $this->db->query($sql);
  855. if (!$updated) {
  856. dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  857. throw new RestException(404, 'Update failed');
  858. }
  859. }
  860. private function checkUserReadPermission()
  861. {
  862. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  863. throw new RestException(403);
  864. }
  865. }
  866. private function checkUserValidatePermission()
  867. {
  868. if (!DolibarrApiAccess::$user->rights->bbus->ticket->validation) {
  869. throw new RestException(403);
  870. }
  871. }
  872. private function getFactureRowIdByFactureId()
  873. {
  874. $facture = new Facture($this->db);
  875. $sqlFacture = "SELECT rowid FROM public.llx_facture WHERE ref ILIKE '%{$this->code}%'";
  876. $result = $this->db->query($sqlFacture);
  877. if (pg_num_rows($result) > 0) {
  878. while ($adatok = pg_fetch_assoc($result)) {
  879. $factureRowid = $adatok['rowid'];
  880. }
  881. } else {
  882. throw new RestException(404, 'Invoice not found.');
  883. }
  884. $sql = "SELECT rowid FROM llx_facture WHERE fk_facture_source = {$factureRowid} AND type = 2";
  885. $res = $this->db->query($sql);
  886. if (pg_num_rows($res) > 0) {
  887. throw new RestException(404, 'Invoice has a Credit account.');
  888. }
  889. return $factureRowid;
  890. }
  891. private function checkResult($result, $tableName)
  892. {
  893. if (!is_array($result) || empty($result)) {
  894. dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  895. throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
  896. }
  897. }
  898. private function saveBbTicketNaplo($user)
  899. {
  900. $bbTicketNaplo = new BbTicketNaplo($this->db);
  901. $bbTicketNaplo->ticket_row_id = $this->bbTicketRowId;
  902. $bbTicketNaplo->bbservicelocation_id = isset($this->service_location_id) ? $this->service_location_id : null;
  903. $bbTicketNaplo->device_id = isset($this->device_id) ? $this->device_id : null;
  904. $bbTicketNaplo->status = $this->status;
  905. if ($bbTicketNaplo->create($user) < 0) {
  906. dol_syslog('Nem sikerult menteni a bbticketNaplo tablaba a rekordot.', LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  907. throw new RestException(500, 'Nem sikerult menteni a bbticketNaplo tablaba a rekordot.');
  908. }
  909. }
  910. private function getTicketsByFactureId($facture_id)
  911. {
  912. $bbticket = new BbTicket($this->db);
  913. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  914. if ($bbTicketsByFacture < 1) {
  915. throw new RestException(404, 'BBTicket not found');
  916. }
  917. return $bbTicketsByFacture;
  918. }
  919. private function getTicketsByInvoiceNumber($ref)
  920. {
  921. $bbticket = new BbTicket($this->db);
  922. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ["customsql" => "invoice_number = '" . $ref . "'"]);
  923. if ($bbTicketsByFacture < 1) {
  924. ApiBbusLog::appLog("getTicketsByInvoiceNumber: BBTicket not found");
  925. throw new RestException(404, 'BBTicket not found');
  926. }
  927. ApiBbusLog::appLog("getTicketsByInvoiceNumber: I got it");
  928. return $bbTicketsByFacture;
  929. }
  930. private function checkPrintedCopies($facture_id)
  931. {
  932. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  933. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  934. return (is_array($copies)) ? count($copies) : 0;
  935. }
  936. private function checkPrintedCopiesWithRef($ref)
  937. {
  938. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  939. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ["customsql" => "invoice_number = '" . $ref . "'"]);
  940. return (is_array($copies)) ? count($copies) : 0;
  941. }
  942. /**
  943. * @param string $facture_id Facture ref
  944. *
  945. * @return array|mixed Data without useless information
  946. *
  947. * @url POST getRefFromFacture
  948. *
  949. * @throws RestException 401
  950. * @throws RestException 403
  951. * @throws RestException 404
  952. */
  953. public function getRefFromFacture(string $facture_id)
  954. {
  955. global $user;
  956. $facture = new Facture($this->db);
  957. $sql = "SELECT ref FROM " . $this->db->prefix() . $facture->table_element . " WHERE rowid = " . $facture_id;
  958. $res = $this->db->query($sql);
  959. while ($adatok = pg_fetch_assoc($res)) {
  960. print_r($adatok['ref']);
  961. exit;
  962. }
  963. return 'OK';
  964. }
  965. /**
  966. * Get properties of a product object by barcode
  967. *
  968. * Return an array with product information.
  969. *
  970. * @param string $barcode Barcode of element
  971. * @param int $includestockdata Load also information about stock (slower)
  972. * @param bool $includesubproducts Load information about subproducts
  973. * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product)
  974. * @param bool $includetrans Load also the translations of product label and description
  975. *
  976. * @return array|mixed Data without useless information
  977. *
  978. * @url GET profileimage/{id}
  979. *
  980. * @throws RestException 401
  981. * @throws RestException 403
  982. * @throws RestException 404
  983. */
  984. public function getUserImage(int $id)
  985. {
  986. $image = null;
  987. $dolApiKey = $_SERVER['HTTP_DOLAPIKEY'] ?? null;
  988. if (empty($dolApiKey)) {
  989. throw new RestException(401, 'Access not allowed');
  990. }
  991. $user = (new ApiUserHandler)->getUser($id, $dolApiKey);
  992. if (empty($user->photo)) {
  993. throw new RestException(404, 'Photo not found');
  994. } else {
  995. $originalFile = get_exdir(0, 0, 0, 0, $user, 'user') . 'photos/' . $user->photo;
  996. $originalFile = DOL_DOCUMENT_ROOT . '/documents/users/' . $originalFile;
  997. $filename = basename($originalFile);
  998. $originalFileOsEncoded = dol_osencode($originalFile); // New file name encoded in OS encoding charset
  999. $fileContent = file_get_contents($originalFileOsEncoded);
  1000. $image = [
  1001. 'filename' => $filename,
  1002. 'content-type' => dol_mimetype($filename),
  1003. 'filesize' => filesize($originalFile),
  1004. 'content' => base64_encode($fileContent),
  1005. 'encoding' => 'base64'
  1006. ];
  1007. }
  1008. return $image;
  1009. }
  1010. /**
  1011. * Create invoices from the order
  1012. *
  1013. * @param int $id_order (Row)Id of the order
  1014. * @param int $id_soc Id of 3th party
  1015. * @return array Response
  1016. * @url POST invoicesFromOrder
  1017. * @throws RestException 401
  1018. * @throws RestException 403
  1019. * @throws RestException 404
  1020. */
  1021. public function invoicesFromOrder(int $id_order, int $id_soc = 0): array
  1022. {
  1023. // echo ini_get('memory_limit');
  1024. // exit;
  1025. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  1026. throw new RestException(401, "Insuffisant rights");
  1027. }
  1028. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  1029. // Standard or deposit invoice, not from a Predefined template invoice
  1030. // Si facture standard
  1031. $this->now = time();
  1032. $this->invoices = [];
  1033. $element == 'order';
  1034. $element = $subelement = 'commande';
  1035. //etalon obj:
  1036. $object = new Facture($this->db);
  1037. // $extrafields = new ExtraFields($db);
  1038. $defaultDevSocId = 1;
  1039. $this->defaultSocId = (isset($_ENV['DEFAULT_SOCID']) && (int) $_ENV['DEFAULT_SOCID']) ? (int) $_ENV['DEFAULT_SOCID'] : $defaultDevSocId;
  1040. $object->socid = (empty((int) $id_soc)) ? $this->defaultSocId : (int) $id_soc;
  1041. $object->type = null;
  1042. $object->ref = null;
  1043. $object->date = $this->now;
  1044. // $object->date_pointoftax = $date_pointoftax;
  1045. // $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1046. // $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1047. // $object->ref_client = GETPOST('ref_client');
  1048. $object->model_pdf = null;
  1049. // $object->fk_project = GETPOST('projectid', 'int');
  1050. // $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1051. // $object->mode_reglement_id = GETPOST('mode_reglement_id');
  1052. // $object->fk_account = GETPOST('fk_account', 'int');
  1053. // $object->amount = price2num(GETPOST('amount'));
  1054. // $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1055. // $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1056. // $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1057. // $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1058. // $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1059. // $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1060. $object->fetch_thirdparty();
  1061. // If creation from another object of another module (Example: origin=propal, originid=1)
  1062. $object->origin = $element;
  1063. $object->origin_id = $id_order;
  1064. // Possibility to add external linked objects with hooks
  1065. $object->linked_objects[$object->origin] = $object->origin_id;
  1066. // link with order if it is a shipping invoice
  1067. if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
  1068. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  1069. }
  1070. //
  1071. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  1072. $classname = ucfirst($subelement);
  1073. $srcobject = new $classname($this->db);
  1074. $result = $srcobject->fetch($id_order);
  1075. if ($result > 0) {
  1076. $lines = $srcobject->lines;
  1077. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1078. $srcobject->fetch_lines();
  1079. $lines = $srcobject->lines;
  1080. }
  1081. /*
  1082. // If we create a standard invoice with a percent, we change amount by changing the qty
  1083. if (is_array($lines)) {
  1084. foreach ($lines as $line) {
  1085. // We keep ->subprice and ->pa_ht, but we change the qty
  1086. $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS');
  1087. }
  1088. }
  1089. */
  1090. $fk_parent_line = 0;
  1091. $num = count($lines);
  1092. $invNum = 0;
  1093. for ($i = 0; $i < $num; $i++) {
  1094. // if (!in_array($lines[$i]->id, $selectedLines)) {
  1095. // continue; // Skip unselected lines
  1096. // }
  1097. //!!! create invoice by line:
  1098. $quantity = $lines[$i]->qty;
  1099. for ($j = 0; $j < $quantity; $j++) {
  1100. $this->invoices[$invNum] = clone $object;
  1101. if ($id = $this->invoices[$invNum]->create(DolibarrApiAccess::$user)) {
  1102. $this->invoices[$invNum]->update_price(1, 'auto', 0, $mysoc);
  1103. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  1104. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
  1105. if ($this->invoices[$invNum]->situation_counter == 1) {
  1106. $lines[$i]->situation_percent = 0;
  1107. }
  1108. if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
  1109. // Negative line, we create a discount line
  1110. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  1111. $discount = new DiscountAbsolute($db);
  1112. $discount->fk_soc = $this->invoices[$invNum]->socid;
  1113. $discount->amount_ht = abs($lines[$i]->total_ht);
  1114. $discount->amount_tva = abs($lines[$i]->total_tva);
  1115. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  1116. $discount->tva_tx = $lines[$i]->tva_tx;
  1117. $discount->fk_user = DolibarrApiAccess::$user->id;
  1118. $discount->description = $desc;
  1119. $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
  1120. $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
  1121. $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
  1122. $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
  1123. $discountid = $discount->create(DolibarrApiAccess::$user);
  1124. if ($discountid > 0) {
  1125. $result = $this->invoices[$invNum]->insert_discount($discountid); // This include link_to_invoice
  1126. } else {
  1127. setEventMessages($discount->error, $discount->errors, 'errors');
  1128. $error++;
  1129. break;
  1130. }
  1131. } else {
  1132. // Positive line
  1133. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1134. // Date start
  1135. $date_start = false;
  1136. if ($lines[$i]->date_debut_prevue) {
  1137. $date_start = $lines[$i]->date_debut_prevue;
  1138. }
  1139. if ($lines[$i]->date_debut_reel) {
  1140. $date_start = $lines[$i]->date_debut_reel;
  1141. }
  1142. if ($lines[$i]->date_start) {
  1143. $date_start = $lines[$i]->date_start;
  1144. }
  1145. // Date end
  1146. $date_end = false;
  1147. if ($lines[$i]->date_fin_prevue) {
  1148. $date_end = $lines[$i]->date_fin_prevue;
  1149. }
  1150. if ($lines[$i]->date_fin_reel) {
  1151. $date_end = $lines[$i]->date_fin_reel;
  1152. }
  1153. if ($lines[$i]->date_end) {
  1154. $date_end = $lines[$i]->date_end;
  1155. }
  1156. // Reset fk_parent_line for no child products and special product
  1157. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1158. $fk_parent_line = 0;
  1159. }
  1160. // Extrafields
  1161. if (method_exists($lines[$i], 'fetch_optionals')) {
  1162. $lines[$i]->fetch_optionals();
  1163. $array_options = $lines[$i]->array_options;
  1164. }
  1165. $tva_tx = $lines[$i]->tva_tx;
  1166. if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  1167. $tva_tx .= ' (' . $lines[$i]->vat_src_code . ')';
  1168. }
  1169. // View third's localtaxes for NOW and do not use value from origin.
  1170. // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
  1171. $localtax1_tx = get_localtax($tva_tx, 1, $this->invoices[$invNum]->thirdparty);
  1172. $localtax2_tx = get_localtax($tva_tx, 2, $this->invoices[$invNum]->thirdparty);
  1173. $result = $this->invoices[$invNum]->addline(
  1174. $desc,
  1175. $lines[$i]->subprice,
  1176. // $lines[$i]->qty,
  1177. 1,
  1178. $tva_tx,
  1179. $localtax1_tx,
  1180. $localtax2_tx,
  1181. $lines[$i]->fk_product,
  1182. $lines[$i]->remise_percent,
  1183. $date_start,
  1184. $date_end,
  1185. 0,
  1186. $lines[$i]->info_bits,
  1187. $lines[$i]->fk_remise_except,
  1188. 'HT',
  1189. 0,
  1190. $product_type,
  1191. $lines[$i]->rang,
  1192. $lines[$i]->special_code,
  1193. $this->invoices[$invNum]->origin,
  1194. $lines[$i]->rowid,
  1195. $fk_parent_line,
  1196. $lines[$i]->fk_fournprice,
  1197. $lines[$i]->pa_ht,
  1198. $label,
  1199. $array_options,
  1200. $lines[$i]->situation_percent,
  1201. $lines[$i]->fk_prev_id,
  1202. $lines[$i]->fk_unit,
  1203. 0,
  1204. '',
  1205. 1
  1206. );
  1207. if ($result > 0) {
  1208. $lineid = $result;
  1209. } else {
  1210. $lineid = 0;
  1211. $error++;
  1212. break;
  1213. }
  1214. // Defined the new fk_parent_line
  1215. if ($result > 0 && $lines[$i]->product_type == 9) {
  1216. $fk_parent_line = $result;
  1217. }
  1218. }
  1219. }
  1220. $invNum++;
  1221. }
  1222. }
  1223. } else {
  1224. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1225. $error++;
  1226. }
  1227. $num = count($this->invoices);
  1228. $return = [
  1229. 'validated' => []
  1230. ];
  1231. // $used_mem = round(memory_get_usage(false) / 1024 / 1024); //mb
  1232. // $used_mem = round(memory_get_usage(true) / 1024 / 1024); //mb
  1233. // echo $used_mem. " / ".$allowed_mem;
  1234. // echo ini_get('memory_limit');
  1235. // exit;
  1236. for ($i = 0; $i < $num; $i++) {
  1237. //!!! validation
  1238. // $idwarehouse = 0;
  1239. // $notrigger = 0;
  1240. // $result = $this->invoices[$i]->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
  1241. $id = $this->invoices[$i]->id;
  1242. $result = $this->invoices[$i]->validate(DolibarrApiAccess::$user, '', null);
  1243. if ($result >= 0) {
  1244. // Define output language
  1245. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1246. global $langs;
  1247. $outputlangs = $langs;
  1248. $newlang = '';
  1249. if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1250. $newlang = GETPOST('lang_id', 'aZ09');
  1251. }
  1252. if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) {
  1253. $newlang = $this->invoices[$i]->thirdparty->default_lang;
  1254. }
  1255. if (!empty($newlang)) {
  1256. $outputlangs = new Translate("", $conf);
  1257. $outputlangs->setDefaultLang($newlang);
  1258. $outputlangs->load('products');
  1259. }
  1260. $model = $this->invoices[$i]->model_pdf;
  1261. $ret = $this->invoices[$i]->fetch($id); // Reload to get new records
  1262. // PDF
  1263. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS)) ? 1 : 0;
  1264. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC)) ? 1 : 0;
  1265. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF)) ? 1 : 0;
  1266. $result = $this->invoices[$i]->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1267. if ($result < 0) {
  1268. //...
  1269. // setEventMessages($this->invoices[$i]->error, $this->invoices[$i]->errors, 'errors');
  1270. }
  1271. }
  1272. } else {
  1273. // if (count($this->invoices[$i]->errors)) {
  1274. // setEventMessages(null, $this->invoices[$i]->errors, 'errors');
  1275. // } else {
  1276. // setEventMessages($this->invoices[$i]->error, $this->invoices[$i]->errors, 'errors');
  1277. // }
  1278. }
  1279. // if ($result == 0) {
  1280. // throw new RestException(304, 'Error nothing done. May be object is already validated');
  1281. // }
  1282. // if ($result < 0) {
  1283. // throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
  1284. // }
  1285. // $this->invoices[$i] = $this->invoicees[$i]->fetch($id);
  1286. if (!$this->invoices[$i]) {
  1287. throw new RestException(404, 'Invoice not found');
  1288. }
  1289. $this->invoices[$i] = parent::_cleanObjectDatas($this->invoices[$i]);
  1290. unset($this->invoices[$i]->note);
  1291. unset($this->invoices[$i]->address);
  1292. unset($this->invoices[$i]->barcode_type);
  1293. unset($this->invoices[$i]->barcode_type_code);
  1294. unset($this->invoices[$i]->barcode_type_label);
  1295. unset($this->invoices[$i]->barcode_type_coder);
  1296. unset($this->invoices[$i]->canvas);
  1297. if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
  1298. throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
  1299. }
  1300. $return['validated'][] = $this->invoices[$i]->ref;
  1301. }
  1302. return $return;
  1303. }
  1304. /**
  1305. * Jegy generálás -> (order?->) invoice -> payment -> jegy -> qr on the bill
  1306. *
  1307. * Return an array with prcess information.
  1308. *
  1309. * @param array $orderDetails Order details
  1310. *
  1311. * @return array|mixed Data without useless information
  1312. *
  1313. * @url POST order
  1314. *
  1315. * @throws RestException 401
  1316. * @throws RestException 403
  1317. * @throws RestException 404
  1318. */
  1319. public function jegy(array $orderDetails)
  1320. {
  1321. $return = [
  1322. "request" => $orderDetails
  1323. ];
  1324. $Jegy = new Jegy();
  1325. $return['hash'] = [
  1326. $Jegy->generate_hash(),
  1327. $Jegy->generate_hash(1),
  1328. $Jegy->generate_hash(20),
  1329. $Jegy->generate_hash(50),
  1330. $Jegy->generate_hash(100),
  1331. ];
  1332. return $return;
  1333. }
  1334. /**
  1335. * Get app config
  1336. *
  1337. * Return an array with config params.
  1338. *
  1339. * @return array|mixed Data without useless information
  1340. *
  1341. * @url GET config
  1342. *
  1343. * @throws RestException 401
  1344. * @throws RestException 403
  1345. * @throws RestException 404
  1346. */
  1347. public function config(): array
  1348. {
  1349. global $user, $conf;
  1350. $helper = new ApiBBusHelper();
  1351. // company
  1352. $companyData = $helper->getCompany();
  1353. return [
  1354. 'exchange_rate' => ExchangeRateUpdater::getExchangeRate(ExchangeRateUpdater::EUR, $conf->entity),
  1355. 'invoice' => [
  1356. 'header' => [
  1357. 'name' => $companyData['company_data']['NOM'],
  1358. 'tax_number' => $companyData['company_data']['TVAINTRA'],
  1359. 'address' => [
  1360. 'zip' => $companyData['company_data']['ZIP'],
  1361. 'city' => $companyData['company_data']['TOWN'],
  1362. 'address' => $companyData['company_data']['ADDRESS']
  1363. ]
  1364. ],
  1365. 'customer' => $helper->getAppCustomers(),
  1366. 'vat_percent' => 27,
  1367. 'entity' => $user->entity,
  1368. 'account_id' => $helper->getAccountRowid($user->entity),
  1369. 'currencies' => $helper->getCurrenciesRowid($user->entity),
  1370. 'payments_mode' => $helper->getPaymentsMode($user->entity)
  1371. ]
  1372. ];
  1373. }
  1374. /**
  1375. * Get groupId for REACT
  1376. *
  1377. * Return an ID.
  1378. *
  1379. * @return integer Data without useless information
  1380. *
  1381. * @url GET getGroupId
  1382. *
  1383. * @throws RestException 401
  1384. * @throws RestException 403
  1385. * @throws RestException 404
  1386. */
  1387. public function getGroupId(): array
  1388. {
  1389. global $user, $db;
  1390. $sql = "SELECT fk_settlements_group FROM public.llx_settlements_groupusers WHERE fk_user = {$user->id} ORDER BY rowid DESC LIMIT 1";
  1391. $result = $db->query($sql);
  1392. while ($row = pg_fetch_assoc($result)) {
  1393. return $row;
  1394. }
  1395. return [];
  1396. }
  1397. /**
  1398. * Insert a row into login log table
  1399. *
  1400. * @param string $login Login name
  1401. *
  1402. * @return array|mixed Data without useless information
  1403. *
  1404. * @url POST savelogin
  1405. *
  1406. * @throws RestException 404
  1407. */
  1408. public function saveLogin(string $login)
  1409. {
  1410. $error = 0;
  1411. $this->db->begin();
  1412. $user = new User($this->db);
  1413. //$user->fetch(0, $login, 0, 0, 1);
  1414. $user->fetch(0, $login, 0, 0);
  1415. if (empty($user->id)) {
  1416. throw new RestException(404, 'User not found');
  1417. }
  1418. $log = new BbLoginLog($this->db);
  1419. $log->entity = 1;
  1420. $log->description = 'Login from App';
  1421. $id = $log->create($user);
  1422. if ($id < 1) {
  1423. $error++;
  1424. throw new RestException(500, 'Log failure');
  1425. }
  1426. $now = dol_now();
  1427. $userremoteip = getUserRemoteIP();
  1428. $sql = "UPDATE " . $this->db->prefix() . "user SET";
  1429. $sql .= " datepreviouslogin = datelastlogin,";
  1430. $sql .= " ippreviouslogin = iplastlogin,";
  1431. $sql .= " datelastlogin = '" . $this->db->idate($now) . "',";
  1432. $sql .= " iplastlogin = '" . $this->db->escape($userremoteip) . "',";
  1433. $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
  1434. $sql .= " WHERE rowid = " . ((int) $user->id);
  1435. $resql = $this->db->query($sql);
  1436. if (!$resql) {
  1437. $error++;
  1438. $this->error = $this->db->lasterror() . ' sql=' . $sql;
  1439. }
  1440. if (!$error) {
  1441. $this->db->commit();
  1442. return 'OK';
  1443. } else {
  1444. $this->db->rollback();
  1445. }
  1446. }
  1447. /**
  1448. * Receive GPS coordinates of the device
  1449. *
  1450. * @param string $licplate License plate of the vehicle
  1451. * @param string $lat GPS latitude coordinate
  1452. * @param string $lon GPS longitude coordinate
  1453. *
  1454. * @return string|mixed Data without useless information
  1455. *
  1456. * @url GET /gps_coords
  1457. *
  1458. * @throws RestException 401
  1459. * @throws RestException 403
  1460. * @throws RestException 404
  1461. * @throws RestException 500
  1462. */
  1463. public function gpsCoords(string $licplate, string $lat, string $lon): string
  1464. {
  1465. if (!(new GpsPosition)->save($licplate, $lat, $lon)) {
  1466. throw new RestException(500, 'Save failure');
  1467. }
  1468. return 'OK';
  1469. }
  1470. /**
  1471. * Receive GPS coordinates of the device
  1472. *
  1473. * @param string $licplate License plate of the vehicle
  1474. * @param string $lat GPS latitude coordinate
  1475. * @param string $lon GPS longitude coordinate
  1476. *
  1477. * @return string|mixed Data without useless information
  1478. *
  1479. * @url POST /gps_position
  1480. *
  1481. * @throws RestException 401
  1482. * @throws RestException 403
  1483. * @throws RestException 404
  1484. * @throws RestException 500
  1485. */
  1486. public function gpsPosition(string $licplate, string $lat, string $lon): string
  1487. {
  1488. if (!(new GpsPosition)->save($licplate, $lat, $lon)) {
  1489. throw new RestException(500, 'Save failure');
  1490. }
  1491. return 'OK';
  1492. }
  1493. /**
  1494. * List of countries
  1495. *
  1496. * Return an array with country name and code.
  1497. *
  1498. * @param string $lang
  1499. * @param string $search
  1500. *
  1501. * @return array|mixed Data without useless information
  1502. *
  1503. * @url GET /countries
  1504. *
  1505. * @throws RestException 401
  1506. * @throws RestException 403
  1507. * @throws RestException 404
  1508. */
  1509. public function countries(string $lang = 'hu', string $search = ''): array
  1510. {
  1511. return (new CountryHandler)->getCountries($lang, $search);
  1512. }
  1513. /**
  1514. * List of entities
  1515. *
  1516. * Return an array with companies data.
  1517. *
  1518. * @return array|mixed Data without useless information
  1519. *
  1520. * @url GET /entities
  1521. *
  1522. * @throws RestException 401
  1523. * @throws RestException 403
  1524. * @throws RestException 404
  1525. */
  1526. public function entities(): array
  1527. {
  1528. return (new EntityHandler)->getEntities();
  1529. }
  1530. /**
  1531. * List of assets received
  1532. *
  1533. * Return an array with assets received.
  1534. *
  1535. * @return array|mixed Data without useless information
  1536. *
  1537. * @url GET /assets_received
  1538. *
  1539. * @throws RestException 401
  1540. * @throws RestException 403
  1541. * @throws RestException 404
  1542. */
  1543. public function assetsReceived(): array
  1544. {
  1545. global $user, $db;
  1546. $packageHistory = new PackageHistory($db);
  1547. $inventoryObj = new Inventory($db);
  1548. $sql = "SELECT pt.device_id, i.ref, i.title, ie.unique_identifier,
  1549. (SELECT ph.date_creation FROM " . $this->db->prefix() . $packageHistory->table_element . " as ph WHERE user_id = {$user->id} AND DATE(ph.date_creation) = CURRENT_DATE
  1550. ORDER BY ph.rowid DESC LIMIT 1) AS ph_date_creation
  1551. FROM llx_settlements_packagetool pt
  1552. INNER JOIN llx_inventory as i ON i.rowid = pt.device_id
  1553. INNER JOIN llx_inventory_extrafields as ie ON ie.fk_object = i.rowid
  1554. WHERE pt.package_id = (SELECT ph.package_id FROM public.llx_rollerstorage_packagehistory as ph WHERE user_id = {$user->id}
  1555. AND DATE(ph.date_creation) = CURRENT_DATE
  1556. ORDER BY ph.rowid DESC LIMIT 1)
  1557. ORDER BY pt.rowid DESC";
  1558. //print $sql;exit;
  1559. $result = $db->query($sql);
  1560. $changeSql = "SELECT ref, title FROM " . $this->db->prefix() . $inventoryObj->table_element . " WHERE ref ILIKE '%Change%'";
  1561. $resultCh = $db->query($changeSql);
  1562. if ($result > 0 && $resultCh > 0) {
  1563. while ($row = $db->fetch_object($result)) {
  1564. $row = (array) $row;
  1565. $date = $row['ph_date_creation'];
  1566. $device[] = [
  1567. "name" => isset($row['title']) ? $row['title'] : '',
  1568. "sku" => isset($row['unique_identifier']) ? $row['unique_identifier'] : ''
  1569. ];
  1570. }
  1571. $change = [];
  1572. while ($rowCh = $db->fetch_object($resultCh)) {
  1573. $rowCh = (array) $rowCh;
  1574. $ChangeArray = explode('_', $rowCh['ref']);
  1575. $key = isset($ChangeArray[1]) ? strtolower($ChangeArray[1]) : '';
  1576. if (!empty($key)) {
  1577. $change[$key] = isset($rowCh['title']) ? $rowCh['title'] : '';
  1578. }
  1579. }
  1580. } else {
  1581. return [];
  1582. }
  1583. return [
  1584. 'date' => $date,
  1585. 'devices' => $device,
  1586. 'change' => $change
  1587. ];
  1588. }
  1589. /**
  1590. * Save card payment log
  1591. *
  1592. * @param string $invoice_ref
  1593. * @param string $data
  1594. *
  1595. * @return array|mixed Data without useless information
  1596. *
  1597. * @url POST /cardpaymentlog
  1598. *
  1599. * @throws RestException 401
  1600. * @throws RestException 403
  1601. * @throws RestException 404
  1602. */
  1603. public function cardPaymentLog(string $invoice_ref, string $data)
  1604. {
  1605. $result = 'OK';
  1606. $facture = new Facture($this->db);
  1607. if ($facture->fetch(0, $invoice_ref) > 0) {
  1608. $facture->array_options['options_payment_log'] = $data;
  1609. $facture->updateExtraField('payment_log');
  1610. $json = json_decode($data, true);
  1611. if (!empty($json['authorization_number'])) {
  1612. $sql = "
  1613. UPDATE " . MAIN_DB_PREFIX . "paiement
  1614. SET num_paiement='" . $json['authorization_number'] . "'
  1615. WHERE rowid=(
  1616. SELECT fk_paiement
  1617. FROM " . MAIN_DB_PREFIX . "paiement_facture
  1618. WHERE fk_facture={$facture->id}
  1619. )
  1620. ";
  1621. $this->db->query($sql);
  1622. }
  1623. } else {
  1624. $result = 'Missing invoice';
  1625. }
  1626. return $result;
  1627. }
  1628. /**
  1629. * Products list with children
  1630. *
  1631. * @param string $sortfield Sort field
  1632. * @param string $sortorder Sort order
  1633. * @param int $limit Limit for list
  1634. * @param int $page Page number
  1635. * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service)
  1636. * @param int $category Use this param to filter list by category
  1637. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)"
  1638. * @param bool $ids_only Return only IDs of product instead of all properties (faster, above all if list is long)
  1639. * @param int $variant_filter Use this param to filter list (0 = all, 1=products without variants, 2=parent of variants, 3=variants only)
  1640. * @param bool $pagination_data If this parameter is set to true the response will include pagination data. Default value is false. Page starts from 0
  1641. * @param int $includestockdata Load also information about stock (slower)
  1642. * @return array Array of product objects
  1643. *
  1644. * @url GET /products
  1645. *
  1646. * @throws RestException 401
  1647. * @throws RestException 403
  1648. * @throws RestException 404
  1649. */
  1650. public function products($sortfield = 't.ref', $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false, $variant_filter = 0, $pagination_data = false, $includestockdata = 0): array
  1651. {
  1652. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  1653. throw new RestException(403);
  1654. }
  1655. $productsArray = [];
  1656. $productsArray = (new ApiProductListHelper)->list($sortfield, $sortorder, $limit, $page, $mode, $category, $sqlfilters, $ids_only, $variant_filter, $pagination_data, $includestockdata);
  1657. return $productsArray;
  1658. }
  1659. /**
  1660. * Products list with children
  1661. *
  1662. * @param string $sortfield Sort field
  1663. * @param string $sortorder Sort order
  1664. * @param int $limit Limit for list
  1665. * @param int $page Page number
  1666. * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service)
  1667. * @param int $category Use this param to filter list by category
  1668. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)"
  1669. * @param bool $ids_only Return only IDs of product instead of all properties (faster, above all if list is long)
  1670. * @param int $variant_filter Use this param to filter list (0 = all, 1=products without variants, 2=parent of variants, 3=variants only)
  1671. * @param bool $pagination_data If this parameter is set to true the response will include pagination data. Default value is false. Page starts from 0
  1672. * @param int $includestockdata Load also information about stock (slower)
  1673. * @return array Array of product objects
  1674. *
  1675. * @url GET /productshotel
  1676. *
  1677. * @throws RestException 401
  1678. * @throws RestException 403
  1679. * @throws RestException 404
  1680. */
  1681. public function productshotel($sortfield = 't.ref', $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '', $ids_only = false, $variant_filter = 0, $pagination_data = false, $includestockdata = 0): array
  1682. {
  1683. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  1684. throw new RestException(403);
  1685. }
  1686. return (new ApiProductListHelper)->listhotel($sortfield, $sortorder, $limit, $page, $mode, $category, $sqlfilters, $ids_only, $variant_filter, $pagination_data, $includestockdata);
  1687. }
  1688. /**
  1689. * Create invoice
  1690. *
  1691. * @param array $invoice Invoice data
  1692. * @param array $lines Invoice lines
  1693. * @param array $payment Invoice payment
  1694. * @param string $cardPaymentLog Card payment log data
  1695. *
  1696. * @return array|mixed Data without useless information
  1697. *
  1698. * @url POST /invoice
  1699. */
  1700. public function invoice(array $invoice, array $lines, array $payment, string $cardPaymentLog = '', string $sendId = '', $server_host_curl = false, $company_invoice = '')
  1701. {
  1702. global $user;
  1703. $lockLabel = 'CREATE_INVOICE';
  1704. if (empty($sendId)) {
  1705. $sendId = substr(md5(rand()), 0, 8);
  1706. }
  1707. /**
  1708. * LOG SECTION
  1709. */
  1710. ApiBbusLog::appLog("{$sendId} === NEW INVOICE ===");
  1711. dol_syslog("{$sendId} === NEW INVOICE ===", LOG_INFO, 0);
  1712. ApiBbusLog::appLog("{$sendId} REQUEST: {$sendId}");
  1713. dol_syslog("{$sendId} REQUEST: {$sendId}", LOG_INFO, 0);
  1714. ApiBbusLog::appLog("{$sendId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})");
  1715. dol_syslog("{$sendId} User: {$user->firstname} {$user->lastname} (ID: {$user->id})", LOG_INFO, 0);
  1716. ApiBbusLog::appLog("{$sendId} " . json_encode([
  1717. 'invoice' => $invoice,
  1718. 'lines' => $lines,
  1719. 'payment' => $payment,
  1720. 'cardPaymentLog' => $cardPaymentLog
  1721. ]));
  1722. /**
  1723. * CHECK RIGHTS
  1724. */
  1725. if (!DolibarrApiAccess::$user->rights->facture->creer) {
  1726. ApiBbusLog::appLog("{$sendId} Insufficient rights");
  1727. throw new RestException(401, 'Insufficient rights');
  1728. }
  1729. $apiInvoiceHelper = new ApiInvoiceHelper;
  1730. /**
  1731. * handle invoice basic data
  1732. */
  1733. $invoiceObj = $apiInvoiceHelper->createInvoice($invoice, $sendId, $company_invoice);
  1734. ApiBbusLog::appLog("{$sendId} Invoice created");
  1735. /**
  1736. * handle invoice line(s)
  1737. */
  1738. $products = [];
  1739. foreach ($lines as $line) {
  1740. $invoiceObj = $apiInvoiceHelper->addLineToInvoice($invoiceObj, $line, $sendId);
  1741. $product = $apiInvoiceHelper->loadProductToResult($line);
  1742. if (!empty($product)) {
  1743. $products[] = $product;
  1744. }
  1745. }
  1746. $invoiceObj->fetch_lines();
  1747. foreach ($products as &$row) {
  1748. foreach ($invoiceObj->lines as $line) {
  1749. if ($line->product_ref == $row['ref']) {
  1750. //$row['price'] = $line->total_ttc;
  1751. $row['price'] = $line->multicurrency_total_ttc;
  1752. $row['total_tva'] = $line->total_tva;
  1753. //$row['total_tva'] = $line->multicurrency_total_tva;
  1754. }
  1755. }
  1756. }
  1757. /**
  1758. * validate
  1759. */
  1760. $invoiceObj = $apiInvoiceHelper->validateInvoice($invoiceObj, $sendId);
  1761. /**
  1762. * set payment
  1763. */
  1764. $apiInvoiceHelper->setPayment($invoiceObj, $payment, $sendId);
  1765. /**
  1766. * save card payment data
  1767. */
  1768. if (!empty($cardPaymentLog)) {
  1769. $invoiceObj = $apiInvoiceHelper->saveCardPaymentLog($invoiceObj, $cardPaymentLog, $sendId);
  1770. }
  1771. ApiBbusLog::appLog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}");
  1772. dol_syslog("{$sendId} Invoice created. ID: {$invoiceObj->id} REF: {$invoiceObj->ref} REQ: {$sendId}", LOG_INFO, 0);
  1773. //$bbApiLock->delete($user);
  1774. ApiBbusLog::appLog("{$sendId}####################################################################");
  1775. dol_syslog("{$sendId}####################################################################", LOG_INFO, 0);
  1776. #-------------- UPDATE BTICKET --------------
  1777. ApiBbusLog::appLog("{$sendId}: Update bbticket with curl");
  1778. $invoiceForCurl['id'] = $invoiceObj->id;
  1779. $invoiceForCurl['ref'] = $invoiceObj->ref;
  1780. //$array['fk_booking_history'] = null;
  1781. $array['invoice'] = $invoiceForCurl;
  1782. $updateBBticketPostFields = json_encode($array);
  1783. ApiBbusLog::appLog("{$updateBBticketPostFields}");
  1784. $this->curlRunner('bookingapi/curlUpdateBbticket', $updateBBticketPostFields, 'POST', true);
  1785. return [
  1786. 'sendId' => $sendId,
  1787. 'invoice' => [
  1788. 'id' => $invoiceObj->id,
  1789. 'ref' => $invoiceObj->ref,
  1790. 'total' => $invoiceObj->multicurrency_total_ttc
  1791. ],
  1792. 'products' => $products,
  1793. ];
  1794. }
  1795. /**
  1796. * Get the saled factures data by user
  1797. *
  1798. * @param string $date Date
  1799. *
  1800. * @return array|mixed Data without useless information
  1801. *
  1802. * @url POST /saledfacturesbyuser
  1803. */
  1804. function saledfacturesbyuser(string $date)
  1805. {
  1806. global $user, $db;
  1807. $date = date("Y-m-d", dol_now());
  1808. $fulldate = date("Y-m-d H:i:s", dol_now());
  1809. $apiBbusHelper = new ApiBBusHelper();
  1810. $from = $apiBbusHelper->getGroupLoginDate($date);
  1811. $to = $apiBbusHelper->getGroupLogout($date, $from);
  1812. $array = [];
  1813. if (strtotime($fulldate) > strtotime($to)) {
  1814. return $array;
  1815. }
  1816. $sql = "SELECT
  1817. f.rowid as facture_rowid,
  1818. f.ref AS facture_ref,
  1819. f.datec,
  1820. f.multicurrency_code,
  1821. pa.libelle,
  1822. pai.note AS transaction_id,
  1823. fdet.fk_product AS product_id,
  1824. pr.label AS product_label,
  1825. pr.ref AS product_ref,
  1826. pr.description,
  1827. pass.fk_product_pere AS bundle_id,
  1828. pr2.label AS bundle_label,
  1829. pr2.ref AS bundle_ref,
  1830. fdet.multicurrency_total_tva AS base_tva,
  1831. fdet.multicurrency_total_ttc AS base_ttc,
  1832. fdete.discount_percent,
  1833. fdete.discount_hours,
  1834. pr.default_vat_code,
  1835. f.multicurrency_total_ttc AS bundle_ttc,
  1836. (SELECT rate FROM llx_multicurrency_rate AS mc WHERE mc.fk_multicurrency = f.fk_multicurrency AND mc.entity = {$user->entity} ORDER BY mc.rowid DESC LIMIT 1) AS rate,
  1837. (SELECT date_start FROM llx_booking_bookinghistory AS bh WHERE bh.fk_facture = f.rowid) AS date_start
  1838. FROM llx_facture AS f
  1839. INNER JOIN llx_facture_extrafields AS fe ON fe.fk_object = f.rowid
  1840. INNER JOIN llx_c_paiement AS pa ON pa.id = f.fk_mode_reglement
  1841. INNER JOIN llx_paiement_facture AS pafa ON pafa.fk_facture = f.rowid
  1842. INNER JOIN llx_paiement AS pai ON pai.rowid = pafa.fk_paiement
  1843. INNER JOIN llx_facturedet AS fdet ON fdet.fk_facture = f.rowid
  1844. INNER JOIN llx_product AS pr ON pr.rowid = fdet.fk_product
  1845. left JOIN llx_product_association AS pass ON pass.fk_product_fils = pr.rowid
  1846. LEFT JOIN llx_product AS pr2 ON pr2.rowid = pass.fk_product_pere
  1847. LEFT JOIN llx_facturedet_extrafields AS fdete ON fdet.rowid = fdete.fk_object
  1848. WHERE f.datec BETWEEN '{$from}' AND '{$to}'
  1849. AND f.fk_user_closing = $user->id
  1850. ORDER BY f.rowid DESC";
  1851. //print $sql;exit;
  1852. $data = $db->query($sql);
  1853. if ($db->num_rows($data > 0)) {
  1854. while ($row = $db->fetch_object($data)) {
  1855. $tmpArray = (array) $row;
  1856. if ($tmpArray['transaction_id'] != '') {
  1857. $jsonArray = json_decode($tmpArray['transaction_id']);
  1858. $row->transaction_id = $jsonArray->card_transaction_id;
  1859. }
  1860. $row->bundle_id = $row->bundle_id == '' ? $row->product_id : $row->bundle_id;
  1861. $row->bundle_label = $row->bundle_label == '' ? $row->product_label : $row->bundle_label;
  1862. $row->bundle_ref = $row->bundle_ref == '' ? $row->product_ref : $row->bundle_ref;
  1863. $array[$row->facture_rowid]['ref'] = $row->facture_ref;
  1864. $array[$row->facture_rowid]['bundle_name'] = $row->bundle_label;
  1865. $array[$row->facture_rowid]['currency'] = $row->multicurrency_code;
  1866. $array[$row->facture_rowid]['total_price'] = $row->bundle_ttc;
  1867. $array[$row->facture_rowid]['type'] = $row->libelle;
  1868. $array[$row->facture_rowid]['transaction_id'] = $row->transaction_id;
  1869. $array[$row->facture_rowid]['rate'] = $row->rate;
  1870. $array[$row->facture_rowid]['date'] = $row->datec;
  1871. $array[$row->facture_rowid]['lines'][$row->product_id] = (array) $row;
  1872. }
  1873. return $array;
  1874. } else {
  1875. return $array;
  1876. }
  1877. }
  1878. /**
  1879. * List of assets received
  1880. *
  1881. * Return an array with assets received.
  1882. *
  1883. * @return array|mixed Data without useless information
  1884. *
  1885. * @url GET /getAllUsersOfTheGroup
  1886. *
  1887. * @throws RestException 401
  1888. * @throws RestException 403
  1889. * @throws RestException 404
  1890. */
  1891. public function getAllUsersOfTheGroup(): array
  1892. {
  1893. global $user, $db;
  1894. $array = [];
  1895. $sql = "SELECT u.rowid, u.firstname, u.lastname, u.login, ue.nickname, u.email, u.office_phone, u.user_mobile, u.personal_mobile FROM llx_settlements_groupusers AS gu
  1896. INNER JOIN llx_user_extrafields as ue ON ue.fk_object = gu.fk_user
  1897. INNER JOIN llx_user as u ON u.rowid = gu.fk_user
  1898. WHERE gu.fk_settlements_group = (SELECT gu2.fk_settlements_group FROM llx_settlements_groupusers as gu2 WHERE gu2.fk_user = {$user->id})";
  1899. $data = $db->query($sql);
  1900. while ($row = $db->fetch_object($data)) {
  1901. $array[] = [
  1902. 'id' => $row->rowid,
  1903. 'name' => $row->firstname . ' ' . $row->lastname,
  1904. 'login' => $row->login,
  1905. 'email' => $row->email,
  1906. 'nickname' => $row->nickname ? $row->nickname : '',
  1907. 'office_phone' => $row->office_phone,
  1908. 'user_mobile' => $row->user_mobile,
  1909. 'personal_mobile' => $row->personal_mobile
  1910. ];
  1911. }
  1912. return $array;
  1913. }
  1914. /**
  1915. * Generate events
  1916. *
  1917. * @return array|mixed Data without useless information
  1918. *
  1919. * @url GET /genEvents
  1920. *
  1921. * @throws RestException 401
  1922. * @throws RestException 403
  1923. * @throws RestException 404
  1924. */
  1925. public function genEvents()
  1926. {
  1927. $period = new DatePeriod(
  1928. new DateTime('2024-05-09'),
  1929. new DateInterval('P1D'),
  1930. new DateTime('2024-09-01')
  1931. );
  1932. $size = 30;
  1933. $buffer = 5;
  1934. $dates = [];
  1935. foreach ($period as $date) {
  1936. if (rand(0, 1)) {
  1937. $eventDate = $date->format('Y-m-d');
  1938. $eventTimes = array_rand(
  1939. array_flip([
  1940. '16:00',
  1941. '18:00',
  1942. '20:00',
  1943. '22:00'
  1944. ]),
  1945. rand(1, 4)
  1946. );
  1947. /* print $eventDate;
  1948. print "\r\n";
  1949. print_r($eventTimes); */
  1950. if (is_array($eventTimes)) {
  1951. foreach ($eventTimes as $eventTime) {
  1952. $dates[$eventDate][] = [
  1953. 'start' => $eventTime,
  1954. 'duration' => '02:00:00',
  1955. ];
  1956. }
  1957. }
  1958. }
  1959. }
  1960. $dates = ['dates' => $dates];
  1961. dol_include_once('/eventwizard/class/eventdetails.class.php');
  1962. $object = new EventDetails($this->db);
  1963. $object->fetch(1);
  1964. $object->genEvents($dates);
  1965. return [];
  1966. }
  1967. /**
  1968. * Generate events
  1969. *
  1970. * @return array|mixed Data without useless information
  1971. *
  1972. * @url GET /updateeventextrafields
  1973. *
  1974. * @throws RestException 401
  1975. * @throws RestException 403
  1976. * @throws RestException 404
  1977. */
  1978. public function updateEventsExtrafields()
  1979. {
  1980. $sql = "SELECT ac.id FROM llx_actioncomm as ac
  1981. LEFT JOIN llx_actioncomm_extrafields as ace ON ace.fk_object = ac.id
  1982. WHERE ac.code = 'AC_EVENT'
  1983. AND ace.fk_object IS NULL";
  1984. $result1 = $this->db->query($sql);
  1985. while ($row1 = $this->db->fetch_object($result1)) {
  1986. $sql2 = "INSERT INTO llx_actioncomm_extrafields (fk_object, max_num, buffer)
  1987. VALUES ({$row1->id}, 30, 5)";
  1988. $result = $this->db->query($sql2);
  1989. }
  1990. }
  1991. /**
  1992. * Generate factures
  1993. *
  1994. * @return array|mixed Data without useless information
  1995. *
  1996. * @url POST /generateFactures
  1997. *
  1998. * @throws RestException 401
  1999. * @throws RestException 403
  2000. * @throws RestException 404
  2001. */
  2002. public function generateFactures()
  2003. {
  2004. $numberOfFactures = 1;
  2005. for ($i = 0; $i < $numberOfFactures; $i++) {
  2006. $currencyRand = rand(0, 1);
  2007. $currencyText = [0 => 'HUF', 1 => 'EUR'];
  2008. $currencyNumber = [0 => 3, 1 => 5];
  2009. $reglementRand = rand(14, 15);
  2010. //$reglementRand = rand(106, 107); ## STAGING
  2011. $mode_reglement_id = $reglementRand;
  2012. $paymentid = $reglementRand;
  2013. $accountid = [0 => 4, 1 => 5];
  2014. $deduction = rand(1, 5) == 3 ? 1 : null;
  2015. $storno = rand(1, 5) == 1 ? 1 : null;
  2016. $invoice = ["mode_reglement_id" => $mode_reglement_id, "array_options_app_facture" => 1, "array_options_commission_deduction" => $deduction, "array_options_marked_for_storno" => $storno, "multicurrency_code" => $currencyText[$currencyRand], "fk_multicurrency" => $currencyNumber[$currencyRand], "array_options_customer_data_zip" => null];
  2017. $linesHUFBundle = [
  2018. ["desc" => "", "subprice" => "787.4015", "qty" => 1, "tva_tx" => "27.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "102", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"],
  2019. ["desc" => "", "subprice" => "13333.3333", "qty" => 1, "tva_tx" => "5.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "108", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"]
  2020. ];
  2021. $linesEURBundle = [
  2022. ["desc" => "", "subprice" => "2.3622", "qty" => 1, "tva_tx" => "27.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "101", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"],
  2023. ["desc" => "", "subprice" => "33.3333", "qty" => 1, "tva_tx" => "5.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "107", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"]
  2024. ];
  2025. $linesEURSimple = [
  2026. ["desc" => "", "subprice" => "12.5984", "qty" => 1, "tva_tx" => "27.0", "localtax1_tx" => "0.000", "localtax2_tx" => "0.000", "fk_product" => "132", "remise_percent" => "0", "date_start" => "", "date_end" => "", "fk_code_ventilation" => 0, "info_bits" => "0", "fk_remise_except" => null, "product_type" => "1", "rang" => "-1", "special_code" => "0", "fk_parent_line" => null, "fk_fournprice" => null, "pa_ht" => "0.00000000", "label" => "", "array_options" => [], "situation_percent" => "100", "fk_prev_id" => null, "fk_unit" => null, "price_base_type" => "HT"],
  2027. ];
  2028. $linesArray = [
  2029. 0 => $linesEURBundle,
  2030. 1 => $linesEURSimple,
  2031. 2 => $linesHUFBundle
  2032. ];
  2033. if ($currencyRand == 1) {
  2034. $lineRand = rand(0, 1);
  2035. $lines = $linesArray[$lineRand];
  2036. } else {
  2037. $lines = $linesArray[2];
  2038. }
  2039. $payment = ["datepaye" => time(), "paymentid" => $paymentid, "closepaidinvoices" => "yes", "accountid" => $accountid[$currencyRand]];
  2040. $comment = "{\"timestamp\":\"1704241200\",\"merchant_id\":\"000000000014202\",\"acquirer_id\":\"88105000003\",\"operation_number\":\"000037\",\"termid\":\"36002058\",\"pan\":\"428312******1789\",\"exp\":\"****\",\"stan\":\"000007\",\"authorization_number\":\"282597\",\"trans_type\":\"CLI\",\"amount\":\"2.0\",\"cvm\":\"2\",\"billnumber\":\"AcTbHmcWsMGcF6Nf\",\"card_transaction_id\":\"AcTbHmcWsMGcF6Nf\"}";
  2041. $payment['comment'] = $reglementRand == 15 ? '' : $comment;
  2042. //$payment['comment'] = $reglementRand == 107 ? '' : $comment; ## STAGING
  2043. $cardPaymentLog = "";
  2044. /* print_r($invoice);
  2045. print_r($lines);
  2046. print_r($payment);
  2047. exit; */
  2048. $invoiceNumber = $this->invoice($invoice, $lines, $payment, $cardPaymentLog, $sendId = '');
  2049. $ref = $invoiceNumber['invoice']['ref'];
  2050. $datetime = date("Y-m-d H:i:s", $payment['datepaye']);
  2051. $multiprint = rand(1, 5);
  2052. $this->dateHandler($ref, $datetime);
  2053. if ($multiprint == 2 || $multiprint == 3) {
  2054. $prints = rand(1, 5);
  2055. $dateofprint = $payment['datepaye'];
  2056. for ($i = 0; $i < $prints; $i++) {
  2057. $dateofprint = strtotime('+5 seconds', $dateofprint);
  2058. $datetime = date("Y-m-d H:i:s", $dateofprint);
  2059. $this->dateHandler($ref, $datetime);
  2060. }
  2061. }
  2062. }
  2063. return 'OK';
  2064. }
  2065. /**
  2066. * Generate events
  2067. *
  2068. * @return array|mixed Data without useless information
  2069. *
  2070. * @url GET /getDatetime
  2071. *
  2072. * @throws RestException 401
  2073. * @throws RestException 403
  2074. * @throws RestException 404
  2075. */
  2076. public function getDatetime()
  2077. {
  2078. $dateArray = [];
  2079. $now = dol_now();
  2080. $dateArray = ["timestamp" => $now, "date" => date("Y-m-d", $now), "datetime" => date("Y-m-d H:i:s", $now)];
  2081. return $dateArray;
  2082. }
  2083. /**
  2084. * Get the saled factures data by user
  2085. *
  2086. * @param string $ref Date
  2087. *
  2088. * @return array|mixed Data without useless information
  2089. *
  2090. * @url POST /curlgetdatecfromfacture
  2091. */
  2092. public function curlgetdatecfromfacture(string $ref)
  2093. {
  2094. $sql = "SELECT datec FROM llx_facture WHERE ref = '{$ref}'";
  2095. $result = $this->db->query($sql);
  2096. if ($this->db->num_rows($result) < 1) {
  2097. return [];
  2098. } else {
  2099. while ($row = $this->db->fetch_object($result)) {
  2100. return $row->datec;
  2101. }
  2102. }
  2103. }
  2104. /**
  2105. * Get the saled factures data by user
  2106. *
  2107. * @param string $ref Date
  2108. *
  2109. * @return array|mixed Data without useless information
  2110. *
  2111. * @url POST /curlgetproductidfromfacturedet
  2112. */
  2113. public function curlgetproductidfromfacturedet(string $ref)
  2114. {
  2115. ApiBbusLog::appLog("curlgetproductidfromfacturedet");
  2116. $helper = new ApiBBusHelper();
  2117. $facture_id = $helper->getFactureIdForInvoicePrinting($ref);
  2118. global $db;
  2119. $array = [];
  2120. $sql = "SELECT fk_product FROM public.llx_facturedet WHERE fk_facture = " . $facture_id;
  2121. $result = $db->query($sql);
  2122. while ($facturedetrecord = pg_fetch_assoc($result)) {
  2123. $array[] = $facturedetrecord['fk_product'];
  2124. }
  2125. return $array;
  2126. }
  2127. }