feat: add multi-channel notification delivery

This commit is contained in:
biss committed 2026-10-29 18:54:04 +08:00
1 parent 22ae66fe2d
commit 0552b3e424
21 files changed
+13567 -7

No files matched your search

+1
View File
@@ -67,6 +67,7 @@ declare module 'vue' {
GradeAppealPanel: typeof import('./components/GradeAppealPanel.vue')['default']
LoginCaptcha: typeof import('./components/LoginCaptcha.vue')['default']
NativePlaceCascader: typeof import('./components/NativePlaceCascader.vue')['default']
NotificationDeliverySettings: typeof import('./components/NotificationDeliverySettings.vue')['default']
NotificationRichTextEditor: typeof import('./components/NotificationRichTextEditor.vue')['default']
PerformanceReportPanel: typeof import('./components/PerformanceReportPanel.vue')['default']
RichMessageContent: typeof import('./components/RichMessageContent.vue')['default']
@@ -0,0 +1,272 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Bell, Delete, Message, Refresh } from '@element-plus/icons-vue'
import http, { apiErrorMessage } from '../api/http'
const loading = ref(false)
const saving = ref(false)
const subscribing = ref(false)
const preferences = ref<any>()
const deliveries = ref<any[]>([])
const deliveryTotal = ref(0)
const form = reactive({
emailEnabled: false,
webPushEnabled: false,
quietHoursEnabled: false,
quietStart: '22:00',
quietEnd: '07:00',
timeZoneId: 'Asia/Shanghai',
})
const canUseBrowserPush = computed(() =>
window.isSecureContext &&
'Notification' in window &&
'serviceWorker' in navigator &&
'PushManager' in window)
const timeZones = [
{ value: 'Asia/Shanghai', label: '中国标准时间(上海)' },
{ value: 'Asia/Hong_Kong', label: '香港时间' },
{ value: 'Asia/Tokyo', label: '日本时间(东京)' },
{ value: 'Europe/London', label: '英国时间(伦敦)' },
{ value: 'America/New_York', label: '美国东部时间(纽约)' },
{ value: 'UTC', label: 'UTC' },
]
function minuteToTime(value: number) {
return `${String(Math.floor(value / 60)).padStart(2, '0')}:${String(value % 60).padStart(2, '0')}`
}
function timeToMinute(value: string) {
const [hour, minute] = value.split(':').map(Number)
return hour * 60 + minute
}
function base64UrlToUint8Array(value: string) {
const padding = '='.repeat((4 - value.length % 4) % 4)
const raw = atob((value + padding).replaceAll('-', '+').replaceAll('_', '/'))
return Uint8Array.from(raw, char => char.charCodeAt(0))
}
function channelLabel(value: string) {
return value === 'Email' ? '邮件' : 'Web Push'
}
function stateLabel(value: string) {
return ({
Pending: '等待投递',
Processing: '投递中',
Delivered: '已送达',
Failed: '失败',
Suppressed: '未投递',
} as Record<string, string>)[value] ?? value
}
function stateType(value: string): 'success' | 'info' | 'warning' | 'primary' | 'danger' {
const types: Record<string, 'success' | 'info' | 'warning' | 'primary' | 'danger'> = {
Pending: 'warning',
Processing: 'primary',
Delivered: 'success',
Failed: 'danger',
Suppressed: 'info',
}
return types[value] ?? 'info'
}
async function load() {
loading.value = true
try {
const [preferenceResponse, deliveryResponse] = await Promise.all([
http.get('/notifications/preferences'),
http.get('/notifications/deliveries', { params: { page: 1, pageSize: 20 } }),
])
preferences.value = preferenceResponse.data
form.emailEnabled = preferenceResponse.data.emailEnabled
form.webPushEnabled = preferenceResponse.data.webPushEnabled
form.quietHoursEnabled = preferenceResponse.data.quietHoursEnabled
form.quietStart = minuteToTime(preferenceResponse.data.quietStartMinute)
form.quietEnd = minuteToTime(preferenceResponse.data.quietEndMinute)
form.timeZoneId = preferenceResponse.data.timeZoneId
deliveries.value = deliveryResponse.data.items
deliveryTotal.value = deliveryResponse.data.total
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
loading.value = false
}
}
async function save(showMessage = true) {
saving.value = true
try {
await http.put('/notifications/preferences', {
emailEnabled: form.emailEnabled,
webPushEnabled: form.webPushEnabled,
quietHoursEnabled: form.quietHoursEnabled,
quietStartMinute: timeToMinute(form.quietStart),
quietEndMinute: timeToMinute(form.quietEnd),
timeZoneId: form.timeZoneId,
})
if (showMessage) ElMessage.success('通知偏好已保存')
} catch (error) {
ElMessage.error(apiErrorMessage(error))
throw error
} finally {
saving.value = false
}
}
async function subscribeBrowser() {
if (!canUseBrowserPush.value) {
ElMessage.warning('当前浏览器或页面环境不支持 Web Push,请使用 HTTPS 打开 PWA。')
return
}
if (!preferences.value?.webPushProviderEnabled || !preferences.value?.webPushPublicKey) {
ElMessage.warning('服务器尚未配置 Web Push。')
return
}
subscribing.value = true
try {
const permission = await Notification.requestPermission()
if (permission !== 'granted') throw new Error('浏览器未授予通知权限。')
const registration = await navigator.serviceWorker.ready
const existing = await registration.pushManager.getSubscription()
const subscription = existing ?? await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: base64UrlToUint8Array(preferences.value.webPushPublicKey),
})
const json = subscription.toJSON()
await http.post('/notifications/push-subscriptions', {
endpoint: subscription.endpoint,
p256dh: json.keys?.p256dh,
auth: json.keys?.auth,
expiresAt: subscription.expirationTime
? new Date(subscription.expirationTime).toISOString()
: null,
})
form.webPushEnabled = true
await save(false)
await load()
ElMessage.success('当前浏览器已启用推送通知')
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : apiErrorMessage(error))
} finally {
subscribing.value = false
}
}
async function removeSubscription(id: string) {
try {
await http.delete(`/notifications/push-subscriptions/${id}`)
await load()
ElMessage.success('已撤销该浏览器的服务端推送订阅')
} catch (error) {
ElMessage.error(apiErrorMessage(error))
}
}
onMounted(load)
</script>
<template>
<section v-loading="loading" class="delivery-settings">
<header class="settings-heading">
<div>
<span>DELIVERY PREFERENCES</span>
<h3>外部通知与静默时段</h3>
<p>站内消息始终保留;这里仅控制邮件和浏览器推送,不会削弱业务通知留痕。</p>
</div>
<el-button :icon="Refresh" @click="load">刷新状态</el-button>
</header>
<div class="settings-grid">
<article class="channel-card">
<div class="channel-icon email"><el-icon><Message /></el-icon></div>
<div>
<h4>邮件通知</h4>
<p v-if="preferences?.emailConfirmed">发送到 {{ preferences.email }}</p>
<p v-else>账号尚未配置并验证邮箱。</p>
<small v-if="!preferences?.emailProviderEnabled">服务器 SMTP 尚未启用。</small>
</div>
<el-switch
v-model="form.emailEnabled"
:disabled="!preferences?.emailProviderEnabled || !preferences?.emailConfirmed"
/>
</article>
<article class="channel-card">
<div class="channel-icon push"><el-icon><Bell /></el-icon></div>
<div>
<h4>浏览器 Web Push</h4>
<p>已登记 {{ preferences?.subscriptions?.length ?? 0 }} 个浏览器订阅。</p>
<small v-if="!preferences?.webPushProviderEnabled">服务器 VAPID 尚未配置。</small>
<small v-else-if="!canUseBrowserPush">当前页面不是受支持的 HTTPS/PWA 环境。</small>
</div>
<el-switch
v-model="form.webPushEnabled"
:disabled="!preferences?.webPushProviderEnabled"
/>
</article>
</div>
<div class="quiet-panel">
<div class="quiet-copy">
<el-switch v-model="form.quietHoursEnabled" />
<div>
<h4>静默时段</h4>
<p>静默期间外部渠道延后投递,站内收件箱仍会立即收到。</p>
</div>
</div>
<div class="quiet-controls">
<el-time-select v-model="form.quietStart" start="00:00" step="00:30" end="23:30" :disabled="!form.quietHoursEnabled" />
<span>至</span>
<el-time-select v-model="form.quietEnd" start="00:00" step="00:30" end="23:30" :disabled="!form.quietHoursEnabled" />
<el-select v-model="form.timeZoneId" filterable :disabled="!form.quietHoursEnabled">
<el-option v-for="item in timeZones" :key="item.value" :value="item.value" :label="item.label" />
</el-select>
</div>
</div>
<div class="settings-actions">
<el-button
type="primary"
:loading="subscribing"
:disabled="!preferences?.webPushProviderEnabled || !canUseBrowserPush"
@click="subscribeBrowser"
>
启用当前浏览器推送
</el-button>
<el-button type="success" :loading="saving" @click="save()">保存偏好</el-button>
</div>
<div v-if="preferences?.subscriptions?.length" class="subscription-list">
<h4>已登记浏览器</h4>
<div v-for="item in preferences.subscriptions" :key="item.id" class="subscription-row">
<div>
<b>{{ item.userAgent || '未知浏览器' }}</b>
<small>最近登记:{{ new Date(item.lastSeenAt).toLocaleString('zh-CN') }}</small>
</div>
<el-button type="danger" plain :icon="Delete" @click="removeSubscription(item.id)">撤销</el-button>
</div>
</div>
<div class="delivery-log">
<header>
<div><h4>最近投递记录</h4><p>展示当前账号的邮件和 Web Push 送达、延后与失败状态。</p></div>
<span>共 {{ deliveryTotal }} 条</span>
</header>
<el-table :data="deliveries" empty-text="启用外部渠道后,新的通知投递记录会显示在这里">
<el-table-column prop="title" label="通知" min-width="220" show-overflow-tooltip />
<el-table-column label="渠道" width="110"><template #default="{ row }">{{ channelLabel(row.channel) }}</template></el-table-column>
<el-table-column label="状态" width="120"><template #default="{ row }"><el-tag :type="stateType(row.state)">{{ stateLabel(row.state) }}</el-tag></template></el-table-column>
<el-table-column prop="attemptCount" label="尝试" width="80" />
<el-table-column label="时间" width="190"><template #default="{ row }">{{ new Date(row.deliveredAt || row.nextAttemptAt).toLocaleString('zh-CN') }}</template></el-table-column>
<el-table-column prop="lastError" label="说明" min-width="220" show-overflow-tooltip />
</el-table>
</div>
</section>
</template>
<style scoped>
.delivery-settings{display:grid;gap:20px}.settings-heading,.delivery-log>header{display:flex;justify-content:space-between;align-items:flex-start;gap:20px}.settings-heading span{font-size:12px;font-weight:800;letter-spacing:.14em;color:#4468a8}.settings-heading h3,.delivery-log h4{margin:5px 0 4px;color:#17233f}.settings-heading p,.delivery-log p,.channel-card p,.quiet-panel p{margin:0;color:#68748a}.settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.channel-card{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:15px;padding:20px;border:1px solid #e1e7f1;border-radius:16px;background:#fff}.channel-card h4,.quiet-panel h4,.subscription-list h4{margin:0 0 5px;color:#1b2945}.channel-card small{display:block;margin-top:5px;color:#a06a24}.channel-icon{display:grid;place-items:center;width:44px;height:44px;border-radius:13px;font-size:21px}.channel-icon.email{color:#3068ad;background:#eaf2ff}.channel-icon.push{color:#7a4cab;background:#f2eafe}.quiet-panel{display:flex;justify-content:space-between;align-items:center;gap:20px;padding:20px;border-radius:16px;background:#f6f8fc}.quiet-copy,.quiet-controls{display:flex;align-items:center;gap:12px}.quiet-controls .el-select{width:230px}.settings-actions{display:flex;justify-content:flex-end;gap:10px}.subscription-list{display:grid;gap:10px;padding-top:4px}.subscription-row{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:13px 15px;border:1px solid #e4e9f2;border-radius:12px}.subscription-row div{display:grid;gap:4px;min-width:0}.subscription-row b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#27344c}.subscription-row small{color:#7d8798}.delivery-log{display:grid;gap:14px;padding-top:6px}.delivery-log>header>span{padding:6px 10px;border-radius:999px;background:#eef3fa;color:#466087;font-size:13px}@media(max-width:900px){.settings-grid{grid-template-columns:1fr}.quiet-panel,.settings-heading,.delivery-log>header{align-items:stretch;flex-direction:column}.quiet-controls{flex-wrap:wrap}.quiet-controls .el-select{width:100%}.settings-actions{justify-content:stretch;flex-wrap:wrap}.settings-actions .el-button{flex:1}}
</style>
+16 -4
View File
@@ -9,11 +9,13 @@ import {
Promotion,
Refresh,
Search,
Setting,
User,
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import http, { apiErrorMessage } from '../api/http'
import RichMessageContent from '../components/RichMessageContent.vue'
import NotificationDeliverySettings from '../components/NotificationDeliverySettings.vue'
import { useAuthStore } from '../stores/auth'
const router = useRouter()
@@ -24,7 +26,7 @@ const senderRoles = ['SuperAdmin', 'AcademicAdmin', 'CollegeAdmin', 'Counselor',
const canSend = computed(() =>
auth.user?.roles.some(role => senderRoles.includes(role)) ?? false)
const activeTab = ref<'inbox' | 'compose' | 'sent'>('inbox')
const activeTab = ref<'inbox' | 'compose' | 'sent' | 'settings'>('inbox')
const notifications = ref<any[]>([])
const sentMessages = ref<any[]>([])
const unreadCount = ref(0)
@@ -306,7 +308,7 @@ function removeSelectedRecipient(recipientId: string) {
item => item.id !== recipientId)
}
async function changeTab(tab: 'inbox' | 'compose' | 'sent') {
async function changeTab(tab: 'inbox' | 'compose' | 'sent' | 'settings') {
activeTab.value = tab
if (tab === 'compose') await loadComposer()
if (tab === 'sent') await loadSent(true)
@@ -447,7 +449,7 @@ onMounted(() => load())
>
全部已读
</el-button>
<el-button :icon="Refresh" @click="activeTab === 'sent' ? loadSent() : load()">
<el-button v-if="activeTab !== 'settings'" :icon="Refresh" @click="activeTab === 'sent' ? loadSent() : load()">
刷新
</el-button>
</div>
@@ -481,6 +483,14 @@ onMounted(() => load())
<el-icon><Message /></el-icon>
已发送
</button>
<button
type="button"
:class="{ active: activeTab === 'settings' }"
@click="changeTab('settings')"
>
<el-icon><Setting /></el-icon>
通知设置
</button>
</section>
<template v-if="activeTab === 'inbox'">
@@ -848,7 +858,7 @@ onMounted(() => load())
</div>
</section>
<template v-else>
<template v-else-if="activeTab === 'sent'">
<section v-loading="loading" class="sent-list">
<article v-for="item in sentMessages" :key="item.id" class="sent-card">
<header>
@@ -878,6 +888,8 @@ onMounted(() => load())
</div>
</template>
<NotificationDeliverySettings v-else />
<el-dialog
v-model="selectedNotification"
width="min(680px, 92vw)"