CalcServeBonusCalc.php 58 KB

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