CalcServeBonusCalc.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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. $insertBonusData = [];
  536. foreach ($allData as $userId) {
  537. // 从缓存中获取会员的业绩信息
  538. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  539. if( !$perfData ) continue;
  540. $decRoleBonusFrom = explode(',', $this->_sysConfig['decRoleBonusFrom']['VALUE']);
  541. $validPvPcs = 0;
  542. foreach ($decRoleBonusFrom as $orderType) {
  543. $orderTypeName = sprintf('PV_PCS_%s', $orderType);
  544. $orderTypeValue = $perfData[$orderTypeName] ?? 0;
  545. $coefficientName = self::ORDER_TYPE_TO_FW_COEFFICIENT[$orderType];
  546. $coefficient = $this->_sysConfig[$coefficientName]['VALUE'] ?? 1;
  547. $validPvPcs += $orderTypeValue * $coefficient;
  548. unset($orderType, $orderTypeName, $orderTypeValue, $coefficientName, $coefficient);
  549. }
  550. unset($perfData, $decRoleBonusFrom);
  551. if ( $validPvPcs <= 0 ) continue;
  552. // 查询会员产生时,填写的报单中心
  553. $bonusUserId = DecOrder::find()->where('TO_USER_ID=:TO_USER_ID', [':TO_USER_ID' => $userId])->select('DEC_ID')->orderBy('CREATED_AT DESC')->scalar();
  554. LoggerTool::debug(json_encode(['$bonusUserId', $bonusUserId]));
  555. //判断parent的报单中心级别 和 服务奖比例
  556. //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  557. // $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  558. // $isDec = $bonusUserInfo['IS_DEC'];
  559. // if ($isDec == 0) {
  560. // return self::LOOP_CONTINUE; // 如果不是报单中心则跳过循环
  561. // }
  562. // $decRoleId = $bonusUserInfo['DEC_ROLE_ID'];
  563. // if( !$decRoleId ) return self::LOOP_CONTINUE;
  564. // if( !isset($this->_decRoleConfig[$decRoleId]) ) return self::LOOP_CONTINUE;
  565. // 取报单中心级别对应的拿奖比例
  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. //
  572. // $fwBonus = $validPvPcs * $diffPercent / 100;
  573. // if( $fwBonus <= 0 ) return self::LOOP_CONTINUE;
  574. //给本人添加服务奖比例
  575. // CalcCache::fwMaxBonusPercent($userId, $this->_periodNum, $parentFwBonusPercent);
  576. // //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  577. // CalcCache::saveFwBonusList($bonusUserId, $this->_periodNum, $fwBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$validPvPcs]);
  578. // CalcCache::addHasFwBonusUsers($bonusUserId, $this->_periodNum);
  579. unset($userId, $validPvPcs);
  580. }
  581. unset($allData, $insertBonusData);
  582. return $this->calcBonusBDStepOne($offset + $this->_limit);
  583. }
  584. unset($allData);
  585. return true;
  586. }
  587. /**
  588. * 服务奖第二步
  589. * @param int $offset
  590. * @return bool
  591. * @throws \yii\db\Exception
  592. */
  593. public function calcBonusBDStepTwo(int $offset = 0) {
  594. echo sprintf("时间:[%s]服务奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  595. $allData = CalcCache::getHasFwBonusUsers($this->_periodNum, $offset, $this->_limit);
  596. if ($allData) {
  597. $insertBonusData = [];
  598. foreach ($allData as $userId) {
  599. $fwBonusData = CalcCache::getFwBonusList($userId, $this->_periodNum);
  600. if( !$fwBonusData ) continue;
  601. $fwBonus = $fwBonusData['fwBonus'] ?? 0;
  602. if( $fwBonus <=0 ) continue;
  603. //总金额限制
  604. try {
  605. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  606. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_BD', $fwBonus);
  607. $decRoleId = $userBaseInfo['DEC_ROLE_ID'];
  608. $insertBonusData[] = [
  609. 'ID' => SnowFake::instance()->generateId(),
  610. 'USER_ID' => $userId,
  611. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  612. 'LAST_EMP_LV' => $this->_nowLastEmpLv($userId),
  613. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  614. 'FROM_USER_ID' => $userId,
  615. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  616. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  617. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  618. 'AMOUNT' => $fwBonus,
  619. 'ORI_BONUS' => $fwBonus,
  620. 'RECONSUME_POINTS' => 0,
  621. 'MANAGE_TAX' => 0,
  622. 'PERIOD_NUM' => $this->_periodNum,
  623. 'CALC_YEAR' => $this->_calcYear,
  624. 'CALC_MONTH' => $this->_calcYearMonth,
  625. 'CREATED_AT' => Date::nowTime(),
  626. 'LOGS' => json_encode([
  627. 'decRoleId' => $decRoleId,
  628. ])
  629. ];
  630. } catch(Exception $e) {
  631. var_dump('---->>>', $e->getMessage());exit;
  632. }
  633. unset($userId, $fwBonusData, $userBaseInfo, $decRoleId, $fwBonus);
  634. }
  635. CalcBonusBD::batchInsert($insertBonusData);
  636. unset($insertBonusData, $allData);
  637. $this->calcBonusBDStepTwo($offset + $this->_limit);
  638. }
  639. unset($allData);
  640. return true;
  641. }
  642. /**
  643. * 团队奖
  644. * @param int $offset
  645. * @return bool
  646. * @throws \yii\db\Exception
  647. */
  648. public function calcBonusQY(int $offset = 0) {
  649. echo sprintf("时间:[%s]团队奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  650. $periodNum = $this->_periodNum;
  651. // 从缓存获取分页有业绩的会员信息
  652. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  653. if ($allData) {
  654. $insertBonusData = [];
  655. foreach ($allData as $userId) {
  656. // 从缓存中获取会员的业绩信息
  657. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  658. // 从缓存中获取会员的上期结余业绩信息
  659. $pervSurplusPerf = CalcCache::surplusPerf($userId, $periodNum);
  660. // 本期 + 上期结余
  661. $perfArr = [
  662. 'SURPLUS_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  663. 'SURPLUS_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  664. 'SURPLUS_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  665. 'SURPLUS_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  666. 'SURPLUS_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  667. ];
  668. $oriPerfArr = [
  669. 'perfArr' => $perfArr,
  670. 'touchBonus' => 0,
  671. ];
  672. // 获取会员的报单级别
  673. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  674. $decLevelConfig = $this->_decLevelConfig;
  675. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  676. // 对碰
  677. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $nowDecLevelConfig['QY_PERCENT']/100);
  678. $touchPerfArr = [];
  679. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  680. $touchPerfArr[$keyR] = $perfR;
  681. }
  682. // 对碰完成后把结余的业绩存入本期业绩缓存中
  683. CalcCache::nowPeriodPerf($userId, $periodNum, $touchPerfArr);
  684. //更新数据库
  685. PerfPeriod::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  686. 'USER_ID' => $userId,
  687. 'PERIOD_NUM' => $periodNum,
  688. ]);
  689. if ($touchBonusArr['touchBonus'] <= 0) continue;
  690. $teamBonus = $touchBonusArr['touchBonus'];
  691. $capBonusQy = $teamBonus; // 封顶前的奖金
  692. //判断级别上限,个人奖金封顶限制
  693. $teamBonus = $this->declarationLevelCap($teamBonus, $userId, $userBaseInfo['DEC_LV']);
  694. if( $teamBonus <= 0 ) continue;
  695. // 将封顶前的金额加入用户奖金缓存中,此金额不能发放(总奖金,总实际奖金)
  696. CalcCache::bonus($userId, $periodNum, 'CAPPED_BONUS_QY', $capBonusQy);
  697. // TODO:取小腿值
  698. $payLeg = min([$perfArr['SURPLUS_1L'], $perfArr['SURPLUS_2L']]);
  699. // 计算荣衔星级
  700. $starCrown = StarCrownLevel::getStarCrown($payLeg);
  701. // 是否活跃
  702. $isActive = User::isPerfActive($userId, $this->_periodNum, $this->_calcYearMonth);
  703. $oriBonus = $isActive ? $teamBonus : 0;
  704. $lastCrownLv = $isActive ? $starCrown['ID'] : StarCrownLevel::getDefaultLevelId();
  705. //团队奖流水
  706. $insertBonusData[] = [
  707. 'ID' => SnowFake::instance()->generateId(),
  708. 'USER_ID' => $userId,
  709. 'ORI_CAPPED_BONUS_QY' => $capBonusQy,
  710. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  711. 'LAST_EMP_LV' => $this->_nowLastEmpLv($userId),
  712. 'LAST_CROWN_LV' => $lastCrownLv,
  713. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  714. 'AMOUNT' => $oriBonus,
  715. 'ORI_BONUS' => $oriBonus,
  716. 'PERIOD_NUM' => $this->_periodNum,
  717. 'CALC_YEAR' => $this->_calcYear,
  718. 'CALC_MONTH' => $this->_calcYearMonth,
  719. 'CREATED_AT' => Date::nowTime(),
  720. 'LOGS' => json_encode([
  721. 'perfArr' => $perfArr,
  722. 'touchPerfArrOri' => $touchBonusArr['perfArr'],
  723. 'touchPerfArr' => $touchPerfArr,
  724. 'nowDecLevelConfig' => $nowDecLevelConfig,
  725. 'decLevel' => $userBaseInfo['DEC_LV'],
  726. ]),
  727. 'IS_ACTIVE' => (int)$isActive,
  728. 'HOPE_CROWN_LV' => $starCrown['ID'],
  729. 'HOPE_BONUS' => $teamBonus,
  730. ];
  731. // 星级放入缓存
  732. CalcCache::addUserStarCrown($userId, $periodNum, $lastCrownLv);
  733. if ($oriBonus > 0) {
  734. // 把对碰后的奖金存入缓存中
  735. // CalcCache::bonus($userId, $periodNum, 'BONUS_QY', $oriBonus, $deductData);
  736. CalcCache::bonus($userId, $periodNum, 'BONUS_QY', $teamBonus);
  737. }
  738. unset($perfData, $pervSurplusPerf, $perfArr, $oriPerfArr, $touchPerfArr, $userBaseInfo, $decLevelConfig, $touchBonusArr, $userId, $nowDecLevelConfig, $teamBonus, $deductData);
  739. }
  740. CalcBonusQY::batchInsert($insertBonusData);
  741. unset($allData, $insertBonusData);
  742. return $this->calcBonusQY($offset + $this->_limit);
  743. }
  744. unset($allData);
  745. return true;
  746. }
  747. /**
  748. * 季度奖计算
  749. */
  750. public function calcQuarter() {
  751. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  752. // echo('不是季结点,进这里,不计算季度奖'. PHP_EOL);
  753. return false;
  754. }
  755. $result = \Yii::$app->db->createCommand("CALL QtrCalc(:periodNum)")
  756. ->bindValue(':periodNum' , $this->_periodNum )
  757. ->execute();
  758. return $result;
  759. }
  760. // 执行蓝星管理奖金的存储过程
  761. public function calcBsProcedure() {
  762. if( !$this->_isCalcMonth ) {
  763. // 不是结算月,则不进行计算
  764. return false;
  765. }
  766. $result = \Yii::$app->db->createCommand("CALL CalcBlue(:periodNum)")
  767. ->bindValue(':periodNum' , $this->_periodNum )
  768. ->execute();
  769. return $result;
  770. }
  771. // 执行旅游奖的计算
  772. public function calcBonusTourism() {
  773. // 月结,如果不是月结点,则直接退出
  774. if (!$this->_isCalcMonth) {
  775. return true;
  776. }
  777. $bonusConfig = $this->_sysConfig['openTourism'];
  778. // 达标条件:聘级、级别、奖项比例
  779. $config = json_decode($bonusConfig['OPTIONS'], true);
  780. // 奖金总比例
  781. $mate = $bonusConfig['VALUE'] / 100;
  782. // 会员级别
  783. $minDecLevel = $config['OPTIONS']['declarationLevel'] ?? [];
  784. // 月度公司总PV
  785. $monthTotalPV = PerfMonth::find()
  786. ->yearMonth($this->_calcYearMonth)
  787. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  788. ->sum('PV_PCS');
  789. // 用于分发的奖金总数
  790. $transferAmount = $monthTotalPV * $mate;
  791. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  792. $userStarDirector = CalcBonusBS::find()
  793. ->yearMonth($this->_calcYearMonth)
  794. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  795. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STATUS')
  796. ->groupBy('USER_ID')
  797. ->asArray()
  798. ->all();
  799. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  800. // 基于团队奖/绩效奖结果计算会员的StarCrown
  801. $userStarCrown = CalcBonusQY::find()
  802. ->yearMonth($this->_calcYearMonth)
  803. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  804. ->select('USER_ID,LAST_CROWN_LV')
  805. ->groupBy('USER_ID')
  806. ->asArray()
  807. ->all();
  808. $userStarCrownObj = array_column($userStarCrown, NULL, 'USER_ID');
  809. // 合并用户ID,去重
  810. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  811. // 奖金点数综合
  812. $bonusPointComplex = 0;
  813. $insertBonusData = [];
  814. foreach($bonusUsers as $userId) {
  815. // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
  816. $starDirectorPoint = $this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['TOURISM_PERCENT'] ?? 0;
  817. $starCrownPoint = $this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['TOURISM_PERCENT'] ?? 0;
  818. // 奖金比例:
  819. $bonusPoint = max($starDirectorPoint, $starCrownPoint);
  820. if ($bonusPoint <= 0) {
  821. continue;
  822. }
  823. $insertBonusData[] = [
  824. 'ID' => SnowFake::instance()->generateId(),
  825. 'USER_ID' => $userId,
  826. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'],
  827. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LEVEL_ID'],
  828. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'],
  829. 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'],
  830. 'AMOUNT_STANDARD' => 0,
  831. 'POINT' => $bonusPoint,
  832. 'PERIOD_NUM' => $this->_periodNum,
  833. 'CALC_YEAR' => $this->_calcYear,
  834. 'CALC_MONTH' => $this->_calcYearMonth,
  835. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  836. 'CREATED_AT' => Date::nowTime(),
  837. 'PERF' => $monthTotalPV,
  838. 'TRANSFER_RATE' => $mate,
  839. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  840. 'CAP_AMOUNT' => 0,
  841. 'POINT_COMPLEX' => 0,
  842. ];
  843. $bonusPointComplex += $bonusPoint;
  844. }
  845. // 数据写入总表
  846. if ($insertBonusData) {
  847. foreach ($insertBonusData as &$bonusData) {
  848. // 计算奖金
  849. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  850. if ($amount <= 0) {
  851. continue;
  852. }
  853. // 会员级别达到要求才会发放奖金
  854. if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
  855. // 放入缓存
  856. CalcCache::tourismBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  857. }
  858. $bonusData['AMOUNT'] = $amount;
  859. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  860. }
  861. CalcBonusTourism::batchInsert($insertBonusData);
  862. }
  863. return true;
  864. }
  865. // 执行房奖的计算
  866. public function calcBonusVilla() {
  867. if (!$this->_isCalcMonth) {
  868. return true;
  869. }
  870. $bonusConfig = $this->_sysConfig['openVilla'];
  871. // 达标条件:聘级、级别、奖项比例
  872. $config = json_decode($bonusConfig['OPTIONS'], true);
  873. // 奖金总比例
  874. $mate = $bonusConfig['VALUE'] / 100;
  875. // 个人奖金封顶
  876. $capBonus = intval($this->_sysConfig['openVillaCap']['VALUE'] ?? 0);
  877. // 会员级别
  878. $minDecLevel = $config['declarationLevel'] ?? [];
  879. // 月度公司总PV
  880. $monthTotalPV = PerfMonth::find()
  881. ->yearMonth($this->_calcYearMonth)
  882. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  883. ->sum('PV_PCS');
  884. // 用于分发的奖金总数
  885. $transferAmount = $monthTotalPV * $mate;
  886. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  887. $subQuery = CalcBonusQY::find()
  888. ->yearMonth($this->_calcYearMonth)
  889. ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
  890. ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
  891. ->joinWith(['starCrown' => function($query) {
  892. $query->select(['LEVEL_NAME', 'SORT']);
  893. }])
  894. ->having(1)
  895. ->orderBy('USER_ID ASC, SORT DESC');
  896. $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();
  897. // 奖金点数综合
  898. $bonusPointComplex = 0;
  899. $insertBonusData = [];
  900. foreach($userStarCrownObj as $item) {
  901. // 奖金比例
  902. $bonusPoint = $this->_starCrownLevelConfig[$item['LAST_CROWN_LV']]['VILLA_PERCENT'] ?? 0;
  903. if (!$bonusPoint) {
  904. continue;
  905. }
  906. // 会员级别达到要求才会发放奖金
  907. if ($item['LAST_DEC_LV'] != $minDecLevel) {
  908. continue;
  909. }
  910. $insertBonusData[] = [
  911. 'ID' => SnowFake::instance()->generateId(),
  912. 'USER_ID' => $item['USER_ID'],
  913. 'LAST_DEC_LV' => $item['LAST_DEC_LV'] ?? '',
  914. 'LAST_EMP_LV' => $this->_nowLastEmpLv($item['USER_ID']),
  915. 'LAST_STATUS' => $item['LAST_STATUS'] ?? 0,
  916. 'LAST_CROWN_LV' => $item['LAST_CROWN_LV'] ?? '',
  917. 'AMOUNT' => 0,
  918. 'POINT' => $bonusPoint,
  919. 'PERIOD_NUM' => $this->_periodNum,
  920. 'CALC_YEAR' => $this->_calcYear,
  921. 'CALC_MONTH' => $this->_calcYearMonth,
  922. 'CREATED_AT' => Date::nowTime(),
  923. 'PERF' => $monthTotalPV,
  924. 'TRANSFER_RATE' => $mate,
  925. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  926. 'CAP_AMOUNT' => 0,
  927. 'POINT_COMPLEX' => 0,
  928. ];
  929. $bonusPointComplex += $bonusPoint;
  930. }
  931. // 数据写入总表
  932. if ($insertBonusData) {
  933. // 计算个人奖金
  934. foreach ($insertBonusData as &$bonusData) {
  935. // 计算奖金
  936. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  937. if ($amount <= 0) {
  938. continue;
  939. }
  940. // 封顶前奖金数
  941. $capAmount = $amount;
  942. // 奖金数不能大于封顶值
  943. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  944. $bonusData['AMOUNT'] = $amount;
  945. $bonusData['CAP_AMOUNT'] = $capAmount;
  946. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  947. // 放入缓存
  948. CalcCache::villaBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  949. }
  950. CalcBonusVilla::batchInsert($insertBonusData);
  951. }
  952. return true;
  953. }
  954. // 执行车奖的计算
  955. public function calcBonusGarage() {
  956. // 月结,如果不是月结点,则直接退出
  957. if (!$this->_isCalcMonth) {
  958. return true;
  959. }
  960. $bonusConfig = $this->_sysConfig['openGarage'];
  961. // 达标条件:聘级、级别、奖项比例
  962. $config = json_decode($bonusConfig['OPTIONS'], true);
  963. // 奖金总比例
  964. $mate = $bonusConfig['VALUE'] / 100;
  965. // 会员级别
  966. $minDecLevel = $config['declarationLevel'] ?? [];
  967. // 个人奖金封顶
  968. $capBonus = intval($this->_sysConfig['openGarageCap']['VALUE'] ?? 0);
  969. // 月度公司总PV
  970. $monthTotalPV = PerfMonth::find()
  971. ->yearMonth($this->_calcYearMonth)
  972. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  973. ->sum('PV_PCS');
  974. // 用于分发的奖金总数
  975. $transferAmount = $monthTotalPV * $mate;
  976. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  977. $userStarDirector = CalcBonusBS::find()
  978. ->yearMonth($this->_calcYearMonth)
  979. ->where('CALC_MONTH = :CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  980. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_STATUS')
  981. ->groupBy('USER_ID')
  982. ->asArray()
  983. ->all();
  984. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  985. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  986. $subQuery = CalcBonusQY::find()
  987. ->yearMonth($this->_calcYearMonth)
  988. ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
  989. ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
  990. ->joinWith(['starCrown' => function($query) {
  991. $query->select(['LEVEL_NAME', 'SORT']);
  992. }])
  993. ->having(1)
  994. ->orderBy('USER_ID ASC, SORT DESC');
  995. $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();
  996. // 合并用户ID,去重
  997. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  998. sort($bonusUsers);
  999. // 奖金点数综合
  1000. $bonusPointComplex = 0;
  1001. $insertBonusData = [];
  1002. foreach($bonusUsers as $userId) {
  1003. // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
  1004. $starDirectorPoint = !isset($userStarDirectorObj[$userId]['LEVEL_ID']) ? 0 : ($this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['GARAGE_PERCENT'] ?? 0);
  1005. $starCrownPoint = !isset($userStarCrownObj[$userId]['LAST_CROWN_LV']) ? 0: ($this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['GARAGE_PERCENT'] ?? 0);
  1006. // 奖金比例:
  1007. $bonusPoint = max($starDirectorPoint, $starCrownPoint);
  1008. if ($bonusPoint <= 0) {
  1009. continue;
  1010. }
  1011. // 会员级别达到要求才会发放奖金
  1012. $lastDecLv = $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? '');
  1013. if ($lastDecLv != $minDecLevel) {
  1014. continue;
  1015. }
  1016. $insertBonusData[] = [
  1017. 'ID' => SnowFake::instance()->generateId(),
  1018. 'USER_ID' => $userId,
  1019. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? ''),
  1020. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LEVEL_ID'] ?? '',
  1021. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'] ?? ($userStarCrownObj[$userId]['LAST_STATUS'] ?? 1),
  1022. 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'] ?? '',
  1023. 'AMOUNT' => 0,
  1024. 'POINT' => $bonusPoint,
  1025. 'PERIOD_NUM' => $this->_periodNum,
  1026. 'CALC_YEAR' => $this->_calcYear,
  1027. 'CALC_MONTH' => $this->_calcYearMonth,
  1028. 'CREATED_AT' => Date::nowTime(),
  1029. 'PERF' => $monthTotalPV,
  1030. 'TRANSFER_RATE' => $mate,
  1031. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1032. 'CAP_AMOUNT' => 0,
  1033. 'POINT_COMPLEX' => 0,
  1034. ];
  1035. $bonusPointComplex += $bonusPoint;
  1036. }
  1037. // 数据写入总表
  1038. if ($insertBonusData) {
  1039. foreach ($insertBonusData as &$bonusData) {
  1040. // 计算奖金
  1041. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1042. if ($amount <= 0) {
  1043. continue;
  1044. }
  1045. // 封顶前奖金数
  1046. $capAmount = $amount;
  1047. // 奖金数不能大于封顶值
  1048. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  1049. $bonusData['AMOUNT'] = $amount;
  1050. $bonusData['CAP_AMOUNT'] = $capAmount;
  1051. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1052. // 放入缓存
  1053. CalcCache::garageBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1054. }
  1055. CalcBonusGarage::batchInsert($insertBonusData);
  1056. }
  1057. return true;
  1058. }
  1059. /**
  1060. * 季度奖写用户缓存
  1061. */
  1062. public function calcQuarterUser(int $offset = 0) {
  1063. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  1064. // 不是结算月,则不进行计算
  1065. return false;
  1066. }
  1067. try{
  1068. $allData = CalcBonusQuarter::finduseDbCalc()
  1069. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1070. ->groupBy('USER_ID')
  1071. ->offset($offset)
  1072. ->limit($this->_limit)
  1073. ->asArray()
  1074. ->all();
  1075. if ($allData){
  1076. // 达标条件:会员级别:钻卡
  1077. $config = json_decode($this->_sysConfig['openQuarter']['OPTIONS'], true);
  1078. $minDecLevel = $config['declarationLevel'] ?? [];
  1079. foreach ($allData as $user) {
  1080. // 管理奖钻卡发放
  1081. if ($user['LAST_DEC_LV'] == $minDecLevel) {
  1082. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_QUARTER', $user['ORI_BONUS']);
  1083. } else {
  1084. // 如果未发奖,则将实发字段,改成0
  1085. CalcBonusQuarter::updateAll(
  1086. [
  1087. 'AMOUNT' => '0.00'
  1088. ],
  1089. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1090. [
  1091. ':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum
  1092. ]
  1093. );
  1094. }
  1095. }
  1096. return $this->calcQuarterUser($offset + $this->_limit);
  1097. }
  1098. } catch(Exception $e) {
  1099. var_dump($e->getMessage(),'--------------------');
  1100. }
  1101. unset($allData);
  1102. return true;
  1103. }
  1104. /**
  1105. * 蓝星管理奖金未拆分
  1106. */
  1107. public function calcBonusBsGL(int $offset = 0) {
  1108. if( !$this->_isCalcMonth ) {
  1109. // 不是结算月,则不进行计算
  1110. return false;
  1111. }
  1112. // 从缓存获取分页有收入的会员信息
  1113. $allData = CalcBonusBS::findUseDbCalc()
  1114. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1115. ->groupBy('USER_ID')
  1116. ->offset($offset)
  1117. ->limit($this->_limit)
  1118. ->asArray()
  1119. ->all();
  1120. if ($allData) {
  1121. foreach ($allData as $user) {
  1122. // 是否活跃会员
  1123. $isActive = User::isPerfActive($user['USER_ID'], $this->_periodNum, $this->_calcYearMonth);
  1124. $oriBonus = $isActive ? $user['ORI_BONUS'] : 0;
  1125. $lastEmpLv = $isActive ? $user['LEVEL_ID'] : EmployLevel::getDefaultLevelId();
  1126. if ($oriBonus > 0) {
  1127. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS', $user['ORI_BONUS']);
  1128. }
  1129. // 如果不活跃,则不发放奖金,积分,级别
  1130. // 更新蓝星奖金存储过程的实发金额数据
  1131. CalcBonusBS::updateAll(
  1132. [
  1133. 'IS_ACTIVE' => (int)$isActive,
  1134. 'HOPE_EMP_LV' => $user['LEVEL_ID'],
  1135. 'LEVEL_ID' => $lastEmpLv,
  1136. 'HOPE_BONUS' => $user['ORI_BONUS'],
  1137. 'ORI_BONUS' => $oriBonus,
  1138. 'HOPE_BONUS_MNT' => $user['ORI_BONUS_MNT'],
  1139. 'HOPE_BONUS_ABBR' => $user['ORI_BONUS_ABBR'],
  1140. 'ORI_BONUS_MNT' => $isActive ? $user['ORI_BONUS_MNT'] : 0,
  1141. 'ORI_BONUS_ABBR' => $isActive ? $user['ORI_BONUS_ABBR'] : 0,
  1142. ],
  1143. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1144. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1145. // 修改用户缓存中记录的用户的最新级别
  1146. // $userInfo = CalcCache::getUserInfo($user['USER_ID'], $this->_periodNum);
  1147. // $userInfo['LAST_EMP_LV'] = $lastEmpLv;
  1148. // CalcCache::setUserInfo($user['USER_ID'], $this->_periodNum, $userInfo);
  1149. }
  1150. return $this->calcBonusBsGL($offset + $this->_limit);
  1151. }
  1152. unset($allData);
  1153. return true;
  1154. }
  1155. /**
  1156. * 对碰
  1157. */
  1158. public function touchPerf(array $oriPerfArr, array $perfArr, $percent, $loopTimes=1) {
  1159. $resultArr = $oriPerfArr;
  1160. foreach ($perfArr as $keyT => $perfT) {
  1161. if ($perfT <= 0) {
  1162. unset($perfArr[$keyT]);
  1163. }
  1164. }
  1165. if (count($perfArr) >= 2 && $loopTimes < 6) {
  1166. arsort($perfArr, SORT_NUMERIC);
  1167. $onePerf = null;
  1168. $oneKey = null;
  1169. // $touchSurplusAmount = 0;
  1170. $touchAmount = 0;
  1171. // 前两个进行对碰
  1172. foreach ($perfArr as $key => $perf) {
  1173. if ($onePerf === null) {
  1174. $oneKey = $key;
  1175. $onePerf = $perf;
  1176. } else {
  1177. $touchSurplusAmount = $perf - $onePerf;
  1178. if ($touchSurplusAmount > 0) {
  1179. unset($perfArr[$oneKey]);
  1180. $resultArr['perfArr'][$oneKey] = 0;
  1181. $perfArr[$key] = $touchSurplusAmount;
  1182. $touchAmount = $onePerf;
  1183. } elseif ($touchSurplusAmount < 0) {
  1184. unset($perfArr[$key]);
  1185. $resultArr['perfArr'][$key] = 0;
  1186. $perfArr[$oneKey] = abs($touchSurplusAmount);
  1187. $touchAmount = $perf;
  1188. } else {
  1189. unset($perfArr[$oneKey], $perfArr[$key]);
  1190. $resultArr['perfArr'][$oneKey] = 0;
  1191. $resultArr['perfArr'][$key] = 0;
  1192. $touchAmount = $perf;
  1193. }
  1194. break;
  1195. }
  1196. }
  1197. $touchBonus = Tool::formatPrice($touchAmount * $percent);
  1198. $resultArr['touchBonus'] += $touchBonus;
  1199. foreach ($perfArr as $keyR => $perfR) {
  1200. $resultArr['perfArr'][$keyR] = $perfR;
  1201. }
  1202. return $this->touchPerf($resultArr, $perfArr, $percent, $loopTimes+1);
  1203. }
  1204. return $resultArr;
  1205. }
  1206. /**
  1207. * 循环父级并执行回调函数
  1208. * @param $userId
  1209. * @param callable $callbackFunc
  1210. * @param int $offset
  1211. * @return bool
  1212. */
  1213. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1214. $allParents = Cache::getAllNetworkParents($userId);
  1215. $allData = array_slice($allParents, $offset, $this->_limit);
  1216. unset($allParents);
  1217. if ($allData) {
  1218. foreach ($allData as $data) {
  1219. $funcResult = $callbackFunc($data);
  1220. if ($funcResult === self::LOOP_FINISH) {
  1221. return true;
  1222. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1223. continue;
  1224. }
  1225. unset($data, $funcResult);
  1226. }
  1227. unset($allData);
  1228. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1229. }
  1230. return true;
  1231. }
  1232. /**
  1233. * 循环推荐网络的父级
  1234. * @param $userId
  1235. * @param callable $callbackFunc
  1236. * @param int $offset
  1237. * @return bool
  1238. */
  1239. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1240. $allParents = Cache::getAllRelationParents($userId);
  1241. $allData = array_slice($allParents, $offset, $this->_limit);
  1242. unset($allParents);
  1243. if ($allData) {
  1244. foreach ($allData as $data) {
  1245. $funcResult = $callbackFunc($data);
  1246. if ($funcResult === self::LOOP_FINISH) {
  1247. return true;
  1248. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1249. continue;
  1250. }
  1251. unset($data, $funcResult);
  1252. }
  1253. unset($allData);
  1254. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1255. }
  1256. return true;
  1257. }
  1258. /**
  1259. * 按级别的收入上限
  1260. * 新的需求调整: 改成不按月进行限制,并且去掉vip奖
  1261. * @param $bonus
  1262. * @param $userId
  1263. * @param $declarationLevel
  1264. * @return float
  1265. */
  1266. public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  1267. $decLevelConfig = $this->_decLevelConfig;
  1268. $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  1269. unset($decLevelConfig);
  1270. $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'];
  1271. if( $bonus <= $maxGetBonus) {
  1272. return $bonus;
  1273. }else {
  1274. return $maxGetBonus;
  1275. }
  1276. }
  1277. /**
  1278. * 扣除管理费 返回管理费
  1279. */
  1280. public function deductManageTax($bonus) {
  1281. return $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  1282. }
  1283. // 扣除复消积分 返回应扣除的复消费积分
  1284. public function deductReconsumePonits($userId, $bonus) {
  1285. //判断是否达到了本月扣除复消的上限
  1286. $cacheData = CalcCache::monthLastPeriodReconsumePoints($userId, $this->_periodNum, $this->_calcYearMonth);
  1287. $bonusCache = CalcCache::bonus($userId, $this->_periodNum);
  1288. $lastPeriodPoints = '0.00';
  1289. if (!empty($cacheData)) {
  1290. $lastPeriodPoints = $cacheData['RECONSUME_POINTS_SUM'];
  1291. }
  1292. $reConsumePointsTotal = $bonusCache['RECONSUME_POINTS'] + $lastPeriodPoints;
  1293. $reConsumePointsCap = $this->_sysConfig['reConsumePointsMonthCap']['VALUE'];
  1294. unset($cacheData, $bonusCache, $lastPeriodPoints);
  1295. $reConsumePoints = 0;
  1296. if( $reConsumePointsTotal < $reConsumePointsCap ) {
  1297. $reConsumePoints = $bonus * $this->_sysConfig['reConsumePointsPercent']['VALUE'] / 100;
  1298. $reConsumePoints = min($reConsumePoints, $reConsumePointsCap-$reConsumePointsTotal);
  1299. }
  1300. unset($reConsumePointsTotal, $reConsumePointsCap);
  1301. return $reConsumePoints;
  1302. }
  1303. /**
  1304. * 更新百分比并发送
  1305. * @param $percent
  1306. */
  1307. private function _updatePercent($percent) {
  1308. // 把数据写入数据库中
  1309. Period::updateAll(['CALC_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  1310. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'CALC_PERCENT']);
  1311. }
  1312. /**
  1313. * 循环奖服务奖金会员,并入库
  1314. */
  1315. public function loopBonusUsers($offset = 0) {
  1316. echo sprintf("时间:[%s]缓存奖金数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1317. // 从缓存列表里面从底层往上倒序获取会员
  1318. $allData = CalcCache::getHasBonusUsers($this->_periodNum, $offset, $this->_limit);
  1319. if($allData){
  1320. $insertDataBonus = [];
  1321. foreach($allData as $userId){
  1322. try {
  1323. $tempBonusData = $this->bonusData($userId);
  1324. if(!empty($tempBonusData['result'])){
  1325. $insertDataBonus[] = $tempBonusData['result'];
  1326. }
  1327. }catch(Exception $e) {
  1328. var_dump($e->getMessage(),'ssssssssssssssss',$userId);
  1329. }
  1330. unset($userId, $tempBonusData);
  1331. }
  1332. CalcBonus::batchInsert($insertDataBonus);
  1333. unset($insertDataBonus, $allData);
  1334. return $this->loopBonusUsers($offset + $this->_limit);
  1335. }
  1336. return true;
  1337. }
  1338. /**
  1339. * 奖金入库
  1340. */
  1341. public function bonusData($userId) {
  1342. // 车奖和房奖是积分,不参加到奖金累计中.季度奖季度发放,无最低消费限制
  1343. try{
  1344. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  1345. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1346. $perfData = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  1347. $tourismBonus = CalcCache::tourismBonus($userId, $this->_periodNum);
  1348. $garageBonus = CalcCache::garageBonus($userId, $this->_periodNum);
  1349. $villaBonus = CalcCache::villaBonus($userId, $this->_periodNum);
  1350. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  1351. $starCrownLv = CalcCache::getUserStarCrown($userId, $this->_periodNum);// 星级
  1352. $bonusReal = '0.000'; // 总实发
  1353. $deductManageTaxItems = Config::DEDUCT_MANAGE_TAX; // 扣除管理费的列表
  1354. $deductReconsumePointsItems = Config::DEDUCT_RECONSUME_POINTS;// 扣除复消积分的列表
  1355. $totalReconsumePointSum = $totalManageSum = '0.000'; // 需要扣除的奖金项,扣除完之后的实发金额
  1356. $deductManageTax = '0.000'; // 扣除的管理费
  1357. $deductReconsumePoints = '0.000'; // 扣除的复消积分
  1358. foreach($deductManageTaxItems as $v) {
  1359. $totalManageSum+= $bonus[$v]; // 需要扣除管理费的累计之和
  1360. }
  1361. foreach($deductReconsumePointsItems as $v) {
  1362. $totalReconsumePointSum+= $bonus[$v]; // 需要扣除复消积分的累计之和
  1363. }
  1364. // 扣除管理费
  1365. if ($totalManageSum > 0) {
  1366. $deductManageTax = $this->deductManageTax($totalManageSum);
  1367. }
  1368. // 扣除复消积分
  1369. if ($totalReconsumePointSum > 0) {
  1370. $deductReconsumePoints = $this->deductReconsumePonits($userId, $totalReconsumePointSum);
  1371. }
  1372. // 总实发=总原奖金-扣除的总管理费-总复消积分
  1373. $bonusReal = $bonus['BONUS_TOTAL'] - $deductManageTax - $deductReconsumePoints;
  1374. // NG系统,不发放兑换积分
  1375. // 因为是最后统一发奖金,每个奖金得实发是和原奖金一样得.只不过要扣除管理费和复消积分.
  1376. // 当然,ng现在不扣除管理费和复消积分.所以都是0
  1377. $result = [
  1378. 'USER_ID' => $userId,
  1379. 'LAST_USER_NAME' => $baseInfo['USER_NAME'],
  1380. 'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
  1381. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1382. 'LAST_EMP_LV' => $this->_nowLastEmpLv($userId),
  1383. 'LAST_CROWN_LV' => $starCrownLv ?? StarCrownLevel::getDefaultLevelId(),
  1384. 'RECONSUME_POINTS' => $deductReconsumePoints,
  1385. 'MANAGE_TAX' => $deductManageTax, // 管理费
  1386. 'BONUS_REAL'=> $bonusReal,
  1387. 'BONUS_TOTAL'=>$bonus['BONUS_TOTAL'],
  1388. 'ORI_BONUS_BD' => $bonus['ORI_BONUS_BD'],
  1389. 'ORI_BONUS_TG' => $bonus['ORI_BONUS_TG'],
  1390. 'ORI_BONUS_BS' => $bonus['ORI_BONUS_BS'], // 蓝星管理奖金原奖金
  1391. 'ORI_BONUS_QY' => $bonus['ORI_BONUS_QY'],
  1392. 'ORI_CAPPED_BONUS_QY' => $bonus['ORI_CAPPED_BONUS_QY'], // 团队奖封顶前的奖金
  1393. 'ORI_BONUS_QUARTER' => $bonus['ORI_BONUS_QUARTER'],
  1394. 'ORI_BONUS_TOURISM' => $tourismBonus, // 旅游奖
  1395. 'ORI_BONUS_VILLA' => $villaBonus, // 房奖
  1396. 'ORI_BONUS_GARAGE' => $garageBonus, // 车奖
  1397. 'PV_1L' => $perfData['PV_1L_TOUCH'],//TOUCH为碰业绩
  1398. 'QY_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  1399. 'SURPLUS_1L' => $perfData['SURPLUS_1L'],
  1400. 'PV_2L' => $perfData['PV_2L_TOUCH'],
  1401. 'QY_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  1402. 'SURPLUS_2L' => $perfData['SURPLUS_2L'],
  1403. 'PV_3L' => $perfData['PV_3L_TOUCH'],
  1404. 'QY_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  1405. 'SURPLUS_3L' => $perfData['SURPLUS_3L'],
  1406. 'PV_4L' => $perfData['PV_4L_TOUCH'],
  1407. 'QY_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  1408. 'SURPLUS_4L' => $perfData['SURPLUS_4L'],
  1409. 'PV_5L' => $perfData['PV_5L_TOUCH'],
  1410. 'QY_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  1411. 'SURPLUS_5L' => $perfData['SURPLUS_5L'],
  1412. 'PV_PCS' => $perfData['PV_PCS'],
  1413. 'PV_TOUCH' => Tool::formatPrice($perfData['PV_1L_TOUCH'] + $perfData['PV_2L_TOUCH'] + $perfData['PV_3L_TOUCH'] + $perfData['PV_4L_TOUCH'] + $perfData['PV_5L_TOUCH']),
  1414. 'PERIOD_NUM' => $this->_periodNum,
  1415. 'CALC_YEAR' => $this->_calcYear,
  1416. 'CALC_MONTH' => $this->_calcYearMonth,
  1417. 'CREATED_AT' => Date::nowTime(),
  1418. ];
  1419. } catch(Exception $e) {
  1420. var_dump($e->getMessage(),'-----------------------------------------------',$userId);
  1421. }
  1422. $resend = [];
  1423. unset($bonus, $bonusReal);
  1424. return ['result'=>$result,'resend'=>$resend];
  1425. }
  1426. // 判断是否满足月最低消费
  1427. public function _isMonthPerfLimit($userId) {
  1428. $userMonthTotal = PerfMonth::find()->where(
  1429. 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  1430. ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth]
  1431. )
  1432. ->asArray()
  1433. ->one();
  1434. $fxPvStatus = false;
  1435. if (isset($userMonthTotal['PV_PCS']) && $userMonthTotal['PV_PCS'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
  1436. $fxPvStatus = true;
  1437. }
  1438. return $fxPvStatus;
  1439. }
  1440. // 获取用户当期最新聘级
  1441. // 非结算月,直接获取传过来的用户级别.如果是结算月,bs流水表无数据则是无级别.有数据,则直接取缓存中数据.因为第一步计算bs奖已更新缓存数据
  1442. public function _nowLastEmpLv($userId) {
  1443. // 如果是结算月,且蓝星奖流水没记录,则为无级别
  1444. $lastEmpLv = EmployLevel::getDefaultLevelId();
  1445. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1446. if( $this->_isCalcMonth ) {
  1447. $hasBs = CalcBonusBS::findUseDbCalc()
  1448. ->where('PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID', [':PERIOD_NUM' => $this->_periodNum, ':USER_ID' => $userId])
  1449. ->asArray()
  1450. ->one();
  1451. if (!empty($hasBs)) {
  1452. $lastEmpLv = $hasBs['LEVEL_ID'];
  1453. }
  1454. } else {
  1455. $lastEmpLv = $userBaseInfo['LAST_EMP_LV'];
  1456. }
  1457. return $lastEmpLv;
  1458. }
  1459. }