PerfCalc.php 71 KB

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