api_bbus_helper.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. <?php
  2. use Luracast\Restler\RestException;
  3. include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  4. require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
  5. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/userloginnaplo.class.php';
  6. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticket.class.php';
  7. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketinvoiceprinting.class.php';
  8. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';
  9. class ApiBBusHelper
  10. {
  11. use CurlApi;
  12. public $db;
  13. const EMAIL_TEMPLATE = 'multiticketprinting';
  14. const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
  15. const GLOBAL_CONF_EMAIL_FROM = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL_FROM';
  16. public function __construct()
  17. {
  18. global $db, $user;
  19. $this->db = $db;
  20. }
  21. public function getSaledItems($date)
  22. {
  23. global $user, $db;
  24. $from = $this->getGroupLoginDate($date);
  25. $to = $this->getGroupLogout($date, $from);
  26. $fulldate = date("Y-m-d H:i:s", dol_now());
  27. $facturesArray = [];
  28. if(strtotime($fulldate) > strtotime($to)){
  29. return $facturesArray;
  30. }
  31. $sql = "SELECT f.rowid, pa.fk_product_pere, pr.label, pa.fk_product_fils, fdet.multicurrency_total_ttc, fdet.multicurrency_code FROM
  32. llx_facture AS f
  33. INNER JOIN llx_facturedet AS fdet ON fdet.fk_facture = f.rowid
  34. INNER JOIN llx_product_association AS pa ON pa.fk_product_fils = fdet.fk_product
  35. INNER JOIN llx_product AS pr ON pr.rowid = pa.fk_product_pere
  36. WHERE f.fk_user_author = {$user->id}
  37. AND f.entity = {$user->entity}
  38. AND f.fk_statut = 2
  39. AND f.datec BETWEEN '{$from}' AND '{$to}'
  40. UNION
  41. SELECT f.rowid, fdet.fk_product as fk_product_pere, pr.label, fdet.fk_product as fk_product_fils, fdet.multicurrency_total_ttc, fdet.multicurrency_code FROM
  42. llx_facture AS f
  43. INNER JOIN llx_facturedet AS fdet ON fdet.fk_facture = f.rowid
  44. INNER JOIN llx_product AS pr ON pr.rowid = fdet.fk_product
  45. INNER JOIN llx_product_extrafields as pre ON pre.fk_object = pr.rowid
  46. WHERE f.fk_user_author = {$user->id}
  47. AND f.entity = {$user->entity}
  48. AND f.fk_statut = 2
  49. AND pre.is_in_bundle IS NULL
  50. AND f.datec BETWEEN '{$from}' AND '{$to}'";
  51. //print $sql;exit;
  52. $facatures = $db->query($sql);
  53. $this->checkValidation($facatures, 'Factures');
  54. while ($row = pg_fetch_assoc($facatures)) {
  55. $facturesArray[] = $row;
  56. }
  57. return $facturesArray;
  58. }
  59. public function getGroupLoginDate($date)
  60. {
  61. global $user, $db;
  62. $sqlusernaploLogin = "SELECT date_creation FROM public.llx_settlements_usernaplo
  63. WHERE user_id = $user->id
  64. AND status = 1
  65. ORDER BY rowid DESC LIMIT 1";
  66. $resultLogin = $db->query($sqlusernaploLogin);
  67. if(pg_num_rows($resultLogin) > 0 && strtotime($date) == strtotime(date('Y-m-d', dol_now()))){
  68. while ($row = pg_fetch_assoc($resultLogin)) {
  69. return $row['date_creation'];
  70. }
  71. }
  72. return $date . ' 00:00:00';
  73. }
  74. public function getGroupLogout($date, $from)
  75. {
  76. global $user, $db;
  77. $sqlusernaploLogin = "SELECT date_creation FROM public.llx_settlements_usernaplo
  78. WHERE user_id = $user->id
  79. AND status = 0
  80. ORDER BY rowid DESC LIMIT 1";
  81. $resultLogin = $db->query($sqlusernaploLogin);
  82. if(pg_num_rows($resultLogin) > 0){
  83. while ($row = pg_fetch_assoc($resultLogin)) {
  84. $to = $row['date_creation'];
  85. }
  86. }
  87. return $from > $to ? $date . ' ' . date('H:i:s', dol_now()) : $to;
  88. }
  89. public function getSaledItemsArray($facturesArray)
  90. {
  91. $pereArray = [];
  92. foreach ($facturesArray as $item) {
  93. $pereArray[$item['rowid']]['pere'] = $item['fk_product_pere'];
  94. $pereArray[$item['rowid']]['label'] = $item['label'];
  95. if (isset($item['rowid'])) {
  96. $pereArray[$item['rowid']]['sum'] += $item['multicurrency_total_ttc'];
  97. } else {
  98. $pereArray[$item['rowid']]['sum'] = $item['multicurrency_total_ttc'];
  99. }
  100. $pereArray[$item['rowid']]['currency'] = $item['multicurrency_code'];
  101. }
  102. $resultArray = [];
  103. foreach ($pereArray as $record) {
  104. if (isset($record['pere'])) {
  105. $resultArray[$record['pere']]['sum'] += $record['sum'];
  106. } else {
  107. $resultArray[$record['pere']]['sum'] = $record['sum'];
  108. }
  109. if (isset($record['pere'])) {
  110. $resultArray[$record['pere']]['count']++;
  111. ;
  112. } else {
  113. $resultArray[$record['pere']]['count'] = 1;
  114. }
  115. $resultArray[$record['pere']]['label'] = $record['label'];
  116. $resultArray[$record['pere']]['currency'] = $record['currency'];
  117. }
  118. $array = [];
  119. foreach ($resultArray as $row) {
  120. $array[] = $row;
  121. }
  122. return $array;
  123. }
  124. private function checkValidation($res, $name)
  125. {
  126. if (pg_num_rows($res) == 0) {
  127. throw new RestException(404, $name . ' not found');
  128. }
  129. }
  130. public function getFactureIdForInvoicePrinting($ref)
  131. {
  132. global $db;
  133. $sql = "SELECT * FROM llx_facture WHERE ref = '{$ref}'";
  134. ApiBbusLog::appLog("{$sql}");
  135. $resultBBT = $db->query($sql);
  136. if (pg_num_rows($resultBBT) < 1) {
  137. return [];
  138. }
  139. while ($row = pg_fetch_assoc($resultBBT)) {
  140. return $row['rowid'];
  141. }
  142. }
  143. public function setPrintingInvoiceObject($user, $facture_id, $datetime, $datetime_timestamp, $ticket, $ref)
  144. {
  145. global $db;
  146. $newCopy = new BbTicketInvoicePrinting($db);
  147. $newCopy->fk_user_api_key = $user->api_key;
  148. $newCopy->fk_facture = $facture_id;
  149. $newCopy->printing_date = $datetime;
  150. $newCopy->printing_date_timestamp = $datetime_timestamp;
  151. $newCopy->ticket_id = $ticket->id; //bbticket -> rowid
  152. $newCopy->product_id = $ticket->ticket_id; // product -> rowid = bbticket->ticket_id
  153. $newCopy->invoice_number = $ref; // product -> rowid = bbticket->ticket_id
  154. if ($newCopy->create($user) > 0) {
  155. ApiBbusLog::appLog("Invoiceprinting saved");
  156. // successful saving
  157. } else {
  158. ApiBbusLog::appLog("Invoiceprinting Insert failed");
  159. dol_syslog("Nem sikerult a bbticketinvoiceprinting insertje. facture_id: {$facture_id} datetime: {$datetime}");
  160. throw new RestException(404, 'Insert failed');
  161. }
  162. }
  163. public function getTicketIdsByFactureId($facture_id)
  164. {
  165. $object = new stdClass();
  166. $object->fk_facture = $facture_id;
  167. $object->fk_product = $this->getproductIdFromFActuredet($facture_id);
  168. $bbTicketHandler = new BbTicketHandler();
  169. // uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
  170. return $bbTicketHandler->addTicketForPrinting($object);
  171. }
  172. public function getTicketIdsForCrossShopping($ref)
  173. {
  174. ApiBbusLog::appLog("getTicketIdsForCrossShopping");
  175. $object = new stdClass();
  176. $object->invoice_number = $ref;
  177. $object->fk_product = $this->curlGetproductIdFromFActuredet($ref);
  178. $bbTicketHandler = new BbTicketHandler();
  179. // uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
  180. return $bbTicketHandler->addTicketForPrintingCrossShopping($object);
  181. }
  182. function curlGetproductIdFromFActuredet($ref){
  183. $params = '{"ref":"' . $ref . '"}';
  184. return $this->curlRunner('bbus/curlgetproductidfromfacturedet', $params, 'POST', true);
  185. }
  186. private function getproductIdFromFActuredet($facture_id)
  187. {
  188. global $db;
  189. $array = [];
  190. $sql = "SELECT fk_product FROM public.llx_facturedet WHERE fk_facture = " . $facture_id;
  191. $result = $db->query($sql);
  192. while ($facturedetrecord = pg_fetch_assoc($result)) {
  193. $array[] = $facturedetrecord['fk_product'];
  194. }
  195. return $array;
  196. }
  197. public function sendMail($fk_facture, $datetime, $now): void
  198. {
  199. $const = new GlobalConst;
  200. $recipients = $const->load(self::GLOBAL_CONF_SEND_TO_EMAIL);
  201. $emailFrom = $const->load(self::GLOBAL_CONF_EMAIL_FROM);
  202. //$recipients = 'szollosi.laszlo@urbanms.hu';
  203. //$emailFrom = 'bbus@urbanms.hu';
  204. if (!empty($recipients) && !empty($emailFrom)) {
  205. $emailTemplateHandler = new EmailTemplateHandler;
  206. $template = $emailTemplateHandler->load(self::EMAIL_TEMPLATE);
  207. $templateObject = new stdClass();
  208. foreach ($template as $key => $value) {
  209. $templateObject->$key = $value;
  210. }
  211. if ($templateObject) {
  212. $vars = [
  213. '__FACTURE__' => $fk_facture,
  214. '__DATETIME__' => $datetime,
  215. '__PRINTINGDATE__' => $now
  216. ];
  217. $template = $emailTemplateHandler->prepareTemplate($templateObject, $vars);
  218. $mail = new CMailFile(
  219. $template->topic,
  220. $recipients,
  221. $emailFrom,
  222. $template->content,
  223. null,
  224. null,
  225. null,
  226. '',
  227. '',
  228. 0,
  229. 1
  230. );
  231. // Send Email
  232. $mail->sendfile();
  233. if ($mail->error) {
  234. //print_r($mail->error);
  235. //exit;
  236. // do something...
  237. dol_syslog('CRON ALERT EMAIL ERROR: ' . $mail->error, LOG_ERR);
  238. }
  239. }
  240. }
  241. }
  242. /**
  243. *
  244. */
  245. public function getAppCustomers(): array
  246. {
  247. $customers = [];
  248. $table = (new Societe($this->db))->table_element;
  249. $sql = "
  250. SELECT soc.rowid AS id, soc.nom AS name, soc.address, soc.zip, soc.town, (CASE WHEN soc.nom ILIKE '%eur%' THEN 'EUR' ELSE 'HUF' END) AS currency
  251. FROM ".MAIN_DB_PREFIX.$table." as soc
  252. INNER JOIN ".MAIN_DB_PREFIX.$table."_extrafields as socex ON soc.rowid = socex.fk_object
  253. WHERE socex.is_general_customer = 1
  254. ORDER BY soc.rowid ASC
  255. ";
  256. $rows = $this->db->query($sql);
  257. if ($rows) {
  258. while ($row = $this->db->fetch_object($rows)) {
  259. $row->full_address = implode(' ', [
  260. $row->zip,
  261. $row->town,
  262. $row->address
  263. ]);
  264. $customers[$row->currency] = $row;
  265. }
  266. }
  267. return $customers;
  268. }
  269. function getAccountRowid($entity)
  270. {
  271. $sql = "SELECT ba.currency_code, ba.rowid FROM llx_bank_account as ba WHERE entity = {$entity} ORDER BY rowid ASC";
  272. //$sql = "SELECT mc.code, mc.rowid FROM llx_multicurrency as mc WHERE entity = {$entity}";
  273. $data = $this->db->query($sql);
  274. $accounts = [];
  275. while ($row = pg_fetch_array($data)) {
  276. $accounts[$row['currency_code']] = $row['rowid'];
  277. //$accounts[$row['code']] = $row['rowid'];
  278. }
  279. return $accounts;
  280. }
  281. function getCurrenciesRowid($entity)
  282. {
  283. $sql = "SELECT mc.rowid, mc.code FROM llx_multicurrency as mc WHERE entity = {$entity} ORDER BY rowid ASC";
  284. $data = $this->db->query($sql);
  285. $currencies = [];
  286. while ($row = pg_fetch_array($data)) {
  287. $currencies[$row['code']] = $row['rowid'];
  288. }
  289. return $currencies;
  290. }
  291. function getPaymentsMode($entity)
  292. {
  293. $paymentsModeArray = [];
  294. $table = (new Paiement($this->db))->table_element;
  295. $sql = "SELECT id, code, libelle FROM " . MAIN_DB_PREFIX. 'c_' . $table . " WHERE code IN ('LIQ', 'CB') AND entity = {$entity}";
  296. $rows = $this->db->query($sql);
  297. if(pg_num_rows($rows) > 0){
  298. $result = pg_fetch_all($rows);
  299. foreach($result as $record){
  300. $paymentsModeArray[] = ['id' => $record['id'], 'label' => $record['libelle'], 'code' => $record['code']];
  301. }
  302. }
  303. return $paymentsModeArray;
  304. }
  305. public function getCompany(): array
  306. {
  307. global $user;
  308. $entity = null;
  309. $result = [];
  310. $data = $this->getCompanyData($user->id);
  311. //print_r($data);exit;
  312. if (empty($data)) {
  313. $entityId = (empty($user->entity)) ? 1 : $user->entity;
  314. $data = $this->getCompanyData(null, $entityId);
  315. }
  316. if (!empty($data)) {
  317. foreach ($data as $row) {
  318. $newStr = substr($row['name'], strlen('MAIN_INFO_'));
  319. if ($newStr != 'TVAINTRA') {
  320. $newStr = substr($newStr, strlen('SOCIETE_'));
  321. }
  322. $result[$newStr] = $row['value'];
  323. if (!empty($row['entity']) && is_null($entity)) {
  324. $entity = intval($row['entity']);
  325. }
  326. }
  327. }
  328. /*
  329. $sql = "
  330. SELECT c.*
  331. FROM ".MAIN_DB_PREFIX."settlements_groupusers gu
  332. INNER JOIN ".MAIN_DB_PREFIX."settlements_group AS g ON g.rowid = gu.fk_settlements_group
  333. INNER JOIN ".MAIN_DB_PREFIX."const AS c ON c.entity = g.fk_entity
  334. WHERE gu.fk_user = {$user->id} AND c.name IN (
  335. 'MAIN_INFO_SOCIETE_COUNTRY',
  336. 'MAIN_INFO_SOCIETE_NOM',
  337. 'MAIN_INFO_SOCIETE_ADDRESS',
  338. 'MAIN_INFO_SOCIETE_TOWN',
  339. 'MAIN_INFO_SOCIETE_ZIP',
  340. 'MAIN_INFO_SOCIETE_STATE',
  341. 'MAIN_INFO_TVAINTRA'
  342. )";
  343. $entityData = $this->db->query($sql);
  344. while ($row = $this->db->fetch_array($entityData)) {
  345. $newStr = substr($row['name'], strlen('MAIN_INFO_'));
  346. if ($newStr != 'TVAINTRA') {
  347. $newStr = substr($newStr, strlen('SOCIETE_'));
  348. }
  349. $result[$newStr] = $row['value'];
  350. if (!empty($row['entity']) && is_null($entity)) {
  351. $entity = intval($row['entity']);
  352. }
  353. }
  354. */
  355. return [
  356. 'company_data' => $result,
  357. 'entity' => $entity
  358. ];
  359. }
  360. public function getCompanyData(int $userId = null, int $entity = null): array
  361. {
  362. $result = [];
  363. $where = '';
  364. if (!empty($userId)) {
  365. $where = 'gu.fk_user = ' . $userId;
  366. } else if (!empty($entity)) {
  367. $where = 'c.entity = ' . $entity;
  368. }
  369. if (!empty($where)) {
  370. $where .= ' AND ';
  371. }
  372. $sql = "
  373. SELECT c.*
  374. FROM " . MAIN_DB_PREFIX . "settlements_groupusers gu
  375. INNER JOIN " . MAIN_DB_PREFIX . "settlements_group AS g ON g.rowid = gu.fk_settlements_group
  376. INNER JOIN " . MAIN_DB_PREFIX . "const AS c ON c.entity = g.fk_entity
  377. WHERE {$where} c.name IN (
  378. 'MAIN_INFO_SOCIETE_COUNTRY',
  379. 'MAIN_INFO_SOCIETE_NOM',
  380. 'MAIN_INFO_SOCIETE_ADDRESS',
  381. 'MAIN_INFO_SOCIETE_TOWN',
  382. 'MAIN_INFO_SOCIETE_ZIP',
  383. 'MAIN_INFO_SOCIETE_STATE',
  384. 'MAIN_INFO_TVAINTRA'
  385. )";
  386. $entityData = $this->db->query($sql);
  387. if ($entityData) {
  388. while ($row = $this->db->fetch_array($entityData)) {
  389. $result[] = $row;
  390. }
  391. }
  392. return $result;
  393. }
  394. public function getGroupUserIdByUserId($user_id)
  395. {
  396. global $db;
  397. $groupUsersObj = new GroupUsers($db);
  398. $result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
  399. if (!empty($result)) {
  400. foreach ($result as $record) {
  401. return $record->fk_settlements_group;
  402. }
  403. }
  404. return -1;
  405. }
  406. public function isLastStatusLogout($user)
  407. {
  408. global $db;
  409. $userLoginNaplo = new UserLoginNaplo($db);
  410. $result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
  411. foreach ($result as $lastrecord) {
  412. return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
  413. }
  414. }
  415. public function factureUpdate($sql, $facture_id)
  416. {
  417. $updated = $this->db->query($sql);
  418. if (!$updated) {
  419. dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  420. throw new RestException(404, 'Update failed');
  421. }
  422. }
  423. public function checkResult($result, $tableName)
  424. {
  425. if (!is_array($result) || empty($result)) {
  426. dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  427. throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
  428. }
  429. }
  430. public function getTicketsByFacture($facture_id)
  431. {
  432. $bbticket = new BbTicket($this->db);
  433. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  434. if ($bbTicketsByFacture < 1) {
  435. throw new RestException(404, 'BBTicket not found');
  436. }
  437. return $bbTicketsByFacture;
  438. }
  439. public function checkPrintedCopies($facture_id)
  440. {
  441. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  442. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  443. return (is_array($copies)) ? count($copies) : 0;
  444. }
  445. public function getbookingHistoryId($ref){
  446. $sql = "SELECT rowid FROM llx_booking_bookinghistory WHERE invoice_number = '{$ref}' ORDER BY rowid DESC LIMIT 1";
  447. $result = $this->db->query($sql);
  448. if($this->db->num_rows($result) < 1){
  449. return '';
  450. }else{
  451. while($row = $this->db->fetch_object($result)){
  452. return $row->rowid;
  453. }
  454. }
  455. }
  456. }