BonusSend.php 49 KB

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