CalcServeBonusCalc.php 71 KB

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