BonusSend.php 49 KB

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