PerfCalc.php 75 KB

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