BonusSend.php 50 KB

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