BonusSend.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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, 'ORDER_TYPE'=>'FO'])->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 $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. // 更新聘级
  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. // 更新星级
  203. $this->updateStarLevel();
  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', $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. ->yearMonth($this->_calcYearMonth)
  389. ->where(
  390. '(IS_SENT=0 OR IS_SENT=2) AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  391. [':CALC_MONTH' => $this->_calcYearMonth, ':PERIOD_NUM' => $periodNum]
  392. )
  393. ->limit($this->_limit)
  394. ->asArray()
  395. ->all();
  396. if ($allData) {
  397. $transaction = Yii::$app->db->beginTransaction();
  398. try {
  399. foreach ($allData as $key => $data) {
  400. // 期奖金
  401. // $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'];
  402. $periodAmount = $data['BONUS_REAL'];
  403. // 获取本期结算的管理员
  404. // $period = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
  405. // $updateAminId = $period['CALC_ADMIN_ID'];
  406. if ($periodAmount > 0) {
  407. Balance::changeUserBonus($data['USER_ID'], 'bonus', $periodAmount, [
  408. 'CALC_ID' => $data['ID'],
  409. 'REMARK' => 'From Period ' . $periodNum,
  410. 'PERIOD_NUM' => $periodNum,
  411. 'QY' => $data['BONUS_QY'],
  412. 'FW' => $data['BONUS_FW'],
  413. 'YC' => $data['BONUS_YC'],
  414. 'VIP' => $data['BONUS_VIP'],
  415. 'BD' => $data['BONUS_BD'],
  416. 'TG' => $data['BONUS_TG'],
  417. 'YJ' => $data['BONUS_YJ'],
  418. 'GX' => $data['BONUS_GX'],
  419. 'GL' => $data['BONUS_GL'],
  420. 'BS' => $data['BONUS_BS'],
  421. 'BS_MNT' => $data['BONUS_BS_MNT'],
  422. 'BS_ABBR' => $data['BONUS_BS_ABBR'],
  423. 'ORI_QY' => $data['ORI_BONUS_QY'],
  424. 'ORI_YC' => $data['ORI_BONUS_YC'],
  425. 'ORI_VIP' => $data['ORI_BONUS_VIP'],
  426. 'ORI_STANDARD' => $data['ORI_BONUS_STANDARD'],
  427. 'ORI_BD' => $data['ORI_BONUS_BD'],
  428. 'ORI_TG' => $data['ORI_BONUS_TG'],
  429. 'ORI_YJ' => $data['ORI_BONUS_YJ'],
  430. 'ORI_GX' => $data['ORI_BONUS_GX'],
  431. 'ORI_GL' => $data['ORI_BONUS_GL'],
  432. 'ORI_BS' => $data['ORI_BONUS_BS'],
  433. 'ORI_BS_MNT' => $data['ORI_BONUS_BS_MNT'],
  434. 'ORI_BS_ABBR' => $data['ORI_BONUS_BS_ABBR'],
  435. 'RECONSUME_POINTS_TOTAL' => $data['RECONSUME_POINTS'],
  436. 'EXCHANGE_POINTS_TOTAL' => $data['EXCHANGE_POINTS'],
  437. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  438. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  439. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  440. 'SORT' => $key * 10,
  441. 'BONUS_ISSUE' => true,
  442. ]);
  443. // $this->_teamworkBonus($data['USER_ID'], $periodAmount, $key);
  444. }
  445. // 旅游奖
  446. if ($data['BONUS_TOURISM'] > 0) {
  447. Balance::changeUserBonus($data['USER_ID'], 'tourism_points', $data['BONUS_TOURISM'], [
  448. 'CALC_ID' => $data['ID'],
  449. 'REMARK' => 'From Period ' . $periodNum,
  450. 'PERIOD_NUM' => $periodNum,
  451. 'TOURISM_POINTS' => $data['BONUS_TOURISM'],
  452. 'DEAL_TYPE_ID' => DealType::TOURISM_SEND,
  453. 'SORT' => $key * 10,
  454. 'BONUS_ISSUE' => true,
  455. ]);
  456. }
  457. // 车房奖
  458. if ($data['BONUS_GARAGE'] > 0) {
  459. Balance::changeUserBonus($data['USER_ID'], 'garage_points', $data['BONUS_GARAGE'], [
  460. 'CALC_ID' => $data['ID'],
  461. 'REMARK' => 'From Period ' . $periodNum,
  462. 'PERIOD_NUM' => $periodNum,
  463. 'GARAGE_POINTS' => $data['BONUS_GARAGE'],
  464. 'DEAL_TYPE_ID' => DealType::GARAGE_SEND,
  465. 'SORT' => $key * 10,
  466. 'BONUS_ISSUE' => true,
  467. ]);
  468. }
  469. //发放重消积分
  470. // if ($data['RECONSUME_POINTS'] > 0) {
  471. // Balance::changeUserBonus($data['USER_ID'], 'reconsume_points', $data['RECONSUME_POINTS'], [
  472. // 'CALC_ID' => $data['ID'],
  473. // 'REMARK' => 'From ' . $periodNum . '期',
  474. // 'PERIOD_NUM' => $periodNum,
  475. // 'RECONSUME_POINTS' => $data['RECONSUME_POINTS'],
  476. // 'DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_SEND,
  477. // ]);
  478. // }
  479. //
  480. // //发放兑换积分
  481. // if ($data['EXCHANGE_POINTS'] > 0) {
  482. // Balance::changeUserBonus($data['USER_ID'], 'exchange_points', $data['EXCHANGE_POINTS'], [
  483. // 'CALC_ID' => $data['ID'],
  484. // 'REMARK' => 'From ' . $periodNum . '期',
  485. // 'PERIOD_NUM' => $periodNum,
  486. // 'EXCHANGE_POINTS' => $data['EXCHANGE_POINTS'],
  487. // 'DEAL_TYPE_ID' => DealType::EXCHANGE_POINTS_SEND,
  488. // 'BONUS_ISSUE' => true,
  489. // ]);
  490. // }
  491. // 把记录标记为已发放状态
  492. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  493. unset($periodAmount, $key, $data);
  494. }
  495. $transaction->commit();
  496. } catch (Exception $e) {
  497. $transaction->rollBack();
  498. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  499. return false;
  500. }
  501. unset($allData, $transaction);
  502. $page++;
  503. return $this->sendBonusLoop($page);
  504. }
  505. unset($allData);
  506. return true;
  507. }
  508. /**
  509. * 蓝星奖金(即新的管理奖),更新会员聘级
  510. * @param int $offset
  511. * @return bool
  512. * @throws \yii\db\Exception
  513. */
  514. public function updateEmpLevel(int $offset = 0) {
  515. if ($this->_isCalcMonth) {
  516. $empLv = EmployLevel::getIdConvertLevelSortCache();
  517. $allData = CalcBonus::findUseDbCalc()
  518. ->yearMonth($this->_calcYearMonth)
  519. ->where(
  520. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  521. [
  522. ':CALC_MONTH' => $this->_calcYearMonth,
  523. ':PERIOD_NUM' =>$this->_periodNum
  524. ]
  525. )
  526. ->orderBy('CREATED_AT DESC')
  527. ->offset($offset)
  528. ->limit($this->_limit)
  529. ->all();
  530. //@todo 用户级别不变则不更新
  531. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  532. if ($allData) {
  533. $transaction = Yii::$app->db->beginTransaction();
  534. try {
  535. foreach ($allData as $data) {
  536. //@todo 用户级别不变则不更新
  537. if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
  538. $nowBsEmpLv = $data['LAST_EMP_LV']; // 当前蓝星奖计算(即管理奖) 的等级
  539. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  540. $userEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  541. $userEmpLvSort = $empLv[$userEmpLv]; // 历史最高聘级的 级别值
  542. $nowBsEmpLvSort = $empLv[$nowBsEmpLv]; // 当前蓝星计算的聘级 级别值
  543. if ($nowBsEmpLvSort > $userEmpLvSort) {
  544. // 如果当前期的级别值大于历史最高级别,则更新用户表里的最高聘级
  545. User::updateAll(['EMP_LV' => $nowBsEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  546. User::deleteBaseInfoFromRedis($data['USER_ID']);
  547. unset($data);
  548. } else {
  549. continue;
  550. }
  551. }
  552. $transaction->commit();
  553. } catch (Exception $e) {
  554. $transaction->rollBack();
  555. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  556. return false;
  557. }
  558. unset($transaction, $allData, $defaultEmpLv);
  559. return $this->updateEmpLevel($offset + $this->_limit);
  560. }
  561. unset($allData);
  562. }
  563. return true;
  564. }
  565. /**
  566. * 更新用户星级
  567. * @param int $offset
  568. * @return bool
  569. */
  570. public function updateStarLevel(int $offset = 0)
  571. {
  572. $allData = CalcBonusQY::findUseDbCalc()
  573. ->yearMonth($this->_calcYearMonth)
  574. ->where(
  575. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  576. [
  577. ':CALC_MONTH' => $this->_calcYearMonth,
  578. ':PERIOD_NUM' =>$this->_periodNum
  579. ]
  580. )
  581. ->orderBy('CREATED_AT DESC')
  582. ->groupBy('USER_ID')
  583. ->offset($offset)
  584. ->limit($this->_limit)
  585. ->all();
  586. if ($allData) {
  587. $transaction = Yii::$app->db->beginTransaction();
  588. try {
  589. foreach ($allData as $data) {
  590. User::updateAll(['STAR_LV' => $data['LAST_STAR_LV']], 'ID = :USER_ID', [':USER_ID' => $data['USER_ID']]);
  591. User::deleteBaseInfoFromRedis($data['USER_ID']);
  592. unset($data);
  593. }
  594. $transaction->commit();
  595. } catch (Exception $e) {
  596. $transaction->rollBack();
  597. $this->addError('updateStarCrownLevel', '更新星级失败,原因:' . $e->getMessage());
  598. return false;
  599. }
  600. unset($transaction, $allData);
  601. return $this->updateStarLevel($offset + $this->_limit);
  602. }
  603. unset($allData);
  604. return true;
  605. }
  606. // /**
  607. // * 更新会员聘级
  608. // * @param int $offset
  609. // * @return bool
  610. // * @throws \yii\db\Exception
  611. // */
  612. // public function updateEmpLevel(int $offset = 0) {
  613. // if ($this->_isCalcMonth) {
  614. // $allData = PerfMonth::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->all();
  615. // //@todo 用户级别不变则不更新
  616. // $defaultEmpLv = EmployLevel::getDefaultLevelId();
  617. // if ($allData) {
  618. // $transaction = Yii::$app->db->beginTransaction();
  619. // try {
  620. // foreach ($allData as $data) {
  621. // //@todo 用户级别不变则不更新
  622. // if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
  623. // User::updateAll(['EMP_LV' => $data['LAST_EMP_LV']], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  624. // User::deleteBaseInfoFromRedis($data['USER_ID']);
  625. // unset($data);
  626. // }
  627. // $transaction->commit();
  628. // } catch (Exception $e) {
  629. // $transaction->rollBack();
  630. // $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  631. // return false;
  632. // }
  633. // unset($transaction, $allData, $defaultEmpLv);
  634. // return $this->updateEmpLevel($offset + $this->_limit);
  635. // }
  636. // unset($allData);
  637. // }
  638. // return true;
  639. // }
  640. // 更活跃会员,将is_send改成1
  641. public function updateActiveUser() {
  642. try {
  643. $ret = PerfActiveUser::updateAll(
  644. ['IS_SENT' => 1],
  645. 'PERIOD_NUM=:PERIOD_NUM AND IS_SENT=:IS_SENT',
  646. ['IS_SENT'=>0, 'PERIOD_NUM'=>$this->_periodNum]
  647. );
  648. return $ret;
  649. } catch(Exception $e) {
  650. $this->addError('updateActiveUser', '更新活跃会员业绩期处理状态失败,原因:' . $e->getMessage());
  651. return false;
  652. }
  653. }
  654. /**
  655. * 更新会员的累计业绩
  656. * @param int $offset
  657. * @return bool
  658. * @throws \yii\db\Exception
  659. */
  660. public function updateUserPerf(int $offset = 0) {
  661. $allData = PerfPeriod::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  662. if ($allData) {
  663. $transaction = Yii::$app->db->beginTransaction();
  664. try {
  665. foreach ($allData as $data) {
  666. $isUpdate = false;
  667. if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  668. // 判断本期是否已经更新过业绩
  669. 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()) {
  670. $isUpdate = true;
  671. // 更新业绩
  672. UserPerf::updateAll([
  673. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  674. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  675. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  676. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  677. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  678. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  679. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  680. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  681. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  682. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  683. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  684. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  685. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  686. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  687. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  688. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  689. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  690. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  691. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  692. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  693. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  694. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  695. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  696. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  697. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  698. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  699. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  700. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  701. }
  702. } else {
  703. $isUpdate = true;
  704. UserPerf::insertOne([
  705. 'USER_ID' => $data['USER_ID'],
  706. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  707. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  708. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  709. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  710. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  711. 'PV_PSS' => $data['PV_PSS'],
  712. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  713. 'PV_1L' => $data['PV_1L'],
  714. 'PV_2L' => $data['PV_2L'],
  715. 'PV_3L' => $data['PV_3L'],
  716. 'PV_4L' => $data['PV_4L'],
  717. 'PV_5L' => $data['PV_5L'],
  718. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  719. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  720. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  721. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  722. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  723. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  724. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  725. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  726. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  727. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  728. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  729. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  730. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  731. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  732. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  733. 'CREATED_AT' => Date::nowTime(),
  734. ]);
  735. }
  736. if ($isUpdate) {
  737. // 变为已更新
  738. 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()]);
  739. }
  740. unset($data, $isUpdate);
  741. }
  742. $transaction->commit();
  743. } catch (Exception $e) {
  744. $transaction->rollBack();
  745. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  746. return false;
  747. }
  748. unset($allData, $transaction);
  749. return $this->updateUserPerf($offset + $this->_limit);
  750. }
  751. unset($allData);
  752. return true;
  753. }
  754. /**
  755. * 更新会员的月剩余业绩
  756. * @param int $offset
  757. * @return bool
  758. * @throws \yii\db\Exception
  759. */
  760. public function updateUserPerfMonth(int $offset = 0) {
  761. // 月结,如果不是月结点,则直接退出
  762. if (!$this->_isCalcMonth) {
  763. return true;
  764. }
  765. $allData = PerfMonth::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  766. if ($allData) {
  767. $transaction = Yii::$app->db->beginTransaction();
  768. try {
  769. foreach ($allData as $data) {
  770. $isUpdate = false;
  771. if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  772. // 判断本期是否已经更新过业绩
  773. if (!UserPerfMonthUpdate::findUseDbCalc()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  774. $isUpdate = true;
  775. // 更新业绩
  776. UserPerf::updateAll([
  777. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  778. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  779. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  780. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  781. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  782. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  783. }
  784. } else {
  785. $isUpdate = true;
  786. UserPerf::insertOne([
  787. 'USER_ID' => $data['USER_ID'],
  788. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  789. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  790. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  791. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  792. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  793. 'CREATED_AT' => Date::nowTime(),
  794. ]);
  795. }
  796. if ($isUpdate) {
  797. // 变为已更新
  798. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  799. }
  800. unset($data, $isUpdate);
  801. }
  802. $transaction->commit();
  803. } catch (Exception $e) {
  804. $transaction->rollBack();
  805. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  806. return false;
  807. }
  808. unset($allData, $transaction);
  809. return $this->updateUserPerfMonth($offset + $this->_limit);
  810. }
  811. unset($allData);
  812. return true;
  813. }
  814. /**
  815. * 检测复消积分是否过期
  816. * @return bool
  817. * @throws \yii\db\Exception
  818. */
  819. public function checkReconsumePointsExpired(int $offset = 0) {
  820. $periodNum = $this->_periodNum;
  821. //一期为7天,那么365天为52.14即53期
  822. $expiredPeriodNum = $periodNum - 53;
  823. if( $expiredPeriodNum <= 0 ) return true;
  824. //查询需要过期的期数
  825. $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();
  826. if( $allData ) {
  827. $transaction = Yii::$app->db->beginTransaction();
  828. try{
  829. //扣除钱包的复消积分
  830. foreach ($allData as $everyData) {
  831. //过期
  832. UserPeriodPoints::updateAll([
  833. 'REMAINDER_POINTS' => 0,
  834. 'EXPIRED' => 1,
  835. 'EXPIRED_PERIOD' => $periodNum,
  836. 'EXPIRED_AT' => Date::nowTime(),
  837. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  838. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  839. UserBonus::updateAllCounters([
  840. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  841. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  842. unset($everyData);
  843. }
  844. unset($periodNum, $expiredPeriodNum, $allData);
  845. $transaction->commit();
  846. }catch (\Exception $e){
  847. $transaction->rollBack();
  848. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  849. return false;
  850. }
  851. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  852. }
  853. unset($allData);
  854. return true;
  855. }
  856. /**
  857. * 更新会员上次报单级别
  858. * @return bool
  859. */
  860. public function updateUserDevLv() {
  861. $transaction = Yii::$app->dbShop->beginTransaction();
  862. try {
  863. \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();
  864. $transaction->commit();
  865. } catch (Exception $e) {
  866. $transaction->rollBack();
  867. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  868. return false;
  869. }
  870. return true;
  871. }
  872. /**
  873. * 给商城会员增加货款
  874. * @param $userId
  875. * @param $amount
  876. * @param $remark
  877. * @throws Exception
  878. */
  879. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  880. $db = \Yii::$app->dbShop;
  881. $transaction = $db->beginTransaction();
  882. try {
  883. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  884. // 增加流水
  885. $flowInsertData[] = [
  886. 'USER_ID' => $userId,
  887. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  888. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  889. 'ORDER_SN' => null,
  890. 'AMOUNT' => $amount,
  891. 'CREATED_AT' => Date::nowTime(),
  892. 'PERIOD_AT' => $this->_periodNum,
  893. 'IS_INCR' => 1,
  894. 'REMARK' => $remark,
  895. 'PARTITION_DATE' => Date::ociToDate(),
  896. 'WALLET_TYPE' => 'payment_for_goods',
  897. 'FROM_TYPE' => 'incr',
  898. ];
  899. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  900. $transaction->commit();
  901. } catch (Exception $e) {
  902. $transaction->rollBack();
  903. throw new Exception($e->getMessage());
  904. }
  905. }
  906. /**
  907. * 更新百分比并发送
  908. * @param $percent
  909. */
  910. private function _updatePercent($percent) {
  911. // 把数据写入数据库中
  912. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  913. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  914. }
  915. /**
  916. * 更新最高聘级
  917. * @param $user_id
  918. * @return bool
  919. * @throws Exception
  920. */
  921. private function _updateHighestEmpLv($user_id) {
  922. $empLv = Info::getEmpLv($user_id);
  923. $highEmpLv = Info::getHighEmpLv($user_id);
  924. $empLvSort = EmployLevel::getSortById($empLv);
  925. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  926. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  927. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  928. 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]);
  929. }
  930. } else {
  931. $yearHighest = new YearHighestEmpLv();
  932. $yearHighest->USER_ID = $user_id;
  933. $yearHighest->YEAR = $this->_calcYear;
  934. $yearHighest->HIGHEST_EMP_LV = $empLv;
  935. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  936. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  937. $yearHighest->CREATED_AT = Date::nowTime();
  938. if (!$yearHighest->save()) {
  939. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  940. }
  941. }
  942. if ($empLvSort > $empLvHighSort) {
  943. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  944. //发送历史最高聘级短信
  945. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  946. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  947. $realName = Info::getUserRealNameByUserId($user_id);
  948. $empLvDate = Date::convert();
  949. $empLvName = EmployLevel::getNameById($empLv);
  950. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  951. $params = [
  952. 'mobiles' => Info::getUserMobileByUserId($user_id),
  953. 'content' => $content,
  954. ];
  955. SmsApi::instance()->clearError();
  956. SmsApi::instance()->goSend($params);
  957. }
  958. }
  959. return true;
  960. }
  961. return false;
  962. }
  963. /**
  964. * 点位合作奖金
  965. * @param $userId
  966. * @param $amount
  967. * @param null $type
  968. * @return bool
  969. * @throws Exception
  970. * @throws \yii\db\Exception
  971. */
  972. private function _teamworkBonus($userId, $amount, $key) {
  973. 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;
  974. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  975. foreach ($teamwork as $value) {
  976. $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
  977. if ($bonus <= 0) continue;
  978. $toUserInfo = CalcCache::getUserInfo($value['USER_ID'], $this->_periodNum);
  979. 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'] . '%']);
  980. 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'] . '%']);
  981. }
  982. }
  983. /**
  984. * 发送短信
  985. * @param int $offset
  986. * @return bool
  987. * @throws \yii\db\Exception
  988. */
  989. public function sendSmsLoop(int $offset = 0) {
  990. $allData = UserInfo::findUseDbCalc()->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  991. if ($allData) {
  992. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  993. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  994. //获取剩余月份
  995. $period = Period::instance();
  996. $year = $period->getYear($this->_periodNum);
  997. $monthLeft = Period::getMonthLeft($this->_periodNum);
  998. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  999. $to = Date::yearEnd();
  1000. $transaction = Yii::$app->db->beginTransaction();
  1001. try {
  1002. foreach ($allData as $data) {
  1003. $userId = $data['USER_ID'];
  1004. //过期续费
  1005. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  1006. foreach ($smsWallet as $item) {
  1007. //1奖金钱包2现金钱包
  1008. if ($item == 1) {
  1009. //看余额是否充足
  1010. if (Balance::getAvailableBalance($userId) < $smsFee){
  1011. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  1012. continue;
  1013. };
  1014. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  1015. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  1016. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  1017. break;
  1018. } elseif ($item == 2) {
  1019. throw new Exception('不存在此方式');
  1020. break;
  1021. }
  1022. }
  1023. }
  1024. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  1025. $realName = Info::getUserRealNameByUserId($userId);
  1026. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  1027. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  1028. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  1029. $month = $period->getNowMonth();
  1030. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  1031. //todo 发短信函数 待测试
  1032. $params = [
  1033. 'mobiles' => $mobile,
  1034. 'content' => $content,
  1035. ];
  1036. SmsApi::instance()->clearError();
  1037. SmsApi::instance()->goSend($params);
  1038. }
  1039. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  1040. }
  1041. $transaction->commit();
  1042. } catch (Exception $e) {
  1043. $transaction->rollBack();
  1044. return false;
  1045. }
  1046. unset($data);
  1047. return $this->sendSmsLoop($offset + $this->_limit);
  1048. }
  1049. unset($allData);
  1050. return true;
  1051. }
  1052. }