PerfCalc.php 82 KB

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