BonusSend.php 45 KB

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