UserNetwork.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. namespace common\models;
  3. use common\components\ActiveRecord;
  4. use common\helpers\Cache;
  5. use common\helpers\NetPoint;
  6. use common\helpers\user\Info;
  7. use common\helpers\user\Perf;
  8. use Exception;
  9. use Yii;
  10. use yii\data\Pagination;
  11. use yii\helpers\Json;
  12. /**
  13. * This is the model class for table "{{%USER_NETWORK}}".
  14. *
  15. * @property string $ID
  16. * @property string $USER_ID 会员ID
  17. * @property string $PARENT_UID 相对上级会员ID
  18. * @property int $LOCATION_TAG 网体标记
  19. * @property int $RELATIVE_LOCATION 相对上级会员区位
  20. * @property string $TOP_UID 顶端会员ID
  21. * @property string $PARENT_UIDS 所有上级ID
  22. * @property int $TOP_DEEP 距离顶端会员深度
  23. * @property int $CREATED_AT 创建时间
  24. * @property int $UPDATED_AT 更新时间
  25. */
  26. class UserNetwork extends \common\components\ActiveRecord
  27. {
  28. /**
  29. * @inheritdoc
  30. */
  31. public static function tableName()
  32. {
  33. return '{{%USER_NETWORK_NEW}}';
  34. }
  35. /**
  36. * @inheritdoc
  37. */
  38. public function rules()
  39. {
  40. return [
  41. [['USER_ID', 'PARENT_UID', 'LOCATION', 'TOP_UID', 'TOP_DEEP', 'CREATED_AT'], 'required'],
  42. [['TOP_DEEP', 'PERIOD_NUM', 'RELATIVE_LOCATION', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
  43. [['ID', 'USER_ID', 'PARENT_UID', 'TOP_UID'], 'string', 'max' => 32],
  44. [['ID'], 'unique'],
  45. ];
  46. }
  47. /**
  48. * @inheritdoc
  49. */
  50. public function attributeLabels()
  51. {
  52. return [
  53. 'ID' => 'ID',
  54. 'USER_ID' => '会员ID',
  55. 'PARENT_UID' => '相对上级会员ID',
  56. 'LOCATION_TAG' => '网体标记',
  57. 'RELATIVE_LOCATION' => '相对父级的区位',
  58. 'TOP_UID' => '顶端会员ID',
  59. 'TOP_DEEP' => '距离顶端会员深度',
  60. 'PARENT_UIDS' => '所有上级ID',
  61. 'CREATED_AT' => '创建时间',
  62. 'UPDATED_AT' => '更新时间',
  63. ];
  64. }
  65. /**
  66. * 获取一层下级数量
  67. * @param $userId
  68. * @return int|string
  69. */
  70. public static function firstFloorChildNum($userId){
  71. return intval(UserInfo::find()->where('CON_UID=:CON_UID AND DELETED=0', [':CON_UID'=>$userId])->count());
  72. }
  73. /**
  74. * 分页获取上级会员
  75. * @param $userId
  76. * @param $offset
  77. * @param $limit
  78. * @param string $orderBy
  79. * @param bool $isSlaves
  80. * @param string $db
  81. * @return array|\yii\db\ActiveRecord[]
  82. */
  83. public static function getParentsWithOffset($userId, $offset, $limit, $orderBy='DESC', $isSlaves = false, $db = 'db'){
  84. $userNetInfo = static::find($isSlaves, $db)->select(['TOP_DEEP', 'PARENT_UIDS', 'LOCATION_TAG'])->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
  85. if( !$userNetInfo ) return [];
  86. $parentUidsStr = $userNetInfo['PARENT_UIDS'];
  87. if( !$parentUidsStr ) return [];
  88. $parentUidsArr = explode(',', $parentUidsStr);
  89. unset($parentUidsStr);
  90. if( $orderBy === 'DESC' ) {
  91. $parentUidsArr = array_reverse($parentUidsArr);
  92. }
  93. if( !$parentUidsArr ) return [];
  94. $pageParentUids = array_slice($parentUidsArr, $offset, $limit);
  95. unset($parentUidsArr);
  96. $parentList = [];
  97. foreach ($pageParentUids as $parentUid) {
  98. try {
  99. $parentNetInfo = static::find($isSlaves, $db)->select(['TOP_DEEP', 'LOCATION_TAG'])->where('USER_ID=:USER_ID', ['USER_ID'=>$parentUid])->asArray()->one();
  100. $parentList[] = [
  101. 'USER_ID' => $userId,
  102. 'TOP_DEEP' => $userNetInfo['TOP_DEEP'],
  103. 'PARENT_UID' => $parentUid,
  104. 'PARENT_DEEP' => $parentNetInfo['TOP_DEEP'],
  105. // 'LOCATION_TAG' => $userNetInfo['LOCATION_TAG'],
  106. // 'PARENT_LOCATION_TAG' => $parentNetInfo['LOCATION_TAG'],
  107. 'LOCATION' => substr($userNetInfo['LOCATION_TAG'], strlen($parentNetInfo['LOCATION_TAG']), 1),
  108. ];
  109. } catch (Exception $e) {
  110. $file_name = date('Y-m-d', time()).'_usernetwork.php_error.log';
  111. file_put_contents($file_name, var_export([
  112. '$parentUid' => $parentUid,
  113. '$userId' => $userId,
  114. 'error' => $e->getMessage()
  115. ],true), FILE_APPEND);
  116. }
  117. unset($parentUid, $parentNetInfo);
  118. }
  119. unset($pageParentUids, $userNetInfo);
  120. return $parentList;
  121. }
  122. /**
  123. * 分页获取上级会员结算库
  124. * @param $userId
  125. * @param $callbackFunc
  126. * @param $limit
  127. * @param int $offset
  128. * @param string $orderBy
  129. */
  130. public static function getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset = 0, $orderBy='DESC'){
  131. $allData = self::getParentsWithOffset($userId, $offset, $limit, $orderBy, false, 'dbCalc');
  132. if($allData){
  133. foreach($allData as $data){
  134. $callbackFunc($data);
  135. unset($data);
  136. }
  137. unset($allData);
  138. self::getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset + $limit);
  139. }
  140. }
  141. /**
  142. * 获取上一级父级的会员信息
  143. * @param $userId
  144. * @return array|null
  145. */
  146. public static function getFirstParentUserInfo($userId){
  147. $oneUserInfo = UserInfo::findOneAsArray(['USER_ID'=>$userId]);
  148. if($oneUserInfo['CON_UID']){
  149. return UserInfo::findOneAsArray(['USER_ID'=>$oneUserInfo['CON_UID']]);
  150. } else {
  151. return null;
  152. }
  153. }
  154. /**
  155. * 获取指定深度的子会员
  156. * @param $userId
  157. * @param $deep
  158. * @param string $orderBy
  159. * @return array
  160. */
  161. public static function getChildrenWithDeep($userId, $deep, $orderBy='TOP_DEEP ASC'){
  162. $userNetInfo = static::find()->select(['LOCATION_TAG', 'TOP_DEEP'])->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
  163. $childrenNetInfo = static::find()->select(['USER_ID', 'LOCATION_TAG', 'TOP_DEEP'])->where('LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP', ['LOCATION_TAG'=>$userNetInfo['LOCATION_TAG'] . '%', 'TOP_DEEP'=>$userNetInfo['TOP_DEEP'] + $deep])->orderBy($orderBy)->asArray()->all();
  164. foreach ($childrenNetInfo as $key => $childNetInfo) {
  165. $childrenNetInfo[$key]['LOCATION'] = substr($childNetInfo['LOCATION_TAG'], strlen($userNetInfo['LOCATION_TAG']), 1);
  166. unset($key, $childNetInfo);
  167. }
  168. unset($userNetInfo);
  169. return $childrenNetInfo;
  170. }
  171. /**
  172. * 获取下一层会员的接点信息
  173. * @param $userId
  174. * @return array|\yii\db\ActiveRecord[]
  175. */
  176. public static function getFirstFloorChildren($userId) {
  177. $childrenNetInfo = static::find()->select(['USER_ID', 'RELATIVE_LOCATION', 'LOCATION_TAG', 'TOP_DEEP'])->where('PARENT_UID=:PARENT_UID', ['PARENT_UID'=>$userId])->asArray()->all();
  178. unset($userNetInfo);
  179. return $childrenNetInfo;
  180. }
  181. /**
  182. * 查看所传父级节点会员是不是所传会员的父级
  183. * @param $userId
  184. * @param $parentUserId
  185. * @param null $periodNum
  186. * @return bool
  187. * @throws \yii\db\Exception
  188. */
  189. public static function isParentUser($userId, $parentUserId, $periodNum = null){
  190. $table = self::getTableNameFromPeriod($periodNum);
  191. $db = $table['db'];
  192. $tableName = $table['tableName'];
  193. $data = $db->createCommand("SELECT PARENT_UIDS FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  194. if( !$data ) {
  195. unset($table, $db, $tableName, $data);
  196. return false;
  197. }
  198. $parentListArr = explode(',', $data['PARENT_UIDS']);
  199. unset($table, $db, $tableName, $data);
  200. $existStatus = in_array($parentUserId, $parentListArr);
  201. unset($parentListArr);
  202. return $existStatus;
  203. }
  204. /**
  205. * 获取会员相较于父级的区位
  206. * @param $userId
  207. * @param $parentUserId
  208. * @param $periodNum
  209. * @return mixed|null
  210. */
  211. public static function getLocation($userId, $parentUserId, $periodNum = null){
  212. $table = self::getTableNameFromPeriod($periodNum);
  213. $db = $table['db'];
  214. $tableName = $table['tableName'];
  215. $userNetInfo = $db->createCommand("SELECT LOCATION_TAG FROM $tableName WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  216. if( !$userNetInfo || !isset($userNetInfo['LOCATION_TAG']) ) return 0;
  217. $parentNetInfo = $db->createCommand("SELECT LOCATION_TAG FROM $tableName WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  218. if( !$parentNetInfo || !isset($parentNetInfo['LOCATION_TAG']) ) return 0;
  219. $location = substr($userNetInfo['LOCATION_TAG'], strlen($parentNetInfo['LOCATION_TAG']), 1);
  220. return $location ? $location : 0;
  221. }
  222. /**
  223. * 获取子会员节点带着总深度和循环的子节点层级关系
  224. * @param $userId
  225. * @param $deep
  226. * @param int $loopedDeep
  227. * @param null $periodNum
  228. * @return mixed
  229. * @throws \yii\base\Exception
  230. * @throws \yii\db\Exception
  231. */
  232. public static function getChildrenWithDeepAndLayer($userId, $deep, $loopedDeep = 1, $periodNum=null){
  233. $allData = self::getChildrenFromPeriod($userId, $periodNum);
  234. if($allData){
  235. $decLevelConfig = Cache::getDecLevelConfig();
  236. $empLevelConfig = Cache::getEmpLevelConfig();
  237. $starLevelConfig = Cache::getStarCrownLevelConfig();
  238. foreach($allData as $key=>$data){
  239. // 获取用户的基本信息
  240. $baseInfo = Info::baseInfo($data['USER_ID'], $periodNum);
  241. $allData[$key] = array_merge($data, [
  242. 'USER_NAME' => $baseInfo['USER_NAME'],
  243. 'TOP_NETWORK_DEEP' => $data['TOP_DEEP'],
  244. 'REAL_NAME' => $baseInfo['REAL_NAME'],
  245. 'DEC_LV_NAME' => $decLevelConfig[$baseInfo['DEC_LV']]['LEVEL_NAME'],
  246. 'EMP_LV_NAME' => isset($empLevelConfig[$baseInfo['EMP_LV']])?$empLevelConfig[$baseInfo['EMP_LV']]['LEVEL_NAME']:'',
  247. 'STAR_LV_NAME' => $starLevelConfig[$baseInfo['STAR_LV']]['LEVEL_NAME'],
  248. // 'MOBILE' => $baseInfo['MOBILE'],
  249. 'PERIOD_AT' => $baseInfo['PERIOD_AT'],
  250. ]);
  251. // 获取字节点数量
  252. $childNum = self::firstFloorChildNumFromPeriod($data['USER_ID'], $periodNum);
  253. if($childNum > 0 && $loopedDeep < $deep){
  254. $child = self::getChildrenWithDeepAndLayer($data['USER_ID'], $deep, $loopedDeep + 1, $periodNum);
  255. $leaf = false;
  256. $icon = 'el-icon-user-solid';
  257. }
  258. elseif($childNum > 0){
  259. $child = null;
  260. $leaf = false;
  261. $icon = 'el-icon-user-solid';
  262. }
  263. else {
  264. $child = null;
  265. $leaf = true;
  266. $icon = 'el-icon-user';
  267. }
  268. $allData[$key]['children'] = $child;
  269. $allData[$key]['leaf'] = $leaf;
  270. $allData[$key]['icon'] = $icon;
  271. $allData[$key]['isExpanded'] = false;
  272. $allData[$key]['displayNone'] = 'display-none';
  273. }
  274. }
  275. return $allData;
  276. }
  277. /**
  278. * 通过期数获取应该查询哪个表和库
  279. * @param $periodNum
  280. * @return array
  281. */
  282. public static function getTableNameFromPeriod($periodNum = null){
  283. $db = self::getDb();
  284. $tableName = self::tableName();
  285. // if($periodNum !== null){
  286. // // 获取当前期数
  287. // $period = Period::instance();
  288. // $nowPeriodNum = $period->getNowPeriodNum();
  289. // if($nowPeriodNum != $periodNum){
  290. // // 从备份库里找到期数对应的网络
  291. // if(ActiveRecord::isExistsTable('{{%USER_NETWORK_'.$periodNum.'}}', 'dbNetPoint')){
  292. // $db = Yii::$app->dbNetPoint;
  293. // $tableName = '{{%USER_NETWORK_'.$periodNum.'}}';
  294. // }
  295. // }
  296. // }
  297. return [
  298. 'db' => $db,
  299. 'tableName' => $tableName,
  300. ];
  301. }
  302. /**
  303. * 获取指定深度的子会员从指定的期数中
  304. * @param $userId
  305. * @param $periodNum
  306. * @return array|\yii\db\DataReader
  307. * @throws \yii\db\Exception
  308. */
  309. public static function getChildrenFromPeriod($userId, $periodNum=null){
  310. $table = self::getTableNameFromPeriod($periodNum);
  311. $db = $table['db'];
  312. $tableName = $table['tableName'];
  313. return $db->createCommand("SELECT USER_ID,TOP_DEEP,RELATIVE_LOCATION FROM {$tableName} WHERE PARENT_UID=:PARENT_UID")->bindValues([':PARENT_UID'=>$userId])->queryAll();
  314. }
  315. /**
  316. * 获取指定层数的这一层的会员以分页的方式
  317. * @param $userId
  318. * @param $deep
  319. * @param null $periodNum
  320. * @param array $params
  321. * @return array
  322. */
  323. public static function getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum=null, $params=[]){
  324. $pageSize = method_exists(\Yii::$app->request,'get')?\Yii::$app->request->get('pageSize', \Yii::$app->params['pageSize']):\Yii::$app->params['pageSize'];
  325. if(isset($params['pageSize'])) $pageSize=$params['pageSize'];
  326. $page = null;
  327. if( isset($params['page']) ) $page=$params['page'];
  328. $orderBy = 'TOP_DEEP ASC, ID ASC';
  329. if( isset($params['orderBy']) ) $orderBy = $params['orderBy'];
  330. $table = self::getTableNameFromPeriod($periodNum);
  331. $db = $table['db'];
  332. $tableName = $table['tableName'];
  333. $userNetInfo = $db->createCommand("SELECT LOCATION_TAG,TOP_DEEP FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  334. $userDeep = $userNetInfo['TOP_DEEP'];
  335. $userLocationTag = $userNetInfo['LOCATION_TAG'];
  336. $totalCountSql = "SELECT COUNT(ID) AS TOTAL_COUNT FROM {$tableName} WHERE LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP AND INSTR(`PARENT_UIDS`,'{$userId}')>0 ORDER BY {$orderBy}";
  337. $totalCount = $db->createCommand($totalCountSql)->bindValues([':LOCATION_TAG'=>$userLocationTag . '%', ':TOP_DEEP'=>$userDeep + $deep])->queryOne();
  338. $count = $totalCount['TOTAL_COUNT'];
  339. $pagination = new Pagination(['totalCount' => $count]);
  340. $pagination->setPageSize($pageSize);
  341. if( $page !== null ) {
  342. $pagination->setPage($page);
  343. }
  344. $offset = $pagination->offset;
  345. $limit = $pagination->limit;
  346. // $end = $offset + $limit;
  347. $listSql = "SELECT * FROM $tableName WHERE LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP AND INSTR(`PARENT_UIDS`,'{$userId}')>0 ORDER BY {$orderBy} LIMIT {$limit} OFFSET {$offset}";
  348. $lists = $db->createCommand($listSql)->bindValues([':LOCATION_TAG'=>$userLocationTag . '%', ':TOP_DEEP'=>$userDeep + $deep])->queryAll();
  349. return [
  350. 'list' => $lists ? $lists : [],
  351. 'pagination' => $pagination,
  352. 'currentPage'=>$pagination->page,
  353. 'totalPages'=>$pagination->pageCount,
  354. 'totalCount' => $pagination->totalCount,
  355. 'pageSize' => $pagination->pageSize,
  356. ];
  357. }
  358. /**
  359. * 获取所有的上级会员带着分页和期数
  360. * @param $userId
  361. * @param null $periodNum
  362. * @param null $deep
  363. * @return array
  364. */
  365. public static function getAllParentFromPeriodWithPage($userId, $periodNum=null, $deep=null){
  366. $pageSize = method_exists(\Yii::$app->request,'get')?\Yii::$app->request->get('pageSize', \Yii::$app->params['pageSize']):\Yii::$app->params['pageSize'];
  367. $table = self::getTableNameFromPeriod($periodNum);
  368. $db = $table['db'];
  369. $tableName = $table['tableName'];
  370. $sql = "SELECT * FROM {$tableName} WHERE USER_ID=:USER_ID";
  371. $oneData = $db->createCommand($sql)->bindValues([':USER_ID'=>$userId])->queryOne();
  372. $userDeep = $oneData['TOP_DEEP'];
  373. $parentUidsStr = $oneData['PARENT_UIDS'] ?? "";
  374. if( !$parentUidsStr ) return [];
  375. $parentUidsArr = explode(',', $parentUidsStr);
  376. $parentUidsFlip = array_reverse($parentUidsArr);
  377. if ($deep != null) {
  378. $parentUidsFlip = array_slice($parentUidsFlip, 0, $deep);
  379. }
  380. $count = count($parentUidsFlip);
  381. $pagination = new Pagination(['totalCount' => $count]);
  382. $pagination->setPageSize($pageSize);
  383. $offset = $pagination->offset;
  384. $limit = $pagination->limit;
  385. $parentUidList = array_slice($parentUidsFlip, $offset, $limit);
  386. $lists = [];
  387. foreach ($parentUidList as $parentUid) {
  388. $sql = "SELECT * FROM {$tableName} WHERE USER_ID=:USER_ID";
  389. $data = $db->createCommand($sql)->bindValues([':USER_ID' => $parentUid])->queryOne();
  390. if( !$data ) continue;
  391. $data['LOCATION'] = substr($oneData['LOCATION_TAG'], strlen($data['LOCATION_TAG']), 1);
  392. $lists[] = $data;
  393. }
  394. return [
  395. 'list' => $lists ? $lists : [],
  396. 'pagination' => $pagination,
  397. 'currentPage' => $pagination->page,
  398. 'totalPages' => $pagination->pageCount,
  399. 'totalCount' => $pagination->totalCount,
  400. 'pageSize' => $pagination->pageSize,
  401. 'listTopDeep' => $userDeep,
  402. ];
  403. }
  404. /**
  405. * 获取一层下级数量从期数
  406. * @param $userId
  407. * @param null $periodNum
  408. * @return int
  409. */
  410. public static function firstFloorChildNumFromPeriod($userId, $periodNum=null){
  411. $table = self::getTableNameFromPeriod($periodNum);
  412. $db = $table['db'];
  413. $tableName = $table['tableName'];
  414. $count = $db->createCommand("SELECT COUNT(ID) AS ID_COUNT FROM {$tableName} WHERE PARENT_UID=:PARENT_UID")->bindValues([':PARENT_UID'=>$userId])->queryOne();
  415. return intval($count['ID_COUNT']);
  416. }
  417. /**
  418. * 从缓存中获取会员的全部父级(主要用于结算时的处理,能够提高效率不去查库)
  419. * @param $userId
  420. * @return array|mixed
  421. */
  422. public static function getAllParentsFromRedis($userId){
  423. $key = Cache::USER_NETWORK_PARENTS;
  424. $data = Yii::$app->redis->hget($key, $userId);
  425. if(!$data){
  426. $data = [];
  427. self::getParentsWithOffsetFromDbCalc($userId, function($oneData) use(&$data){
  428. $data[] = $oneData;
  429. }, 100);
  430. $data = Json::encode($data);
  431. Yii::$app->redis->hset($key, $userId, $data);
  432. }
  433. return $data ? Json::decode($data) : [];
  434. }
  435. /**
  436. * 判断在某个区位是否存在会员
  437. * @param $userId
  438. * @param $location
  439. * @return bool
  440. */
  441. public static function issetUserInLocation($userId, $location){
  442. $childrenNetList = UserNetwork::find()->select(['LOCATION_TAG'])->where('PARENT_UID=:PARENT_UID', [':PARENT_UID' => $userId])->asArray()->all();
  443. foreach ($childrenNetList as $everyData) {
  444. //取最后一位数
  445. $everyLocation = substr($everyData['LOCATION_TAG'], -1);
  446. if( $everyLocation == $location ) return true;
  447. }
  448. return false;
  449. }
  450. }