BonusSend.php 52 KB

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