BonusSend.php 41 KB

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