api_bbus.class.php.bak 86 KB

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