Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

设置-用户字段增删改查接口 #1250

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/bk-user/bkuser/apis/web/tenant_setting/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# -*- 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.
"""
97 changes: 97 additions & 0 deletions src/bk-user/bkuser/apis/web/tenant_setting/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# -*- 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.
"""
import logging

from drf_yasg.utils import swagger_serializer_method
from rest_framework import serializers

from bkuser.apps.tenant_setting.constants import UserFieldDataType
from bkuser.apps.tenant_setting.models import UserCustomField

logger = logging.getLogger(__name__)


class BuiltinFieldOutputSLZ(serializers.Serializer):
id = serializers.IntegerField(help_text="字段ID", read_only=True)
name = serializers.CharField(help_text="字段名称")
display_name = serializers.CharField(help_text="展示用名称")
data_type = serializers.CharField(help_text="字段类型")
required = serializers.BooleanField(help_text="是否必填")
unique = serializers.BooleanField(help_text="是否唯一")
default = serializers.JSONField(help_text="默认值")
options = serializers.JSONField(help_text="选项")


class CustomFieldOutputSLZ(serializers.Serializer):
id = serializers.IntegerField(help_text="字段ID", read_only=True)
name = serializers.CharField(help_text="字段名称")
display_name = serializers.CharField(help_text="展示用名称")
data_type = serializers.CharField(help_text="字段类型")
required = serializers.BooleanField(help_text="是否必填")
default = serializers.JSONField(help_text="默认值")
options = serializers.JSONField(help_text="选项")


class UserFieldOutputSLZ(serializers.Serializer):
narasux marked this conversation as resolved.
Show resolved Hide resolved
builtin_fields = serializers.SerializerMethodField(help_text="内置字段")
narasux marked this conversation as resolved.
Show resolved Hide resolved
custom_fields = serializers.SerializerMethodField(help_text="自定义字段")

@swagger_serializer_method(serializer_or_field=BuiltinFieldOutputSLZ(many=True))
def get_builtin_fields(self, obj):
return BuiltinFieldOutputSLZ(obj["builtin_fields"], many=True).data

@swagger_serializer_method(serializer_or_field=CustomFieldOutputSLZ(many=True))
def get_custom_fields(self, obj):
return CustomFieldOutputSLZ(obj["custom_fields"], many=True).data


class UserCustomFieldCreateInputSLZ(serializers.Serializer):
narasux marked this conversation as resolved.
Show resolved Hide resolved
name = serializers.CharField(help_text="字段名称", max_length=128)
display_name = serializers.CharField(help_text="展示用名称", max_length=128)
data_type = serializers.ChoiceField(help_text="字段类型", choices=UserFieldDataType.get_choices())
required = serializers.BooleanField(help_text="是否必填")
default = serializers.JSONField(help_text="默认值", required=False)
options = serializers.JSONField(help_text="选项", required=False)

def validate_display_name(self, display_name):
if UserCustomField.objects.filter(tenant=self.context["tenant"], display_name=display_name).exists():
raise serializers.ValidationError("display_name already exists")
narasux marked this conversation as resolved.
Show resolved Hide resolved
return display_name

def validate_name(self, name):
if UserCustomField.objects.filter(tenant=self.context["tenant"], name=name).exists():
raise serializers.ValidationError("name already exists")
return name

def validate(self, data):
narasux marked this conversation as resolved.
Show resolved Hide resolved
data_type = data.get("data_type")
default = data.get("default")
options = data.get("options")

if data_type in [UserFieldDataType.ENUM.value, UserFieldDataType.MULTI_ENUM.value] and (
default is None or options is None
):
narasux marked this conversation as resolved.
Show resolved Hide resolved
raise serializers.ValidationError(
"default and options fields are required for enum and multi_enum data types"
narasux marked this conversation as resolved.
Show resolved Hide resolved
)

return data


class UserCustomFieldCreateOutputSLZ(serializers.Serializer):
id = serializers.IntegerField()


