CalcServeBonusCalc.php 71 KB

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