BonusSend.php 48 KB

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