BonusSend.php 38 KB

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