api_bbus.class_old.php 75 KB

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