api_bbus.class.php 87 KB

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