PerfCalc.php 66 KB

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