feat(notifications): 新增可定制的通知配置页面

- NotificationSettingsPanel: 支持通知时机、字段排序、三种模板、预览与确认发送测试
- NotificationMarkdownPreview: 安全渲染消息预览,支持 emoji 与自定义文案
- notificationApi: 接入后端通知偏好接口并补充 Markdown 回归测试
This commit is contained in:
湛兮
2026-10-28 10:44:39 +08:00
parent 8910ee6be3
commit b867847eaa
8 changed files with 1374 additions and 0 deletions
+10
View File
@@ -66,3 +66,13 @@ npm run build
发布页只保留目标版本和生产确认。发布记录中的“回滚到此版本”会重新构建历史成功记录的精确提交;回滚不撤销数据库迁移或外部数据。流水线需支持 `DEPLOY_COMMIT`,无法核实历史 SHA 时明确拒绝。
MIT License。环境文件与真实凭据不得进入 Git。
## 通知配置
超级管理员打开 `/settings?tab=notifications`,可选择六种通知时机、十一种显示字段及字段顺序,切换软萌信笺 / 清爽简报 / 极简速报,并编辑标题、Markdown 正文与信尾。支持 emoji 和发布详情 / 构建日志链接开关。
`NotificationSettingsPanel.vue` 通过 `services/notificationApi.ts` 调用后端 `/notifications/config` 的读取、保存、预览、测试接口。预览示例由后端生成,和实际发布通知共用渲染逻辑;浏览器只解析安全的 Markdown 子集,不执行模板 HTML。字段为空时自动略过,正文留空时使用选定的预设样式。
保存使用版本号防止覆盖他人更新;离开页面时提示未保存修改。发送测试会先展示确认框,以当前草稿发送一条带测试标记的消息,不会自动保存;后端有发送限流。此页面不接收或保存通知 webhook。
后端上线前需要执行 `20261028030000_notification_config` 迁移。数据库、真实企微投递与生产部署需分别验收。
@@ -0,0 +1,90 @@
<script setup lang="ts">
import { computed } from 'vue'
import { notificationInlineParts } from '../utils/notificationMarkdown'
const props = defineProps<{ title: string; body: string }>()
const lines = computed(() =>
props.body.split('\n').map((text) => ({
quote: text.startsWith('> '),
heading: /^#{1,6} /.test(text),
empty: !text.trim(),
parts: notificationInlineParts(text.replace(/^(?:> |#{1,6} )/, '')),
})),
)
</script>
<template>
<div class="message-bubble">
<h3>{{ title }}</h3>
<div
v-for="(line, index) in lines"
:key="index"
class="message-line"
:class="{ quote: line.quote, heading: line.heading, spacer: line.empty }"
>
<template v-for="(part, partIndex) in line.parts" :key="partIndex">
<a
v-if="part.kind === 'link'"
:href="part.href"
aria-disabled="true"
tabindex="-1"
@click.prevent
>{{ part.text }}</a
>
<strong v-else-if="part.kind === 'strong'">{{ part.text }}</strong>
<code v-else-if="part.kind === 'code'">{{ part.text }}</code>
<span v-else>{{ part.text }}</span>
</template>
</div>
</div>
</template>
<style scoped>
.message-bubble {
position: relative;
padding: 20px;
border: 1px solid #e3e8e5;
border-radius: 3px 14px 14px 14px;
background: #fff;
color: #303a35;
box-shadow: 0 5px 18px #263c3005;
overflow-wrap: anywhere;
}
h3 {
margin: 0 0 14px;
font-size: 16px;
line-height: 1.65;
font-weight: 650;
}
.message-line {
font-size: 12px;
line-height: 1.95;
min-height: 1.2em;
white-space: pre-wrap;
}
.quote {
padding-left: 10px;
border-left: 3px solid #dce6df;
color: #6c786f;
}
.heading {
font-weight: 650;
font-size: 14px;
}
.spacer {
min-height: 12px;
}
a {
color: #347ab2;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
code {
padding: 2px 4px;
border-radius: 3px;
background: #f2f5f3;
font-size: 11px;
}
</style>
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
import { http } from './http'
import type {
NotificationConfig,
NotificationEvent,
NotificationPreferences,
NotificationPreview,
} from '../types/notifications'
export const notificationApi = {
async getConfig(): Promise<NotificationConfig> {
return (await http.get<NotificationConfig>('/notifications/config')).data
},
async save(
preferences: NotificationPreferences,
version: number,
): Promise<NotificationConfig> {
return (
await http.put<NotificationConfig>('/notifications/config', {
preferences,
version,
})
).data
},
async preview(
preferences: NotificationPreferences,
event: NotificationEvent,
): Promise<NotificationPreview> {
return (
await http.post<NotificationPreview>('/notifications/config/preview', {
preferences,
event,
})
).data
},
async test(preferences: NotificationPreferences, event: NotificationEvent) {
return (
await http.post<{ success: boolean; message: string; checkedAt: string }>(
'/notifications/config/test',
{ preferences, event, confirmed: true },
{ timeout: 15_000 },
)
).data
},
}
+65
View File
@@ -0,0 +1,65 @@
export type NotificationEvent =
| 'created'
| 'queued'
| 'succeeded'
| 'failed'
| 'canceled'
| 'retried'
export type NotificationField =
| 'projectKey'
| 'environment'
| 'ref'
| 'status'
| 'operator'
| 'buildNumber'
| 'duration'
| 'commit'
| 'createdAt'
| 'runId'
| 'failureSummary'
export interface NotificationPreferences {
enabled: boolean
events: NotificationEvent[]
fields: NotificationField[]
style: 'cozy' | 'simple' | 'compact'
emojiEnabled: boolean
titleTemplate: string
bodyTemplate: string
footer: string
includeDetailLink: boolean
includeBuildLink: boolean
}
export interface NotificationConfig {
preferences: NotificationPreferences
version: number
updatedAt?: string
channel: {
status: 'ok' | 'not_configured' | 'unavailable'
provider?: 'wecom' | 'feishu' | 'generic'
message?: string
}
catalog: {
events: {
key: NotificationEvent
label: string
emoji: string
title: string
}[]
fields: { key: NotificationField; label: string; emoji: string }[]
styles: {
key: NotificationPreferences['style']
label: string
emoji: string
description: string
}[]
variables: string[]
}
}
export interface NotificationPreview {
title: string
body: string
markdown: string
plainText: string
byteLength: number
sample: boolean
}
+39
View File
@@ -0,0 +1,39 @@
export type InlinePart = {
kind: 'text' | 'strong' | 'code' | 'link'
text: string
href?: string
}
// 只解析企微预览需要的 Markdown 子集。内容由 Vue 文本节点渲染,不执行 HTML。
export function notificationInlineParts(line: string): InlinePart[] {
const parts: InlinePart[] = []
const pattern = /\[([^\]\n]+)\]\(([^\s)]+)\)|\*\*([^*\n]+)\*\*|`([^`\n]+)`/g
let offset = 0
for (const match of line.matchAll(pattern)) {
const index = match.index ?? 0
if (index > offset)
parts.push({ kind: 'text', text: line.slice(offset, index) })
if (match[1] && match[2]) {
let safe = false
try {
const url = new URL(match[2])
safe =
['https:', 'http:'].includes(url.protocol) &&
!url.username &&
!url.password
} catch {
/* 无效链接按纯文本呈现。 */
}
parts.push(
safe
? { kind: 'link', text: match[1], href: match[2] }
: { kind: 'text', text: match[0] },
)
} else if (match[3]) parts.push({ kind: 'strong', text: match[3] })
else if (match[4]) parts.push({ kind: 'code', text: match[4] })
offset = index + match[0].length
}
if (offset < line.length)
parts.push({ kind: 'text', text: line.slice(offset) })
return parts
}
+3
View File
@@ -7,6 +7,7 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import AuditJsonCell from '../components/AuditJsonCell.vue'
import NotificationSettingsPanel from '../components/NotificationSettingsPanel.vue'
import { devopsApi } from '../services/devopsApi'
import { usePlatformStore } from '../stores/platform'
import { useSessionStore } from '../stores/session'
@@ -660,6 +661,8 @@ function resetAuditFilters() {
</div>
</section>
<NotificationSettingsPanel v-if="activeTab === 'notifications' && session.role === 'super_admin'" />
<section v-if="activeTab === 'notifications' && session.role === 'super_admin'" class="panel">
<div class="panel-header">
<h2>通知 outbox</h2>
+42
View File
@@ -0,0 +1,42 @@
import { after, test } from 'node:test'
import assert from 'node:assert/strict'
import { createServer } from 'vite'
const server = await createServer({
server: { middlewareMode: true, hmr: false, ws: false },
appType: 'custom',
})
const { notificationInlineParts } = await server.ssrLoadModule(
'/src/utils/notificationMarkdown.ts',
)
after(() => server.close())
test('通知预览呈现加粗、代码和 HTTP(S) 链接', () => {
const parts = notificationInlineParts(
'项目 **role-user** · `v1.2` [详情](https://example.com/runs)',
)
assert.equal(parts.find((part) => part.kind === 'strong').text, 'role-user')
assert.equal(parts.find((part) => part.kind === 'code').text, 'v1.2')
assert.equal(
parts.find((part) => part.kind === 'link').href,
'https://example.com/runs',
)
})
test('危险协议和包含凭据的链接按纯文本呈现', () => {
for (const url of [
'javascript:alert',
'data:text/html,hello',
'https://user:pass@example.com/',
]) {
assert.equal(
notificationInlineParts(`[链接](${url})`).some(
(part) => part.kind === 'link',
),
false,
)
}
})
test('模板 HTML 保留为文本节点,不生成可执行节点', () => {
const text = '<img src=x onerror=alert(1)><script>alert(1)</script>'
assert.deepEqual(notificationInlineParts(text), [{ kind: 'text', text }])
})