class UserCustomFieldUpdateInputSLZ(serializers.Serializer):
narasux marked this conversation as resolved.
Show resolved Hide resolved
name = serializers.CharField(help_text="字段名称", max_length=128, required=False)
required = serializers.BooleanField(help_text="是否必填", required=False)
default = serializers.JSONField(help_text="默认值", required=False)
options = serializers.JSONField(help_text="选项", required=False)
narasux marked this conversation as resolved.
Show resolved Hide resolved
27 changes: 27 additions & 0 deletions src/bk-user/bkuser/apis/web/tenant_setting/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# -*- 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 django.urls import path

from . import views

urlpatterns = [
path("<str:tenant_id>/fields/", views.UserFieldListApi.as_view(), name="tenant_setting_fields.list"),
path(
"<str:tenant_id>/custom_fields/",
views.UserCustomFieldCreateApi.as_view(),
name="tenant_setting_custom_fields.create",
),
narasux marked this conversation as resolved.
Show resolved Hide resolved
path(
"custom_fields/<int:id>/",
views.UserCustomFieldUpdateDeleteApi.as_view(),
name="tenant_setting_custom_fields.update_delete",
),
]
97 changes: 97 additions & 0 deletions src/bk-user/bkuser/apis/web/tenant_setting/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# -*- 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 drf_yasg.utils import swagger_auto_schema
from rest_framework import generics, status
from rest_framework.response import Response

from bkuser.apis.web.tenant_setting.serializers import (
UserCustomFieldCreateInputSLZ,
UserCustomFieldCreateOutputSLZ,
UserCustomFieldUpdateInputSLZ,
UserFieldOutputSLZ,
)
from bkuser.apps.tenant.models import Tenant
from bkuser.apps.tenant_setting.models import UserBuiltinField, UserCustomField
from bkuser.common.error_codes import error_codes
from bkuser.common.views import ExcludePutAPIViewMixin


class UserFieldListApi(generics.ListAPIView):
pagination_class = None
serializer_class = UserFieldOutputSLZ

@swagger_auto_schema(
tags=["tenant-setting"],
operation_description="用户字段列表",
responses={status.HTTP_200_OK: UserFieldOutputSLZ(many=True)},
narasux marked this conversation as resolved.
Show resolved Hide resolved
)
def get(self, request, *args, **kwargs):
# 校验租户是否存在
tenant = Tenant.objects.filter(id=kwargs["tenant_id"]).first()
narasux marked this conversation as resolved.
Show resolved Hide resolved
if not tenant:
raise error_codes.TENANT_NOT_EXIST

slz = UserFieldOutputSLZ(
instance={
"builtin_fields": UserBuiltinField.objects.all().values(),
"custom_fields": UserCustomField.objects.filter(tenant=tenant).values(),
narasux marked this conversation as resolved.
Show resolved Hide resolved
}
)
return Response(slz.data)


class UserCustomFieldCreateApi(generics.CreateAPIView):
@swagger_auto_schema(
tags=["tenant-setting"],
operation_description="新建用户自定义字段",
request_body=UserCustomFieldCreateInputSLZ(),
responses={status.HTTP_201_CREATED: UserCustomFieldCreateOutputSLZ()},
)
def post(self, request, *args, **kwargs):
# 校验租户是否存在
tenant = Tenant.objects.filter(id=kwargs["tenant_id"]).first()
narasux marked this conversation as resolved.
Show resolved Hide resolved
if not tenant:
raise error_codes.TENANT_NOT_EXIST

slz = UserCustomFieldCreateInputSLZ(data=request.data, context={"tenant": tenant})
slz.is_valid(raise_exception=True)
data = slz.validated_data

user_custom_field = UserCustomField.objects.create(tenant=tenant, **data)
return Response(
UserCustomFieldCreateOutputSLZ(instance={"id": user_custom_field.id}).data, status=status.HTTP_201_CREATED
)


class UserCustomFieldUpdateDeleteApi(ExcludePutAPIViewMixin, generics.UpdateAPIView, generics.DestroyAPIView):
queryset = UserCustomField.objects.all()
narasux marked this conversation as resolved.
Show resolved Hide resolved
lookup_url_kwarg = "id"

