Vue 通知系統完整文件
系統概述
Vue 通知系統是一個功能完整的電商平台通知管理系統,支援個人通知、群組通知、即時推送、智能建議等功能。系統採用 Vue 3 + TypeScript + Supabase 架構,提供完整的通知生命週期管理。
核心特性
核心功能
- 個人通知管理:支援個人通知的創建、讀取、標記、歸檔
- 群組通知系統:支援角色通知、廣播通知、自定義群組通知
- 即時通知推送:基於 Supabase Realtime 的即時通知推送
- 智能建議系統:自動分析通知並提供完成建議
- 通知模板系統:支援動態模板和參數替換
- 多場景顯示:支援列表、彈窗、徽章、Toast 等多種顯示模式
通知分類
- 資訊型通知(informational):純資訊展示,使用者只需知悉
- 任務型通知(actionable):需要使用者處理或回應的通知
完成策略
- 自動完成(auto):系統自動標記為完成
- 智能建議(suggested):系統提供智能完成建議
- 手動完成(manual):需要使用者手動標記完成
系統架構
資料庫結構
sql
-- 核心通知表
notifications (
id, user_id, type, title, message, priority, status,
category, completion_strategy, metadata, created_at, ...
)
-- 通知模板表
notification_templates (
id, type, title_template, message_template,
default_priority, category, completion_strategy, ...
)
-- 使用者偏好設定
notification_preferences (
id, user_id, notification_type, channels, is_enabled, ...
)前端組件架構
src/components/notify/
├── NotificationCard.vue # 通知卡片組件
├── NotificationBadge.vue # 通知徽章組件
├── NotificationList.vue # 通知列表組件
├── NotificationSettings.vue # 通知設定組件
├── notificationIconConfig.ts # 統一圖示配置
└── config.ts # 通知配置API 使用指南
useNotification Composable
核心通知管理 composable,提供完整的通知操作功能。
typescript
import { useNotification } from '@/composables/useNotification'
const {
// 狀態
notifications,
stats,
loading,
error,
// 方法
loadNotifications,
markAsRead,
markAsCompleted,
createNotification,
// 群組通知
groupNotifications,
// 即時訂閱
subscribeToNotifications,
} = useNotification(userId)創建通知
typescript
// 個人通知
await createNotification('order_new', {
order_number: 'ORD-2024-001',
total_amount: 1250.0
})
// 群組通知
await groupNotifications.notifyRole('admin', 'system_maintenance', {
title: '系統維護通知',
message: '系統將於今晚進行維護'
})通知操作
typescript
// 標記為已讀
await markAsRead(notificationId)
// 標記任務完成
await markAsCompleted(notificationId)
// 接受智能建議
await acceptCompletionSuggestion(notificationId)組件使用指南
NotificationCard
支援多種顯示模式的通知卡片組件。
vue
<template>
<NotificationCard
:notification="notification"
:display-mode="'list'"
@mark-as-read="handleMarkAsRead"
@click="handleNotificationClick"
/>
</template>DisplayMode 選項:
list:列表模式(預設),完整功能badge:徽章模式,緊湊顯示toast:Toast 模式,用於彈出通知modal:彈窗模式,適用於對話框
NotificationBadge
頁面右上角的通知徽章組件。
vue
<template>
<NotificationBadge
:user-id="userId"
:auto-refresh="true"
:refresh-interval="30000"
@notification-click="handleNotificationClick"
@view-all="goToNotificationCenter"
/>
</template>NotificationList
完整的通知列表組件,支援搜尋、篩選、分頁。
vue
<template>
<NotificationList
:user-id="userId"
:show-filters="true"
:show-search="true"
:initial-tab="'all'"
@notification-click="handleClick"
/>
</template>通知類型系統
內建通知類型
訂單相關
order_new:新訂單通知order_payment_failed:支付失敗通知order_cancelled:訂單取消通知order_shipping_delayed:出貨延遲通知
庫存相關
inventory_low_stock:庫存不足通知inventory_out_of_stock:缺貨通知
客服相關
customer_service_new_request:新客服請求customer_service_urgent:緊急客服通知
安全相關
security_unusual_login:異常登入通知security_permission_changed:權限變更通知
自定義通知類型
typescript
// 1. 在資料庫新增通知模板
await notificationTemplateApi.createTemplate({
type: 'custom_notification',
titleTemplate: '自定義通知:{{title}}',
messageTemplate: '{{message}}',
category: 'informational',
completionStrategy: 'manual'
})
// 2. 更新 notificationIconConfig.ts
export const notificationIcons = {
// ... 其他圖示
custom_notification: CustomIcon,
}
// 3. 使用新的通知類型
await createNotification('custom_notification', {
title: '自定義標題',
message: '自定義訊息'
})樣式系統
統一圖示配置
所有通知相關的圖示都統一管理在 notificationIconConfig.ts 中:
typescript
// 通知類型圖示
export const notificationIcons = {
order_new: ShoppingCart,
inventory_low_stock: Package,
// ...
}
// 優先級樣式
export const priorityIconClasses = {
urgent: 'bg-red-100 text-red-600',
high: 'bg-orange-100 text-orange-600',
// ...
}
// 分類樣式
export const categoryClasses = {
actionable: 'bg-blue-100 text-blue-800', // 任務
informational: 'bg-green-100 text-green-800', // 通知
}響應式設計
所有組件都支援響應式設計,自動適應不同螢幕尺寸。
即時通訊整合
Supabase Realtime 訂閱
系統使用 Supabase Realtime 實現即時通知推送:
typescript
// 自動訂閱通知變更
const { subscribeToNotifications, isRealtimeConnected } = useNotification(userId)
// 組件掛載時自動訂閱
onMounted(() => {
subscribeToNotifications()
})
// 連線狀態監控
watch(isRealtimeConnected, (connected) => {
if (!connected) {
// 啟動備援輪詢機制
startPolling()
}
})備援輪詢機制
當 Realtime 連線失敗時,系統會自動啟動輪詢機制確保通知不遺漏。
智能建議系統
觸發條件
智能建議會在以下情況觸發:
- 任務型通知超過預定時間未處理
- 系統檢測到可自動完成的操作
- 基於歷史資料的智能推薦
🔍 智能建議機制的 notification_templates 模板
目前系統中有 5個模板 配置了智能建議機制(completion_strategy = 'suggested'),涵蓋庫存管理、訂單處理和客戶服務三個核心業務領域。
1. inventory_low_stock - 低庫存警告
- 分類: informational
- 智能建議觸發: 庫存補充時建議完成
- 觸發器支援: notify_inventory_events
- 標記為常用模板: ✅
- 使用場景: 當商品庫存低於安全值時發送警告,庫存補充後系統自動建議完成
typescript
// 使用範例
await createNotification('inventory_low_stock', {
product_name: '熱銷商品A',
current_stock: 5,
productId: 'prod-001'
})2. order_new - 新訂單通知
- 分類: actionable
- 智能建議觸發: 訂單狀態變更時建議完成
- 觸發器支援: notify_order_events
- 標記為常用模板: ✅
- 使用場景: 新訂單產生時通知相關人員,訂單進入處理狀態後建議完成
typescript
// 使用範例
await createNotification('order_new', {
order_number: 'ORD-2024-001',
total_amount: 1250.0,
orderId: 'ord-001'
})3. customer_service_new_request - 新客服請求
- 分類: actionable
- 智能建議觸發: 客服回覆時建議完成
- 觸發器支援: notify_customer_service_events
- 標記為常用模板: ✅
- 使用場景: 客戶提交新的服務請求時通知客服人員,首次回覆後建議完成
typescript
// 使用範例
await createNotification('customer_service_new_request', {
customer_name: '張先生',
customer_id: 'cust-001',
conversationId: 'conv-001'
})4. inventory_overstock - 庫存過多警告 (Phase 1 新增)
- 分類: informational
- 智能建議觸發: 庫存調整時建議完成
- 觸發器支援: notify_inventory_events
- 標記為常用模板: ❌
- 使用場景: 商品庫存超過預期上限時發出警告,庫存調整後建議完成
typescript
// 使用範例
await createNotification('inventory_overstock', {
product_name: '滯銷商品B',
current_stock: 500,
productId: 'prod-002'
})5. customer_service_overdue - 客服案件逾期 (Phase 1 新增)
- 分類: actionable
- 智能建議觸發: 案件回覆時建議完成
- 觸發器支援: notify_customer_service_events
- 標記為常用模板: ✅
- 使用場景: 客服案件超過預定處理時間時發出逾期警告,案件回覆後建議完成
typescript
// 使用範例
await createNotification('customer_service_overdue', {
ticket_id: 'TICKET-001',
overdue_hours: 24,
conversationId: 'conv-001'
})智能建議工作原理
智能建議系統透過以下四個步驟運作:
1. 自動偵測機制
- 系統持續監控相關實體的變更事件(庫存變更、訂單狀態、客服回覆等)
- 使用 PostgreSQL 觸發器即時捕獲資料變更
- 根據預定義規則判斷是否符合建議觸發條件
2. 條件判斷邏輯
sql
-- 範例:庫存補充觸發智能建議
UPDATE notifications
SET
suggested_complete = TRUE,
suggested_at = NOW(),
suggestion_reason = '庫存已補充至安全水位'
WHERE
type IN ('inventory_low_stock', 'inventory_overstock')
AND completion_strategy = 'suggested'
AND status NOT IN ('completed', 'archived', 'dismissed');3. 建議生成流程
- 觸發條件滿足時,設定
suggested_complete = TRUE - 記錄建議時間
suggested_at和建議原因suggestion_reason - 透過 Realtime 推送即時通知給使用者
- 在前端 UI 中顯示建議完成的視覺提示
4. 用戶確認機制
- 使用者可以選擇「接受建議」或「保持未完成」
- 接受建議時自動標記通知為完成狀態
- 拒絕建議時重置
suggested_complete = FALSE
PostgreSQL 觸發器函數
系統包含以下智能建議觸發器函數:
1. notify_inventory_events()
- 監控對象: products 表的庫存欄位變更
- 觸發條件: 庫存數量達到預設安全值或調整完成
- 影響模板: inventory_low_stock, inventory_overstock
2. notify_order_events()
- 監控對象: orders 表的狀態欄位變更
- 觸發條件: 訂單狀態從 'pending' 變更為 'processing' 或其他狀態
- 影響模板: order_new
3. notify_customer_service_events()
- 監控對象: conversations 表的回覆時間和狀態
- 觸發條件: 客服人員首次回覆或案件狀態變更
- 影響模板: customer_service_new_request, customer_service_overdue
實踐指南
配置新的智能建議模板
- 建立模板時設定完成策略:
sql
INSERT INTO notification_templates (
type, title_template, message_template,
category, completion_strategy, completion_notes
) VALUES (
'custom_smart_notification',
'智能通知標題',
'智能通知內容',
'actionable',
'suggested',
'特定條件滿足時自動建議完成'
);- 建立對應的觸發器函數:
sql
CREATE OR REPLACE FUNCTION notify_custom_events()
RETURNS TRIGGER AS $$
BEGIN
-- 判斷觸發條件
IF NEW.status = 'completed' AND OLD.status != 'completed' THEN
-- 更新相關通知為建議完成
UPDATE notifications
SET
suggested_complete = TRUE,
suggested_at = NOW(),
suggestion_reason = '相關任務已完成'
WHERE
type = 'custom_smart_notification'
AND completion_strategy = 'suggested'
AND status NOT IN ('completed', 'archived');
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;測試智能建議功能
typescript
// 1. 創建智能建議通知
const notification = await createNotification('inventory_low_stock', {
product_name: '測試商品',
current_stock: 3,
productId: 'test-001'
});
// 2. 模擬觸發條件(補充庫存)
await updateProductStock('test-001', 50);
// 3. 檢查是否產生智能建議
const updatedNotification = await getNotification(notification.id);
expect(updatedNotification.suggestedComplete).toBe(true);
// 4. 接受智能建議
await acceptCompletionSuggestion(notification.id);監控建議準確度
sql
-- 查詢智能建議的接受率
SELECT
type,
COUNT(*) as total_suggestions,
COUNT(CASE WHEN status = 'completed' THEN 1 END) as accepted_suggestions,
ROUND(
COUNT(CASE WHEN status = 'completed' THEN 1 END) * 100.0 / COUNT(*),
2
) as acceptance_rate
FROM notifications
WHERE suggested_complete = TRUE
AND suggested_at >= NOW() - INTERVAL '30 days'
GROUP BY type
ORDER BY acceptance_rate DESC;測試場景
typescript
// 1. 創建需要處理的任務型通知
await createNotification('customer_service_new_request', {
customer_name: '測試客戶',
request_type: 'refund'
})
// 2. 等待系統生成智能建議
// 3. 使用者可以接受或拒絕建議
await acceptCompletionSuggestion(notificationId)效能最佳化
快取策略
- 通知列表使用本地狀態快取
- 模板資料快取在 composable 中
- 統計資料定期更新
批量操作
typescript
// 批量標記為已讀
await bulkUpdateNotifications({
action: 'mark_as_read',
notificationIds: ['id1', 'id2', 'id3']
})
// 批量歸檔
await bulkUpdateNotifications({
action: 'archive',
notificationIds: selectedIds
})虛擬滾動
長列表自動啟用虛擬滾動,提升大量通知的渲染效能。
安全考量
權限控制
- 使用者只能查看自己的通知
- 群組通知需要相應角色權限
- 管理員可查看系統通知日誌
資料驗證
- 所有通知資料都經過型別驗證
- 模板參數安全過濾
- SQL 注入防護
測試指南
單元測試
bash
# 執行通知相關測試
npm run test -- src/components/notify
npm run test -- src/composables/useNotification整合測試
typescript
// 測試通知完整流程
describe('Notification System Integration', () => {
it('should create and display notification', async () => {
const notification = await createNotification('order_new', testData)
expect(notification.success).toBe(true)
const notifications = await loadNotifications()
expect(notifications.data).toContainEqual(
expect.objectContaining({ type: 'order_new' })
)
})
})故障排除
常見問題
通知沒有即時更新
- 檢查 Realtime 連線狀態
- 確認使用者 ID 正確
- 檢查 RLS 政策設定
圖示顯示異常
- 確認
notificationIconConfig.ts中有對應圖示 - 檢查 Vue 組件是否正確引入
- 確認通知類型拼寫正確
智能建議不工作
- 確認通知類型為
actionable - 檢查完成策略設定為
suggested - 查看後端智能建議生成日誌
除錯工具
typescript
// 開啟通知系統除錯模式
const { enableDebugMode } = useNotification(userId)
enableDebugMode(true)
// 查看 Realtime 連線狀態
console.log('Realtime connected:', isRealtimeConnected.value)
// 檢查通知統計
console.log('Notification stats:', stats.value)未來規劃
計劃功能
- [ ] 通知排程系統
- [ ] 多語言支援
- [ ] 通知統計分析
- [ ] 使用者通知偏好 AI 推薦
- [ ] 通知效果追蹤
效能改進
- [ ] 通知預載入機制
- [ ] 更智能的快取策略
- [ ] 離線通知同步
貢獻指南
如需對通知系統進行修改或新增功能,請遵循以下步驟:
- 閱讀現有程式碼和文件
- 在對應的測試檔案中新增測試案例
- 實施功能並確保所有測試通過
- 更新相關文件
- 提交 Pull Request
授權
本通知系統遵循 MIT 授權條款。