BonusSend.php 42 KB

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