Skip to content

Commit

Permalink
refactor: cr调整
Browse files Browse the repository at this point in the history
  • Loading branch information
neronkl committed Nov 7, 2023
1 parent c401079 commit 65de189
Show file tree
Hide file tree
Showing 10 changed files with 42 additions and 122 deletions.
11 changes: 6 additions & 5 deletions src/bk-user/bkuser/apis/web/tenant_setting/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from bkuser.apps.tenant.constants import UserFieldDataType
from bkuser.apps.tenant.data_models import TenantUserCustomFieldOptions
from bkuser.apps.tenant.models import TenantUserCustomField, UserBuiltinField
from bkuser.biz.tenant_setting import NotificationMethod

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -85,7 +86,7 @@ class TenantUserCustomFieldCreateInputSLZ(serializers.Serializer):
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)
options = serializers.JSONField(help_text="选项", required=False, default=list)

def validate_display_name(self, display_name):
if TenantUserCustomField.objects.filter(
Expand Down Expand Up @@ -131,8 +132,8 @@ class TenantUserCustomFieldCreateOutputSLZ(serializers.Serializer):
class TenantUserCustomFieldUpdateInputSLZ(serializers.Serializer):
display_name = serializers.CharField(help_text="展示用名称", max_length=128)
required = serializers.BooleanField(help_text="是否必填")
default = serializers.JSONField(help_text="默认值")
options = serializers.JSONField(help_text="选项")
default = serializers.JSONField(help_text="默认值", required=False)
options = serializers.JSONField(help_text="选项", required=False, default=list)

def validate_display_name(self, display_name):
if (
Expand Down Expand Up @@ -166,7 +167,7 @@ def validate(self, attrs):


class NotificationTemplatesInputSLZ(serializers.Serializer):
method = serializers.CharField(help_text="信息传递方式")
method = serializers.ChoiceField(help_text="信息传递方式", choices=NotificationMethod.get_choices())
scene = serializers.CharField(help_text="通知类型")
title = serializers.CharField(help_text="通知标题", allow_null=True)
sender = serializers.CharField(help_text="发送人")
Expand All @@ -175,7 +176,7 @@ class NotificationTemplatesInputSLZ(serializers.Serializer):


class TenantUserValidityPeriodConfigInputSLZ(serializers.Serializer):
enabled_validity_period = serializers.BooleanField(help_text="账户有效期使能值")
enabled_validity_period = serializers.BooleanField(help_text="是否启用账户有效期")
valid_time = serializers.IntegerField(help_text="账户有效期")
remind_before_expire = serializers.ListField(help_text="临过期提醒时间")
enabled_notification_methods = serializers.ListField(help_text="通知方式")
Expand Down
21 changes: 9 additions & 12 deletions src/bk-user/bkuser/apis/web/tenant_setting/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,8 @@ def delete(self, request, *args, **kwargs):
class TenantUserValidityPeriodConfigRetrieveUpdateApi(
ExcludePatchAPIViewMixin, CurrentUserTenantMixin, generics.RetrieveUpdateAPIView
):
queryset = TenantUserValidityPeriodConfig.objects.all()

def get_object(self) -> TenantUserValidityPeriodConfig:
tenant_id = self.get_current_tenant_id()
tenant_user_validity_period_config = self.queryset.filter(tenant_id=tenant_id).first()
if not tenant_user_validity_period_config:
raise error_codes.OBJECT_NOT_FOUND.f(_("账户有效期配置丢失,请联系系统管理员"))

return tenant_user_validity_period_config
def get_queryset(self):
return TenantUserValidityPeriodConfig.objects.filter(tenant_id=self.get_current_tenant_id())

@swagger_auto_schema(
tags=["tenant-setting"],
Expand All @@ -136,7 +129,11 @@ def get_object(self) -> TenantUserValidityPeriodConfig:
},
)
def get(self, request, *args, **kwargs):
instance = self.get_object()
instance = self.get_queryset().first()

if not instance:
raise error_codes.OBJECT_NOT_FOUND.f(_("账户有效期配置丢失,请联系系统管理员"))

slz = TenantUserValidityPeriodConfigOutputSLZ(instance)
return Response(slz.data)

Expand All @@ -145,7 +142,7 @@ def get(self, request, *args, **kwargs):
operation_description="更新当前租户的账户有效期配置",
request_body=TenantUserValidityPeriodConfigInputSLZ(),
responses={
status.HTTP_200_OK: "",
status.HTTP_204_NO_CONTENT: "",
},
)
def put(self, request, *args, **kwargs):
Expand Down Expand Up @@ -182,4 +179,4 @@ def put(self, request, *args, **kwargs):
tenant_id, operator, tenant_user_validity_period_config
)

