api_bbus.class.php 88 KB

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