PerfCalc.php 76 KB

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