BonusSend.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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\helpers\user\Status;
  18. use common\libs\api\sms\SmsApi;
  19. use common\libs\swoole\Process;
  20. use common\models\DealType;
  21. use common\models\FlowRemainPv;
  22. use common\models\PerfPeriod;
  23. use common\models\DecOrder;
  24. use common\models\EmployLevel;
  25. use common\models\StarCrownLevel;
  26. use common\models\UserBonus;
  27. use common\models\UserPerfMonthUpdate;
  28. use common\models\UserPeriodPoints;
  29. use common\models\UserWallet;
  30. use common\models\UserInfo;
  31. use common\models\UserPerf;
  32. use common\models\UserPerfUpdate;
  33. use common\models\UserTeamwork;
  34. use common\models\YearHighestEmpLv;
  35. use common\models\Order;
  36. use common\models\RemainPv;
  37. use common\models\forms\OrderForm;
  38. use yii\base\BaseObject;
  39. use yii\base\StaticInstanceTrait;
  40. use common\helpers\Cache;
  41. use common\helpers\Date;
  42. use common\models\CalcBonus;
  43. use common\models\CalcBonusBD;
  44. use common\models\CalcBonusBS;
  45. use common\models\CalcBonusGX;
  46. use common\models\CalcBonusQY;
  47. use common\models\CalcBonusTG;
  48. use common\models\FlowBonus;
  49. use common\models\PerfActiveUser;
  50. use common\models\PerfMonth;
  51. use common\models\User;
  52. use Yii;
  53. use common\models\Period;
  54. use yii\base\Exception;
  55. use yii\db\Expression;
  56. class BonusSend extends BaseObject {
  57. use StaticInstanceTrait;
  58. private $_limit = 1000;
  59. private $_appUserId = null;
  60. private $_sysConfig = [];
  61. private $_decLevelConfig = [];
  62. private $_empLevelConfig = [];
  63. private $_decRoleConfig = [];
  64. private $_errors = [];
  65. private $_periodNum = 0;
  66. private $_periodId;
  67. private $_isCalcMonth = 0;
  68. private $_isCalcYear = 0;
  69. private $_calcYear;
  70. private $_calcMonth;
  71. private $_calcYearMonth;
  72. private $_lastCalcYear;
  73. private $_lastCalcMonth;
  74. private $_lastCalcYearMonth;
  75. private $_workerId;
  76. private $_workerNum;
  77. public function init(int $periodNum = 0, $appUserId = null, $workerId = null, $workerNum = null) {
  78. parent::init();
  79. $this->_sysConfig = Cache::getSystemConfig();
  80. $this->_decLevelConfig = Cache::getDecLevelConfig();
  81. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  82. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  83. $this->_periodNum = $periodNum;
  84. $this->_appUserId = $appUserId;
  85. $this->_workerId = $workerId;
  86. $this->_workerNum = $workerNum;
  87. }
  88. /**
  89. * 设置期数
  90. * @param int $periodNum
  91. * @return int
  92. */
  93. public function setPeriodNum(int $periodNum) {
  94. return $this->_periodNum = $periodNum;
  95. }
  96. /**
  97. * 获取期数
  98. * @return int
  99. */
  100. public function getPeriodNum() {
  101. return $this->_periodNum;
  102. }
  103. /**
  104. * 加入错误错误
  105. * @param $attr
  106. * @param $error
  107. */
  108. public function addError($attr, $error) {
  109. $this->_errors[$attr][] = $error;
  110. }
  111. /**
  112. * 获取错误信息
  113. * @return array
  114. */
  115. public function getErrors() {
  116. return $this->_errors;
  117. }
  118. /**
  119. * 挂网时处理虚假订单
  120. *
  121. */
  122. public function putFakeOrder() {
  123. echo('开始处理-假订单' . PHP_EOL);
  124. $sysConfig = Cache::getSystemConfig();
  125. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  126. $fakeOrder= Order::find()->where(['PERIOD_NUM'=>$this->_periodNum, 'IS_AUTO'=>'1'])->asArray()->all();
  127. foreach($fakeOrder as $fOrder){
  128. $oRemainPv=RemainPv::findOne(["USER_ID"=>$fOrder['USER_ID']]);
  129. $transactionRemain = \Yii::$app->db->beginTransaction();
  130. try{
  131. $fakeOrderPv = $oRemainPv->REMAIN_PV>=$mesureUpCondition?$mesureUpCondition:$oRemainPv->REMAIN_PV;
  132. $flowRemainPvModel = new FlowRemainPv();
  133. $flowRemainPvModel->ID = $this->_generateSn();
  134. $flowRemainPvModel->USER_ID = $fOrder['USER_ID'];
  135. $flowRemainPvModel->REMAIN_PV_FLOW = 0 - $fakeOrderPv;
  136. $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv->REMAIN_PV - $fakeOrderPv;
  137. $flowRemainPvModel->PERIOD_NUM = $this->_periodNum;
  138. $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  139. $flowRemainPvModel->ORDER_SN = $fOrder['SN'];
  140. if(!$flowRemainPvModel->save()){
  141. $this->addErrors($flowRemainPvModel->getErrors());
  142. return false;
  143. }
  144. $oRemainPv->updateCounters(['REMAIN_PV'=>0-$fakeOrderPv]);
  145. $transactionRemain->commit();
  146. } catch (Exception $e) {
  147. $transactionRemain->rollBack();
  148. $this->addError('add', $e->getMessage());
  149. return null;
  150. }
  151. }
  152. echo('假订单处理完' . PHP_EOL);
  153. return true; // $flowRemainPvModel;
  154. }
  155. /**
  156. * 生成流水号
  157. * @return string
  158. */
  159. private function _generateSn() {
  160. return Date::today('Ymd') . $this->_random(10, 1);
  161. }
  162. /**
  163. * 生成随机数
  164. * @param $length
  165. * @param int $numeric
  166. * @return string
  167. */
  168. private function _random($length, $numeric = 0) {
  169. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  170. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  171. $hash = '';
  172. $max = strlen($seed) - 1;
  173. for ($i = 0; $i < $length; $i++) {
  174. $hash .= $seed[mt_rand(0, $max)];
  175. }
  176. return $hash;
  177. }
  178. /**
  179. * 进行奖金发放步骤
  180. * @return bool
  181. */
  182. public function sendStep() {
  183. try {
  184. $t1 = microtime(true);
  185. // 初始化
  186. $this->initTask();
  187. echo('挂网开始');
  188. $this->putFakeOrder();
  189. // 先把有remainPv的订单处理一下,将remainPv加入到remain_pv及流水表
  190. echo('处理当期REMAIN PV ' . date('Y-m-d H:i:s', time()) . PHP_EOL);
  191. $this->_calcRemainPv();
  192. $t2 = microtime(true);
  193. echo('初始化完成,当前期数【' . $this->_periodNum . '】,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  194. // 改变状态
  195. $this->setSendStatus('start');
  196. $t3 = microtime(true);
  197. echo('改变状态完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  198. $this->_updatePercent(20);
  199. //Yii::$app->db->close();
  200. //Yii::$app->dbShop->close();
  201. // 更新StarDirectory
  202. $this->updateEmpLevel();
  203. $this->_updatePercent(40);
  204. $t4 = microtime(true);
  205. echo('更新聘级完成,耗时:' . round($t4 - $t3, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  206. // 更新StarCrown
  207. $this->updateCrownLevel();
  208. $this->_updatePercent(50);
  209. $t41 = microtime(true);
  210. echo('更新星级完成,耗时:' . round($t41 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  211. // 发放奖金
  212. $this->sendBonusLoop();
  213. $this->_updatePercent(60);
  214. $t5 = microtime(true);
  215. echo('发放奖金完成,耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  216. // 更新会员上次报单级别
  217. // $this->updateUserDevLv();
  218. // $this->_updatePercent(80);
  219. $t6 = microtime(true);
  220. // echo('更新会员上次报单级别完成,耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  221. // 更新会员累计业绩
  222. $this->updateUserPerf();
  223. $this->_updatePercent(80);
  224. $t7 = microtime(true);
  225. echo('更新会员累计业绩完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  226. $this->updateUserPerfMonth();
  227. $this->_updatePercent(90);
  228. $t8 = microtime(true);
  229. echo('更新会员累计月业绩完成,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  230. // 更新活跃用户状态,更新为已处理
  231. // $this->updateActiveUser();
  232. // $this->_updatePercent(95);
  233. // $t9 = microtime(true);
  234. // echo('更新会员累计月业绩完成,耗时:' . round($t9 - $t8, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  235. // 开启子进程去完成下面的循环发放和循环改聘级和循环更新累计业绩
  236. /*$process = new Process('sendBonus', 3);
  237. $process->run(function($workId, $pmid){
  238. $this->processStep($workId);
  239. });
  240. while (true){
  241. if($process->isFinish()) break;
  242. }
  243. unset($process);
  244. $this->_updatePercent(90);
  245. $t4 = microtime(true);
  246. echo('所有子进程的任务完成,耗时:'.round($t4 - $t3, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);*/
  247. echo('全部奖金发放完成,耗时:'.round($t7 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
  248. $this->_updatePercent(100);
  249. } catch (\Exception $e) {
  250. LoggerTool::error('sendBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
  251. $this->addError('sendBonus', sprintf('%s',$e->getMessage()));
  252. return false;
  253. }
  254. if (count($this->_errors) > 0) {
  255. return false;
  256. }
  257. return true;
  258. }
  259. /**
  260. * 处理order表中有remain_pv的订单
  261. * 将结果写入到remainPv相关表中
  262. *
  263. */
  264. private function _calcRemainPv(){
  265. $orders = Order::find()->where('PERIOD_NUM=:PERIOD_NUM AND REMAIN_PV>0',[':PERIOD_NUM'=>$this->_periodNum])->asArray()->all();
  266. foreach($orders as $order){
  267. $oRemainPv = RemainPv::find()->where(['USER_ID' => $order['USER_ID']])->one();
  268. $transactionRemain = \Yii::$app->db->beginTransaction();
  269. try{
  270. $flowRemainPvModel = new FlowRemainPv();
  271. $flowRemainPvModel->ID = $this->_generateSn();
  272. $flowRemainPvModel->USER_ID = $order['USER_ID'];
  273. $flowRemainPvModel->REMAIN_PV_FLOW = $order['REMAIN_PV'];
  274. $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv['REMAIN_PV'] + $order['REMAIN_PV'];
  275. $flowRemainPvModel->PERIOD_NUM = $this->_periodNum;
  276. $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  277. $flowRemainPvModel->ORDER_SN = $order['SN'];
  278. if(!$flowRemainPvModel->save()){
  279. $this->addErrors($flowRemainPvModel->getErrors());
  280. return false;
  281. }
  282. $oRemainPv = RemainPv::find()->where(['USER_ID' => $order['USER_ID']])->one();
  283. if($oRemainPv){
  284. $oRemainPv->updateCounters(['REMAIN_PV'=>$order['REMAIN_PV']]);
  285. }else{
  286. $remainPvModel = new RemainPv();
  287. $remainPvModel->ID = $this->_generateSn();
  288. $remainPvModel->USER_ID = $order['USER_ID'];
  289. $remainPvModel->UPDATED_AT = Date::nowTime();
  290. $remainPvModel->REMAIN_PV = $order['REMAIN_PV'];
  291. $remainPvModel->STATUS = 1;
  292. if(!$remainPvModel->save()){
  293. $this->addErrors($remainPvModel->getErrors());
  294. return false;
  295. }
  296. }
  297. $transactionRemain->commit();
  298. } catch (Exception $e) {
  299. $transactionRemain->rollBack();
  300. $this->addError('add', $e->getMessage());
  301. return null;
  302. }
  303. }
  304. return null;
  305. }
  306. /**
  307. * 需要多进程执行的任务
  308. * @param $workId
  309. * @throws \yii\db\Exception
  310. */
  311. public function processStep($workId = null) {
  312. if ($workId == 1 || $workId === null) {
  313. // 发放奖金
  314. $this->sendBonusLoop();
  315. }
  316. if ($workId == 2 || $workId === null) {
  317. // 更新聘级
  318. $this->updateEmpLevel();
  319. }
  320. if ($workId == 3 || $workId === null) {
  321. // 更新会员累计业绩
  322. $this->updateUserPerf();
  323. }
  324. Yii::$app->db->close();
  325. Yii::$app->dbShop->close();
  326. }
  327. /**
  328. * 初始化发放任务
  329. * @throws Exception
  330. */
  331. public function initTask() {
  332. $this->_errors = [];
  333. $periodNum = $this->_periodNum;
  334. // 获取传入期数的相关信息
  335. $periodObj = Period::instance();
  336. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  337. $this->_periodId = $periodDataArr['ID'];
  338. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  339. $this->_calcYear = $periodObj->getYear($periodNum);
  340. $this->_calcMonth = $periodObj->getMonth($periodNum);
  341. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  342. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  343. $this->_lastCalcYear = $lastYearMonthArr['year'];
  344. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  345. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  346. }
  347. /**
  348. * 设置结算状态
  349. * @param $type
  350. * start|end|fail
  351. */
  352. public function setSendStatus($type) {
  353. Yii::$app->db->close();
  354. if ($type == 'start') {
  355. Period::updateAll(['IS_SENDING' => 1, 'SEND_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  356. } elseif ($type == 'end') {
  357. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FINISH, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  358. } elseif ($type == 'fail') {
  359. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FAIL, 'SENT_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  360. }
  361. }
  362. /**
  363. * 结束计算任务
  364. * @throws \yii\db\Exception
  365. */
  366. public function endTask() {
  367. CalcCache::clearAll($this->_periodNum);
  368. $this->setSendStatus('end');
  369. //@todo 先不备份数据
  370. // DataBak::backup($this->_periodNum);
  371. //发送复销短信
  372. // if ($this->_isCalcMonth && $this->_sysConfig['smsOpen']['VALUE']) {
  373. // $this->sendSmsLoop();
  374. // }
  375. }
  376. /**
  377. * 出现错误
  378. */
  379. public function errorTask() {
  380. $this->setSendStatus('fail');
  381. }
  382. /**
  383. * 发放奖金
  384. * @param int $page
  385. * @return bool
  386. * @throws \yii\db\Exception
  387. */
  388. public function sendBonusLoop($page=1) {
  389. echo sprintf("时间:[%s]数据库发奖,当前page为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $page);
  390. $periodNum = $this->_periodNum;
  391. // 从奖金结算表中获取当期未发放的所有数据
  392. // $allData = CalcBonus::findUseDbCalc()
  393. $allData = CalcBonus::find()
  394. ->yearMonth($this->_calcYearMonth)
  395. ->where(
  396. '(IS_SENT=0 OR IS_SENT=2) AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  397. [':CALC_MONTH' => $this->_calcYearMonth, ':PERIOD_NUM' => $periodNum]
  398. )
  399. ->limit($this->_limit)
  400. ->asArray()
  401. ->all();
  402. if ($allData) {
  403. $transaction = Yii::$app->db->beginTransaction();
  404. try {
  405. foreach ($allData as $key => $data) {
  406. // 期奖金
  407. // $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'];
  408. $periodAmount = $data['BONUS_REAL'];
  409. // 获取本期结算的管理员
  410. // $period = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
  411. // $updateAminId = $period['CALC_ADMIN_ID'];
  412. if ($periodAmount > 0) {
  413. Balance::changeUserBonus($data['USER_ID'], 'bonus', $periodAmount, [
  414. 'CALC_ID' => $data['ID'],
  415. 'REMARK' => 'From Period ' . $periodNum,
  416. 'PERIOD_NUM' => $periodNum,
  417. 'QY' => $data['BONUS_QY'],
  418. 'FW' => $data['BONUS_FW'],
  419. 'YC' => $data['BONUS_YC'],
  420. 'VIP' => $data['BONUS_VIP'],
  421. 'BD' => $data['BONUS_BD'],
  422. 'TG' => $data['BONUS_TG'],
  423. 'YJ' => $data['BONUS_YJ'],
  424. 'GX' => $data['BONUS_GX'],
  425. 'GL' => $data['BONUS_GL'],
  426. 'BS' => $data['BONUS_BS'],
  427. 'BS_MNT' => $data['BONUS_BS_MNT'],
  428. 'BS_ABBR' => $data['BONUS_BS_ABBR'],
  429. 'ORI_QY' => $data['ORI_BONUS_QY'],
  430. 'ORI_YC' => $data['ORI_BONUS_YC'],
  431. 'ORI_VIP' => $data['ORI_BONUS_VIP'],
  432. 'ORI_STANDARD' => $data['ORI_BONUS_STANDARD'],
  433. 'ORI_BD' => $data['ORI_BONUS_BD'],
  434. 'ORI_TG' => $data['ORI_BONUS_TG'],
  435. 'ORI_YJ' => $data['ORI_BONUS_YJ'],
  436. 'ORI_GX' => $data['ORI_BONUS_GX'],
  437. 'ORI_GL' => $data['ORI_BONUS_GL'],
  438. 'ORI_BS' => $data['ORI_BONUS_BS'],
  439. 'ORI_BS_MNT' => $data['ORI_BONUS_BS_MNT'],
  440. 'ORI_BS_ABBR' => $data['ORI_BONUS_BS_ABBR'],
  441. 'RECONSUME_POINTS_TOTAL' => $data['RECONSUME_POINTS'],
  442. 'EXCHANGE_POINTS_TOTAL' => $data['EXCHANGE_POINTS'],
  443. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  444. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  445. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  446. 'SORT' => $key * 10,
  447. 'BONUS_ISSUE' => true,
  448. ]);
  449. // $this->_teamworkBonus($data['USER_ID'], $periodAmount, $key);
  450. }
  451. // 旅游奖
  452. if ($data['BONUS_TOURISM'] > 0) {
  453. Balance::changeUserBonus($data['USER_ID'], 'tourism_points', $data['BONUS_TOURISM'], [
  454. 'CALC_ID' => $data['ID'],
  455. 'REMARK' => 'From Period ' . $periodNum,
  456. 'PERIOD_NUM' => $periodNum,
  457. 'TOURISM_POINTS' => $data['BONUS_TOURISM'],
  458. 'DEAL_TYPE_ID' => DealType::TOURISM_SEND,
  459. 'SORT' => $key * 10,
  460. 'BONUS_ISSUE' => true,
  461. ]);
  462. }
  463. // 车奖
  464. if ($data['BONUS_GARAGE'] > 0) {
  465. Balance::changeUserBonus($data['USER_ID'], 'garage_points', $data['BONUS_GARAGE'], [
  466. 'CALC_ID' => $data['ID'],
  467. 'REMARK' => 'From Period ' . $periodNum,
  468. 'PERIOD_NUM' => $periodNum,
  469. 'GARAGE_POINTS' => $data['BONUS_GARAGE'],
  470. 'DEAL_TYPE_ID' => DealType::GARAGE_SEND,
  471. 'SORT' => $key * 10,
  472. 'BONUS_ISSUE' => true,
  473. ]);
  474. }
  475. // 房奖
  476. if ($data['BONUS_VILLA'] > 0) {
  477. Balance::changeUserBonus($data['USER_ID'], 'villa_points', $data['BONUS_VILLA'], [
  478. 'CALC_ID' => $data['ID'],
  479. 'REMARK' => 'From Period ' . $periodNum,
  480. 'PERIOD_NUM' => $periodNum,
  481. 'VILLA_POINTS' => $data['BONUS_VILLA'],
  482. 'DEAL_TYPE_ID' => DealType::VILLA_SEND,
  483. 'SORT' => $key * 10,
  484. 'BONUS_ISSUE' => true,
  485. ]);
  486. }
  487. //发放重消积分
  488. // if ($data['RECONSUME_POINTS'] > 0) {
  489. // Balance::changeUserBonus($data['USER_ID'], 'reconsume_points', $data['RECONSUME_POINTS'], [
  490. // 'CALC_ID' => $data['ID'],
  491. // 'REMARK' => 'From ' . $periodNum . '期',
  492. // 'PERIOD_NUM' => $periodNum,
  493. // 'RECONSUME_POINTS' => $data['RECONSUME_POINTS'],
  494. // 'DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_SEND,
  495. // ]);
  496. // }
  497. //
  498. // //发放兑换积分
  499. // if ($data['EXCHANGE_POINTS'] > 0) {
  500. // Balance::changeUserBonus($data['USER_ID'], 'exchange_points', $data['EXCHANGE_POINTS'], [
  501. // 'CALC_ID' => $data['ID'],
  502. // 'REMARK' => 'From ' . $periodNum . '期',
  503. // 'PERIOD_NUM' => $periodNum,
  504. // 'EXCHANGE_POINTS' => $data['EXCHANGE_POINTS'],
  505. // 'DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_SEND,
  506. // 'BONUS_ISSUE' => true,
  507. // ]);
  508. // }
  509. // 把记录标记为已发放状态
  510. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  511. unset($periodAmount, $key, $data);
  512. }
  513. $transaction->commit();
  514. } catch (Exception $e) {
  515. $transaction->rollBack();
  516. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  517. return false;
  518. }
  519. unset($allData, $transaction);
  520. $page++;
  521. return $this->sendBonusLoop($page);
  522. }
  523. unset($allData);
  524. return true;
  525. }
  526. /**
  527. * 蓝星奖金(即新的管理奖),更新会员聘级
  528. * @param int $offset
  529. * @return bool
  530. * @throws \yii\db\Exception
  531. */
  532. public function updateEmpLevel(int $offset = 0) {
  533. if ($this->_isCalcMonth) {
  534. $empLv = EmployLevel::getIdConvertLevelSortCache();
  535. $allData = CalcBonusBS::find()
  536. ->yearMonth($this->_calcYearMonth)
  537. ->where(
  538. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  539. [
  540. ':CALC_MONTH' => $this->_calcYearMonth,
  541. ':PERIOD_NUM' =>$this->_periodNum
  542. ]
  543. )
  544. ->orderBy('CREATED_AT DESC')
  545. ->offset($offset)
  546. ->limit($this->_limit)
  547. ->all();
  548. LoggerTool::info($allData);
  549. //@todo 用户级别不变则不更新
  550. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  551. if ($allData) {
  552. $transaction = Yii::$app->db->beginTransaction();
  553. try {
  554. foreach ($allData as $data) {
  555. // 蓝星奖计算的最新聘级
  556. $latestEmpLv = $data['LEVEL_ID']; // 本期计算最新管理级别
  557. $latestEmpLvSort = $empLv[$latestEmpLv]; // 当前蓝星计算的聘级 级别值
  558. if ($defaultEmpLv == $latestEmpLv) {
  559. continue;
  560. }
  561. // 用户存储的最高聘级
  562. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  563. $highestEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  564. $highestEmpLvSort = $empLv[$highestEmpLv]; // 历史最高聘级的 级别值
  565. // 如果当前期的聘级高于用户表的最高聘级,则进行更新
  566. if ($latestEmpLvSort > $highestEmpLvSort) {
  567. User::updateAll(['EMP_LV' => $latestEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  568. User::deleteBaseInfoFromRedis($data['USER_ID']);
  569. }
  570. // 更新最新用户表级别
  571. User::updateAll([
  572. 'LAST_EMP_LV' => $latestEmpLv,
  573. 'LAST_EMP_LV_UPDATED_AT' => time(),
  574. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum
  575. ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  576. User::deleteBaseInfoFromRedis($data['USER_ID']);
  577. unset($data);
  578. }
  579. $transaction->commit();
  580. } catch (Exception $e) {
  581. $transaction->rollBack();
  582. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  583. return false;
  584. }
  585. unset($transaction, $allData, $defaultEmpLv);
  586. return $this->updateEmpLevel($offset + $this->_limit);
  587. }
  588. unset($allData);
  589. // 刷新会员EmpLv为0
  590. User::updateAll([
  591. 'LAST_EMP_LV' => '',
  592. 'LAST_EMP_LV_UPDATED_AT' => time(),
  593. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  594. ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $this->_periodNum]);
  595. User::deleteAllBaseInfoFromRedis();
  596. }
  597. return true;
  598. }
  599. /**
  600. * 更新用户星级
  601. * @param int $offset
  602. * @return bool
  603. */
  604. public function updateCrownLevel(int $offset = 0)
  605. {
  606. $starCrownLv = StarCrownLevel::getIdConvertLevelSortCache();
  607. // $allData = CalcBonusQY::findUseDbCalc()
  608. $allData = CalcBonusQY::find()
  609. ->yearMonth($this->_calcYearMonth)
  610. ->where(
  611. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  612. [
  613. ':CALC_MONTH' => $this->_calcYearMonth,
  614. ':PERIOD_NUM' =>$this->_periodNum
  615. ]
  616. )
  617. ->orderBy('CREATED_AT DESC')
  618. ->groupBy('USER_ID')
  619. ->offset($offset)
  620. ->limit($this->_limit)
  621. ->all();
  622. $defaultCrownLv = StarCrownLevel::getDefaultLevelId();
  623. if ($allData) {
  624. $transaction = Yii::$app->db->beginTransaction();
  625. try {
  626. foreach ($allData as $data) {
  627. // 默认级别不更新
  628. if( $data['LAST_CROWN_LV'] === $defaultCrownLv ) continue;
  629. $modernCrownLv = $data['LAST_CROWN_LV']; // 本期计算出的最新级别
  630. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  631. $originCrownLv = $user['CROWN_LV']; // 用户的历史最高crown级别
  632. $originCrownLvSort = $starCrownLv[$originCrownLv]; // 历史最高crown级别值
  633. $modernCrownLvSort = $starCrownLv[$modernCrownLv]; // 当前计算的crown级别值
  634. if ($modernCrownLvSort > $originCrownLvSort) {
  635. $columns = [
  636. 'CROWN_LV' => $data['LAST_CROWN_LV'],
  637. 'LAST_CROWN_LV' => $data['LAST_CROWN_LV'],
  638. 'LAST_CROWN_LV_UPDATED_AT' => time(),
  639. 'LAST_CROWN_LV_UPDATED_PERIOD' => $this->_periodNum,
  640. ];
  641. } else {
  642. $columns = [
  643. 'LAST_CROWN_LV' => $data['LAST_CROWN_LV'],
  644. 'LAST_CROWN_LV_UPDATED_AT' => time(),
  645. 'LAST_CROWN_LV_UPDATED_PERIOD' => $this->_periodNum,
  646. ];
  647. }
  648. User::updateAll($columns, 'ID = :USER_ID', [':USER_ID' => $data['USER_ID']]);
  649. User::deleteBaseInfoFromRedis($data['USER_ID']);
  650. unset($data);
  651. }
  652. $transaction->commit();
  653. } catch (Exception $e) {
  654. $transaction->rollBack();
  655. $this->addError('updateStarCrownLevel', '更新StartCrown失败,原因:' . $e->getMessage());
  656. return false;
  657. }
  658. unset($transaction, $allData);
  659. return $this->updateCrownLevel($offset + $this->_limit);
  660. }
  661. // 刷新会员CrownLv为0
  662. User::updateAll([
  663. 'LAST_CROWN_LV' => '',
  664. 'LAST_CROWN_LV_UPDATED_AT' => time(),
  665. 'LAST_CROWN_LV_UPDATED_PERIOD' => $this->_periodNum,
  666. ], 'LAST_CROWN_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_CROWN_LV <> ""' , [':PERIOD_NUM' => $this->_periodNum]);
  667. User::deleteAllBaseInfoFromRedis();
  668. return true;
  669. }
  670. // /**
  671. // * 更新会员聘级
  672. // * @param int $offset
  673. // * @return bool
  674. // * @throws \yii\db\Exception
  675. // */
  676. // public function updateEmpLevel(int $offset = 0) {
  677. // if ($this->_isCalcMonth) {
  678. // $allData = PerfMonth::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->all();
  679. // //@todo 用户级别不变则不更新
  680. // $defaultEmpLv = EmployLevel::getDefaultLevelId();
  681. // if ($allData) {
  682. // $transaction = Yii::$app->db->beginTransaction();
  683. // try {
  684. // foreach ($allData as $data) {
  685. // //@todo 用户级别不变则不更新
  686. // if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
  687. // User::updateAll(['EMP_LV' => $data['LAST_EMP_LV']], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  688. // User::deleteBaseInfoFromRedis($data['USER_ID']);
  689. // unset($data);
  690. // }
  691. // $transaction->commit();
  692. // } catch (Exception $e) {
  693. // $transaction->rollBack();
  694. // $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  695. // return false;
  696. // }
  697. // unset($transaction, $allData, $defaultEmpLv);
  698. // return $this->updateEmpLevel($offset + $this->_limit);
  699. // }
  700. // unset($allData);
  701. // }
  702. // return true;
  703. // }
  704. // 更活跃会员,将is_send改成1
  705. public function updateActiveUser() {
  706. try {
  707. $ret = PerfActiveUser::updateAll(
  708. ['IS_SENT' => 1],
  709. 'PERIOD_NUM=:PERIOD_NUM AND IS_SENT=:IS_SENT',
  710. ['IS_SENT'=>0, 'PERIOD_NUM'=>$this->_periodNum]
  711. );
  712. return $ret;
  713. } catch(Exception $e) {
  714. $this->addError('updateActiveUser', '更新活跃会员业绩期处理状态失败,原因:' . $e->getMessage());
  715. return false;
  716. }
  717. }
  718. /**
  719. * 更新会员的累计业绩
  720. * @param int $offset
  721. * @return bool
  722. * @throws \yii\db\Exception
  723. */
  724. public function updateUserPerf(int $offset = 0) {
  725. // $allData = PerfPeriod::findUseDbCalc()
  726. $allData = PerfPeriod::find()
  727. ->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  728. if ($allData) {
  729. $transaction = Yii::$app->db->beginTransaction();
  730. try {
  731. foreach ($allData as $data) {
  732. $isUpdate = false;
  733. // if (UserPerf::findUseDbCalc()
  734. if (UserPerf::find()
  735. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  736. // 判断本期是否已经更新过业绩
  737. // if (!UserPerfUpdate::findUseDbCalc()
  738. if (!UserPerfUpdate::find()
  739. ->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
  740. $isUpdate = true;
  741. // 更新业绩
  742. UserPerf::updateAll([
  743. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  744. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  745. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  746. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  747. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  748. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  749. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  750. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  751. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  752. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  753. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  754. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  755. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  756. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  757. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  758. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  759. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  760. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  761. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  762. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  763. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  764. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  765. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  766. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  767. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  768. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  769. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  770. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  771. }
  772. } else {
  773. $isUpdate = true;
  774. UserPerf::insertOne([
  775. 'USER_ID' => $data['USER_ID'],
  776. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  777. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  778. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  779. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  780. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  781. 'PV_PSS' => $data['PV_PSS'],
  782. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  783. 'PV_1L' => $data['PV_1L'],
  784. 'PV_2L' => $data['PV_2L'],
  785. 'PV_3L' => $data['PV_3L'],
  786. 'PV_4L' => $data['PV_4L'],
  787. 'PV_5L' => $data['PV_5L'],
  788. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  789. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  790. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  791. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  792. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  793. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  794. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  795. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  796. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  797. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  798. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  799. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  800. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  801. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  802. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  803. 'CREATED_AT' => Date::nowTime(),
  804. ]);
  805. }
  806. if ($isUpdate) {
  807. // 变为已更新
  808. 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()]);
  809. }
  810. unset($data, $isUpdate);
  811. }
  812. $transaction->commit();
  813. } catch (Exception $e) {
  814. $transaction->rollBack();
  815. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  816. return false;
  817. }
  818. unset($allData, $transaction);
  819. return $this->updateUserPerf($offset + $this->_limit);
  820. }
  821. unset($allData);
  822. return true;
  823. }
  824. /**
  825. * 更新会员的月剩余业绩
  826. * @param int $offset
  827. * @return bool
  828. * @throws \yii\db\Exception
  829. */
  830. public function updateUserPerfMonth(int $offset = 0) {
  831. // 月结,如果不是月结点,则直接退出
  832. if (!$this->_isCalcMonth) {
  833. return true;
  834. }
  835. // $allData = PerfMonth::findUseDbCalc()
  836. $allData = PerfMonth::find()
  837. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  838. if ($allData) {
  839. $transaction = Yii::$app->db->beginTransaction();
  840. try {
  841. foreach ($allData as $data) {
  842. $isUpdate = false;
  843. // if (UserPerf::findUseDbCalc()
  844. if (UserPerf::find()
  845. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  846. // 判断本期是否已经更新过业绩
  847. // if (!UserPerfMonthUpdate::findUseDbCalc()
  848. if (!UserPerfMonthUpdate::find()
  849. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  850. $isUpdate = true;
  851. // 更新业绩
  852. UserPerf::updateAll([
  853. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  854. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  855. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  856. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  857. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  858. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  859. }
  860. } else {
  861. $isUpdate = true;
  862. UserPerf::insertOne([
  863. 'USER_ID' => $data['USER_ID'],
  864. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  865. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  866. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  867. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  868. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  869. 'CREATED_AT' => Date::nowTime(),
  870. ]);
  871. }
  872. if ($isUpdate) {
  873. // 变为已更新
  874. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  875. }
  876. unset($data, $isUpdate);
  877. }
  878. $transaction->commit();
  879. } catch (Exception $e) {
  880. $transaction->rollBack();
  881. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  882. return false;
  883. }
  884. unset($allData, $transaction);
  885. return $this->updateUserPerfMonth($offset + $this->_limit);
  886. }
  887. unset($allData);
  888. return true;
  889. }
  890. /**
  891. * 检测复消积分是否过期
  892. * @return bool
  893. * @throws \yii\db\Exception
  894. */
  895. public function checkReconsumePointsExpired(int $offset = 0) {
  896. $periodNum = $this->_periodNum;
  897. //一期为7天,那么365天为52.14即53期
  898. $expiredPeriodNum = $periodNum - 53;
  899. if( $expiredPeriodNum <= 0 ) return true;
  900. //查询需要过期的期数
  901. $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();
  902. if( $allData ) {
  903. $transaction = Yii::$app->db->beginTransaction();
  904. try{
  905. //扣除钱包的复消积分
  906. foreach ($allData as $everyData) {
  907. //过期
  908. UserPeriodPoints::updateAll([
  909. 'REMAINDER_POINTS' => 0,
  910. 'EXPIRED' => 1,
  911. 'EXPIRED_PERIOD' => $periodNum,
  912. 'EXPIRED_AT' => Date::nowTime(),
  913. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  914. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  915. UserBonus::updateAllCounters([
  916. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  917. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  918. unset($everyData);
  919. }
  920. unset($periodNum, $expiredPeriodNum, $allData);
  921. $transaction->commit();
  922. }catch (\Exception $e){
  923. $transaction->rollBack();
  924. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  925. return false;
  926. }
  927. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  928. }
  929. unset($allData);
  930. return true;
  931. }
  932. /**
  933. * 更新会员上次报单级别
  934. * @return bool
  935. */
  936. public function updateUserDevLv() {
  937. $transaction = Yii::$app->dbShop->beginTransaction();
  938. try {
  939. \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();
  940. $transaction->commit();
  941. } catch (Exception $e) {
  942. $transaction->rollBack();
  943. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  944. return false;
  945. }
  946. return true;
  947. }
  948. /**
  949. * 给商城会员增加货款
  950. * @param $userId
  951. * @param $amount
  952. * @param $remark
  953. * @throws Exception
  954. */
  955. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  956. $db = \Yii::$app->dbShop;
  957. $transaction = $db->beginTransaction();
  958. try {
  959. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  960. // 增加流水
  961. $flowInsertData[] = [
  962. 'USER_ID' => $userId,
  963. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  964. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  965. 'ORDER_SN' => null,
  966. 'AMOUNT' => $amount,
  967. 'CREATED_AT' => Date::nowTime(),
  968. 'PERIOD_AT' => $this->_periodNum,
  969. 'IS_INCR' => 1,
  970. 'REMARK' => $remark,
  971. 'PARTITION_DATE' => Date::ociToDate(),
  972. 'WALLET_TYPE' => 'payment_for_goods',
  973. 'FROM_TYPE' => 'incr',
  974. ];
  975. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  976. $transaction->commit();
  977. } catch (Exception $e) {
  978. $transaction->rollBack();
  979. throw new Exception($e->getMessage());
  980. }
  981. }
  982. /**
  983. * 更新百分比并发送
  984. * @param $percent
  985. */
  986. private function _updatePercent($percent) {
  987. // 把数据写入数据库中
  988. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  989. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  990. }
  991. /**
  992. * 更新最高聘级
  993. * @param $user_id
  994. * @return bool
  995. * @throws Exception
  996. */
  997. private function _updateHighestEmpLv($user_id) {
  998. $empLv = Info::getEmpLv($user_id);
  999. $highEmpLv = Info::getHighEmpLv($user_id);
  1000. $empLvSort = EmployLevel::getSortById($empLv);
  1001. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  1002. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  1003. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  1004. 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]);
  1005. }
  1006. } else {
  1007. $yearHighest = new YearHighestEmpLv();
  1008. $yearHighest->USER_ID = $user_id;
  1009. $yearHighest->YEAR = $this->_calcYear;
  1010. $yearHighest->HIGHEST_EMP_LV = $empLv;
  1011. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  1012. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  1013. $yearHighest->CREATED_AT = Date::nowTime();
  1014. if (!$yearHighest->save()) {
  1015. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  1016. }
  1017. }
  1018. if ($empLvSort > $empLvHighSort) {
  1019. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  1020. //发送历史最高聘级短信
  1021. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  1022. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  1023. $realName = Info::getUserRealNameByUserId($user_id);
  1024. $empLvDate = Date::convert();
  1025. $empLvName = EmployLevel::getNameById($empLv);
  1026. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  1027. $params = [
  1028. 'mobiles' => Info::getUserMobileByUserId($user_id),
  1029. 'content' => $content,
  1030. ];
  1031. SmsApi::instance()->clearError();
  1032. SmsApi::instance()->goSend($params);
  1033. }
  1034. }
  1035. return true;
  1036. }
  1037. return false;
  1038. }
  1039. /**
  1040. * 点位合作奖金
  1041. * @param $userId
  1042. * @param $amount
  1043. * @param null $type
  1044. * @return bool
  1045. * @throws Exception
  1046. * @throws \yii\db\Exception
  1047. */
  1048. private function _teamworkBonus($userId, $amount, $key) {
  1049. 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;
  1050. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1051. foreach ($teamwork as $value) {
  1052. $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
  1053. if ($bonus <= 0) continue;
  1054. $toUserInfo = CalcCache::getUserInfo($value['USER_ID'], $this->_periodNum);
  1055. 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'] . '%']);
  1056. 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'] . '%']);
  1057. }
  1058. }
  1059. /**
  1060. * 发送短信
  1061. * @param int $offset
  1062. * @return bool
  1063. * @throws \yii\db\Exception
  1064. */
  1065. public function sendSmsLoop(int $offset = 0) {
  1066. // $allData = UserInfo::findUseDbCalc()
  1067. $allData = UserInfo::find()
  1068. ->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  1069. if ($allData) {
  1070. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  1071. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  1072. //获取剩余月份
  1073. $period = Period::instance();
  1074. $year = $period->getYear($this->_periodNum);
  1075. $monthLeft = Period::getMonthLeft($this->_periodNum);
  1076. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  1077. $to = Date::yearEnd();
  1078. $transaction = Yii::$app->db->beginTransaction();
  1079. try {
  1080. foreach ($allData as $data) {
  1081. $userId = $data['USER_ID'];
  1082. //过期续费
  1083. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  1084. foreach ($smsWallet as $item) {
  1085. //1奖金钱包2现金钱包
  1086. if ($item == 1) {
  1087. //看余额是否充足
  1088. if (Balance::getAvailableBalance($userId) < $smsFee){
  1089. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  1090. continue;
  1091. };
  1092. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  1093. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  1094. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  1095. break;
  1096. } elseif ($item == 2) {
  1097. throw new Exception('不存在此方式');
  1098. break;
  1099. }
  1100. }
  1101. }
  1102. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  1103. $realName = Info::getUserRealNameByUserId($userId);
  1104. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  1105. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  1106. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  1107. $month = $period->getNowMonth();
  1108. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  1109. //todo 发短信函数 待测试
  1110. $params = [
  1111. 'mobiles' => $mobile,
  1112. 'content' => $content,
  1113. ];
  1114. SmsApi::instance()->clearError();
  1115. SmsApi::instance()->goSend($params);
  1116. }
  1117. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  1118. }
  1119. $transaction->commit();
  1120. } catch (Exception $e) {
  1121. $transaction->rollBack();
  1122. return false;
  1123. }
  1124. unset($data);
  1125. return $this->sendSmsLoop($offset + $this->_limit);
  1126. }
  1127. unset($allData);
  1128. return true;
  1129. }
  1130. }