CalcServeBonusCalc.php 71 KB

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