api_bbus.class.php 88 KB

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