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. // //发放兑换积分
  368. // if ($data['EXCHANGE_POINTS'] > 0) {
  369. // Balance::changeUserBonus($data['USER_ID'], 'exchange_points', $data['EXCHANGE_POINTS'], [
  370. // 'CALC_ID' => $data['ID'],
  371. // 'REMARK' => 'From ' . $periodNum . '期',
  372. // 'PERIOD_NUM' => $periodNum,
  373. // 'EXCHANGE_POINTS' => $data['EXCHANGE_POINTS'],
  374. // 'DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_SEND,
  375. // 'BONUS_ISSUE' => true,
  376. // ]);
  377. // }
  378. // 把记录标记为已发放状态
  379. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  380. unset($periodAmount, $key, $data);
  381. }
  382. $transaction->commit();
  383. } catch (Exception $e) {
  384. $transaction->rollBack();
  385. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  386. return false;
  387. }
  388. unset($allData, $transaction);
  389. $page++;
  390. return $this->sendBonusLoop($page);
  391. }
  392. unset($allData);
  393. return true;
  394. }
  395. /**
  396. * 蓝星奖金(即新的管理奖),更新会员聘级
  397. * @param int $offset
  398. * @return bool
  399. * @throws \yii\db\Exception
  400. */
  401. public function updateEmpLevel(int $offset = 0) {
  402. if ($this->_isCalcMonth) {
  403. $empLv = EmployLevel::getIdConvertLevelSortCache();
  404. $allData = CalcBonus::findUseDbCalc()
  405. ->yearMonth($this->_calcYearMonth)
  406. ->where(
  407. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  408. [
  409. ':CALC_MONTH' => $this->_calcYearMonth,
  410. ':PERIOD_NUM' =>$this->_periodNum
  411. ]
  412. )
  413. ->orderBy('CREATED_AT DESC')
  414. ->offset($offset)
  415. ->limit($this->_limit)
  416. ->all();
  417. //@todo 用户级别不变则不更新
  418. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  419. if ($allData) {
  420. $transaction = Yii::$app->db->beginTransaction();
  421. try {
  422. foreach ($allData as $data) {
  423. //@todo 用户级别不变则不更新
  424. if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
  425. $nowBsEmpLv = $data['LAST_EMP_LV']; // 当前蓝星奖计算(即管理奖) 的等级
  426. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  427. $userEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  428. $userEmpLvSort = $empLv[$userEmpLv]; // 历史最高聘级的 级别值
  429. $nowBsEmpLvSort = $empLv[$nowBsEmpLv]; // 当前蓝星计算的聘级 级别值
  430. if ($nowBsEmpLvSort > $userEmpLvSort) {
  431. // 如果当前期的级别值大于历史最高级别,则更新用户表里的最高聘级
  432. User::updateAll(['EMP_LV' => $nowBsEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  433. User::deleteBaseInfoFromRedis($data['USER_ID']);
  434. unset($data);
  435. } else {
  436. continue;
  437. }
  438. }
  439. $transaction->commit();
  440. } catch (Exception $e) {
  441. $transaction->rollBack();
  442. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  443. return false;
  444. }
  445. unset($transaction, $allData, $defaultEmpLv);
  446. return $this->updateEmpLevel($offset + $this->_limit);
  447. }
  448. unset($allData);
  449. }
  450. return true;
  451. }
  452. /**
  453. * 更新用户星级
  454. * @param int $offset
  455. * @return bool
  456. */
  457. public function updateStarLevel(int $offset = 0)
  458. {
  459. $allData = CalcBonusQY::findUseDbCalc()
  460. ->yearMonth($this->_calcYearMonth)
  461. ->where(
  462. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  463. [
  464. ':CALC_MONTH' => $this->_calcYearMonth,
  465. ':PERIOD_NUM' =>$this->_periodNum
  466. ]
  467. )
  468. ->orderBy('CREATED_AT DESC')
  469. ->groupBy('USER_ID')
  470. ->offset($offset)
  471. ->limit($this->_limit)
  472. ->all();
  473. if ($allData) {
  474. $transaction = Yii::$app->db->beginTransaction();
  475. try {
  476. foreach ($allData as $data) {
  477. User::updateAll(['STAR_LV' => $data['LAST_STAR_LV']], 'ID = :USER_ID', [':USER_ID' => $data['USER_ID']]);
  478. User::deleteBaseInfoFromRedis($data['USER_ID']);
  479. unset($data);
  480. }
  481. $transaction->commit();
  482. } catch (Exception $e) {
  483. $transaction->rollBack();
  484. $this->addError('updateStarCrownLevel', '更新星级失败,原因:' . $e->getMessage());
  485. return false;
  486. }
  487. unset($transaction, $allData);
  488. return $this->updateStarLevel($offset + $this->_limit);
  489. }
  490. unset($allData);
  491. return true;
  492. }
  493. // /**
  494. // * 更新会员聘级
  495. // * @param int $offset
  496. // * @return bool
  497. // * @throws \yii\db\Exception
  498. // */
  499. // public function updateEmpLevel(int $offset = 0) {
  500. // if ($this->_isCalcMonth) {
  501. // $allData = PerfMonth::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->all();
  502. // //@todo 用户级别不变则不更新
  503. // $defaultEmpLv = EmployLevel::getDefaultLevelId();
  504. // if ($allData) {
  505. // $transaction = Yii::$app->db->beginTransaction();
  506. // try {
  507. // foreach ($allData as $data) {
  508. // //@todo 用户级别不变则不更新
  509. // if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
  510. // User::updateAll(['EMP_LV' => $data['LAST_EMP_LV']], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  511. // User::deleteBaseInfoFromRedis($data['USER_ID']);
  512. // unset($data);
  513. // }
  514. // $transaction->commit();
  515. // } catch (Exception $e) {
  516. // $transaction->rollBack();
  517. // $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  518. // return false;
  519. // }
  520. // unset($transaction, $allData, $defaultEmpLv);
  521. // return $this->updateEmpLevel($offset + $this->_limit);
  522. // }
  523. // unset($allData);
  524. // }
  525. // return true;
  526. // }
  527. // 更活跃会员,将is_send改成1
  528. public function updateActiveUser() {
  529. try {
  530. $ret = PerfActiveUser::updateAll(
  531. ['IS_SENT' => 1],
  532. 'PERIOD_NUM=:PERIOD_NUM AND IS_SENT=:IS_SENT',
  533. ['IS_SENT'=>0, 'PERIOD_NUM'=>$this->_periodNum]
  534. );
  535. return $ret;
  536. } catch(Exception $e) {
  537. $this->addError('updateActiveUser', '更新活跃会员业绩期处理状态失败,原因:' . $e->getMessage());
  538. return false;
  539. }
  540. }
  541. /**
  542. * 更新会员的累计业绩
  543. * @param int $offset
  544. * @return bool
  545. * @throws \yii\db\Exception
  546. */
  547. public function updateUserPerf(int $offset = 0) {
  548. $allData = PerfPeriod::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  549. if ($allData) {
  550. $transaction = Yii::$app->db->beginTransaction();
  551. try {
  552. foreach ($allData as $data) {
  553. $isUpdate = false;
  554. if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  555. // 判断本期是否已经更新过业绩
  556. 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()) {
  557. $isUpdate = true;
  558. // 更新业绩
  559. UserPerf::updateAll([
  560. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  561. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  562. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  563. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  564. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  565. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  566. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  567. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  568. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  569. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  570. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  571. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  572. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  573. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  574. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  575. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  576. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  577. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  578. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  579. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  580. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  581. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  582. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  583. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  584. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  585. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  586. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  587. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  588. }
  589. } else {
  590. $isUpdate = true;
  591. UserPerf::insertOne([
  592. 'USER_ID' => $data['USER_ID'],
  593. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  594. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  595. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  596. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  597. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  598. 'PV_PSS' => $data['PV_PSS'],
  599. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  600. 'PV_1L' => $data['PV_1L'],
  601. 'PV_2L' => $data['PV_2L'],
  602. 'PV_3L' => $data['PV_3L'],
  603. 'PV_4L' => $data['PV_4L'],
  604. 'PV_5L' => $data['PV_5L'],
  605. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  606. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  607. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  608. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  609. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  610. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  611. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  612. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  613. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  614. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  615. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  616. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  617. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  618. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  619. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  620. 'CREATED_AT' => Date::nowTime(),
  621. ]);
  622. }
  623. if ($isUpdate) {
  624. // 变为已更新
  625. 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()]);
  626. }
  627. unset($data, $isUpdate);
  628. }
  629. $transaction->commit();
  630. } catch (Exception $e) {
  631. $transaction->rollBack();
  632. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  633. return false;
  634. }
  635. unset($allData, $transaction);
  636. return $this->updateUserPerf($offset + $this->_limit);
  637. }
  638. unset($allData);
  639. return true;
  640. }
  641. /**
  642. * 更新会员的月剩余业绩
  643. * @param int $offset
  644. * @return bool
  645. * @throws \yii\db\Exception
  646. */
  647. public function updateUserPerfMonth(int $offset = 0) {
  648. // 月结,如果不是月结点,则直接退出
  649. if (!$this->_isCalcMonth) {
  650. return true;
  651. }
  652. $allData = PerfMonth::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  653. if ($allData) {
  654. $transaction = Yii::$app->db->beginTransaction();
  655. try {
  656. foreach ($allData as $data) {
  657. $isUpdate = false;
  658. if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  659. // 判断本期是否已经更新过业绩
  660. if (!UserPerfMonthUpdate::findUseDbCalc()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  661. $isUpdate = true;
  662. // 更新业绩
  663. UserPerf::updateAll([
  664. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  665. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  666. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  667. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  668. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  669. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  670. }
  671. } else {
  672. $isUpdate = true;
  673. UserPerf::insertOne([
  674. 'USER_ID' => $data['USER_ID'],
  675. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  676. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  677. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  678. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  679. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  680. 'CREATED_AT' => Date::nowTime(),
  681. ]);
  682. }
  683. if ($isUpdate) {
  684. // 变为已更新
  685. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  686. }
  687. unset($data, $isUpdate);
  688. }
  689. $transaction->commit();
  690. } catch (Exception $e) {
  691. $transaction->rollBack();
  692. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  693. return false;
  694. }
  695. unset($allData, $transaction);
  696. return $this->updateUserPerfMonth($offset + $this->_limit);
  697. }
  698. unset($allData);
  699. return true;
  700. }
  701. /**
  702. * 检测复消积分是否过期
  703. * @return bool
  704. * @throws \yii\db\Exception
  705. */
  706. public function checkReconsumePointsExpired(int $offset = 0) {
  707. $periodNum = $this->_periodNum;
  708. //一期为7天,那么365天为52.14即53期
  709. $expiredPeriodNum = $periodNum - 53;
  710. if( $expiredPeriodNum <= 0 ) return true;
  711. //查询需要过期的期数
  712. $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();
  713. if( $allData ) {
  714. $transaction = Yii::$app->db->beginTransaction();
  715. try{
  716. //扣除钱包的复消积分
  717. foreach ($allData as $everyData) {
  718. //过期
  719. UserPeriodPoints::updateAll([
  720. 'REMAINDER_POINTS' => 0,
  721. 'EXPIRED' => 1,
  722. 'EXPIRED_PERIOD' => $periodNum,
  723. 'EXPIRED_AT' => Date::nowTime(),
  724. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  725. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  726. UserBonus::updateAllCounters([
  727. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  728. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  729. unset($everyData);
  730. }
  731. unset($periodNum, $expiredPeriodNum, $allData);
  732. $transaction->commit();
  733. }catch (\Exception $e){
  734. $transaction->rollBack();
  735. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  736. return false;
  737. }
  738. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  739. }
  740. unset($allData);
  741. return true;
  742. }
  743. /**
  744. * 更新会员上次报单级别
  745. * @return bool
  746. */
  747. public function updateUserDevLv() {
  748. $transaction = Yii::$app->dbShop->beginTransaction();
  749. try {
  750. \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();
  751. $transaction->commit();
  752. } catch (Exception $e) {
  753. $transaction->rollBack();
  754. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  755. return false;
  756. }
  757. return true;
  758. }
  759. /**
  760. * 给商城会员增加货款
  761. * @param $userId
  762. * @param $amount
  763. * @param $remark
  764. * @throws Exception
  765. */
  766. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  767. $db = \Yii::$app->dbShop;
  768. $transaction = $db->beginTransaction();
  769. try {
  770. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  771. // 增加流水
  772. $flowInsertData[] = [
  773. 'USER_ID' => $userId,
  774. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  775. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  776. 'ORDER_SN' => null,
  777. 'AMOUNT' => $amount,
  778. 'CREATED_AT' => Date::nowTime(),
  779. 'PERIOD_AT' => $this->_periodNum,
  780. 'IS_INCR' => 1,
  781. 'REMARK' => $remark,
  782. 'PARTITION_DATE' => Date::ociToDate(),
  783. 'WALLET_TYPE' => 'payment_for_goods',
  784. 'FROM_TYPE' => 'incr',
  785. ];
  786. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  787. $transaction->commit();
  788. } catch (Exception $e) {
  789. $transaction->rollBack();
  790. throw new Exception($e->getMessage());
  791. }
  792. }
  793. /**
  794. * 更新百分比并发送
  795. * @param $percent
  796. */
  797. private function _updatePercent($percent) {
  798. // 把数据写入数据库中
  799. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  800. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  801. }
  802. /**
  803. * 更新最高聘级
  804. * @param $user_id
  805. * @return bool
  806. * @throws Exception
  807. */
  808. private function _updateHighestEmpLv($user_id) {
  809. $empLv = Info::getEmpLv($user_id);
  810. $highEmpLv = Info::getHighEmpLv($user_id);
  811. $empLvSort = EmployLevel::getSortById($empLv);
  812. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  813. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  814. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  815. 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]);
  816. }
  817. } else {
  818. $yearHighest = new YearHighestEmpLv();
  819. $yearHighest->USER_ID = $user_id;
  820. $yearHighest->YEAR = $this->_calcYear;
  821. $yearHighest->HIGHEST_EMP_LV = $empLv;
  822. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  823. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  824. $yearHighest->CREATED_AT = Date::nowTime();
  825. if (!$yearHighest->save()) {
  826. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  827. }
  828. }
  829. if ($empLvSort > $empLvHighSort) {
  830. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  831. //发送历史最高聘级短信
  832. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  833. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  834. $realName = Info::getUserRealNameByUserId($user_id);
  835. $empLvDate = Date::convert();
  836. $empLvName = EmployLevel::getNameById($empLv);
  837. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  838. $params = [
  839. 'mobiles' => Info::getUserMobileByUserId($user_id),
  840. 'content' => $content,
  841. ];
  842. SmsApi::instance()->clearError();
  843. SmsApi::instance()->goSend($params);
  844. }
  845. }
  846. return true;
  847. }
  848. return false;
  849. }
  850. /**
  851. * 点位合作奖金
  852. * @param $userId
  853. * @param $amount
  854. * @param null $type
  855. * @return bool
  856. * @throws Exception
  857. * @throws \yii\db\Exception
  858. */
  859. private function _teamworkBonus($userId, $amount, $key) {
  860. 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;
  861. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  862. foreach ($teamwork as $value) {
  863. $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
  864. if ($bonus <= 0) continue;
  865. $toUserInfo = CalcCache::getUserInfo($value['USER_ID'], $this->_periodNum);
  866. 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'] . '%']);
  867. 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'] . '%']);
  868. }
  869. }
  870. /**
  871. * 发送短信
  872. * @param int $offset
  873. * @return bool
  874. * @throws \yii\db\Exception
  875. */
  876. public function sendSmsLoop(int $offset = 0) {
  877. $allData = UserInfo::findUseDbCalc()->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  878. if ($allData) {
  879. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  880. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  881. //获取剩余月份
  882. $period = Period::instance();
  883. $year = $period->getYear($this->_periodNum);
  884. $monthLeft = Period::getMonthLeft($this->_periodNum);
  885. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  886. $to = Date::yearEnd();
  887. $transaction = Yii::$app->db->beginTransaction();
  888. try {
  889. foreach ($allData as $data) {
  890. $userId = $data['USER_ID'];
  891. //过期续费
  892. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  893. foreach ($smsWallet as $item) {
  894. //1奖金钱包2现金钱包
  895. if ($item == 1) {
  896. //看余额是否充足
  897. if (Balance::getAvailableBalance($userId) < $smsFee){
  898. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  899. continue;
  900. };
  901. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  902. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  903. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  904. break;
  905. } elseif ($item == 2) {
  906. throw new Exception('不存在此方式');
  907. break;
  908. }
  909. }
  910. }
  911. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  912. $realName = Info::getUserRealNameByUserId($userId);
  913. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  914. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  915. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  916. $month = $period->getNowMonth();
  917. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  918. //todo 发短信函数 待测试
  919. $params = [
  920. 'mobiles' => $mobile,
  921. 'content' => $content,
  922. ];
  923. SmsApi::instance()->clearError();
  924. SmsApi::instance()->goSend($params);
  925. }
  926. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  927. }
  928. $transaction->commit();
  929. } catch (Exception $e) {
  930. $transaction->rollBack();
  931. return false;
  932. }
  933. unset($data);
  934. return $this->sendSmsLoop($offset + $this->_limit);
  935. }
  936. unset($allData);
  937. return true;
  938. }
  939. }