@swagger_auto_schema(
tags=["tenant-setting"],
operation_description="修改用户自定义字段",
responses={status.HTTP_204_NO_CONTENT: ""},
narasux marked this conversation as resolved.
Show resolved Hide resolved
)
def patch(self, request, *args, **kwargs):
narasux marked this conversation as resolved.
Show resolved Hide resolved
custom_field = self.get_object()
narasux marked this conversation as resolved.
Show resolved Hide resolved
slz = UserCustomFieldUpdateInputSLZ(data=request.data)
slz.is_valid(raise_exception=True)

UserCustomField.objects.filter(id=custom_field.id).update(**slz.data)
narasux marked this conversation as resolved.
Show resolved Hide resolved
return Response()
narasux marked this conversation as resolved.
Show resolved Hide resolved

@swagger_auto_schema(
tags=["tenant-setting"],
operation_description="删除用户自定义字段",
responses={status.HTTP_204_NO_CONTENT: ""},
)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
1 change: 1 addition & 0 deletions src/bk-user/bkuser/apis/web/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
path("tenant-organization/", include("bkuser.apis.web.organization.urls")),
path("data-sources/", include("bkuser.apis.web.data_source.urls")),
path("data-sources/", include("bkuser.apis.web.data_source_organization.urls")),
path("tenant-setting/", include("bkuser.apis.web.tenant_setting.urls")),
]
10 changes: 10 additions & 0 deletions src/bk-user/bkuser/apps/tenant_setting/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# -*- 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.
"""
16 changes: 16 additions & 0 deletions src/bk-user/bkuser/apps/tenant_setting/apps.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 django.apps import AppConfig


class TenantConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "bkuser.apps.tenant_setting"
22 changes: 22 additions & 0 deletions src/bk-user/bkuser/apps/tenant_setting/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# -*- 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 blue_krill.data_types.enum import EnumField, StructuredEnum
from django.utils.translation import gettext_lazy as _


class UserFieldDataType(str, StructuredEnum):
"""租户用户自定义字段数据类型"""

STRING = EnumField("string", label=_("字符串"))
NUMBER = EnumField("number", label=_("数字"))
ENUM = EnumField("enum", label=_("枚举"))
MULTI_ENUM = EnumField("multi_enum", label=_("多选枚举"))
52 changes: 52 additions & 0 deletions src/bk-user/bkuser/apps/tenant_setting/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Generated by Django 3.2.20 on 2023-09-20 10:45

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
('tenant', '0003_auto_20230914_1013'),
]

operations = [
migrations.CreateModel(
name='UserBuiltinField',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=128, unique=True, verbose_name='字段名称')),
('display_name', models.CharField(max_length=128, unique=True, verbose_name='展示用名称')),
('data_type', models.CharField(choices=[('string', '字符串'), ('number', '数字'), ('enum', '枚举'), ('multi_enum', '多选枚举')], max_length=32, verbose_name='数据类型')),
('required', models.BooleanField(verbose_name='是否必填')),
('unique', models.BooleanField(verbose_name='是否唯一')),
('default', models.JSONField(default='', verbose_name='默认值')),
('options', models.JSONField(default={}, verbose_name='配置项')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='UserCustomField',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=128, verbose_name='字段名称')),
('display_name', models.CharField(max_length=128, verbose_name='展示用名称')),
('data_type', models.CharField(choices=[('string', '字符串'), ('number', '数字'), ('enum', '枚举'), ('multi_enum', '多选枚举')], max_length=32, verbose_name='数据类型')),
('required', models.BooleanField(verbose_name='是否必填')),
('default', models.JSONField(default='', verbose_name='默认值')),
('options', models.JSONField(default={}, verbose_name='配置项')),
('tenant', models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='tenant.tenant')),
],
options={
'unique_together': {('display_name', 'tenant'), ('name', 'tenant')},
},
),
]
10 changes: 10 additions & 0 deletions src/bk-user/bkuser/apps/tenant_setting/migrations/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# -*- 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.
"""
Loading
Loading