PerfCalc.php 76 KB

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