BonusSend.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. * @return bool
  283. * @throws \yii\db\Exception
  284. */
  285. public function sendBonusLoop(): bool
  286. {
  287. echo sprintf("时间:[%s] 奖金挂网" . PHP_EOL, date('Y-m-d H:i:s', time()));
  288. $periodNum = $this->_periodNum;
  289. // 从奖金结算表中获取当期未发放的所有数据
  290. $allData = CalcBonus::find()
  291. ->select('ID, USER_ID, PERIOD_NUM, BONUS_TOTAL, MANAGE_TAX, BONUS_PB')
  292. ->where('IS_SENT=0 AND PERIOD_NUM=:PERIOD_NUM AND (BONUS_TOTAL>0 OR BONUS_PB>0)', [':PERIOD_NUM' => $this->_periodNum])
  293. ->asArray()
  294. ->all();
  295. LoggerTool::info(['$allData', $allData]);
  296. if ($allData) {
  297. $transaction = Yii::$app->db->beginTransaction();
  298. try {
  299. foreach ($allData as $key => $data) {
  300. // 用户奖金发放
  301. if ($data['BONUS_TOTAL'] > 0) {
  302. Balance::changeUserBonus($data['USER_ID'], 'bonus', $data['BONUS_TOTAL'],
  303. [
  304. 'CALC_ID' => $data['ID'],
  305. 'REMARK' => 'From Period ' . $data['PERIOD_NUM'],
  306. 'PERIOD_NUM' => $periodNum,
  307. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  308. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  309. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  310. 'SORT' => $key * 10,
  311. 'BONUS_ISSUE' => true,
  312. ]);
  313. }
  314. // 绩效奖金发放
  315. if ($data['BONUS_PB'] > 0) {
  316. UserPerformance::sentUserPerformance($data['USER_ID'], $data['BONUS_PB'], $data['PERIOD_NUM']);
  317. }
  318. // 把记录标记为已发放状态
  319. Period::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $data['PERIOD_NUM']]);
  320. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  321. unset($key, $data);
  322. }
  323. $transaction->commit();
  324. } catch (Exception $e) {
  325. $transaction->rollBack();
  326. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  327. return false;
  328. }
  329. }
  330. return true;
  331. }
  332. /**
  333. * 蓝星奖金(即新的管理奖),更新会员聘级
  334. * @param int $offset
  335. * @return bool
  336. * @throws \yii\db\Exception
  337. */
  338. public function updateEmpLevel(int $offset = 0) {
  339. if ($this->_isCalcMonth) {
  340. $empLv = EmployLevel::getIdConvertLevelSortCache();
  341. $allData = CalcBonusBS::find()
  342. ->yearMonth($this->_calcYearMonth)
  343. ->where(
  344. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  345. [
  346. ':CALC_MONTH' => $this->_calcYearMonth,
  347. ':PERIOD_NUM' =>$this->_periodNum
  348. ]
  349. )
  350. ->orderBy('CREATED_AT DESC')
  351. ->offset($offset)
  352. ->limit($this->_limit)
  353. ->all();
  354. LoggerTool::info($allData);
  355. //@todo 用户级别不变则不更新
  356. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  357. if ($allData) {
  358. $transaction = Yii::$app->db->beginTransaction();
  359. try {
  360. foreach ($allData as $data) {
  361. // 蓝星奖计算的最新聘级
  362. $latestEmpLv = $data['LEVEL_ID']; // 本期计算最新管理级别
  363. $latestEmpLvSort = $empLv[$latestEmpLv]; // 当前蓝星计算的聘级 级别值
  364. if ($defaultEmpLv == $latestEmpLv) {
  365. continue;
  366. }
  367. // 用户存储的最高聘级
  368. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  369. $highestEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  370. $highestEmpLvSort = $empLv[$highestEmpLv]; // 历史最高聘级的 级别值
  371. // 如果当前期的聘级高于用户表的最高聘级,则进行更新
  372. if ($latestEmpLvSort > $highestEmpLvSort) {
  373. User::updateAll(['EMP_LV' => $latestEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  374. User::deleteBaseInfoFromRedis($data['USER_ID']);
  375. }
  376. // 更新最新用户表级别
  377. User::updateAll([
  378. 'LAST_EMP_LV' => $latestEmpLv,
  379. 'LAST_EMP_LV_UPDATED_AT' => time(),
  380. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum
  381. ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  382. User::deleteBaseInfoFromRedis($data['USER_ID']);
  383. unset($data);
  384. }
  385. $transaction->commit();
  386. } catch (Exception $e) {
  387. $transaction->rollBack();
  388. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  389. return false;
  390. }
  391. unset($transaction, $allData, $defaultEmpLv);
  392. return $this->updateEmpLevel($offset + $this->_limit);
  393. }
  394. unset($allData);
  395. // 刷新会员EmpLv为0
  396. User::updateAll([
  397. 'LAST_EMP_LV' => '',
  398. 'LAST_EMP_LV_UPDATED_AT' => time(),
  399. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  400. ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $this->_periodNum]);
  401. User::deleteAllBaseInfoFromRedis();
  402. }
  403. return true;
  404. }
  405. /**
  406. * @return bool
  407. */
  408. public function sentMemberLevel(): bool
  409. {
  410. $transaction = Yii::$app->db->beginTransaction();
  411. try {
  412. $db = Yii::$app->db;
  413. // 刷新所有会员最新EliteLevel和最新EmpLevel为默认等级
  414. User::updateAll(
  415. [
  416. 'LAST_EMP_LV' => EmployLevel::getDefaultLevelId(),
  417. 'LAST_EMP_LV_UPDATED_AT' => time(),
  418. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  419. 'LAST_ELITE_LV' => EliteLevel::getDefaultLevelId(),
  420. 'LAST_ELITE_LV_UPDATED_AT' => time(),
  421. 'LAST_ELITE_LV_UPDATED_PERIOD' => $this->_periodNum,
  422. ]);
  423. // 刷新会员最高EliteLevel和最高EmpLevel(统一数据,更新为默认Elite级别)
  424. User::updateAll(['EMP_LV' => EmployLevel::getDefaultLevelId()], "EMP_LV = '' OR EMP_LV IS NULL");
  425. User::updateAll(['ELITE_LV' => EliteLevel::getDefaultLevelId()], "ELITE_LV = '' OR ELITE_LV IS NULL");
  426. $sql =<<<SQL
  427. UPDATE `AR_USER` `user`
  428. INNER JOIN `AR_CALC_BONUS` `bonus` ON `user`.`ID` = `bonus`.`USER_ID` AND `bonus`.`CALC_MONTH` = :CALC_MONTH AND `bonus`.`PERIOD_NUM` = :PERIOD_NUM
  429. SET
  430. `user`.`EMP_LV` = `bonus`.`HIGHEST_HONOR_LV`,
  431. `user`.`LAST_EMP_LV` = `bonus`.`LAST_EMP_LV`,
  432. `user`.`LAST_EMP_LV_UPDATED_AT` = :UPDATED_AT,
  433. `user`.`LAST_EMP_LV_UPDATED_PERIOD` = :PERIOD_NUM,
  434. `user`.`ELITE_LV` = `bonus`.`HIGHEST_ELITE_LV`,
  435. `user`.`LAST_ELITE_LV` = `bonus`.`LAST_ELITE_LV`,
  436. `user`.`LAST_ELITE_LV_UPDATED_AT` = :UPDATED_AT,
  437. `user`.`LAST_ELITE_LV_UPDATED_PERIOD` = :PERIOD_NUM
  438. WHERE
  439. `bonus`.`PERIOD_NUM` = :PERIOD_NUM
  440. SQL;
  441. $db->createCommand($sql)
  442. ->bindValues(
  443. [
  444. ':CALC_MONTH' => $this->_calcYearMonth,
  445. ':PERIOD_NUM' => $this->_periodNum,
  446. ':UPDATED_AT' => time(),
  447. ])
  448. ->execute();
  449. $transaction->commit();
  450. // 刷新本期无Elite的用户级别
  451. // 删除缓存中的会员信息
  452. User::deleteAllBaseInfoFromRedis();
  453. } catch (Exception $e) {
  454. $transaction->rollBack();
  455. $this->addError('sendLevelFailed', '发放会员级别失败,原因:' . $e->getMessage());
  456. return false;
  457. }
  458. return true;
  459. }
  460. // 更活跃会员,将is_send改成1
  461. public function updateActiveUser() {
  462. $ret = PerfActiveUser::updateAll(
  463. ['IS_SENT' => 1],
  464. 'PERIOD_NUM=:PERIOD_NUM AND IS_SENT=:IS_SENT',
  465. ['IS_SENT'=>0, 'PERIOD_NUM'=>$this->_periodNum]
  466. );
  467. return $ret;
  468. }
  469. /**
  470. * 更新会员的累计业绩
  471. * @param int $offset
  472. * @return bool
  473. * @throws \yii\db\Exception
  474. */
  475. public function updateUserPerf(int $offset = 0) {
  476. $allData = PerfPeriod::find()
  477. ->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  478. if ($allData) {
  479. $transaction = Yii::$app->db->beginTransaction();
  480. try {
  481. foreach ($allData as $data) {
  482. $isUpdate = false;
  483. if (UserPerf::find()
  484. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  485. // 判断本期是否已经更新过业绩
  486. if (!UserPerfUpdate::find()
  487. ->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
  488. $isUpdate = true;
  489. // 更新业绩
  490. UserPerf::updateAll([
  491. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  492. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  493. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  494. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  495. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  496. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  497. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  498. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  499. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  500. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  501. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  502. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  503. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  504. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  505. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  506. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  507. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  508. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  509. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  510. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  511. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  512. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  513. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  514. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  515. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  516. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  517. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  518. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  519. }
  520. } else {
  521. $isUpdate = true;
  522. UserPerf::insertOne([
  523. 'USER_ID' => $data['USER_ID'],
  524. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  525. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  526. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  527. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  528. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  529. 'PV_PSS' => $data['PV_PSS'],
  530. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  531. 'PV_1L' => $data['PV_1L'],
  532. 'PV_2L' => $data['PV_2L'],
  533. 'PV_3L' => $data['PV_3L'],
  534. 'PV_4L' => $data['PV_4L'],
  535. 'PV_5L' => $data['PV_5L'],
  536. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  537. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  538. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  539. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  540. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  541. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  542. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  543. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  544. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  545. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  546. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  547. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  548. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  549. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  550. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  551. 'CREATED_AT' => Date::nowTime(),
  552. ]);
  553. }
  554. if ($isUpdate) {
  555. // 变为已更新
  556. 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()]);
  557. }
  558. unset($data, $isUpdate);
  559. }
  560. $transaction->commit();
  561. } catch (Exception $e) {
  562. $transaction->rollBack();
  563. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  564. return false;
  565. }
  566. unset($allData, $transaction);
  567. return $this->updateUserPerf($offset + $this->_limit);
  568. }
  569. unset($allData);
  570. return true;
  571. }
  572. /**
  573. * 更新会员的月剩余业绩
  574. * @param int $offset
  575. * @return bool
  576. * @throws \yii\db\Exception
  577. */
  578. public function updateUserPerfMonth(int $offset = 0) {
  579. // 月结,如果不是月结点,则直接退出
  580. if (!$this->_isCalcMonth) {
  581. return true;
  582. }
  583. // $allData = PerfMonth::findUseDbCalc()
  584. $allData = PerfMonth::find()
  585. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  586. if ($allData) {
  587. $transaction = Yii::$app->db->beginTransaction();
  588. try {
  589. foreach ($allData as $data) {
  590. $isUpdate = false;
  591. // if (UserPerf::findUseDbCalc()
  592. if (UserPerf::find()
  593. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  594. // 判断本期是否已经更新过业绩
  595. // if (!UserPerfMonthUpdate::findUseDbCalc()
  596. if (!UserPerfMonthUpdate::find()
  597. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  598. $isUpdate = true;
  599. // 更新业绩
  600. UserPerf::updateAll([
  601. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  602. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  603. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  604. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  605. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  606. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  607. }
  608. } else {
  609. $isUpdate = true;
  610. UserPerf::insertOne([
  611. 'USER_ID' => $data['USER_ID'],
  612. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  613. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  614. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  615. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  616. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  617. 'CREATED_AT' => Date::nowTime(),
  618. ]);
  619. }
  620. if ($isUpdate) {
  621. // 变为已更新
  622. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  623. }
  624. unset($data, $isUpdate);
  625. }
  626. $transaction->commit();
  627. } catch (Exception $e) {
  628. $transaction->rollBack();
  629. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  630. return false;
  631. }
  632. unset($allData, $transaction);
  633. return $this->updateUserPerfMonth($offset + $this->_limit);
  634. }
  635. unset($allData);
  636. return true;
  637. }
  638. /**
  639. * 检测复消积分是否过期
  640. * @return bool
  641. * @throws \yii\db\Exception
  642. */
  643. public function checkReconsumePointsExpired(int $offset = 0) {
  644. $periodNum = $this->_periodNum;
  645. //一期为7天,那么365天为52.14即53期
  646. $expiredPeriodNum = $periodNum - 53;
  647. if( $expiredPeriodNum <= 0 ) return true;
  648. //查询需要过期的期数
  649. $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();
  650. if( $allData ) {
  651. $transaction = Yii::$app->db->beginTransaction();
  652. try{
  653. //扣除钱包的复消积分
  654. foreach ($allData as $everyData) {
  655. //过期
  656. UserPeriodPoints::updateAll([
  657. 'REMAINDER_POINTS' => 0,
  658. 'EXPIRED' => 1,
  659. 'EXPIRED_PERIOD' => $periodNum,
  660. 'EXPIRED_AT' => Date::nowTime(),
  661. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  662. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  663. UserBonus::updateAllCounters([
  664. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  665. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  666. unset($everyData);
  667. }
  668. unset($periodNum, $expiredPeriodNum, $allData);
  669. $transaction->commit();
  670. }catch (\Exception $e){
  671. $transaction->rollBack();
  672. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  673. return false;
  674. }
  675. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  676. }
  677. unset($allData);
  678. return true;
  679. }
  680. /**
  681. * 更新会员上次报单级别
  682. * @return bool
  683. */
  684. public function updateUserDevLv() {
  685. $transaction = Yii::$app->dbShop->beginTransaction();
  686. try {
  687. \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();
  688. $transaction->commit();
  689. } catch (Exception $e) {
  690. $transaction->rollBack();
  691. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  692. return false;
  693. }
  694. return true;
  695. }
  696. /**
  697. * 给商城会员增加货款
  698. * @param $userId
  699. * @param $amount
  700. * @param $remark
  701. * @throws Exception
  702. */
  703. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  704. $db = \Yii::$app->dbShop;
  705. $transaction = $db->beginTransaction();
  706. try {
  707. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  708. // 增加流水
  709. $flowInsertData[] = [
  710. 'USER_ID' => $userId,
  711. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  712. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  713. 'ORDER_SN' => null,
  714. 'AMOUNT' => $amount,
  715. 'CREATED_AT' => Date::nowTime(),
  716. 'PERIOD_AT' => $this->_periodNum,
  717. 'IS_INCR' => 1,
  718. 'REMARK' => $remark,
  719. 'PARTITION_DATE' => Date::ociToDate(),
  720. 'WALLET_TYPE' => 'payment_for_goods',
  721. 'FROM_TYPE' => 'incr',
  722. ];
  723. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  724. $transaction->commit();
  725. } catch (Exception $e) {
  726. $transaction->rollBack();
  727. throw new Exception($e->getMessage());
  728. }
  729. }
  730. /**
  731. * 更新百分比并发送
  732. * @param $percent
  733. */
  734. private function _updatePercent($percent) {
  735. // 把数据写入数据库中
  736. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  737. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  738. }
  739. /**
  740. * 更新最高聘级
  741. * @param $user_id
  742. * @return bool
  743. * @throws Exception
  744. */
  745. private function _updateHighestEmpLv($user_id) {
  746. $empLv = Info::getEmpLv($user_id);
  747. $highEmpLv = Info::getHighEmpLv($user_id);
  748. $empLvSort = EmployLevel::getSortById($empLv);
  749. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  750. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  751. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  752. 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]);
  753. }
  754. } else {
  755. $yearHighest = new YearHighestEmpLv();
  756. $yearHighest->USER_ID = $user_id;
  757. $yearHighest->YEAR = $this->_calcYear;
  758. $yearHighest->HIGHEST_EMP_LV = $empLv;
  759. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  760. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  761. $yearHighest->CREATED_AT = Date::nowTime();
  762. if (!$yearHighest->save()) {
  763. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  764. }
  765. }
  766. if ($empLvSort > $empLvHighSort) {
  767. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  768. //发送历史最高聘级短信
  769. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  770. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  771. $realName = Info::getUserRealNameByUserId($user_id);
  772. $empLvDate = Date::convert();
  773. $empLvName = EmployLevel::getNameById($empLv);
  774. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  775. $params = [
  776. 'mobiles' => Info::getUserMobileByUserId($user_id),
  777. 'content' => $content,
  778. ];
  779. SmsApi::instance()->clearError();
  780. SmsApi::instance()->goSend($params);
  781. }
  782. }
  783. return true;
  784. }
  785. return false;
  786. }
  787. /**
  788. * 发送短信
  789. * @param int $offset
  790. * @return bool
  791. * @throws \yii\db\Exception
  792. */
  793. public function sendSmsLoop(int $offset = 0) {
  794. // $allData = UserInfo::findUseDbCalc()
  795. $allData = UserInfo::find()
  796. ->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  797. if ($allData) {
  798. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  799. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  800. //获取剩余月份
  801. $period = Period::instance();
  802. $year = $period->getYear($this->_periodNum);
  803. $monthLeft = Period::getMonthLeft($this->_periodNum);
  804. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  805. $to = Date::yearEnd();
  806. $transaction = Yii::$app->db->beginTransaction();
  807. try {
  808. foreach ($allData as $data) {
  809. $userId = $data['USER_ID'];
  810. //过期续费
  811. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  812. foreach ($smsWallet as $item) {
  813. //1奖金钱包2现金钱包
  814. if ($item == 1) {
  815. //看余额是否充足
  816. if (Balance::getAvailableBalance($userId) < $smsFee){
  817. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  818. continue;
  819. };
  820. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  821. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  822. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  823. break;
  824. } elseif ($item == 2) {
  825. throw new Exception('不存在此方式');
  826. break;
  827. }
  828. }
  829. }
  830. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  831. $realName = Info::getUserRealNameByUserId($userId);
  832. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  833. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  834. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  835. $month = $period->getNowMonth();
  836. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  837. //todo 发短信函数 待测试
  838. $params = [
  839. 'mobiles' => $mobile,
  840. 'content' => $content,
  841. ];
  842. SmsApi::instance()->clearError();
  843. SmsApi::instance()->goSend($params);
  844. }
  845. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  846. }
  847. $transaction->commit();
  848. } catch (Exception $e) {
  849. $transaction->rollBack();
  850. return false;
  851. }
  852. unset($data);
  853. return $this->sendSmsLoop($offset + $this->_limit);
  854. }
  855. unset($allData);
  856. return true;
  857. }
  858. }