ticket_checker.class.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. <?php
  2. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
  3. use Luracast\Restler\RestException;
  4. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  5. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';
  6. class TicketChecker
  7. {
  8. use CurlApi;
  9. private $db;
  10. private $mac;
  11. private $code;
  12. private $lat;
  13. private $lon;
  14. private $printingTime;
  15. private $status = 0;
  16. private $device_id;
  17. private $service_location_id;
  18. private $product_id;
  19. private $fils = array();
  20. private $ticketIdForCheck;
  21. private $basic_service_id;
  22. private $ticket_id;
  23. private $bbTicketRowId;
  24. private $usage;
  25. private $facture_id;
  26. private $bundle_id;
  27. private $merged_tickets;
  28. private $imei;
  29. private $validated_at;
  30. private $expire_at;
  31. private $duration;
  32. private $productObj;
  33. private $factureObj;
  34. private $bbticketNaploObj;
  35. private $bbDevicesObj;
  36. private $BbDevicesServiceLocationObj;
  37. private $BbDevicesServiceLocationProductObj;
  38. private $bbticketObj;
  39. private $bbticketInvoicePrintingObj;
  40. public function __construct()
  41. {
  42. global $db, $conf, $user;
  43. $this->db = $db;
  44. $this->user = $user;
  45. $this->productObj = new Product($this->db);
  46. $this->factureObj = new Facture($this->db);
  47. $this->bbticketNaploObj = new BbTicketNaplo($this->db);
  48. $this->bbDevicesObj = new BbDevices($this->db);
  49. $this->BbDevicesServiceLocationObj = new BbDevicesServiceLocation($this->db);
  50. $this->BbDevicesServiceLocationProductObj = new BbDevicesServiceLocationProduct($this->db);
  51. $this->bbticketObj = new BbTicket($this->db);
  52. $this->bbticketInvoicePrintingObj = new BbTicketInvoicePrinting($this->db);
  53. }
  54. public function setMac($mac)
  55. {
  56. $this->mac = $mac;
  57. }
  58. public function setCode($code)
  59. {
  60. $code_and_timstamp = explode('_', $code);
  61. $this->code = $code_and_timstamp[0];
  62. }
  63. public function setLat($lat)
  64. {
  65. $this->lat = $lat;
  66. }
  67. public function setLon($lon)
  68. {
  69. $this->lon = $lon;
  70. }
  71. public function setTimestamp($code, $log, $logId)
  72. {
  73. global $user;
  74. $code_and_timstamp = explode('_', $code);
  75. $this->printingTime = $code_and_timstamp[1];
  76. if (empty($this->printingTime)) {
  77. ApiBbusLog::$log("{$logId} Timestamp is empty!");
  78. throw new RestException(404, 'Timestamp is empty!');
  79. }
  80. }
  81. public function setImei($imei, $logId)
  82. {
  83. global $user;
  84. $this->imei = $imei;
  85. if (empty($this->imei)) {
  86. ApiBbusLog::ticketvalidationByPhone("{$logId} IMEI is empty!");
  87. throw new RestException(404, 'IMEI is empty!');
  88. }
  89. }
  90. public function SetTicketidFromPhone($ticketid, $logId)
  91. {
  92. $this->ticket_id = $ticketid;
  93. ApiBbusLog::ticketvalidationByPhone("{$logId} Ticketid: {$this->ticket_id}");
  94. if (empty($this->ticket_id)) {
  95. ApiBbusLog::ticketvalidationByPhone("{$logId} Ticketid is empty!");
  96. throw new RestException(404, 'Ticketid is empty!');
  97. }
  98. }
  99. public function set_device_id()
  100. {
  101. $result = $this->bbDevicesObj->fetchAll('ASC', 'date_creation', 1, 0, ["customsql" => "device_id = '" . $this->mac . "'"]);
  102. $this->setId($result, 'BbDevices', 'device_id', 'id');
  103. }
  104. public function set_service_location_id()
  105. {
  106. $result = $this->BbDevicesServiceLocationObj->fetchAll('ASC', 'date_creation', 1, 0, ['customsql' => "device_id = " . $this->device_id]);
  107. $this->setId($result, 'device_servicelocation', 'service_location_id', 'id');
  108. }
  109. public function set_basic_service_id()
  110. {
  111. $result = $this->BbDevicesServiceLocationProductObj->fetchAll('ASC', 'date_creation', 1, 0, ['customsql' => "devicesservicelocation_id = " . $this->service_location_id]);
  112. $this->setId($result, 'device_service_location_product', 'basic_service_id', 'basic_service');
  113. }
  114. public function get_Basic_service_array()
  115. {
  116. $productRowIdsArray = [];
  117. $sql = "SELECT fk_object FROM " . $this->db->prefix() . $this->productObj->table_element . "_extrafields WHERE basic_service = '{$this->basic_service_id}'";
  118. $productsRowIDs = $this->db->query($sql);
  119. while ($row = pg_fetch_assoc($productsRowIDs)) {
  120. $productRowIdsArray[] = $row['fk_object'];
  121. }
  122. return $productRowIdsArray;
  123. }
  124. public function setTicketId($logId)
  125. {
  126. $this->set_device_id();
  127. $this->set_service_location_id();
  128. $this->set_basic_service_id();
  129. $this->set_ticketIDForCheck();
  130. if (!isset($this->ticketIdForCheck)) {
  131. ApiBbusLog::getByBarcode("{$logId} Invalid ticket");
  132. throw new RestException(404, 'Invalid ticket');
  133. }
  134. $sqlBbticketInvoicePrinting = "SELECT * FROM " . $this->db->prefix() . $this->bbticketInvoicePrintingObj->table_element . " WHERE printing_date_timestamp ILIKE '%{$this->printingTime}%' AND product_id = {$this->ticketIdForCheck}";
  135. //print $sqlBbticketInvoicePrinting;exit;
  136. $resultBBT = $this->db->query($sqlBbticketInvoicePrinting);
  137. while ($row = pg_fetch_assoc($resultBBT)) {
  138. $result2[$row['rowid']] = (object) $row;
  139. }
  140. //print_r($result2);exit;
  141. $this->setId($result2, 'bbticketinvoiceprinting', 'ticket_id', 'ticket_id');
  142. }
  143. public function set_ticketIDForCheck()
  144. {
  145. $basic_service_array = $this->get_Basic_service_array();
  146. foreach ($this->fils as $elem) {
  147. if (in_array($elem, $basic_service_array)) {
  148. $this->ticketIdForCheck = $elem;
  149. }
  150. }
  151. }
  152. public function check5Minutes($logId)
  153. {
  154. ApiBbusLog::getByBarcode("check5Minutes!!!!");
  155. $result = $this->bbticketNaploObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "ticket_row_id = {$this->bbTicketRowId}"]);
  156. if ($result > 0) {
  157. foreach ($result as $ticket) {
  158. if (strtotime("+5 minutes", $ticket->date_creation) > dol_now()) {
  159. ApiBbusLog::getByBarcode("{$logId} Too fast!");
  160. throw new RestException(401, 'Too fast');
  161. }
  162. }
  163. }
  164. }
  165. public function setFilsArray()
  166. {
  167. if (is_null($this->facture_id)) {
  168. $this->curlSetFilsArray($this->code);
  169. }else{
  170. $sql = "SELECT fdet.fk_product FROM " . $this->db->prefix() . $this->factureObj->table_element . " AS f
  171. INNER JOIN " . $this->db->prefix() . $this->factureObj->table_element_line . " as fdet ON fdet.fk_facture = f.rowid
  172. INNER JOIN " . $this->db->prefix() . $this->productObj->table_element . " AS p ON p.rowid = fdet.fk_product
  173. WHERE f.rowid = {$this->facture_id}";
  174. $result = $this->db->query($sql);
  175. while ($sqlDataResult = pg_fetch_assoc($result)) {
  176. $this->fils[] = $sqlDataResult['fk_product'];
  177. }
  178. }
  179. }
  180. public function curlSetFilsArray($ref)
  181. {
  182. $postFields = '{"ref":"' . $ref . '"}';
  183. $this->fils = $this->curlRunner('bbus/curlGetFilsArray', $postFields, 'POST', true);
  184. }
  185. public function setFactureId($log, $logId)
  186. {
  187. $sqlFacture = "SELECT rowid FROM " . $this->db->prefix() . $this->factureObj->table_element . " WHERE ref ILIKE '%{$this->code}%'";
  188. $result = $this->db->query($sqlFacture);
  189. if (pg_num_rows($result) > 0) {
  190. while ($adatok = pg_fetch_assoc($result)) {
  191. $factureRowid = $adatok['rowid'];
  192. }
  193. } else {
  194. ApiBbusLog::$log("{$logId} Invoice not found. Maybe cross-shopping: {$this->code}");
  195. $this->facture_id = null;
  196. //throw new RestException(404, 'Invoice not found.');
  197. }
  198. if(!is_null($factureRowid)){
  199. $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->factureObj->table_element . " WHERE fk_facture_source = {$factureRowid} AND type = 2";
  200. $res = $this->db->query($sql);
  201. if (pg_num_rows($res) > 0) {
  202. ApiBbusLog::$log("{$logId} Invoice has a Credit account.");
  203. throw new RestException(404, 'Invoice has a Credit account.');
  204. }
  205. $this->facture_id = $factureRowid;
  206. }
  207. }
  208. public function setBbTicketRowId($id)
  209. {
  210. $this->bbTicketRowId = $id;
  211. }
  212. public function saveData($selectedTicket)
  213. {
  214. global $user;
  215. if ($this->newTicket($selectedTicket)) {
  216. $this->validated_at = date('Y-m-d H:i:s');
  217. $this->setDurationByProductId($selectedTicket->ticket_id);
  218. $this->setExpireAt($selectedTicket);
  219. $this->setUsage($selectedTicket);
  220. if ($this->merged_tickets) {
  221. $tickets = $this->getAllTicketsByfactureIdAndTimestamp();
  222. foreach ($tickets as $key => $value) {
  223. $sql = "UPDATE " . $this->db->prefix() . $this->bbticketObj->table_element . " SET validated_at = '" . $this->validated_at . "', expire_at = '" . $this->expire_at . "'";
  224. if ($key == $this->bbTicketRowId && $this->usage != 0) {
  225. $sql .= ", usage = '" . $this->usage . "'";
  226. }
  227. $sql .= " WHERE rowid = " . $key;
  228. $this->bbTicketRowId = $key;
  229. $this->saveAndCreateNaplo($sql);
  230. }
  231. } else {
  232. $sql = "UPDATE " . $this->db->prefix() . $this->bbticketObj->table_element . " SET usage = '" . $this->usage . "', validated_at = '" . $this->validated_at . "', expire_at = '" . $this->expire_at . "' WHERE rowid = " . $this->bbTicketRowId;
  233. $this->saveAndCreateNaplo($sql);
  234. }
  235. } else {
  236. $this->setUsage($selectedTicket);
  237. $sql = "UPDATE " . $this->db->prefix() . $this->bbticketObj->table_element . " SET usage = '" . $this->usage . "' WHERE rowid = " . $this->bbTicketRowId;
  238. $this->saveAndCreateNaplo($sql);
  239. }
  240. }
  241. public function saveCoordinates($logId)
  242. {
  243. global $db, $user;
  244. $bbTicketValidationCoordsObj = new BbTicketValidationCoords($db);
  245. $bbTicketValidationCoordsObj->fk_ticket = $this->bbTicketRowId;
  246. $bbTicketValidationCoordsObj->device_id = $this->device_id;
  247. $bbTicketValidationCoordsObj->location_id = $this->service_location_id;
  248. $bbTicketValidationCoordsObj->lat = $this->lat;
  249. $bbTicketValidationCoordsObj->lon = $this->lon;
  250. if ($bbTicketValidationCoordsObj->create($user) < 0) {
  251. ApiBbusLog::getByBarcode("{$logId} ##ERROR## Nem sikerult menteni a jegy koordinatait.");
  252. dol_syslog("{$logId} ##ERROR## Nem sikerult menteni a jegy koordinatait.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  253. }
  254. ApiBbusLog::getByBarcode("{$logId} Koordinatak mentve");
  255. }
  256. private function newTicket($selectedTicket)
  257. {
  258. return is_null($selectedTicket->validated_at) && is_null($selectedTicket->expire_at) || empty($selectedTicket->validated_at) && empty($selectedTicket->expire_at);
  259. }
  260. private function setExpireAt($selectedTicket)
  261. {
  262. $discountArray = $this->getDiscountFromfacturedet($selectedTicket->ticket_id);
  263. if (!empty($discountArray)) {
  264. $this->expire_at = date('Y-m-d H:i:s', strtotime($this->validated_at . ' +' . substr($this->duration, 0, -1) . ' ' . $this->getIntervalTimeByDuration() . ' +' . $discountArray['value'] . ' hours'));
  265. } else {
  266. $this->expire_at = date('Y-m-d H:i:s', strtotime($this->validated_at . ' +' . substr($this->duration, 0, -1) . ' ' . $this->getIntervalTimeByDuration()));
  267. }
  268. }
  269. private function getDiscountFromFActuredet($ticket_id)
  270. {
  271. $sql = "SELECT fdete.discount_hours AS value FROM " . $this->db->prefix() . $this->factureObj->table_element . " AS f
  272. INNER JOIN " . $this->db->prefix() . $this->factureObj->table_element_line . " AS fdet ON f.rowid = fdet.fk_facture
  273. INNER JOIN " . $this->db->prefix() . "facturedet_extrafields AS fdete ON fdete.fk_object = fdet.rowid
  274. WHERE f.rowid = {$this->facture_id} AND fdet.fk_product = {$ticket_id}";
  275. $res = $this->db->query($sql);
  276. if (pg_num_rows($res) > 0) {
  277. while ($adatok = pg_fetch_assoc($res)) {
  278. return $adatok;
  279. }
  280. } else {
  281. return [];
  282. }
  283. }
  284. private function setDurationByProductId($ticket_id)
  285. {
  286. $sql = "SELECT p.duration as duration FROM " . $this->db->prefix() . $this->productObj->table_element . " AS p WHERE rowid = " . $ticket_id;
  287. $result = $this->getDataFromDatabase($sql, "Product");
  288. $this->duration = $this->getIdFromResult($result, 'duration');
  289. }
  290. private function getIdFromResult($res, $fieldName)
  291. {
  292. while ($adatok = pg_fetch_assoc($res)) {
  293. return $adatok[$fieldName];
  294. }
  295. }
  296. private function getIntervalTimeByDiscountPeriod($period)
  297. {
  298. switch ($period) {
  299. case 'hour':
  300. return 'hours';
  301. case 'day':
  302. return 'days';
  303. default:
  304. return 'hours';
  305. }
  306. }
  307. private function getIntervalTimeByDuration()
  308. {
  309. $duration = $this->duration[-1];
  310. switch ($duration) {
  311. case 'h':
  312. return 'hours';
  313. case 'd':
  314. return 'days';
  315. case 'w':
  316. return 'weeks';
  317. case 'm':
  318. return 'months';
  319. case 'y':
  320. return 'years';
  321. default:
  322. return 'hours';
  323. }
  324. }
  325. private function setUsage($selectedTicket)
  326. {
  327. $this->usage = $selectedTicket->usage;
  328. if ($selectedTicket->usable_occasions !== 0) {
  329. $this->usage++;
  330. }
  331. }
  332. private function getAllTicketsByfactureIdAndTimestamp()
  333. {
  334. $tickets = [];
  335. $sql = "SELECT ip.ticket_id, t.usable_occasions FROM " . $this->db->prefix() . $this->bbticketInvoicePrintingObj->table_element . " as ip
  336. INNER JOIN " . $this->db->prefix() . $this->bbticketObj->table_element . " as t ON t.rowid = ip.ticket_id
  337. WHERE ip.printing_date_timestamp = '{$this->printingTime}' AND ip.fk_facture = {$this->facture_id}";
  338. $res = $this->db->query($sql);
  339. while ($result = pg_fetch_assoc($res)) {
  340. $tickets[$result['ticket_id']] = $result['usable_occasions'];
  341. }
  342. return $tickets;
  343. }
  344. public function checkExceptionHandlers($selectedTicket, $log, $logId)
  345. {
  346. $now = strtotime(date("Y-m-d H:i:s"));
  347. if ($selectedTicket->usage == $selectedTicket->usable_occasions && $selectedTicket->usable_occasions != 0) {
  348. ApiBbusLog::$log("{$logId} Out of usage!");
  349. $this->ExceptionHandler(2, 'Out of usage!');
  350. }
  351. if ($selectedTicket->available_at < $now || ((!is_null($selectedTicket->expire_at) && !empty($selectedTicket->expire_at)) && $selectedTicket->expire_at < $now)) {
  352. ApiBbusLog::$log("{$logId} Expired!");
  353. $this->ExceptionHandler(1, 'Expired');
  354. }
  355. }
  356. private function ExceptionHandler($status, $message)
  357. {
  358. $this->status = $status;
  359. $this->saveBbTicketNaplo();
  360. throw new RestException(401, $message);
  361. }
  362. private function saveAndCreateNaplo($sql)
  363. {
  364. $this->bbticketUpdate($sql);
  365. $this->saveBbTicketNaplo();
  366. }
  367. private function bbticketUpdate($sql)
  368. {
  369. $updated = $this->db->query($sql);
  370. if (!$updated) {
  371. dol_syslog("Nem sikerult a ticketek updateje. facture_id: " . $this->facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  372. throw new RestException(404, 'Update failed');
  373. }
  374. }
  375. private function saveBbTicketNaplo()
  376. {
  377. global $user;
  378. $bbTicketNaplo = new BbTicketNaplo($this->db);
  379. $bbTicketNaplo->ticket_row_id = $this->bbTicketRowId;
  380. $bbTicketNaplo->bbservicelocation_id = isset($this->service_location_id) ? $this->service_location_id : null;
  381. $bbTicketNaplo->device_id = isset($this->device_id) ? $this->device_id : null;
  382. $bbTicketNaplo->status = $this->status;
  383. if ($bbTicketNaplo->create($user) < 0) {
  384. print_r($bbTicketNaplo->error);exit;
  385. dol_syslog('Nem sikerult menteni a bbticketNaplo tablaba a rekordot.', LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  386. throw new RestException(500, 'Nem sikerult menteni a bbticketNaplo tablaba a rekordot.');
  387. }
  388. }
  389. public function setMergedTickets($selectedTicket, $log, $logId)
  390. {
  391. $this->bundle_id = $selectedTicket->bundle_id;
  392. $sql = "SELECT merged_tickets FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $this->bundle_id;
  393. $result = $this->getDataFromDatabase($sql, "Product_extrafields");
  394. while ($adatok = pg_fetch_assoc($result)) {
  395. $this->merged_tickets = $adatok['merged_tickets'] == 1 ? true : false;
  396. if($this->merged_tickets){
  397. ApiBbusLog::$log("{$logId} Merged ticket");
  398. }
  399. }
  400. }
  401. public function checkBbTicketInvoicePrinting()
  402. {
  403. $result = $this->bbticketInvoicePrintingObj->fetchAll('', '', 0, 0, ['customsql' => "printing_date_timestamp = '{$this->printingTime}' AND fk_facture = {$this->facture_id} AND ticket_id = {$this->ticket_id}"]);
  404. $this->checkResult($result, 'bbticketinvoiceprinting');
  405. }
  406. public function getDataOfTheSelectedTicket()
  407. {
  408. $result = $this->bbticketObj->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => "rowid = {$this->ticket_id} AND fk_ticket IS NULL"]);
  409. $this->checkResult($result, 'bbticket');
  410. foreach ($result as $device) {
  411. $selectedTicket = $device;
  412. }
  413. return $selectedTicket;
  414. }
  415. #_______________________________________________________________
  416. private function getDataFromDatabase($sql, $name)
  417. {
  418. $res = $this->db->query($sql);
  419. $this->checkValidation($res, $name);
  420. return $res;
  421. }
  422. private function checkValidation($res, $name)
  423. {
  424. if (pg_num_rows($res) == 0) {
  425. throw new RestException(404, $name . ' not found');
  426. }
  427. }
  428. private function setId($result, $tableName, $variableName, $fieldName)
  429. {
  430. $this->checkResult($result, $tableName);
  431. foreach ($result as $device) {
  432. $this->$variableName = $device->$fieldName;
  433. }
  434. }
  435. private function checkResult($result, $tableName)
  436. {
  437. if (!is_array($result) || empty($result)) {
  438. dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  439. throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
  440. }
  441. }
  442. public function getTicketTypeByProductId($product_id){
  443. $productObj = new Product($this->db);
  444. $result = $productObj->fetch($product_id);
  445. if($result > 0){
  446. $basicServicesObj = new BasicServices($this->db);
  447. $resultBS = $basicServicesObj->fetch($productObj->array_options['options_basic_service']);
  448. if($resultBS > 0){
  449. return $basicServicesObj->server_host;
  450. }
  451. }else{
  452. return false;
  453. }
  454. }
  455. }