PerfCalc.php 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: liyunlong
  5. * Date: 2019-01-11
  6. * Time: 15:27
  7. */
  8. namespace common\helpers\bonus;
  9. use common\helpers\Cache;
  10. use common\helpers\Date;
  11. use common\helpers\Form;
  12. use common\helpers\snowflake\SnowFake;
  13. use common\helpers\Tool;
  14. use common\helpers\user\Info;
  15. use common\helpers\user\Reconsume;
  16. use common\models\CalcBonus;
  17. use common\models\DeclarationLevel;
  18. use common\models\forms\DeclarationForm;
  19. use common\models\Order;
  20. use common\models\OrderDec;
  21. use common\models\OrderShop;
  22. use common\models\OrderStandard;
  23. use common\models\PerfCompany;
  24. use common\models\PerfMonth;
  25. use common\models\PerfOrder;
  26. use common\models\PerfPeriod;
  27. use common\models\PerfStandard;
  28. use common\models\Period;
  29. use common\models\DecOrder;
  30. use common\models\EmployLevel;
  31. use common\models\PerfActiveUser;
  32. use common\models\StorePerfLog;
  33. use common\models\UserRelation;
  34. use yii\base\Exception;
  35. use yii\base\StaticInstanceTrait;
  36. class PerfCalc {
  37. use StaticInstanceTrait;
  38. private $_limit = 1000;
  39. private $_handleUserId;
  40. private $_companyMonthPerf = 0;
  41. private $_cfTotalPercent = 0;
  42. private $_lxTotalPercent = 0;
  43. private $_sysConfig = [];
  44. private $_decLevelConfig = [];
  45. private $_empLevelConfig = [];
  46. private $_decRoleConfig = [];
  47. private $_errors = [];
  48. private $_periodNum = 0;
  49. private $_periodId;
  50. private $_isCalcMonth = 0;
  51. private $_calcYear;
  52. private $_calcMonth;
  53. private $_calcYearMonth;
  54. private $_lastCalcYear;
  55. private $_lastCalcMonth;
  56. private $_lastCalcYearMonth;
  57. private $_lastPeriodNum;
  58. private $_lastPeriodYear;
  59. private $_lastPeriodMonth;
  60. private $_lastPeriodYearMonth;
  61. //pv
  62. private $_pvRatio;
  63. const LOOP_FINISH = 1;
  64. const LOOP_CONTINUE = 2;
  65. const ORDER_PAY_TYPE_CASH = 'cash';
  66. // const ORDER_PAY_TYPE_POINT = 'point';
  67. /**
  68. * 设置期数
  69. * @param int $periodNum
  70. * @return int
  71. */
  72. public function setPeriodNum(int $periodNum) {
  73. return $this->_periodNum = $periodNum;
  74. }
  75. /**
  76. * 获取期数
  77. * @return int
  78. */
  79. public function getPeriodNum() {
  80. return $this->_periodNum;
  81. }
  82. /**
  83. * 加入错误错误
  84. * @param string $attr
  85. * @param string $error
  86. */
  87. public function addError(string $attr, string $error) {
  88. $this->_errors[$attr][] = $error;
  89. }
  90. /**
  91. * 获取错误信息
  92. * @return array
  93. */
  94. public function getErrors() {
  95. return $this->_errors;
  96. }
  97. /**
  98. * 计算步骤
  99. * @param $periodNum
  100. * @param null $handleUserId
  101. * @return bool
  102. */
  103. public function calcStep($periodNum, $handleUserId = null) {
  104. try {
  105. $this->_errors = [];
  106. $this->setPeriodNum($periodNum);
  107. $this->_handleUserId = $handleUserId;
  108. $t1 = microtime(true);
  109. // 初始化结算任务
  110. $this->initCalcTask();
  111. // 设置结算状态
  112. $this->setCalcStatus('start');
  113. // 清空所有本期结算用到的缓存
  114. CalcCache::clearAll($this->_periodNum);
  115. // 清空会员推荐和接点关系缓存
  116. CalcCache::clearNetCache();
  117. // 清空相关表数据
  118. $this->clearTableData();
  119. $t2 = microtime(true);
  120. echo('初始化、清空缓存及相关数据表完成,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  121. $this->_updatePercent(10);
  122. // 计算月奖,才需要向缓存中加入按推荐深度的所有用户
  123. //修改每一期都缓存所有用户
  124. CalcCache::addUsers($this->_periodNum);
  125. $t3 = microtime(true);
  126. echo('向缓存中加入用户完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  127. $this->_updatePercent(20);
  128. // 周结,循环向上级计入业绩并加入业绩单
  129. $this->loopCalcPeriodPerfByDecOrder();
  130. $this->loopCalcPeriodPerfByOrderDec();
  131. $t4 = microtime(true);
  132. echo('计算周业绩表中的数据完成,耗时:' . round($t4 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  133. $this->_updatePercent(40);
  134. // 从会员的复销订单会员计算复销业绩并加入业绩单
  135. $this->loopCalcPerfByFXOrder();
  136. $this->loopCalcPerfByShopFXOrder();
  137. $t5 = microtime(true);
  138. echo('计算复销业绩并写入业绩单完成,耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  139. $this->_updatePercent(60);
  140. //本期业绩入库
  141. $this->loopWriteNowPerf();
  142. $t6 = microtime(true);
  143. echo('本期业绩入库完成,耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  144. $this->_updatePercent(70);
  145. //计算月业绩表中的数据
  146. $this->loopCalcMonthPerfTableData();
  147. $t7 = microtime(true);
  148. echo('计算月业绩表中的数据完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  149. $this->_updatePercent(80);
  150. //每月计算聘级
  151. // modify 聘级字段改成蓝星奖的 奖衔级别(蓝星奖的等级).不在使用荣衔奖金.聘级的等级切换成蓝星奖等级,
  152. // 此等级会影响团队将的封顶.
  153. // $this->loopCalcEmpLevel();
  154. $t8 = microtime(true);
  155. // echo('计算聘级完成,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  156. //$this->_updatePercent(90);
  157. //本月业绩入库
  158. $this->loopWriteMonthPerf();
  159. $t7 = microtime(true);
  160. echo('本月业绩入库完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  161. $this->_updatePercent(90);
  162. // 店服务奖/月节点
  163. $this->storePerf();
  164. $t8 = microtime(true);
  165. echo('店服务业绩计算,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  166. $this->_updatePercent(95);
  167. // // //达标业绩
  168. // $this->loopCalcPerfByStandardFXOrder();
  169. // // //达标业绩入库
  170. // $this->loopWriteStandardPerf();
  171. $t9 = microtime(true);
  172. echo('本月业绩入库完成,耗时:' . round($t9 - $t8, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  173. $this->_updatePercent(95);
  174. // 通过插入到perforder中的业绩订单数据,生成此业绩期活跃用户数据
  175. // $this->loopWriteActiveUser();
  176. $this->_updatePercent(100);
  177. $t10 = microtime(true);
  178. echo('业绩结算全部完成,共耗时:' . round($t10 - $t9, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  179. } catch (\Exception $e) {
  180. $this->errorCalcTask();
  181. $this->addError('calc', $e->getMessage());
  182. return false;
  183. }
  184. return true;
  185. }
  186. /**
  187. * 结算完成
  188. * @return bool
  189. */
  190. public function endCalcTask() {
  191. // 更新结算状态
  192. $this->setCalcStatus('end');
  193. //如果自动结算
  194. if(boolval($this->_sysConfig['autoCalcPeriod']['VALUE'])){
  195. $period = Period::instance();
  196. if($period->isLastSent($this->_periodNum)) {
  197. $bonusCalc = BonusCalc::instance();
  198. $asyncResult = $bonusCalc->calcStep($this->_periodNum);
  199. if ($asyncResult) {
  200. $bonusCalc->endCalcTask();
  201. } else {
  202. $bonusCalc->errorCalcTask();
  203. }
  204. return $asyncResult;
  205. }
  206. }
  207. }
  208. /**
  209. * 结算错误
  210. */
  211. public function errorCalcTask() {
  212. // 清空所有本期结算用到的缓存
  213. CalcCache::clearAll($this->_periodNum);
  214. // 更新结算状态
  215. $this->setCalcStatus('fail');
  216. }
  217. /**
  218. * 设置生成业绩单状态
  219. * @param $type
  220. * start|end|fail
  221. */
  222. public function setCalcStatus($type) {
  223. if ($type == 'start') {
  224. Period::updateAll(['IS_PERFING' => 1, 'IS_PERFED' => Period::PERF_NONE, 'PERF_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  225. } elseif ($type == 'end') {
  226. Period::updateAll(['IS_PERFING' => 0, 'IS_PERFED' => Period::PERF_FINISH, 'PERFED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  227. } elseif ($type == 'fail') {
  228. Period::updateAll(['IS_PERFING' => 0, 'IS_PERFED' => Period::PERF_FAIL, 'PERFED_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  229. }
  230. }
  231. /**
  232. * 初始化结算任务
  233. * @throws \yii\db\Exception
  234. */
  235. public function initCalcTask() {
  236. $this->_sysConfig = Cache::getSystemConfig();
  237. $this->_decLevelConfig = Cache::getDecLevelConfig();
  238. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  239. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  240. $periodNum = $this->_periodNum;
  241. // 获取本年月和上年月
  242. $periodObj = Period::instance();
  243. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  244. $this->_periodId = $periodDataArr['ID'];
  245. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  246. $this->_calcYear = $periodObj->getYear($periodNum);
  247. $this->_calcMonth = $periodObj->getMonth($periodNum);
  248. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  249. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  250. $this->_lastCalcYear = $lastYearMonthArr['year'];
  251. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  252. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  253. $this->_lastPeriodNum = $periodNum - 1;
  254. if (Period::isExistsPeriodNum($this->_lastPeriodNum)) {
  255. $this->_lastPeriodYear = $periodObj->getYear($this->_lastPeriodNum);
  256. $this->_lastPeriodMonth = $periodObj->getMonth($this->_lastPeriodNum);
  257. $this->_lastPeriodYearMonth = $periodObj->getYearMonth($this->_lastPeriodNum);
  258. } else {
  259. $this->_lastPeriodYear = 0;
  260. $this->_lastPeriodMonth = 0;
  261. $this->_lastPeriodYearMonth = 0;
  262. }
  263. $this->_pvRatio = $this->_sysConfig['pvRatio']['VALUE'];
  264. }
  265. /**
  266. * 清空相关表数据
  267. */
  268. public function clearTableData() {
  269. // 周业绩
  270. PerfPeriod::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  271. // 业绩单
  272. PerfOrder::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  273. // 删除活跃用户
  274. // PerfActiveUser::pageDeleteAll('PERIOD_NUM='.$this->_periodNum.' AND IS_SENT=0 ');
  275. // 月结时要清空的数据
  276. if ($this->_isCalcMonth) {
  277. // 月业绩表
  278. PerfMonth::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
  279. // 店服务业绩log表
  280. StorePerfLog::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
  281. //达标业绩表
  282. PerfStandard::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
  283. }
  284. }
  285. /**
  286. * 循环判断活跃会员,并入库
  287. * @param int $offset
  288. * @return bool
  289. * @throws \yii\db\Exception
  290. */
  291. public function loopWriteActiveUser($offset = 0) {
  292. echo sprintf("时间:[%s]本期活跃用户PerfOrder表中,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  293. // 从PerfOrder表中获取此周期的用户数据
  294. $data = PerfPeriod::findUseDbCalc()
  295. ->select('USER_ID')
  296. ->where('PERIOD_NUM=:PERIOD_NUM',[
  297. ':PERIOD_NUM' => $this->_periodNum
  298. ])->offset($offset)->limit($this->_limit)->asArray()->all();
  299. if ($data) {
  300. foreach ($data as $upv) {
  301. $userId = $upv['USER_ID'];
  302. // 判断用户每周是否是活跃用户
  303. $allData = PerfOrder::findUseDbCalc()
  304. ->select('USER_ID,PV,DEC_AMOUNT,PERIOD_NUM,CALC_MONTH,P_CALC_MONTH, DEC_SN,ORDER_CREATED_AT')
  305. ->where('PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',[
  306. ':PERIOD_NUM' => $this->_periodNum,
  307. ':USER_ID' => $userId
  308. ])
  309. ->orderBy('ORDER_CREATED_AT DESC')
  310. ->asArray()
  311. ->all();
  312. if($allData) {
  313. $this->weekMonthOrder($allData);
  314. unset($insertDataPeriodPerf, $allData);
  315. }
  316. unset($allData);
  317. }
  318. unset($data);
  319. return $this->loopWriteActiveUser($offset + $this->_limit);
  320. }
  321. return true;
  322. }
  323. // 活跃判断
  324. public function weekMonthOrder($data) {
  325. // 获取每个订单是周几,把他们分别放到各自的周里面.
  326. // 因为是自然月,所以需要知道是此月的几号,是此月的第几周.然后往前和往后推出时间戳范围内pv的累计之和是多少
  327. $one = 24*60*60; // 一天的时间戳
  328. $time_arr = [];
  329. foreach ($data as $orders) {
  330. $day = intval(date('d', $orders['ORDER_CREATED_AT'])); // 当月第多少号
  331. $weekDay = (date('w', $orders['ORDER_CREATED_AT']) == 0) ? 7 : date('w', $orders['ORDER_CREATED_AT']);// 周几 1-7
  332. $format = date('Y-m-d', $orders['ORDER_CREATED_AT']);
  333. $orderDayStart = strtotime($format.' 0:0:0');
  334. $orderDayEnd = strtotime($format.' 23:59:59');
  335. $startCaluc = $weekDay-1;
  336. $endCaluc = 7-$weekDay;
  337. $calucWeekStart = $orderDayStart - $startCaluc*$one;
  338. $calucWeekEnd = $orderDayEnd + $endCaluc*$one;
  339. if (!isset($time_arr[$calucWeekStart])) {
  340. $time_arr[$calucWeekStart] = array_merge($orders, [
  341. 'temp_start' => $calucWeekStart,
  342. 'temp_end' => $calucWeekEnd,
  343. 'calculate_total_pv' => $orders['PV']
  344. ]);
  345. } else {
  346. $time_arr[$calucWeekStart]['calculate_total_pv'] = $time_arr[$calucWeekStart]['calculate_total_pv'] + $orders['PV'];
  347. }
  348. }
  349. unset($data);
  350. $insert = [];
  351. // 循环判断,当周pv累计是否达到400
  352. foreach ($time_arr as $k => $v) {
  353. if ($v['calculate_total_pv'] >= $this->_sysConfig['activeUserPvCondition']['VALUE']) {
  354. // 如果个人业累计绩达400PV,取得连续四周活跃
  355. // 取出周末再增加三周的时间戳
  356. $insert[] = [
  357. 'ID' => SnowFake::instance()->generateId(),
  358. 'USER_ID' => $v['USER_ID'],
  359. 'PERIOD_NUM' => $v['PERIOD_NUM'],
  360. 'CALC_MONTH' => $v['CALC_MONTH'],
  361. 'P_CALC_MONTH' => $v['P_CALC_MONTH'],
  362. 'SRATR_AT' => $v['temp_start'],
  363. 'END_AT' => $v['temp_end']+(3*7*24*60*60),
  364. 'CREATED_AT' => time(),
  365. 'PV' => $v['calculate_total_pv'],
  366. ];
  367. }
  368. }
  369. PerfActiveUser::batchInsert($insert);
  370. unset($insert);
  371. return true;
  372. }
  373. /**
  374. * 周结,向上级算业绩,并计入业绩单
  375. * @param int $offset
  376. * @return bool
  377. * @throws \yii\db\Exception
  378. */
  379. public function loopCalcPeriodPerfByDecOrder($offset = 0) {
  380. // 循环获取全部报单
  381. $allData = DecOrder::findUseDbCalc()->select('ID,DEC_SN,ORDER_SN,USER_ID,TYPE,TO_USER_ID,IS_ADMIN,DEC_AMOUNT,DEC_PV,PERIOD_NUM,CALC_MONTH,IS_DEL,P_CALC_MONTH,CREATED_AT,DEC_ID')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DEL=0 AND TYPE='ZC'", [':PERIOD_NUM' => $this->_periodNum])->orderBy('CREATED_AT DESC,ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  382. if ($allData) {
  383. $insertPerfOrderData = [];
  384. foreach ($allData as $data) {
  385. // 是否关停等状态不能拿业绩
  386. if (!$this->isHasPerf($data['TO_USER_ID'])) {
  387. continue;
  388. }
  389. //零售单不累计业绩,仅存业绩单
  390. // if($data['TYPE']!='LS') {
  391. // 给自己增加PCS(个人消费)
  392. CalcCache::nowPeriodPerf($data['TO_USER_ID'], $this->_periodNum, [
  393. 'PV_PCS' => $data['DEC_PV'],
  394. 'PV_PCS_ZC' => $data['DEC_PV'],
  395. ]);
  396. // 把该会员加入到能拿到业绩的会员缓存中
  397. CalcCache::addHasPerfUsers($data['TO_USER_ID'], $this->_periodNum);
  398. //加入到报单会员中
  399. $toInfo = CalcCache::getUserInfo($data['TO_USER_ID'], $this->_periodNum);
  400. CalcCache::addHasBDUsers($data['TO_USER_ID'], $this->_periodNum, [
  401. 'TO_USER_ID' => $data['TO_USER_ID'],
  402. 'USER_ID' => $data['USER_ID'],
  403. 'DEC_ID' => $data['DEC_ID'],
  404. //考虑可能会移网的情况
  405. 'REC_USER_ID' => $toInfo['REC_UID'] ?? '',
  406. 'CON_USER_ID' => $toInfo['CON_UID'] ?? '',
  407. 'DEC_AMOUNT' => $data['DEC_AMOUNT'],
  408. 'DEC_PV' => $data['DEC_PV'],
  409. ]);
  410. // 给上追加业绩
  411. $this->loopNetworkParentDo($data['TO_USER_ID'], function ($parent) use (&$data) {
  412. // 给上级会员追加业绩到缓存中
  413. // CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
  414. // 'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
  415. // ]);
  416. // 给上级会员追加本期业绩到缓存中
  417. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  418. 'PV_' . $parent['LOCATION'] . 'L' => $data['DEC_PV'],
  419. 'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $data['DEC_PV'],
  420. 'PV_' . $parent['LOCATION'] . 'L_' . $data['TYPE'] => $data['DEC_PV'],
  421. ]);
  422. // 把该会员加入到能拿到业绩的会员缓存中
  423. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  424. unset($parent);
  425. });
  426. //给推荐关系累计增加业绩
  427. $this->loopRelationParentDo($data['TO_USER_ID'], function ($parent) use (&$data) {
  428. // 给上级会员追加业绩到缓存中
  429. // CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
  430. // 'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
  431. // ]);
  432. // 给上级会员追加本期业绩到缓存中
  433. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  434. 'PV_PSS' => $data['DEC_PV'],
  435. ]);
  436. // 把该会员加入到能拿到业绩的会员缓存中
  437. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  438. unset($parent);
  439. });
  440. // }
  441. // 写入业绩单表
  442. $decInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  443. $sn = PerfOrder::generateSN();
  444. $insertPerfOrderData[] = [
  445. 'ID' => SnowFake::instance()->generateId(),
  446. 'SN' => $sn,
  447. 'DEC_SN' => $data['DEC_SN'],
  448. 'DEC_TYPE' => strtoupper($data['TYPE']),
  449. 'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
  450. 'USER_ID' => $data['TO_USER_ID'],
  451. 'LAST_REC_USER_NAME' => $toInfo['REC_USER_NAME'],
  452. 'LAST_REC_REAL_NAME' => $toInfo['REC_REAL_NAME'],
  453. 'LAST_DEC_LV' => $toInfo['DEC_LV'],
  454. 'LAST_EMP_LV' => $toInfo['EMP_LV'],
  455. 'LAST_STATUS' => $toInfo['STATUS'],
  456. 'PV' => $data['DEC_PV'],
  457. 'DEC_AMOUNT' => $data['DEC_AMOUNT'],
  458. 'LAST_SUB_COM_ID' => $toInfo['SUB_COM_ID'],
  459. 'LAST_PROVINCE' => $toInfo['PROVINCE'],
  460. 'LAST_CITY' => $toInfo['CITY'],
  461. 'LAST_COUNTY' => $toInfo['COUNTY'],
  462. 'DEC_USER_ID' => $data['USER_ID'],
  463. 'LAST_DEC_DEC_LV' => $decInfo['DEC_LV'],
  464. 'LAST_DEC_SUB_COM_ID' => $decInfo['SUB_COM_ID'],
  465. 'LAST_DEC_PROVINCE' => $decInfo['DEC_PROVINCE'],
  466. 'LAST_DEC_CITY' => $decInfo['DEC_CITY'],
  467. 'LAST_DEC_COUNTY' => $decInfo['DEC_COUNTY'],
  468. 'PERIOD_NUM' => $this->_periodNum,
  469. 'CALC_MONTH' => $this->_calcYearMonth,
  470. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  471. 'CREATED_AT' => Date::nowTime(),
  472. 'CLOSED_AT' => 0,
  473. 'ORDER_CREATED_AT' => $data['CREATED_AT'],
  474. ];
  475. unset($data, $decInfo, $sn, $toInfo);
  476. }
  477. PerfOrder::batchInsert($insertPerfOrderData);
  478. unset($insertPerfOrderData, $allData, $snArr);
  479. return $this->loopCalcPeriodPerfByDecOrder($offset + $this->_limit);
  480. }
  481. unset($allData);
  482. return true;
  483. }
  484. /**
  485. * 周结,向上级算业绩,并计入业绩单
  486. * @param int $offset
  487. * @return bool
  488. * @throws \yii\db\Exception
  489. */
  490. public function loopCalcPeriodPerfByOrderDec($offset = 0) {
  491. // 循环获取全部报单
  492. $allData = OrderDec::findUseDbCalc()->select('CREATED_AT,ID,SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PV,PAY_AMOUNT,PAY_PV,PERIOD_NUM,PAY_TYPE')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DELETE=0 AND ORDER_TYPE=:ORDER_TYPE", [':PERIOD_NUM' => $this->_periodNum, ':ORDER_TYPE'=>'ZC'])->orderBy('ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  493. if ($allData) {
  494. $insertPerfOrderData = [];
  495. foreach ($allData as $data) {
  496. // 是否关停等状态不能拿业绩
  497. if (!$this->isHasPerf($data['USER_ID'])) {
  498. continue;
  499. }
  500. // 给自己增加PCS(个人消费)
  501. CalcCache::nowPeriodPerf($data['USER_ID'], $this->_periodNum, [
  502. 'PV_PCS' => $data['PAY_PV'],
  503. 'PV_PCS_ZC' => $data['PAY_PV'],
  504. ]);
  505. // 把该会员加入到能拿到业绩的会员缓存中
  506. CalcCache::addHasPerfUsers($data['USER_ID'], $this->_periodNum);
  507. //加入到报单会员中
  508. $toInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  509. CalcCache::addHasBDUsers($data['USER_ID'], $this->_periodNum, [
  510. 'TO_USER_ID' => $data['USER_ID'],
  511. 'USER_ID' => $toInfo['DEC_ID'],
  512. 'DEC_ID' => $toInfo['DEC_ID'],
  513. //考虑可能会移网的情况
  514. 'REC_USER_ID' => $toInfo['REC_UID'] ?? '',
  515. 'CON_USER_ID' => $toInfo['CON_UID'] ?? '',
  516. 'DEC_AMOUNT' => $data['ORDER_AMOUNT'],
  517. 'DEC_PV' => $data['PAY_PV'],
  518. ]);
  519. // 给上追加业绩
  520. $this->loopNetworkParentDo($data['USER_ID'], function ($parent) use (&$data) {
  521. // 给上级会员追加本期业绩到缓存中
  522. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  523. 'PV_' . $parent['LOCATION'] . 'L' => $data['PAY_PV'],
  524. 'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $data['PAY_PV'],
  525. 'PV_' . $parent['LOCATION'] . 'L_' . $data['ORDER_TYPE'] => $data['PAY_PV'],
  526. ]);
  527. // 把该会员加入到能拿到业绩的会员缓存中
  528. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  529. unset($parent);
  530. });
  531. //给推荐关系累计增加业绩
  532. $this->loopRelationParentDo($data['USER_ID'], function ($parent) use (&$data) {
  533. // 给上级会员追加本期业绩到缓存中
  534. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  535. 'PV_PSS' => $data['PAY_PV'],
  536. ]);
  537. // 把该会员加入到能拿到业绩的会员缓存中
  538. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  539. unset($parent);
  540. });
  541. // 写入业绩单表
  542. $decInfo = CalcCache::getUserInfo($toInfo['DEC_ID'], $this->_periodNum);
  543. $sn = PerfOrder::generateSN();
  544. $insertPerfOrderData[] = [
  545. 'ID' => SnowFake::instance()->generateId(),
  546. 'SN' => $sn,
  547. 'DEC_SN' => $data['SN'],
  548. 'DEC_TYPE' => strtoupper($data['ORDER_TYPE']),
  549. 'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
  550. 'USER_ID' => $data['USER_ID'],
  551. 'LAST_REC_USER_NAME' => $toInfo['REC_USER_NAME'],
  552. 'LAST_REC_REAL_NAME' => $toInfo['REC_REAL_NAME'],
  553. 'LAST_DEC_LV' => $toInfo['DEC_LV'],
  554. 'LAST_EMP_LV' => $toInfo['EMP_LV'],
  555. 'LAST_STATUS' => $toInfo['STATUS'],
  556. 'PV' => $data['PAY_PV'],
  557. 'DEC_AMOUNT' => $data['ORDER_AMOUNT'],
  558. 'LAST_SUB_COM_ID' => $toInfo['SUB_COM_ID'],
  559. 'LAST_PROVINCE' => $toInfo['PROVINCE'],
  560. 'LAST_CITY' => $toInfo['CITY'],
  561. 'LAST_COUNTY' => $toInfo['COUNTY'],
  562. 'DEC_USER_ID' => $toInfo['DEC_ID'],
  563. 'LAST_DEC_DEC_LV' => $decInfo['DEC_LV'],
  564. 'LAST_DEC_SUB_COM_ID' => $decInfo['SUB_COM_ID'],
  565. 'LAST_DEC_PROVINCE' => $decInfo['DEC_PROVINCE'],
  566. 'LAST_DEC_CITY' => $decInfo['DEC_CITY'],
  567. 'LAST_DEC_COUNTY' => $decInfo['DEC_COUNTY'],
  568. 'PERIOD_NUM' => $this->_periodNum,
  569. 'CALC_MONTH' => $this->_calcYearMonth,
  570. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  571. 'CREATED_AT' => Date::nowTime(),
  572. 'CLOSED_AT' => 0,
  573. 'ORDER_CREATED_AT' => $data['CREATED_AT']
  574. ];
  575. unset($data, $decInfo, $sn, $toInfo);
  576. }
  577. PerfOrder::batchInsert($insertPerfOrderData);
  578. unset($insertPerfOrderData, $allData, $snArr);
  579. return $this->loopCalcPeriodPerfByOrderDec($offset + $this->_limit);
  580. }
  581. unset($allData);
  582. return true;
  583. }
  584. /**
  585. * 从会员的复销订单会员计算复销业绩并加入业绩单
  586. * @param int $offset
  587. * @return bool
  588. * @throws \yii\db\Exception
  589. */
  590. public function loopCalcPerfByFXOrder(int $offset = 0) {
  591. // 循环获取全部报单
  592. $allData = Order::findUseDbCalc()->select('ID,SN,DEC_SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PAY_AMOUNT,PAY_PV,PAY_TYPE,PERIOD_NUM,STATUS,IS_DELETE,P_CALC_MONTH,CREATED_AT')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DELETE=0 AND ORDER_TYPE=:ORDER_TYPE", [':PERIOD_NUM' => $this->_periodNum, ':ORDER_TYPE'=>DeclarationForm::TYPE_FX])->orderBy('CREATED_AT DESC,ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  593. if ($allData) {
  594. $insertPerfOrderData = [];
  595. foreach ($allData as $data) {
  596. // 是否关停等状态不能拿业绩
  597. if (!$this->isHasPerf($data['USER_ID'])) {
  598. continue;
  599. }
  600. //如果支付方式是现金,那么实际业绩是支付PV的50%
  601. if( $data['PAY_TYPE'] === self::ORDER_PAY_TYPE_CASH ) {
  602. $orderCashAmount = $data['ORDER_AMOUNT'];
  603. //111期开始由50%改为60%-by 2020-04-30修改
  604. $payPv = $data['PAY_PV'] * $this->_sysConfig['cashReconsumeBonusPercent']['VALUE'] / 100;
  605. $cacheDataKey = 'PV_PCS_FX_CASH';
  606. }else {
  607. $orderCashAmount = 0;
  608. $payPv = $data['PAY_PV'];
  609. $cacheDataKey = 'PV_PCS_FX_POINT';
  610. }
  611. if( $payPv <= 0 ) continue;
  612. // 给自己增加PCS(个人消费)
  613. CalcCache::nowPeriodPerf($data['USER_ID'], $this->_periodNum, [
  614. 'FX_AMOUNT_CASH' => $orderCashAmount,
  615. 'PV_PCS' => $payPv,
  616. 'PV_PCS_FX' => $payPv,
  617. $cacheDataKey => $payPv,
  618. ]);
  619. // 把该会员加入到能拿到业绩的会员缓存中
  620. CalcCache::addHasPerfUsers($data['USER_ID'], $this->_periodNum);
  621. // 给上追加业绩
  622. try {
  623. $this->loopNetworkParentDo($data['USER_ID'], function ($parent) use (&$data, $payPv) {
  624. // 给上级会员追加业绩到缓存中
  625. // CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
  626. // 'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
  627. // ]);
  628. // 给上级会员追加本期业绩到缓存中
  629. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  630. 'PV_' . $parent['LOCATION'] . 'L' => $payPv,
  631. 'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $payPv,
  632. 'PV_' . $parent['LOCATION'] . 'L_FX' => $payPv,
  633. ]);
  634. // 把该会员加入到能拿到业绩的会员缓存中
  635. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  636. });
  637. } catch(\Exception $e) {
  638. file_put_contents('loopNetworkParentDo_error.txt', var_export([
  639. 'USER_ID' => $data['USER_ID'],
  640. '_periodNum' => $this->_periodNum,
  641. 'error' => $e->getMessage()
  642. ],true));
  643. }
  644. //给推荐关系累计增加业绩
  645. $this->loopRelationParentDo($data['USER_ID'], function ($parent) use ($data, $payPv) {
  646. // 给上级会员追加业绩到缓存中
  647. // CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
  648. // 'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
  649. // ]);
  650. // 给上级会员追加本期业绩到缓存中
  651. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  652. 'PV_PSS' => $payPv,
  653. ]);
  654. // 把该会员加入到能拿到业绩的会员缓存中
  655. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  656. });
  657. // }
  658. // 写入业绩单表
  659. $baseInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  660. $sn = PerfOrder::generateSN();
  661. $insertPerfOrderData[] = [
  662. 'ID' => SnowFake::instance()->generateId(),
  663. 'SN' => $sn,
  664. 'DEC_SN' => null,
  665. 'DEC_TYPE' => 'FX',
  666. 'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
  667. 'USER_ID' => $data['USER_ID'],
  668. 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
  669. 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
  670. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  671. 'LAST_EMP_LV' => $baseInfo['EMP_LV'],
  672. 'LAST_STATUS' => $baseInfo['STATUS'],
  673. 'PV' => $payPv,
  674. 'DEC_AMOUNT' => $data['PAY_AMOUNT'],
  675. 'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  676. 'LAST_PROVINCE' => $baseInfo['PROVINCE'],
  677. 'LAST_CITY' => $baseInfo['CITY'],
  678. 'LAST_COUNTY' => $baseInfo['COUNTY'],
  679. 'DEC_USER_ID' => $data['USER_ID'],
  680. 'LAST_DEC_DEC_LV' => $baseInfo['DEC_LV'],
  681. 'LAST_DEC_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  682. 'LAST_DEC_PROVINCE' => $baseInfo['PROVINCE'],
  683. 'LAST_DEC_CITY' => $baseInfo['CITY'],
  684. 'LAST_DEC_COUNTY' => $baseInfo['COUNTY'],
  685. 'PERIOD_NUM' => $this->_periodNum,
  686. 'CALC_MONTH' => $this->_calcYearMonth,
  687. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  688. 'CREATED_AT' => Date::nowTime(),
  689. 'CLOSED_AT' => 0,
  690. 'ORDER_CREATED_AT' => $data['CREATED_AT']
  691. ];
  692. unset($data, $baseInfo, $sn, $orderCashAmount, $payPv, $cacheDataKey);
  693. }
  694. PerfOrder::batchInsert($insertPerfOrderData);
  695. unset($insertPerfOrderData, $allData, $snArr);
  696. return $this->loopCalcPerfByFXOrder($offset + $this->_limit);
  697. }
  698. unset($allData);
  699. return true;
  700. }
  701. /**
  702. * 从会员的商城复销订单会员计算复销业绩并加入业绩单
  703. * @param int $offset
  704. * @return bool
  705. * @throws \yii\db\Exception
  706. */
  707. public function loopCalcPerfByShopFXOrder(int $offset = 0) {
  708. // 循环获取全部报单
  709. $allData = OrderShop::findUseDbCalc()->select('ID,SN,DEC_SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PAY_AMOUNT,PAY_PV,PAY_TYPE,PERIOD_NUM,STATUS,IS_DELETE,P_CALC_MONTH,CREATED_AT')->where("PERIOD_NUM=:PERIOD_NUM AND IS_DELETE=0 AND ORDER_TYPE=:ORDER_TYPE", [':PERIOD_NUM' => $this->_periodNum, ':ORDER_TYPE'=>DeclarationForm::TYPE_FX])->orderBy('CREATED_AT DESC,ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  710. if ($allData) {
  711. $insertPerfOrderData = [];
  712. foreach ($allData as $data) {
  713. // 是否关停等状态不能拿业绩
  714. if (!$this->isHasPerf($data['USER_ID'])) {
  715. continue;
  716. }
  717. //如果支付方式是现金,那么实际业绩是支付PV的50%
  718. if( $data['PAY_TYPE'] === self::ORDER_PAY_TYPE_CASH ) {
  719. $orderCashAmount = $data['ORDER_AMOUNT'];
  720. //111期开始由50%改为60%-by 2020-04-30修改
  721. $payPv = $data['PAY_PV'] * $this->_sysConfig['cashReconsumeBonusPercent']['VALUE'] / 100;
  722. $cacheDataKey = 'PV_PCS_FX_CASH';
  723. }else {
  724. $orderCashAmount = 0;
  725. $payPv = $data['PAY_PV'];
  726. $cacheDataKey = 'PV_PCS_FX_POINT';
  727. }
  728. if( $payPv <= 0 ) continue;
  729. // 给自己增加PCS(个人消费)
  730. CalcCache::nowPeriodPerf($data['USER_ID'], $this->_periodNum, [
  731. 'FX_AMOUNT_CASH' => $orderCashAmount,
  732. 'PV_PCS' => $payPv,
  733. 'PV_PCS_FX' => $payPv,
  734. $cacheDataKey => $payPv,
  735. ]);
  736. // 把该会员加入到能拿到业绩的会员缓存中
  737. CalcCache::addHasPerfUsers($data['USER_ID'], $this->_periodNum);
  738. // 给上追加业绩
  739. $this->loopNetworkParentDo($data['USER_ID'], function ($parent) use (&$data, $payPv) {
  740. // 给上级会员追加业绩到缓存中
  741. // CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
  742. // 'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
  743. // ]);
  744. // 给上级会员追加本期业绩到缓存中
  745. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  746. 'PV_' . $parent['LOCATION'] . 'L' => $payPv,
  747. 'PV_' . $parent['LOCATION'] . 'L_TOUCH' => $payPv,
  748. 'PV_' . $parent['LOCATION'] . 'L_FX' => $payPv,
  749. ]);
  750. // 把该会员加入到能拿到业绩的会员缓存中
  751. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  752. });
  753. //给推荐关系累计增加业绩
  754. $this->loopRelationParentDo($data['USER_ID'], function ($parent) use ($data, $payPv) {
  755. // 给上级会员追加业绩到缓存中
  756. // CalcCache::addUserPerf($parent['PARENT_UID'], $this->_periodNum, [
  757. // 'PV_'.$parent['LOCATION'].'L' => $data['DEC_PV'],
  758. // ]);
  759. // 给上级会员追加本期业绩到缓存中
  760. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  761. 'PV_PSS' => $payPv,
  762. ]);
  763. // 把该会员加入到能拿到业绩的会员缓存中
  764. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  765. });
  766. // }
  767. // 写入业绩单表
  768. $baseInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  769. $sn = PerfOrder::generateSN();
  770. $insertPerfOrderData[] = [
  771. 'ID' => SnowFake::instance()->generateId(),
  772. 'SN' => $sn,
  773. 'DEC_SN' => null,
  774. 'DEC_TYPE' => 'FX',
  775. 'DEC_STATUS' => PerfOrder::STATUS_NORMAL,
  776. 'USER_ID' => $data['USER_ID'],
  777. 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
  778. 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
  779. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  780. 'LAST_EMP_LV' => $baseInfo['EMP_LV'],
  781. 'LAST_STATUS' => $baseInfo['STATUS'],
  782. 'PV' => $payPv,
  783. 'DEC_AMOUNT' => $data['PAY_AMOUNT'],
  784. 'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  785. 'LAST_PROVINCE' => $baseInfo['PROVINCE'],
  786. 'LAST_CITY' => $baseInfo['CITY'],
  787. 'LAST_COUNTY' => $baseInfo['COUNTY'],
  788. 'DEC_USER_ID' => $data['USER_ID'],
  789. 'LAST_DEC_DEC_LV' => $baseInfo['DEC_LV'],
  790. 'LAST_DEC_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  791. 'LAST_DEC_PROVINCE' => $baseInfo['PROVINCE'],
  792. 'LAST_DEC_CITY' => $baseInfo['CITY'],
  793. 'LAST_DEC_COUNTY' => $baseInfo['COUNTY'],
  794. 'PERIOD_NUM' => $this->_periodNum,
  795. 'CALC_MONTH' => $this->_calcYearMonth,
  796. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  797. 'CREATED_AT' => Date::nowTime(),
  798. 'CLOSED_AT' => 0,
  799. 'ORDER_CREATED_AT' => $data['CREATED_AT']
  800. ];
  801. unset($data, $baseInfo, $sn, $orderCashAmount, $payPv, $cacheDataKey);
  802. }
  803. PerfOrder::batchInsert($insertPerfOrderData);
  804. unset($insertPerfOrderData, $allData, $snArr);
  805. return $this->loopCalcPerfByShopFXOrder($offset + $this->_limit);
  806. }
  807. unset($allData);
  808. return true;
  809. }
  810. /**
  811. * 达标复销订单
  812. * @param int $offset
  813. * @return bool
  814. * @throws \yii\db\Exception
  815. */
  816. public function loopCalcPerfByStandardFXOrder(int $offset = 0) {
  817. if (!$this->_isCalcMonth) {
  818. return true;
  819. }
  820. $allData = OrderStandard::findUseDbCalc()->select('ID,SN,DEC_SN,USER_ID,ORDER_TYPE,ORDER_AMOUNT,PAY_AMOUNT,PAY_PV,PAY_TYPE,PERIOD_NUM,STATUS,IS_DELETE,CREATED_AT')->where("CALC_MONTH=:CALC_MONTH", [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  821. if ($allData) {
  822. $insertPerfOrderData = [];
  823. foreach ($allData as $data) {
  824. // 是否关停等状态不能拿业绩
  825. if (!$this->isHasPerf($data['USER_ID'])) {
  826. continue;
  827. }
  828. //如果支付方式是现金,那么实际业绩是支付PV的50%
  829. if( $data['PAY_TYPE'] === self::ORDER_PAY_TYPE_CASH ) {
  830. $orderCashAmount = $data['ORDER_AMOUNT'];
  831. // $payPv = $data['PAY_PV'] * $this->_sysConfig['cashReconsumeBonusPercent']['VALUE'] / 100;
  832. }else {
  833. $orderCashAmount = 0;
  834. // $payPv = $data['PAY_PV'];
  835. }
  836. if( $orderCashAmount <= 0 ) continue;
  837. // 给自己增加个人业绩
  838. CalcCache::nowStandardMonthPerf($data['USER_ID'], $this->_periodNum, [
  839. 'AMOUNT_PCS' => $orderCashAmount,
  840. ]);
  841. // 把该会员加入到能拿到业绩的会员缓存中
  842. CalcCache::addHasStandardMonthPerfUsers($data['USER_ID'], $this->_periodNum);
  843. //只有无聘级业绩才向上累加
  844. $baseInfo = CalcCache::getUserInfo($data['USER_ID'], $this->_periodNum);
  845. if( $baseInfo['EMP_LV'] != EmployLevel::NO_LEVEL_ID ) {
  846. continue;
  847. }
  848. //给推荐团队添加团队业绩 注:如果些订单特别多的情况,可以分2步。先只计算个人业绩、然后根据个人业绩再计算团队业绩。
  849. //给推荐关系累计增加业绩
  850. $this->loopRelationParentDo($data['USER_ID'], function ($parent) use ($data, $orderCashAmount) {
  851. // 给上级会员追加本期业绩到缓存中
  852. CalcCache::nowStandardMonthPerf($parent['PARENT_UID'], $this->_periodNum, [
  853. 'AMOUNT_PSS' => $orderCashAmount,
  854. ]);
  855. // 把该会员加入到能拿到业绩的会员缓存中
  856. CalcCache::addHasStandardMonthPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  857. //获取parent聘级
  858. $parentUserInfo = CalcCache::getUserInfo($parent['PARENT_UID'], $this->_periodNum);
  859. if( $parentUserInfo['EMP_LV'] != EmployLevel::NO_LEVEL_ID ) {//如果碰到有聘级的业绩就不在向上累加了
  860. return self::LOOP_FINISH;
  861. }
  862. });
  863. unset($data, $baseInfo, $orderCashAmount);
  864. }
  865. unset($insertPerfOrderData, $allData, $snArr);
  866. return $this->loopCalcPerfByStandardFXOrder($offset + $this->_limit);
  867. }
  868. unset($allData);
  869. return true;
  870. }
  871. /**
  872. * 计算月业绩表相关的数据并写入数据库
  873. * @param int $offset
  874. * @return bool
  875. * @throws Exception
  876. * @throws \yii\db\Exception
  877. */
  878. public function loopCalcMonthPerfTableData(int $offset = 0) {
  879. if (!$this->_isCalcMonth) {
  880. return true;
  881. }
  882. echo sprintf("时间:[%s]月业绩,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  883. // 从缓存列表里面从底层往上倒序获取会员
  884. // $allData = PerfPeriod::findUseDbCalc()->from(PerfPeriod::tableName() . ' AS PP')->select('PP.USER_ID AS USER_ID, SUM(PP.PV_PCS) AS PV_PCS_SUM,SUM(PP.PV_PSS) AS PV_PSS_SUM,SUM(PP.PV_1L) AS PV_1L_SUM,SUM(PP.PV_2L) AS PV_2L_SUM,SUM(PP.PV_3L) AS PV_3L_SUM,SUM(PP.PV_4L) AS PV_4L_SUM,SUM(PP.PV_5L) AS PV_5L_SUM, SUM(PM.PV_1L_TOTAL) AS PV_1L_TOTAL, SUM(PM.PV_2L_TOTAL) AS PV_2L_TOTAL, SUM(PM.PV_3L_TOTAL) AS PV_3L_TOTAL, SUM(PM.PV_4L_TOTAL) AS PV_4L_TOTAL,SUM(PM.PV_5L_TOTAL) AS PV_5L_TOTAL, SUM(PM.PV_PSS_TOTAL) AS PV_PSS_TOTAL')->leftJoin(PerfMonth::tableName() . ' AS PM', 'PM.USER_ID=PP.USER_ID AND PM.CALC_MONTH=:LAST_CALC_MONTH', ['LAST_CALC_MONTH'=>$this->_lastCalcYearMonth])->where('PP.CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->groupBy('PP.USER_ID')->orderBy('PP.USER_ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  885. $allData = PerfPeriod::findUseDbCalc()->select('USER_ID, SUM(FX_AMOUNT_CASH) AS FX_AMOUNT_CASH_SUM,SUM(PV_PCS) AS PV_PCS_SUM,SUM(PV_PCS_FX) AS PV_PCS_FX_SUM,SUM(PV_PSS) AS PV_PSS_SUM,SUM(PV_1L) AS PV_1L_SUM,SUM(PV_2L) AS PV_2L_SUM,SUM(PV_3L) AS PV_3L_SUM,SUM(PV_4L) AS PV_4L_SUM,SUM(PV_5L) AS PV_5L_SUM,SUM(PV_1L_ZC) AS PV_1L_ZC_SUM,SUM(PV_2L_ZC) AS PV_2L_ZC_SUM,SUM(PV_3L_ZC) AS PV_3L_ZC_SUM,SUM(PV_4L_ZC) AS PV_4L_ZC_SUM,SUM(PV_5L_ZC) AS PV_5L_ZC_SUM')->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->groupBy('USER_ID')->orderBy('USER_ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  886. if ($allData) {
  887. // 月度业绩表
  888. foreach ($allData as $everyData) {
  889. $userId = $everyData['USER_ID'];
  890. // $lastMonthData = PerfMonth::find()->select('PV_1L_TOTAL, PV_2L_TOTAL, PV_3L_TOTAL, PV_4L_TOTAL, PV_5L_TOTAL, PV_PSS_TOTAL')->where('USER_ID=:USER_ID AND CALC_MONTH=:LAST_CALC_MONTH', [
  891. // 'USER_ID'=>$userId,
  892. // 'LAST_CALC_MONTH'=>$this->_lastCalcYearMonth,
  893. // ])->asArray()->one();
  894. //往期业绩
  895. $userLastPerf = CalcCache::userPerf($userId, $this->_periodNum);
  896. //本期业绩
  897. $periodPerf = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  898. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  899. //级别必须为VIP
  900. $isVip = false;
  901. if( $userBaseInfo['DEC_LV'] === DeclarationLevel::VIP_LEVEL_ID ) {
  902. $isVip= true;
  903. }
  904. if( $this->_sysConfig['vipBonusGoldDecLevel']['VALUE'] && $userBaseInfo['DEC_LV'] === DeclarationLevel::JIN_ZUAN_LEVEL_ID ) {
  905. $isVip = true;
  906. }
  907. $nowMonthPerf = [
  908. 'USER_ID' => $userId,
  909. 'FX_AMOUNT_CASH' => $everyData['FX_AMOUNT_CASH_SUM'],
  910. 'PV_PCS' => $everyData['PV_PCS_SUM'],
  911. 'PV_PCS_FX' => $everyData['PV_PCS_FX_SUM'],
  912. 'PV_PSS' => $everyData['PV_PSS_SUM'],
  913. 'PV_1L' => $everyData['PV_1L_SUM'],
  914. 'PV_2L' => $everyData['PV_2L_SUM'],
  915. 'PV_3L' => $everyData['PV_3L_SUM'],
  916. 'PV_4L' => $everyData['PV_4L_SUM'],
  917. 'PV_5L' => $everyData['PV_5L_SUM'],
  918. //VIP统计相关业绩
  919. 'VIP_PV_1L_ZC' => $isVip ? $everyData['PV_1L_ZC_SUM'] : 0,
  920. 'VIP_PV_2L_ZC' => $isVip ? $everyData['PV_2L_ZC_SUM'] : 0,
  921. 'VIP_PV_3L_ZC' => $isVip ? $everyData['PV_3L_ZC_SUM'] : 0,
  922. 'VIP_PV_4L_ZC' => $isVip ? $everyData['PV_4L_ZC_SUM'] : 0,
  923. 'VIP_PV_5L_ZC' => $isVip ? $everyData['PV_5L_ZC_SUM'] : 0,
  924. //总数据,历史+本期。不能用上月加本月,因为上月可能没业绩,上上个月有业绩。
  925. 'PV_1L_TOTAL' => $periodPerf['PV_1L'] + $userLastPerf['PV_1L'],
  926. 'PV_2L_TOTAL' => $periodPerf['PV_2L'] + $userLastPerf['PV_2L'],
  927. 'PV_3L_TOTAL' => $periodPerf['PV_3L'] + $userLastPerf['PV_3L'],
  928. 'PV_4L_TOTAL' => $periodPerf['PV_4L'] + $userLastPerf['PV_4L'],
  929. 'PV_5L_TOTAL' => $periodPerf['PV_5L'] + $userLastPerf['PV_5L'],
  930. 'PV_PSS_TOTAL' => $periodPerf['PV_PSS'] + $userLastPerf['PV_PSS_TOTAL'],
  931. ];
  932. // 把会员的月业绩写入缓存中,以便下面的奖金计算从缓冲中获取数据效率高
  933. CalcCache::addHasMonthPerfUsers($userId, $this->_periodNum);
  934. CalcCache::nowMonthPerf($userId, $this->_periodNum, $nowMonthPerf);
  935. unset($userId, $everyData, $nowMonthPerf, $lastMonthData, $userBaseInfo, $isVip);
  936. }
  937. unset($allData);
  938. $this->loopCalcMonthPerfTableData($offset + $this->_limit);
  939. }
  940. unset($allData);
  941. return true;
  942. }
  943. /**
  944. * 计算聘级
  945. * @param int $offset
  946. * @return bool
  947. * @throws Exception
  948. * @throws \yii\db\Exception
  949. */
  950. public function loopCalcEmpLevel(int $offset = 0) {
  951. if (!$this->_isCalcMonth) {
  952. return true;
  953. }
  954. echo sprintf("时间:[%s]计算聘级,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  955. // 从缓存列表里面从底层往上倒序获取会员
  956. $allData = CalcCache::getUsers($this->_periodNum, $offset, $this->_limit);
  957. if ($allData) {
  958. // 月度业绩表
  959. foreach ($allData as $userId) {
  960. $userInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  961. $nowMonthPerf = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  962. $empLevel = $this->checkEmpLevel($userId, $nowMonthPerf, $userInfo['EMP_LV']);
  963. //根据用户的级别判断 能否得到级别积分
  964. if( $empLevel['LEVEL_SCORE'] > 0 ) {
  965. CalcCache::nowMonthScore($userId, $this->_periodNum, [
  966. 'LEVEL_SCORE' => $empLevel['LEVEL_SCORE'],
  967. ]);
  968. CalcCache::addHasScoreUsers($userId, $this->_periodNum);
  969. }
  970. //更新月业绩的聘级和用户信息中的聘级
  971. CalcCache::nowMonthPerf($userId, $this->_periodNum, [
  972. 'EMP_LEVEL' => $empLevel['ID']
  973. ]);
  974. //为业绩单更新结算时聘级
  975. // PerfOrder::updateAll(['LAST_EMP_LV'=>$empLevel['ID']],'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',[':USER_ID'=>$userId,':PERIOD_NUM'=>$this->_periodNum]);
  976. $userEmpLevel = $this->_empLevelConfig[$userInfo['EMP_LV']];
  977. $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  978. //不降级
  979. if( $empLevel['SORT'] <= $userEmpLevelSort ) continue;
  980. $userInfo['EMP_LV'] = $empLevel['ID'];
  981. CalcCache::setUserInfo($userId, $this->_periodNum, $userInfo);
  982. //可以判断用户是否升级,能否得到升级积分
  983. //因为默认是不降级,直接获得升级积分
  984. $upgradeScore = 0;
  985. foreach ($this->_empLevelConfig as $everyEmpLevel) {
  986. if( $everyEmpLevel['SORT'] <= $userEmpLevelSort ) continue;
  987. if( $everyEmpLevel['SORT'] > $empLevel['SORT'] ) continue;
  988. $upgradeScore += $everyEmpLevel['UPGRADE_SCORE'];
  989. unset($everyEmpLevel);
  990. }
  991. if( $upgradeScore > 0 ) {
  992. CalcCache::nowMonthScore($userId, $this->_periodNum, [
  993. 'UPGRADE_SCORE' => $upgradeScore
  994. ]);
  995. CalcCache::addHasScoreUsers($userId, $this->_periodNum);
  996. }
  997. unset($userId, $empLevel, $nowMonthPerf, $userInfo, $userEmpLevel, $userEmpLevelSort, $upgradeScore);
  998. }
  999. unset($allData);
  1000. $this->loopCalcEmpLevel($offset + $this->_limit);
  1001. }
  1002. unset($allData);
  1003. return true;
  1004. }
  1005. /**
  1006. * 计算公司总业绩
  1007. * @return bool
  1008. * @throws Exception
  1009. */
  1010. public function calcPerfCompany() {
  1011. if (!$this->_isCalcMonth) {
  1012. return true;
  1013. }
  1014. $perfCompany = PerfCompany::findOne(['CALC_MONTH' => $this->_calcYearMonth]);
  1015. $db = \Yii::$app->db;
  1016. $transaction = $db->beginTransaction();
  1017. try {
  1018. if (!$perfCompany) {
  1019. $perfCompany = new PerfCompany();
  1020. }
  1021. $perfCompany->PV = $this->_companyMonthPerf;
  1022. $perfCompany->CREATED_AT = Date::nowTime();
  1023. $perfCompany->CALC_YEAR = $this->_calcYear;
  1024. $perfCompany->CALC_MONTH = $this->_calcYearMonth;
  1025. if (!$perfCompany->save()) {
  1026. throw new Exception(Form::formatErrorsForApi($perfCompany->getErrors()));
  1027. }
  1028. $transaction->commit();
  1029. } catch (Exception $e) {
  1030. $transaction->rollBack();
  1031. throw new Exception($e->getMessage());
  1032. }
  1033. unset($perfCompany);
  1034. return true;
  1035. }
  1036. /**
  1037. * 循环有业绩会员,并入库
  1038. * @param int $offset
  1039. * @return bool
  1040. * @throws \yii\db\Exception
  1041. */
  1042. public function loopWriteNowPerf($offset = 0) {
  1043. echo sprintf("时间:[%s]缓存本期业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1044. // 从缓存列表里面从底层往上倒序获取会员
  1045. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  1046. if($allData){
  1047. $insertDataPeriodPerf = [];
  1048. foreach($allData as $userId){
  1049. $insertDataPeriodPerf[] = $this->nowPeriodPerfData($userId);
  1050. unset($userId);
  1051. }
  1052. PerfPeriod::batchInsert($insertDataPeriodPerf);
  1053. unset($insertDataPeriodPerf, $allData);
  1054. return $this->loopWriteNowPerf($offset + $this->_limit);
  1055. }
  1056. unset($allData);
  1057. return true;
  1058. }
  1059. /**
  1060. * 循环有月业绩会员,并入库
  1061. * @param int $offset
  1062. * @return bool
  1063. * @throws \yii\db\Exception
  1064. */
  1065. public function loopWriteMonthPerf($offset = 0) {
  1066. if(!$this->_isCalcMonth){
  1067. return true;
  1068. }
  1069. echo sprintf("时间:[%s]缓存本月业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1070. // 从缓存列表里面从底层往上倒序获取会员
  1071. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  1072. if($allData){
  1073. $insertDataMonthPerf = [];
  1074. foreach($allData as $userId){
  1075. $insertDataMonthPerf[] = $this->nowMonthPerfData($userId);
  1076. unset($userId);
  1077. }
  1078. PerfMonth::batchInsert($insertDataMonthPerf);
  1079. unset($insertDataMonthPerf, $allData);
  1080. return $this->loopWriteMonthPerf($offset + $this->_limit);
  1081. }
  1082. unset($allData);
  1083. return true;
  1084. }
  1085. /**
  1086. * 店服务奖,循环结算月所有数据,并计算小组业绩
  1087. * @param int $offset
  1088. * @return bool
  1089. * @throws \yii\db\Exception
  1090. */
  1091. public function storePerf($offset = 0) {
  1092. if(!$this->_isCalcMonth){
  1093. return true;
  1094. }
  1095. echo sprintf("时间:[%s]店服务奖业绩计算,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1096. $allData = PerfOrder::findUseDbCalc()
  1097. ->select('ID,USER_ID, SUM(PV) AS MONTH_PV, CALC_MONTH')
  1098. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1099. ->groupBy('USER_ID')
  1100. ->orderBy('USER_ID DESC')
  1101. ->offset($offset)
  1102. ->limit($this->_limit)
  1103. ->asArray()
  1104. ->all();
  1105. if ($allData) {
  1106. foreach ($allData as $everyData) {
  1107. $userId = $everyData['USER_ID'];
  1108. $pv = $everyData['MONTH_PV'];
  1109. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1110. $userRelation = CalcCache::getUserRelationInfo($userId, $this->_periodNum);
  1111. // 记录有业绩单的用户
  1112. StorePerfLog::addOrUpdate(
  1113. $this->_periodNum,
  1114. $this->_calcYearMonth,
  1115. $userId,
  1116. [
  1117. 'USER_ID' => $userId,
  1118. 'IS_STUDIO' => $userBaseInfo['IS_STUDIO'],
  1119. 'MONTH_PV' => $pv,
  1120. 'PERIOD_NUM' => $this->_periodNum,
  1121. 'CALC_MONTH' => $this->_calcYearMonth,
  1122. 'CREATE_AT' => time(),
  1123. 'PARENT_UID' => $userRelation['PARENT_UID']
  1124. ],
  1125. $pv
  1126. );
  1127. // 判断此用户是否是店铺,如果是店铺则累计此业绩到自己身上
  1128. if ($userBaseInfo['IS_STUDIO'] == 1) {
  1129. CalcCache::addHasPerfUsers($userId, $this->_periodNum);
  1130. CalcCache::nowPeriodPerf($userId, $this->_periodNum, [
  1131. 'STORE_PV_GRAND' => $pv,
  1132. ]);
  1133. } else {
  1134. // 如果此用户不是店铺,继续上找到店铺并累加上去PV
  1135. $this->loopRelationParentDo($userId, function ($parent) use (&$everyData) {
  1136. $parentUser = CalcCache::getUserInfo($parent['PARENT_UID'], $this->_periodNum);
  1137. $userRelation = CalcCache::getUserRelationInfo($parent['PARENT_UID'], $this->_periodNum);
  1138. $isStudio = $parentUser['IS_STUDIO'] == 1 ? true : false;
  1139. $appendPv = $isStudio ? $everyData['MONTH_PV'] : 0;
  1140. StorePerfLog::addOrUpdate(
  1141. $this->_periodNum,
  1142. $this->_calcYearMonth,
  1143. $parent['PARENT_UID'],
  1144. [
  1145. 'USER_ID' => $parent['PARENT_UID'],
  1146. 'IS_STUDIO' => $isStudio,
  1147. 'MONTH_PV' => 0,
  1148. 'PERIOD_NUM' => $this->_periodNum,
  1149. 'CALC_MONTH' => $this->_calcYearMonth,
  1150. 'CREATE_AT' => time(),
  1151. 'PARENT_UID' => $userRelation['PARENT_UID']
  1152. ],
  1153. $appendPv
  1154. );
  1155. if ($isStudio) {
  1156. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  1157. 'STORE_PV_GRAND' => $everyData['PV']
  1158. ]);
  1159. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  1160. return self::LOOP_FINISH;
  1161. }
  1162. unset($parent);
  1163. });
  1164. }
  1165. }
  1166. unset($allData);
  1167. return $this->storePerf($offset + $this->_limit);
  1168. }
  1169. unset($allData);
  1170. return true;
  1171. }
  1172. /**
  1173. * 循环达标业绩会员,并入库
  1174. * @param int $offset
  1175. * @return bool
  1176. * @throws \yii\db\Exception
  1177. */
  1178. public function loopWriteStandardPerf($offset = 0) {
  1179. if(!$this->_isCalcMonth){
  1180. return true;
  1181. }
  1182. echo sprintf("时间:[%s]缓存达标业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1183. // 从缓存列表里面从底层往上倒序获取会员
  1184. $allData = CalcCache::getHasStandardMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  1185. if($allData){
  1186. $insertDataStandardPerf = [];
  1187. foreach($allData as $userId) {
  1188. $data = CalcCache::nowStandardMonthPerf($userId, $this->_periodNum);
  1189. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1190. $insertDataStandardPerf[] = [
  1191. 'ID' => SnowFake::instance()->generateId(),
  1192. 'USER_ID' => $userId,
  1193. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1194. 'LAST_EMP_LV' => $baseInfo['EMP_LV'],
  1195. 'LAST_STATUS' => $baseInfo['STATUS'],
  1196. 'AMOUNT_PCS' => $data['AMOUNT_PCS'],
  1197. 'AMOUNT_PSS' => $data['AMOUNT_PSS'],
  1198. 'CALC_MONTH' => $this->_calcYearMonth,
  1199. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1200. 'CREATED_AT' => Date::nowTime(),
  1201. ];
  1202. unset($data, $baseInfo, $userId);
  1203. }
  1204. PerfStandard::batchInsert($insertDataStandardPerf);
  1205. unset($insertDataStandardPerf, $allData);
  1206. return $this->loopWriteStandardPerf($offset + $this->_limit);
  1207. }
  1208. unset($allData);
  1209. return true;
  1210. }
  1211. /**
  1212. * 本期业绩数据
  1213. * @param $userId
  1214. * @return array
  1215. */
  1216. public function nowPeriodPerfData($userId){
  1217. $data = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  1218. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1219. $result = [
  1220. 'ID' => SnowFake::instance()->generateId(),
  1221. 'USER_ID' => $userId,
  1222. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1223. 'LAST_EMP_LV' => $baseInfo['EMP_LV'],
  1224. 'LAST_STATUS' => $baseInfo['STATUS'],
  1225. 'FX_AMOUNT_CASH' => $data['FX_AMOUNT_CASH'],
  1226. 'PV_PCS' => $data['PV_PCS'],
  1227. 'PV_PSS' => $data['PV_PSS'],
  1228. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  1229. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  1230. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  1231. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  1232. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  1233. 'PV_PCS_FX_CASH' => $data['PV_PCS_FX_CASH'],
  1234. 'PV_PCS_FX_POINT' => $data['PV_PCS_FX_POINT'],
  1235. 'PV_1L' => $data['PV_1L'],
  1236. 'PV_1L_TOUCH' => $data['PV_1L_TOUCH'],
  1237. 'PV_1L_ZC' => $data['PV_1L_ZC'],
  1238. 'PV_1L_YH' => $data['PV_1L_YH'],
  1239. 'PV_1L_ZG' => $data['PV_1L_ZG'],
  1240. 'PV_1L_LS' => $data['PV_1L_LS'],
  1241. 'PV_1L_FX' => $data['PV_1L_FX'],
  1242. 'PV_2L' => $data['PV_2L'],
  1243. 'PV_2L_TOUCH' => $data['PV_2L_TOUCH'],
  1244. 'PV_2L_ZC' => $data['PV_2L_ZC'],
  1245. 'PV_2L_YH' => $data['PV_2L_YH'],
  1246. 'PV_2L_ZG' => $data['PV_2L_ZG'],
  1247. 'PV_2L_LS' => $data['PV_2L_LS'],
  1248. 'PV_2L_FX' => $data['PV_2L_FX'],
  1249. 'PV_3L' => $data['PV_3L'],
  1250. 'PV_3L_TOUCH' => $data['PV_3L_TOUCH'],
  1251. 'PV_3L_ZC' => $data['PV_3L_ZC'],
  1252. 'PV_3L_YH' => $data['PV_3L_YH'],
  1253. 'PV_3L_ZG' => $data['PV_3L_ZG'],
  1254. 'PV_3L_LS' => $data['PV_3L_LS'],
  1255. 'PV_3L_FX' => $data['PV_3L_FX'],
  1256. 'PV_4L' => $data['PV_4L'],
  1257. 'PV_4L_TOUCH' => $data['PV_4L_TOUCH'],
  1258. 'PV_4L_ZC' => $data['PV_4L_ZC'],
  1259. 'PV_4L_YH' => $data['PV_4L_YH'],
  1260. 'PV_4L_ZG' => $data['PV_4L_ZG'],
  1261. 'PV_4L_LS' => $data['PV_4L_LS'],
  1262. 'PV_4L_FX' => $data['PV_4L_FX'],
  1263. 'PV_5L' => $data['PV_5L'],
  1264. 'PV_5L_TOUCH' => $data['PV_5L_TOUCH'],
  1265. 'PV_5L_ZC' => $data['PV_5L_ZC'],
  1266. 'PV_5L_YH' => $data['PV_5L_YH'],
  1267. 'PV_5L_ZG' => $data['PV_5L_ZG'],
  1268. 'PV_5L_LS' => $data['PV_5L_LS'],
  1269. 'PV_5L_FX' => $data['PV_5L_FX'],
  1270. 'PV_LS_TOUCH' => $data['PV_LS_TOUCH'],
  1271. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  1272. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  1273. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  1274. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  1275. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  1276. 'SURPLUS_LS' => $data['SURPLUS_LS'],
  1277. 'PERIOD_NUM' => $this->_periodNum,
  1278. 'CALC_MONTH' => $this->_calcYearMonth,
  1279. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1280. 'CREATED_AT' => Date::nowTime(),
  1281. ];
  1282. unset($data);
  1283. return $result;
  1284. }
  1285. /**
  1286. * 本月业绩
  1287. * @param $userId
  1288. * @return array
  1289. */
  1290. public function nowMonthPerfData($userId){
  1291. $data = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  1292. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1293. $result = [
  1294. 'ID' => SnowFake::instance()->generateId(),
  1295. 'USER_ID' => $userId,
  1296. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1297. 'LAST_EMP_LV' => $data['EMP_LEVEL'],
  1298. 'LAST_STATUS' => $baseInfo['STATUS'],
  1299. 'FX_AMOUNT_CASH' => $data['FX_AMOUNT_CASH'],
  1300. 'PV_PCS' => $data['PV_PCS'],
  1301. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  1302. 'PV_PSS' => $data['PV_PSS'],
  1303. 'PV_1L' => $data['PV_1L'],
  1304. 'PV_2L' => $data['PV_2L'],
  1305. 'PV_3L' => $data['PV_3L'],
  1306. 'PV_4L' => $data['PV_4L'],
  1307. 'PV_5L' => $data['PV_5L'],
  1308. 'VIP_PV_1L_ZC' => $data['VIP_PV_1L_ZC'],
  1309. 'VIP_PV_2L_ZC' => $data['VIP_PV_2L_ZC'],
  1310. 'VIP_PV_3L_ZC' => $data['VIP_PV_3L_ZC'],
  1311. 'VIP_PV_4L_ZC' => $data['VIP_PV_4L_ZC'],
  1312. 'VIP_PV_5L_ZC' => $data['VIP_PV_5L_ZC'],
  1313. 'PV_1L_TOTAL' => $data['PV_1L_TOTAL'],
  1314. 'PV_2L_TOTAL' => $data['PV_2L_TOTAL'],
  1315. 'PV_3L_TOTAL' => $data['PV_3L_TOTAL'],
  1316. 'PV_4L_TOTAL' => $data['PV_4L_TOTAL'],
  1317. 'PV_5L_TOTAL' => $data['PV_5L_TOTAL'],
  1318. 'PV_PSS_TOTAL' => $data['PV_PSS_TOTAL'],
  1319. 'CF_PERCENT' => $data['CF_PERCENT'],
  1320. 'LX_PERCENT' => $data['LX_PERCENT'],
  1321. 'FX_STATUS' => $data['FX_STATUS'],
  1322. 'CALC_MONTH' => $this->_calcYearMonth,
  1323. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1324. 'CREATED_AT' => Date::nowTime(),
  1325. ];
  1326. unset($data);
  1327. return $result;
  1328. }
  1329. /**
  1330. * 循环父级并执行回调函数
  1331. * @param $userId
  1332. * @param callable $callbackFunc
  1333. * @param int $offset
  1334. * @return bool
  1335. */
  1336. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1337. $allParents = Cache::getAllNetworkParents($userId);
  1338. $allData = array_slice($allParents, $offset, $this->_limit);
  1339. unset($allParents);
  1340. if ($allData) {
  1341. foreach ($allData as $data) {
  1342. $funcResult = $callbackFunc($data);
  1343. if ($funcResult === self::LOOP_FINISH) {
  1344. return true;
  1345. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1346. continue;
  1347. }
  1348. unset($data, $funcResult);
  1349. }
  1350. unset($allData);
  1351. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1352. }
  1353. return true;
  1354. }
  1355. /**
  1356. * 循环推荐网络的父级
  1357. * @param $userId
  1358. * @param callable $callbackFunc
  1359. * @param int $offset
  1360. * @return bool
  1361. */
  1362. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1363. $allParents = Cache::getAllRelationParents($userId);
  1364. $allData = array_slice($allParents, $offset, $this->_limit);
  1365. unset($allParents);
  1366. if ($allData) {
  1367. foreach ($allData as $data) {
  1368. $funcResult = $callbackFunc($data);
  1369. if ($funcResult === self::LOOP_FINISH) {
  1370. return true;
  1371. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1372. continue;
  1373. }
  1374. unset($data, $funcResult);
  1375. }
  1376. unset($allData);
  1377. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1378. }
  1379. return true;
  1380. }
  1381. /**
  1382. * ==== 聘级计算开始 ====
  1383. */
  1384. /**
  1385. * 查看会员聘级
  1386. * @param $userId
  1387. * @param $nowMonthPerf
  1388. * @param $userEmpLevelId
  1389. * @return bool|mixed|\yii\db\ActiveRecord
  1390. */
  1391. public function checkEmpLevel($userId, $nowMonthPerf, $userEmpLevelId) {
  1392. $empLevel = $this->_empLevelConfig;
  1393. $userEmpLevel = $empLevel[$userEmpLevelId];
  1394. $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  1395. $childEmpLevelNumArr = CalcCache::hasEmpLevelNum($userId, $this->_periodNum);
  1396. // 判断主任到首席总监
  1397. $resultLevel = $this->isEmpLevelOther($empLevel, $childEmpLevelNumArr, $userEmpLevelSort);
  1398. unset($empLevel, $childEmpLevelNumArr);
  1399. if( empty($resultLevel) ) {
  1400. //不降级
  1401. if ( $userEmpLevelSort < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {
  1402. //主任
  1403. if ($checkLevel = $this->isEmpLevel1($userId, $nowMonthPerf)) {
  1404. $resultLevel = $checkLevel;
  1405. } else {// 无聘级会员
  1406. $resultLevel = EmployLevel::getLevelFromSort(EmployLevel::EMP_LEVEL_SORT['NO_LEVEL']);
  1407. }
  1408. }else {
  1409. $resultLevel = $userEmpLevel;
  1410. }
  1411. }
  1412. unset($userEmpLevel, $userEmpLevelSort);
  1413. // 获取到级别以后,给上级的相应人数中追加数量
  1414. $parentRecUserId = $userId;
  1415. $this->loopRelationParentDo($userId, function ($parent) use ($resultLevel, &$parentRecUserId) {
  1416. if( !$parentRecUserId ) return self::LOOP_FINISH;
  1417. //判断$parentRecUserId是否为$parent['PARENT_UID']的直推
  1418. $parentUid = $parent['PARENT_UID'];
  1419. $toInfo = CalcCache::getUserInfo($parentRecUserId, $this->_periodNum);
  1420. if( !isset($toInfo['REC_UID']) ) {
  1421. echo $parentRecUserId . PHP_EOL;
  1422. }
  1423. if( isset($toInfo['REC_UID']) && $parentUid !== $toInfo['REC_UID'] ) {
  1424. $parentUid = $toInfo['REC_UID'];
  1425. }
  1426. unset($toInfo);
  1427. if( !$parentUid ) self::LOOP_FINISH;
  1428. CalcCache::hasEmpLevelNum($parentUid, $this->_periodNum, [$parentRecUserId => [$resultLevel['ID'] => 1]]);
  1429. //每次记录上次的USER_ID
  1430. $parentRecUserId = $parentUid;
  1431. });
  1432. return $resultLevel;
  1433. }
  1434. /**
  1435. * 是否达到主任
  1436. * @param $userId
  1437. * @param $nowMonthPerf
  1438. * @return bool|mixed|\yii\db\ActiveRecord
  1439. * @throws \yii\db\Exception
  1440. */
  1441. public function isEmpLevel1($userId, $nowMonthPerf) {
  1442. $level1Option = EmployLevel::getLevelFromSort(EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL']);
  1443. //条件去除最大部门,其它部门累计50万
  1444. if( $nowMonthPerf['PV_PSS_TOTAL'] < $level1Option['OTHER_DEPART_PERF'] ) {//本身业绩就小于50万
  1445. unset($level1Option);
  1446. return false;
  1447. }
  1448. $oneDeepRelation = CalcCache::getChildrenOneDeepFromRedis($userId, $this->_periodNum);
  1449. if ( count($oneDeepRelation) <= 1 ) {//只有一个区就不判断了
  1450. unset($oneDeepRelation, $level1Option);
  1451. return false;
  1452. }
  1453. $maxPvPSS = 0;
  1454. $childPvPssTotalSum = 0;
  1455. foreach ($oneDeepRelation as $childData) {
  1456. //往期业绩
  1457. $userLastPerf = CalcCache::userPerf($childData['USER_ID'], $this->_periodNum);
  1458. //本期业绩
  1459. $periodPerf = CalcCache::nowPeriodPerf($childData['USER_ID'], $this->_periodNum);
  1460. $pvPcsTotal = $userLastPerf['PV_PCS_ZC'] + $userLastPerf['PV_PCS_FX'] + $periodPerf['PV_PCS'];
  1461. $pvPssTotal = $userLastPerf['PV_PSS_TOTAL'] + $periodPerf['PV_PSS'];
  1462. $childPvPssTotal = $pvPcsTotal + $pvPssTotal;
  1463. unset($userLastPerf, $periodPerf, $pvPcsTotal, $pvPssTotal);
  1464. $childPvPssTotalSum += $childPvPssTotal;
  1465. if( $childPvPssTotal >= $maxPvPSS ) {
  1466. $maxPvPSS = $childPvPssTotal;
  1467. }
  1468. unset($childData, $childPvPssTotal);
  1469. }
  1470. unset($oneDeepRelation);
  1471. if( $childPvPssTotalSum - $maxPvPSS >= $level1Option['OTHER_DEPART_PERF'] ) {
  1472. unset($maxPvPSS, $childPvPssTotalSum);
  1473. return $level1Option;
  1474. }else {
  1475. unset($maxPvPSS, $childPvPssTotalSum, $level1Option);
  1476. return false;
  1477. }
  1478. }
  1479. /**
  1480. * 是否达到其他级别
  1481. * @param $empLevel
  1482. * @param $childEmpLevelNumArr
  1483. * @param $userEmpLevelSort
  1484. * @return bool|mixed|\yii\db\ActiveRecord
  1485. */
  1486. public function isEmpLevelOther($empLevel, $childEmpLevelNumArr, $userEmpLevelSort) {
  1487. $resultLevel = [];
  1488. foreach ($empLevel as $level) {
  1489. if ($level['SORT'] < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL']) continue;
  1490. //不降级
  1491. if ($level['SORT'] <= $userEmpLevelSort) continue;
  1492. // 级别要求有几个区
  1493. $locationNum = $level['LOCATION_NUM'];
  1494. // 级别要求这几个区分别存在级别会员的数量
  1495. $minEmpNum = $level['MIN_EMPLOY_NUM'];
  1496. $minEmpLevel = $level['MIN_EMPLOY_LEVEL'];
  1497. if( !$minEmpLevel || !isset($empLevel[$minEmpLevel]) || $minEmpNum < 1 ) continue;
  1498. $minEmpLevelSort = $empLevel[$minEmpLevel]['SORT'];
  1499. $resultEmpLevelNumArr = array_filter($childEmpLevelNumArr, function ($item, $departUserId) use ($empLevel, $minEmpLevelSort, $minEmpNum) {
  1500. $tempEmpLevelNum = 0;
  1501. foreach ($item as $levelIndex => $levelNum) {
  1502. if ($empLevel[$levelIndex]['SORT'] >= $minEmpLevelSort && $levelNum >= $minEmpNum) {
  1503. $tempEmpLevelNum += 1;
  1504. }
  1505. }
  1506. return $tempEmpLevelNum >= 1;
  1507. }, ARRAY_FILTER_USE_BOTH);
  1508. if (count($resultEmpLevelNumArr) >= $locationNum) {
  1509. if( $level['SORT'] == EmployLevel::EMP_LEVEL_SORT['SHX_ZJ_LEVEL'] ) {
  1510. //首席总监还要满足一个条件、任意部门1个高级总监
  1511. $gjZjLevelNumArr = array_filter($childEmpLevelNumArr, function ($item, $departUserId) use ($empLevel) {
  1512. $tempEmpLevelNum = 0;
  1513. foreach ($item as $levelIndex => $levelNum) {
  1514. if ($empLevel[$levelIndex]['SORT'] >= EmployLevel::EMP_LEVEL_SORT['GJ_ZJ_LEVEL'] && $levelNum >= 1) {
  1515. $tempEmpLevelNum += 1;
  1516. }
  1517. }
  1518. return $tempEmpLevelNum >= 1;
  1519. }, ARRAY_FILTER_USE_BOTH);
  1520. if( count($gjZjLevelNumArr) >= 1 ) {
  1521. $resultLevel = $level;
  1522. }
  1523. unset($gjZjLevelNumArr);
  1524. }else {
  1525. $resultLevel = $level;
  1526. }
  1527. }
  1528. unset($level, $minEmpLevel, $minEmpLevelSort, $resultEmpLevelNumArr);
  1529. }
  1530. unset($empLevel, $childEmpLevelNumArr, $userEmpLevelSort);
  1531. return $resultLevel;
  1532. }
  1533. /**
  1534. * 是否可拿业绩(即注销、关停、停发状态)
  1535. * @param $userId
  1536. * @return bool
  1537. */
  1538. public function isHasPerf($userId) {
  1539. //@todo 所有人都有业绩
  1540. return true;
  1541. }
  1542. /**
  1543. * ==== 聘级计算结束 ====
  1544. */
  1545. /**
  1546. * 更新百分比并发送
  1547. * @param $percent
  1548. */
  1549. private function _updatePercent($percent) {
  1550. // 把数据写入数据库中
  1551. Period::updateAll(['PERF_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  1552. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'PERF_PERCENT']);
  1553. }
  1554. }