BonusSend.php 53 KB

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