PerfCalc.php 76 KB

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