BonusSend.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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\LoggerTool;
  13. use common\helpers\Tool;
  14. use common\helpers\user\Balance;
  15. use common\helpers\user\Info;
  16. use common\helpers\user\Reconsume;
  17. use common\libs\api\sms\SmsApi;
  18. use common\models\DealType;
  19. use common\models\FlowRemainPv;
  20. use common\models\PerfPeriod;
  21. use common\models\EmployLevel;
  22. use common\models\UserBonus;
  23. use common\models\UserPerfMonthUpdate;
  24. use common\models\UserPerformance;
  25. use common\models\UserPeriodPoints;
  26. use common\models\UserInfo;
  27. use common\models\UserPerf;
  28. use common\models\UserPerfUpdate;
  29. use common\models\UserTeamwork;
  30. use common\models\YearHighestEmpLv;
  31. use common\models\Order;
  32. use common\models\RemainPv;
  33. use yii\base\BaseObject;
  34. use yii\base\StaticInstanceTrait;
  35. use common\helpers\Cache;
  36. use common\helpers\Date;
  37. use common\models\CalcBonus;
  38. use common\models\CalcBonusBS;
  39. use common\models\CalcBonusQY;
  40. use common\models\PerfActiveUser;
  41. use common\models\PerfMonth;
  42. use common\models\User;
  43. use Yii;
  44. use common\models\Period;
  45. use yii\base\Exception;
  46. use yii\db\Expression;
  47. class BonusSend extends BaseObject {
  48. use StaticInstanceTrait;
  49. private $_limit = 1000;
  50. private $_appUserId = null;
  51. private $_sysConfig = [];
  52. private $_decLevelConfig = [];
  53. private $_empLevelConfig = [];
  54. private $_decRoleConfig = [];
  55. private $_errors = [];
  56. private $_periodNum = 0;
  57. private $_periodId;
  58. private $_isCalcMonth = 0;
  59. private $_isCalcYear = 0;
  60. private $_calcYear;
  61. private $_calcMonth;
  62. private $_calcYearMonth;
  63. private $_lastCalcYear;
  64. private $_lastCalcMonth;
  65. private $_lastCalcYearMonth;
  66. private $_workerId;
  67. private $_workerNum;
  68. public function init(int $periodNum = 0, $appUserId = null, $workerId = null, $workerNum = null) {
  69. parent::init();
  70. $this->_sysConfig = Cache::getSystemConfig();
  71. $this->_decLevelConfig = Cache::getDecLevelConfig();
  72. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  73. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  74. $this->_periodNum = $periodNum;
  75. $this->_appUserId = $appUserId;
  76. $this->_workerId = $workerId;
  77. $this->_workerNum = $workerNum;
  78. }
  79. /**
  80. * 设置期数
  81. * @param int $periodNum
  82. * @return int
  83. */
  84. public function setPeriodNum(int $periodNum) {
  85. return $this->_periodNum = $periodNum;
  86. }
  87. /**
  88. * 获取期数
  89. * @return int
  90. */
  91. public function getPeriodNum() {
  92. return $this->_periodNum;
  93. }
  94. /**
  95. * 加入错误错误
  96. * @param $attr
  97. * @param $error
  98. */
  99. public function addError($attr, $error) {
  100. $this->_errors[$attr][] = $error;
  101. }
  102. /**
  103. * 获取错误信息
  104. * @return array
  105. */
  106. public function getErrors() {
  107. return $this->_errors;
  108. }
  109. /**
  110. * 挂网时处理虚假订单
  111. *
  112. */
  113. public function putFakeOrder() {
  114. echo('开始处理-假订单' . PHP_EOL);
  115. $sysConfig = Cache::getSystemConfig();
  116. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  117. $fakeOrder= Order::find()->where(['PERIOD_NUM'=>$this->_periodNum, 'IS_AUTO'=>'1'])->asArray()->all();
  118. foreach($fakeOrder as $fOrder){
  119. $oRemainPv=RemainPv::findOne(["USER_ID"=>$fOrder['USER_ID']]);
  120. $transactionRemain = \Yii::$app->db->beginTransaction();
  121. try{
  122. $fakeOrderPv = $oRemainPv->REMAIN_PV>=$mesureUpCondition?$mesureUpCondition:$oRemainPv->REMAIN_PV;
  123. $flowRemainPvModel = new FlowRemainPv();
  124. $flowRemainPvModel->ID = $this->_generateSn();
  125. $flowRemainPvModel->USER_ID = $fOrder['USER_ID'];
  126. $flowRemainPvModel->REMAIN_PV_FLOW = 0 - $fakeOrderPv;
  127. $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv->REMAIN_PV - $fakeOrderPv;
  128. $flowRemainPvModel->PERIOD_NUM = $this->_periodNum;
  129. $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  130. $flowRemainPvModel->ORDER_SN = $fOrder['SN'];
  131. if(!$flowRemainPvModel->save()){
  132. $this->addErrors($flowRemainPvModel->getErrors());
  133. return false;
  134. }
  135. $oRemainPv->updateCounters(['REMAIN_PV'=>0-$fakeOrderPv]);
  136. $transactionRemain->commit();
  137. } catch (Exception $e) {
  138. $transactionRemain->rollBack();
  139. $this->addError('add', $e->getMessage());
  140. return null;
  141. }
  142. }
  143. echo('假订单处理完' . PHP_EOL);
  144. return true; // $flowRemainPvModel;
  145. }
  146. /**
  147. * 生成流水号
  148. * @return string
  149. */
  150. private function _generateSn() {
  151. return Date::today('Ymd') . $this->_random(10, 1);
  152. }
  153. /**
  154. * 生成随机数
  155. * @param $length
  156. * @param int $numeric
  157. * @return string
  158. */
  159. private function _random($length, $numeric = 0) {
  160. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  161. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  162. $hash = '';
  163. $max = strlen($seed) - 1;
  164. for ($i = 0; $i < $length; $i++) {
  165. $hash .= $seed[mt_rand(0, $max)];
  166. }
  167. return $hash;
  168. }
  169. /**
  170. * 进行奖金发放步骤
  171. * @return bool
  172. */
  173. public function sendStep() {
  174. try {
  175. $t1 = microtime(true);
  176. // 初始化
  177. $this->initTask();
  178. echo('挂网开始');
  179. // 改变状态
  180. $this->setSendStatus('start');
  181. // 发放荣衔级别(Honor/Emp)、Elite级别
  182. $this->sendMemberLevel();
  183. $this->_updatePercent(30);
  184. $t2 = microtime(true);
  185. echo('更新会员级别完成,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  186. // 发放奖金
  187. $this->sendBonusLoop();
  188. $this->_updatePercent(80);
  189. $t3 = microtime(true);
  190. echo('发放奖金完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  191. echo('全部奖金发放完成,耗时:'.round($t3 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
  192. $this->_updatePercent(100);
  193. } catch (\Exception $e) {
  194. LoggerTool::error('sendBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
  195. $this->addError('sendBonus', sprintf('%s',$e->getMessage()));
  196. return false;
  197. }
  198. if (count($this->_errors) > 0) {
  199. return false;
  200. }
  201. return true;
  202. }
  203. /**
  204. * 需要多进程执行的任务
  205. * @param $workId
  206. * @throws \yii\db\Exception
  207. */
  208. public function processStep($workId = null) {
  209. if ($workId == 1 || $workId === null) {
  210. // 发放奖金
  211. $this->sendBonusLoop();
  212. }
  213. if ($workId == 2 || $workId === null) {
  214. // 更新聘级
  215. $this->updateEmpLevel();
  216. }
  217. if ($workId == 3 || $workId === null) {
  218. // 更新会员累计业绩
  219. $this->updateUserPerf();
  220. }
  221. Yii::$app->db->close();
  222. Yii::$app->dbShop->close();
  223. }
  224. /**
  225. * 初始化发放任务
  226. * @throws Exception
  227. */
  228. public function initTask() {
  229. $this->_errors = [];
  230. $periodNum = $this->_periodNum;
  231. // 获取传入期数的相关信息
  232. $periodObj = Period::instance();
  233. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  234. $this->_periodId = $periodDataArr['ID'];
  235. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  236. $this->_calcYear = $periodObj->getYear($periodNum);
  237. $this->_calcMonth = $periodObj->getMonth($periodNum);
  238. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  239. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  240. $this->_lastCalcYear = $lastYearMonthArr['year'];
  241. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  242. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  243. }
  244. /**
  245. * 设置结算状态
  246. * @param $type
  247. * start|end|fail
  248. */
  249. public function setSendStatus($type) {
  250. Yii::$app->db->close();
  251. if ($type == 'start') {
  252. Period::updateAll(['IS_SENDING' => 1, 'SEND_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  253. } elseif ($type == 'end') {
  254. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FINISH, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  255. } elseif ($type == 'fail') {
  256. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FAIL, 'SENT_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  257. }
  258. }
  259. /**
  260. * 结束计算任务
  261. * @throws \yii\db\Exception
  262. */
  263. public function endTask() {
  264. CalcCache::clearAll($this->_periodNum);
  265. $this->setSendStatus('end');
  266. //@todo 先不备份数据
  267. // DataBak::backup($this->_periodNum);
  268. //发送复销短信
  269. // if ($this->_isCalcMonth && $this->_sysConfig['smsOpen']['VALUE']) {
  270. // $this->sendSmsLoop();
  271. // }
  272. }
  273. /**
  274. * 出现错误
  275. */
  276. public function errorTask() {
  277. $this->setSendStatus('fail');
  278. }
  279. /**
  280. * 发放奖金
  281. * @param int $page
  282. * @return bool
  283. * @throws \yii\db\Exception
  284. */
  285. public function sendBonusLoop($page = 1) {
  286. echo sprintf("时间:[%s]数据库发奖,当前page为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $page);
  287. $periodNum = $this->_periodNum;
  288. // 从奖金结算表中获取当期未发放的所有数据
  289. $allData = CalcBonus::find()
  290. ->yearMonth($this->_calcYearMonth)
  291. ->select('ID, USER_ID, BONUS_REAL, BONUS_TOTAL, MANAGE_TAX, ')
  292. ->where('(IS_SENT=0 OR IS_SENT=2) AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  293. [':CALC_MONTH' => $this->_calcYearMonth, ':PERIOD_NUM' => $this->_periodNum]
  294. )
  295. ->limit($this->_limit)
  296. ->asArray()
  297. ->all();
  298. if ($allData) {
  299. $transaction = Yii::$app->db->beginTransaction();
  300. try {
  301. foreach ($allData as $key => $data) {
  302. // 用户奖金发放
  303. if ($data['BONUS_REAL'] > 0) {
  304. Balance::changeUserBonus($data['USER_ID'], 'userBonus', $data['BONUS_REAL'],
  305. [
  306. 'CALC_ID' => $data['ID'],
  307. 'REMARK' => 'From Period ' . $data['PERIOD_NUM'],
  308. 'PERIOD_NUM' => $periodNum,
  309. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  310. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  311. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  312. 'SORT' => $key * 10,
  313. 'BONUS_ISSUE' => true,
  314. ]);
  315. }
  316. // 绩效奖金发放
  317. if ($data['BONUS_PB'] > 0) {
  318. UserPerformance::sentUserPerformance($data['USER_ID'], $data['BONUS_PB'], $data['PERIOD_NUM']);
  319. }
  320. // 把记录标记为已发放状态
  321. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  322. unset($periodAmount, $key, $data);
  323. }
  324. $transaction->commit();
  325. } catch (Exception $e) {
  326. $transaction->rollBack();
  327. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  328. return false;
  329. }
  330. unset($allData, $transaction);
  331. $page++;
  332. return $this->sendBonusLoop($page);
  333. }
  334. unset($allData);
  335. return true;
  336. }
  337. /**
  338. * 蓝星奖金(即新的管理奖),更新会员聘级
  339. * @param int $offset
  340. * @return bool
  341. * @throws \yii\db\Exception
  342. */
  343. public function updateEmpLevel(int $offset = 0) {
  344. if ($this->_isCalcMonth) {
  345. $empLv = EmployLevel::getIdConvertLevelSortCache();
  346. $allData = CalcBonusBS::find()
  347. ->yearMonth($this->_calcYearMonth)
  348. ->where(
  349. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  350. [
  351. ':CALC_MONTH' => $this->_calcYearMonth,
  352. ':PERIOD_NUM' =>$this->_periodNum
  353. ]
  354. )
  355. ->orderBy('CREATED_AT DESC')
  356. ->offset($offset)
  357. ->limit($this->_limit)
  358. ->all();
  359. LoggerTool::info($allData);
  360. //@todo 用户级别不变则不更新
  361. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  362. if ($allData) {
  363. $transaction = Yii::$app->db->beginTransaction();
  364. try {
  365. foreach ($allData as $data) {
  366. // 蓝星奖计算的最新聘级
  367. $latestEmpLv = $data['LEVEL_ID']; // 本期计算最新管理级别
  368. $latestEmpLvSort = $empLv[$latestEmpLv]; // 当前蓝星计算的聘级 级别值
  369. if ($defaultEmpLv == $latestEmpLv) {
  370. continue;
  371. }
  372. // 用户存储的最高聘级
  373. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  374. $highestEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  375. $highestEmpLvSort = $empLv[$highestEmpLv]; // 历史最高聘级的 级别值
  376. // 如果当前期的聘级高于用户表的最高聘级,则进行更新
  377. if ($latestEmpLvSort > $highestEmpLvSort) {
  378. User::updateAll(['EMP_LV' => $latestEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  379. User::deleteBaseInfoFromRedis($data['USER_ID']);
  380. }
  381. // 更新最新用户表级别
  382. User::updateAll([
  383. 'LAST_EMP_LV' => $latestEmpLv,
  384. 'LAST_EMP_LV_UPDATED_AT' => time(),
  385. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum
  386. ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  387. User::deleteBaseInfoFromRedis($data['USER_ID']);
  388. unset($data);
  389. }
  390. $transaction->commit();
  391. } catch (Exception $e) {
  392. $transaction->rollBack();
  393. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  394. return false;
  395. }
  396. unset($transaction, $allData, $defaultEmpLv);
  397. return $this->updateEmpLevel($offset + $this->_limit);
  398. }
  399. unset($allData);
  400. // 刷新会员EmpLv为0
  401. User::updateAll([
  402. 'LAST_EMP_LV' => '',
  403. 'LAST_EMP_LV_UPDATED_AT' => time(),
  404. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  405. ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $this->_periodNum]);
  406. User::deleteAllBaseInfoFromRedis();
  407. }
  408. return true;
  409. }
  410. public function sendMemberLevel()
  411. {
  412. $transaction = Yii::$app->db->beginTransaction();
  413. try {
  414. $db = Yii::$app->db;
  415. $sql =<<<SQL
  416. UPDATE `AR_USER` `user`
  417. INNER JOIN `AR_CALC_BONUS` `bonus` ON `user`.`ID` = `bonus`.`USER_ID` AND `bonus`.`CALC_MONTH` = :CALC_MONTH AND `bonus`.`PERIOD_NUM` = :PERIOD_NUM
  418. SET
  419. `user`.`EMP_LV` = `bonus`.`EMP_LV`,
  420. `user`.`LAST_EMP_LV` = `bonus`.`LAST_EMP_LV`,
  421. `user`.`LAST_EMP_LV_UPDATED_AT` = :UPDATED_AT,
  422. `user`.`LAST_EMP_LV_UPDATED_PERIOD` = :PERIOD_NUM,
  423. `user`.`ELITE_LV` = `bonus`.`ELITE_LV`,
  424. `user`.`LAST_ELITE_LV` = `bonus`.`LAST_ELITE_LV`,
  425. `user`.`LAST_ELITE_LV_UPDATED_AT` = :UPDATED_AT,
  426. `user`.`LAST_ELITE_LV_UPDATED_PERIOD` = :PERIOD_NUM
  427. SQL;
  428. $db->createCommand($sql)
  429. ->bindValues(
  430. [
  431. ':CALC_MONTH' => $this->_calcYearMonth,
  432. ':PERIOD_NUM' => $this->_periodNum,
  433. ':UPDATED_AT' => time(),
  434. ])
  435. ->execute();
  436. $transaction->commit();
  437. // 删除缓存中的会员信息
  438. User::deleteAllBaseInfoFromRedis();
  439. } catch (Exception $e) {
  440. $transaction->rollBack();
  441. $this->addError('sendLevelFailed', '发放会员级别失败,原因:' . $e->getMessage());
  442. return false;
  443. }
  444. return true;
  445. }
  446. // 更活跃会员,将is_send改成1
  447. public function updateActiveUser() {
  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. }
  455. /**
  456. * 更新会员的累计业绩
  457. * @param int $offset
  458. * @return bool
  459. * @throws \yii\db\Exception
  460. */
  461. public function updateUserPerf(int $offset = 0) {
  462. $allData = PerfPeriod::find()
  463. ->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  464. if ($allData) {
  465. $transaction = Yii::$app->db->beginTransaction();
  466. try {
  467. foreach ($allData as $data) {
  468. $isUpdate = false;
  469. if (UserPerf::find()
  470. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  471. // 判断本期是否已经更新过业绩
  472. if (!UserPerfUpdate::find()
  473. ->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
  474. $isUpdate = true;
  475. // 更新业绩
  476. UserPerf::updateAll([
  477. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  478. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  479. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  480. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  481. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  482. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  483. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  484. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  485. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  486. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  487. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  488. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  489. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  490. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  491. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  492. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  493. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  494. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  495. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  496. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  497. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  498. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  499. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  500. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  501. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  502. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  503. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  504. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  505. }
  506. } else {
  507. $isUpdate = true;
  508. UserPerf::insertOne([
  509. 'USER_ID' => $data['USER_ID'],
  510. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  511. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  512. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  513. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  514. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  515. 'PV_PSS' => $data['PV_PSS'],
  516. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  517. 'PV_1L' => $data['PV_1L'],
  518. 'PV_2L' => $data['PV_2L'],
  519. 'PV_3L' => $data['PV_3L'],
  520. 'PV_4L' => $data['PV_4L'],
  521. 'PV_5L' => $data['PV_5L'],
  522. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  523. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  524. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  525. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  526. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  527. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  528. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  529. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  530. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  531. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  532. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  533. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  534. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  535. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  536. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  537. 'CREATED_AT' => Date::nowTime(),
  538. ]);
  539. }
  540. if ($isUpdate) {
  541. // 变为已更新
  542. 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()]);
  543. }
  544. unset($data, $isUpdate);
  545. }
  546. $transaction->commit();
  547. } catch (Exception $e) {
  548. $transaction->rollBack();
  549. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  550. return false;
  551. }
  552. unset($allData, $transaction);
  553. return $this->updateUserPerf($offset + $this->_limit);
  554. }
  555. unset($allData);
  556. return true;
  557. }
  558. /**
  559. * 更新会员的月剩余业绩
  560. * @param int $offset
  561. * @return bool
  562. * @throws \yii\db\Exception
  563. */
  564. public function updateUserPerfMonth(int $offset = 0) {
  565. // 月结,如果不是月结点,则直接退出
  566. if (!$this->_isCalcMonth) {
  567. return true;
  568. }
  569. // $allData = PerfMonth::findUseDbCalc()
  570. $allData = PerfMonth::find()
  571. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  572. if ($allData) {
  573. $transaction = Yii::$app->db->beginTransaction();
  574. try {
  575. foreach ($allData as $data) {
  576. $isUpdate = false;
  577. // if (UserPerf::findUseDbCalc()
  578. if (UserPerf::find()
  579. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  580. // 判断本期是否已经更新过业绩
  581. // if (!UserPerfMonthUpdate::findUseDbCalc()
  582. if (!UserPerfMonthUpdate::find()
  583. ->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()
  801. $allData = UserInfo::find()
  802. ->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  803. if ($allData) {
  804. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  805. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  806. //获取剩余月份
  807. $period = Period::instance();
  808. $year = $period->getYear($this->_periodNum);
  809. $monthLeft = Period::getMonthLeft($this->_periodNum);
  810. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  811. $to = Date::yearEnd();
  812. $transaction = Yii::$app->db->beginTransaction();
  813. try {
  814. foreach ($allData as $data) {
  815. $userId = $data['USER_ID'];
  816. //过期续费
  817. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  818. foreach ($smsWallet as $item) {
  819. //1奖金钱包2现金钱包
  820. if ($item == 1) {
  821. //看余额是否充足
  822. if (Balance::getAvailableBalance($userId) < $smsFee){
  823. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  824. continue;
  825. };
  826. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  827. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  828. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  829. break;
  830. } elseif ($item == 2) {
  831. throw new Exception('不存在此方式');
  832. break;
  833. }
  834. }
  835. }
  836. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  837. $realName = Info::getUserRealNameByUserId($userId);
  838. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  839. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  840. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  841. $month = $period->getNowMonth();
  842. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  843. //todo 发短信函数 待测试
  844. $params = [
  845. 'mobiles' => $mobile,
  846. 'content' => $content,
  847. ];
  848. SmsApi::instance()->clearError();
  849. SmsApi::instance()->goSend($params);
  850. }
  851. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  852. }
  853. $transaction->commit();
  854. } catch (Exception $e) {
  855. $transaction->rollBack();
  856. return false;
  857. }
  858. unset($data);
  859. return $this->sendSmsLoop($offset + $this->_limit);
  860. }
  861. unset($allData);
  862. return true;
  863. }
  864. }