api_bbus.class.php 80 KB

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