Skip to content

Commit

Permalink
code review 调整
Browse files Browse the repository at this point in the history
  • Loading branch information
neronkl committed Aug 22, 2023
1 parent 93eaa4e commit 8db7177
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 83 deletions.
60 changes: 33 additions & 27 deletions src/bk-user/bkuser/apis/web/organization/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from bkuser.apps.tenant.models import TenantUser
from bkuser.biz.tenant import TenantUserHandler
from bkuser.common.serializers import PagePageNumberInputSLZ


class TenantUserDepartmentOutputSLZ(serializers.Serializer):
Expand All @@ -25,14 +26,12 @@ class TenantUserDepartmentOutputSLZ(serializers.Serializer):

class TenantUserLeaderOutputSLZ(serializers.Serializer):
id = serializers.IntegerField(help_text="租户用户ID")
username = serializers.CharField(help_text="上级用户名")
full_name = serializers.BooleanField(help_text="上级名称")
username = serializers.CharField(help_text="租户用户名")
full_name = serializers.CharField(help_text="租户名称")


class TenantDepartmentUserSearchInputSLZ(serializers.Serializer):
page = serializers.IntegerField(required=False, default=1)
page_size = serializers.IntegerField(required=False, default=10)
recursive = serializers.BooleanField(help_text="仅仅展示该部门下人员", default=True)
class TenantDepartmentUserSearchInputSLZ(PagePageNumberInputSLZ):
recursive = serializers.BooleanField(help_text="包含子部门的人员", default=False)
keyword = serializers.CharField(help_text="搜索关键字", required=False)


Expand All @@ -58,28 +57,31 @@ def get_departments(self, instance: TenantUser) -> List[Dict]:

@swagger_serializer_method(serializer_or_field=TenantUserLeaderOutputSLZ(many=True))
def get_leaders(self, instance: TenantUser) -> List[Dict]:
leader_infos = self.context["tenant_user_leaders"].get(instance.id)
leader_infos = TenantUserHandler.get_tenant_user_leaders_by_id(instance.id)
if not leader_infos:
return []
return [
{
"id": i.id,
**i.data_source_user.model_dump(include={"username", "full_name"}),
"username": i.username,
"full_name": i.full_name,
}
for i in leader_infos
]

def to_representation(self, instance: TenantUser) -> Dict:
data = super().to_representation(instance)

user = instance.data_source_user
if user:
data["full_name"] = user.full_name
data["username"] = user.username
data["email"] = user.email
data["phone"] = user.phone
data["phone_country_code"] = user.phone_country_code
data["logo"] = user.logo or settings.DEFAULT_DATA_SOURCE_USER_LOGO
data.update(
{
"full_name": user.full_name,
"username": user.username,
"email": user.email,
"phone": user.phone,
"phone_country_code": user.phone_country_code,
"logo": user.logo or settings.DEFAULT_DATA_SOURCE_USER_LOGO,
}
)
return data


Expand All @@ -94,25 +96,29 @@ def get_departments(self, instance: TenantUser) -> List[Dict]:

@swagger_serializer_method(serializer_or_field=TenantUserLeaderOutputSLZ(many=True))
def get_leaders(self, instance: TenantUser) -> List[Dict]:
tenant_user_leaders = TenantUserHandler.get_tenant_user_leaders_by_id([instance.id])
if not tenant_user_leaders:
leader_info = TenantUserHandler.get_tenant_user_leaders_by_id(instance.id)
if not leader_info:
return []
leader_infos = tenant_user_leaders[0].leaders
return [
{
"id": i.id,
**i.data_source_user.model_dump(include={"username", "full_name"}),
"username": i.username,
"full_name": i.full_name,
}
for i in leader_infos
for i in leader_info
]

