CalcServeBonusCalc.php 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/8/2
  6. * Time: 上午10:32
  7. */
  8. namespace common\helpers\bonus;
  9. use common\helpers\Cache;
  10. use common\helpers\Date;
  11. use common\helpers\snowflake\SnowFake;
  12. use common\helpers\Tool;
  13. use common\models\CalcBonus;
  14. use common\models\CalcBonusBD;
  15. use common\models\CalcBonusBS;
  16. use common\models\CalcBonusQuarter;
  17. use common\models\CalcBonusGarage;
  18. use common\models\CalcBonusQY;
  19. use common\models\CalcBonusTG;
  20. use common\models\CalcBonusTourism;
  21. use common\models\CalcBonusVilla;
  22. use common\models\PerfMonth;
  23. use common\models\PerfPeriod;
  24. use common\models\Period;
  25. use common\models\ServeProcess;
  26. use common\models\StarCrownLevel;
  27. use yii\base\BaseObject;
  28. use yii\base\StaticInstanceTrait;
  29. use yii\db\Query;
  30. class CalcServeBonusCalc extends BaseObject {
  31. use StaticInstanceTrait;
  32. private $_limit = 3000;
  33. private $_handleUserId;
  34. private $_sysConfig = [];
  35. private $_decLevelConfig = [];
  36. private $_empLevelConfig = [];
  37. private $_starCrownLevelConfig = [];
  38. private $_decRoleConfig = [];
  39. private $_errors = [];
  40. private $_periodNum = 0;
  41. private $_periodId;
  42. private $_isCalcMonth = 0;
  43. private $_calcYear;
  44. private $_calcMonth;
  45. private $_calcYearMonth;
  46. private $_calcMonthPeriodNumCount = 0;
  47. //pv
  48. private $_pvRatio;
  49. private $_calcZone = ['openTravel', 'openCar', 'openHouse'];
  50. const LOOP_FINISH = 1;
  51. const LOOP_CONTINUE = 2;
  52. const ORDER_TYPE_TO_FW_COEFFICIENT = [
  53. 'ZC' => 'fwCoefficientFromZc',
  54. 'FX_CASH' => 'fwCoefficientFromFxCash',
  55. 'FX_POINT' => 'fwCoefficientFromFxPoint',
  56. ];
  57. //最小报单pv
  58. const MIN_BD_PV = 980;
  59. public function init() {
  60. parent::init();
  61. }
  62. /**
  63. * 设置期数
  64. * @param int $periodNum
  65. * @return int
  66. */
  67. public function setPeriodNum(int $periodNum) {
  68. return $this->_periodNum = $periodNum;
  69. }
  70. /**
  71. * 获取期数
  72. * @return int
  73. */
  74. public function getPeriodNum() {
  75. return $this->_periodNum;
  76. }
  77. /**
  78. * 加入错误错误
  79. * @param $attr
  80. * @param $error
  81. */
  82. public function addError($attr, $error) {
  83. $this->_errors[$attr][] = $error;
  84. }
  85. /**
  86. * 获取错误信息
  87. * @return array
  88. */
  89. public function getErrors() {
  90. return $this->_errors;
  91. }
  92. /**
  93. * 开始执行结算步骤
  94. * @param $periodNum
  95. * @param null $handleUserId
  96. * @return bool
  97. */
  98. public function calcStep($periodNum, $handleUserId = null) {
  99. try {
  100. $this->_errors = [];
  101. $this->setPeriodNum($periodNum);
  102. $this->_handleUserId = $handleUserId;
  103. $t1 = microtime(true);
  104. // 初始化结算任务
  105. $this->initCalcTask();
  106. $t2 = microtime(true);
  107. ServeProcess::recordProcess($t1, $t2, $this->_periodNum, '奖金计算初始化配置', 'bonus');
  108. // 设置结算状态
  109. $this->setCalcStatus('start');
  110. // 清空所有本期结算用到的缓存
  111. CalcCache::clearCalcBonusCache($this->_periodNum);
  112. $t3 = microtime(true);
  113. ServeProcess::recordProcess($t2, $t3, $this->_periodNum, '设置结算状态,清空缓存', 'bonus');
  114. // 清空相关表数据
  115. $this->clearCalcTableData();
  116. $t4 = microtime(true);
  117. ServeProcess::recordProcess($t3, $t4, $this->_periodNum, '清空相关表数据', 'bonus');
  118. echo('初始化、清空缓存及相关数据表完成,耗时:' . round($t4 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  119. $this->_updatePercent(10);
  120. // 蓝星奖放到最前面 奖金计算开始
  121. if($this->_sysConfig['openGL']['VALUE']) {
  122. echo('计算蓝星奖开始,' . date('Y-m-d H:i:s', $t4) . PHP_EOL);
  123. // 调用存储过程,计算蓝星管理奖金
  124. $this->calcBsProcedure();
  125. // 将有蓝星管理奖金的用户加入到有奖金缓存用户中
  126. $this->calcBonusBsGL();
  127. // 将有【蓝星业绩奖金】的用户加入到有奖金缓存用户中
  128. // $this->calcBonusBsYJ();
  129. // // 将有【蓝星管理奖金】的用户加入到有奖金缓存用户中
  130. // $this->calcBonusBsGL();
  131. if ($this->_isCalcMonth) {
  132. ServeProcess::recordProcess($t4, time(), $this->_periodNum, '计算蓝星奖', 'bonus');
  133. }
  134. }
  135. $t5 = microtime(true);
  136. echo('计算蓝星奖'.($this->_sysConfig['openGL']['VALUE']?'完成':'关闭').',耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  137. if($this->_sysConfig['openFW']['VALUE']) {
  138. $this->calcBonusBDStepOne();
  139. $this->calcBonusBDStepTwo();
  140. ServeProcess::recordProcess($t5, time(), $this->_periodNum, '计算服务奖', 'bonus');
  141. }
  142. $t6 = microtime(true);
  143. echo('计算服务奖'.($this->_sysConfig['openFW']['VALUE']?'完成':'关闭').',耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  144. $this->_updatePercent(15);
  145. // 销售奖/推广奖
  146. if($this->_sysConfig['openTG']['VALUE']) {
  147. $this->calcBonusTG();
  148. ServeProcess::recordProcess($t6, time(), $this->_periodNum, '计算推广奖', 'bonus');
  149. }
  150. $t7 = microtime(true);
  151. echo('计算推广奖'.($this->_sysConfig['openTG']['VALUE']?'完成':'关闭').',耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  152. $this->_updatePercent(20);
  153. // 绩效奖/团队奖
  154. if($this->_sysConfig['openQY']['VALUE']) {
  155. $this->calcBonusQY();
  156. ServeProcess::recordProcess($t7, time(), $this->_periodNum, '计算团队奖', 'bonus');
  157. }
  158. $t8 = microtime(true);
  159. echo('计算团队奖'.($this->_sysConfig['openQY']['VALUE']?'完成':'关闭').',耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  160. $this->_updatePercent(35);
  161. // $this->calcBonusTourism($this->_sysConfig['openTourism']);
  162. // $t21 = microtime(true);
  163. // echo('计算旅游奖' . ($this->_sysConfig['openTourism']['VALUE'] ? '完成' : '关闭') . ',耗时:' . round($t21 - $t20, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  164. // $this->_updatePercent(68);
  165. if($this->_sysConfig['openVilla']['VALUE']) {
  166. $this->calcBonusVilla();
  167. ServeProcess::recordProcess($t8, time(), $this->_periodNum, '计算房奖', 'bonus');
  168. }
  169. $t22 = microtime(true);
  170. echo('计算房奖' . ($this->_sysConfig['openVilla']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t22 - $t8, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  171. $this->_updatePercent(45);
  172. if($this->_sysConfig['openGarage']['VALUE']) {
  173. $this->calcBonusGarage();
  174. ServeProcess::recordProcess($t22, time(), $this->_periodNum, '计算车奖', 'bonus');
  175. }
  176. $t23 = microtime(true);
  177. echo('计算车奖' . ($this->_sysConfig['openGarage']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t23 - $t22, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  178. $this->_updatePercent(55);
  179. // 计算季度奖
  180. if($this->_sysConfig['openQuarter']['VALUE']) {
  181. $this->calcQuarter();
  182. ServeProcess::recordProcess($t23, time(), $this->_periodNum, '计算季度奖-调用存储过程', 'bonus');
  183. }
  184. $t24 = microtime(true);
  185. echo('计算季度奖' . ($this->_sysConfig['openQuarter']['VALUE'] ? '开启调用存储过程' : '关闭').',耗时:' . round($t24 - $t23, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  186. // 将用户写入缓存
  187. if($this->_sysConfig['openQuarter']['VALUE']) {
  188. $this->calcQuarterUser();
  189. ServeProcess::recordProcess($t23, time(), $this->_periodNum, '计算季度奖-存入奖金会员', 'bonus');
  190. }
  191. $this->_updatePercent(65);
  192. $t25 = microtime(true);
  193. echo('计算季度奖' . ($this->_sysConfig['openQuarter']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t25 - $t24, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  194. // 奖金写库
  195. $this->loopBonusUsers();
  196. $this->_updatePercent(75);
  197. $t30 = microtime(true);
  198. ServeProcess::recordProcess($t25, $t30, $this->_periodNum, '奖金写库', 'bonus');
  199. echo('奖金写库操作完成,耗时:' . round($t30 - $t25, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  200. Period::updateCalcProcess(3, $this->_periodNum);
  201. ServeProcess::recordProcess($t30, time(), $this->_periodNum, '标记为计算完成', 'bonus');
  202. $this->_updatePercent(100);
  203. $t35 = microtime(true);
  204. echo('结算全部完成,共耗时:' . round($t35 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  205. } catch (\Exception $e) {
  206. $this->errorCalcTask();
  207. $this->addError('calc', sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
  208. return false;
  209. }
  210. return true;
  211. }
  212. /**
  213. * 结算完成
  214. */
  215. public function endCalcTask() {
  216. // 更新结算状态
  217. $this->setCalcStatus('end');
  218. }
  219. /**
  220. * 结算错误
  221. */
  222. public function errorCalcTask() {
  223. // 清空所有本期结算用到的缓存
  224. CalcCache::clearCalcBonusCache($this->_periodNum);
  225. // 更新结算状态
  226. $this->setCalcStatus('fail');
  227. }
  228. /**
  229. * 初始化结算任务
  230. * @throws \yii\db\Exception
  231. */
  232. public function initCalcTask() {
  233. $periodObj = Period::instance();
  234. $periodDataArr = $periodObj->setPeriodNum($this->_periodNum);
  235. if (empty($this->_periodNum)) {
  236. $this->_periodNum = $periodDataArr['PERIOD_NUM'];
  237. }
  238. $this->_sysConfig = Cache::getSystemConfig();
  239. $this->_decLevelConfig = Cache::getDecLevelConfig();
  240. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  241. $this->_starCrownLevelConfig = Cache::getStarCrownLevelConfig();
  242. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  243. $this->_periodId = $periodDataArr['ID'];
  244. $this->_isCalcMonth = $periodObj->isCalcMonth($this->_periodNum);
  245. $this->_calcYear = $periodObj->getYear($this->_periodNum);
  246. $this->_calcMonth = $periodObj->getMonth($this->_periodNum);
  247. $this->_calcYearMonth = $periodObj->getYearMonth($this->_periodNum);
  248. }
  249. /**
  250. * 设置结算状态
  251. * @param $type
  252. * start|end|fail
  253. */
  254. public function setCalcStatus($type) {
  255. if ($type == 'start') {
  256. Period::updateAll(['IS_CALCING' => 1, 'IS_CALCULATED' => Period::CALCULATE_NONE, 'CALCULATE_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  257. } elseif ($type == 'end') {
  258. Period::updateAll(['IS_CALCING' => 0, 'IS_CALCULATED' => Period::CALCULATE_FINISH, 'CALCULATED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  259. } elseif ($type == 'fail') {
  260. Period::updateAll(['IS_CALCING' => 0, 'IS_CALCULATED' => Period::CALCULATE_FAIL, 'CALCULATED_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  261. }
  262. }
  263. /**
  264. * 清空相关表数据
  265. */
  266. public function clearCalcTableData() {
  267. // 奖金表
  268. CalcBonus::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  269. CalcBonusQY::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  270. CalcBonusBD::pageDeleteAll('PERIOD_NUM='.$this->_periodNum); // 实际上是服务奖流水表
  271. CalcBonusTG::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  272. // 月结时要清空的数据
  273. if ($this->_isCalcMonth) {
  274. CalcBonusTourism::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  275. CalcBonusGarage::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  276. CalcBonusVilla::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  277. }
  278. }
  279. /**
  280. * 推广奖
  281. * @param int $offset
  282. * @return bool
  283. * @throws \yii\db\Exception
  284. */
  285. public function calcBonusTG(int $offset = 0) {
  286. $periodNum = $this->_periodNum;
  287. // 从缓存获取分页有业绩的会员信息
  288. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  289. if ($allData) {
  290. $insertBonusData = [];
  291. foreach ($allData as $userId) {
  292. // 从缓存中获取会员的业绩信息
  293. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  294. if( !$perfData ) continue;
  295. //个人业绩都算推荐奖,包括报单和复消、二次购物
  296. $perfPv = $perfData['PV_PCS_ZC'] ?? 0;
  297. if( $perfPv <= 0 ) continue;
  298. //推广奖使用个人PCS
  299. $recBonus = Tool::formatPrice($perfPv * $this->_sysConfig['recPercent']['VALUE'] / 100);
  300. if ($recBonus <= 0) continue;
  301. // 把对碰后的奖金存入缓存中
  302. $perfUserInfo = CalcCache::getUserInfo($userId, $periodNum);
  303. $bonusUserId = $perfUserInfo['REC_UID'] ?? '';
  304. if( !$bonusUserId ) continue;
  305. // 获取会员的报单级别
  306. $userBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  307. //扣除相应的复消积分和管理费
  308. $deductData = $this->deduct($bonusUserId, $recBonus);
  309. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_TG', $recBonus, $deductData);
  310. //来源会员信息
  311. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  312. //推广奖流水
  313. $insertBonusData[] = [
  314. 'ID' => SnowFake::instance()->generateId(),
  315. 'USER_ID' => $bonusUserId,
  316. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  317. 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],,
  318. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  319. 'FROM_USER_ID' => $userId,
  320. 'LAST_FROM_DEC_LV' => $fromUserInfo['DEC_LV'],
  321. 'LAST_FROM_EMP_LV' => $fromUserInfo['EMP_LV'],
  322. 'LAST_FROM_STATUS' => $fromUserInfo['STATUS'],
  323. 'AMOUNT' => $deductData['surplus'],
  324. 'ORI_BONUS' => $recBonus,
  325. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  326. 'MANAGE_TAX' => $deductData['manageTax'],
  327. 'PERIOD_NUM' => $this->_periodNum,
  328. 'CALC_YEAR' => $this->_calcYear,
  329. 'CALC_MONTH' => $this->_calcYearMonth,
  330. 'CREATED_AT' => Date::nowTime(),
  331. 'LOGS' => json_encode([
  332. 'perfPv' => $perfPv,
  333. 'recPercentConfig' => $this->_sysConfig['recPercent']['VALUE'],
  334. 'recNum' => $userBaseInfo['REC_NUM'],
  335. 'decAmount' => $userBaseInfo['ZC_AMOUNT'],
  336. 'decLevel' => $userBaseInfo['DEC_LV'],
  337. 'bonusTotalLimit' => [
  338. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  339. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  340. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  341. ],
  342. ]),
  343. ];
  344. unset($perfData, $perfPv, $perfUserInfo, $recBonus, $bonusUserId, $userBaseInfo, $userId, $deductData, $fromUserInfo);
  345. }
  346. CalcBonusTG::batchInsert($insertBonusData);
  347. unset($allData, $insertBonusData);
  348. return $this->calcBonusTG($offset + $this->_limit);
  349. }
  350. unset($allData);
  351. return true;
  352. }
  353. /**
  354. * 服务奖第一步
  355. * @param int $offset
  356. * @return bool
  357. * @throws \yii\db\Exception
  358. */
  359. public function calcBonusBDStepOne(int $offset = 0) {
  360. echo sprintf("时间:[%s]服务奖第【1】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  361. $periodNum = $this->_periodNum;
  362. // 从缓存获取分页有业绩的会员信息
  363. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  364. if ($allData) {
  365. $insertBonusData = [];
  366. foreach ($allData as $userId) {
  367. // 从缓存中获取会员的业绩信息
  368. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  369. if( !$perfData ) continue;
  370. $decRoleBonusFrom = explode(',', $this->_sysConfig['decRoleBonusFrom']['VALUE']);
  371. $validPvPcs = 0;
  372. foreach ($decRoleBonusFrom as $orderType) {
  373. $orderTypeName = sprintf('PV_PCS_%s', $orderType);
  374. $orderTypeValue = $perfData[$orderTypeName] ?? 0;
  375. $coefficientName = self::ORDER_TYPE_TO_FW_COEFFICIENT[$orderType];
  376. $coefficient = $this->_sysConfig[$coefficientName]['VALUE'] ?? 1;
  377. $validPvPcs += $orderTypeValue * $coefficient;
  378. unset($orderType, $orderTypeName, $orderTypeValue, $coefficientName, $coefficient);
  379. }
  380. unset($perfData, $decRoleBonusFrom);
  381. if ( $validPvPcs <= 0 ) continue;
  382. $this->loopRelationParentDo($userId, function ($parent) use($userId, $validPvPcs){
  383. //判断parent的报单中心级别 和 服务奖比例
  384. $bonusUserId = $parent['PARENT_UID'];
  385. //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  386. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  387. $isDec = $bonusUserInfo['IS_DEC'];
  388. if($isDec == 0) return self::LOOP_CONTINUE;
  389. $decRoleId = $bonusUserInfo['DEC_ROLE_ID'];
  390. if( !$decRoleId ) return self::LOOP_CONTINUE;
  391. if( !isset($this->_decRoleConfig[$decRoleId]) ) return self::LOOP_CONTINUE;
  392. $parentDecRoleLevel = $this->_decRoleConfig[$decRoleId];
  393. $parentFwBonusPercent = $parentDecRoleLevel['FW_BONUS_PERCENT'] ?? 0;
  394. $cacheMaxPercent = CalcCache::fwMaxBonusPercent($userId, $this->_periodNum);
  395. $diffPercent = $parentFwBonusPercent - $cacheMaxPercent;
  396. if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
  397. $fwBonus = $validPvPcs * $diffPercent / 100;
  398. if( $fwBonus <= 0 ) return self::LOOP_CONTINUE;
  399. //给本人添加服务奖比例
  400. CalcCache::fwMaxBonusPercent($userId, $this->_periodNum, $parentFwBonusPercent);
  401. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  402. CalcCache::saveFwBonusList($bonusUserId, $this->_periodNum, $fwBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$validPvPcs]);
  403. CalcCache::addHasFwBonusUsers($bonusUserId, $this->_periodNum);
  404. unset($bonusUserId, $bonusUserInfo, $isDec, $decRoleId, $parentDecRoleLevel, $parentFwBonusPercent, $cacheMaxPercent, $diffPercent, $fwBonus);
  405. });
  406. unset($userId, $validPvPcs);
  407. }
  408. unset($allData, $insertBonusData);
  409. return $this->calcBonusBDStepOne($offset + $this->_limit);
  410. }
  411. unset($allData);
  412. return true;
  413. }
  414. /**
  415. * 服务奖第二步
  416. * @param int $offset
  417. * @return bool
  418. * @throws \yii\db\Exception
  419. */
  420. public function calcBonusBDStepTwo(int $offset = 0) {
  421. echo sprintf("时间:[%s]服务奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  422. $allData = CalcCache::getHasFwBonusUsers($this->_periodNum, $offset, $this->_limit);
  423. if ($allData) {
  424. $insertBonusData = [];
  425. foreach ($allData as $userId) {
  426. $fwBonusData = CalcCache::getFwBonusList($userId, $this->_periodNum);
  427. if( !$fwBonusData ) continue;
  428. $fwBonus = $fwBonusData['fwBonus'] ?? 0;
  429. if( $fwBonus <=0 ) continue;
  430. //总金额限制
  431. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  432. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_BD', $fwBonus);
  433. $decRoleId = $userBaseInfo['DEC_ROLE_ID'];
  434. $insertBonusData[] = [
  435. 'ID' => SnowFake::instance()->generateId(),
  436. 'USER_ID' => $userId,
  437. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  438. 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],
  439. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  440. 'FROM_USER_ID' => $userId,
  441. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  442. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  443. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  444. 'AMOUNT' => $fwBonus,
  445. 'ORI_BONUS' => $fwBonus,
  446. 'RECONSUME_POINTS' => 0,
  447. 'MANAGE_TAX' => 0,
  448. 'PERIOD_NUM' => $this->_periodNum,
  449. 'CALC_YEAR' => $this->_calcYear,
  450. 'CALC_MONTH' => $this->_calcYearMonth,
  451. 'CREATED_AT' => Date::nowTime(),
  452. 'LOGS' => json_encode([
  453. 'decRoleId' => $decRoleId,
  454. ])
  455. ];
  456. unset($userId, $fwBonusData, $userBaseInfo, $decRoleId, $fwBonus);
  457. }
  458. CalcBonusBD::batchInsert($insertBonusData);
  459. unset($insertBonusData, $allData);
  460. $this->calcBonusBDStepTwo($offset + $this->_limit);
  461. }
  462. unset($allData);
  463. return true;
  464. }
  465. /**
  466. * 团队奖
  467. * @param int $offset
  468. * @return bool
  469. * @throws \yii\db\Exception
  470. */
  471. public function calcBonusQY(int $offset = 0) {
  472. echo sprintf("时间:[%s]团队奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  473. $periodNum = $this->_periodNum;
  474. // 从缓存获取分页有业绩的会员信息
  475. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  476. if ($allData) {
  477. $insertBonusData = [];
  478. foreach ($allData as $userId) {
  479. // 从缓存中获取会员的业绩信息
  480. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  481. // 从缓存中获取会员的上期结余业绩信息
  482. $pervSurplusPerf = CalcCache::surplusPerf($userId, $periodNum);
  483. // 本期 + 上期结余
  484. $perfArr = [
  485. 'SURPLUS_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  486. 'SURPLUS_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  487. 'SURPLUS_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  488. 'SURPLUS_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  489. 'SURPLUS_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  490. ];
  491. $oriPerfArr = [
  492. 'perfArr' => $perfArr,
  493. 'touchBonus' => 0,
  494. ];
  495. // 获取会员的报单级别
  496. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  497. $decLevelConfig = $this->_decLevelConfig;
  498. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  499. // 对碰
  500. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $nowDecLevelConfig['QY_PERCENT']/100);
  501. $touchPerfArr = [];
  502. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  503. $touchPerfArr[$keyR] = $perfR;
  504. }
  505. // 对碰完成后把结余的业绩存入本期业绩缓存中
  506. CalcCache::nowPeriodPerf($userId, $periodNum, $touchPerfArr);
  507. //更新数据库
  508. PerfPeriod::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  509. 'USER_ID' => $userId,
  510. 'PERIOD_NUM' => $periodNum,
  511. ]);
  512. if ($touchBonusArr['touchBonus'] <= 0) continue;
  513. $teamBonus = $touchBonusArr['touchBonus'];
  514. $capBonusQy = $teamBonus; // 封顶前的奖金
  515. //判断级别上限,个人奖金封顶限制
  516. $teamBonus = $this->declarationLevelCap($teamBonus, $userId, $userBaseInfo['DEC_LV']);
  517. if( $teamBonus <= 0 ) continue;
  518. // 将封顶前的金额加入用户奖金缓存中,此金额不能发放(总奖金,总实际奖金)
  519. CalcCache::bonus($userId, $periodNum, 'CAPPED_BONUS_QY', $capBonusQy);
  520. //扣除相应的复消积分和管理费
  521. $deductData = $this->deduct($userId, $teamBonus);
  522. // 把对碰后的奖金存入缓存中
  523. CalcCache::bonus($userId, $periodNum, 'BONUS_QY', $teamBonus, $deductData);
  524. // TODO:取小腿值
  525. $payLeg = min([$perfArr['SURPLUS_1L'], $perfArr['SURPLUS_2L']]);
  526. // 计算荣衔星级
  527. $starCrown = StarCrownLevel::getStarCrown($payLeg);
  528. // 星级放入缓存
  529. CalcCache::addUserStarCrown($userId, $periodNum, $starCrown['ID']);
  530. //团队奖流水
  531. $insertBonusData[] = [
  532. 'ID' => SnowFake::instance()->generateId(),
  533. 'USER_ID' => $userId,
  534. 'ORI_CAPPED_BONUS_QY' => $capBonusQy,
  535. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  536. 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],
  537. 'LAST_CROWN_LV' => $starCrown['ID'],
  538. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  539. 'AMOUNT' => $deductData['surplus'],
  540. 'ORI_BONUS' => $teamBonus,
  541. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  542. 'MANAGE_TAX' => $deductData['manageTax'],
  543. 'PERIOD_NUM' => $this->_periodNum,
  544. 'CALC_YEAR' => $this->_calcYear,
  545. 'CALC_MONTH' => $this->_calcYearMonth,
  546. 'CREATED_AT' => Date::nowTime(),
  547. 'LOGS' => json_encode([
  548. 'perfArr' => $perfArr,
  549. 'touchPerfArrOri' => $touchBonusArr['perfArr'],
  550. 'touchPerfArr' => $touchPerfArr,
  551. 'nowDecLevelConfig' => $nowDecLevelConfig,
  552. 'decLevel' => $userBaseInfo['DEC_LV'],
  553. ]),
  554. ];
  555. unset($perfData, $pervSurplusPerf, $perfArr, $oriPerfArr, $touchPerfArr, $userBaseInfo, $decLevelConfig, $touchBonusArr, $userId, $nowDecLevelConfig, $teamBonus, $deductData);
  556. }
  557. CalcBonusQY::batchInsert($insertBonusData);
  558. unset($allData, $insertBonusData);
  559. return $this->calcBonusQY($offset + $this->_limit);
  560. }
  561. unset($allData);
  562. return true;
  563. }
  564. /**
  565. * 季度奖计算
  566. *
  567. */
  568. public function calcQuarter() {
  569. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  570. // echo('不是季结点,进这里,不计算季度奖'. PHP_EOL);
  571. return false;
  572. }
  573. $result = \Yii::$app->db->createCommand("CALL QtrCalc(:periodNum)")
  574. ->bindValue(':periodNum' , $this->_periodNum )
  575. ->execute();
  576. return $result;
  577. }
  578. // 执行蓝星管理奖金的存储过程
  579. public function calcBsProcedure() {
  580. if( !$this->_isCalcMonth ) {
  581. // 不是结算月,则不进行计算
  582. return false;
  583. }
  584. $result = \Yii::$app->db->createCommand("CALL CalcBlue(:periodNum)")
  585. ->bindValue(':periodNum' , $this->_periodNum )
  586. ->execute();
  587. return $result;
  588. }
  589. // 执行旅游奖的计算
  590. public function calcBonusTourism() {
  591. // 月结,如果不是月结点,则直接退出
  592. if (!$this->_isCalcMonth) {
  593. return true;
  594. }
  595. $bonusConfig = $this->_sysConfig['openTourism'];
  596. // 达标条件:聘级、级别、奖项比例
  597. $config = json_decode($bonusConfig['OPTIONS'], true);
  598. // 奖金总比例
  599. $mate = $bonusConfig['VALUE'] / 100;
  600. // 会员级别
  601. $minDecLevel = $config['OPTIONS']['declarationLevel'] ?? [];
  602. // 月度公司总PV
  603. $monthTotalPV = PerfMonth::find()
  604. ->yearMonth($this->_calcYearMonth)
  605. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  606. ->sum('PV_PCS');
  607. // 用于分发的奖金总数
  608. $transferAmount = $monthTotalPV * $mate;
  609. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  610. $userStarDirector = CalcBonusBS::find()
  611. ->yearMonth($this->_calcYearMonth)
  612. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  613. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STATUS')
  614. ->groupBy('USER_ID')
  615. ->asArray()
  616. ->all();
  617. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  618. // 基于团队奖/绩效奖结果计算会员的StarCrown
  619. $userStarCrown = CalcBonusQY::find()
  620. ->yearMonth($this->_calcYearMonth)
  621. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  622. ->select('USER_ID,LAST_CROWN_LV')
  623. ->groupBy('USER_ID')
  624. ->asArray()
  625. ->all();
  626. $userStarCrownObj = array_column($userStarCrown, NULL, 'USER_ID');
  627. // 合并用户ID,去重
  628. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  629. // 奖金点数综合
  630. $bonusPointComplex = 0;
  631. $insertBonusData = [];
  632. foreach($bonusUsers as $userId) {
  633. // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
  634. $starDirectorPoint = $this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['TOURISM_PERCENT'] ?? 0;
  635. $starCrownPoint = $this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['TOURISM_PERCENT'] ?? 0;
  636. // 奖金比例:
  637. $bonusPoint = max($starDirectorPoint, $starCrownPoint);
  638. if ($bonusPoint <= 0) {
  639. continue;
  640. }
  641. $insertBonusData[] = [
  642. 'ID' => SnowFake::instance()->generateId(),
  643. 'USER_ID' => $userId,
  644. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'],
  645. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LAST_EMP_LV'],
  646. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'],
  647. 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'],
  648. 'AMOUNT_STANDARD' => 0,
  649. 'POINT' => $bonusPoint,
  650. 'PERIOD_NUM' => $this->_periodNum,
  651. 'CALC_YEAR' => $this->_calcYear,
  652. 'CALC_MONTH' => $this->_calcYearMonth,
  653. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  654. 'CREATED_AT' => Date::nowTime(),
  655. 'PERF' => $monthTotalPV,
  656. 'TRANSFER_RATE' => $mate,
  657. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  658. 'CAP_AMOUNT' => 0,
  659. 'POINT_COMPLEX' => 0,
  660. ];
  661. $bonusPointComplex += $bonusPoint;
  662. }
  663. // 数据写入总表
  664. if ($insertBonusData) {
  665. foreach ($insertBonusData as &$bonusData) {
  666. // 计算奖金
  667. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  668. if ($amount <= 0) {
  669. continue;
  670. }
  671. // 会员级别达到要求才会发放奖金
  672. if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
  673. // 放入缓存
  674. CalcCache::tourismBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  675. // 加入月奖的会员
  676. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  677. }
  678. $bonusData['AMOUNT'] = $amount;
  679. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  680. }
  681. CalcBonusTourism::batchInsert($insertBonusData);
  682. }
  683. return true;
  684. }
  685. // 执行房奖的计算
  686. public function calcBonusVilla() {
  687. // 月结,如果不是月结点,则直接退出
  688. if (!$this->_isCalcMonth) {
  689. return true;
  690. }
  691. $bonusConfig = $this->_sysConfig['openVilla'];
  692. // 达标条件:聘级、级别、奖项比例
  693. $config = json_decode($bonusConfig['OPTIONS'], true);
  694. // 奖金总比例
  695. $mate = $bonusConfig['VALUE'] / 100;
  696. // 个人奖金封顶
  697. $capBonus = intval($this->_sysConfig['openVillaCap']['VALUE'] ?? 0);
  698. // 会员级别
  699. $minDecLevel = $config['declarationLevel'] ?? [];
  700. // 月度公司总PV
  701. $monthTotalPV = PerfMonth::find()
  702. ->yearMonth($this->_calcYearMonth)
  703. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  704. ->sum('PV_PCS');
  705. // 用于分发的奖金总数
  706. $transferAmount = $monthTotalPV * $mate;
  707. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  708. $subQuery = CalcBonusQY::find()
  709. ->yearMonth($this->_calcYearMonth)
  710. ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
  711. ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
  712. ->joinWith(['starCrown' => function($query) {
  713. $query->select(['LEVEL_NAME', 'SORT']);
  714. }])
  715. ->having(1)
  716. ->orderBy('USER_ID ASC, SORT DESC');
  717. $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();
  718. // 奖金点数综合
  719. $bonusPointComplex = 0;
  720. $insertBonusData = [];
  721. foreach($userStarCrownObj as $item) {
  722. // 奖金比例
  723. $bonusPoint = $this->_starCrownLevelConfig[$item['LAST_CROWN_LV']]['VILLA_PERCENT'] ?? 0;
  724. if (!$bonusPoint) {
  725. continue;
  726. }
  727. // 会员级别达到要求才会发放奖金
  728. if ($item['LAST_DEC_LV'] != $minDecLevel) {
  729. continue;
  730. }
  731. $userBaseInfo = CalcCache::getUserInfo($item['USER_ID'], $this->_periodNum);
  732. $insertBonusData[] = [
  733. 'ID' => SnowFake::instance()->generateId(),
  734. 'USER_ID' => $item['USER_ID'],
  735. 'LAST_DEC_LV' => $item['LAST_DEC_LV'] ?? '',
  736. 'LAST_EMP_LV' => $userBaseInfo['LAST_EMP_LV'],
  737. 'LAST_STATUS' => $item['LAST_STATUS'] ?? 0,
  738. 'LAST_CROWN_LV' => $item['LAST_CROWN_LV'] ?? '',
  739. 'AMOUNT' => 0,
  740. 'POINT' => $bonusPoint,
  741. 'PERIOD_NUM' => $this->_periodNum,
  742. 'CALC_YEAR' => $this->_calcYear,
  743. 'CALC_MONTH' => $this->_calcYearMonth,
  744. 'CREATED_AT' => Date::nowTime(),
  745. 'PERF' => $monthTotalPV,
  746. 'TRANSFER_RATE' => $mate,
  747. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  748. 'CAP_AMOUNT' => 0,
  749. 'POINT_COMPLEX' => 0,
  750. ];
  751. $bonusPointComplex += $bonusPoint;
  752. }
  753. // 数据写入总表
  754. if ($insertBonusData) {
  755. // 计算个人奖金
  756. foreach ($insertBonusData as &$bonusData) {
  757. // 计算奖金
  758. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  759. if ($amount <= 0) {
  760. continue;
  761. }
  762. // 封顶前奖金数
  763. $capAmount = $amount;
  764. // 奖金数不能大于封顶值
  765. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  766. $bonusData['AMOUNT'] = $amount;
  767. $bonusData['CAP_AMOUNT'] = $capAmount;
  768. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  769. // 放入缓存
  770. CalcCache::villaBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  771. // 加入月奖的会员
  772. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  773. }
  774. CalcBonusVilla::batchInsert($insertBonusData);
  775. }
  776. return true;
  777. }
  778. // 执行车奖的计算
  779. public function calcBonusGarage() {
  780. // 月结,如果不是月结点,则直接退出
  781. if (!$this->_isCalcMonth) {
  782. return true;
  783. }
  784. $bonusConfig = $this->_sysConfig['openGarage'];
  785. // 达标条件:聘级、级别、奖项比例
  786. $config = json_decode($bonusConfig['OPTIONS'], true);
  787. // 奖金总比例
  788. $mate = $bonusConfig['VALUE'] / 100;
  789. // 会员级别
  790. $minDecLevel = $config['declarationLevel'] ?? [];
  791. // 个人奖金封顶
  792. $capBonus = intval($this->_sysConfig['openGarageCap']['VALUE'] ?? 0);
  793. // 月度公司总PV
  794. $monthTotalPV = PerfMonth::find()
  795. ->yearMonth($this->_calcYearMonth)
  796. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  797. ->sum('PV_PCS');
  798. // 用于分发的奖金总数
  799. $transferAmount = $monthTotalPV * $mate;
  800. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  801. $userStarDirector = CalcBonusBS::find()
  802. ->yearMonth($this->_calcYearMonth)
  803. ->where('CALC_MONTH = :CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  804. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_STATUS')
  805. ->groupBy('USER_ID')
  806. ->asArray()
  807. ->all();
  808. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  809. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  810. $subQuery = CalcBonusQY::find()
  811. ->yearMonth($this->_calcYearMonth)
  812. ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
  813. ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
  814. ->joinWith(['starCrown' => function($query) {
  815. $query->select(['LEVEL_NAME', 'SORT']);
  816. }])
  817. ->having(1)
  818. ->orderBy('USER_ID ASC, SORT DESC');
  819. $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();
  820. // 合并用户ID,去重
  821. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  822. sort($bonusUsers);
  823. // 奖金点数综合
  824. $bonusPointComplex = 0;
  825. $insertBonusData = [];
  826. foreach($bonusUsers as $userId) {
  827. // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
  828. $starDirectorPoint = !isset($userStarDirectorObj[$userId]['LEVEL_ID']) ? 0 : ($this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['GARAGE_PERCENT'] ?? 0);
  829. $starCrownPoint = !isset($userStarCrownObj[$userId]['LAST_CROWN_LV']) ? 0: ($this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['GARAGE_PERCENT'] ?? 0);
  830. // 奖金比例:
  831. $bonusPoint = max($starDirectorPoint, $starCrownPoint);
  832. if ($bonusPoint <= 0) {
  833. continue;
  834. }
  835. // 会员级别达到要求才会发放奖金
  836. $lastDecLv = $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? '');
  837. if ($lastDecLv != $minDecLevel) {
  838. continue;
  839. }
  840. $insertBonusData[] = [
  841. 'ID' => SnowFake::instance()->generateId(),
  842. 'USER_ID' => $userId,
  843. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? ''),
  844. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LEVEL_ID'] ?? '',
  845. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'] ?? ($userStarCrownObj[$userId]['LAST_STATUS'] ?? 1),
  846. 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'] ?? '',
  847. 'AMOUNT' => 0,
  848. 'POINT' => $bonusPoint,
  849. 'PERIOD_NUM' => $this->_periodNum,
  850. 'CALC_YEAR' => $this->_calcYear,
  851. 'CALC_MONTH' => $this->_calcYearMonth,
  852. 'CREATED_AT' => Date::nowTime(),
  853. 'PERF' => $monthTotalPV,
  854. 'TRANSFER_RATE' => $mate,
  855. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  856. 'CAP_AMOUNT' => 0,
  857. 'POINT_COMPLEX' => 0,
  858. ];
  859. $bonusPointComplex += $bonusPoint;
  860. }
  861. // 数据写入总表
  862. if ($insertBonusData) {
  863. foreach ($insertBonusData as &$bonusData) {
  864. // 计算奖金
  865. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  866. if ($amount <= 0) {
  867. continue;
  868. }
  869. // 封顶前奖金数
  870. $capAmount = $amount;
  871. // 奖金数不能大于封顶值
  872. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  873. $bonusData['AMOUNT'] = $amount;
  874. $bonusData['CAP_AMOUNT'] = $capAmount;
  875. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  876. // 放入缓存
  877. CalcCache::garageBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  878. // 加入月奖的会员
  879. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  880. }
  881. CalcBonusGarage::batchInsert($insertBonusData);
  882. }
  883. return true;
  884. }
  885. /**
  886. * 季度奖写用户缓存
  887. *
  888. */
  889. public function calcQuarterUser(int $offset = 0) {
  890. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  891. // 不是结算月,则不进行计算
  892. return false;
  893. }
  894. $allData = CalcBonusQuarter::finduseDbCalc()
  895. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  896. ->groupBy('USER_ID')
  897. ->offset($offset)
  898. ->limit($this->_limit)
  899. ->asArray()
  900. ->all();
  901. if ($allData){
  902. // 达标条件:会员级别:钻卡
  903. $config = json_decode($this->_sysConfig['openQuarter']['OPTIONS'], true);
  904. $minDecLevel = $config['declarationLevel'] ?? [];
  905. foreach ($allData as $user) {
  906. // 扣除相应的复消积分和管理费
  907. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS']);
  908. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  909. $manageTax = $deductData['manageTax']; // 管理费
  910. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  911. // 管理奖钻卡发放
  912. if ($user['LAST_DEC_LV'] == $minDecLevel) {
  913. // 把对碰后的奖金存入缓存中
  914. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_QUARTER', $user['ORI_BONUS'], $deductData);
  915. // 加入月奖的会员
  916. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  917. }
  918. // 更新奖金存储过程的实发金额数据
  919. CalcBonusQuarter::updateAll([
  920. 'RECONSUME_POINTS' => $point,
  921. 'AMOUNT' => $realBonusBs,
  922. 'MANAGE_TAX' => $manageTax],
  923. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  924. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  925. }
  926. return $this->calcQuarterUser($offset + $this->_limit);
  927. }
  928. unset($allData);
  929. return true;
  930. }
  931. /**
  932. * 蓝星管理奖金未拆分
  933. * @param int $offset
  934. * @return bool
  935. * @throws \yii\db\Exception
  936. */
  937. public function calcBonusBsGL(int $offset = 0) {
  938. if( !$this->_isCalcMonth ) {
  939. // 不是结算月,则不进行计算
  940. return false;
  941. }
  942. // 从缓存获取分页有收入的会员信息
  943. $allData = CalcBonusBS::findUseDbCalc()
  944. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  945. ->groupBy('USER_ID')
  946. ->offset($offset)
  947. ->limit($this->_limit)
  948. ->asArray()
  949. ->all();
  950. if ($allData) {
  951. foreach ($allData as $user) {
  952. $fxStatus = $this->_isMonthPerfLimit($user['USER_ID']);
  953. if ($fxStatus) {
  954. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS', $user['ORI_BONUS']);
  955. }
  956. }
  957. return $this->calcBonusBsGL($offset + $this->_limit);
  958. }
  959. unset($allData);
  960. return true;
  961. }
  962. // /**
  963. // * 蓝星管理奖金
  964. // * @param int $offset
  965. // * @return bool
  966. // * @throws \yii\db\Exception
  967. // */
  968. // public function calcBonusBsGL(int $offset = 0) {
  969. // if( !$this->_isCalcMonth ) {
  970. // // 不是结算月,则不进行计算
  971. // return false;
  972. // }
  973. // // 从缓存获取分页有收入的会员信息
  974. // $allData = CalcBonusBS::findUseDbCalc()
  975. // ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  976. // ->groupBy('USER_ID')
  977. // ->offset($offset)
  978. // ->limit($this->_limit)
  979. // ->asArray()
  980. // ->all();
  981. // if ($allData) {
  982. // // 达标条件:会员级别:钻卡
  983. // $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  984. // $minDecLevel = $config['mntDec'] ?? [];
  985. // foreach ($allData as $user) {
  986. // //扣除相应的复消积分和管理费
  987. // $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS_MNT']);
  988. // $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  989. // $manageTax = $deductData['manageTax']; // 管理费
  990. // $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  991. // // 管理奖钻卡发放
  992. // // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  993. // // 把对碰后的奖金存入缓存中
  994. // CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS_MNT', $user['ORI_BONUS_MNT'], $deductData);
  995. // // 加入月奖的会员
  996. // CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  997. // // }
  998. // // 更新蓝星奖金存储过程的实发金额数据
  999. // CalcBonusBS::updateAll([
  1000. // 'RECONSUME_POINTS' => $point,
  1001. // 'AMOUNT_MNT' => $realBonusBs,
  1002. // 'MANAGE_TAX_MNT' => $manageTax],
  1003. // 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1004. // [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1005. // }
  1006. // return $this->calcBonusBsGL($offset + $this->_limit);
  1007. // }
  1008. // unset($allData);
  1009. // return true;
  1010. // }
  1011. // /**
  1012. // * 蓝星业绩奖金
  1013. // * @param int $offset
  1014. // * @return bool
  1015. // * @throws \yii\db\Exception
  1016. // */
  1017. // public function calcBonusBsYJ(int $offset = 0) {
  1018. // if( !$this->_isCalcMonth ) {
  1019. // // 不是结算月,则不进行计算
  1020. // return false;
  1021. // }
  1022. // // 从缓存获取分页有收入的会员信息
  1023. // $allData = CalcBonusBS::findUseDbCalc()
  1024. // ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1025. // ->groupBy('USER_ID')
  1026. // ->offset($offset)
  1027. // ->limit($this->_limit)
  1028. // ->asArray()
  1029. // ->all();
  1030. // if ($allData) {
  1031. // // 达标条件:会员级别:金卡、钻卡
  1032. // $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  1033. // $minDecLevel = $config['abbrDec'] ?? [];
  1034. // foreach ($allData as $user) {
  1035. // //扣除相应的复消积分和管理费
  1036. // $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS_ABBR']);
  1037. // $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1038. // $manageTax = $deductData['manageTax']; // 管理费
  1039. // $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1040. // // 业绩奖金卡、钻卡发放
  1041. // // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  1042. // // 把对碰后的奖金存入缓存中
  1043. // CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS_ABBR', $user['ORI_BONUS_ABBR'], $deductData);
  1044. // // 加入月奖的会员
  1045. // CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1046. // // }
  1047. // // 更新蓝星业绩奖金存储过程的实发金额数据
  1048. // CalcBonusBS::updateAll([
  1049. // 'AMOUNT_ABBR' => $realBonusBs,
  1050. // 'MANAGE_TAX_ABBR' => $manageTax,
  1051. // 'RECONSUME_POINTS' => $point],
  1052. // 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1053. // [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1054. // }
  1055. // return $this->calcBonusBsYJ($offset + $this->_limit);
  1056. // }
  1057. // unset($allData);
  1058. // return true;
  1059. // }
  1060. /**
  1061. * 对碰
  1062. * @param array $oriPerfArr
  1063. * @param array $perfArr
  1064. * @param $percent
  1065. * @param $loopTimes
  1066. * @return array
  1067. */
  1068. public function touchPerf(array $oriPerfArr, array $perfArr, $percent, $loopTimes=1) {
  1069. $resultArr = $oriPerfArr;
  1070. foreach ($perfArr as $keyT => $perfT) {
  1071. if ($perfT <= 0) {
  1072. unset($perfArr[$keyT]);
  1073. }
  1074. }
  1075. if (count($perfArr) >= 2 && $loopTimes < 6) {
  1076. arsort($perfArr, SORT_NUMERIC);
  1077. $onePerf = null;
  1078. $oneKey = null;
  1079. // $touchSurplusAmount = 0;
  1080. $touchAmount = 0;
  1081. // 前两个进行对碰
  1082. foreach ($perfArr as $key => $perf) {
  1083. if ($onePerf === null) {
  1084. $oneKey = $key;
  1085. $onePerf = $perf;
  1086. } else {
  1087. $touchSurplusAmount = $perf - $onePerf;
  1088. if ($touchSurplusAmount > 0) {
  1089. unset($perfArr[$oneKey]);
  1090. $resultArr['perfArr'][$oneKey] = 0;
  1091. $perfArr[$key] = $touchSurplusAmount;
  1092. $touchAmount = $onePerf;
  1093. } elseif ($touchSurplusAmount < 0) {
  1094. unset($perfArr[$key]);
  1095. $resultArr['perfArr'][$key] = 0;
  1096. $perfArr[$oneKey] = abs($touchSurplusAmount);
  1097. $touchAmount = $perf;
  1098. } else {
  1099. unset($perfArr[$oneKey], $perfArr[$key]);
  1100. $resultArr['perfArr'][$oneKey] = 0;
  1101. $resultArr['perfArr'][$key] = 0;
  1102. $touchAmount = $perf;
  1103. }
  1104. break;
  1105. }
  1106. }
  1107. $touchBonus = Tool::formatPrice($touchAmount * $percent);
  1108. $resultArr['touchBonus'] += $touchBonus;
  1109. foreach ($perfArr as $keyR => $perfR) {
  1110. $resultArr['perfArr'][$keyR] = $perfR;
  1111. }
  1112. return $this->touchPerf($resultArr, $perfArr, $percent, $loopTimes+1);
  1113. }
  1114. return $resultArr;
  1115. }
  1116. /**
  1117. * 循环父级并执行回调函数
  1118. * @param $userId
  1119. * @param callable $callbackFunc
  1120. * @param int $offset
  1121. * @return bool
  1122. */
  1123. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1124. $allParents = Cache::getAllNetworkParents($userId);
  1125. $allData = array_slice($allParents, $offset, $this->_limit);
  1126. unset($allParents);
  1127. if ($allData) {
  1128. foreach ($allData as $data) {
  1129. $funcResult = $callbackFunc($data);
  1130. if ($funcResult === self::LOOP_FINISH) {
  1131. return true;
  1132. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1133. continue;
  1134. }
  1135. unset($data, $funcResult);
  1136. }
  1137. unset($allData);
  1138. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1139. }
  1140. return true;
  1141. }
  1142. /**
  1143. * 循环推荐网络的父级
  1144. * @param $userId
  1145. * @param callable $callbackFunc
  1146. * @param int $offset
  1147. * @return bool
  1148. */
  1149. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1150. $allParents = Cache::getAllRelationParents($userId);
  1151. $allData = array_slice($allParents, $offset, $this->_limit);
  1152. unset($allParents);
  1153. if ($allData) {
  1154. foreach ($allData as $data) {
  1155. $funcResult = $callbackFunc($data);
  1156. if ($funcResult === self::LOOP_FINISH) {
  1157. return true;
  1158. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1159. continue;
  1160. }
  1161. unset($data, $funcResult);
  1162. }
  1163. unset($allData);
  1164. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1165. }
  1166. return true;
  1167. }
  1168. /**
  1169. * 按级别的收入上限
  1170. * 新的需求调整: 改成不按月进行限制,并且去掉vip奖
  1171. * @param $bonus
  1172. * @param $userId
  1173. * @param $declarationLevel
  1174. * @return float
  1175. */
  1176. public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  1177. $decLevelConfig = $this->_decLevelConfig;
  1178. $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  1179. unset($decLevelConfig);
  1180. $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'];
  1181. if( $bonus <= $maxGetBonus) {
  1182. return $bonus;
  1183. }else {
  1184. return $maxGetBonus;
  1185. }
  1186. }
  1187. /**
  1188. * 扣除复消积分和管理费
  1189. * @param $userId
  1190. * @param $bonus
  1191. * @return array
  1192. * @throws \yii\db\Exception
  1193. */
  1194. public function deduct($userId, $bonus) {
  1195. //判断是否达到了本月扣除复消的上限
  1196. $cacheData = CalcCache::monthLastPeriodReconsumePoints($userId, $this->_periodNum, $this->_calcYearMonth);
  1197. $bonusCache = CalcCache::bonus($userId, $this->_periodNum);
  1198. $reConsumePointsTotal = $bonusCache['RECONSUME_POINTS'] + $cacheData['RECONSUME_POINTS_SUM'];
  1199. $reConsumePointsCap = $this->_sysConfig['reConsumePointsMonthCap']['VALUE'];
  1200. unset($cacheData, $bonusCache);
  1201. $reConsumePoints = 0;
  1202. if( $reConsumePointsTotal < $reConsumePointsCap ) {
  1203. $reConsumePoints = $bonus * $this->_sysConfig['reConsumePointsPercent']['VALUE'] / 100;
  1204. $reConsumePoints = min($reConsumePoints, $reConsumePointsCap-$reConsumePointsTotal);
  1205. }
  1206. unset($reConsumePointsTotal, $reConsumePointsCap);
  1207. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  1208. $surplus = $bonus - $reConsumePoints - $manageTax;
  1209. return [
  1210. 'reConsumePoints' => Tool::formatPrice($reConsumePoints),//复效积分
  1211. 'manageTax' => Tool::formatPrice($manageTax),//管理费
  1212. 'surplus' => Tool::formatPrice($surplus),//真实奖金
  1213. ];
  1214. }
  1215. /**
  1216. * 更新百分比并发送
  1217. * @param $percent
  1218. */
  1219. private function _updatePercent($percent) {
  1220. // 把数据写入数据库中
  1221. Period::updateAll(['CALC_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  1222. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'CALC_PERCENT']);
  1223. }
  1224. /**
  1225. * 循环奖服务奖金会员,并入库
  1226. * @param int $offset
  1227. * @return bool
  1228. * @throws \yii\db\Exception
  1229. */
  1230. public function loopBonusUsers($offset = 0) {
  1231. echo sprintf("时间:[%s]缓存奖金数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1232. // 从缓存列表里面从底层往上倒序获取会员
  1233. $allData = CalcCache::getHasBonusUsers($this->_periodNum, $offset, $this->_limit);
  1234. if($allData){
  1235. $insertDataBonus = [];
  1236. foreach($allData as $userId){
  1237. $tempBonusData = $this->bonusData($userId);
  1238. if(!empty($tempBonusData['result'])){
  1239. $insertDataBonus[] = $tempBonusData['result'];
  1240. }
  1241. unset($userId, $tempBonusData);
  1242. }
  1243. CalcBonus::batchInsert($insertDataBonus);
  1244. unset($insertDataBonus, $allData);
  1245. return $this->loopBonusUsers($offset + $this->_limit);
  1246. }
  1247. return true;
  1248. }
  1249. /**
  1250. * 奖金
  1251. * @param $userId
  1252. * @return array
  1253. * @throws \yii\db\Exception
  1254. */
  1255. public function bonusData($userId) {
  1256. // 从缓存中获取用户的奖金
  1257. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  1258. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1259. $perfData = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  1260. $tourismBonus = CalcCache::tourismBonus($userId, $this->_periodNum);
  1261. $garageBonus = CalcCache::garageBonus($userId, $this->_periodNum);
  1262. $villaBonus = CalcCache::villaBonus($userId, $this->_periodNum);
  1263. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  1264. // 星级
  1265. $starCrownLv = CalcCache::getUserStarCrown($userId, $this->_periodNum);
  1266. //没有共享和管理奖
  1267. $bonusReal = $bonus['BONUS_BD'] + $bonus['BONUS_TG'] + $bonus['BONUS_XF'] + $bonus['BONUS_YJ'] +
  1268. $bonus['BONUS_QY'] + $bonus['BONUS_YC'] + $bonus['BONUS_YC_EXTRA'] + $bonus['BONUS_VIP'] +
  1269. $bonus['BONUS_BS_MNT'] + $bonus['BONUS_BS_ABBR'] + $bonus['BONUS_QUARTER'];
  1270. $realBonusGx = 0;
  1271. $realBonusGl = 0;
  1272. $realBonusBs = 0; // 蓝星管理奖. BlueStar
  1273. $blueStartOriBonus = 0;
  1274. $blueStartManageTax = 0;
  1275. $exchangePoints = 0; // 蓝星奖管理奖. 产生的兑换积分
  1276. $realBonusBsMnt = 0; // 蓝星管理奖——实发奖金
  1277. $blueStartOriBonusMnt = 0; // 蓝星管理奖——原奖金
  1278. $blueStartManageTaxMnt = 0; // 蓝星管理奖——管理费
  1279. $realBonusBsAbbr = 0; // 蓝星业绩奖——实发奖金
  1280. $blueStartOriBonusAbbr = 0; // 蓝星业绩奖——原奖金
  1281. $blueStartManageTaxAbbr = 0; // 蓝星业绩奖——管理费
  1282. if( $this->_isCalcMonth ) {
  1283. // 个人月消费PV大于配置值,才会计算发放蓝星奖
  1284. $fxPvStatus = $this->_isMonthPerfLimit($userId);
  1285. // BONUS_REAL 字段是发到用户的真实奖金
  1286. if ( $fxPvStatus ) {
  1287. $userBS = CalcBonusBS::find()
  1288. ->where(
  1289. 'PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',
  1290. [
  1291. ':PERIOD_NUM' => $this->_periodNum,
  1292. ':USER_ID' => $userId
  1293. ]
  1294. )
  1295. ->select('AMOUNT,ORI_BONUS,MANAGE_TAX,LEVEL_ID,PRODUCT_POINT,AMOUNT_MNT,ORI_BONUS_MNT,MANAGE_TAX_MNT,AMOUNT_ABBR,ORI_BONUS_ABBR,MANAGE_TAX_ABBR')
  1296. ->limit(1)
  1297. ->orderBy('CREATED_AT DESC')
  1298. ->asArray()
  1299. ->all();
  1300. $userBS = is_array($userBS) ? reset($userBS) : [];
  1301. $blueStartAmount = isset($userBS['AMOUNT']) && !empty($userBS['AMOUNT']) ? $userBS['AMOUNT'] : 0; // 奖金
  1302. $blueStartOriBonus = isset($userBS['ORI_BONUS']) && !empty($userBS['ORI_BONUS']) ? $userBS['ORI_BONUS'] : 0; // 原奖金
  1303. $blueStartManageTax = isset($userBS['MANAGE_TAX']) && !empty($userBS['MANAGE_TAX']) ? $userBS['MANAGE_TAX'] : 0; // 管理费
  1304. $realBonusBsMnt = $userBS['AMOUNT_MNT'] ?? 0; // 蓝星管理奖. 实发奖金
  1305. $blueStartOriBonusMnt = $userBS['ORI_BONUS_MNT'] ?? 0; // 蓝星管理奖. 原奖金
  1306. $blueStartManageTaxMnt = $userBS['MANAGE_TAX_MNT'] ?? 0; // 蓝星管理奖. 管理费
  1307. $realBonusBsAbbr = $userBS['AMOUNT_ABBR'] ?? 0; // 蓝星业绩奖. 奖金
  1308. $blueStartOriBonusAbbr = $userBS['ORI_BONUS_ABBR'] ?? 0; // 蓝星业绩奖. 原奖金
  1309. $blueStartManageTaxAbbr = $userBS['MANAGE_TAX_ABBR'] ?? 0; // 蓝星业绩奖. 管理费
  1310. $blueStartManageTax += $blueStartManageTaxMnt + $blueStartManageTaxAbbr; // 管理费
  1311. $realBonusBs = $blueStartAmount; // 蓝星奖直接取数据库中算好的值PRODUCT_POINT
  1312. $exchangePoints = isset($userBS['PRODUCT_POINT']) && !empty($userBS['PRODUCT_POINT']) ? $userBS['PRODUCT_POINT'] : 0; // 兑换积分
  1313. }
  1314. }
  1315. if( $this->_isCalcMonth ) { //季度奖
  1316. if(in_array($this->_calcMonth, [3,6,9,12])){ // 季度奖
  1317. }
  1318. }
  1319. $result = [
  1320. 'USER_ID' => $userId,
  1321. 'LAST_USER_NAME' => $baseInfo['USER_NAME'],
  1322. 'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
  1323. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1324. 'LAST_EMP_LV' => $baseInfo['LAST_EMP_LV'],
  1325. 'LAST_CROWN_LV' => $starCrownLv ?? StarCrownLevel::getDefaultLevelId(),
  1326. 'LAST_STATUS' => $baseInfo['STATUS'],
  1327. 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
  1328. 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
  1329. 'LAST_CON_USER_NAME' => $baseInfo['CON_USER_NAME'],
  1330. 'LAST_CON_REAL_NAME' => $baseInfo['CON_REAL_NAME'],
  1331. 'EXCHANGE_POINTS' => $exchangePoints, // 兑换积分
  1332. // 'LAST_LOCATION' => $baseInfo['LOCATION'] ? $baseInfo['LOCATION'] : 1,
  1333. //@todo
  1334. 'LAST_LOCATION' => 1,
  1335. 'BONUS_BD' => $bonus['BONUS_BD'],
  1336. 'BONUS_TG' => $bonus['BONUS_TG'],
  1337. 'BONUS_QY' => $bonus['BONUS_QY'],
  1338. 'RECONSUME_POINTS' => $bonus['RECONSUME_POINTS'],
  1339. 'MANAGE_TAX' => $blueStartManageTax, // 管理费
  1340. 'BONUS_INCOME'=>$bonus['INCOME_TOTAL'],
  1341. 'BONUS_REAL'=> $bonusReal,
  1342. 'BONUS_TOTAL'=>$bonus['BONUS_TOTAL'],
  1343. 'ORI_BONUS_BD' => $bonus['ORI_BONUS_BD'],
  1344. 'ORI_BONUS_TG' => $bonus['ORI_BONUS_TG'],
  1345. 'BONUS_BS' => $realBonusBs, // 新的管理奖金,即蓝星管理奖
  1346. 'ORI_BONUS_BS' => $blueStartOriBonus, // 蓝星管理奖金原奖金,即包含管理费
  1347. 'REAL_BONUS_BS' => $realBonusBs, // 实发蓝星管理奖金
  1348. 'BONUS_BS_MNT' => $realBonusBsMnt, // 蓝星管理奖
  1349. 'ORI_BONUS_BS_MNT' => $blueStartOriBonusMnt, // 蓝星管理奖金原奖金,即包含管理费
  1350. 'REAL_BONUS_BS_MNT' => $realBonusBsMnt, // 实发蓝星管理奖金
  1351. 'MANAGE_TAX_MNT' => $blueStartManageTaxMnt, // 实发蓝星管理——管理费
  1352. 'BONUS_BS_ABBR' => $realBonusBsAbbr, // 蓝星业绩奖
  1353. 'ORI_BONUS_BS_ABBR' => $blueStartOriBonusAbbr, // 蓝星业绩奖金原奖金,即包含管理费
  1354. 'REAL_BONUS_BS_ABBR' => $realBonusBsAbbr, // 实发蓝星业绩奖金
  1355. 'MANAGE_TAX_ABBR' => $blueStartManageTaxAbbr, // 实发蓝星业绩奖——管理费
  1356. 'ORI_BONUS_QY' => $bonus['ORI_BONUS_QY'],
  1357. 'ORI_CAPPED_BONUS_QY' => $bonus['ORI_CAPPED_BONUS_QY'], // 团队奖封顶前的奖金
  1358. 'BONUS_QUARTER' => $bonus['BONUS_QUARTER'],
  1359. 'ORI_BONUS_QUARTER' => $bonus['ORI_BONUS_QUARTER'],
  1360. 'BONUS_TOURISM' => $tourismBonus, // 旅游奖
  1361. 'BONUS_VILLA' => $villaBonus, // 房奖
  1362. 'BONUS_GARAGE' => $garageBonus, // 车奖
  1363. //以下没有用
  1364. 'PV_1L' => $perfData['PV_1L_TOUCH'],//TOUCH为碰业绩
  1365. 'QY_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  1366. 'SURPLUS_1L' => $perfData['SURPLUS_1L'],
  1367. 'PV_2L' => $perfData['PV_2L_TOUCH'],
  1368. 'QY_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  1369. 'SURPLUS_2L' => $perfData['SURPLUS_2L'],
  1370. 'PV_3L' => $perfData['PV_3L_TOUCH'],
  1371. 'QY_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  1372. 'SURPLUS_3L' => $perfData['SURPLUS_3L'],
  1373. 'PV_4L' => $perfData['PV_4L_TOUCH'],
  1374. 'QY_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  1375. 'SURPLUS_4L' => $perfData['SURPLUS_4L'],
  1376. 'PV_5L' => $perfData['PV_5L_TOUCH'],
  1377. 'QY_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  1378. 'SURPLUS_5L' => $perfData['SURPLUS_5L'],
  1379. 'PV_PCS' => $perfData['PV_PCS'],
  1380. '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']),
  1381. 'PERIOD_NUM' => $this->_periodNum,
  1382. 'CALC_YEAR' => $this->_calcYear,
  1383. 'CALC_MONTH' => $this->_calcYearMonth,
  1384. 'CREATED_AT' => Date::nowTime(),
  1385. ];
  1386. $resend = [];
  1387. unset($bonus, $realBonusGx, $realBonusGl, $bonusReal);
  1388. return ['result'=>$result,'resend'=>$resend];
  1389. }
  1390. // 判断是否满足月最低消费
  1391. public function _isMonthPerfLimit($userId) {
  1392. $userMonthTotal = PerfMonth::find()->where(
  1393. 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  1394. ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth]
  1395. )
  1396. ->asArray()
  1397. ->one();
  1398. $fxPvStatus = false;
  1399. if (isset($userMonthTotal['PV_PCS']) && $userMonthTotal['PV_PCS'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
  1400. $fxPvStatus = true;
  1401. }
  1402. return $fxPvStatus;
  1403. }
  1404. }