PerfCalc.php 71 KB

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