BonusSend.php 41 KB

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