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