CalcServeBonusCalc.php 71 KB

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