BonusSend.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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\libs\api\sms\SmsApi;
  18. use common\models\Countries;
  19. use common\models\CurrencyConversions;
  20. use common\models\DealType;
  21. use common\models\EliteLevel;
  22. use common\models\FlowRemainPv;
  23. use common\models\PerfPeriod;
  24. use common\models\EmployLevel;
  25. use common\models\UserBonus;
  26. use common\models\UserPerfMonthUpdate;
  27. use common\models\UserPerformance;
  28. use common\models\UserPeriodPoints;
  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\models\CalcBonus;
  41. use common\models\CalcBonusBS;
  42. use common\models\CalcBonusQY;
  43. use common\models\PerfActiveUser;
  44. use common\models\PerfMonth;
  45. use common\models\User;
  46. use Yii;
  47. use common\models\Period;
  48. use yii\base\Exception;
  49. use yii\db\Expression;
  50. class BonusSend extends BaseObject {
  51. use StaticInstanceTrait;
  52. private $_limit = 1000;
  53. private $_appUserId = null;
  54. private $_sysConfig = [];
  55. private $_decLevelConfig = [];
  56. private $_empLevelConfig = [];
  57. private $_decRoleConfig = [];
  58. private $_errors = [];
  59. private $_periodNum = 0;
  60. private $_periodId;
  61. private $_isCalcMonth = 0;
  62. private $_isCalcYear = 0;
  63. private $_calcYear;
  64. private $_calcMonth;
  65. private $_calcYearMonth;
  66. private $_lastCalcYear;
  67. private $_lastCalcMonth;
  68. private $_lastCalcYearMonth;
  69. private $_workerId;
  70. private $_workerNum;
  71. public function init(int $periodNum = 0, $appUserId = null, $workerId = null, $workerNum = null) {
  72. parent::init();
  73. $this->_sysConfig = Cache::getSystemConfig();
  74. $this->_decLevelConfig = Cache::getDecLevelConfig();
  75. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  76. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  77. $this->_periodNum = $periodNum;
  78. $this->_appUserId = $appUserId;
  79. $this->_workerId = $workerId;
  80. $this->_workerNum = $workerNum;
  81. }
  82. /**
  83. * 设置期数
  84. * @param int $periodNum
  85. * @return int
  86. */
  87. public function setPeriodNum(int $periodNum) {
  88. return $this->_periodNum = $periodNum;
  89. }
  90. /**
  91. * 获取期数
  92. * @return int
  93. */
  94. public function getPeriodNum() {
  95. return $this->_periodNum;
  96. }
  97. /**
  98. * 加入错误错误
  99. * @param $attr
  100. * @param $error
  101. */
  102. public function addError($attr, $error) {
  103. $this->_errors[$attr][] = $error;
  104. }
  105. /**
  106. * 获取错误信息
  107. * @return array
  108. */
  109. public function getErrors() {
  110. return $this->_errors;
  111. }
  112. /**
  113. * 挂网时处理虚假订单
  114. *
  115. */
  116. public function putFakeOrder() {
  117. echo('开始处理-假订单' . PHP_EOL);
  118. $sysConfig = Cache::getSystemConfig();
  119. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NG默认30
  120. $fakeOrder= Order::find()->where(['PERIOD_NUM'=>$this->_periodNum, 'IS_AUTO'=>'1'])->asArray()->all();
  121. foreach($fakeOrder as $fOrder){
  122. $oRemainPv=RemainPv::findOne(["USER_ID"=>$fOrder['USER_ID']]);
  123. $transactionRemain = \Yii::$app->db->beginTransaction();
  124. try{
  125. $fakeOrderPv = $oRemainPv->REMAIN_PV>=$mesureUpCondition?$mesureUpCondition:$oRemainPv->REMAIN_PV;
  126. $flowRemainPvModel = new FlowRemainPv();
  127. $flowRemainPvModel->ID = $this->_generateSn();
  128. $flowRemainPvModel->USER_ID = $fOrder['USER_ID'];
  129. $flowRemainPvModel->REMAIN_PV_FLOW = 0 - $fakeOrderPv;
  130. $flowRemainPvModel->REMAIN_PV_TOTAL = $oRemainPv->REMAIN_PV - $fakeOrderPv;
  131. $flowRemainPvModel->PERIOD_NUM = $this->_periodNum;
  132. $flowRemainPvModel->UPDATED_AT = Date::nowTime();
  133. $flowRemainPvModel->ORDER_SN = $fOrder['SN'];
  134. if(!$flowRemainPvModel->save()){
  135. $this->addErrors($flowRemainPvModel->getErrors());
  136. return false;
  137. }
  138. $oRemainPv->updateCounters(['REMAIN_PV'=>0-$fakeOrderPv]);
  139. $transactionRemain->commit();
  140. } catch (Exception $e) {
  141. $transactionRemain->rollBack();
  142. $this->addError('add', $e->getMessage());
  143. return null;
  144. }
  145. }
  146. echo('假订单处理完' . PHP_EOL);
  147. return true; // $flowRemainPvModel;
  148. }
  149. /**
  150. * 生成流水号
  151. * @return string
  152. */
  153. private function _generateSn() {
  154. return Date::today('Ymd') . $this->_random(10, 1);
  155. }
  156. /**
  157. * 生成随机数
  158. * @param $length
  159. * @param int $numeric
  160. * @return string
  161. */
  162. private function _random($length, $numeric = 0) {
  163. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  164. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  165. $hash = '';
  166. $max = strlen($seed) - 1;
  167. for ($i = 0; $i < $length; $i++) {
  168. $hash .= $seed[mt_rand(0, $max)];
  169. }
  170. return $hash;
  171. }
  172. /**
  173. * 进行奖金发放步骤
  174. * @return bool
  175. */
  176. public function sendStep() {
  177. try {
  178. $t1 = microtime(true);
  179. // 初始化
  180. $this->initTask();
  181. echo('挂网开始');
  182. // 改变状态
  183. $this->setSendStatus('start');
  184. // 发放荣衔级别(Honor/Emp)、Elite级别
  185. $this->sentMemberLevel();
  186. $this->_updatePercent(30);
  187. $t2 = microtime(true);
  188. echo('更新会员级别完成,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  189. // 发放奖金
  190. $this->sendBonusLoop();
  191. $this->_updatePercent(80);
  192. $t3 = microtime(true);
  193. echo('发放奖金完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  194. echo('全部奖金发放完成,耗时:'.round($t3 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
  195. $this->_updatePercent(100);
  196. } catch (\Exception $e) {
  197. LoggerTool::error('sendBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
  198. $this->addError('sendBonus', sprintf('%s',$e->getMessage()));
  199. return false;
  200. }
  201. if (count($this->_errors) > 0) {
  202. return false;
  203. }
  204. return true;
  205. }
  206. /**
  207. * 需要多进程执行的任务
  208. * @param $workId
  209. * @throws \yii\db\Exception
  210. */
  211. public function processStep($workId = null) {
  212. if ($workId == 1 || $workId === null) {
  213. // 发放奖金
  214. $this->sendBonusLoop();
  215. }
  216. if ($workId == 2 || $workId === null) {
  217. // 更新聘级
  218. $this->updateEmpLevel();
  219. }
  220. if ($workId == 3 || $workId === null) {
  221. // 更新会员累计业绩
  222. $this->updateUserPerf();
  223. }
  224. Yii::$app->db->close();
  225. Yii::$app->dbShop->close();
  226. }
  227. /**
  228. * 初始化发放任务
  229. * @throws Exception
  230. */
  231. public function initTask() {
  232. $this->_errors = [];
  233. $periodNum = $this->_periodNum;
  234. // 获取传入期数的相关信息
  235. $periodObj = Period::instance();
  236. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  237. $this->_periodId = $periodDataArr['ID'];
  238. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  239. $this->_calcYear = $periodObj->getYear($periodNum);
  240. $this->_calcMonth = $periodObj->getMonth($periodNum);
  241. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  242. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  243. $this->_lastCalcYear = $lastYearMonthArr['year'];
  244. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  245. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  246. }
  247. /**
  248. * 设置结算状态
  249. * @param $type
  250. * start|end|fail
  251. */
  252. public function setSendStatus($type) {
  253. Yii::$app->db->close();
  254. if ($type == 'start') {
  255. Period::updateAll(['IS_SENDING' => 1, 'SEND_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  256. } elseif ($type == 'end') {
  257. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FINISH, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  258. } elseif ($type == 'fail') {
  259. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FAIL, 'SENT_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  260. }
  261. }
  262. /**
  263. * 结束计算任务
  264. * @throws \yii\db\Exception
  265. */
  266. public function endTask() {
  267. CalcCache::clearAll($this->_periodNum);
  268. $this->setSendStatus('end');
  269. //@todo 先不备份数据
  270. // DataBak::backup($this->_periodNum);
  271. //发送复销短信
  272. // if ($this->_isCalcMonth && $this->_sysConfig['smsOpen']['VALUE']) {
  273. // $this->sendSmsLoop();
  274. // }
  275. }
  276. /**
  277. * 出现错误
  278. */
  279. public function errorTask() {
  280. $this->setSendStatus('fail');
  281. }
  282. /**
  283. * 发放奖金
  284. * @return bool
  285. * @throws \yii\db\Exception
  286. */
  287. public function sendBonusLoop(): bool
  288. {
  289. echo sprintf("时间:[%s] 奖金挂网" . PHP_EOL, date('Y-m-d H:i:s', time()));
  290. $periodNum = $this->_periodNum;
  291. // 从奖金结算表中获取当期未发放的所有数据
  292. $allData = CalcBonus::find()
  293. ->select('ID, USER_ID, PERIOD_NUM, BONUS_TOTAL, MANAGE_TAX, BONUS_PB')
  294. ->where('IS_SENT=0 AND PERIOD_NUM=:PERIOD_NUM AND (BONUS_TOTAL>0 OR BONUS_PB>0)', [':PERIOD_NUM' => $this->_periodNum])
  295. ->asArray()
  296. ->all();
  297. if ($allData) {
  298. $transaction = Yii::$app->db->beginTransaction();
  299. try {
  300. foreach ($allData as $key => $data) {
  301. // 用户奖金发放
  302. if ($data['BONUS_TOTAL'] > 0) {
  303. Balance::changeUserBonus($data['USER_ID'], 'bonus', $data['BONUS_TOTAL'],
  304. [
  305. 'CALC_ID' => $data['ID'],
  306. 'REMARK' => 'From Period ' . $data['PERIOD_NUM'],
  307. 'PERIOD_NUM' => $periodNum,
  308. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  309. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  310. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  311. 'SORT' => $key * 10,
  312. 'BONUS_ISSUE' => true,
  313. ]);
  314. }
  315. // 绩效奖金发放
  316. if ($data['BONUS_PB'] > 0) {
  317. // 汇率
  318. $countryId = User::getEnCodeInfo($data['USER_ID'])['COUNTRY_ID'];
  319. $currencyId = Countries::getById($countryId)['LOCAL_CURRENCY_ID'];
  320. $bonusConversions = CurrencyConversions::getToUSDRate($currencyId, 'bonus');
  321. // 奖金转化为会员所在国家汇率后进行发放
  322. $localAmount = $data['BONUS_PB'] * $bonusConversions;
  323. // 奖金发放
  324. UserPerformance::sentUserPerformance($data['USER_ID'], $localAmount, $data['PERIOD_NUM']);
  325. }
  326. // 把记录标记为已发放状态
  327. Period::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $data['PERIOD_NUM']]);
  328. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  329. unset($key, $data);
  330. }
  331. $transaction->commit();
  332. } catch (Exception $e) {
  333. $transaction->rollBack();
  334. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  335. return false;
  336. }
  337. }
  338. return true;
  339. }
  340. /**
  341. * 蓝星奖金(即新的管理奖),更新会员聘级
  342. * @param int $offset
  343. * @return bool
  344. * @throws \yii\db\Exception
  345. */
  346. public function updateEmpLevel(int $offset = 0) {
  347. if ($this->_isCalcMonth) {
  348. $empLv = EmployLevel::getIdConvertLevelSortCache();
  349. $allData = CalcBonusBS::find()
  350. ->yearMonth($this->_calcYearMonth)
  351. ->where(
  352. 'CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM',
  353. [
  354. ':CALC_MONTH' => $this->_calcYearMonth,
  355. ':PERIOD_NUM' =>$this->_periodNum
  356. ]
  357. )
  358. ->orderBy('CREATED_AT DESC')
  359. ->offset($offset)
  360. ->limit($this->_limit)
  361. ->all();
  362. LoggerTool::info($allData);
  363. //@todo 用户级别不变则不更新
  364. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  365. if ($allData) {
  366. $transaction = Yii::$app->db->beginTransaction();
  367. try {
  368. foreach ($allData as $data) {
  369. // 蓝星奖计算的最新聘级
  370. $latestEmpLv = $data['LEVEL_ID']; // 本期计算最新管理级别
  371. $latestEmpLvSort = $empLv[$latestEmpLv]; // 当前蓝星计算的聘级 级别值
  372. if ($defaultEmpLv == $latestEmpLv) {
  373. continue;
  374. }
  375. // 用户存储的最高聘级
  376. $user = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  377. $highestEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
  378. $highestEmpLvSort = $empLv[$highestEmpLv]; // 历史最高聘级的 级别值
  379. // 如果当前期的聘级高于用户表的最高聘级,则进行更新
  380. if ($latestEmpLvSort > $highestEmpLvSort) {
  381. User::updateAll(['EMP_LV' => $latestEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  382. User::deleteBaseInfoFromRedis($data['USER_ID']);
  383. }
  384. // 更新最新用户表级别
  385. User::updateAll([
  386. 'LAST_EMP_LV' => $latestEmpLv,
  387. 'LAST_EMP_LV_UPDATED_AT' => time(),
  388. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum
  389. ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  390. User::deleteBaseInfoFromRedis($data['USER_ID']);
  391. unset($data);
  392. }
  393. $transaction->commit();
  394. } catch (Exception $e) {
  395. $transaction->rollBack();
  396. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  397. return false;
  398. }
  399. unset($transaction, $allData, $defaultEmpLv);
  400. return $this->updateEmpLevel($offset + $this->_limit);
  401. }
  402. unset($allData);
  403. // 刷新会员EmpLv为0
  404. User::updateAll([
  405. 'LAST_EMP_LV' => '',
  406. 'LAST_EMP_LV_UPDATED_AT' => time(),
  407. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  408. ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $this->_periodNum]);
  409. User::deleteAllBaseInfoFromRedis();
  410. }
  411. return true;
  412. }
  413. /**
  414. * @return bool
  415. */
  416. public function sentMemberLevel(): bool
  417. {
  418. $transaction = Yii::$app->db->beginTransaction();
  419. try {
  420. $db = Yii::$app->db;
  421. // 刷新所有会员最新EliteLevel和最新EmpLevel为默认等级
  422. User::updateAll(
  423. [
  424. 'LAST_EMP_LV' => EmployLevel::getDefaultLevelId(),
  425. 'LAST_EMP_LV_UPDATED_AT' => time(),
  426. 'LAST_EMP_LV_UPDATED_PERIOD' => $this->_periodNum,
  427. 'LAST_ELITE_LV' => EliteLevel::getDefaultLevelId(),
  428. 'LAST_ELITE_LV_UPDATED_AT' => time(),
  429. 'LAST_ELITE_LV_UPDATED_PERIOD' => $this->_periodNum,
  430. ]);
  431. // 刷新会员最高EliteLevel和最高EmpLevel(统一数据,更新为默认Elite级别)
  432. User::updateAll(['EMP_LV' => EmployLevel::getDefaultLevelId()], "EMP_LV = '' OR EMP_LV IS NULL");
  433. User::updateAll(['ELITE_LV' => EliteLevel::getDefaultLevelId()], "ELITE_LV = '' OR ELITE_LV IS NULL");
  434. $sql =<<<SQL
  435. UPDATE `AR_USER` `user`
  436. INNER JOIN `AR_CALC_BONUS` `bonus` ON `user`.`ID` = `bonus`.`USER_ID` AND `bonus`.`PERIOD_NUM` = :PERIOD_NUM
  437. SET
  438. `user`.`EMP_LV` = `bonus`.`HIGHEST_HONOR_LV`,
  439. `user`.`LAST_EMP_LV` = `bonus`.`LAST_EMP_LV`,
  440. `user`.`LAST_EMP_LV_UPDATED_AT` = :UPDATED_AT,
  441. `user`.`LAST_EMP_LV_UPDATED_PERIOD` = :PERIOD_NUM,
  442. `user`.`ELITE_LV` = `bonus`.`HIGHEST_ELITE_LV`,
  443. `user`.`LAST_ELITE_LV` = `bonus`.`LAST_ELITE_LV`,
  444. `user`.`LAST_ELITE_LV_UPDATED_AT` = :UPDATED_AT,
  445. `user`.`LAST_ELITE_LV_UPDATED_PERIOD` = :PERIOD_NUM
  446. WHERE
  447. `bonus`.`PERIOD_NUM` = :PERIOD_NUM AND `bonus`.`IS_SENT` = 0
  448. SQL;
  449. $db->createCommand($sql)
  450. ->bindValues(
  451. [
  452. ':PERIOD_NUM' => $this->_periodNum,
  453. ':UPDATED_AT' => time(),
  454. ])
  455. ->execute();
  456. $transaction->commit();
  457. // 刷新本期无Elite的用户级别
  458. // 删除缓存中的会员信息
  459. User::deleteAllBaseInfoFromRedis();
  460. } catch (Exception $e) {
  461. $transaction->rollBack();
  462. $this->addError('sendLevelFailed', '发放会员级别失败,原因:' . $e->getMessage());
  463. return false;
  464. }
  465. return true;
  466. }
  467. // 更活跃会员,将is_send改成1
  468. public function updateActiveUser() {
  469. $ret = PerfActiveUser::updateAll(
  470. ['IS_SENT' => 1],
  471. 'PERIOD_NUM=:PERIOD_NUM AND IS_SENT=:IS_SENT',
  472. ['IS_SENT'=>0, 'PERIOD_NUM'=>$this->_periodNum]
  473. );
  474. return $ret;
  475. }
  476. /**
  477. * 更新会员的累计业绩
  478. * @param int $offset
  479. * @return bool
  480. * @throws \yii\db\Exception
  481. */
  482. public function updateUserPerf(int $offset = 0) {
  483. $allData = PerfPeriod::find()
  484. ->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  485. if ($allData) {
  486. $transaction = Yii::$app->db->beginTransaction();
  487. try {
  488. foreach ($allData as $data) {
  489. $isUpdate = false;
  490. if (UserPerf::find()
  491. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  492. // 判断本期是否已经更新过业绩
  493. if (!UserPerfUpdate::find()
  494. ->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
  495. $isUpdate = true;
  496. // 更新业绩
  497. UserPerf::updateAll([
  498. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  499. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  500. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  501. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  502. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  503. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  504. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  505. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  506. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  507. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  508. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  509. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  510. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  511. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  512. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  513. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  514. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  515. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  516. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  517. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  518. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  519. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  520. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  521. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  522. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  523. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  524. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  525. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  526. }
  527. } else {
  528. $isUpdate = true;
  529. UserPerf::insertOne([
  530. 'USER_ID' => $data['USER_ID'],
  531. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  532. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  533. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  534. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  535. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  536. 'PV_PSS' => $data['PV_PSS'],
  537. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  538. 'PV_1L' => $data['PV_1L'],
  539. 'PV_2L' => $data['PV_2L'],
  540. 'PV_3L' => $data['PV_3L'],
  541. 'PV_4L' => $data['PV_4L'],
  542. 'PV_5L' => $data['PV_5L'],
  543. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  544. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  545. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  546. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  547. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  548. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  549. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  550. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  551. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  552. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  553. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  554. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  555. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  556. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  557. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  558. 'CREATED_AT' => Date::nowTime(),
  559. ]);
  560. }
  561. if ($isUpdate) {
  562. // 变为已更新
  563. 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()]);
  564. }
  565. unset($data, $isUpdate);
  566. }
  567. $transaction->commit();
  568. } catch (Exception $e) {
  569. $transaction->rollBack();
  570. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  571. return false;
  572. }
  573. unset($allData, $transaction);
  574. return $this->updateUserPerf($offset + $this->_limit);
  575. }
  576. unset($allData);
  577. return true;
  578. }
  579. /**
  580. * 更新会员的月剩余业绩
  581. * @param int $offset
  582. * @return bool
  583. * @throws \yii\db\Exception
  584. */
  585. public function updateUserPerfMonth(int $offset = 0) {
  586. // 月结,如果不是月结点,则直接退出
  587. if (!$this->_isCalcMonth) {
  588. return true;
  589. }
  590. // $allData = PerfMonth::findUseDbCalc()
  591. $allData = PerfMonth::find()
  592. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  593. if ($allData) {
  594. $transaction = Yii::$app->db->beginTransaction();
  595. try {
  596. foreach ($allData as $data) {
  597. $isUpdate = false;
  598. // if (UserPerf::findUseDbCalc()
  599. if (UserPerf::find()
  600. ->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  601. // 判断本期是否已经更新过业绩
  602. // if (!UserPerfMonthUpdate::findUseDbCalc()
  603. if (!UserPerfMonthUpdate::find()
  604. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  605. $isUpdate = true;
  606. // 更新业绩
  607. UserPerf::updateAll([
  608. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  609. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  610. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  611. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  612. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  613. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  614. }
  615. } else {
  616. $isUpdate = true;
  617. UserPerf::insertOne([
  618. 'USER_ID' => $data['USER_ID'],
  619. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  620. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  621. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  622. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  623. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  624. 'CREATED_AT' => Date::nowTime(),
  625. ]);
  626. }
  627. if ($isUpdate) {
  628. // 变为已更新
  629. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  630. }
  631. unset($data, $isUpdate);
  632. }
  633. $transaction->commit();
  634. } catch (Exception $e) {
  635. $transaction->rollBack();
  636. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  637. return false;
  638. }
  639. unset($allData, $transaction);
  640. return $this->updateUserPerfMonth($offset + $this->_limit);
  641. }
  642. unset($allData);
  643. return true;
  644. }
  645. /**
  646. * 检测复消积分是否过期
  647. * @return bool
  648. * @throws \yii\db\Exception
  649. */
  650. public function checkReconsumePointsExpired(int $offset = 0) {
  651. $periodNum = $this->_periodNum;
  652. //一期为7天,那么365天为52.14即53期
  653. $expiredPeriodNum = $periodNum - 53;
  654. if( $expiredPeriodNum <= 0 ) return true;
  655. //查询需要过期的期数
  656. $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();
  657. if( $allData ) {
  658. $transaction = Yii::$app->db->beginTransaction();
  659. try{
  660. //扣除钱包的复消积分
  661. foreach ($allData as $everyData) {
  662. //过期
  663. UserPeriodPoints::updateAll([
  664. 'REMAINDER_POINTS' => 0,
  665. 'EXPIRED' => 1,
  666. 'EXPIRED_PERIOD' => $periodNum,
  667. 'EXPIRED_AT' => Date::nowTime(),
  668. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  669. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  670. UserBonus::updateAllCounters([
  671. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  672. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  673. unset($everyData);
  674. }
  675. unset($periodNum, $expiredPeriodNum, $allData);
  676. $transaction->commit();
  677. }catch (\Exception $e){
  678. $transaction->rollBack();
  679. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  680. return false;
  681. }
  682. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  683. }
  684. unset($allData);
  685. return true;
  686. }
  687. /**
  688. * 更新会员上次报单级别
  689. * @return bool
  690. */
  691. public function updateUserDevLv() {
  692. $transaction = Yii::$app->dbShop->beginTransaction();
  693. try {
  694. \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();
  695. $transaction->commit();
  696. } catch (Exception $e) {
  697. $transaction->rollBack();
  698. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  699. return false;
  700. }
  701. return true;
  702. }
  703. /**
  704. * 给商城会员增加货款
  705. * @param $userId
  706. * @param $amount
  707. * @param $remark
  708. * @throws Exception
  709. */
  710. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  711. $db = \Yii::$app->dbShop;
  712. $transaction = $db->beginTransaction();
  713. try {
  714. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  715. // 增加流水
  716. $flowInsertData[] = [
  717. 'USER_ID' => $userId,
  718. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  719. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  720. 'ORDER_SN' => null,
  721. 'AMOUNT' => $amount,
  722. 'CREATED_AT' => Date::nowTime(),
  723. 'PERIOD_AT' => $this->_periodNum,
  724. 'IS_INCR' => 1,
  725. 'REMARK' => $remark,
  726. 'PARTITION_DATE' => Date::ociToDate(),
  727. 'WALLET_TYPE' => 'payment_for_goods',
  728. 'FROM_TYPE' => 'incr',
  729. ];
  730. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  731. $transaction->commit();
  732. } catch (Exception $e) {
  733. $transaction->rollBack();
  734. throw new Exception($e->getMessage());
  735. }
  736. }
  737. /**
  738. * 更新百分比并发送
  739. * @param $percent
  740. */
  741. private function _updatePercent($percent) {
  742. // 把数据写入数据库中
  743. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  744. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  745. }
  746. /**
  747. * 更新最高聘级
  748. * @param $user_id
  749. * @return bool
  750. * @throws Exception
  751. */
  752. private function _updateHighestEmpLv($user_id) {
  753. $empLv = Info::getEmpLv($user_id);
  754. $highEmpLv = Info::getHighEmpLv($user_id);
  755. $empLvSort = EmployLevel::getSortById($empLv);
  756. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  757. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  758. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  759. 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]);
  760. }
  761. } else {
  762. $yearHighest = new YearHighestEmpLv();
  763. $yearHighest->USER_ID = $user_id;
  764. $yearHighest->YEAR = $this->_calcYear;
  765. $yearHighest->HIGHEST_EMP_LV = $empLv;
  766. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  767. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  768. $yearHighest->CREATED_AT = Date::nowTime();
  769. if (!$yearHighest->save()) {
  770. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  771. }
  772. }
  773. if ($empLvSort > $empLvHighSort) {
  774. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  775. //发送历史最高聘级短信
  776. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  777. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  778. $realName = Info::getUserRealNameByUserId($user_id);
  779. $empLvDate = Date::convert();
  780. $empLvName = EmployLevel::getNameById($empLv);
  781. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  782. $params = [
  783. 'mobiles' => Info::getUserMobileByUserId($user_id),
  784. 'content' => $content,
  785. ];
  786. SmsApi::instance()->clearError();
  787. SmsApi::instance()->goSend($params);
  788. }
  789. }
  790. return true;
  791. }
  792. return false;
  793. }
  794. /**
  795. * 发送短信
  796. * @param int $offset
  797. * @return bool
  798. * @throws \yii\db\Exception
  799. */
  800. public function sendSmsLoop(int $offset = 0) {
  801. // $allData = UserInfo::findUseDbCalc()
  802. $allData = UserInfo::find()
  803. ->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  804. if ($allData) {
  805. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  806. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  807. //获取剩余月份
  808. $period = Period::instance();
  809. $year = $period->getYear($this->_periodNum);
  810. $monthLeft = Period::getMonthLeft($this->_periodNum);
  811. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  812. $to = Date::yearEnd();
  813. $transaction = Yii::$app->db->beginTransaction();
  814. try {
  815. foreach ($allData as $data) {
  816. $userId = $data['USER_ID'];
  817. //过期续费
  818. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  819. foreach ($smsWallet as $item) {
  820. //1奖金钱包2现金钱包
  821. if ($item == 1) {
  822. //看余额是否充足
  823. if (Balance::getAvailableBalance($userId) < $smsFee){
  824. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  825. continue;
  826. };
  827. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  828. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  829. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  830. break;
  831. } elseif ($item == 2) {
  832. throw new Exception('不存在此方式');
  833. break;
  834. }
  835. }
  836. }
  837. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  838. $realName = Info::getUserRealNameByUserId($userId);
  839. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  840. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  841. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  842. $month = $period->getNowMonth();
  843. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  844. //todo 发短信函数 待测试
  845. $params = [
  846. 'mobiles' => $mobile,
  847. 'content' => $content,
  848. ];
  849. SmsApi::instance()->clearError();
  850. SmsApi::instance()->goSend($params);
  851. }
  852. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  853. }
  854. $transaction->commit();
  855. } catch (Exception $e) {
  856. $transaction->rollBack();
  857. return false;
  858. }
  859. unset($data);
  860. return $this->sendSmsLoop($offset + $this->_limit);
  861. }
  862. unset($allData);
  863. return true;
  864. }
  865. }