PerfCalc.php 71 KB

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