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