api.cudiscounts.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. <?php
  2. /**
  3. * Cumulative discounts implementation
  4. */
  5. class CumulativeDiscounts {
  6. protected $allDiscounts = array();
  7. protected $allUsers = array();
  8. protected $allUserTags = array();
  9. protected $altCfg = array();
  10. protected $tariffPrices = array();
  11. protected $customDiscounts = array();
  12. protected $discountPullDays = 30;
  13. protected $fillPercent = 1;
  14. protected $discountPayId = 1;
  15. protected $discountLimit = 10;
  16. protected $customDiscountCfId = '';
  17. protected $onlyTagId = 0;
  18. protected $cashMode = 'ADD';
  19. protected $debug = 0;
  20. protected $logPath = '';
  21. protected $curdate = '';
  22. protected $login = '';
  23. public function __construct() {
  24. $this->loadAlter();
  25. $this->setOptions();
  26. $this->loadUsers();
  27. $this->loadDiscounts();
  28. $this->loadTariffPrices();
  29. $this->loadCustomDiscounts();
  30. $this->loadUserTags();
  31. }
  32. /**
  33. * Loads system-wide alter.ini for further usage
  34. *
  35. * @return void
  36. */
  37. protected function loadAlter() {
  38. global $ubillingConfig;
  39. $this->altCfg = $ubillingConfig->getAlter();
  40. }
  41. /**
  42. * Sets default options
  43. *
  44. * @return void
  45. */
  46. protected function setOptions() {
  47. $this->curdate = curdatetime();
  48. $this->discountPullDays = ubRouting::filters($this->altCfg['CUD_PULLDAYS'], 'int');
  49. $this->fillPercent = ubRouting::filters($this->altCfg['CUD_PERCENT'], 'int');
  50. $this->discountPayId = ubRouting::filters($this->altCfg['CUD_PAYID'], 'int');
  51. $this->discountLimit = ubRouting::filters($this->altCfg['CUD_PERCENTLIMIT'], 'int');
  52. $this->customDiscountCfId = ubRouting::filters($this->altCfg['CUD_CFID'], 'int');
  53. $this->logPath = DATA_PATH . 'documents/cudiscounts.log';
  54. $this->setDebug($this->altCfg['CUD_ENABLED']);
  55. $this->customDiscountCfId = ubRouting::filters($this->altCfg['CUD_CFID'], 'int');
  56. if (isset($this->altCfg['CUD_OPERATION'])) {
  57. $this->cashMode = $this->altCfg['CUD_OPERATION'];
  58. }
  59. if (isset($this->altCfg['CUD_ONLY_TAGID'])) {
  60. $this->onlyTagId = ubRouting::filters($this->altCfg['CUD_ONLY_TAGID'], 'int');
  61. }
  62. }
  63. /**
  64. * Loads all available users into private data property
  65. *
  66. * @return void
  67. */
  68. protected function loadUsers() {
  69. $query = "SELECT * from `users`"; // WHERE `Cash`>= -`Credit` AND `Passive`='0' AND `Down`=0; ?
  70. $tmp = zb_UserGetAllStargazerData();
  71. if (!empty($tmp)) {
  72. foreach ($tmp as $io => $each) {
  73. $this->allUsers[$each['login']] = $each;
  74. }
  75. }
  76. }
  77. /**
  78. * Loads custom discounts if its available for all users
  79. *
  80. * @return void
  81. */
  82. protected function loadCustomDiscounts() {
  83. if (!empty($this->customDiscountCfId)) {
  84. $cf = new CustomFields();
  85. $raw = $cf->getAllFieldsData();
  86. if (!empty($raw)) {
  87. foreach ($raw as $io => $each) {
  88. if ($each['typeid'] == $this->customDiscountCfId) {
  89. $discount = vf($each['content'], 3); // numeric int
  90. if ($discount) {
  91. $this->customDiscounts[$each['login']] = $discount;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. }
  98. /**
  99. * Getter for custom discount for some users
  100. *
  101. * @param string $login
  102. * @return int
  103. */
  104. protected function getCustomDiscount($login) {
  105. $result = 0;
  106. if (isset($this->customDiscounts[$login])) {
  107. $result = $this->customDiscounts[$login];
  108. }
  109. return ($result);
  110. }
  111. /**
  112. * Load prices of all available tariffs
  113. *
  114. * @return void
  115. */
  116. protected function loadTariffPrices() {
  117. $raw = zb_TariffGetPricesAll();
  118. if (!empty($raw)) {
  119. foreach ($raw as $io => $each) {
  120. $this->tariffPrices[$io] = $each;
  121. }
  122. }
  123. }
  124. /**
  125. * Loads all available cummulative discounts from database
  126. *
  127. * @return void
  128. */
  129. protected function loadDiscounts() {
  130. $query = "SELECT * from `cudiscounts`";
  131. $raw = simple_queryall($query);
  132. if (!empty($raw)) {
  133. foreach ($raw as $io => $each) {
  134. $this->allDiscounts[$each['login']] = $each;
  135. }
  136. }
  137. }
  138. /**
  139. * Loads the user assigned tags.
  140. *
  141. * If the `onlyTagId` property is set, it retrieves all user tags that match the specified tag ID.
  142. *
  143. * @return void
  144. */
  145. protected function loadUserTags() {
  146. if ($this->onlyTagId) {
  147. $this->allUserTags = zb_UserGetAllTagsUnique('', $this->onlyTagId);
  148. }
  149. }
  150. /**
  151. * Basic setter for the debugging mode
  152. *
  153. * @param int $state
  154. *
  155. * @return void
  156. */
  157. public function setDebug($state) {
  158. if ($state) {
  159. $this->debug = $state;
  160. }
  161. }
  162. /**
  163. * Creates discount field in database
  164. *
  165. * @param string $login
  166. *
  167. * @return void
  168. */
  169. protected function createDiscount($login, $days) {
  170. $login = mysql_real_escape_string($login);
  171. $currentDiscount = 0;
  172. $days = vf($days, 3);
  173. $query = "INSERT INTO `cudiscounts` (`id`, `login`, `discount`, `date`, `days`) "
  174. . "VALUES (NULL,'" . $login . "','" . $currentDiscount . "','" . $this->curdate . "','" . $days . "');";
  175. nr_query($query);
  176. $this->debugLog("CUDISCOUNTS CREATE (" . $login . ")");
  177. }
  178. /**
  179. * Changes discount data in database
  180. *
  181. * @param string $login
  182. * @param int $days
  183. * @param float $discount
  184. */
  185. protected function setDiscount($login, $days, $discount) {
  186. $days = vf($days, 3);
  187. $discount = mysql_real_escape_string($discount);
  188. $login = mysql_real_escape_string($login);
  189. $this->allDiscounts[$login]['days'] = $days;
  190. $this->allDiscounts[$login]['discount'] = $discount;
  191. $query = "UPDATE `cudiscounts` SET `days`='" . $days . "', `discount`='" . $discount . "' WHERE `login`='" . $login . "'; ";
  192. nr_query($query);
  193. }
  194. /**
  195. * Returns discount data for some login
  196. *
  197. * @param string $login
  198. * @return array
  199. */
  200. protected function getDiscountData($login) {
  201. $result = array();
  202. if (isset($this->allDiscounts[$login])) {
  203. $result = $this->allDiscounts[$login];
  204. }
  205. return ($result);
  206. }
  207. /**
  208. * Pushes log data if debugging mode is enabled
  209. *
  210. * @param string $data
  211. */
  212. protected function debugLog($data) {
  213. if ($this->debug) {
  214. file_put_contents($this->logPath, $this->curdate . ' ' . $data . "\n", FILE_APPEND); //append data to log
  215. }
  216. if ($this->debug > 1) {
  217. log_register($data);
  218. }
  219. }
  220. /**
  221. * Adds cash for user
  222. *
  223. * @param string $login
  224. *
  225. * @return void
  226. */
  227. protected function pushDiscount($login) {
  228. if (isset($this->allUsers[$login])) {
  229. $discountData = $this->getDiscountData($login);
  230. if (!empty($discountData)) {
  231. $userTariff = $this->allUsers[$login]['Tariff'];
  232. if (isset($this->tariffPrices[$userTariff])) {
  233. $tariffPrice = $this->tariffPrices[$userTariff];
  234. if ($tariffPrice != 0) {
  235. $discountPercent = $discountData['discount'];
  236. $discountPayment = ($tariffPrice / 100) * $discountPercent;
  237. if ($this->cashMode == 'CORR') {
  238. $cashOperation = 'correct';
  239. } else {
  240. $cashOperation = 'add';
  241. }
  242. zb_CashAdd($login, $discountPayment, $cashOperation, $this->discountPayId, 'DISCOUNT:' . $discountPercent);
  243. $this->debugLog('CUDISCOUNTS PUSH (' . $login . ') PERCENT:' . $discountPercent . ' DAYS:' . $discountData['days'] . ' CASH:' . $discountPayment . ' TARIFF:' . $userTariff);
  244. } else {
  245. $this->debugLog('CUDISCOUNTS IGNORE (' . $login . ') TARIFF ' . $userTariff . ' ZERO PRICE');
  246. }
  247. } else {
  248. $this->debugLog('CUDISCOUNTS IGNORE (' . $login . ') TARIFF ' . $userTariff . ' NOT EXISTS');
  249. }
  250. } else {
  251. $this->debugLog('CUDISCOUNTS IGNORE (' . $login . ') EMPTY DISCOUNT DATA');
  252. }
  253. } else {
  254. $this->debugLog('CUDISCOUNTS IGNORE (' . $login . ') LOGIN NOT EXISTS');
  255. }
  256. }
  257. /**
  258. * Do the discounts preprocessing
  259. *
  260. * @return void
  261. */
  262. public function processDiscounts() {
  263. if (!empty($this->allUsers)) {
  264. foreach ($this->allUsers as $login => $each) {
  265. if ($this->onlyTagId) {
  266. //some specific tag required
  267. $userProcessing = false;
  268. if (isset($this->allUserTags[$login])) {
  269. //its ok
  270. $userProcessing = true;
  271. }
  272. } else {
  273. //all users processing
  274. $userProcessing = true;
  275. }
  276. if ($userProcessing) {
  277. //maybe first run?
  278. if (!isset($this->allDiscounts[$login])) {
  279. if (($each['Cash'] >= -$each['Credit']) and ($each['Passive'] == 0) and ($each['Down'] == 0)) {
  280. $this->createDiscount($login, 1); // yep, nice day
  281. } else {
  282. $this->createDiscount($login, 0); // you are looser, man
  283. }
  284. } else {
  285. //discount already available
  286. $discountData = $this->getDiscountData($login);
  287. if (($each['Cash'] >= -$each['Credit']) and ($each['Passive'] == 0) and ($each['Down'] == 0)) {
  288. if ($discountData['days'] < $this->discountPullDays) {
  289. //user active - normal processing
  290. $daysFill = $discountData['days'] + 1;
  291. $customDiscount = $this->getCustomDiscount($login);
  292. if ($customDiscount) {
  293. //is custom discount set for this user?
  294. $newDiscount = $customDiscount;
  295. $this->debugLog('CUDISCOUNTS OVERRIDE (' . $login . ') PERCENT:' . $customDiscount);
  296. } else {
  297. $newDiscount = $discountData['discount'];
  298. }
  299. $this->setDiscount($login, $daysFill, $newDiscount);
  300. $this->debugLog('CUDISCOUNTS UPDATE (' . $login . ') DAYS:' . $daysFill . ' PERCENT:' . $discountData['discount']);
  301. } else {
  302. //discount pushing, clearing days counter
  303. //may be override with custom field?
  304. $customDiscount = $this->getCustomDiscount($login);
  305. if ($customDiscount) {
  306. //CF override
  307. $newDiscount = $customDiscount;
  308. } else {
  309. //natural cumulative discount
  310. $newDiscount = ($discountData['discount'] < $this->discountLimit) ? $discountData['discount'] + $this->fillPercent : $this->discountLimit;
  311. }
  312. $this->setDiscount($login, 0, $newDiscount);
  313. $this->pushDiscount($login); // pay some money, flush counters
  314. }
  315. } else {
  316. //passive user
  317. //try to save mysql query count
  318. if ($discountData['days'] != 0) {
  319. $this->setDiscount($login, 0, 0);
  320. $this->debugLog('CUDISCOUNTS SETDOWN (' . $login . ') DAYS: 0 PERCENT: 0');
  321. }
  322. }
  323. }
  324. }
  325. }
  326. } else {
  327. $this->debugLog('CUDISCOUNTS NO USERS');
  328. }
  329. }
  330. /**
  331. * Sets filtering login private property
  332. *
  333. * @param string $login
  334. *
  335. * @return void
  336. */
  337. public function setLogin($login) {
  338. $this->login = $login;
  339. }
  340. /**
  341. * Parses log data for some user login
  342. *
  343. * @return array
  344. */
  345. protected function getLogData() {
  346. $result = array();
  347. global $ubillingConfig;
  348. $billCfg = $ubillingConfig->getBilling();
  349. $cat = $billCfg['CAT'];
  350. $grep = $billCfg['GREP'];
  351. $i = 0;
  352. if (!empty($this->login)) {
  353. if (file_exists($this->logPath)) {
  354. $command = $cat . ' ' . $this->logPath . ' | grep "(' . $this->login . ')"';
  355. $raw = shell_exec($command);
  356. if (!empty($raw)) {
  357. $raw = explodeRows($raw);
  358. if (!empty($raw)) {
  359. foreach ($raw as $io => $each) {
  360. if (!empty($each)) {
  361. $line = explode(' ', $each);
  362. $date = $line[0] . ' ' . $line[1];
  363. $event = $line[3];
  364. $params = explode(')', $each);
  365. $params = $params[1];
  366. $result[$i]['date'] = $date;
  367. $result[$i]['event'] = $event;
  368. $result[$i]['params'] = $params;
  369. $i++;
  370. }
  371. }
  372. }
  373. }
  374. }
  375. }
  376. return ($result);
  377. }
  378. /**
  379. * Renders cumulative discounts report
  380. *
  381. * @return string
  382. */
  383. public function renderReport() {
  384. $result = '';
  385. $currentData = $this->getDiscountData($this->login);
  386. $customDiscount = $this->getCustomDiscount($this->login);
  387. if (!empty($currentData)) {
  388. $cells = wf_TableCell(__('Discount'));
  389. $cells .= wf_TableCell(__('Day'));
  390. $cells .= wf_TableCell(__('Custom discount'));
  391. $rows = wf_TableRow($cells, 'row1');
  392. $cells = wf_TableCell($currentData['discount'] . '%');
  393. $cells .= wf_TableCell($currentData['days']);
  394. if ($customDiscount == 0) {
  395. $customDiscount = __('No');
  396. } else {
  397. $customDiscount = $customDiscount . '%';
  398. }
  399. $cells .= wf_TableCell($customDiscount);
  400. $rows .= wf_TableRow($cells, 'row3');
  401. $result .= wf_TableBody($rows, '100%', 0, 'glamour');
  402. $result .= wf_CleanDiv();
  403. $result .= wf_delimiter();
  404. }
  405. $logData = $this->getLogData();
  406. if (!empty($logData)) {
  407. $cells = wf_TableCell(__('Date'));
  408. $cells .= wf_TableCell(__('Event'));
  409. $cells .= wf_TableCell(__('Details'));
  410. $rows = wf_TableRow($cells, 'row1');
  411. foreach ($logData as $io => $each) {
  412. $fc = wf_tag('font', false);
  413. $efc = wf_tag('font', true);
  414. if ($each['event'] == 'CREATE') {
  415. $fc = wf_tag('font', false, '', 'color="#ffac1b"');
  416. }
  417. if ($each['event'] == 'UPDATE') {
  418. $fc = wf_tag('font', false, '', 'color="#6396ff"');
  419. }
  420. if ($each['event'] == 'PUSH') {
  421. $fc = wf_tag('font', false, '', 'color="#1c7700"');
  422. }
  423. if ($each['event'] == 'SET') {
  424. $fc = wf_tag('font', false, '', 'color="#a90000"');
  425. }
  426. if ($each['event'] == 'SETDOWN') {
  427. $fc = wf_tag('font', false, '', 'color="#a90000"');
  428. }
  429. $params = $each['params'];
  430. $params = str_replace('DAYS', __('Day'), $params);
  431. $params = str_replace('PERCENT', __('Percent'), $params);
  432. $params = str_replace('CASH', __('Cash'), $params);
  433. $params = str_replace('TARIFF', __('Tariff'), $params);
  434. $cells = wf_TableCell($fc . $each['date'] . $efc);
  435. $cells .= wf_TableCell($fc . $each['event'] . $efc);
  436. $cells .= wf_TableCell($params);
  437. $rows .= wf_TableRow($cells, 'row3');
  438. }
  439. $result .= wf_TableBody($rows, '100%', 0, 'sortable');
  440. } else {
  441. $result .= wf_tag('span', false, 'alert_warning') . __('Nothing found') . wf_tag('span', true);
  442. }
  443. return ($result);
  444. }
  445. }