PerfCalc.php 76 KB

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