PerfCalc.php 76 KB

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