CalcServeBonusCalc.php 70 KB

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