api_bbus.class.php 81 KB

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