def to_representation(self, instance: TenantUser) -> Dict:
data = super().to_representation(instance)
user = instance.data_source_user
data["full_name"] = user.full_name
data["username"] = user.username
data["email"] = user.email
data["phone"] = user.phone
data["phone_country_code"] = user.phone_country_code
data["logo"] = user.logo or settings.DEFAULT_DATA_SOURCE_USER_LOGO
data.update(
{
"full_name": user.full_name,
"username": user.username,
"email": user.email,
"phone": user.phone,
"phone_country_code": user.phone_country_code,
"logo": user.logo or settings.DEFAULT_DATA_SOURCE_USER_LOGO,
}
)
return data
21 changes: 8 additions & 13 deletions src/bk-user/bkuser/apis/web/organization/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
TenantDepartmentUserSearchInputSLZ,
TenantUserRetrieveOutputSLZ,
)
from bkuser.apps.tenant.models import TenantDepartment, TenantUser
from bkuser.apps.tenant.models import TenantUser
from bkuser.biz.tenant import TenantUserHandler
from bkuser.common.pagination import CustomPageNumberPagination

Expand All @@ -34,24 +34,21 @@ class TenantDepartmentUserListApi(generics.ListAPIView):
serializer_class = TenantDepartmentUserOutputSLZ

def get_serializer_context(self):
tenant_department = TenantDepartment.objects.get(id=self.kwargs[self.lookup_url_kwarg])
tenant_user_ids = TenantUser.objects.filter(tenant_id=tenant_department.tenant_id).values_list("id", flat=True)
# 过滤出该租户部门(包括子部门)的租户用户
tenant_user_ids = TenantUserHandler.get_tenant_users_by_tenant_department(
tenant_department_id=self.kwargs["id"]
)

# 租户用户基础信息
tenant_users = TenantUserHandler.list_tenant_user_by_id(tenant_user_ids)
tenant_users_info_map = {i.id: i for i in tenant_users}

# 租户用户上级信息
tenant_user_leaders = TenantUserHandler.get_tenant_user_leaders_by_id(tenant_user_ids)
tenant_user_leader_map = {i.id: i.leaders for i in tenant_user_leaders}

# 租户用户所属租户组织
tenant_user_departments = TenantUserHandler.get_tenant_user_departments_by_id(tenant_user_ids)
tenant_user_department_map = {i.id: i.departments for i in tenant_user_departments}

return {
"tenant_users_info": tenant_users_info_map,
"tenant_user_leaders": tenant_user_leader_map,
"tenant_user_departments": tenant_user_department_map,
}

Expand All @@ -63,17 +60,15 @@ def get(self, request, *args, **kwargs):
slz = TenantDepartmentUserSearchInputSLZ(data=self.request.query_params)
slz.is_valid(raise_exception=True)
data = slz.validated_data
recursive = data.get("recursive")
keyword = data.get("keyword")
# 过滤该租户部门下的用户
tenant_user_ids = TenantUserHandler.get_tenant_users_by_tenant_department(
tenant_department_id=self.kwargs["id"], recursive=recursive
tenant_department_id=self.kwargs["id"], recursive=data.get("recursive")
)

