api.btrxcrm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. <?php
  2. /**
  3. * Bitrix24 CRM integration
  4. */
  5. class BtrxCRM {
  6. /**
  7. * Contains system alter config as key=>value
  8. *
  9. * @var array
  10. */
  11. protected $altCfg = array();
  12. /**
  13. * Contains all available users data as login=>userData
  14. *
  15. * @var array
  16. */
  17. protected $allUserData = array();
  18. /**
  19. * Contains all stargazer raw DB data
  20. *
  21. * @var array
  22. */
  23. protected $allStgRawData = array();
  24. /**
  25. * Export URL HTTP abstraction placeholder
  26. *
  27. * @var object
  28. */
  29. protected $apiCrm = '';
  30. /**
  31. * Contains OpenPayz instance
  32. *
  33. * @var object
  34. */
  35. protected $openPayz = '';
  36. /**
  37. * Contains all customers payemntIds as login=>paymentId
  38. *
  39. * @var array
  40. */
  41. protected $allPaymentIds = array();
  42. /**
  43. * Contains all users tags as login=>tagsArr
  44. *
  45. * @var array
  46. */
  47. protected $allUserTags = array();
  48. /**
  49. * Contains all of available tariffs prices as tariffname=>fee
  50. *
  51. * @var array
  52. */
  53. protected $allTariffsPricess = array();
  54. /**
  55. * Contains all of available tariff speeds as tariffname=>data (speeddown/speedup keys)
  56. *
  57. * @var array
  58. */
  59. protected $allTariffsSpeeds = array();
  60. /**
  61. * Contains extended mobiles instance
  62. *
  63. * @var object
  64. */
  65. protected $extMobiles = '';
  66. /**
  67. * Contains all user extmobiles info as login=>mobilesExtData
  68. *
  69. * @var array
  70. */
  71. protected $allExtMobiles = array();
  72. /**
  73. * Contains current instance URL to push some data
  74. *
  75. * @var string
  76. */
  77. protected $exportUrl = '';
  78. /**
  79. * Name of POST variable to export updated users data
  80. *
  81. * @var string
  82. */
  83. protected $exportVar = '';
  84. /**
  85. * LastActivityTime export flag
  86. *
  87. * @var bool
  88. */
  89. protected $exportLatFlag = false;
  90. /**
  91. * System caching instance placeholder
  92. *
  93. * @var object
  94. */
  95. protected $cache = '';
  96. /**
  97. * Current instance caching timeout
  98. *
  99. * @var int
  100. */
  101. protected $cacheTimeout = 2592000;
  102. /**
  103. * Contains already exported user data as login=>hash(?)
  104. *
  105. * @var array
  106. */
  107. protected $cachedUsers = array();
  108. /**
  109. * Deal With It database abstraction layer
  110. *
  111. * @var object
  112. */
  113. protected $dealWithItDb = '';
  114. /**
  115. * Payments database abstraction layer
  116. *
  117. * @var object
  118. */
  119. protected $paymentsDb = '';
  120. /**
  121. * Contains records about first user payments dates as login=>date
  122. *
  123. * @var array
  124. */
  125. protected $firstUserPayments = array();
  126. /**
  127. * Contains records about latest user payments dates login=>date
  128. *
  129. * @var array
  130. */
  131. protected $latestUserPayments = array();
  132. /**
  133. * Contains all user payments summ as login=>summ
  134. *
  135. * @var array
  136. */
  137. protected $userPaymentsSumm = array();
  138. /**
  139. * Contains all users deal with it data about tariff changes as login=>date/tariff as param
  140. *
  141. * @var array
  142. */
  143. protected $allDealWithItChanges = array();
  144. /**
  145. * Contains all user assigned agents data as login=>agentName
  146. *
  147. * @var array
  148. */
  149. protected $allUserAgents = array();
  150. /**
  151. * Contains all user assigned ONU signals as login=>signal
  152. *
  153. * @var array
  154. */
  155. protected $allUserOnuSignals = array();
  156. /**
  157. * Some predefined stuff here
  158. */
  159. const CACHE_KEY = 'BTRX_DATA';
  160. const PID_NAME = 'BITRX24_UPD';
  161. /**
  162. * Point me to the sky above
  163. * I can't get there on my own
  164. * Walk me to the graveyard
  165. * Dig up her bones
  166. */
  167. public function __construct() {
  168. $this->loadConfig();
  169. $this->initCache();
  170. $this->initApiCrm();
  171. $this->initOpenPayz();
  172. $this->initDealWithItDb();
  173. $this->initPaymentsDb();
  174. $this->initExtMobiles();
  175. $this->loadUserData();
  176. $this->loadPaymentsData();
  177. $this->loadExtMobiles();
  178. $this->loadTariffsData();
  179. $this->loadDealWithitData();
  180. $this->loadUserTags();
  181. $this->loadPayIds();
  182. $this->loadAgentsData();
  183. $this->loadPonizerData();
  184. $this->loadCachedData();
  185. }
  186. /**
  187. * Preloads some required configs for further usage
  188. *
  189. * @global object $ubillingConfig
  190. *
  191. * @return void
  192. */
  193. protected function loadConfig() {
  194. global $ubillingConfig;
  195. $this->altCfg = $ubillingConfig->getAlter();
  196. if (isset($this->altCfg['BTRX24_EXPORT_URL'])) {
  197. $this->exportUrl = $this->altCfg['BTRX24_EXPORT_URL'];
  198. }
  199. if (isset($this->altCfg['BTRX24_EXPORT_VAR'])) {
  200. $this->exportVar = $this->altCfg['BTRX24_EXPORT_VAR'];
  201. }
  202. if (isset($this->altCfg['BTRX24_EXPORT_LAT'])) {
  203. if ($this->altCfg['BTRX24_EXPORT_LAT']) {
  204. $this->exportLatFlag = true;
  205. }
  206. }
  207. }
  208. /**
  209. * Inits system caching layer
  210. *
  211. * @return void
  212. */
  213. protected function initCache() {
  214. $this->cache = new UbillingCache();
  215. }
  216. /**
  217. * Inits OpenPayz instance
  218. *
  219. * @return void
  220. */
  221. protected function initOpenPayz() {
  222. $this->openPayz = new OpenPayz();
  223. }
  224. /**
  225. * Inits scheduler database abstraction layer
  226. *
  227. * @return void
  228. */
  229. protected function initDealWithItDb() {
  230. $this->dealWithItDb = new NyanORM('dealwithit');
  231. }
  232. /**
  233. * Loads deal with it tariff changes
  234. *
  235. * @return void
  236. */
  237. protected function loadDealWithitData() {
  238. $this->dealWithItDb->where('action', '=', 'tariffchange');
  239. $this->dealWithItDb->orderBy('date', 'DESC');
  240. $this->allDealWithItChanges = $this->dealWithItDb->getAll('login');
  241. }
  242. /**
  243. * Inits extended mobiles instance
  244. *
  245. * @return void
  246. */
  247. protected function initExtMobiles() {
  248. $this->extMobiles = new MobilesExt();
  249. }
  250. /**
  251. * Loads all users extmobiles data
  252. *
  253. * @return void
  254. */
  255. protected function loadExtMobiles() {
  256. $this->allExtMobiles = $this->extMobiles->getAllUsersMobileNumbers();
  257. }
  258. /**
  259. * Inits payments database abstraction layer
  260. *
  261. * @return void
  262. */
  263. protected function initPaymentsDb() {
  264. $this->paymentsDb = new NyanORM('payments');
  265. }
  266. /**
  267. * Preloads first/last user payments data
  268. *
  269. * @return void
  270. */
  271. protected function loadPaymentsData() {
  272. //user payments summ total
  273. $this->paymentsDb->where('summ', '>', 0);
  274. $this->paymentsDb->selectable(array('id', 'login', 'date', 'summ'));
  275. $this->paymentsDb->orderBy('id', 'ASC');
  276. $rawPayments = $this->paymentsDb->getAll();
  277. if (!empty($rawPayments)) {
  278. foreach ($rawPayments as $io => $each) {
  279. if (is_numeric($each['summ'])) {
  280. if (isset($this->userPaymentsSumm[$each['login']])) {
  281. $this->userPaymentsSumm[$each['login']] += $each['summ'];
  282. //latest user payment date here
  283. $this->latestUserPayments[$each['login']] = $each['date'];
  284. } else {
  285. //first occurency
  286. $this->userPaymentsSumm[$each['login']] = $each['summ'];
  287. //looks like first payment
  288. $this->firstUserPayments[$each['login']] = $each['date'];
  289. }
  290. }
  291. }
  292. }
  293. }
  294. /**
  295. * Loads all available users PaymentIds
  296. *
  297. * @return void
  298. */
  299. protected function loadPayIds() {
  300. $opCustomers = $this->openPayz->getCustomers();
  301. $this->allPaymentIds = array_flip($opCustomers); // login=>payId
  302. }
  303. /**
  304. * Inits CRM HTTP abstraction layer
  305. *
  306. * @return void
  307. */
  308. protected function initApiCrm() {
  309. if (!empty($this->exportUrl)) {
  310. $this->apiCrm = new OmaeUrl($this->exportUrl);
  311. } else {
  312. throw new Exception('EX_NO_EXPORT_URL');
  313. }
  314. }
  315. /**
  316. * Loads all users agent assigns data
  317. *
  318. * @return void
  319. */
  320. protected function loadAgentsData() {
  321. if (!empty($this->allUserData)) {
  322. $allAssigns = zb_AgentAssignGetAllData();
  323. $allStrictAssigns = zb_AgentAssignStrictGetAllData();
  324. $allAgentsData = zb_ExportAgentsLoadAll();
  325. foreach ($this->allUserData as $io => $each) {
  326. $assignedAgentId = zb_AgentAssignCheckLoginFast($each['login'], $allAssigns, $each['fulladress'], $allStrictAssigns);
  327. if ($assignedAgentId) {
  328. if (isset($allAgentsData[$assignedAgentId])) {
  329. $this->allUserAgents[$each['login']] = $allAgentsData[$assignedAgentId]['contrname'];
  330. }
  331. }
  332. }
  333. }
  334. }
  335. /**
  336. * Loads all PONizer related data
  337. *
  338. * @return void
  339. */
  340. protected function loadPonizerData() {
  341. $ponizer = new PONizer();
  342. $this->allUserOnuSignals = $ponizer->getAllONUSignals();
  343. }
  344. /**
  345. * Loads available tariffs data
  346. *
  347. * @return void
  348. */
  349. protected function loadTariffsData() {
  350. $this->allTariffsPricess = zb_TariffGetPricesAll();
  351. $this->allTariffsSpeeds = zb_TariffGetAllSpeeds();
  352. }
  353. /**
  354. * Preloads all existing users data
  355. *
  356. * @return void
  357. */
  358. protected function loadUserData() {
  359. $this->allUserData = zb_UserGetAllDataCache();
  360. $this->allStgRawData = zb_UserGetAllStargazerDataAssoc();
  361. }
  362. /**
  363. * Preloads previously exported to CRM data from cache
  364. *
  365. * @return void
  366. */
  367. protected function loadCachedData() {
  368. $rawCachedData = $this->cache->get(self::CACHE_KEY, $this->cacheTimeout);
  369. if (!empty($rawCachedData)) {
  370. $this->cachedUsers = $rawCachedData; // fuck mem economy, lol
  371. }
  372. }
  373. /**
  374. * Loads existing tag types from database
  375. *
  376. * @return void
  377. */
  378. protected function loadUserTags() {
  379. $this->allUserTags = zb_UserGetAllTags();
  380. }
  381. /**
  382. * Returns unique user numeric ID
  383. *
  384. * @param string $userLogin
  385. *
  386. * @return int
  387. */
  388. protected function getUserUniqId($userLogin) {
  389. $result = 0;
  390. if (!empty($userLogin)) {
  391. $result = crc32($userLogin);
  392. }
  393. return($result);
  394. }
  395. /**
  396. * Returns users tags list as string, if assigned
  397. *
  398. * @param string $userLogin
  399. *
  400. * @return string
  401. */
  402. protected function getUserTagsList($userLogin) {
  403. $result = '';
  404. if (isset($this->allUserTags[$userLogin])) {
  405. if (!empty($this->allUserTags[$userLogin])) {
  406. $result .= implode(',', $this->allUserTags[$userLogin]);
  407. }
  408. }
  409. return($result);
  410. }
  411. /**
  412. *
  413. * @param array $userData
  414. *
  415. * @return array
  416. */
  417. protected function getUserStruct($userData) {
  418. $result = array();
  419. if (!empty($userData)) {
  420. $userLogin = $userData['login'];
  421. $userPassword = $userData['Password'];
  422. $fullAddress = $userData['fulladress'];
  423. $userIp = $userData['ip'];
  424. $userMac = $userData['mac'];
  425. $userPaymentId = (isset($this->allPaymentIds[$userLogin])) ? $this->allPaymentIds[$userLogin] : '';
  426. $userRealName = $userData['realname'];
  427. $userBalance = $userData['Cash'];
  428. $userCredit = $userData['Credit'];
  429. $creditExpire = $this->allStgRawData[$userLogin]['CreditExpire'];
  430. $userFrozen = $userData['Passive'];
  431. $userTags = $this->getUserTagsList($userLogin);
  432. $latTimestamp = 0;
  433. if ($this->exportLatFlag) {
  434. $latTimestamp = $this->allStgRawData[$userLogin]['LastActivityTime'];
  435. }
  436. $userAgent = (isset($this->allUserAgents[$userLogin])) ? $this->allUserAgents[$userLogin] : '';
  437. $onuSignal = (isset($this->allUserOnuSignals[$userLogin])) ? $this->allUserOnuSignals[$userLogin] : 0;
  438. //tariffs related data
  439. $userTariff = $userData['Tariff'];
  440. $speedDown = (isset($this->allTariffsSpeeds[$userTariff]['speeddown'])) ? $this->allTariffsSpeeds[$userTariff]['speeddown'] : 0;
  441. $speedUp = (isset($this->allTariffsSpeeds[$userTariff]['speedup'])) ? $this->allTariffsSpeeds[$userTariff]['speedup'] : 0;
  442. $tariffFee = isset($this->allTariffsPricess[$userTariff]) ? $this->allTariffsPricess[$userTariff] : 0;
  443. $tariffChange = (isset($this->allDealWithItChanges[$userLogin])) ? $this->allDealWithItChanges[$userLogin]['param'] : '';
  444. $tariffChangeDate = (isset($this->allDealWithItChanges[$userLogin])) ? $this->allDealWithItChanges[$userLogin]['date'] : 0;
  445. if ($tariffChangeDate) {
  446. $tariffChangeDate = strtotime($tariffChangeDate . ' 02:10:00');
  447. }
  448. //payments related data
  449. $firstPaymentDate = (isset($this->firstUserPayments[$userLogin])) ? strtotime($this->firstUserPayments[$userLogin]) : 0;
  450. $latestPaymentDate = (isset($this->latestUserPayments[$userLogin])) ? strtotime($this->latestUserPayments[$userLogin]) : 0;
  451. $userPaymentsSumm = (isset($this->userPaymentsSumm[$userLogin])) ? $this->userPaymentsSumm[$userLogin] : 0;
  452. //phone related data
  453. $userPhone = $userData['mobile'];
  454. $mobileExt = '';
  455. if (isset($this->allExtMobiles[$userLogin])) {
  456. $mobileExt = $this->allExtMobiles[$userLogin][0];
  457. }
  458. //
  459. //
  460. // _(\_/)
  461. // ,((((^`\
  462. // (((( (6 \
  463. // ,((((( , \
  464. // ,,,_ ,((((( /"._ ,`,
  465. // ((((\\ ,... ,(((( / `-.-'
  466. // ))) ;' `"'"'""(((( (
  467. // ((( / ((( \
  468. // )) | |
  469. // (( | . ' |
  470. // )) \ _ ' `t ,.')
  471. // ( | y;- -,-""'"-.\ \/
  472. // ) / ./ ) / `\ \
  473. // |./ ( ( / /'
  474. // || \\ //'|
  475. // || \\ _//'|| CIRCUS WITH THE HORSES
  476. // || )) |_/ ||
  477. // \_\ |_/ ||
  478. // `'" \_\
  479. $result = array(
  480. 'phone' => $userPhone,
  481. 'fio' => $userRealName,
  482. 'pay_id' => $userPaymentId,
  483. 'login' => $userLogin,
  484. 'password' => $userPassword,
  485. 'tariff' => $userTariff,
  486. 'balance' => $userBalance,
  487. 'tegs' => $userTags,
  488. 'speed_up' => $speedUp,
  489. 'speed_down' => $speedDown,
  490. 'abonplata' => $tariffFee,
  491. 'cash_first_pay' => $firstPaymentDate,
  492. 'mobile2' => $mobileExt,
  493. 'cash_last_pay' => $latestPaymentDate,
  494. 'full_adress' => $fullAddress,
  495. 'cash_all_pays' => $userPaymentsSumm,
  496. 'deal_with_it1' => $tariffChangeDate,
  497. 'deal_with_it2' => $tariffChange,
  498. 'owner' => $userAgent,
  499. 'credit' => $userCredit,
  500. 'credit_day' => $creditExpire,
  501. 'ip' => $userIp,
  502. 'mac' => $userMac,
  503. 'onu_signal' => $onuSignal,
  504. 'lat' => $latTimestamp
  505. );
  506. }
  507. return($result);
  508. }
  509. /**
  510. * Pushes changed users struct into CRM hook
  511. *
  512. * @param array $changedUsersStruct
  513. *
  514. * @return void
  515. */
  516. protected function pushCrmData($changedUsersStruct) {
  517. $jsonData = json_encode($changedUsersStruct);
  518. $this->apiCrm->dataPost($this->exportVar, $jsonData);
  519. $this->apiCrm->response();
  520. }
  521. /**
  522. * Processing of existing user data to deicide export this to CRM or nothing changed?
  523. *
  524. * @return void
  525. */
  526. public function runExport() {
  527. $somethingChanged = array();
  528. if (!empty($this->allUserData)) {
  529. foreach ($this->allUserData as $eachUserLogin => $eachUserData) {
  530. $updateFlag = false;
  531. $eachUserStruct = $this->getUserStruct($eachUserData);
  532. if (isset($this->cachedUsers[$eachUserLogin])) {
  533. //user data was changed someway
  534. if ($eachUserStruct != $this->cachedUsers[$eachUserLogin]) {
  535. $updateFlag = true;
  536. }
  537. } else {
  538. //newly registered user?
  539. $updateFlag = true;
  540. }
  541. if ($updateFlag) {
  542. $somethingChanged[] = $eachUserStruct;
  543. $this->cachedUsers[$eachUserLogin] = $eachUserStruct;
  544. }
  545. }
  546. //pushing data to CRM
  547. if (!empty($somethingChanged)) {
  548. $this->pushCrmData($somethingChanged);
  549. }
  550. //saving cache
  551. $this->cache->set(self::CACHE_KEY, $this->cachedUsers, $this->cacheTimeout);
  552. }
  553. }
  554. }