api_bbus.class.php.bak 87 KB

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