api_bbus.class.php 79 KB

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