PerfCalc.php 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  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. StorePerfLog::addOrUpdate(
  1139. $this->_periodNum,
  1140. $this->_calcYearMonth,
  1141. $parent['PARENT_UID'],
  1142. [
  1143. 'USER_ID' => $parent['PARENT_UID'],
  1144. 'IS_STUDIO' => $parentUser['IS_STUDIO'],
  1145. 'MONTH_PV' => 0,
  1146. 'PERIOD_NUM' => $this->_periodNum,
  1147. 'CALC_MONTH' => $this->_calcYearMonth,
  1148. 'CREATE_AT' => time(),
  1149. 'PARENT_UID' => $userRelation['PARENT_UID']
  1150. ],
  1151. $everyData['MONTH_PV']
  1152. );
  1153. if ($parentUser['IS_STUDIO']) {
  1154. CalcCache::nowPeriodPerf($parent['PARENT_UID'], $this->_periodNum, [
  1155. 'STORE_PV_GRAND' => $everyData['MONTH_PV']
  1156. ]);
  1157. CalcCache::addHasPerfUsers($parent['PARENT_UID'], $this->_periodNum);
  1158. return self::LOOP_FINISH;
  1159. }
  1160. unset($parent);
  1161. });
  1162. }
  1163. }
  1164. unset($allData);
  1165. return $this->storePerf($offset + $this->_limit);
  1166. }
  1167. unset($allData);
  1168. return true;
  1169. }
  1170. /**
  1171. * 循环达标业绩会员,并入库
  1172. * @param int $offset
  1173. * @return bool
  1174. * @throws \yii\db\Exception
  1175. */
  1176. public function loopWriteStandardPerf($offset = 0) {
  1177. if(!$this->_isCalcMonth){
  1178. return true;
  1179. }
  1180. echo sprintf("时间:[%s]缓存达标业绩数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1181. // 从缓存列表里面从底层往上倒序获取会员
  1182. $allData = CalcCache::getHasStandardMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  1183. if($allData){
  1184. $insertDataStandardPerf = [];
  1185. foreach($allData as $userId) {
  1186. $data = CalcCache::nowStandardMonthPerf($userId, $this->_periodNum);
  1187. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1188. $insertDataStandardPerf[] = [
  1189. 'ID' => SnowFake::instance()->generateId(),
  1190. 'USER_ID' => $userId,
  1191. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1192. 'LAST_EMP_LV' => $baseInfo['EMP_LV'],
  1193. 'LAST_STATUS' => $baseInfo['STATUS'],
  1194. 'AMOUNT_PCS' => $data['AMOUNT_PCS'],
  1195. 'AMOUNT_PSS' => $data['AMOUNT_PSS'],
  1196. 'CALC_MONTH' => $this->_calcYearMonth,
  1197. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1198. 'CREATED_AT' => Date::nowTime(),
  1199. ];
  1200. unset($data, $baseInfo, $userId);
  1201. }
  1202. PerfStandard::batchInsert($insertDataStandardPerf);
  1203. unset($insertDataStandardPerf, $allData);
  1204. return $this->loopWriteStandardPerf($offset + $this->_limit);
  1205. }
  1206. unset($allData);
  1207. return true;
  1208. }
  1209. /**
  1210. * 本期业绩数据
  1211. * @param $userId
  1212. * @return array
  1213. */
  1214. public function nowPeriodPerfData($userId){
  1215. $data = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  1216. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1217. $result = [
  1218. 'ID' => SnowFake::instance()->generateId(),
  1219. 'USER_ID' => $userId,
  1220. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1221. 'LAST_EMP_LV' => $baseInfo['EMP_LV'],
  1222. 'LAST_STATUS' => $baseInfo['STATUS'],
  1223. 'FX_AMOUNT_CASH' => $data['FX_AMOUNT_CASH'],
  1224. 'PV_PCS' => $data['PV_PCS'],
  1225. 'PV_PSS' => $data['PV_PSS'],
  1226. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  1227. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  1228. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  1229. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  1230. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  1231. 'PV_PCS_FX_CASH' => $data['PV_PCS_FX_CASH'],
  1232. 'PV_PCS_FX_POINT' => $data['PV_PCS_FX_POINT'],
  1233. 'PV_1L' => $data['PV_1L'],
  1234. 'PV_1L_TOUCH' => $data['PV_1L_TOUCH'],
  1235. 'PV_1L_ZC' => $data['PV_1L_ZC'],
  1236. 'PV_1L_YH' => $data['PV_1L_YH'],
  1237. 'PV_1L_ZG' => $data['PV_1L_ZG'],
  1238. 'PV_1L_LS' => $data['PV_1L_LS'],
  1239. 'PV_1L_FX' => $data['PV_1L_FX'],
  1240. 'PV_2L' => $data['PV_2L'],
  1241. 'PV_2L_TOUCH' => $data['PV_2L_TOUCH'],
  1242. 'PV_2L_ZC' => $data['PV_2L_ZC'],
  1243. 'PV_2L_YH' => $data['PV_2L_YH'],
  1244. 'PV_2L_ZG' => $data['PV_2L_ZG'],
  1245. 'PV_2L_LS' => $data['PV_2L_LS'],
  1246. 'PV_2L_FX' => $data['PV_2L_FX'],
  1247. 'PV_3L' => $data['PV_3L'],
  1248. 'PV_3L_TOUCH' => $data['PV_3L_TOUCH'],
  1249. 'PV_3L_ZC' => $data['PV_3L_ZC'],
  1250. 'PV_3L_YH' => $data['PV_3L_YH'],
  1251. 'PV_3L_ZG' => $data['PV_3L_ZG'],
  1252. 'PV_3L_LS' => $data['PV_3L_LS'],
  1253. 'PV_3L_FX' => $data['PV_3L_FX'],
  1254. 'PV_4L' => $data['PV_4L'],
  1255. 'PV_4L_TOUCH' => $data['PV_4L_TOUCH'],
  1256. 'PV_4L_ZC' => $data['PV_4L_ZC'],
  1257. 'PV_4L_YH' => $data['PV_4L_YH'],
  1258. 'PV_4L_ZG' => $data['PV_4L_ZG'],
  1259. 'PV_4L_LS' => $data['PV_4L_LS'],
  1260. 'PV_4L_FX' => $data['PV_4L_FX'],
  1261. 'PV_5L' => $data['PV_5L'],
  1262. 'PV_5L_TOUCH' => $data['PV_5L_TOUCH'],
  1263. 'PV_5L_ZC' => $data['PV_5L_ZC'],
  1264. 'PV_5L_YH' => $data['PV_5L_YH'],
  1265. 'PV_5L_ZG' => $data['PV_5L_ZG'],
  1266. 'PV_5L_LS' => $data['PV_5L_LS'],
  1267. 'PV_5L_FX' => $data['PV_5L_FX'],
  1268. 'PV_LS_TOUCH' => $data['PV_LS_TOUCH'],
  1269. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  1270. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  1271. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  1272. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  1273. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  1274. 'SURPLUS_LS' => $data['SURPLUS_LS'],
  1275. 'PERIOD_NUM' => $this->_periodNum,
  1276. 'CALC_MONTH' => $this->_calcYearMonth,
  1277. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1278. 'CREATED_AT' => Date::nowTime(),
  1279. ];
  1280. unset($data);
  1281. return $result;
  1282. }
  1283. /**
  1284. * 本月业绩
  1285. * @param $userId
  1286. * @return array
  1287. */
  1288. public function nowMonthPerfData($userId){
  1289. $data = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  1290. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1291. $result = [
  1292. 'ID' => SnowFake::instance()->generateId(),
  1293. 'USER_ID' => $userId,
  1294. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  1295. 'LAST_EMP_LV' => $data['EMP_LEVEL'],
  1296. 'LAST_STATUS' => $baseInfo['STATUS'],
  1297. 'FX_AMOUNT_CASH' => $data['FX_AMOUNT_CASH'],
  1298. 'PV_PCS' => $data['PV_PCS'],
  1299. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  1300. 'PV_PSS' => $data['PV_PSS'],
  1301. 'PV_1L' => $data['PV_1L'],
  1302. 'PV_2L' => $data['PV_2L'],
  1303. 'PV_3L' => $data['PV_3L'],
  1304. 'PV_4L' => $data['PV_4L'],
  1305. 'PV_5L' => $data['PV_5L'],
  1306. 'VIP_PV_1L_ZC' => $data['VIP_PV_1L_ZC'],
  1307. 'VIP_PV_2L_ZC' => $data['VIP_PV_2L_ZC'],
  1308. 'VIP_PV_3L_ZC' => $data['VIP_PV_3L_ZC'],
  1309. 'VIP_PV_4L_ZC' => $data['VIP_PV_4L_ZC'],
  1310. 'VIP_PV_5L_ZC' => $data['VIP_PV_5L_ZC'],
  1311. 'PV_1L_TOTAL' => $data['PV_1L_TOTAL'],
  1312. 'PV_2L_TOTAL' => $data['PV_2L_TOTAL'],
  1313. 'PV_3L_TOTAL' => $data['PV_3L_TOTAL'],
  1314. 'PV_4L_TOTAL' => $data['PV_4L_TOTAL'],
  1315. 'PV_5L_TOTAL' => $data['PV_5L_TOTAL'],
  1316. 'PV_PSS_TOTAL' => $data['PV_PSS_TOTAL'],
  1317. 'CF_PERCENT' => $data['CF_PERCENT'],
  1318. 'LX_PERCENT' => $data['LX_PERCENT'],
  1319. 'FX_STATUS' => $data['FX_STATUS'],
  1320. 'CALC_MONTH' => $this->_calcYearMonth,
  1321. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1322. 'CREATED_AT' => Date::nowTime(),
  1323. ];
  1324. unset($data);
  1325. return $result;
  1326. }
  1327. /**
  1328. * 循环父级并执行回调函数
  1329. * @param $userId
  1330. * @param callable $callbackFunc
  1331. * @param int $offset
  1332. * @return bool
  1333. */
  1334. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1335. $allParents = Cache::getAllNetworkParents($userId);
  1336. $allData = array_slice($allParents, $offset, $this->_limit);
  1337. unset($allParents);
  1338. if ($allData) {
  1339. foreach ($allData as $data) {
  1340. $funcResult = $callbackFunc($data);
  1341. if ($funcResult === self::LOOP_FINISH) {
  1342. return true;
  1343. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1344. continue;
  1345. }
  1346. unset($data, $funcResult);
  1347. }
  1348. unset($allData);
  1349. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1350. }
  1351. return true;
  1352. }
  1353. /**
  1354. * 循环推荐网络的父级
  1355. * @param $userId
  1356. * @param callable $callbackFunc
  1357. * @param int $offset
  1358. * @return bool
  1359. */
  1360. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  1361. $allParents = Cache::getAllRelationParents($userId);
  1362. $allData = array_slice($allParents, $offset, $this->_limit);
  1363. unset($allParents);
  1364. if ($allData) {
  1365. foreach ($allData as $data) {
  1366. $funcResult = $callbackFunc($data);
  1367. if ($funcResult === self::LOOP_FINISH) {
  1368. return true;
  1369. } elseif ($funcResult === self::LOOP_CONTINUE) {
  1370. continue;
  1371. }
  1372. unset($data, $funcResult);
  1373. }
  1374. unset($allData);
  1375. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  1376. }
  1377. return true;
  1378. }
  1379. /**
  1380. * ==== 聘级计算开始 ====
  1381. */
  1382. /**
  1383. * 查看会员聘级
  1384. * @param $userId
  1385. * @param $nowMonthPerf
  1386. * @param $userEmpLevelId
  1387. * @return bool|mixed|\yii\db\ActiveRecord
  1388. */
  1389. public function checkEmpLevel($userId, $nowMonthPerf, $userEmpLevelId) {
  1390. $empLevel = $this->_empLevelConfig;
  1391. $userEmpLevel = $empLevel[$userEmpLevelId];
  1392. $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  1393. $childEmpLevelNumArr = CalcCache::hasEmpLevelNum($userId, $this->_periodNum);
  1394. // 判断主任到首席总监
  1395. $resultLevel = $this->isEmpLevelOther($empLevel, $childEmpLevelNumArr, $userEmpLevelSort);
  1396. unset($empLevel, $childEmpLevelNumArr);
  1397. if( empty($resultLevel) ) {
  1398. //不降级
  1399. if ( $userEmpLevelSort < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {
  1400. //主任
  1401. if ($checkLevel = $this->isEmpLevel1($userId, $nowMonthPerf)) {
  1402. $resultLevel = $checkLevel;
  1403. } else {// 无聘级会员
  1404. $resultLevel = EmployLevel::getLevelFromSort(EmployLevel::EMP_LEVEL_SORT['NO_LEVEL']);
  1405. }
  1406. }else {
  1407. $resultLevel = $userEmpLevel;
  1408. }
  1409. }
  1410. unset($userEmpLevel, $userEmpLevelSort);
  1411. // 获取到级别以后,给上级的相应人数中追加数量
  1412. $parentRecUserId = $userId;
  1413. $this->loopRelationParentDo($userId, function ($parent) use ($resultLevel, &$parentRecUserId) {
  1414. if( !$parentRecUserId ) return self::LOOP_FINISH;
  1415. //判断$parentRecUserId是否为$parent['PARENT_UID']的直推
  1416. $parentUid = $parent['PARENT_UID'];
  1417. $toInfo = CalcCache::getUserInfo($parentRecUserId, $this->_periodNum);
  1418. if( !isset($toInfo['REC_UID']) ) {
  1419. echo $parentRecUserId . PHP_EOL;
  1420. }
  1421. if( isset($toInfo['REC_UID']) && $parentUid !== $toInfo['REC_UID'] ) {
  1422. $parentUid = $toInfo['REC_UID'];
  1423. }
  1424. unset($toInfo);
  1425. if( !$parentUid ) self::LOOP_FINISH;
  1426. CalcCache::hasEmpLevelNum($parentUid, $this->_periodNum, [$parentRecUserId => [$resultLevel['ID'] => 1]]);
  1427. //每次记录上次的USER_ID
  1428. $parentRecUserId = $parentUid;
  1429. });
  1430. return $resultLevel;
  1431. }
  1432. /**
  1433. * 是否达到主任
  1434. * @param $userId
  1435. * @param $nowMonthPerf
  1436. * @return bool|mixed|\yii\db\ActiveRecord
  1437. * @throws \yii\db\Exception
  1438. */
  1439. public function isEmpLevel1($userId, $nowMonthPerf) {
  1440. $level1Option = EmployLevel::getLevelFromSort(EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL']);
  1441. //条件去除最大部门,其它部门累计50万
  1442. if( $nowMonthPerf['PV_PSS_TOTAL'] < $level1Option['OTHER_DEPART_PERF'] ) {//本身业绩就小于50万
  1443. unset($level1Option);
  1444. return false;
  1445. }
  1446. $oneDeepRelation = CalcCache::getChildrenOneDeepFromRedis($userId, $this->_periodNum);
  1447. if ( count($oneDeepRelation) <= 1 ) {//只有一个区就不判断了
  1448. unset($oneDeepRelation, $level1Option);
  1449. return false;
  1450. }
  1451. $maxPvPSS = 0;
  1452. $childPvPssTotalSum = 0;
  1453. foreach ($oneDeepRelation as $childData) {
  1454. //往期业绩
  1455. $userLastPerf = CalcCache::userPerf($childData['USER_ID'], $this->_periodNum);
  1456. //本期业绩
  1457. $periodPerf = CalcCache::nowPeriodPerf($childData['USER_ID'], $this->_periodNum);
  1458. $pvPcsTotal = $userLastPerf['PV_PCS_ZC'] + $userLastPerf['PV_PCS_FX'] + $periodPerf['PV_PCS'];
  1459. $pvPssTotal = $userLastPerf['PV_PSS_TOTAL'] + $periodPerf['PV_PSS'];
  1460. $childPvPssTotal = $pvPcsTotal + $pvPssTotal;
  1461. unset($userLastPerf, $periodPerf, $pvPcsTotal, $pvPssTotal);
  1462. $childPvPssTotalSum += $childPvPssTotal;
  1463. if( $childPvPssTotal >= $maxPvPSS ) {
  1464. $maxPvPSS = $childPvPssTotal;
  1465. }
  1466. unset($childData, $childPvPssTotal);
  1467. }
  1468. unset($oneDeepRelation);
  1469. if( $childPvPssTotalSum - $maxPvPSS >= $level1Option['OTHER_DEPART_PERF'] ) {
  1470. unset($maxPvPSS, $childPvPssTotalSum);
  1471. return $level1Option;
  1472. }else {
  1473. unset($maxPvPSS, $childPvPssTotalSum, $level1Option);
  1474. return false;
  1475. }
  1476. }
  1477. /**
  1478. * 是否达到其他级别
  1479. * @param $empLevel
  1480. * @param $childEmpLevelNumArr
  1481. * @param $userEmpLevelSort
  1482. * @return bool|mixed|\yii\db\ActiveRecord
  1483. */
  1484. public function isEmpLevelOther($empLevel, $childEmpLevelNumArr, $userEmpLevelSort) {
  1485. $resultLevel = [];
  1486. foreach ($empLevel as $level) {
  1487. if ($level['SORT'] < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL']) continue;
  1488. //不降级
  1489. if ($level['SORT'] <= $userEmpLevelSort) continue;
  1490. // 级别要求有几个区
  1491. $locationNum = $level['LOCATION_NUM'];
  1492. // 级别要求这几个区分别存在级别会员的数量
  1493. $minEmpNum = $level['MIN_EMPLOY_NUM'];
  1494. $minEmpLevel = $level['MIN_EMPLOY_LEVEL'];
  1495. if( !$minEmpLevel || !isset($empLevel[$minEmpLevel]) || $minEmpNum < 1 ) continue;
  1496. $minEmpLevelSort = $empLevel[$minEmpLevel]['SORT'];
  1497. $resultEmpLevelNumArr = array_filter($childEmpLevelNumArr, function ($item, $departUserId) use ($empLevel, $minEmpLevelSort, $minEmpNum) {
  1498. $tempEmpLevelNum = 0;
  1499. foreach ($item as $levelIndex => $levelNum) {
  1500. if ($empLevel[$levelIndex]['SORT'] >= $minEmpLevelSort && $levelNum >= $minEmpNum) {
  1501. $tempEmpLevelNum += 1;
  1502. }
  1503. }
  1504. return $tempEmpLevelNum >= 1;
  1505. }, ARRAY_FILTER_USE_BOTH);
  1506. if (count($resultEmpLevelNumArr) >= $locationNum) {
  1507. if( $level['SORT'] == EmployLevel::EMP_LEVEL_SORT['SHX_ZJ_LEVEL'] ) {
  1508. //首席总监还要满足一个条件、任意部门1个高级总监
  1509. $gjZjLevelNumArr = array_filter($childEmpLevelNumArr, function ($item, $departUserId) use ($empLevel) {
  1510. $tempEmpLevelNum = 0;
  1511. foreach ($item as $levelIndex => $levelNum) {
  1512. if ($empLevel[$levelIndex]['SORT'] >= EmployLevel::EMP_LEVEL_SORT['GJ_ZJ_LEVEL'] && $levelNum >= 1) {
  1513. $tempEmpLevelNum += 1;
  1514. }
  1515. }
  1516. return $tempEmpLevelNum >= 1;
  1517. }, ARRAY_FILTER_USE_BOTH);
  1518. if( count($gjZjLevelNumArr) >= 1 ) {
  1519. $resultLevel = $level;
  1520. }
  1521. unset($gjZjLevelNumArr);
  1522. }else {
  1523. $resultLevel = $level;
  1524. }
  1525. }
  1526. unset($level, $minEmpLevel, $minEmpLevelSort, $resultEmpLevelNumArr);
  1527. }
  1528. unset($empLevel, $childEmpLevelNumArr, $userEmpLevelSort);
  1529. return $resultLevel;
  1530. }
  1531. /**
  1532. * 是否可拿业绩(即注销、关停、停发状态)
  1533. * @param $userId
  1534. * @return bool
  1535. */
  1536. public function isHasPerf($userId) {
  1537. //@todo 所有人都有业绩
  1538. return true;
  1539. }
  1540. /**
  1541. * ==== 聘级计算结束 ====
  1542. */
  1543. /**
  1544. * 更新百分比并发送
  1545. * @param $percent
  1546. */
  1547. private function _updatePercent($percent) {
  1548. // 把数据写入数据库中
  1549. Period::updateAll(['PERF_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  1550. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'PERF_PERCENT']);
  1551. }
  1552. }