PerfCalc.php 71 KB

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