api_bbus_helper.class.php.bak 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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, $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. private 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. /*
  330. $sql = "
  331. SELECT c.*
  332. FROM ".MAIN_DB_PREFIX."settlements_groupusers gu
  333. INNER JOIN ".MAIN_DB_PREFIX."settlements_group AS g ON g.rowid = gu.fk_settlements_group
  334. INNER JOIN ".MAIN_DB_PREFIX."const AS c ON c.entity = g.fk_entity
  335. WHERE gu.fk_user = {$user->id} AND c.name IN (
  336. 'MAIN_INFO_SOCIETE_COUNTRY',
  337. 'MAIN_INFO_SOCIETE_NOM',
  338. 'MAIN_INFO_SOCIETE_ADDRESS',
  339. 'MAIN_INFO_SOCIETE_TOWN',
  340. 'MAIN_INFO_SOCIETE_ZIP',
  341. 'MAIN_INFO_SOCIETE_STATE',
  342. 'MAIN_INFO_TVAINTRA'
  343. )";
  344. $entityData = $this->db->query($sql);
  345. while ($row = $this->db->fetch_array($entityData)) {
  346. $newStr = substr($row['name'], strlen('MAIN_INFO_'));
  347. if ($newStr != 'TVAINTRA') {
  348. $newStr = substr($newStr, strlen('SOCIETE_'));
  349. }
  350. $result[$newStr] = $row['value'];
  351. if (!empty($row['entity']) && is_null($entity)) {
  352. $entity = intval($row['entity']);
  353. }
  354. }
  355. */
  356. return [
  357. 'company_data' => $result,
  358. 'entity' => $entity
  359. ];
  360. }
  361. public function getCompanyData(int $userId = null, int $entity = null): array
  362. {
  363. $result = [];
  364. $where = '';
  365. if (!empty($userId)) {
  366. $where = 'gu.fk_user = ' . $userId;
  367. } else if (!empty($entity)) {
  368. $where = 'c.entity = ' . $entity;
  369. }
  370. if (!empty($where)) {
  371. $where .= ' AND ';
  372. }
  373. $sql = "
  374. SELECT c.*
  375. FROM " . MAIN_DB_PREFIX . "settlements_groupusers gu
  376. INNER JOIN " . MAIN_DB_PREFIX . "settlements_group AS g ON g.rowid = gu.fk_settlements_group
  377. INNER JOIN " . MAIN_DB_PREFIX . "const AS c ON c.entity = g.fk_entity
  378. WHERE {$where} c.name IN (
  379. 'MAIN_INFO_SOCIETE_COUNTRY',
  380. 'MAIN_INFO_SOCIETE_NOM',
  381. 'MAIN_INFO_SOCIETE_ADDRESS',
  382. 'MAIN_INFO_SOCIETE_TOWN',
  383. 'MAIN_INFO_SOCIETE_ZIP',
  384. 'MAIN_INFO_SOCIETE_STATE',
  385. 'MAIN_INFO_TVAINTRA'
  386. )";
  387. $entityData = $this->db->query($sql);
  388. if ($entityData) {
  389. while ($row = $this->db->fetch_array($entityData)) {
  390. $result[] = $row;
  391. }
  392. }
  393. return $result;
  394. }
  395. public function getGroupUserIdByUserId($user_id)
  396. {
  397. global $db;
  398. $groupUsersObj = new GroupUsers($db);
  399. $result = $groupUsersObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "fk_user = {$user_id}"]);
  400. if (!empty($result)) {
  401. foreach ($result as $record) {
  402. return $record->fk_settlements_group;
  403. }
  404. }
  405. return -1;
  406. }
  407. public function isLastStatusLogout($user)
  408. {
  409. global $db;
  410. $userLoginNaplo = new UserLoginNaplo($db);
  411. $result = $userLoginNaplo->fetchAll('DESC', 'date_creation', 1, 0, array('user_id' => $user->id));
  412. foreach ($result as $lastrecord) {
  413. return $lastrecord->login_logout_status == 1 ? $lastrecord->date_creation : '';
  414. }
  415. }
  416. public function factureUpdate($sql, $facture_id)
  417. {
  418. $updated = $this->db->query($sql);
  419. if (!$updated) {
  420. dol_syslog("Nem sikerult a facture updateje. rowid: " . $facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  421. throw new RestException(404, 'Update failed');
  422. }
  423. }
  424. public function checkResult($result, $tableName)
  425. {
  426. if (!is_array($result) || empty($result)) {
  427. dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
  428. throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
  429. }
  430. }
  431. public function getTicketsByFacture($facture_id)
  432. {
  433. $bbticket = new BbTicket($this->db);
  434. $bbTicketsByFacture = $bbticket->fetchAll('', '', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  435. if ($bbTicketsByFacture < 1) {
  436. throw new RestException(404, 'BBTicket not found');
  437. }
  438. return $bbTicketsByFacture;
  439. }
  440. public function checkPrintedCopies($facture_id)
  441. {
  442. $bbticketinvoiceprinting = new BbTicketInvoicePrinting($this->db);
  443. $copies = $bbticketinvoiceprinting->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => 'fk_facture = ' . intval($facture_id)]);
  444. return (is_array($copies)) ? count($copies) : 0;
  445. }
  446. public function getbookingHistoryId($ref){
  447. $sql = "SELECT rowid FROM llx_booking_bookinghistory WHERE invoice_number = '{$ref}' ORDER BY rowid DESC LIMIT 1";
  448. $result = $this->db->query($sql);
  449. if($this->db->num_rows($result) < 1){
  450. return '';
  451. }else{
  452. while($row = $this->db->fetch_object($result)){
  453. return $row->rowid;
  454. }
  455. }
  456. }
  457. }