UserRelation.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. $userRelationInfo = static::find($isSlaves, $db)->select(['TOP_DEEP', 'PARENT_UIDS'])->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
  79. if( !$userRelationInfo ) return [];
  80. $parentUidsStr = $userRelationInfo['PARENT_UIDS'];
  81. if( !$parentUidsStr ) return [];
  82. $parentUidsArr = explode(',', $parentUidsStr);
  83. unset($parentUidsStr);
  84. if( $orderBy === 'DESC' ) {
  85. $parentUidsArr = array_reverse($parentUidsArr);
  86. }
  87. if( !$parentUidsArr ) return [];
  88. $pageParentUids = array_slice($parentUidsArr, $offset, $limit);
  89. unset($parentUidsArr);
  90. $parentList = [];
  91. foreach ($pageParentUids as $parentUid) {
  92. $parentRelationInfo = static::find($isSlaves, $db)->select(['TOP_DEEP'])->where('USER_ID=:USER_ID', ['USER_ID'=>$parentUid])->asArray()->one();
  93. $parentList[] = [
  94. 'USER_ID' => $userId,
  95. 'TOP_DEEP' => $userRelationInfo['TOP_DEEP'],
  96. 'PARENT_UID' => $parentUid,
  97. 'PARENT_DEEP' => $parentRelationInfo['TOP_DEEP'],
  98. ];
  99. unset($parentUid, $parentRelationInfo);
  100. }
  101. unset($pageParentUids, $userRelationInfo);
  102. return $parentList;
  103. }
  104. /**
  105. * 分页获取上级会员结算库
  106. * @param $userId
  107. * @param $callbackFunc
  108. * @param $limit
  109. * @param int $offset
  110. * @param string $orderBy
  111. */
  112. public static function getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset = 0, $orderBy='DESC'){
  113. $allData = self::getParentsWithOffset($userId, $offset, $limit, $orderBy, false, 'dbCalc');
  114. if($allData){
  115. foreach($allData as $data){
  116. $callbackFunc($data);
  117. unset($data);
  118. }
  119. unset($allData);
  120. self::getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset + $limit);
  121. }
  122. }
  123. /**
  124. * 获取上一级父级的会员信息
  125. * @param $userId
  126. * @return array|null
  127. */
  128. public static function getFirstParentUserInfo($userId){
  129. $oneUserInfo = UserInfo::findOneAsArray(['USER_ID'=>$userId]);
  130. if($oneUserInfo['REC_UID']){
  131. return UserInfo::findOneAsArray(['USER_ID'=>$oneUserInfo['REC_UID']]);
  132. } else {
  133. return null;
  134. }
  135. }
  136. /**
  137. * 查看所传父级节点会员是不是所传会员的父级
  138. * @param $userId
  139. * @param $parentUserId
  140. * @param $periodNum
  141. * @return bool
  142. */
  143. public static function isParentUser($userId, $parentUserId, $periodNum = null){
  144. $table = self::getTableNameFromPeriod($periodNum);
  145. $db = $table['db'];
  146. $tableName = $table['tableName'];
  147. $data = $db->createCommand("SELECT PARENT_UIDS FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  148. if( !$data ) {
  149. unset($table, $db, $tableName, $data);
  150. return false;
  151. }
  152. $parentListArr = explode(',', $data['PARENT_UIDS']);
  153. unset($table, $db, $tableName, $data);
  154. $existStatus = in_array($parentUserId, $parentListArr);
  155. unset($parentListArr);
  156. return $existStatus;
  157. }
  158. /**
  159. * 获取相交于父级的深度
  160. * @param $userId
  161. * @param $parentUserId
  162. * @param bool $isSlave
  163. * @return mixed|null
  164. */
  165. public static function deepWithParent($userId, $parentUserId, $isSlave = false){
  166. $userRelationInfo = static::find($isSlave)->select(['TOP_DEEP'])->where('USER_ID=:USER_ID', [':USER_ID'=>$userId])->asArray()->one();
  167. if( !$userRelationInfo ) return null;
  168. $parentRelationInfo = static::find($isSlave)->select(['TOP_DEEP'])->where('PARENT_UID=:PARENT_UID', [':PARENT_UID'=>$parentUserId])->asArray()->one();
  169. if( !$parentRelationInfo ) return null;
  170. return $parentRelationInfo['TOP_DEEP'] - $userRelationInfo['TOP_DEEP'];
  171. }
  172. /**
  173. * 获取子会员节点带着总深度和循环的子节点层级关系
  174. * @param $userId
  175. * @param $deep
  176. * @param int $loopedDeep
  177. * @param null $periodNum
  178. * @return mixed
  179. * @throws \yii\base\Exception
  180. * @throws \yii\db\Exception
  181. */
  182. public static function getChildrenWithDeepAndLayer($userId, $deep, $loopedDeep = 1, $periodNum=null){
  183. $allData = self::getFirstFloorChildrenFromPeriod($userId,'TOP_DEEP ASC', $periodNum);
  184. if($allData){
  185. $decLevelConfig = Cache::getDecLevelConfig();
  186. $empLevelConfig = Cache::getEmpLevelConfig();
  187. $starLevelConfig = Cache::getStarCrownLevelConfig();
  188. foreach($allData as $key=>$data){
  189. // 获取用户的基本信息
  190. $baseInfo = Info::baseInfo($data['USER_ID'], $periodNum);
  191. $allData[$key] = array_merge($data, [
  192. 'USER_NAME' => $baseInfo['USER_NAME'],
  193. 'TOP_RELATION_DEEP' => $data['TOP_DEEP'],
  194. 'REAL_NAME' => $baseInfo['REAL_NAME'],
  195. 'DEC_LV_NAME' => $decLevelConfig[$baseInfo['DEC_LV']]['LEVEL_NAME'],
  196. 'EMP_LV_NAME' => isset($empLevelConfig[$baseInfo['EMP_LV']])?$empLevelConfig[$baseInfo['EMP_LV']]['LEVEL_NAME']:'',
  197. 'STAR_LV_NAME' => $starLevelConfig[$baseInfo['STAR_LV']]['LEVEL_NAME'],
  198. 'PERIOD_AT' => $baseInfo['PERIOD_AT'],
  199. ]);
  200. // 获取字节点数量
  201. $childNum = self::firstFloorChildNumFromPeriod($data['USER_ID'], $periodNum);
  202. if($childNum > 0 && $loopedDeep < $deep){
  203. $child = self::getChildrenWithDeepAndLayer($data['USER_ID'], $deep, $loopedDeep + 1, $periodNum);
  204. $leaf = false;
  205. $icon = 'el-icon-user-solid';
  206. }
  207. elseif($childNum > 0){
  208. $child = null;
  209. $leaf = false;
  210. $icon = 'el-icon-user-solid';
  211. }
  212. else {
  213. $child = null;
  214. $leaf = true;
  215. $icon = 'el-icon-user';
  216. }
  217. $allData[$key]['children'] = $child;
  218. $allData[$key]['leaf'] = $leaf;
  219. $allData[$key]['icon'] = $icon;
  220. $allData[$key]['isExpanded'] = false;
  221. $allData[$key]['displayNone'] = 'display-none';
  222. }
  223. }
  224. return $allData;
  225. }
  226. /**
  227. * 通过期数获取应该查询哪个表和库
  228. * @param $periodNum
  229. * @return array
  230. */
  231. public static function getTableNameFromPeriod($periodNum = null){
  232. $db = self::getDb();
  233. $tableName = self::tableName();
  234. // if($periodNum !== null){
  235. // // 获取当前期数
  236. // $period = Period::instance();
  237. // $nowPeriodNum = $period->getNowPeriodNum();
  238. // if($nowPeriodNum != $periodNum){
  239. // // 从备份库里找到期数对应的网络
  240. // if(ActiveRecord::isExistsTable('{{%USER_RELATION_'.$periodNum.'}}', 'dbNetPoint')){
  241. // $db = Yii::$app->dbNetPoint;
  242. // $tableName = '{{%USER_RELATION_'.$periodNum.'}}';
  243. // }
  244. // }
  245. // }
  246. return [
  247. 'db' => $db,
  248. 'tableName' => $tableName,
  249. ];
  250. }
  251. /**
  252. * 获取直推子会员
  253. * @param $userId
  254. * @param string $orderBy
  255. * @param null $periodNum
  256. * @return mixed
  257. */
  258. public static function getFirstFloorChildrenFromPeriod($userId, $orderBy='TOP_DEEP ASC,ID ASC', $periodNum=null){
  259. $table = self::getTableNameFromPeriod($periodNum);
  260. $db = $table['db'];
  261. $tableName = $table['tableName'];
  262. 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();
  263. }
  264. /**
  265. * 获取指定层数的这一层的会员以分页的方式
  266. * @param $userId
  267. * @param $deep
  268. * @param null $periodNum
  269. * @return array
  270. */
  271. public static function getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum=null,$params=[]){
  272. $pageSize = method_exists(\Yii::$app->request,'get')?\Yii::$app->request->get('pageSize', \Yii::$app->params['pageSize']):\Yii::$app->params['pageSize'];
  273. if(isset($params['pageSize'])) $pageSize=$params['pageSize'];
  274. $page = null;
  275. if( isset($params['page']) ) $page=$params['page'];
  276. $orderBy = 'TOP_DEEP ASC,ID ASC';
  277. if( isset($params['orderBy']) ) $orderBy = $params['orderBy'];
  278. $table = self::getTableNameFromPeriod($periodNum);
  279. $db = $table['db'];
  280. $tableName = $table['tableName'];
  281. $userRecInfo = $db->createCommand("SELECT TOP_DEEP FROM $tableName WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  282. $userDeep = $userRecInfo['TOP_DEEP'];
  283. $totalCountSql = "SELECT COUNT(ID) AS TOTAL_COUNT FROM $tableName WHERE INSTR(`PARENT_UIDS`,'{$userId}')>0 AND TOP_DEEP<=:TOP_DEEP ORDER BY {$orderBy}";
  284. $totalCount = $db->createCommand($totalCountSql)->bindValues([ ':TOP_DEEP'=>$userDeep + $deep])->queryOne();
  285. $count = $totalCount['TOTAL_COUNT'];
  286. $pagination = new Pagination(['totalCount' => $count]);
  287. if( $page !== null ) {
  288. $pagination->setPage($page);
  289. }
  290. $pagination->setPageSize($pageSize);
  291. $offset = $pagination->offset;
  292. $limit = $pagination->limit;
  293. // $end = $offset + $limit;
  294. $listSql = "SELECT * FROM $tableName WHERE INSTR(`PARENT_UIDS`,'{$userId}')>0 AND TOP_DEEP<=:TOP_DEEP ORDER BY {$orderBy} LIMIT {$limit} OFFSET {$offset}";
  295. $lists = $db->createCommand($listSql)->bindValues([ ':TOP_DEEP'=>$userDeep + $deep])->queryAll();
  296. return [
  297. 'list' => $lists ? $lists : [],
  298. 'pagination' => $pagination,
  299. 'currentPage'=>$pagination->page,
  300. 'totalPages'=>$pagination->pageCount,
  301. 'totalCount' => $pagination->totalCount,
  302. 'pageSize' => $pagination->pageSize,
  303. ];
  304. }
  305. /**
  306. * 获取一层下级数量从期数
  307. * @param $userId
  308. * @param null $periodNum
  309. * @return int
  310. */
  311. public static function firstFloorChildNumFromPeriod($userId, $periodNum=null){
  312. $table = self::getTableNameFromPeriod($periodNum);
  313. $db = $table['db'];
  314. $tableName = $table['tableName'];
  315. $count = $db->createCommand("SELECT COUNT(ID) AS ID_COUNT FROM $tableName WHERE PARENT_UID=:PARENT_UID")->bindValues([':PARENT_UID'=>$userId])->queryOne();
  316. return intval($count['ID_COUNT']);
  317. }
  318. /**
  319. * 从缓存中获取会员的全部父级(主要用于结算时的处理,能够提高效率不去查库)
  320. * @param $userId
  321. * @return array|mixed
  322. */
  323. public static function getAllParentsFromRedis($userId){
  324. $key = Cache::USER_RELATION_PARENTS;
  325. $data = Yii::$app->redis->hget($key, $userId);
  326. if(!$data){
  327. $data = [];
  328. self::getParentsWithOffsetFromDbCalc($userId, function($oneData) use(&$data){
  329. $data[] = $oneData;
  330. }, 100);
  331. $data = Json::encode($data);
  332. Yii::$app->redis->hset($key, $userId, $data);
  333. }
  334. return $data ? Json::decode($data) : [];
  335. }
  336. }