api_bbus_helper.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. } else {
  112. $resultArray[$record['pere']]['count'] = 1;
  113. }
  114. $resultArray[$record['pere']]['label'] = $record['label'];
  115. $resultArray[$record['pere']]['currency'] = $record['currency'];
  116. }
  117. $array = [];
  118. foreach ($resultArray as $row) {
  119. $array[] = $row;
  120. }
  121. return $array;
  122. }
  123. private function checkValidation($res, $name)
  124. {
  125. if (pg_num_rows($res) == 0) {
  126. throw new RestException(404, $name . ' not found');
  127. }
  128. }
  129. public function getFactureIdForInvoicePrinting($ref)
  130. {
  131. global $db;
  132. $sql = "SELECT * FROM llx_facture WHERE ref = '{$ref}'";
  133. ApiBbusLog::appLog("{$sql}");
  134. $resultBBT = $db->query($sql);
  135. if (pg_num_rows($resultBBT) < 1) {
  136. ApiBbusLog::appLog("Invoice not found");
  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;
  154. if ($newCopy->create($user) > 0) {
  155. ApiBbusLog::appLog("BBticketInvoiceprinting saved");
  156. // successful saving
  157. } else {
  158. ApiBbusLog::appLog("BBticketInvoiceprinting save 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, $ref)
  164. {
  165. $object = new stdClass();
  166. $object->fk_facture = $facture_id;
  167. $object->fk_product = $this->getproductIdFromFActuredet($facture_id);
  168. $object->invoice_number = $ref;
  169. $bbTicketHandler = new BbTicketHandler();
  170. // uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
  171. return $bbTicketHandler->addTicketForPrinting($object);
  172. }
  173. public function getTicketIdsForCrossShopping($ref)
  174. {
  175. ApiBbusLog::appLog("getTicketIdsForCrossShopping");
  176. $object = new stdClass();
  177. $object->invoice_number = $ref;
  178. $object->fk_product = $this->curlGetproductIdFromFActuredet($ref);
  179. $bbTicketHandler = new BbTicketHandler();
  180. // uj rekordot veszek fel a bbticket tablaba és visszaterek a rogzitett rekordok roid-javal
  181. return $bbTicketHandler->addTicketForPrintingCrossShopping($object);
  182. }
  183. function curlGetproductIdFromFActuredet($ref){
  184. $params = '{"ref":"' . $ref . '"}';
  185. return $this->curlRunner('bbus/curlgetproductidfromfacturedet', $params, 'POST', true);
  186. }
  187. public function getproductIdFromFActuredet($facture_id)
  188. {
  189. global $db;
  190. $array = [];
  191. $sql = "SELECT fk_product FROM public.llx_facturedet WHERE fk_facture = " . $facture_id;
  192. $result = $db->query($sql);
  193. while ($facturedetrecord = pg_fetch_assoc($result)) {
  194. $array[] = $facturedetrecord['fk_product'];
  195. }
  196. return $array;
  197. }
  198. public function sendMail($fk_facture, $datetime, $now): void
  199. {
  200. $const = new GlobalConst;
  201. $recipients = $const->load(self::GLOBAL_CONF_SEND_TO_EMAIL);
  202. $emailFrom = $const->load(self::GLOBAL_CONF_EMAIL_FROM);
  203. //$recipients = 'szollosi.laszlo@urbanms.hu';
  204. //$emailFrom = 'bbus@urbanms.hu';
  205. if (!empty($recipients) && !empty($emailFrom)) {
  206. $emailTemplateHandler = new EmailTemplateHandler;
  207. $template = $emailTemplateHandler->load(self::EMAIL_TEMPLATE);
  208. $templateObject = new stdClass();
  209. foreach ($template as $key => $value) {
  210. $templateObject->$key = $value;
  211. }
  212. if ($templateObject) {
  213. $vars = [
  214. '__FACTURE__' => $fk_facture,
  215. '__DATETIME__' => $datetime,
  216. '__PRINTINGDATE__' => $now
  217. ];
  218. $template = $emailTemplateHandler->prepareTemplate($templateObject, $vars);
  219. $mail = new CMailFile(
  220. $template->topic,
  221. $recipients,
  222. $emailFrom,
  223. $template->content,
  224. null,
  225. null,
  226. null,
  227. '',
  228. '',
  229. 0,
  230. 1
  231. );
  232. // Send Email
  233. $mail->sendfile();
  234. if ($mail->error) {
  235. //print_r($mail->error);
  236. //exit;
  237. // do something...
  238. dol_syslog('CRON ALERT EMAIL ERROR: ' . $mail->error, LOG_ERR);
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. *
  245. */
  246. public function getAppCustomers(): array
  247. {
  248. $customers = [];
  249. $table = (new Societe($this->db))->table_element;
  250. $sql = "
  251. 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
  252. FROM ".MAIN_DB_PREFIX.$table." as soc
  253. INNER JOIN ".MAIN_DB_PREFIX.$table."_extrafields as socex ON soc.rowid = socex.fk_object
  254. WHERE socex.is_general_customer = 1
  255. ORDER BY soc.rowid ASC
  256. ";
  257. $rows = $this->db->query($sql);
  258. if ($rows) {
  259. while ($row = $this->db->fetch_object($rows)) {
  260. $row->full_address = implode(' ', [
  261. $row->zip,
  262. $row->town,
  263. $row->address
  264. ]);
  265. $customers[$row->currency] = $row;
  266. }
  267. }
  268. return $customers;
  269. }
  270. function getAccountRowid($entity)
  271. {
  272. $sql = "SELECT ba.currency_code, ba.rowid FROM llx_bank_account as ba WHERE entity = {$entity} ORDER BY rowid ASC";
  273. //$sql = "SELECT mc.code, mc.rowid FROM llx_multicurrency as mc WHERE entity = {$entity}";
  274. $data = $this->db->query($sql);
  275. $accounts = [];
  276. while ($row = pg_fetch_array($data)) {
  277. $accounts[$row['currency_code']] = $row['rowid'];
  278. //$accounts[$row['code']] = $row['rowid'];
  279. }
  280. return $accounts;
  281. }
  282. function getCurrenciesRowid($entity)
  283. {
  284. $sql = "SELECT mc.rowid, mc.code FROM llx_multicurrency as mc WHERE entity = {$entity} ORDER BY rowid ASC";
  285. $data = $this->db->query($sql);
  286. $currencies = [];
  287. while ($row = pg_fetch_array($data)) {
  288. $currencies[$row['code']] = $row['rowid'];
  289. }
  290. return $currencies;
  291. }
  292. function getPaymentsMode($entity)
  293. {
  294. $paymentsModeArray = [];
  295. $table = (new Paiement($this->db))->table_element;
  296. $sql = "SELECT id, code, libelle FROM " . MAIN_DB_PREFIX. 'c_' . $table . " WHERE code IN ('LIQ', 'CB') AND entity = {$entity}";
  297. $rows = $this->db->query($sql);
  298. if(pg_num_rows($rows) > 0){
  299. $result = pg_fetch_all($rows);
  300. foreach($result as $record){
  301. $paymentsModeArray[] = ['id' => $record['id'], 'label' => $record['libelle'], 'code' => $record['code']];
  302. }
  303. }
  304. return $paymentsModeArray;
  305. }
  306. public function getCompany(): array
  307. {
  308. global $user;
  309. $entity = null;
  310. $result = [];
  311. $data = $this->getCompanyData($user->id);
  312. //print_r($data);exit;
  313. if (empty($data)) {
  314. $entityId = (empty($user->entity)) ? 1 : $user->entity;
  315. $data = $this->getCompanyData(null, $entityId);
  316. }
  317. if (!empty($data)) {
  318. foreach ($data as $row) {
  319. $newStr = substr($row['name'], strlen('MAIN_INFO_'));
  320. if ($newStr != 'TVAINTRA') {
  321. $newStr = substr($newStr, strlen('SOCIETE_'));
  322. }
  323. $result[$newStr] = $row['value'];
  324. if (!empty($row['entity']) && is_null($entity)) {
  325. $entity = intval($row['entity']);
  326. }
  327. }
  328. }
  329. return [
  330. 'company_data' => $result,
  331. 'entity' => $entity
  332. ];
  333. }
  334. public function getCompanyData(int $userId = null, int $entity = null): array
  335. {
  336. $result = [];
  337. $where = '';
  338. if (!empty($userId)) {
  339. $where = 'gu.fk_user = ' . $userId;
  340. } else if (!empty($entity)) {
  341. $where = 'c.entity = ' . $entity;
  342. }
  343. if (!empty($where)) {
  344. $where .= ' AND ';
  345. }
  346. $sql = "
  347. SELECT c.*
  348. FROM " . MAIN_DB_PREFIX . "settlements_groupusers gu
  349. INNER JOIN " . MAIN_DB_PREFIX . "settlements_group AS g ON g.rowid = gu.fk_settlements_group
  350. INNER JOIN " . MAIN_DB_PREFIX . "const AS c ON c.entity = g.fk_entity
  351. WHERE {$where} c.name IN (
  352. 'MAIN_INFO_SOCIETE_COUNTRY',
  353. 'MAIN_INFO_SOCIETE_NOM',
  354. 'MAIN_INFO_SOCIETE_ADDRESS',
  355. 'MAIN_INFO_SOCIETE_TOWN',
  356. 'MAIN_INFO_SOCIETE_ZIP',
  357. 'MAIN_INFO_SOCIETE_STATE',
  358. 'MAIN_INFO_TVAINTRA'
  359. )";
  360. $entityData = $this->db->query($sql);
  361. if ($entityData) {
  362. while ($row = $this->db->fetch_array($entityData)) {
  363. $result[] = $row;
  364. }
  365. }
  366. return $result;
  367. }
  368. public function getGroupUserIdByUserId($user_id)
  369. {
  370. global $db;
  371. $groupUsersObj = new GroupUsers($db);
  372. $result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
  373. if (!empty($result)) {
  374. foreach ($result as $record) {
  375. return $record->fk_settlements_group;
  376. }
  377. }
  378. return -1;
  379. }
  380. public function isLastStatusLogout($user)
  381. {
  382. global $db;
  383. $userLoginNaplo = new UserLoginNaplo($db);
  384. $result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
  385. foreach ($result as $lastrecord) {
  386. return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
  387. }
  388. }
  389. public function factureUpdate($sql, $facture_id)
  390. {
  391. $updated = $this->db->query($sql);
  392. if (!$updated) {
  393. dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  394. throw new RestException(404, 'Update failed');
  395. }
  396. }
  397. public function checkResult($result, $tableName)
  398. {
  399. if (!is_array($result) || empty($result)) {
  400. dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  401. throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
  402. }
  403. }
  404. public function getTicketsByFacture($facture_id)
  405. {
  406. $bbticket = new BbTicket($this->db);
  407. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  408. if ($bbTicketsByFacture < 1) {
  409. throw new RestException(404, 'BBTicket not found');
  410. }
  411. return $bbTicketsByFacture;
  412. }
  413. public function checkPrintedCopies($facture_id)
  414. {
  415. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  416. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  417. return (is_array($copies)) ? count($copies) : 0;
  418. }
  419. public function getbookingHistoryId($ref){
  420. $sql = "SELECT rowid FROM llx_booking_bookinghistory WHERE invoice_number = '{$ref}' ORDER BY rowid DESC LIMIT 1";
  421. $result = $this->db->query($sql);
  422. if($this->db->num_rows($result) < 1){
  423. return '';
  424. }else{
  425. while($row = $this->db->fetch_object($result)){
  426. return $row->rowid;
  427. }
  428. }
  429. }
  430. }