UserRelation.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 Yii;
  8. use yii\data\Pagination;
  9. use yii\helpers\Json;
  10. /**
  11. * This is the model class for table "{{%USER_RELATION}}".
  12. *
  13. * @property string $ID
  14. * @property string $USER_ID 会员ID
  15. * @property string $PARENT_UID 相对上级会员ID
  16. * @property string $TOP_UID 顶端会员ID
  17. * @property int $TOP_DEEP 距离顶端会员深度
  18. * @property int $PARENT_UIDS 所有的上级ID
  19. * @property int $CREATED_AT 创建时间
  20. * @property int $UPDATED_AT 更新时间
  21. */
  22. class UserRelation extends \common\components\ActiveRecord
  23. {
  24. /**
  25. * @inheritdoc
  26. */
  27. public static function tableName()
  28. {
  29. return '{{%USER_RELATION_NEW}}';
  30. }
  31. /**
  32. * @inheritdoc
  33. */
  34. public function rules()
  35. {
  36. return [
  37. [['USER_ID', 'PARENT_UID', 'TOP_UID', 'TOP_DEEP', 'CREATED_AT'], 'required'],
  38. [['TOP_DEEP', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
  39. [['ID', 'USER_ID', 'PARENT_UID', 'TOP_UID'], 'string', 'max' => 32],
  40. [['ID'], 'unique'],
  41. ];
  42. }
  43. /**
  44. * @inheritdoc
  45. */
  46. public function attributeLabels()
  47. {
  48. return [
  49. 'ID' => 'ID',
  50. 'USER_ID' => '会员ID',
  51. 'PARENT_UID' => '相对上级会员ID',
  52. 'TOP_UID' => '顶端会员ID',
  53. 'TOP_DEEP' => '距离顶端会员深度',
  54. 'PARENT_UIDS' => '所有的上级ID',
  55. 'CREATED_AT' => '创建时间',
  56. 'UPDATED_AT' => '更新时间',
  57. ];
  58. }
  59. /**
  60. * 获取一层下级数量
  61. * @param $userId
  62. * @return int|string
  63. */
  64. public static function firstFloorChildNum($userId){
  65. return intval(UserInfo::find()->where('REC_UID=:REC_UID', [':REC_UID'=>$userId])->count());
  66. }
  67. /**
  68. * 分页获取上级会员
  69. * @param $userId
  70. * @param $offset
  71. * @param $limit
  72. * @param string $orderBy
  73. * @param bool $isSlaves
  74. * @param string $db
  75. * @return array|\yii\db\ActiveRecord[]
  76. */
  77. public static function getParentsWithOffset($userId, $offset, $limit, $orderBy = 'DESC', $isSlaves = false, $db = 'db'){
  78. $sql = "SELECT t2.USER_ID
  79. FROM
  80. (
  81. SELECT
  82. @r AS _id,
  83. (SELECT @r := PARENT_UID FROM AR_USER_RELATION_NEW WHERE USER_ID = _id) AS PARENT_UID,
  84. @l := @l + 1 AS lvl
  85. FROM
  86. (SELECT @r := '".$userId."', @l := 0) vars, AR_USER_RELATION_NEW AS h
  87. WHERE @r <> 0
  88. ) t1
  89. JOIN AR_USER_RELATION_NEW t2
  90. ON t1._id = t2.USER_ID AND t1._id != '".$userId."';";
  91. $parentUidsArr = \Yii::$app->db->createCommand($sql)->queryAll();
  92. if (empty($parentUidsArr)) {
  93. return [];
  94. }
  95. $allUserIds = array_column($parentUidsArr, 'USER_ID');
  96. if ($orderBy === 'ASC') {
  97. $allUserIds = array_reverse($allUserIds);
  98. }
  99. if(empty($allUserIds)) return [];
  100. $topDeep = count($allUserIds);
  101. $pageParentUids = array_slice($allUserIds, $offset, $limit);
  102. unset($allUserIds);
  103. $parentList = [];
  104. foreach ($pageParentUids as $parentUid) {
  105. // $parentRelationInfo = static::find($isSlaves, $db)
  106. // ->select(['TOP_DEEP'])
  107. // ->where('USER_ID=:USER_ID', ['USER_ID'=>$parentUid])
  108. // ->asArray()
  109. // ->one();
  110. $parentList[] = [
  111. 'USER_ID' => $userId,
  112. 'TOP_DEEP' => $topDeep,
  113. 'PARENT_UID' => $parentUid,
  114. //'PARENT_DEEP' => $parentRelationInfo['TOP_DEEP'],
  115. ];
  116. unset($parentUid, $parentRelationInfo);
  117. }
  118. unset($pageParentUids, $userRelationInfo);
  119. return $parentList;
  120. }
  121. // /**
  122. // * 分页获取上级会员
  123. // * @param $userId
  124. // * @param $offset
  125. // * @param $limit
  126. // * @param string $orderBy
  127. // * @param bool $isSlaves
  128. // * @param string $db
  129. // * @return array|\yii\db\ActiveRecord[]
  130. // */
  131. // public static function getParentsWithOffset($userId, $offset, $limit, $orderBy = 'DESC', $isSlaves = false, $db = 'db'){
  132. // $userRelationInfo = static::find($isSlaves, $db)->select(['TOP_DEEP', 'PARENT_UIDS'])->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
  133. // if( !$userRelationInfo ) return [];
  134. // $parentUidsStr = $userRelationInfo['PARENT_UIDS'];
  135. // if( !$parentUidsStr ) return [];
  136. // $parentUidsArr = explode(',', $parentUidsStr);
  137. // unset($parentUidsStr);
  138. // if( $orderBy === 'DESC' ) {
  139. // $parentUidsArr = array_reverse($parentUidsArr);
  140. // }
  141. // if( !$parentUidsArr ) return [];
  142. // $pageParentUids = array_slice($parentUidsArr, $offset, $limit);
  143. // unset($parentUidsArr);
  144. // $parentList = [];
  145. // foreach ($pageParentUids as $parentUid) {
  146. // $parentRelationInfo = static::find($isSlaves, $db)->select(['TOP_DEEP'])->where('USER_ID=:USER_ID', ['USER_ID'=>$parentUid])->asArray()->one();
  147. // $parentList[] = [
  148. // 'USER_ID' => $userId,
  149. // 'TOP_DEEP' => $userRelationInfo['TOP_DEEP'],
  150. // 'PARENT_UID' => $parentUid,
  151. // 'PARENT_DEEP' => $parentRelationInfo['TOP_DEEP'],
  152. // ];
  153. // unset($parentUid, $parentRelationInfo);
  154. // }
  155. // unset($pageParentUids, $userRelationInfo);
  156. // return $parentList;
  157. // }
  158. /**
  159. * 分页获取上级会员结算库
  160. * @param $userId
  161. * @param $callbackFunc
  162. * @param $limit
  163. * @param int $offset
  164. * @param string $orderBy
  165. */
  166. public static function getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset = 0, $orderBy='DESC'){
  167. $allData = self::getParentsWithOffset($userId, $offset, $limit, $orderBy, false, 'dbCalc');
  168. if($allData){
  169. foreach($allData as $data){
  170. $callbackFunc($data);
  171. unset($data);
  172. }
  173. unset($allData);
  174. self::getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset + $limit);
  175. }
  176. }
  177. /**
  178. * 获取上一级父级的会员信息
  179. * @param $userId
  180. * @return array|null
  181. */
  182. public static function getFirstParentUserInfo($userId){
  183. $oneUserInfo = UserInfo::findOneAsArray(['USER_ID'=>$userId]);
  184. if($oneUserInfo['REC_UID']){
  185. return UserInfo::findOneAsArray(['USER_ID'=>$oneUserInfo['REC_UID']]);
  186. } else {
  187. return null;
  188. }
  189. }
  190. /**
  191. * 查看所传父级节点会员是不是所传会员的父级
  192. * @param $userId
  193. * @param $parentUserId
  194. * @param $periodNum
  195. * @return bool
  196. */
  197. public static function isParentUser($userId, $parentUserId, $periodNum = null){
  198. $table = self::getTableNameFromPeriod($periodNum);
  199. $db = $table['db'];
  200. $tableName = $table['tableName'];
  201. $data = $db->createCommand("SELECT PARENT_UIDS FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  202. if( !$data ) {
  203. unset($table, $db, $tableName, $data);
  204. return false;
  205. }
  206. $parentListArr = explode(',', $data['PARENT_UIDS']);
  207. unset($table, $db, $tableName, $data);
  208. $existStatus = in_array($parentUserId, $parentListArr);
  209. unset($parentListArr);
  210. return $existStatus;
  211. }
  212. /**
  213. * 获取相交于父级的深度
  214. * @param $userId
  215. * @param $parentUserId
  216. * @param bool $isSlave
  217. * @return mixed|null
  218. */
  219. public static function deepWithParent($userId, $parentUserId, $isSlave = false){
  220. $userRelationInfo = static::find($isSlave)->select(['TOP_DEEP'])->where('USER_ID=:USER_ID', [':USER_ID'=>$userId])->asArray()->one();
  221. if( !$userRelationInfo ) return null;
  222. $parentRelationInfo = static::find($isSlave)->select(['TOP_DEEP'])->where('PARENT_UID=:PARENT_UID', [':PARENT_UID'=>$parentUserId])->asArray()->one();
  223. if( !$parentRelationInfo ) return null;
  224. return $parentRelationInfo['TOP_DEEP'] - $userRelationInfo['TOP_DEEP'];
  225. }
  226. /**
  227. * 获取子会员节点带着总深度和循环的子节点层级关系
  228. * @param $userId
  229. * @param $deep
  230. * @param int $loopedDeep
  231. * @param null $periodNum
  232. * @return mixed
  233. * @throws \yii\base\Exception
  234. * @throws \yii\db\Exception
  235. */
  236. public static function getChildrenWithDeepAndLayer($userId, $deep, $loopedDeep = 1, $periodNum=null){
  237. $allData = self::getFirstFloorChildrenFromPeriod($userId,'TOP_DEEP ASC', $periodNum);
  238. if($allData){
  239. $decLevelConfig = Cache::getDecLevelConfig();
  240. $empLevelConfig = Cache::getEmpLevelConfig();
  241. $crownLevelConfig = Cache::getStarCrownLevelConfig();
  242. foreach($allData as $key=>$data){
  243. // 获取用户的基本信息
  244. $baseInfo = Info::baseInfo($data['USER_ID'], $periodNum);
  245. $allData[$key] = array_merge($data, [
  246. 'USER_NAME' => $baseInfo['USER_NAME'],
  247. 'TOP_RELATION_DEEP' => $data['TOP_DEEP'],
  248. 'REAL_NAME' => $baseInfo['REAL_NAME'],
  249. 'DEC_LV_NAME' => $decLevelConfig[$baseInfo['DEC_LV']]['LEVEL_NAME'],
  250. 'EMP_LV_NAME' => isset($empLevelConfig[$baseInfo['EMP_LV']])?$empLevelConfig[$baseInfo['EMP_LV']]['LEVEL_NAME']:'',
  251. 'CROWN_LV_NAME' => isset($crownLevelConfig[$baseInfo['CROWN_LV']])?$crownLevelConfig[$baseInfo['CROWN_LV']]['LEVEL_NAME']:'',
  252. 'PERIOD_AT' => $baseInfo['PERIOD_AT'],
  253. ]);
  254. // 获取字节点数量
  255. $childNum = self::firstFloorChildNumFromPeriod($data['USER_ID'], $periodNum);
  256. if($childNum > 0 && $loopedDeep < $deep){
  257. $child = self::getChildrenWithDeepAndLayer($data['USER_ID'], $deep, $loopedDeep + 1, $periodNum);
  258. $leaf = false;
  259. $icon = 'el-icon-user-solid';
  260. }
  261. elseif($childNum > 0){
  262. $child = null;
  263. $leaf = false;
  264. $icon = 'el-icon-user-solid';
  265. }
  266. else {
  267. $child = null;
  268. $leaf = true;
  269. $icon = 'el-icon-user';
  270. }
  271. $allData[$key]['children'] = $child;
  272. $allData[$key]['leaf'] = $leaf;
  273. $allData[$key]['icon'] = $icon;
  274. $allData[$key]['isExpanded'] = false;
  275. $allData[$key]['displayNone'] = 'display-none';
  276. }
  277. }
  278. return $allData;
  279. }
  280. /**
  281. * 通过期数获取应该查询哪个表和库
  282. * @param $periodNum
  283. * @return array
  284. */
  285. public static function getTableNameFromPeriod($periodNum = null){
  286. $db = self::getDb();
  287. $tableName = self::tableName();
  288. // if($periodNum !== null){
  289. // // 获取当前期数
  290. // $period = Period::instance();
  291. // $nowPeriodNum = $period->getNowPeriodNum();
  292. // if($nowPeriodNum != $periodNum){
  293. // // 从备份库里找到期数对应的网络
  294. // if(ActiveRecord::isExistsTable('{{%USER_RELATION_'.$periodNum.'}}', 'dbNetPoint')){
  295. // $db = Yii::$app->dbNetPoint;
  296. // $tableName = '{{%USER_RELATION_'.$periodNum.'}}';
  297. // }
  298. // }
  299. // }
  300. return [
  301. 'db' => $db,
  302. 'tableName' => $tableName,
  303. ];
  304. }
  305. /**
  306. * 获取直推子会员
  307. * @param $userId
  308. * @param string $orderBy
  309. * @param null $periodNum
  310. * @return mixed
  311. */
  312. public static function getFirstFloorChildrenFromPeriod($userId, $orderBy='TOP_DEEP ASC,ID ASC', $periodNum=null){
  313. $table = self::getTableNameFromPeriod($periodNum);
  314. $db = $table['db'];
  315. $tableName = $table['tableName'];
  316. return $db->createCommand("SELECT USER_ID,PARENT_UID,TOP_DEEP FROM {$tableName} WHERE PARENT_UID=:PARENT_UID ORDER BY {$orderBy}")->bindValues([':PARENT_UID'=>$userId])->queryAll();
  317. }
  318. /**
  319. * 获取指定层数的这一层的会员以分页的方式
  320. * @param $userId
  321. * @param $deep
  322. * @param null $periodNum
  323. * @return array
  324. */
  325. public static function getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum=null,$params=[]){
  326. $pageSize = method_exists(\Yii::$app->request,'get')?\Yii::$app->request->get('pageSize', \Yii::$app->params['pageSize']):\Yii::$app->params['pageSize'];
  327. if(isset($params['pageSize'])) $pageSize=$params['pageSize'];
  328. $page = null;
  329. if( isset($params['page']) ) $page=$params['page'];
  330. $orderBy = 'TOP_DEEP ASC,ID ASC';
  331. if( isset($params['orderBy']) ) $orderBy = $params['orderBy'];
  332. $table = self::getTableNameFromPeriod($periodNum);
  333. $db = $table['db'];
  334. $tableName = $table['tableName'];
  335. $userRecInfo = $db->createCommand("SELECT TOP_DEEP FROM $tableName WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  336. $userDeep = $userRecInfo['TOP_DEEP'];
  337. $totalCountSql = "SELECT COUNT(ID) AS TOTAL_COUNT FROM $tableName WHERE INSTR(`PARENT_UIDS`,'{$userId}')>0 AND TOP_DEEP<=:TOP_DEEP ORDER BY {$orderBy}";
  338. $totalCount = $db->createCommand($totalCountSql)->bindValues([ ':TOP_DEEP'=>$userDeep + $deep])->queryOne();
  339. $count = $totalCount['TOTAL_COUNT'];
  340. $pagination = new Pagination(['totalCount' => $count]);
  341. if( $page !== null ) {
  342. $pagination->setPage($page);
  343. }
  344. $pagination->setPageSize($pageSize);
  345. $offset = $pagination->offset;
  346. $limit = $pagination->limit;
  347. // $end = $offset + $limit;
  348. $listSql = "SELECT * FROM $tableName WHERE INSTR(`PARENT_UIDS`,'{$userId}')>0 AND TOP_DEEP<=:TOP_DEEP ORDER BY {$orderBy} LIMIT {$limit} OFFSET {$offset}";
  349. $lists = $db->createCommand($listSql)->bindValues([ ':TOP_DEEP'=>$userDeep + $deep])->queryAll();
  350. return [
  351. 'list' => $lists ? $lists : [],
  352. 'pagination' => $pagination,
  353. 'currentPage'=>$pagination->page,
  354. 'totalPages'=>$pagination->pageCount,
  355. 'totalCount' => $pagination->totalCount,
  356. 'pageSize' => $pagination->pageSize,
  357. ];
  358. }
  359. /**
  360. * 获取一层下级数量从期数
  361. * @param $userId
  362. * @param null $periodNum
  363. * @return int
  364. */
  365. public static function firstFloorChildNumFromPeriod($userId, $periodNum=null){
  366. $table = self::getTableNameFromPeriod($periodNum);
  367. $db = $table['db'];
  368. $tableName = $table['tableName'];
  369. $count = $db->createCommand("SELECT COUNT(ID) AS ID_COUNT FROM $tableName WHERE PARENT_UID=:PARENT_UID")->bindValues([':PARENT_UID'=>$userId])->queryOne();
  370. return intval($count['ID_COUNT']);
  371. }
  372. /**
  373. * 从缓存中获取会员的全部父级(主要用于结算时的处理,能够提高效率不去查库)
  374. * @param $userId
  375. * @return array|mixed
  376. */
  377. public static function getAllParentsFromRedis($userId){
  378. $key = Cache::USER_RELATION_PARENTS;
  379. $data = Yii::$app->redis->hget($key, $userId);
  380. if(!$data){
  381. $data = [];
  382. self::getParentsWithOffsetFromDbCalc($userId, function($oneData) use(&$data){
  383. $data[] = $oneData;
  384. }, 100);
  385. $data = Json::encode($data);
  386. Yii::$app->redis->hset($key, $userId, $data);
  387. }
  388. return $data ? Json::decode($data) : [];
  389. }
  390. }