| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321 |
- <?php
- /**
- * Created by PhpStorm.
- * User: leo
- * Date: 2018/8/2
- * Time: 上午10:32
- */
- namespace common\helpers\bonus;
- use common\helpers\Cache;
- use common\helpers\Date;
- use common\helpers\snowflake\SnowFake;
- use common\helpers\Tool;
- use common\models\CalcBonus;
- use common\models\CalcBonusBD;
- use common\models\CalcBonusBS;
- use common\models\CalcBonusQuarter;
- use common\models\CalcBonusGarage;
- use common\models\CalcBonusQY;
- use common\models\CalcBonusTG;
- use common\models\CalcBonusTourism;
- use common\models\CalcBonusVilla;
- use common\models\PerfMonth;
- use common\models\PerfPeriod;
- use common\models\Period;
- use common\models\ServeProcess;
- use common\models\StarCrownLevel;
- use yii\base\BaseObject;
- use yii\base\StaticInstanceTrait;
- use yii\db\Query;
- class CalcServeBonusCalc extends BaseObject {
- use StaticInstanceTrait;
- private $_limit = 3000;
- private $_handleUserId;
- private $_sysConfig = [];
- private $_decLevelConfig = [];
- private $_empLevelConfig = [];
- private $_starCrownLevelConfig = [];
- private $_decRoleConfig = [];
- private $_errors = [];
- private $_periodNum = 0;
- private $_periodId;
- private $_isCalcMonth = 0;
- private $_calcYear;
- private $_calcMonth;
- private $_calcYearMonth;
- private $_calcMonthPeriodNumCount = 0;
- //pv
- private $_pvRatio;
- private $_calcZone = ['openTravel', 'openCar', 'openHouse'];
- const LOOP_FINISH = 1;
- const LOOP_CONTINUE = 2;
- const ORDER_TYPE_TO_FW_COEFFICIENT = [
- 'ZC' => 'fwCoefficientFromZc',
- 'FX_CASH' => 'fwCoefficientFromFxCash',
- 'FX_POINT' => 'fwCoefficientFromFxPoint',
- ];
- //最小报单pv
- const MIN_BD_PV = 980;
- public function init() {
- parent::init();
- }
- /**
- * 设置期数
- * @param int $periodNum
- * @return int
- */
- public function setPeriodNum(int $periodNum) {
- return $this->_periodNum = $periodNum;
- }
- /**
- * 获取期数
- * @return int
- */
- public function getPeriodNum() {
- return $this->_periodNum;
- }
- /**
- * 加入错误错误
- * @param $attr
- * @param $error
- */
- public function addError($attr, $error) {
- $this->_errors[$attr][] = $error;
- }
- /**
- * 获取错误信息
- * @return array
- */
- public function getErrors() {
- return $this->_errors;
- }
- /**
- * 开始执行结算步骤
- * @param $periodNum
- * @param null $handleUserId
- * @return bool
- */
- public function calcStep($periodNum, $handleUserId = null) {
- try {
- $this->_errors = [];
- $this->setPeriodNum($periodNum);
- $this->_handleUserId = $handleUserId;
- $t1 = microtime(true);
- // 初始化结算任务
- $this->initCalcTask();
- $t2 = microtime(true);
- ServeProcess::recordProcess($t1, $t2, $this->_periodNum, '奖金计算初始化配置', 'bonus');
- // 设置结算状态
- $this->setCalcStatus('start');
- // 清空所有本期结算用到的缓存
- CalcCache::clearCalcBonusCache($this->_periodNum);
- $t3 = microtime(true);
- ServeProcess::recordProcess($t2, $t3, $this->_periodNum, '设置结算状态,清空缓存', 'bonus');
- // 清空相关表数据
- $this->clearCalcTableData();
- $t4 = microtime(true);
- ServeProcess::recordProcess($t3, $t4, $this->_periodNum, '清空相关表数据', 'bonus');
- echo('初始化、清空缓存及相关数据表完成,耗时:' . round($t4 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- $this->_updatePercent(10);
- // 蓝星奖放到最前面 奖金计算开始
- if($this->_sysConfig['openBS']['VALUE']) {
- echo('计算蓝星奖开始,' . date('Y-m-d H:i:s', $t4) . PHP_EOL);
- // 调用存储过程,计算蓝星管理奖金
- $this->calcBsProcedure();
- // 将有蓝星管理奖金的用户加入到有奖金缓存用户中
- $this->calcBonusBsGL();
- if ($this->_isCalcMonth) {
- ServeProcess::recordProcess($t4, time(), $this->_periodNum, '计算蓝星奖', 'bonus');
- }
- }
- $t5 = microtime(true);
- echo('计算蓝星奖'.($this->_sysConfig['openBS']['VALUE']?'完成':'关闭').',耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- if($this->_sysConfig['openFW']['VALUE']) {
- $this->calcBonusBDStepOne();
- $this->calcBonusBDStepTwo();
- ServeProcess::recordProcess($t5, time(), $this->_periodNum, '计算服务奖', 'bonus');
- }
- $t6 = microtime(true);
- echo('计算服务奖'.($this->_sysConfig['openFW']['VALUE']?'完成':'关闭').',耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- $this->_updatePercent(15);
- // 销售奖/推广奖
- if($this->_sysConfig['openTG']['VALUE']) {
- $this->calcBonusTG();
- ServeProcess::recordProcess($t6, time(), $this->_periodNum, '计算推广奖', 'bonus');
- }
- $t7 = microtime(true);
- echo('计算推广奖'.($this->_sysConfig['openTG']['VALUE']?'完成':'关闭').',耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- $this->_updatePercent(20);
- // 绩效奖/团队奖
- if($this->_sysConfig['openQY']['VALUE']) {
- $this->calcBonusQY();
- ServeProcess::recordProcess($t7, time(), $this->_periodNum, '计算团队奖', 'bonus');
- }
- $t8 = microtime(true);
- echo('计算团队奖'.($this->_sysConfig['openQY']['VALUE']?'完成':'关闭').',耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- $this->_updatePercent(35);
- // $this->calcBonusTourism($this->_sysConfig['openTourism']);
- // $t21 = microtime(true);
- // echo('计算旅游奖' . ($this->_sysConfig['openTourism']['VALUE'] ? '完成' : '关闭') . ',耗时:' . round($t21 - $t20, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- // $this->_updatePercent(68);
- if($this->_sysConfig['openVilla']['VALUE']) {
- $this->calcBonusVilla();
- ServeProcess::recordProcess($t8, time(), $this->_periodNum, '计算房奖', 'bonus');
- }
- $t22 = microtime(true);
- echo('计算房奖' . ($this->_sysConfig['openVilla']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t22 - $t8, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
- $this->_updatePercent(45);
- if($this->_sysConfig['openGarage']['VALUE']) {
- $this->calcBonusGarage();
- ServeProcess::recordProcess($t22, time(), $this->_periodNum, '计算车奖', 'bonus');
- }
- $t23 = microtime(true);
- echo('计算车奖' . ($this->_sysConfig['openGarage']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t23 - $t22, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
- $this->_updatePercent(55);
- // 计算季度奖
- if($this->_sysConfig['openQuarter']['VALUE']) {
- $this->calcQuarter();
- ServeProcess::recordProcess($t23, time(), $this->_periodNum, '计算季度奖-调用存储过程', 'bonus');
- }
- $t24 = microtime(true);
- echo('计算季度奖' . ($this->_sysConfig['openQuarter']['VALUE'] ? '开启调用存储过程' : '关闭').',耗时:' . round($t24 - $t23, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
- // 将用户写入缓存
- if($this->_sysConfig['openQuarter']['VALUE']) {
- $this->calcQuarterUser();
- ServeProcess::recordProcess($t23, time(), $this->_periodNum, '计算季度奖-存入奖金会员', 'bonus');
- }
- $this->_updatePercent(65);
- $t25 = microtime(true);
- echo('计算季度奖' . ($this->_sysConfig['openQuarter']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t25 - $t24, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
- // 奖金写库
- $this->loopBonusUsers();
- $this->_updatePercent(75);
- $t30 = microtime(true);
- ServeProcess::recordProcess($t25, $t30, $this->_periodNum, '奖金写库', 'bonus');
- echo('奖金写库操作完成,耗时:' . round($t30 - $t25, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
- Period::updateCalcProcess(3, $this->_periodNum);
- ServeProcess::recordProcess($t30, time(), $this->_periodNum, '标记为计算完成', 'bonus');
- $this->_updatePercent(100);
- $t35 = microtime(true);
- echo('结算全部完成,共耗时:' . round($t35 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
- } catch (\Exception $e) {
- $this->errorCalcTask();
- $this->addError('calc', sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
- return false;
- }
- return true;
- }
- /**
- * 结算完成
- */
- public function endCalcTask() {
- $this->setCalcStatus('end');// 更新结算状态
- }
- /**
- * 结算错误
- */
- public function errorCalcTask() {
- CalcCache::clearCalcBonusCache($this->_periodNum); // 清空所有本期结算用到的缓存
- $this->setCalcStatus('fail'); // 更新结算状态
- }
- /**
- * 初始化结算任务
- * @throws \yii\db\Exception
- */
- public function initCalcTask() {
- $periodObj = Period::instance();
- $periodDataArr = $periodObj->setPeriodNum($this->_periodNum);
- if (empty($this->_periodNum)) {
- $this->_periodNum = $periodDataArr['PERIOD_NUM'];
- }
- $this->_sysConfig = Cache::getSystemConfig();
- $this->_decLevelConfig = Cache::getDecLevelConfig();
- $this->_empLevelConfig = Cache::getEmpLevelConfig();
- $this->_starCrownLevelConfig = Cache::getStarCrownLevelConfig();
- $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
- $this->_periodId = $periodDataArr['ID'];
- $this->_isCalcMonth = $periodObj->isCalcMonth($this->_periodNum);
- $this->_calcYear = $periodObj->getYear($this->_periodNum);
- $this->_calcMonth = $periodObj->getMonth($this->_periodNum);
- $this->_calcYearMonth = $periodObj->getYearMonth($this->_periodNum);
- }
- /**
- * 设置结算状态
- * @param $type
- * start|end|fail
- */
- public function setCalcStatus($type) {
- if ($type == 'start') {
- Period::updateAll(['IS_CALCING' => 1, 'IS_CALCULATED' => Period::CALCULATE_NONE, 'CALCULATE_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
- } elseif ($type == 'end') {
- Period::updateAll(['IS_CALCING' => 0, 'IS_CALCULATED' => Period::CALCULATE_FINISH, 'CALCULATED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
- } elseif ($type == 'fail') {
- Period::updateAll(['IS_CALCING' => 0, 'IS_CALCULATED' => Period::CALCULATE_FAIL, 'CALCULATED_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
- }
- }
- /**
- * 清空相关表数据
- */
- public function clearCalcTableData() {
- // 奖金表
- CalcBonus::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
- CalcBonusQY::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
- CalcBonusBD::pageDeleteAll('PERIOD_NUM='.$this->_periodNum); // 实际上是服务奖流水表
- CalcBonusTG::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
- // 月结时要清空的数据
- if ($this->_isCalcMonth) {
- CalcBonusTourism::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
- CalcBonusGarage::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
- CalcBonusVilla::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
- }
- }
- /**
- * 推广奖
- * @param int $offset
- * @return bool
- * @throws \yii\db\Exception
- */
- public function calcBonusTG(int $offset = 0) {
- $periodNum = $this->_periodNum;
- // 从缓存获取分页有业绩的会员信息
- $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
- if ($allData) {
- $insertBonusData = [];
- foreach ($allData as $userId) {
- // 从缓存中获取会员的业绩信息
- $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
- if( !$perfData ) continue;
- //个人业绩都算推荐奖,包括报单和复消、二次购物
- $perfPv = $perfData['PV_PCS_ZC'] ?? 0;
- if( $perfPv <= 0 ) continue;
- //推广奖使用个人PCS
- $recBonus = Tool::formatPrice($perfPv * $this->_sysConfig['recPercent']['VALUE'] / 100);
- if ($recBonus <= 0) continue;
- // 把对碰后的奖金存入缓存中
- $perfUserInfo = CalcCache::getUserInfo($userId, $periodNum);
- $bonusUserId = $perfUserInfo['REC_UID'] ?? '';
- if( !$bonusUserId ) continue;
- // 获取会员的报单级别
- $userBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
- CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_TG', $recBonus);
- //来源会员信息
- $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
- //推广奖流水
- $insertBonusData[] = [
- 'ID' => SnowFake::instance()->generateId(),
- 'USER_ID' => $bonusUserId,
- 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
- 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],,
- 'LAST_STATUS' => $userBaseInfo['STATUS'],
- 'FROM_USER_ID' => $userId,
- 'LAST_FROM_DEC_LV' => $fromUserInfo['DEC_LV'],
- 'LAST_FROM_EMP_LV' => $fromUserInfo['EMP_LV'],
- 'LAST_FROM_STATUS' => $fromUserInfo['STATUS'],
- 'ORI_BONUS' => $recBonus,
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'CREATED_AT' => Date::nowTime(),
- 'LOGS' => json_encode([
- 'perfPv' => $perfPv,
- 'recPercentConfig' => $this->_sysConfig['recPercent']['VALUE'],
- 'decLevel' => $userBaseInfo['DEC_LV'],
- ]),
- ];
- unset($perfData, $perfPv, $perfUserInfo, $recBonus, $bonusUserId, $userBaseInfo, $userId, $deductData, $fromUserInfo);
- }
- CalcBonusTG::batchInsert($insertBonusData);
- unset($allData, $insertBonusData);
- return $this->calcBonusTG($offset + $this->_limit);
- }
- unset($allData);
- return true;
- }
- /**
- * 服务奖第一步
- * @param int $offset
- * @return bool
- * @throws \yii\db\Exception
- */
- public function calcBonusBDStepOne(int $offset = 0) {
- echo sprintf("时间:[%s]服务奖第【1】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
- $periodNum = $this->_periodNum;
- // 从缓存获取分页有业绩的会员信息
- $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
- if ($allData) {
- $insertBonusData = [];
- foreach ($allData as $userId) {
- // 从缓存中获取会员的业绩信息
- $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
- if( !$perfData ) continue;
- $decRoleBonusFrom = explode(',', $this->_sysConfig['decRoleBonusFrom']['VALUE']);
- $validPvPcs = 0;
- foreach ($decRoleBonusFrom as $orderType) {
- $orderTypeName = sprintf('PV_PCS_%s', $orderType);
- $orderTypeValue = $perfData[$orderTypeName] ?? 0;
- $coefficientName = self::ORDER_TYPE_TO_FW_COEFFICIENT[$orderType];
- $coefficient = $this->_sysConfig[$coefficientName]['VALUE'] ?? 1;
- $validPvPcs += $orderTypeValue * $coefficient;
- unset($orderType, $orderTypeName, $orderTypeValue, $coefficientName, $coefficient);
- }
- unset($perfData, $decRoleBonusFrom);
- if ( $validPvPcs <= 0 ) continue;
- $this->loopRelationParentDo($userId, function ($parent) use($userId, $validPvPcs){
- //判断parent的报单中心级别 和 服务奖比例
- $bonusUserId = $parent['PARENT_UID'];
- //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
- $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
- $isDec = $bonusUserInfo['IS_DEC'];
- if($isDec == 0) return self::LOOP_CONTINUE;
- $decRoleId = $bonusUserInfo['DEC_ROLE_ID'];
- if( !$decRoleId ) return self::LOOP_CONTINUE;
- if( !isset($this->_decRoleConfig[$decRoleId]) ) return self::LOOP_CONTINUE;
- $parentDecRoleLevel = $this->_decRoleConfig[$decRoleId];
- $parentFwBonusPercent = $parentDecRoleLevel['FW_BONUS_PERCENT'] ?? 0;
- $cacheMaxPercent = CalcCache::fwMaxBonusPercent($userId, $this->_periodNum);
- $diffPercent = $parentFwBonusPercent - $cacheMaxPercent;
- if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
- $fwBonus = $validPvPcs * $diffPercent / 100;
- if( $fwBonus <= 0 ) return self::LOOP_CONTINUE;
- //给本人添加服务奖比例
- CalcCache::fwMaxBonusPercent($userId, $this->_periodNum, $parentFwBonusPercent);
- //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
- CalcCache::saveFwBonusList($bonusUserId, $this->_periodNum, $fwBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$validPvPcs]);
- CalcCache::addHasFwBonusUsers($bonusUserId, $this->_periodNum);
- unset($bonusUserId, $bonusUserInfo, $isDec, $decRoleId, $parentDecRoleLevel, $parentFwBonusPercent, $cacheMaxPercent, $diffPercent, $fwBonus);
- });
- unset($userId, $validPvPcs);
- }
- unset($allData, $insertBonusData);
- return $this->calcBonusBDStepOne($offset + $this->_limit);
- }
- unset($allData);
- return true;
- }
- /**
- * 服务奖第二步
- * @param int $offset
- * @return bool
- * @throws \yii\db\Exception
- */
- public function calcBonusBDStepTwo(int $offset = 0) {
- echo sprintf("时间:[%s]服务奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
- $allData = CalcCache::getHasFwBonusUsers($this->_periodNum, $offset, $this->_limit);
- if ($allData) {
- $insertBonusData = [];
- foreach ($allData as $userId) {
- $fwBonusData = CalcCache::getFwBonusList($userId, $this->_periodNum);
- if( !$fwBonusData ) continue;
- $fwBonus = $fwBonusData['fwBonus'] ?? 0;
- if( $fwBonus <=0 ) continue;
- //总金额限制
- $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
- CalcCache::bonus($userId, $this->_periodNum, 'BONUS_BD', $fwBonus);
- $decRoleId = $userBaseInfo['DEC_ROLE_ID'];
- $insertBonusData[] = [
- 'ID' => SnowFake::instance()->generateId(),
- 'USER_ID' => $userId,
- 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
- 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],
- 'LAST_STATUS' => $userBaseInfo['STATUS'],
- 'FROM_USER_ID' => $userId,
- 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
- 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
- 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
- 'AMOUNT' => $fwBonus,
- 'ORI_BONUS' => $fwBonus,
- 'RECONSUME_POINTS' => 0,
- 'MANAGE_TAX' => 0,
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'CREATED_AT' => Date::nowTime(),
- 'LOGS' => json_encode([
- 'decRoleId' => $decRoleId,
- ])
- ];
- unset($userId, $fwBonusData, $userBaseInfo, $decRoleId, $fwBonus);
- }
- CalcBonusBD::batchInsert($insertBonusData);
- unset($insertBonusData, $allData);
- $this->calcBonusBDStepTwo($offset + $this->_limit);
- }
- unset($allData);
- return true;
- }
- /**
- * 团队奖
- * @param int $offset
- * @return bool
- * @throws \yii\db\Exception
- */
- public function calcBonusQY(int $offset = 0) {
- echo sprintf("时间:[%s]团队奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
- $periodNum = $this->_periodNum;
- // 从缓存获取分页有业绩的会员信息
- $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
- if ($allData) {
- $insertBonusData = [];
- foreach ($allData as $userId) {
- // 从缓存中获取会员的业绩信息
- $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
- // 从缓存中获取会员的上期结余业绩信息
- $pervSurplusPerf = CalcCache::surplusPerf($userId, $periodNum);
- // 本期 + 上期结余
- $perfArr = [
- 'SURPLUS_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
- 'SURPLUS_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
- 'SURPLUS_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
- 'SURPLUS_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
- 'SURPLUS_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
- ];
- $oriPerfArr = [
- 'perfArr' => $perfArr,
- 'touchBonus' => 0,
- ];
- // 获取会员的报单级别
- $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
- $decLevelConfig = $this->_decLevelConfig;
- $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
- // 对碰
- $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $nowDecLevelConfig['QY_PERCENT']/100);
- $touchPerfArr = [];
- foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
- $touchPerfArr[$keyR] = $perfR;
- }
- // 对碰完成后把结余的业绩存入本期业绩缓存中
- CalcCache::nowPeriodPerf($userId, $periodNum, $touchPerfArr);
- //更新数据库
- PerfPeriod::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
- 'USER_ID' => $userId,
- 'PERIOD_NUM' => $periodNum,
- ]);
- if ($touchBonusArr['touchBonus'] <= 0) continue;
- $teamBonus = $touchBonusArr['touchBonus'];
- $capBonusQy = $teamBonus; // 封顶前的奖金
- //判断级别上限,个人奖金封顶限制
- $teamBonus = $this->declarationLevelCap($teamBonus, $userId, $userBaseInfo['DEC_LV']);
- if( $teamBonus <= 0 ) continue;
- // 将封顶前的金额加入用户奖金缓存中,此金额不能发放(总奖金,总实际奖金)
- CalcCache::bonus($userId, $periodNum, 'CAPPED_BONUS_QY', $capBonusQy);
- CalcCache::bonus($userId, $periodNum, 'BONUS_QY', $teamBonus);
- // TODO:取小腿值
- $payLeg = min([$perfArr['SURPLUS_1L'], $perfArr['SURPLUS_2L']]);
- // 计算荣衔星级
- $starCrown = StarCrownLevel::getStarCrown($payLeg);
- // 星级放入缓存
- CalcCache::addUserStarCrown($userId, $periodNum, $starCrown['ID']);
- //团队奖流水
- $insertBonusData[] = [
- 'ID' => SnowFake::instance()->generateId(),
- 'USER_ID' => $userId,
- 'ORI_CAPPED_BONUS_QY' => $capBonusQy,
- 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
- 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],
- 'LAST_CROWN_LV' => $starCrown['ID'],
- 'LAST_STATUS' => $userBaseInfo['STATUS'],
- 'ORI_BONUS' => $teamBonus,
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'CREATED_AT' => Date::nowTime(),
- 'LOGS' => json_encode([
- 'perfArr' => $perfArr,
- 'touchPerfArrOri' => $touchBonusArr['perfArr'],
- 'touchPerfArr' => $touchPerfArr,
- 'nowDecLevelConfig' => $nowDecLevelConfig,
- 'decLevel' => $userBaseInfo['DEC_LV'],
- ]),
- ];
- unset($perfData, $pervSurplusPerf, $perfArr, $oriPerfArr, $touchPerfArr, $userBaseInfo, $decLevelConfig, $touchBonusArr, $userId, $nowDecLevelConfig, $teamBonus, $deductData);
- }
- CalcBonusQY::batchInsert($insertBonusData);
- unset($allData, $insertBonusData);
- return $this->calcBonusQY($offset + $this->_limit);
- }
- unset($allData);
- return true;
- }
- /**
- * 季度奖计算
- */
- public function calcQuarter() {
- if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
- // echo('不是季结点,进这里,不计算季度奖'. PHP_EOL);
- return false;
- }
- $result = \Yii::$app->db->createCommand("CALL QtrCalc(:periodNum)")
- ->bindValue(':periodNum' , $this->_periodNum )
- ->execute();
- return $result;
- }
- // 执行蓝星管理奖金的存储过程
- public function calcBsProcedure() {
- if( !$this->_isCalcMonth ) {
- // 不是结算月,则不进行计算
- return false;
- }
- $result = \Yii::$app->db->createCommand("CALL CalcBlue(:periodNum)")
- ->bindValue(':periodNum' , $this->_periodNum )
- ->execute();
-
- return $result;
- }
- // 执行旅游奖的计算
- public function calcBonusTourism() {
- // 月结,如果不是月结点,则直接退出
- if (!$this->_isCalcMonth) {
- return true;
- }
- $bonusConfig = $this->_sysConfig['openTourism'];
- // 达标条件:聘级、级别、奖项比例
- $config = json_decode($bonusConfig['OPTIONS'], true);
- // 奖金总比例
- $mate = $bonusConfig['VALUE'] / 100;
- // 会员级别
- $minDecLevel = $config['OPTIONS']['declarationLevel'] ?? [];
- // 月度公司总PV
- $monthTotalPV = PerfMonth::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
- ->sum('PV_PCS');
- // 用于分发的奖金总数
- $transferAmount = $monthTotalPV * $mate;
- // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
- $userStarDirector = CalcBonusBS::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
- ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STATUS')
- ->groupBy('USER_ID')
- ->asArray()
- ->all();
- $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
- // 基于团队奖/绩效奖结果计算会员的StarCrown
- $userStarCrown = CalcBonusQY::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
- ->select('USER_ID,LAST_CROWN_LV')
- ->groupBy('USER_ID')
- ->asArray()
- ->all();
- $userStarCrownObj = array_column($userStarCrown, NULL, 'USER_ID');
- // 合并用户ID,去重
- $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
- // 奖金点数综合
- $bonusPointComplex = 0;
- $insertBonusData = [];
- foreach($bonusUsers as $userId) {
- // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
- $starDirectorPoint = $this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['TOURISM_PERCENT'] ?? 0;
- $starCrownPoint = $this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['TOURISM_PERCENT'] ?? 0;
- // 奖金比例:
- $bonusPoint = max($starDirectorPoint, $starCrownPoint);
- if ($bonusPoint <= 0) {
- continue;
- }
-
- $insertBonusData[] = [
- 'ID' => SnowFake::instance()->generateId(),
- 'USER_ID' => $userId,
- 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'],
- 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LAST_EMP_LV'],
- 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'],
- 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'],
- 'AMOUNT_STANDARD' => 0,
- 'POINT' => $bonusPoint,
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
- 'CREATED_AT' => Date::nowTime(),
- 'PERF' => $monthTotalPV,
- 'TRANSFER_RATE' => $mate,
- 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
- 'CAP_AMOUNT' => 0,
- 'POINT_COMPLEX' => 0,
- ];
- $bonusPointComplex += $bonusPoint;
- }
- // 数据写入总表
- if ($insertBonusData) {
- foreach ($insertBonusData as &$bonusData) {
- // 计算奖金
- $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
- if ($amount <= 0) {
- continue;
- }
- // 会员级别达到要求才会发放奖金
- if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
- // 放入缓存
- CalcCache::tourismBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
- }
- $bonusData['AMOUNT'] = $amount;
- $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
- }
- CalcBonusTourism::batchInsert($insertBonusData);
- }
- return true;
- }
- // 执行房奖的计算
- public function calcBonusVilla() {
- if (!$this->_isCalcMonth) {
- return true;
- }
- $bonusConfig = $this->_sysConfig['openVilla'];
- // 达标条件:聘级、级别、奖项比例
- $config = json_decode($bonusConfig['OPTIONS'], true);
- // 奖金总比例
- $mate = $bonusConfig['VALUE'] / 100;
- // 个人奖金封顶
- $capBonus = intval($this->_sysConfig['openVillaCap']['VALUE'] ?? 0);
- // 会员级别
- $minDecLevel = $config['declarationLevel'] ?? [];
- // 月度公司总PV
- $monthTotalPV = PerfMonth::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
- ->sum('PV_PCS');
- // 用于分发的奖金总数
- $transferAmount = $monthTotalPV * $mate;
- // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
- $subQuery = CalcBonusQY::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
- ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
- ->joinWith(['starCrown' => function($query) {
- $query->select(['LEVEL_NAME', 'SORT']);
- }])
- ->having(1)
- ->orderBy('USER_ID ASC, SORT DESC');
- $userStarCrownObj = (new Query())->from(['u' => $subQuery])->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')->groupBy('USER_ID')->indexBy('USER_ID')->all();
- // 奖金点数综合
- $bonusPointComplex = 0;
- $insertBonusData = [];
- foreach($userStarCrownObj as $item) {
- // 奖金比例
- $bonusPoint = $this->_starCrownLevelConfig[$item['LAST_CROWN_LV']]['VILLA_PERCENT'] ?? 0;
- if (!$bonusPoint) {
- continue;
- }
- // 会员级别达到要求才会发放奖金
- if ($item['LAST_DEC_LV'] != $minDecLevel) {
- continue;
- }
- $userBaseInfo = CalcCache::getUserInfo($item['USER_ID'], $this->_periodNum);
- $insertBonusData[] = [
- 'ID' => SnowFake::instance()->generateId(),
- 'USER_ID' => $item['USER_ID'],
- 'LAST_DEC_LV' => $item['LAST_DEC_LV'] ?? '',
- 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],
- 'LAST_STATUS' => $item['LAST_STATUS'] ?? 0,
- 'LAST_CROWN_LV' => $item['LAST_CROWN_LV'] ?? '',
- 'AMOUNT' => 0,
- 'POINT' => $bonusPoint,
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'CREATED_AT' => Date::nowTime(),
- 'PERF' => $monthTotalPV,
- 'TRANSFER_RATE' => $mate,
- 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
- 'CAP_AMOUNT' => 0,
- 'POINT_COMPLEX' => 0,
- ];
- $bonusPointComplex += $bonusPoint;
- }
- // 数据写入总表
- if ($insertBonusData) {
- // 计算个人奖金
- foreach ($insertBonusData as &$bonusData) {
- // 计算奖金
- $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
- if ($amount <= 0) {
- continue;
- }
- // 封顶前奖金数
- $capAmount = $amount;
- // 奖金数不能大于封顶值
- $amount = ($amount > $capBonus) ? $capBonus : $amount;
- $bonusData['AMOUNT'] = $amount;
- $bonusData['CAP_AMOUNT'] = $capAmount;
- $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
- // 放入缓存
- CalcCache::villaBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
- }
- CalcBonusVilla::batchInsert($insertBonusData);
- }
- return true;
- }
- // 执行车奖的计算
- public function calcBonusGarage() {
- // 月结,如果不是月结点,则直接退出
- if (!$this->_isCalcMonth) {
- return true;
- }
- $bonusConfig = $this->_sysConfig['openGarage'];
- // 达标条件:聘级、级别、奖项比例
- $config = json_decode($bonusConfig['OPTIONS'], true);
- // 奖金总比例
- $mate = $bonusConfig['VALUE'] / 100;
- // 会员级别
- $minDecLevel = $config['declarationLevel'] ?? [];
- // 个人奖金封顶
- $capBonus = intval($this->_sysConfig['openGarageCap']['VALUE'] ?? 0);
- // 月度公司总PV
- $monthTotalPV = PerfMonth::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
- ->sum('PV_PCS');
- // 用于分发的奖金总数
- $transferAmount = $monthTotalPV * $mate;
- // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
- $userStarDirector = CalcBonusBS::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH = :CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
- ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_STATUS')
- ->groupBy('USER_ID')
- ->asArray()
- ->all();
- $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
- // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
- $subQuery = CalcBonusQY::find()
- ->yearMonth($this->_calcYearMonth)
- ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
- ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
- ->joinWith(['starCrown' => function($query) {
- $query->select(['LEVEL_NAME', 'SORT']);
- }])
- ->having(1)
- ->orderBy('USER_ID ASC, SORT DESC');
- $userStarCrownObj = (new Query())->from(['u' => $subQuery])->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')->groupBy('USER_ID')->indexBy('USER_ID')->all();
-
- // 合并用户ID,去重
- $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
- sort($bonusUsers);
- // 奖金点数综合
- $bonusPointComplex = 0;
- $insertBonusData = [];
- foreach($bonusUsers as $userId) {
- // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
- $starDirectorPoint = !isset($userStarDirectorObj[$userId]['LEVEL_ID']) ? 0 : ($this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['GARAGE_PERCENT'] ?? 0);
- $starCrownPoint = !isset($userStarCrownObj[$userId]['LAST_CROWN_LV']) ? 0: ($this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['GARAGE_PERCENT'] ?? 0);
- // 奖金比例:
- $bonusPoint = max($starDirectorPoint, $starCrownPoint);
- if ($bonusPoint <= 0) {
- continue;
- }
- // 会员级别达到要求才会发放奖金
- $lastDecLv = $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? '');
- if ($lastDecLv != $minDecLevel) {
- continue;
- }
- $insertBonusData[] = [
- 'ID' => SnowFake::instance()->generateId(),
- 'USER_ID' => $userId,
- 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? ''),
- 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LEVEL_ID'] ?? '',
- 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'] ?? ($userStarCrownObj[$userId]['LAST_STATUS'] ?? 1),
- 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'] ?? '',
- 'AMOUNT' => 0,
- 'POINT' => $bonusPoint,
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'CREATED_AT' => Date::nowTime(),
- 'PERF' => $monthTotalPV,
- 'TRANSFER_RATE' => $mate,
- 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
- 'CAP_AMOUNT' => 0,
- 'POINT_COMPLEX' => 0,
- ];
- $bonusPointComplex += $bonusPoint;
- }
- // 数据写入总表
- if ($insertBonusData) {
- foreach ($insertBonusData as &$bonusData) {
- // 计算奖金
- $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
- if ($amount <= 0) {
- continue;
- }
- // 封顶前奖金数
- $capAmount = $amount;
- // 奖金数不能大于封顶值
- $amount = ($amount > $capBonus) ? $capBonus : $amount;
- $bonusData['AMOUNT'] = $amount;
- $bonusData['CAP_AMOUNT'] = $capAmount;
- $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
- // 放入缓存
- CalcCache::garageBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
- }
- CalcBonusGarage::batchInsert($insertBonusData);
- }
- return true;
- }
- /**
- * 季度奖写用户缓存
- */
- public function calcQuarterUser(int $offset = 0) {
- if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
- // 不是结算月,则不进行计算
- return false;
- }
- $allData = CalcBonusQuarter::finduseDbCalc()
- ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
- ->groupBy('USER_ID')
- ->offset($offset)
- ->limit($this->_limit)
- ->asArray()
- ->all();
- if ($allData){
- // 达标条件:会员级别:钻卡
- $config = json_decode($this->_sysConfig['openQuarter']['OPTIONS'], true);
- $minDecLevel = $config['declarationLevel'] ?? [];
- foreach ($allData as $user) {
- // 管理奖钻卡发放
- if ($user['LAST_DEC_LV'] == $minDecLevel) {
- CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_QUARTER', $user['ORI_BONUS']);
- }
- }
- return $this->calcQuarterUser($offset + $this->_limit);
- }
- unset($allData);
- return true;
- }
- /**
- * 蓝星管理奖金未拆分
- */
- public function calcBonusBsGL(int $offset = 0) {
- if( !$this->_isCalcMonth ) {
- // 不是结算月,则不进行计算
- return false;
- }
- // 从缓存获取分页有收入的会员信息
- $allData = CalcBonusBS::findUseDbCalc()
- ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
- ->groupBy('USER_ID')
- ->offset($offset)
- ->limit($this->_limit)
- ->asArray()
- ->all();
- if ($allData) {
- foreach ($allData as $user) {
- $fxStatus = $this->_isMonthPerfLimit($user['USER_ID']);
- if ($fxStatus) {
- CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS', $user['ORI_BONUS']);
- }
- }
- return $this->calcBonusBsGL($offset + $this->_limit);
- }
- unset($allData);
- return true;
- }
- /**
- * 对碰
- */
- public function touchPerf(array $oriPerfArr, array $perfArr, $percent, $loopTimes=1) {
- $resultArr = $oriPerfArr;
- foreach ($perfArr as $keyT => $perfT) {
- if ($perfT <= 0) {
- unset($perfArr[$keyT]);
- }
- }
- if (count($perfArr) >= 2 && $loopTimes < 6) {
- arsort($perfArr, SORT_NUMERIC);
- $onePerf = null;
- $oneKey = null;
- // $touchSurplusAmount = 0;
- $touchAmount = 0;
- // 前两个进行对碰
- foreach ($perfArr as $key => $perf) {
- if ($onePerf === null) {
- $oneKey = $key;
- $onePerf = $perf;
- } else {
- $touchSurplusAmount = $perf - $onePerf;
- if ($touchSurplusAmount > 0) {
- unset($perfArr[$oneKey]);
- $resultArr['perfArr'][$oneKey] = 0;
- $perfArr[$key] = $touchSurplusAmount;
- $touchAmount = $onePerf;
- } elseif ($touchSurplusAmount < 0) {
- unset($perfArr[$key]);
- $resultArr['perfArr'][$key] = 0;
- $perfArr[$oneKey] = abs($touchSurplusAmount);
- $touchAmount = $perf;
- } else {
- unset($perfArr[$oneKey], $perfArr[$key]);
- $resultArr['perfArr'][$oneKey] = 0;
- $resultArr['perfArr'][$key] = 0;
- $touchAmount = $perf;
- }
- break;
- }
- }
- $touchBonus = Tool::formatPrice($touchAmount * $percent);
- $resultArr['touchBonus'] += $touchBonus;
- foreach ($perfArr as $keyR => $perfR) {
- $resultArr['perfArr'][$keyR] = $perfR;
- }
- return $this->touchPerf($resultArr, $perfArr, $percent, $loopTimes+1);
- }
- return $resultArr;
- }
- /**
- * 循环父级并执行回调函数
- * @param $userId
- * @param callable $callbackFunc
- * @param int $offset
- * @return bool
- */
- public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
- $allParents = Cache::getAllNetworkParents($userId);
- $allData = array_slice($allParents, $offset, $this->_limit);
- unset($allParents);
- if ($allData) {
- foreach ($allData as $data) {
- $funcResult = $callbackFunc($data);
- if ($funcResult === self::LOOP_FINISH) {
- return true;
- } elseif ($funcResult === self::LOOP_CONTINUE) {
- continue;
- }
- unset($data, $funcResult);
- }
- unset($allData);
- return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
- }
- return true;
- }
- /**
- * 循环推荐网络的父级
- * @param $userId
- * @param callable $callbackFunc
- * @param int $offset
- * @return bool
- */
- public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
- $allParents = Cache::getAllRelationParents($userId);
- $allData = array_slice($allParents, $offset, $this->_limit);
- unset($allParents);
- if ($allData) {
- foreach ($allData as $data) {
- $funcResult = $callbackFunc($data);
- if ($funcResult === self::LOOP_FINISH) {
- return true;
- } elseif ($funcResult === self::LOOP_CONTINUE) {
- continue;
- }
- unset($data, $funcResult);
- }
- unset($allData);
- return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
- }
- return true;
- }
- /**
- * 按级别的收入上限
- * 新的需求调整: 改成不按月进行限制,并且去掉vip奖
- * @param $bonus
- * @param $userId
- * @param $declarationLevel
- * @return float
- */
- public function declarationLevelCap($bonus, $userId, $declarationLevel) {
- $decLevelConfig = $this->_decLevelConfig;
- $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
- unset($decLevelConfig);
- $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'];
- if( $bonus <= $maxGetBonus) {
- return $bonus;
- }else {
- return $maxGetBonus;
- }
- }
- /**
- * 扣除复消积分和管理费
- */
- public function deduct($userId, $bonus) {
- //判断是否达到了本月扣除复消的上限
- $cacheData = CalcCache::monthLastPeriodReconsumePoints($userId, $this->_periodNum, $this->_calcYearMonth);
- $bonusCache = CalcCache::bonus($userId, $this->_periodNum);
- $reConsumePointsTotal = $bonusCache['RECONSUME_POINTS'] + $cacheData['RECONSUME_POINTS_SUM'];
- $reConsumePointsCap = $this->_sysConfig['reConsumePointsMonthCap']['VALUE'];
- unset($cacheData, $bonusCache);
- $reConsumePoints = 0;
- if( $reConsumePointsTotal < $reConsumePointsCap ) {
- $reConsumePoints = $bonus * $this->_sysConfig['reConsumePointsPercent']['VALUE'] / 100;
- $reConsumePoints = min($reConsumePoints, $reConsumePointsCap-$reConsumePointsTotal);
- }
- unset($reConsumePointsTotal, $reConsumePointsCap);
- $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
- $surplus = $bonus - $reConsumePoints - $manageTax;
- return [
- 'reConsumePoints' => Tool::formatPrice($reConsumePoints),//复效积分
- 'manageTax' => Tool::formatPrice($manageTax),//管理费
- 'surplus' => Tool::formatPrice($surplus),//真实奖金
- ];
- }
- /**
- * 更新百分比并发送
- * @param $percent
- */
- private function _updatePercent($percent) {
- // 把数据写入数据库中
- Period::updateAll(['CALC_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
- \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'CALC_PERCENT']);
- }
- /**
- * 循环奖服务奖金会员,并入库
- */
- public function loopBonusUsers($offset = 0) {
- echo sprintf("时间:[%s]缓存奖金数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
- // 从缓存列表里面从底层往上倒序获取会员
- $allData = CalcCache::getHasBonusUsers($this->_periodNum, $offset, $this->_limit);
- if($allData){
- $insertDataBonus = [];
- foreach($allData as $userId){
- $tempBonusData = $this->bonusData($userId);
- if(!empty($tempBonusData['result'])){
- $insertDataBonus[] = $tempBonusData['result'];
- }
- unset($userId, $tempBonusData);
- }
- CalcBonus::batchInsert($insertDataBonus);
- unset($insertDataBonus, $allData);
- return $this->loopBonusUsers($offset + $this->_limit);
- }
- return true;
- }
- /**
- * 奖金入库
- */
- public function bonusData($userId) {
- // 车奖和房奖是积分,不参加到奖金累计中.季度奖季度发放,无最低消费限制
- $bonus = CalcCache::bonus($userId, $this->_periodNum);
- $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
- $perfData = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
- $tourismBonus = CalcCache::tourismBonus($userId, $this->_periodNum);
- $garageBonus = CalcCache::garageBonus($userId, $this->_periodNum);
- $villaBonus = CalcCache::villaBonus($userId, $this->_periodNum);
- $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
- $starCrownLv = CalcCache::getUserStarCrown($userId, $this->_periodNum);// 星级
- $bonusReal = '0.000'; // 总实发
- $deductConfig = Cache::getSystemConfig()['deductBonusItem']['OPTIONS'];
- $deductConfig = json_decode($deductConfig, true);
- $noDeduct = $deductConfig['noDeduct']; // 不需要扣除的奖金项
- $deduct = $deductConfig['deduct']; // 需要扣除的奖金项
- $totalDeductSum = '0.000'; // 需要扣除的奖金项,扣除完之后的实发金额
- $deductManageTax = '0.000'; // 扣除的管理费
- $deductReconsumePoints = '0.000'; // 扣除的复消积分
- foreach($noDeduct as $v) {
- $bonusReal+= $bonus[$v]; // 累加不需要扣除奖的项
- }
- foreach($deduct as $v) {
- $totalDeductSum+= $bonus[$v]; // 需要扣除的累计之和
- }
- if ($totalDeductSum > 0) {
- // 进行扣除管理费和复消积分
- $tempDeduct = $this->deduct($userId, $totalDeductSum);
- $totalDeductSum = $tempDeduct['surplus'];
- $deductManageTax = $tempDeduct['manageTax'];
- $deductReconsumePoints = $tempDeduct['reConsumePoints'];
- }
- $bonusReal += $totalDeductSum;
- $result = [
- 'USER_ID' => $userId,
- 'LAST_USER_NAME' => $baseInfo['USER_NAME'],
- 'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
- 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
- 'LAST_EMP_LV' => $baseInfo['LAST_EMP_LV'],
- 'LAST_CROWN_LV' => $starCrownLv ?? StarCrownLevel::getDefaultLevelId(),
- 'LAST_STATUS' => $baseInfo['STATUS'],
- 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
- 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
- 'LAST_CON_USER_NAME' => $baseInfo['CON_USER_NAME'],
- 'LAST_CON_REAL_NAME' => $baseInfo['CON_REAL_NAME'],
- // 'LAST_LOCATION' => $baseInfo['LOCATION'] ? $baseInfo['LOCATION'] : 1,
- //@todo
- 'LAST_LOCATION' => 1,
- 'BONUS_BD' => $bonus['BONUS_BD'],
- 'BONUS_TG' => $bonus['BONUS_TG'],
- 'BONUS_QY' => $bonus['BONUS_QY'],
- 'RECONSUME_POINTS' => $deductReconsumePoints,
- 'MANAGE_TAX' => $deductManageTax, // 管理费
- 'BONUS_INCOME'=>$bonus['INCOME_TOTAL'],
- 'BONUS_REAL'=> $bonusReal,
- 'BONUS_TOTAL'=>$bonus['BONUS_TOTAL'],
- 'ORI_BONUS_BD' => $bonus['ORI_BONUS_BD'],
- 'ORI_BONUS_TG' => $bonus['ORI_BONUS_TG'],
- 'ORI_BONUS_BS' => $bonus['ORI_BONUS_BS'], // 蓝星管理奖金原奖金
- 'ORI_BONUS_QY' => $bonus['ORI_BONUS_QY'],
- 'ORI_CAPPED_BONUS_QY' => $bonus['ORI_CAPPED_BONUS_QY'], // 团队奖封顶前的奖金
- 'BONUS_QUARTER' => $bonus['BONUS_QUARTER'],
- 'ORI_BONUS_QUARTER' => $bonus['ORI_BONUS_QUARTER'],
- 'BONUS_TOURISM' => $tourismBonus, // 旅游奖
- 'BONUS_VILLA' => $villaBonus, // 房奖
- 'BONUS_GARAGE' => $garageBonus, // 车奖
- //以下没有用
- 'PV_1L' => $perfData['PV_1L_TOUCH'],//TOUCH为碰业绩
- 'QY_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
- 'SURPLUS_1L' => $perfData['SURPLUS_1L'],
- 'PV_2L' => $perfData['PV_2L_TOUCH'],
- 'QY_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
- 'SURPLUS_2L' => $perfData['SURPLUS_2L'],
- 'PV_3L' => $perfData['PV_3L_TOUCH'],
- 'QY_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
- 'SURPLUS_3L' => $perfData['SURPLUS_3L'],
- 'PV_4L' => $perfData['PV_4L_TOUCH'],
- 'QY_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
- 'SURPLUS_4L' => $perfData['SURPLUS_4L'],
- 'PV_5L' => $perfData['PV_5L_TOUCH'],
- 'QY_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
- 'SURPLUS_5L' => $perfData['SURPLUS_5L'],
- 'PV_PCS' => $perfData['PV_PCS'],
- 'PV_TOUCH' => Tool::formatPrice($perfData['PV_1L_TOUCH'] + $perfData['PV_2L_TOUCH'] + $perfData['PV_3L_TOUCH'] + $perfData['PV_4L_TOUCH'] + $perfData['PV_5L_TOUCH'] + $perfData['PV_LS_TOUCH']),
- 'PERIOD_NUM' => $this->_periodNum,
- 'CALC_YEAR' => $this->_calcYear,
- 'CALC_MONTH' => $this->_calcYearMonth,
- 'CREATED_AT' => Date::nowTime(),
- ];
- $resend = [];
- unset($bonus, $realBonusGl, $bonusReal);
- return ['result'=>$result,'resend'=>$resend];
- }
- // 判断是否满足月最低消费
- public function _isMonthPerfLimit($userId) {
- $userMonthTotal = PerfMonth::find()->where(
- 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
- ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth]
- )
- ->asArray()
- ->one();
- $fxPvStatus = false;
- if (isset($userMonthTotal['PV_PCS']) && $userMonthTotal['PV_PCS'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
- $fxPvStatus = true;
- }
-
- return $fxPvStatus;
- }
- }
|