PerfCalc.php 81 KB

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