PerfCalc.php 81 KB

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