return Response()
return Response(status=status.HTTP_204_NO_CONTENT)
11 changes: 3 additions & 8 deletions src/bk-user/bkuser/apps/sync/syncers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from bkuser.apps.sync.constants import DataSourceSyncObjectType, SyncOperation, TenantSyncObjectType
from bkuser.apps.sync.context import DataSourceSyncTaskContext, TenantSyncTaskContext
from bkuser.apps.sync.converters import DataSourceUserConverter
from bkuser.apps.tenant.models import Tenant, TenantDepartment, TenantUser, TenantUserValidityPeriodConfig
from bkuser.apps.tenant.models import Tenant, TenantDepartment, TenantUser
from bkuser.common.constants import PERMANENT_TIME
from bkuser.plugins.models import RawDataSourceDepartment, RawDataSourceUser
from bkuser.utils.tree import bfs_traversal_tree, build_forest_with_parent_relations
Expand Down Expand Up @@ -533,10 +533,5 @@ def sync(self):
self.ctx.recorder.add(SyncOperation.CREATE, TenantSyncObjectType.USER, waiting_create_tenant_users)

def _get_user_account_expired_at(self) -> datetime.datetime:
# 根据配置初始化账号有效期
valid_time = PERMANENT_TIME
validity_period_config = TenantUserValidityPeriodConfig.objects.get(tenant_id=self.tenant.id)
if validity_period_config.enabled_validity_period and validity_period_config.valid_time > 0:
valid_time = timezone.now() + datetime.timedelta(days=validity_period_config.valid_time)

return valid_time
"""FIXME (su) 支持读取账号有效期配置,然后累加到 timezone.now() 上,目前是直接返回 PERMANENT_TIME"""
return PERMANENT_TIME

This file was deleted.

This file was deleted.

This file was deleted.

8 changes: 4 additions & 4 deletions src/bk-user/bkuser/apps/tenant/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,13 @@ class Meta:
class TenantUserValidityPeriodConfig(AuditedModel):
"""账号有效期-配置"""

tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, db_index=True, unique=True)
tenant = models.OneToOneField(Tenant, on_delete=models.CASCADE, db_index=True, unique=True)

enabled_validity_period = models.BooleanField("是否启用", default=True)
enabled_validity_period = models.BooleanField("是否启用账户有效期", default=True)
valid_time = models.IntegerField("有效期(单位:天)", default=-1)
remind_before_expire = models.JSONField("临X天过期发送提醒(单位:天)", default=list)
enabled_notification_methods = models.JSONField("通知方式", default=dict)
notification_templates = models.JSONField("通知模板", default=dict)
enabled_notification_methods = models.JSONField("通知方式", default=list)
notification_templates = models.JSONField("通知模板", default=list)


# class TenantUserSocialAccountRelation(TimestampedModel):
Expand Down
3 changes: 0 additions & 3 deletions src/bk-user/bkuser/apps/tenant/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ def _gen_base_ctx(self) -> Dict[str, str]:

