BonusSend.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/3/18
  6. * Time: 上午11:06
  7. */
  8. namespace common\helpers\bonus;
  9. use common\components\ActiveRecord;
  10. use common\helpers\DataBak;
  11. use common\helpers\Form;
  12. use common\helpers\LoggerTool;
  13. use common\helpers\Tool;
  14. use common\helpers\user\Balance;
  15. use common\helpers\user\Info;
  16. use common\helpers\user\Reconsume;
  17. use common\libs\api\sms\SmsApi;
  18. use common\models\DealType;
  19. use common\models\EliteLevel;
  20. use common\models\FlowRemainPv;
  21. use common\models\PerfPeriod;
  22. use common\models\EmployLevel;
  23. use common\models\UserBonus;
  24. use common\models\UserPerfMonthUpdate;
  25. use common\models\UserPerformance;
  26. use common\models\UserPeriodPoints;
  27. use common\models\UserInfo;
  28. use common\models\UserPerf;
  29. use common\models\UserPerfUpdate;
  30. use common\models\UserTeamwork;
  31. use common\models\YearHighestEmpLv;
  32. use common\models\Order;
  33. use common\models\RemainPv;
  34. use yii\base\BaseObject;
  35. use yii\base\StaticInstanceTrait;
  36. use common\helpers\Cache;
  37. use common\helpers\Date;
  38. use common\models\CalcBonus;
  39. use common\models\CalcBonusBS;
  40. use common\models\CalcBonusQY;
  41. use common\models\PerfActiveUser;
  42. use common\models\PerfMonth;
  43. use common\models\User;
  44. use Yii;
  45. use common\models\Period;
  46. use yii\base\Exception;
  47. use yii\db\Expression;
  48. class BonusSend extends BaseObject {
  49. use StaticInstanceTrait;
  50. private $_limit = 1000;
  51. private $_appUserId = null;
  52. private $_sysConfig = [];
  53. private $_decLevelConfig = [];
  54. private $_empLevelConfig = [];
  55. private $_decRoleConfig = [];
  56. private $_errors = [];
  57. private $_periodNum = 0;
  58. private $_periodId;
  59. private $_isCalcMonth = 0;
  60. private $_isCalcYear = 0;
  61. private $_calcYear;
  62. private $_calcMonth;
  63. private $_calcYearMonth;
  64. private $_lastCalcYear;
  65. private $_lastCalcMonth;
  66. private $_lastCalcYearMonth;
  67. private $_workerId;
  68. private $_workerNum;
  69. public function init(int $periodNum = 0, $appUserId = null, $workerId = null, $workerNum = null) {
  70. parent::init();
  71. $this->_sysConfig = Cache::getSystemConfig();
  72. $this->_decLevelConfig = Cache::getDecLevelConfig();
  73. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  74. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  75. $this->_periodNum = $periodNum;
  76. $this->_appUserId = $appUserId;
  77. $this->_workerId = $workerId;
  78. $this->_workerNum = $workerNum;
  79. }
  80. /**
  81. * 设置期数
  82. * @param int $periodNum
  83. * @return int
  84. */
  85. public function setPeriodNum(int $periodNum) {
  86. return $this->_periodNum = $periodNum;
  87. }
  88. /**
  89. * 获取期数
  90. * @return int
  91. */
  92. public function getPeriodNum() {
  93. return $this->_periodNum;
  94. }
  95. /**
  96. * 加入错误错误
  97. * @param $attr
  98. * @param $error
  99. */
  100. public function addError($attr, $error) {
  101. $this->_errors[$attr][] = $error;
  102. }
  103. /**
  104. * 获取错误信息
  105. * @return array
  106. */
  107. public function getErrors() {
  108. return $this->_errors;
  109. }
  110. /**
  111. * 挂网时处理虚假订单
  112. *
  113. */
  114. public function putFakeOrder() {
  115. echo('开始处理-假订单' . PHP_EOL);
  116. $sysConfig = Cache::getSystemConfig();
  117. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  118. $fakeOrder= Order::find()->where(['PERIOD_NUM'=>$this->_periodNum, 'IS_AUTO'=>'1'])->asArray()->all();
  119. foreach($fakeOrder as $fOrder){
  120. $oRemainPv=RemainPv::findOne(["USER_ID"=>$fOrder['USER_ID']]);
  121. $transactionRemain = \Yii::$app->db->beginTransaction();
  122. try{
  123. $fakeOrderPv = $oRemainPv->REMAIN_PV>=$mesureUpCondition?$mesureUpCondition:$oRemainPv->REMAIN_PV;
  124. $flowRemainPvModel = new FlowRemainPv();
  125. $flowRemainPvModel->ID = $this->_generateSn();
  126. $flowRemainPvModel->USER_ID = $fOrder['USER_ID'];
  127. $flowRemainPvModel->REMAIN_PV_FLOW = 0 - $fakeOrderPv;
  128. $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv->REMAIN_PV - $fakeOrderPv;
  129. $flowRemainPvModel->PERIOD_NUM = $this->_periodNum;
  130. $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  131. $flowRemainPvModel->ORDER_SN = $fOrder['SN'];
  132. if(!$flowRemainPvModel->save()){
  133. $this->addErrors($flowRemainPvModel->getErrors());
  134. return false;
  135. }
  136. $oRemainPv->updateCounters(['REMAIN_PV'=>0-$fakeOrderPv]);
  137. $transactionRemain->commit();
  138. } catch (Exception $e) {
  139. $transactionRemain->rollBack();
  140. $this->addError('add', $e->getMessage());
  141. return null;
  142. }
  143. }
  144. echo('假订单处理完' . PHP_EOL);
  145. return true; // $flowRemainPvModel;
  146. }
  147. /**
  148. * 生成流水号
  149. * @return string
  150. */
  151. private function _generateSn() {
  152. return Date::today('Ymd') . $this->_random(10, 1);
  153. }
  154. /**
  155. * 生成随机数
  156. * @param $length
  157. * @param int $numeric
  158. * @return string
  159. */
  160. private function _random($length, $numeric = 0) {
  161. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  162. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  163. $hash = '';
  164. $max = strlen($seed) - 1;
  165. for ($i = 0; $i < $length; $i++) {
  166. $hash .= $seed[mt_rand(0, $max)];
  167. }
  168. return $hash;
  169. }
  170. /**
  171. * 进行奖金发放步骤
  172. * @return bool
  173. */
  174. public function sendStep() {
  175. try {
  176. $t1 = microtime(true);
  177. // 初始化
  178. $this->initTask();
  179. echo('挂网开始');
  180. // 改变状态
  181. $this->setSendStatus('start');
  182. // 发放荣衔级别(Honor/Emp)、Elite级别
  183. $this->sentMemberLevel();
  184. $this->_updatePercent(30);
  185. $t2 = microtime(true);
  186. echo('更新会员级别完成,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  187. // 发放奖金
  188. $this->sendBonusLoop();
  189. $this->_updatePercent(80);
  190. $t3 = microtime(true);
  191. echo('发放奖金完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  192. echo('全部奖金发放完成,耗时:'.round($t3 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
  193. $this->_updatePercent(100);
  194. } catch (\Exception $e) {
  195. LoggerTool::error('sendBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
  196. $this->addError('sendBonus', sprintf('%s',$e->getMessage()));
  197. return false;
  198. }
  199. if (count($this->_errors) > 0) {
  200. return false;
  201. }
  202. return true;
  203. }
  204. /**
  205. * 需要多进程执行的任务
  206. * @param $workId
  207. * @throws \yii\db\Exception
  208. */
  209. public function processStep($workId = null) {
  210. if ($workId == 1 || $workId === null) {
  211. // 发放奖金
  212. $this->sendBonusLoop();
  213. }
  214. if ($workId == 2 || $workId === null) {
  215. // 更新聘级
  216. $this->updateEmpLevel();
  217. }
  218. if ($workId == 3 || $workId === null) {
  219. // 更新会员累计业绩
  220. $this->updateUserPerf();
  221. }
  222. Yii::$app->db->close();
  223. Yii::$app->dbShop->close();
  224. }
  225. /**
  226. * 初始化发放任务
  227. * @throws Exception
  228. */
  229. public function initTask() {
  230. $this->_errors = [];
  231. $periodNum = $this->_periodNum;
  232. // 获取传入期数的相关信息
  233. $periodObj = Period::instance();
  234. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  235. $this->_periodId = $periodDataArr['ID'];
  236. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  237. $this->_calcYear = $periodObj->getYear($periodNum);
  238. $this->_calcMonth = $periodObj->getMonth($periodNum);
  239. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  240. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  241. $this->_lastCalcYear = $lastYearMonthArr['year'];
  242. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  243. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  244. }
  245. /**
  246. * 设置结算状态
  247. * @param $type
  248. * start|end|fail
  249. */
  250. public function setSendStatus($type) {
  251. Yii::$app->db->close();
  252. if ($type == 'start') {
  253. Period::updateAll(['IS_SENDING' => 1, 'SEND_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  254. } elseif ($type == 'end') {
  255. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FINISH, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  256. } elseif ($type == 'fail') {
  257. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FAIL, 'SENT_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  258. }
  259. }
  260. /**
  261. * 结束计算任务
  262. * @throws \yii\db\Exception
  263. */
  264. public function endTask() {
  265. CalcCache::clearAll($this->_periodNum);
  266. $this->setSendStatus('end');
  267. //@todo 先不备份数据
  268. // DataBak::backup($this->_periodNum);
  269. //发送复销短信
  270. // if ($this->_isCalcMonth && $this->_sysConfig['smsOpen']['VALUE']) {
  271. // $this->sendSmsLoop();
  272. // }
  273. }
  274. /**
  275. * 出现错误
  276. */
  277. public function errorTask() {
  278. $this->setSendStatus('fail');
  279. }
  280. /**
  281. * 发放奖金
  282. * @param int $page
  283. * @return bool
  284. * @throws \yii\db\Exception
  285. */
  286. public function sendBonusLoop($page = 1) {
  287. echo sprintf("时间:[%s]数据库发奖,当前page为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $page);
  288. $periodNum = $this->_periodNum;
  289. // 从奖金结算表中获取当期未发放的所有数据
  290. $allData = CalcBonus::find()
  291. ->yearMonth($this->_calcYearMonth)
  292. ->select('ID, USER_ID, BONUS_REAL, BONUS_TOTAL, MANAGE_TAX, ')
  293. ->where('(IS_SENT=0 OR IS_SENT=2) AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  294. [':CALC_MONTH' => $this->_calcYearMonth, ':PERIOD_NUM' => $this->_periodNum]
  295. )
  296. ->limit($this->_limit)
  297. ->asArray()
  298. ->all();
  299. if ($allData) {
  300. $transaction = Yii::$app->db->beginTransaction();
  301. try {
  302. foreach ($allData as $key => $data) {
  303. // 用户奖金发放
  304. if ($data['BONUS_REAL'] > 0) {
  305. Balance::changeUserBonus($data['USER_ID'], 'userBonus', $data['BONUS_REAL'],
  306. [
  307. 'CALC_ID' => $data['ID'],
  308. 'REMARK' => 'From Period ' . $data['PERIOD_NUM'],
  309. 'PERIOD_NUM' => $periodNum,
  310. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  311. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  312. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  313. 'SORT' => $key * 10,
  314. 'BONUS_ISSUE' => true,
  315. ]);
  316. }
  317. // 绩效奖金发放
  318. if ($data['BONUS_PB'] > 0) {
  319. UserPerformance::sentUserPerformance($data['USER_ID'], $data['BONUS_PB'], $data['PERIOD_NUM']);
  320. }
  321. // 把记录标记为已发放状态
  322. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  323. unset($periodAmount, $key, $data);
  324. }
  325. $transaction->commit();
  326. } catch (Exception $e) {
  327. $transaction->rollBack();
  328. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  329. return false;
  330. }
  331. unset($allData, $transaction);
  332. $page++;
  333. return $this->sendBonusLoop($page);
  334. }
  335. unset($allData);
  336. return true;
  337. }
  338. /**
  339. * 蓝星奖金(即新的管理奖),更新会员聘级
  340. * @param int $offset
  341. * @return bool
  342. * @throws \yii\db\Exception
  343. */
  344. public function updateEmpLevel(int $offset = 0) {
  345. if ($this->_isCalcMonth) {
  346. $empLv = EmployLevel::getIdConvertLevelSortCache();
  347. $allData = CalcBonusBS::find()
  348. ->yearMonth($this->_calcYearMonth)
  349. ->where(
  350. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  351. [
  352. ':CALC_MONTH' => $this->_calcYearMonth,
  353. ':PERIOD_NUM' =>$this->_periodNum
  354. ]
  355. )
  356. ->orderBy('CREATED_AT DESC')
  357. ->offset($offset)
  358. ->limit($this->_limit)
  359. ->all();
  360. LoggerTool::info($allData);
  361. //@todo 用户级别不变则不更新
  362. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  363. if ($allData) {
  364. $transaction = Yii::$app->db->beginTransaction();
  365. try {
  366. foreach ($allData as $data) {
  367. // 蓝星奖计算的最新聘级
  368. $latestEmpLv = $data['LEVEL_ID']; // 本期计算最新管理级别
  369. $latestEmpLvSort = $empLv[$latestEmpLv]; // 当前蓝星计算的聘级 级别值
  370. if ($defaultEmpLv == $latestEmpLv) {
  371. continue;
  372. }
  373. // 用户存储的最高聘级
  374. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  375. $highestEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  376. $highestEmpLvSort = $empLv[$highestEmpLv]; // 历史最高聘级的 级别值
  377. // 如果当前期的聘级高于用户表的最高聘级,则进行更新
  378. if ($latestEmpLvSort > $highestEmpLvSort) {
  379. User::updateAll(['EMP_LV' => $latestEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  380. User::deleteBaseInfoFromRedis($data['USER_ID']);
  381. }
  382. // 更新最新用户表级别
  383. User::updateAll([
  384. 'LAST_EMP_LV' => $latestEmpLv,
  385. 'LAST_EMP_LV_UPDATED_AT' => time(),
  386. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum
  387. ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  388. User::deleteBaseInfoFromRedis($data['USER_ID']);
  389. unset($data);
  390. }
  391. $transaction->commit();
  392. } catch (Exception $e) {
  393. $transaction->rollBack();
  394. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  395. return false;
  396. }
  397. unset($transaction, $allData, $defaultEmpLv);
  398. return $this->updateEmpLevel($offset + $this->_limit);
  399. }
  400. unset($allData);
  401. // 刷新会员EmpLv为0
  402. User::updateAll([
  403. 'LAST_EMP_LV' => '',
  404. 'LAST_EMP_LV_UPDATED_AT' => time(),
  405. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  406. ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $this->_periodNum]);
  407. User::deleteAllBaseInfoFromRedis();
  408. }
  409. return true;
  410. }
  411. public function sentMemberLevel()
  412. {
  413. $transaction = Yii::$app->db->beginTransaction();
  414. try {
  415. $db = Yii::$app->db;
  416. // 刷新所有会员最新EliteLevel和最新EmpLevel为默认等级
  417. User::updateAll(
  418. [
  419. 'LAST_EMP_LV' => EmployLevel::getDefaultLevelId(),
  420. 'LAST_EMP_LV_UPDATED_AT' => time(),
  421. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  422. 'LAST_ELITE_LV' => EliteLevel::getDefaultLevelId(),
  423. 'LAST_ELITE_LV_UPDATED_AT' => time(),
  424. 'LAST_ELITE_LV_UPDATED_PERIOD' => $this->_periodNum,
  425. ]);
  426. // 刷新会员最高EliteLevel和最高EmpLevel(统一数据,更新为默认Elite级别)
  427. User::updateAll(['EMP_LV' => EmployLevel::getDefaultLevelId()], "EMP_LV = '' OR EMP_LV IS NULL");
  428. User::updateAll(['ELITE_LV' => EliteLevel::getDefaultLevelId()], "ELITE_LV = '' OR ELITE_LV IS NULL");
  429. $sql =<<<SQL
  430. UPDATE `AR_USER` `user`
  431. INNER JOIN `AR_CALC_BONUS` `bonus` ON `user`.`ID` = `bonus`.`USER_ID` AND `bonus`.`CALC_MONTH` = :CALC_MONTH AND `bonus`.`PERIOD_NUM` = :PERIOD_NUM
  432. SET
  433. `user`.`EMP_LV` = `bonus`.`HIGHEST_HONOR_LV`,
  434. `user`.`LAST_EMP_LV` = `bonus`.`LAST_EMP_LV`,
  435. `user`.`LAST_EMP_LV_UPDATED_AT` = :UPDATED_AT,
  436. `user`.`LAST_EMP_LV_UPDATED_PERIOD` = :PERIOD_NUM,
  437. `user`.`ELITE_LV` = `bonus`.`HIGHEST_ELITE_LV`,
  438. `user`.`LAST_ELITE_LV` = `bonus`.`LAST_ELITE_LV`,
  439. `user`.`LAST_ELITE_LV_UPDATED_AT` = :UPDATED_AT,
  440. `user`.`LAST_ELITE_LV_UPDATED_PERIOD` = :PERIOD_NUM
  441. WHERE
  442. `bonus`.`PERIOD_NUM` = :PERIOD_NUM
  443. SQL;
  444. $db->createCommand($sql)
  445. ->bindValues(
  446. [
  447. ':CALC_MONTH' => $this->_calcYearMonth,
  448. ':PERIOD_NUM' => $this->_periodNum,
  449. ':UPDATED_AT' => time(),
  450. ])
  451. ->execute();
  452. $transaction->commit();
  453. // 刷新本期无Elite的用户级别
  454. // 删除缓存中的会员信息
  455. User::deleteAllBaseInfoFromRedis();
  456. } catch (Exception $e) {
  457. $transaction->rollBack();
  458. $this->addError('sendLevelFailed', '发放会员级别失败,原因:' . $e->getMessage());
  459. return false;
  460. }
  461. return true;
  462. }
  463. // 更活跃会员,将is_send改成1
  464. public function updateActiveUser() {
  465. $ret = PerfActiveUser::updateAll(
  466. ['IS_SENT' => 1],
  467. 'PERIOD_NUM=:PERIOD_NUM AND IS_SENT=:IS_SENT',
  468. ['IS_SENT'=>0, 'PERIOD_NUM'=>$this->_periodNum]
  469. );
  470. return $ret;
  471. }
  472. /**
  473. * 更新会员的累计业绩
  474. * @param int $offset
  475. * @return bool
  476. * @throws \yii\db\Exception
  477. */
  478. public function updateUserPerf(int $offset = 0) {
  479. $allData = PerfPeriod::find()
  480. ->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  481. if ($allData) {
  482. $transaction = Yii::$app->db->beginTransaction();
  483. try {
  484. foreach ($allData as $data) {
  485. $isUpdate = false;
  486. if (UserPerf::find()
  487. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  488. // 判断本期是否已经更新过业绩
  489. if (!UserPerfUpdate::find()
  490. ->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
  491. $isUpdate = true;
  492. // 更新业绩
  493. UserPerf::updateAll([
  494. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  495. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  496. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  497. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  498. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  499. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  500. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  501. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  502. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  503. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  504. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  505. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  506. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  507. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  508. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  509. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  510. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  511. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  512. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  513. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  514. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  515. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  516. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  517. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  518. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  519. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  520. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  521. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  522. }
  523. } else {
  524. $isUpdate = true;
  525. UserPerf::insertOne([
  526. 'USER_ID' => $data['USER_ID'],
  527. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  528. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  529. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  530. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  531. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  532. 'PV_PSS' => $data['PV_PSS'],
  533. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  534. 'PV_1L' => $data['PV_1L'],
  535. 'PV_2L' => $data['PV_2L'],
  536. 'PV_3L' => $data['PV_3L'],
  537. 'PV_4L' => $data['PV_4L'],
  538. 'PV_5L' => $data['PV_5L'],
  539. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  540. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  541. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  542. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  543. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  544. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  545. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  546. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  547. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  548. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  549. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  550. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  551. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  552. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  553. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  554. 'CREATED_AT' => Date::nowTime(),
  555. ]);
  556. }
  557. if ($isUpdate) {
  558. // 变为已更新
  559. UserPerfUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'PERIOD_NUM' => $this->_periodNum, 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH), 'CREATED_AT' => Date::nowTime()]);
  560. }
  561. unset($data, $isUpdate);
  562. }
  563. $transaction->commit();
  564. } catch (Exception $e) {
  565. $transaction->rollBack();
  566. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  567. return false;
  568. }
  569. unset($allData, $transaction);
  570. return $this->updateUserPerf($offset + $this->_limit);
  571. }
  572. unset($allData);
  573. return true;
  574. }
  575. /**
  576. * 更新会员的月剩余业绩
  577. * @param int $offset
  578. * @return bool
  579. * @throws \yii\db\Exception
  580. */
  581. public function updateUserPerfMonth(int $offset = 0) {
  582. // 月结,如果不是月结点,则直接退出
  583. if (!$this->_isCalcMonth) {
  584. return true;
  585. }
  586. // $allData = PerfMonth::findUseDbCalc()
  587. $allData = PerfMonth::find()
  588. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  589. if ($allData) {
  590. $transaction = Yii::$app->db->beginTransaction();
  591. try {
  592. foreach ($allData as $data) {
  593. $isUpdate = false;
  594. // if (UserPerf::findUseDbCalc()
  595. if (UserPerf::find()
  596. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  597. // 判断本期是否已经更新过业绩
  598. // if (!UserPerfMonthUpdate::findUseDbCalc()
  599. if (!UserPerfMonthUpdate::find()
  600. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  601. $isUpdate = true;
  602. // 更新业绩
  603. UserPerf::updateAll([
  604. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  605. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  606. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  607. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  608. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  609. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  610. }
  611. } else {
  612. $isUpdate = true;
  613. UserPerf::insertOne([
  614. 'USER_ID' => $data['USER_ID'],
  615. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  616. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  617. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  618. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  619. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  620. 'CREATED_AT' => Date::nowTime(),
  621. ]);
  622. }
  623. if ($isUpdate) {
  624. // 变为已更新
  625. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  626. }
  627. unset($data, $isUpdate);
  628. }
  629. $transaction->commit();
  630. } catch (Exception $e) {
  631. $transaction->rollBack();
  632. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  633. return false;
  634. }
  635. unset($allData, $transaction);
  636. return $this->updateUserPerfMonth($offset + $this->_limit);
  637. }
  638. unset($allData);
  639. return true;
  640. }
  641. /**
  642. * 检测复消积分是否过期
  643. * @return bool
  644. * @throws \yii\db\Exception
  645. */
  646. public function checkReconsumePointsExpired(int $offset = 0) {
  647. $periodNum = $this->_periodNum;
  648. //一期为7天,那么365天为52.14即53期
  649. $expiredPeriodNum = $periodNum - 53;
  650. if( $expiredPeriodNum <= 0 ) return true;
  651. //查询需要过期的期数
  652. $allData = UserPeriodPoints::find()->select('ID,USER_ID,REMAINDER_POINTS')->where('PERIOD_NUM<=:PERIOD_NUM AND EXPIRED=0', ['PERIOD_NUM'=>$expiredPeriodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->asArray()->all();
  653. if( $allData ) {
  654. $transaction = Yii::$app->db->beginTransaction();
  655. try{
  656. //扣除钱包的复消积分
  657. foreach ($allData as $everyData) {
  658. //过期
  659. UserPeriodPoints::updateAll([
  660. 'REMAINDER_POINTS' => 0,
  661. 'EXPIRED' => 1,
  662. 'EXPIRED_PERIOD' => $periodNum,
  663. 'EXPIRED_AT' => Date::nowTime(),
  664. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  665. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  666. UserBonus::updateAllCounters([
  667. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  668. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  669. unset($everyData);
  670. }
  671. unset($periodNum, $expiredPeriodNum, $allData);
  672. $transaction->commit();
  673. }catch (\Exception $e){
  674. $transaction->rollBack();
  675. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  676. return false;
  677. }
  678. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  679. }
  680. unset($allData);
  681. return true;
  682. }
  683. /**
  684. * 更新会员上次报单级别
  685. * @return bool
  686. */
  687. public function updateUserDevLv() {
  688. $transaction = Yii::$app->dbShop->beginTransaction();
  689. try {
  690. \Yii::$app->dbShop->createCommand()->update(User::tableName(), ['LAST_DEC_LV' => new Expression('DEC_LV'), 'LAST_DEC_LV_UPDATED_AT' => Date::nowTime(), 'LAST_DEC_LV_UPDATED_PERIOD' => $this->_periodNum], 'LAST_DEC_LV!=DEC_LV')->execute();
  691. $transaction->commit();
  692. } catch (Exception $e) {
  693. $transaction->rollBack();
  694. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  695. return false;
  696. }
  697. return true;
  698. }
  699. /**
  700. * 给商城会员增加货款
  701. * @param $userId
  702. * @param $amount
  703. * @param $remark
  704. * @throws Exception
  705. */
  706. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  707. $db = \Yii::$app->dbShop;
  708. $transaction = $db->beginTransaction();
  709. try {
  710. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  711. // 增加流水
  712. $flowInsertData[] = [
  713. 'USER_ID' => $userId,
  714. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  715. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  716. 'ORDER_SN' => null,
  717. 'AMOUNT' => $amount,
  718. 'CREATED_AT' => Date::nowTime(),
  719. 'PERIOD_AT' => $this->_periodNum,
  720. 'IS_INCR' => 1,
  721. 'REMARK' => $remark,
  722. 'PARTITION_DATE' => Date::ociToDate(),
  723. 'WALLET_TYPE' => 'payment_for_goods',
  724. 'FROM_TYPE' => 'incr',
  725. ];
  726. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  727. $transaction->commit();
  728. } catch (Exception $e) {
  729. $transaction->rollBack();
  730. throw new Exception($e->getMessage());
  731. }
  732. }
  733. /**
  734. * 更新百分比并发送
  735. * @param $percent
  736. */
  737. private function _updatePercent($percent) {
  738. // 把数据写入数据库中
  739. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  740. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  741. }
  742. /**
  743. * 更新最高聘级
  744. * @param $user_id
  745. * @return bool
  746. * @throws Exception
  747. */
  748. private function _updateHighestEmpLv($user_id) {
  749. $empLv = Info::getEmpLv($user_id);
  750. $highEmpLv = Info::getHighEmpLv($user_id);
  751. $empLvSort = EmployLevel::getSortById($empLv);
  752. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  753. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  754. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  755. YearHighestEmpLv::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_SORT' => $empLvSort, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum, 'UPDATED_AT' => Date::nowTime()], 'USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear]);
  756. }
  757. } else {
  758. $yearHighest = new YearHighestEmpLv();
  759. $yearHighest->USER_ID = $user_id;
  760. $yearHighest->YEAR = $this->_calcYear;
  761. $yearHighest->HIGHEST_EMP_LV = $empLv;
  762. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  763. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  764. $yearHighest->CREATED_AT = Date::nowTime();
  765. if (!$yearHighest->save()) {
  766. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  767. }
  768. }
  769. if ($empLvSort > $empLvHighSort) {
  770. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  771. //发送历史最高聘级短信
  772. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  773. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  774. $realName = Info::getUserRealNameByUserId($user_id);
  775. $empLvDate = Date::convert();
  776. $empLvName = EmployLevel::getNameById($empLv);
  777. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  778. $params = [
  779. 'mobiles' => Info::getUserMobileByUserId($user_id),
  780. 'content' => $content,
  781. ];
  782. SmsApi::instance()->clearError();
  783. SmsApi::instance()->goSend($params);
  784. }
  785. }
  786. return true;
  787. }
  788. return false;
  789. }
  790. /**
  791. * 点位合作奖金
  792. * @param $userId
  793. * @param $amount
  794. * @param null $type
  795. * @return bool
  796. * @throws Exception
  797. * @throws \yii\db\Exception
  798. */
  799. private function _teamworkBonus($userId, $amount, $key) {
  800. if (!$teamwork = UserTeamwork::findAllAsArray('USER_ID!=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userId], 'USER_ID,DIVIDE_PERCENT')) return false;
  801. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  802. foreach ($teamwork as $value) {
  803. $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
  804. if ($bonus <= 0) continue;
  805. $toUserInfo = CalcCache::getUserInfo($value['USER_ID'], $this->_periodNum);
  806. Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_OUT, 'REMARK' => 'To:' . $toUserInfo['USER_NAME'] . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
  807. Balance::changeUserBonus($value['USER_ID'], 'bonus', abs($bonus), ['SORT' => $key*10+2, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_IN, 'REMARK' => 'From: ' . $fromUserInfo['USER_NAME'] . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
  808. }
  809. }
  810. /**
  811. * 发送短信
  812. * @param int $offset
  813. * @return bool
  814. * @throws \yii\db\Exception
  815. */
  816. public function sendSmsLoop(int $offset = 0) {
  817. // $allData = UserInfo::findUseDbCalc()
  818. $allData = UserInfo::find()
  819. ->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  820. if ($allData) {
  821. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  822. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  823. //获取剩余月份
  824. $period = Period::instance();
  825. $year = $period->getYear($this->_periodNum);
  826. $monthLeft = Period::getMonthLeft($this->_periodNum);
  827. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  828. $to = Date::yearEnd();
  829. $transaction = Yii::$app->db->beginTransaction();
  830. try {
  831. foreach ($allData as $data) {
  832. $userId = $data['USER_ID'];
  833. //过期续费
  834. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  835. foreach ($smsWallet as $item) {
  836. //1奖金钱包2现金钱包
  837. if ($item == 1) {
  838. //看余额是否充足
  839. if (Balance::getAvailableBalance($userId) < $smsFee){
  840. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  841. continue;
  842. };
  843. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  844. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  845. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  846. break;
  847. } elseif ($item == 2) {
  848. throw new Exception('不存在此方式');
  849. break;
  850. }
  851. }
  852. }
  853. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  854. $realName = Info::getUserRealNameByUserId($userId);
  855. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  856. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  857. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  858. $month = $period->getNowMonth();
  859. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  860. //todo 发短信函数 待测试
  861. $params = [
  862. 'mobiles' => $mobile,
  863. 'content' => $content,
  864. ];
  865. SmsApi::instance()->clearError();
  866. SmsApi::instance()->goSend($params);
  867. }
  868. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  869. }
  870. $transaction->commit();
  871. } catch (Exception $e) {
  872. $transaction->rollBack();
  873. return false;
  874. }
  875. unset($data);
  876. return $this->sendSmsLoop($offset + $this->_limit);
  877. }
  878. unset($allData);
  879. return true;
  880. }
  881. }