# build response
queryset = self.filter_queryset(self.get_queryset())
if keyword:
queryset = queryset.prefetch_related("data_source_user").filter(
if keyword := data.get("keyword"):
queryset = queryset.select_related("data_source_user").filter(
Q(data_source_user__username__icontains=keyword)
| Q(data_source_user__email__icontains=keyword)
| Q(data_source_user__phone__icontains=keyword),
Expand Down
9 changes: 3 additions & 6 deletions src/bk-user/bkuser/biz/data_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
DataSourceDepartment,
DataSourceDepartmentRelation,
DataSourceDepartmentUserRelation,
DataSourceUser,
)


Expand Down Expand Up @@ -77,9 +76,9 @@ def get_department_info_by_id(department_ids: List[int]) -> Dict[int, DataSource
return departments_map

@staticmethod
def get_users_by_department_id(department_id: int, recursive: bool = True) -> List[str]:
def get_user_ids_by_department_id(department_id: int, recursive: bool = True) -> List[str]:
# 是否返回子部门用户
if recursive:
if not recursive:
user_ids = DataSourceDepartmentUserRelation.objects.filter(department_id=department_id).values_list(
"user_id"
)
Expand All @@ -92,6 +91,4 @@ def get_users_by_department_id(department_id: int, recursive: bool = True) -> Li
department_id__in=recursive_department_ids
).values_list("user_id")

# 过滤数据源用户
data_source_users = DataSourceUser.objects.filter(id__in=user_ids)
return list(data_source_users.values_list("id", flat=True))
return list(user_ids)
64 changes: 27 additions & 37 deletions src/bk-user/bkuser/biz/tenant.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ class TenantDepartmentBaseInfo(BaseModel):

class TenantUserLeadersInfo(BaseModel):
id: str
leaders: List[TenantUserWithInheritedInfo]
username: str
full_name: str


class TenantUserDepartmentInfo(BaseModel):
Expand Down Expand Up @@ -125,45 +126,34 @@ def list_tenant_user_by_id(tenant_user_ids: List[str]) -> List[TenantUserWithInh
return data

@staticmethod
def get_tenant_user_leaders_by_id(tenant_user_ids: List[str]) -> List[TenantUserLeadersInfo]:
tenant_users = TenantUser.objects.select_related("data_source_user").filter(id__in=tenant_user_ids)
data: List = []
for user in tenant_users:
# 从数据源中获取租户用户每个上级
data_source_leaders = DataSourceUserLeaderRelation.objects.filter(user=user.data_source_user)
if not data_source_leaders.exists():
continue
def get_tenant_user_leaders_by_id(tenant_user_id: str) -> List[TenantUserLeadersInfo]:
tenant_user = TenantUser.objects.select_related("data_source_user").get(id=tenant_user_id)
# 从数据源中获取租户用户每个上级
data_source_leaders = DataSourceUserLeaderRelation.objects.filter(user=tenant_user.data_source_user)
if not data_source_leaders.exists():
return []

tenant_user_leaders = TenantUser.objects.select_related("data_source_user").filter(
data_source_user_id__in=data_source_leaders.values_list("leader_id", flat=True),
tenant_id=user.tenant_id,
)
# NOTE:如果用户时通过协同数据源而来,上级不一定被授权
if not tenant_user_leaders.exists():
continue
tenant_user_leaders = TenantUser.objects.select_related("data_source_user").filter(
data_source_user_id__in=data_source_leaders.values_list("leader_id", flat=True),
tenant_id=tenant_user.tenant_id,
)
# NOTE:如果用户时通过协同数据源而来,上级不一定被授权
if not tenant_user_leaders.exists():
return []

# NOTE:如果用户时通过协同数据源而来,被授权的上级一定会绑定该租户
leader_data: List[TenantUserWithInheritedInfo] = []
for leader in tenant_user_leaders:
data_source_user = leader.data_source_user
leader_data.append(
TenantUserWithInheritedInfo(
id=leader.id,
data_source_user=DataSourceUserInfo(
username=data_source_user.username,
full_name=data_source_user.full_name,
email=data_source_user.email,
phone=data_source_user.phone,
phone_country_code=data_source_user.phone_country_code,
logo=data_source_user.logo,
),
)
# NOTE:被授权的上级一定会绑定该租户
leader_data: List[TenantUserLeadersInfo] = []
for leader in tenant_user_leaders:
user = leader.data_source_user
leader_data.append(
TenantUserLeadersInfo(
id=leader.id,
username=user.username,
full_name=user.full_name,
)
)

# 租户用户-上级,数据映射
data.append(TenantUserLeadersInfo(id=user.id, leaders=leader_data))

return data
return leader_data

@staticmethod
def get_tenant_user_departments_by_id(tenant_user_ids: List[str]) -> List[TenantUserDepartmentInfo]:
Expand All @@ -183,7 +173,7 @@ def get_tenant_user_departments_by_id(tenant_user_ids: List[str]) -> List[Tenant
@staticmethod
def get_tenant_users_by_tenant_department(tenant_department_id: int, recursive: bool = True):
tenant_department = TenantDepartment.objects.get(id=tenant_department_id)
data_source_user_ids = DataSourceDepartmentHandler.get_users_by_department_id(
data_source_user_ids = DataSourceDepartmentHandler.get_user_ids_by_department_id(
department_id=tenant_department.data_source_department_id, recursive=recursive
)
return list(
Expand Down
16 changes: 16 additions & 0 deletions src/bk-user/bkuser/common/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from rest_framework import serializers


class PagePageNumberInputSLZ(serializers):
page = serializers.IntegerField(required=False, default=1)
page_size = serializers.IntegerField(required=False, default=10)

0 comments on commit 8db7177

Please sign in to comment.