Skip to content

Commit

Permalink
Merge pull request #437 from 0RAJA/feat_notice_group_var
Browse files Browse the repository at this point in the history
feat: 通知组内新增变量 --story=119072639
  • Loading branch information
0RAJA authored Sep 18, 2024
2 parents 6002681 + 8d2b6c7 commit d79e53c
Show file tree
Hide file tree
Showing 16 changed files with 197 additions and 39 deletions.
4 changes: 3 additions & 1 deletion release.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
### V1.15.0 版本更新日志

[TODO]
### 新增

- [ 新增 ] 通知组内新增变量

### V1.14.0 版本更新日志

Expand Down
18 changes: 18 additions & 0 deletions src/backend/apps/notice/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
We undertake not to change the open source license (MIT license) applicable
to the current version of the project delivered to anyone in the future.
"""
from typing import Optional

from django.utils.translation import gettext_lazy

Expand Down Expand Up @@ -59,3 +60,20 @@ class RelateType(TextChoices):

RISK = "risk", gettext_lazy("风险")
ERROR = "error", gettext_lazy("异常")


class MemberVariable(TextChoices):
"""
成员变量
"""

OPERATOR = "$OPERATOR", gettext_lazy("责任人")
OPERATOR_LEADER = "$OPERATOR_LEADER", gettext_lazy("责任人上级")

@classmethod
def match(cls, key: str) -> Optional["MemberVariable"]:
"""
匹配成员变量
"""

return cls._value2member_map_.get(key)
6 changes: 4 additions & 2 deletions src/backend/apps/notice/handlers/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

from apps.notice.constants import ADMIN_NOTICE_GROUP_ID, RelateType
from apps.notice.models import NoticeContent, NoticeContentConfig, NoticeGroup
from apps.notice.parser import IgnoreMemberVariableParser


class ErrorMsgHandler:
Expand All @@ -38,16 +39,17 @@ def __init__(self, title, content):

def send(self):
notice_group: NoticeGroup = NoticeGroup.objects.get(group_id=ADMIN_NOTICE_GROUP_ID)
receivers = IgnoreMemberVariableParser().parse_group(notice_group)
resource.notice.send_notice(
relate_type=RelateType.ERROR,
relate_id=self.get_current_trace_id(self.__class__.__name__),
agg_key=None,
msg_type=[c.get("msg_type") for c in notice_group.notice_config if "msg_type" in c],
receivers=notice_group.group_member,
receivers=receivers,
title=self.title,
content=self.content.to_string(),
)
logger.info("[SendErrorMsgDone] NoticeGroup => %s; Members => %s", notice_group.pk, notice_group.group_member)
logger.info("[SendErrorMsgDone] NoticeGroup => %s; Members => %s", notice_group.pk, receivers)

def build_content(self, content: str) -> NoticeContent:
return NoticeContent(
Expand Down
71 changes: 71 additions & 0 deletions src/backend/apps/notice/parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
import abc
from typing import List, Union

from bk_resource import resource
from django.db.models import QuerySet

from apps.notice.constants import MemberVariable
from apps.notice.models import NoticeGroup


class MemberVariableParserBase(abc.ABC):
def is_skip(self, member: str) -> bool:
"""默认跳过变量"""
return MemberVariable.match(member) is not None

@abc.abstractmethod
def parse_member(self, member: Union[str, MemberVariable]) -> str:
"""解析成员"""
raise NotImplementedError()

def parse_group(self, group: NoticeGroup) -> List[str]:
"""
处理组成员
"""

parsed_members = set()
for member in group.group_member:
if self.is_skip(member):
continue
member = self.parse_member(member)
if member:
parsed_members.add(member)
return list(parsed_members)

def parse_groups(self, groups: Union[QuerySet["NoticeGroup"], List["NoticeGroup"]]) -> List[str]:
"""
解析处理组成员
"""

return list({member for group in groups for member in self.parse_group(group)})


class MemberVariableParser(MemberVariableParserBase):
"""
成员变量解析器
"""

def __init__(self, operator: str):
"""
:param operator: 责任人
"""

self.operator = operator

def parse_member(self, member: Union[str, MemberVariable]) -> str:
match member:
case MemberVariable.OPERATOR:
return self.operator
case MemberVariable.OPERATOR_LEADER:
return resource.user_manage.retrieve_leader(id=self.operator)
return member


class IgnoreMemberVariableParser(MemberVariableParserBase):
"""
忽略成员变量解析器
"""

def parse_member(self, member: Union[str, MemberVariable]) -> str:
return member
14 changes: 13 additions & 1 deletion src/backend/apps/notice/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@
from django.utils.translation import gettext_lazy

from apps.audit.resources import AuditMixinResource
from apps.notice.constants import MsgType
from apps.notice.constants import MemberVariable, MsgType
from apps.notice.models import NoticeGroup, NoticeLogV2
from apps.notice.serializers import (
CreateNoticeGroupRequestSerializer,
CreateNoticeGroupResponseSerializer,
DeleteNoticeGroupRequestSerializer,
GetMsgTypeResponseSerializer,
GetNoticeCommonResponseSerializer,
ListAllNoticeGroupResponseSerializer,
ListNoticeGroupRequestSerializer,
ListNoticeGroupResponseSerializer,
Expand All @@ -45,6 +46,7 @@
from apps.permission.handlers.actions import ActionEnum
from apps.permission.handlers.permission import Permission
from apps.permission.handlers.resource_types import ResourceEnum
from core.utils.tools import choices_to_dict


class NoticeMeta(AuditMixinResource, abc.ABC):
Expand Down Expand Up @@ -171,3 +173,13 @@ class SendNotice(NoticeMeta):

def perform_request(self, validated_request_data):
NoticeLogV2.objects.create(**validated_request_data)


class GetNoticeCommon(NoticeMeta):
name = gettext_lazy("Get Notice Common")
ResponseSerializer = GetNoticeCommonResponseSerializer

def perform_request(self, validated_request_data):
return {
"member_variable": choices_to_dict(MemberVariable, val="value", name="label"),
}
9 changes: 9 additions & 0 deletions src/backend/apps/notice/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
)
from apps.notice.exceptions import NoticeGroupNameDuplicate
from apps.notice.models import NoticeGroup, NoticeLogV2
from core.serializers import ChoiceListSerializer


class GetMsgTypeResponseSerializer(serializers.Serializer):
Expand Down Expand Up @@ -214,3 +215,11 @@ def validate_receivers(self, receivers: List[str]) -> List[str]:
if not whitelist_users:
return receivers
return [u for u in receivers if u in whitelist_users]


class GetNoticeCommonResponseSerializer(serializers.Serializer):
"""
Get Notice Common
"""

member_variable = ChoiceListSerializer(label=gettext_lazy("Member Variable"), many=True)
1 change: 1 addition & 0 deletions src/backend/apps/notice/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class NoticeViewSet(ResourceViewSet):

resource_routes = [
ResourceRoute("GET", resource.notice.get_msg_type, endpoint="msg_type"),
ResourceRoute("GET", resource.notice.get_notice_common, endpoint="common"),
]


Expand Down
13 changes: 13 additions & 0 deletions src/backend/core/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
from django.utils.translation import gettext_lazy
from rest_framework import serializers


class ChoiceListSerializer(serializers.Serializer):
"""
Choice List
"""

label = serializers.CharField(label=gettext_lazy("Label"), allow_blank=True, allow_null=True)
value = serializers.CharField(label=gettext_lazy("Value"))
config = serializers.JSONField(label=gettext_lazy("Config"), required=False)
29 changes: 19 additions & 10 deletions src/backend/locale/en/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-08-26 10:55+0800\n"
"POT-Creation-Date: 2024-09-12 13:19+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
Expand Down Expand Up @@ -1506,6 +1506,9 @@ msgstr "Risk"
msgid "异常"
msgstr "Error"

msgid "责任人上级"
msgstr "Person Superior"

msgid "通知组名称重复"
msgstr "Notice Group Name Duplicate"

Expand Down Expand Up @@ -1608,6 +1611,9 @@ msgstr "Create Notice Group"
msgid "更新通知组"
msgstr "Update Notice Group"

msgid "Get Notice Common"
msgstr "Get Strategy Common"

msgid "此为系统邮件,由蓝鲸审计中心自动发送,请勿回复"
msgstr "Sent by Blueking Audit Center"

Expand All @@ -1630,6 +1636,9 @@ msgstr "Notice Group Name Invalid with %s"
msgid "内置通知组禁止删除"
msgstr "Build in notice group is not allowed to delete"

msgid "Member Variable"
msgstr "Member Variable"

msgid "权限中心异常"
msgstr "IAM Error"

Expand Down Expand Up @@ -1946,6 +1955,15 @@ msgstr "Admin Required"
msgid "Token Invalid"
msgstr "Token Invalid"

msgid "Label"
msgstr "Label"

msgid "Value"
msgstr "Value"

msgid "Config"
msgstr "Config"

msgid "数据拉取"
msgstr "Data Pull"

Expand Down Expand Up @@ -3469,9 +3487,6 @@ msgstr "Strategy Count"
msgid "Key"
msgstr "Key"

msgid "Value"
msgstr "Value"

msgid "Method"
msgstr "Method"

Expand Down Expand Up @@ -3502,9 +3517,6 @@ msgstr "Detects"
msgid "System ID"
msgstr "System ID"

msgid "Label"
msgstr "Label"

msgid "Children"
msgstr "Children"

Expand All @@ -3514,9 +3526,6 @@ msgstr "Action ID"
msgid "Field Type"
msgstr "Field Type"

msgid "Config"
msgstr "Config"

msgid "Strategy Operator"
msgstr "Strategy Operator"

Expand Down
29 changes: 19 additions & 10 deletions src/backend/locale/zh_CN/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-08-26 10:55+0800\n"
"POT-Creation-Date: 2024-09-12 13:19+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
Expand Down Expand Up @@ -1506,6 +1506,9 @@ msgstr "风险"
msgid "异常"
msgstr "异常"

msgid "责任人上级"
msgstr "责任人上级"

msgid "通知组名称重复"
msgstr "通知组名称重复"

Expand Down Expand Up @@ -1608,6 +1611,9 @@ msgstr "创建通知组"
msgid "更新通知组"
msgstr "更新通知组"

msgid "Get Notice Common"
msgstr "获取策略通用参数"

msgid "此为系统邮件,由蓝鲸审计中心自动发送,请勿回复"
msgstr "此为系统邮件,由蓝鲸审计中心自动发送,请勿回复"

Expand All @@ -1630,6 +1636,9 @@ msgstr "通知组名称不能包含特殊字符 %s"
msgid "内置通知组禁止删除"
msgstr "内置通知组禁止删除"

msgid "Member Variable"
msgstr "成员变量"

msgid "权限中心异常"
msgstr "权限中心异常"

Expand Down Expand Up @@ -1946,6 +1955,15 @@ msgstr "管理员请求"
msgid "Token Invalid"
msgstr "Token验证失败"

msgid "Label"
msgstr "标签"

msgid "Value"
msgstr "值"

msgid "Config"
msgstr "配置"

msgid "数据拉取"
msgstr "数据拉取"

Expand Down Expand Up @@ -3469,9 +3487,6 @@ msgstr "策略数量"
msgid "Key"
msgstr "键"

msgid "Value"
msgstr "值"

msgid "Method"
msgstr "方法"

Expand Down Expand Up @@ -3502,9 +3517,6 @@ msgstr "识别条件"
msgid "System ID"
msgstr "系统ID"

msgid "Label"
msgstr "标签"

msgid "Children"
msgstr "子数据"

Expand All @@ -3514,9 +3526,6 @@ msgstr "操作ID"
msgid "Field Type"
msgstr "字段类型"

msgid "Config"
msgstr "配置"

msgid "Strategy Operator"
msgstr "策略操作符"

Expand Down
Loading

0 comments on commit d79e53c

Please sign in to comment.