def _gen_tenant_user_expiring_ctx(self) -> Dict[str, str]:
"""账号有效期-临期通知渲染参数"""
# FIXME (su) 提供修改密码的 URL(settings.BK_USER_URL + xxxx)
return {
"expired_at": self.user.account_expired_at_display,
**self._gen_base_ctx(),
Expand Down Expand Up @@ -132,15 +131,13 @@ def _send_email(self, user: TenantUser, tmpl: NotificationTemplate):
"send email to user %s, scene %s, title: %s", user.data_source_user.username, tmpl.scene, tmpl.title
)
content = self._render_tmpl(user, tmpl.content_html)
# FIXME (su) 修改为指定用户名
# 根据继承与否,获取真实邮箱
email = user.data_source_user.email if user.is_inherited_email else user.custom_email
cmsi.send_mail([email], tmpl.sender, tmpl.title, content) # type: ignore

def _send_sms(self, user: TenantUser, tmpl: NotificationTemplate):
logger.info("send sms to user %s, scene %s", user.data_source_user.username, tmpl.scene)
content = self._render_tmpl(user, tmpl.content)
# FIXME (su) 修改为指定用户名
# 根据继承与否,获取真实手机号
phone = user.data_source_user.phone if user.is_inherited_phone else user.custom_phone
cmsi.send_sms([phone], content)
Expand Down
11 changes: 9 additions & 2 deletions src/bk-user/bkuser/apps/tenant/periodic_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def send_tenant_user_expiring_notification():
now = timezone.now()

# 获取 租户-未过期用户 映射
tenant_ids = Tenant.objects.filter().values_list("id", flat=True)
tenant_ids = Tenant.objects.all().values_list("id", flat=True)
tenant_users_map = {
tenant_id: TenantUser.objects.filter(account_expired_at__gt=now.date(), tenant_id=tenant_id)
for tenant_id in tenant_ids
Expand All @@ -52,6 +52,9 @@ def send_tenant_user_expiring_notification():
# 发送通知
logger.info("going to notify expiring users in tenant-%s, count: %s", tenant_id, len(should_notify_users))

if not should_notify_users:
return

TenantUserValidityPeriodNotifier(tenant_id=tenant_id, scene=NotificationScene.TENANT_USER_EXPIRING).send(
should_notify_users
)
Expand All @@ -76,6 +79,10 @@ def send_tenant_user_expired_notification():
# 发送通知 过期
logger.info("going to notify expired users in tenant-%s, count: %s", tenant_id, len(tenant_users))

should_notify_users = list(tenant_users)
if not should_notify_users:
return

TenantUserValidityPeriodNotifier(tenant_id=tenant_id, scene=NotificationScene.TENANT_USER_EXPIRED).send(
list(tenant_users)
should_notify_users
)
12 changes: 11 additions & 1 deletion src/bk-user/bkuser/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import environ
import urllib3
from celery.schedules import crontab
from django.utils.encoding import force_bytes

# environ
Expand Down Expand Up @@ -241,7 +242,16 @@
# CELERY 配置,申明任务的文件路径,即包含有 @task 装饰器的函数文件
# CELERY_IMPORTS = []
# 内置的周期任务
# CELERYBEAT_SCHEDULE = {}
CELERYBEAT_SCHEDULE = {
"periodic_notify_expiring_tenant_users": {
"task": "bkuser.apps.tenant.periodic_tasks.send_tenant_user_expiring_notification",
"schedule": crontab(minute="0", hour="0"), # 每天凌晨0时执行
},
"periodic_notify_expired_tenant_users": {
"task": "bkuser.apps.tenant.periodic_tasks.send_tenant_user_expired_notification",
"schedule": crontab(minute="0", hour="4"), # 每天凌晨4时执行
},
}
# Celery 消息队列配置
CELERY_BROKER_URL = env.str("BK_BROKER_URL", default="")

Expand Down

0 comments on commit 65de189

Please sign in to comment.