PerfCalc.php 81 KB

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