BonusSend.php 39 KB

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