api_bbus.class.php 87 KB

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