feat: Phase 2e-1 统一通知中心 + 我的 TabBar 聚合未读红点
后端(notify 模块) - 新增 notify 模块:DAO/Service/Pusher 接口/Controller/Router/CleanupTask - 数据库 DDL:notify_notifications 表 + 3 索引(user+created/user+is_read/user+category) - 11 种 type 枚举(好友/群聊 9 种 + meeting_* 2 种预留)+ 4 种 category - 跨模块集成:contact 3 处 Pusher(friend_request/accepted/rejected) - 跨模块集成:group 6 处 Pusher(invite/join_request/approved/rejected/kicked/role_changed) - WS handler 断线补偿:连接建立即推送 notify.unread.total - 5 REST API(4 用户 + 1 管理员广播)+ 2 WS 事件(notify.new / notify.unread.total) - 30 天已读通知定时清理(未读永久保留) - Provider/Wire 依赖注入(NotifyPusher、NotifyConnectHook、UserInfoResolver 接口) 前端 - 新增 notify 模块:API/Pinia Store(5 分类分页缓存 + 未读数 + WS 事件)/NotifyItem/通知中心主页 - profile 入口:铃铛 badge + 菜单项 badge + 数字显示 - App.vue/login 初始化 notifyStore WS 监听;logout 调用 notifyStore.reset() 清缓存 - 清理 contact.js/group.js 中散落 toast 与冗余 notify.friend.request/group.join.request 处理 - CustomTabBar 新增 hasDot() 聚合指示器:我的 Tab 显示纯红点(无数字), 当前聚合 notifyStore.unreadTotal,未来可扩展「资料待完善/安全提醒/新版本」等 文档 - 新增 Phase 2e 整体路线图 docs/plans/2026-04-20-phase2e-design.md - 新增 Phase 2e-1 专用设计 docs/plans/2026-04-20-phase2e-1-design.md(§6.4 TabBar 聚合红点) - 新增 Phase 2e-1 实施计划 docs/plans/2026-04-20-phase2e-1-implementation.plan.md - 新增 E2E 验证报告 test-report-phase2e-1-notification.md(含 Playwright MCP 2 个现场 Bug 修复记录) - 更新 docs/progress/CURRENT_STATUS.md、docs/api/README.md、docs/api/frontend/notify.md - 更新 .cursor/rules/project-context.mdc、docs/plans/2026-02-27-echochat-system-design.md 其他 - .gitignore 排除 .playwright-mcp/ MCP 临时快照 架构决策 - 单端 WS 连接:沿用现有 ws.Hub,多端已读同步推迟到 Phase 2f/二期 - 跨模块依赖:contact/group → notify 严格单向(接口注入模式) - 降级策略:Pusher 先入库后推送;WS 失败不回滚入库;入库失败仅 Warn 不影响业务 Playwright MCP 回归(4 类场景全通) - 实时推送(admin 广播 → 1s 内前端自动插入 + 角标 +1) - Deep-link 跳转(好友申请通知 → contact/request 页) - 批量清零(全部已读按钮) - TabBar 聚合红点(有未读亮/全部已读灭)与 notifyStore.unreadTotal 三层同步 Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
// Package controller 提供 notify 模块的 HTTP 接口
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"github.com/echochat/backend/app/dto"
|
||||
"github.com/echochat/backend/app/notify/service"
|
||||
"github.com/echochat/backend/pkg/middleware"
|
||||
"github.com/echochat/backend/pkg/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// NotificationController 通知控制器(REST API)
|
||||
type NotificationController struct {
|
||||
notifyService *service.NotifyService
|
||||
}
|
||||
|
||||
// NewNotificationController 创建 NotificationController 实例
|
||||
func NewNotificationController(notifyService *service.NotifyService) *NotificationController {
|
||||
return &NotificationController{notifyService: notifyService}
|
||||
}
|
||||
|
||||
// GetList 获取通知列表
|
||||
// GET /api/v1/notifications?category=&is_read=&before_id=&limit=
|
||||
func (ctl *NotificationController) GetList(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.GetNotificationsRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "请求参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := ctl.notifyService.GetList(ctx, userID, &req)
|
||||
if err != nil {
|
||||
utils.ResponseError(c, "获取通知列表失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, resp)
|
||||
}
|
||||
|
||||
// GetUnreadCount 获取未读数(总数 + 按分类)
|
||||
// GET /api/v1/notifications/unread-count
|
||||
func (ctl *NotificationController) GetUnreadCount(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := ctl.notifyService.GetUnreadCount(ctx, userID)
|
||||
if err != nil {
|
||||
utils.ResponseError(c, "获取未读数失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, resp)
|
||||
}
|
||||
|
||||
// MarkRead 标记单条通知为已读
|
||||
// PUT /api/v1/notifications/:id/read
|
||||
func (ctl *NotificationController) MarkRead(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "通知 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.notifyService.MarkRead(ctx, userID, id); err != nil {
|
||||
if errors.Is(err, service.ErrNotificationNotFound) {
|
||||
utils.ResponseNotFound(c, err.Error())
|
||||
return
|
||||
}
|
||||
utils.ResponseError(c, "标记已读失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// MarkAllRead 一键清零未读
|
||||
// PUT /api/v1/notifications/read-all?category=
|
||||
func (ctl *NotificationController) MarkAllRead(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
category := c.Query("category")
|
||||
affected, err := ctl.notifyService.MarkAllRead(ctx, userID, category)
|
||||
if err != nil {
|
||||
utils.ResponseError(c, "批量标记已读失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, dto.MarkReadResponse{Affected: int(affected)})
|
||||
}
|
||||
|
||||
// Broadcast 管理员发起全员广播
|
||||
// POST /api/v1/admin/notifications/broadcast
|
||||
// 需要 admin/super_admin 角色,由路由层中间件保证
|
||||
func (ctl *NotificationController) Broadcast(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
operatorID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.BroadcastNotificationRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "请求参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
affected, err := ctl.notifyService.Broadcast(ctx, operatorID, &req)
|
||||
if err != nil {
|
||||
utils.ResponseError(c, "广播失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, dto.BroadcastNotificationResponse{Affected: affected})
|
||||
}
|
||||
200
backend/go-service/app/notify/dao/notification_dao.go
Normal file
200
backend/go-service/app/notify/dao/notification_dao.go
Normal file
@@ -0,0 +1,200 @@
|
||||
// Package dao 提供 notify 模块的数据库访问操作
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/app/constants"
|
||||
"github.com/echochat/backend/app/notify/model"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NotificationDAO 通知记录数据访问对象
|
||||
type NotificationDAO struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewNotificationDAO 创建 NotificationDAO 实例
|
||||
func NewNotificationDAO(db *gorm.DB) *NotificationDAO {
|
||||
return &NotificationDAO{db: db}
|
||||
}
|
||||
|
||||
// Create 新增一条通知(单用户)
|
||||
func (d *NotificationDAO) Create(ctx context.Context, n *model.Notification) error {
|
||||
funcName := "dao.notification_dao.Create"
|
||||
err := d.db.WithContext(ctx).Create(n).Error
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "写入通知失败",
|
||||
zap.Int64("user_id", n.UserID), zap.String("type", n.Type), zap.Error(err))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// BatchCreate 批量新增通知(管理员广播场景)
|
||||
// 使用 GORM 的 CreateInBatches 拆分为 500/批次,避免单次参数过多
|
||||
func (d *NotificationDAO) BatchCreate(ctx context.Context, list []*model.Notification) error {
|
||||
funcName := "dao.notification_dao.BatchCreate"
|
||||
if len(list) == 0 {
|
||||
return nil
|
||||
}
|
||||
err := d.db.WithContext(ctx).CreateInBatches(list, 500).Error
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "批量写入通知失败",
|
||||
zap.Int("count", len(list)), zap.Error(err))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// GetByID 根据 ID 获取单条通知
|
||||
func (d *NotificationDAO) GetByID(ctx context.Context, id int64) (*model.Notification, error) {
|
||||
var n model.Notification
|
||||
err := d.db.WithContext(ctx).First(&n, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &n, nil
|
||||
}
|
||||
|
||||
// ListRequest 列表查询条件
|
||||
type ListRequest struct {
|
||||
UserID int64 // 接收者用户 ID(必填)
|
||||
Types []string // type 过滤(空则不限)
|
||||
IsRead *bool // 已读状态过滤(nil 则不限)
|
||||
BeforeID int64 // 游标(小于此 ID 的记录),0 表示不限
|
||||
Limit int // 单页条数
|
||||
}
|
||||
|
||||
// List 按条件分页查询通知(按 ID DESC 返回)
|
||||
// 使用游标分页(id < beforeID)避免 OFFSET 随数据增长变慢
|
||||
func (d *NotificationDAO) List(ctx context.Context, req *ListRequest) ([]model.Notification, error) {
|
||||
funcName := "dao.notification_dao.List"
|
||||
q := d.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Where("user_id = ?", req.UserID)
|
||||
if len(req.Types) > 0 {
|
||||
q = q.Where("type IN ?", req.Types)
|
||||
}
|
||||
if req.IsRead != nil {
|
||||
q = q.Where("is_read = ?", *req.IsRead)
|
||||
}
|
||||
if req.BeforeID > 0 {
|
||||
q = q.Where("id < ?", req.BeforeID)
|
||||
}
|
||||
limit := req.Limit
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
if limit > 100 {
|
||||
limit = 100
|
||||
}
|
||||
var list []model.Notification
|
||||
err := q.Order("id DESC").Limit(limit).Find(&list).Error
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "查询通知列表失败",
|
||||
zap.Int64("user_id", req.UserID), zap.Error(err))
|
||||
}
|
||||
return list, err
|
||||
}
|
||||
|
||||
// CountUnread 统计未读总数
|
||||
func (d *NotificationDAO) CountUnread(ctx context.Context, userID int64) (int64, error) {
|
||||
var total int64
|
||||
err := d.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Where("user_id = ? AND is_read = false", userID).
|
||||
Count(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
// CountUnreadByType 按 type 统计未读数(用于按分类汇总)
|
||||
// 返回 type -> count
|
||||
func (d *NotificationDAO) CountUnreadByType(ctx context.Context, userID int64) (map[string]int64, error) {
|
||||
type row struct {
|
||||
Type string
|
||||
Cnt int64
|
||||
}
|
||||
var rows []row
|
||||
err := d.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Select("type, COUNT(*) as cnt").
|
||||
Where("user_id = ? AND is_read = false", userID).
|
||||
Group("type").
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(map[string]int64, len(rows))
|
||||
for _, r := range rows {
|
||||
result[r.Type] = r.Cnt
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// MarkRead 将指定通知标记为已读(仅限本人)
|
||||
// 返回受影响行数,0 表示无效 ID 或非本人
|
||||
func (d *NotificationDAO) MarkRead(ctx context.Context, id, userID int64) (int64, error) {
|
||||
funcName := "dao.notification_dao.MarkRead"
|
||||
now := time.Now()
|
||||
res := d.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Where("id = ? AND user_id = ? AND is_read = false", id, userID).
|
||||
Updates(map[string]interface{}{
|
||||
"is_read": true,
|
||||
"read_at": now,
|
||||
})
|
||||
if res.Error != nil {
|
||||
logs.Error(ctx, funcName, "标记已读失败",
|
||||
zap.Int64("id", id), zap.Int64("user_id", userID), zap.Error(res.Error))
|
||||
}
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
// MarkAllRead 将用户所有未读通知标记为已读
|
||||
// 可选按 types 过滤(为空则全部类型)
|
||||
func (d *NotificationDAO) MarkAllRead(ctx context.Context, userID int64, types []string) (int64, error) {
|
||||
funcName := "dao.notification_dao.MarkAllRead"
|
||||
now := time.Now()
|
||||
q := d.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Where("user_id = ? AND is_read = false", userID)
|
||||
if len(types) > 0 {
|
||||
q = q.Where("type IN ?", types)
|
||||
}
|
||||
res := q.Updates(map[string]interface{}{
|
||||
"is_read": true,
|
||||
"read_at": now,
|
||||
})
|
||||
if res.Error != nil {
|
||||
logs.Error(ctx, funcName, "批量标记已读失败",
|
||||
zap.Int64("user_id", userID), zap.Error(res.Error))
|
||||
}
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
// DeleteExpired 清理已读过期通知(保留时长由 constants.NotifyRetentionDays 决定)
|
||||
// 未读通知无论多久都不清理,避免用户漏看
|
||||
// 返回清理的行数
|
||||
func (d *NotificationDAO) DeleteExpired(ctx context.Context) (int64, error) {
|
||||
funcName := "dao.notification_dao.DeleteExpired"
|
||||
cutoff := time.Now().AddDate(0, 0, -constants.NotifyRetentionDays)
|
||||
res := d.db.WithContext(ctx).
|
||||
Where("is_read = true AND created_at < ?", cutoff).
|
||||
Delete(&model.Notification{})
|
||||
if res.Error != nil {
|
||||
logs.Error(ctx, funcName, "清理过期通知失败", zap.Error(res.Error))
|
||||
}
|
||||
return res.RowsAffected, res.Error
|
||||
}
|
||||
|
||||
// ListAllActiveUserIDs 查询系统中所有正常状态的用户 ID(用于管理员广播)
|
||||
// 此处直接查 auth_users 表,避免广播时循环依赖 user_dao
|
||||
func (d *NotificationDAO) ListAllActiveUserIDs(ctx context.Context) ([]int64, error) {
|
||||
funcName := "dao.notification_dao.ListAllActiveUserIDs"
|
||||
var ids []int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Table("auth_users").
|
||||
Where("status = ?", constants.UserStatusActive).
|
||||
Pluck("id", &ids).Error
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "查询全量用户 ID 失败", zap.Error(err))
|
||||
}
|
||||
return ids, err
|
||||
}
|
||||
29
backend/go-service/app/notify/model/notification.go
Normal file
29
backend/go-service/app/notify/model/notification.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// Package model 提供 notify 模块的数据库模型
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Notification 通知记录,对应 notify_notifications 表
|
||||
// 通知系统的核心持久化载体,覆盖好友 / 群聊 / 会议 / 系统广播四大类型
|
||||
// 每条通知对应单个接收者,不做跨用户共享
|
||||
type Notification struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"` // 通知唯一标识
|
||||
UserID int64 `json:"user_id" gorm:"not null;index:idx_notify_user_time,priority:1;index:idx_notify_user_unread,priority:1"` // 接收者用户 ID
|
||||
Type string `json:"type" gorm:"size:50;not null"` // 通知类型常量,见 constants.NotifyType*
|
||||
Title string `json:"title" gorm:"size:100;not null;default:''"` // 通知标题(前端列表主文案)
|
||||
Content string `json:"content" gorm:"size:500;not null;default:''"` // 通知副文案
|
||||
Extra *string `json:"extra" gorm:"type:jsonb"` // 扩展数据 JSON 字符串,保存类型相关的业务参数
|
||||
ActorID *int64 `json:"actor_id"` // 触发主体用户 ID(申请人/邀请人等),系统广播为 nil
|
||||
TargetType string `json:"target_type" gorm:"size:30;not null;default:''"` // 业务对象类型:user / group / meeting / system
|
||||
TargetID *int64 `json:"target_id"` // 业务对象 ID
|
||||
IsRead bool `json:"is_read" gorm:"not null;default:false"` // 是否已读:false=未读,true=已读
|
||||
ReadAt *time.Time `json:"read_at"` // 已读时间
|
||||
CreatedAt time.Time `json:"created_at" gorm:"not null;autoCreateTime;type:timestamp(0)"` // 通知生成时间
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (Notification) TableName() string {
|
||||
return "notify_notifications"
|
||||
}
|
||||
23
backend/go-service/app/notify/provider.go
Normal file
23
backend/go-service/app/notify/provider.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// Package notify 通知中心模块
|
||||
// 统一持久化好友 / 群聊 / 会议 / 系统广播四类通知,并通过 WS 实时推送
|
||||
package notify
|
||||
|
||||
import (
|
||||
"github.com/echochat/backend/app/notify/controller"
|
||||
"github.com/echochat/backend/app/notify/dao"
|
||||
"github.com/echochat/backend/app/notify/service"
|
||||
"github.com/echochat/backend/app/notify/task"
|
||||
"github.com/google/wire"
|
||||
)
|
||||
|
||||
// NotifySet 通知模块 Wire Provider Set
|
||||
// 对外暴露:
|
||||
// - *service.NotifyService —— 业务服务,同时实现 Pusher / ConnectHook 接口,供上游模块绑定注入
|
||||
// - *controller.NotificationController —— REST API 控制器
|
||||
// - *task.CleanupTask —— 过期通知清理定时任务
|
||||
var NotifySet = wire.NewSet(
|
||||
dao.NewNotificationDAO,
|
||||
service.NewNotifyService,
|
||||
controller.NewNotificationController,
|
||||
task.NewCleanupTask,
|
||||
)
|
||||
29
backend/go-service/app/notify/router.go
Normal file
29
backend/go-service/app/notify/router.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"github.com/echochat/backend/app/constants"
|
||||
"github.com/echochat/backend/app/notify/controller"
|
||||
"github.com/echochat/backend/pkg/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RegisterRoutes 注册 notify 模块的所有路由
|
||||
// 前台用户接口需 JWT,后台广播接口额外要求 admin/super_admin 角色
|
||||
func RegisterRoutes(r *gin.Engine, ctrl *controller.NotificationController, jwtAuth gin.HandlerFunc) {
|
||||
// 前台用户接口
|
||||
authed := r.Group("/api/v1")
|
||||
authed.Use(jwtAuth)
|
||||
{
|
||||
authed.GET("/notifications", ctrl.GetList)
|
||||
authed.GET("/notifications/unread-count", ctrl.GetUnreadCount)
|
||||
authed.PUT("/notifications/:id/read", ctrl.MarkRead)
|
||||
authed.PUT("/notifications/read-all", ctrl.MarkAllRead)
|
||||
}
|
||||
|
||||
// 管理端广播接口:JWT + admin/super_admin 角色
|
||||
adminGroup := r.Group("/api/v1/admin")
|
||||
adminGroup.Use(jwtAuth, middleware.RequireRole(constants.RoleAdmin, constants.RoleSuperAdmin))
|
||||
{
|
||||
adminGroup.POST("/notifications/broadcast", ctrl.Broadcast)
|
||||
}
|
||||
}
|
||||
420
backend/go-service/app/notify/service/notify_service.go
Normal file
420
backend/go-service/app/notify/service/notify_service.go
Normal file
@@ -0,0 +1,420 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
authModel "github.com/echochat/backend/app/auth/model"
|
||||
"github.com/echochat/backend/app/constants"
|
||||
"github.com/echochat/backend/app/dto"
|
||||
"github.com/echochat/backend/app/notify/dao"
|
||||
"github.com/echochat/backend/app/notify/model"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/echochat/backend/pkg/ws"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotificationNotFound = errors.New("通知不存在")
|
||||
)
|
||||
|
||||
// NotifyService 通知业务服务
|
||||
// 负责:
|
||||
// 1. 面向用户的列表 / 未读数 / 已读操作(REST API 层调用)
|
||||
// 2. 面向上游业务的 Pusher 接口实现(持久化 + WS 推送)
|
||||
// 3. 断线重连时的未读补偿推送
|
||||
type NotifyService struct {
|
||||
notifyDAO *dao.NotificationDAO
|
||||
pubsub *ws.PubSub
|
||||
userResolver UserInfoResolver
|
||||
}
|
||||
|
||||
// NewNotifyService 创建 NotifyService 实例
|
||||
func NewNotifyService(
|
||||
notifyDAO *dao.NotificationDAO,
|
||||
pubsub *ws.PubSub,
|
||||
userResolver UserInfoResolver,
|
||||
) *NotifyService {
|
||||
return &NotifyService{
|
||||
notifyDAO: notifyDAO,
|
||||
pubsub: pubsub,
|
||||
userResolver: userResolver,
|
||||
}
|
||||
}
|
||||
|
||||
// ====== 面向用户的查询与操作 ======
|
||||
|
||||
// GetList 分页查询通知列表
|
||||
func (s *NotifyService) GetList(ctx context.Context, userID int64, req *dto.GetNotificationsRequest) (*dto.NotificationListResponse, error) {
|
||||
funcName := "service.notify_service.GetList"
|
||||
|
||||
types := typesByCategory(req.Category)
|
||||
limit := req.Limit
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
if limit > 100 {
|
||||
limit = 100
|
||||
}
|
||||
|
||||
list, err := s.notifyDAO.List(ctx, &dao.ListRequest{
|
||||
UserID: userID,
|
||||
Types: types,
|
||||
IsRead: req.IsRead,
|
||||
BeforeID: req.BeforeID,
|
||||
Limit: limit + 1, // 多查一条判断是否还有下一页
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hasMore := false
|
||||
if len(list) > limit {
|
||||
hasMore = true
|
||||
list = list[:limit]
|
||||
}
|
||||
|
||||
items := s.toNotificationDTOs(ctx, list)
|
||||
logs.Debug(ctx, funcName, "查询通知列表",
|
||||
zap.Int64("user_id", userID), zap.Int("count", len(items)), zap.Bool("has_more", hasMore))
|
||||
|
||||
return &dto.NotificationListResponse{
|
||||
List: items,
|
||||
HasMore: hasMore,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetUnreadCount 查询未读数(总数 + 按分类)
|
||||
func (s *NotifyService) GetUnreadCount(ctx context.Context, userID int64) (*dto.UnreadCountResponse, error) {
|
||||
countMap, err := s.notifyDAO.CountUnreadByType(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
total := 0
|
||||
byCat := map[string]int{
|
||||
constants.NotifyCategoryFriend: 0,
|
||||
constants.NotifyCategoryGroup: 0,
|
||||
constants.NotifyCategoryMeeting: 0,
|
||||
constants.NotifyCategorySystem: 0,
|
||||
}
|
||||
for t, c := range countMap {
|
||||
total += int(c)
|
||||
byCat[constants.NotifyCategoryOfType(t)] += int(c)
|
||||
}
|
||||
return &dto.UnreadCountResponse{
|
||||
Total: total,
|
||||
ByCategory: byCat,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MarkRead 标记单条通知为已读
|
||||
func (s *NotifyService) MarkRead(ctx context.Context, userID, id int64) error {
|
||||
affected, err := s.notifyDAO.MarkRead(ctx, id, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotificationNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotificationNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkAllRead 将用户某分类(或全部)通知标记为已读
|
||||
// category 为空或 all 时清空全部未读
|
||||
func (s *NotifyService) MarkAllRead(ctx context.Context, userID int64, category string) (int64, error) {
|
||||
types := typesByCategory(category)
|
||||
return s.notifyDAO.MarkAllRead(ctx, userID, types)
|
||||
}
|
||||
|
||||
// PushUnreadTotalOnConnect 向刚建立连接的用户推送未读总数补偿
|
||||
// 由 WS handler 的 OnConnected 钩子调用(通过 NotifyConnectHook 接口适配)
|
||||
func (s *NotifyService) PushUnreadTotalOnConnect(ctx context.Context, userID int64) {
|
||||
funcName := "service.notify_service.PushUnreadTotalOnConnect"
|
||||
resp, err := s.GetUnreadCount(ctx, userID)
|
||||
if err != nil {
|
||||
logs.Warn(ctx, funcName, "查询未读数失败", zap.Int64("user_id", userID), zap.Error(err))
|
||||
return
|
||||
}
|
||||
if resp.Total == 0 {
|
||||
return
|
||||
}
|
||||
s.publishWS(ctx, userID, constants.WSEventNotifyUnreadTotal, map[string]interface{}{
|
||||
"total": resp.Total,
|
||||
"by_category": resp.ByCategory,
|
||||
})
|
||||
}
|
||||
|
||||
// ====== Pusher 接口实现 ======
|
||||
|
||||
// Push 写入通知并推送 WS(单用户)
|
||||
// 实现策略:
|
||||
// 1. 同步入库(保证持久化)
|
||||
// 2. 异步 WS 推送(避免阻塞上游业务事务)
|
||||
// 3. 任一步失败不回滚另一步,全部仅记录 Warn 日志
|
||||
func (s *NotifyService) Push(ctx context.Context, payload *PushPayload) {
|
||||
funcName := "service.notify_service.Push"
|
||||
if payload == nil || payload.UserID <= 0 || payload.Type == "" {
|
||||
logs.Warn(ctx, funcName, "无效的推送载荷", zap.Any("payload", payload))
|
||||
return
|
||||
}
|
||||
|
||||
n := s.buildModel(payload)
|
||||
if err := s.notifyDAO.Create(ctx, n); err != nil {
|
||||
logs.Warn(ctx, funcName, "通知入库失败,放弃 WS 推送",
|
||||
zap.Int64("user_id", payload.UserID), zap.String("type", payload.Type), zap.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
go s.safePushWS(n, payload)
|
||||
}
|
||||
|
||||
// PushBatch 批量写入通知并推送 WS
|
||||
// 适用于管理员广播 / 群操作批量通知场景
|
||||
// 优化:一次 BatchCreate 入库,然后分别 WS 推送
|
||||
func (s *NotifyService) PushBatch(ctx context.Context, payloads []*PushPayload) {
|
||||
funcName := "service.notify_service.PushBatch"
|
||||
if len(payloads) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
models := make([]*model.Notification, 0, len(payloads))
|
||||
valid := make([]*PushPayload, 0, len(payloads))
|
||||
for _, p := range payloads {
|
||||
if p == nil || p.UserID <= 0 || p.Type == "" {
|
||||
continue
|
||||
}
|
||||
models = append(models, s.buildModel(p))
|
||||
valid = append(valid, p)
|
||||
}
|
||||
|
||||
if err := s.notifyDAO.BatchCreate(ctx, models); err != nil {
|
||||
logs.Warn(ctx, funcName, "通知批量入库失败,放弃 WS 推送",
|
||||
zap.Int("count", len(models)), zap.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
// 入库成功后逐条异步推送
|
||||
for i, n := range models {
|
||||
go s.safePushWS(n, valid[i])
|
||||
}
|
||||
}
|
||||
|
||||
// ====== 内部辅助 ======
|
||||
|
||||
// buildModel 由 PushPayload 构造 Notification 持久化模型
|
||||
// 空 Title 使用类型默认文案;空 TargetType 按业务类型映射为默认值
|
||||
func (s *NotifyService) buildModel(p *PushPayload) *model.Notification {
|
||||
title := p.Title
|
||||
if title == "" {
|
||||
if zh, ok := constants.NotifyTypeMap[p.Type]; ok {
|
||||
title = zh
|
||||
}
|
||||
}
|
||||
targetType := p.TargetType
|
||||
if targetType == "" {
|
||||
targetType = defaultTargetType(p.Type)
|
||||
}
|
||||
return &model.Notification{
|
||||
UserID: p.UserID,
|
||||
Type: p.Type,
|
||||
Title: title,
|
||||
Content: p.Content,
|
||||
Extra: marshalExtra(p.Extra),
|
||||
ActorID: p.ActorID,
|
||||
TargetType: targetType,
|
||||
TargetID: p.TargetID,
|
||||
IsRead: false,
|
||||
}
|
||||
}
|
||||
|
||||
// safePushWS 序列化并通过 Redis Pub/Sub 推送 notify.new 事件
|
||||
// 失败仅记录 Warn,不影响持久化的通知记录
|
||||
func (s *NotifyService) safePushWS(n *model.Notification, p *PushPayload) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logs.Warn(context.Background(), "service.notify_service.safePushWS",
|
||||
"推送协程 panic", zap.Any("panic", r))
|
||||
}
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dtoItem := s.toNotificationDTO(ctx, n)
|
||||
s.publishWS(ctx, n.UserID, constants.WSEventNotifyNew, dtoItem)
|
||||
}
|
||||
|
||||
// publishWS 序列化推送消息并发布到用户频道
|
||||
func (s *NotifyService) publishWS(ctx context.Context, userID int64, event string, data interface{}) {
|
||||
if s.pubsub == nil {
|
||||
return
|
||||
}
|
||||
push := ws.NewPushMessage(event, data)
|
||||
bytes, err := ws.MarshalPush(push)
|
||||
if err != nil {
|
||||
logs.Warn(ctx, "service.notify_service.publishWS", "序列化推送失败",
|
||||
zap.String("event", event), zap.Error(err))
|
||||
return
|
||||
}
|
||||
if err := s.pubsub.Publish(ctx, userID, bytes); err != nil {
|
||||
logs.Warn(ctx, "service.notify_service.publishWS", "WS 推送失败",
|
||||
zap.Int64("user_id", userID), zap.String("event", event), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// toNotificationDTO 将 model 转为对外 DTO,补全 actor 信息
|
||||
func (s *NotifyService) toNotificationDTO(ctx context.Context, n *model.Notification) dto.NotificationDTO {
|
||||
item := dto.NotificationDTO{
|
||||
ID: n.ID,
|
||||
Type: n.Type,
|
||||
Category: constants.NotifyCategoryOfType(n.Type),
|
||||
Title: n.Title,
|
||||
Content: n.Content,
|
||||
Extra: n.Extra,
|
||||
ActorID: n.ActorID,
|
||||
TargetType: n.TargetType,
|
||||
TargetID: n.TargetID,
|
||||
IsRead: n.IsRead,
|
||||
CreatedAt: n.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if n.ReadAt != nil {
|
||||
item.ReadAt = n.ReadAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
if n.ActorID != nil && *n.ActorID > 0 && s.userResolver != nil {
|
||||
users, err := s.userResolver.GetUsersByIDs(ctx, []int64{*n.ActorID})
|
||||
if err == nil && len(users) > 0 {
|
||||
item.ActorName = users[0].Nickname
|
||||
item.ActorAvatar = users[0].Avatar
|
||||
}
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
// toNotificationDTOs 批量转换 DTO 并一次性补全 actor 信息,避免 N+1 查询
|
||||
func (s *NotifyService) toNotificationDTOs(ctx context.Context, list []model.Notification) []dto.NotificationDTO {
|
||||
items := make([]dto.NotificationDTO, 0, len(list))
|
||||
if len(list) == 0 {
|
||||
return items
|
||||
}
|
||||
|
||||
actorSet := make(map[int64]struct{})
|
||||
for i := range list {
|
||||
if list[i].ActorID != nil && *list[i].ActorID > 0 {
|
||||
actorSet[*list[i].ActorID] = struct{}{}
|
||||
}
|
||||
}
|
||||
userMap := make(map[int64]*authModel.User)
|
||||
if len(actorSet) > 0 && s.userResolver != nil {
|
||||
ids := make([]int64, 0, len(actorSet))
|
||||
for id := range actorSet {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
users, err := s.userResolver.GetUsersByIDs(ctx, ids)
|
||||
if err == nil {
|
||||
for i := range users {
|
||||
userMap[users[i].ID] = &users[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for i := range list {
|
||||
n := &list[i]
|
||||
item := dto.NotificationDTO{
|
||||
ID: n.ID,
|
||||
Type: n.Type,
|
||||
Category: constants.NotifyCategoryOfType(n.Type),
|
||||
Title: n.Title,
|
||||
Content: n.Content,
|
||||
Extra: n.Extra,
|
||||
ActorID: n.ActorID,
|
||||
TargetType: n.TargetType,
|
||||
TargetID: n.TargetID,
|
||||
IsRead: n.IsRead,
|
||||
CreatedAt: n.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if n.ReadAt != nil {
|
||||
item.ReadAt = n.ReadAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
if n.ActorID != nil {
|
||||
if u, ok := userMap[*n.ActorID]; ok {
|
||||
item.ActorName = u.Nickname
|
||||
item.ActorAvatar = u.Avatar
|
||||
}
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// typesByCategory 把前端的 category 参数转换为 type 列表
|
||||
// all 或空字符串返回 nil(不按类型过滤)
|
||||
func typesByCategory(category string) []string {
|
||||
if category == "" || category == constants.NotifyCategoryAll {
|
||||
return nil
|
||||
}
|
||||
if list, ok := constants.NotifyTypesByCategory[category]; ok {
|
||||
return list
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// defaultTargetType 根据通知类型推导默认业务对象类型
|
||||
// 用于 PushPayload.TargetType 为空时的兜底
|
||||
func defaultTargetType(notifyType string) string {
|
||||
switch constants.NotifyCategoryOfType(notifyType) {
|
||||
case constants.NotifyCategoryFriend:
|
||||
return constants.NotifyTargetUser
|
||||
case constants.NotifyCategoryGroup:
|
||||
return constants.NotifyTargetGroup
|
||||
case constants.NotifyCategoryMeeting:
|
||||
return constants.NotifyTargetMeeting
|
||||
default:
|
||||
return constants.NotifyTargetSystem
|
||||
}
|
||||
}
|
||||
|
||||
// ====== 管理员广播 ======
|
||||
|
||||
// Broadcast 向所有正常用户发送系统公告
|
||||
// 查询活跃用户 ID → 构造 payload → 批量入库 + 推送
|
||||
// 返回受影响用户数
|
||||
func (s *NotifyService) Broadcast(ctx context.Context, operatorID int64, req *dto.BroadcastNotificationRequest) (int, error) {
|
||||
funcName := "service.notify_service.Broadcast"
|
||||
logs.Info(ctx, funcName, "管理员广播",
|
||||
zap.Int64("operator_id", operatorID), zap.String("title", req.Title))
|
||||
|
||||
userIDs, err := s.notifyDAO.ListAllActiveUserIDs(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(userIDs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
targetType := req.TargetType
|
||||
if targetType == "" {
|
||||
targetType = constants.NotifyTargetSystem
|
||||
}
|
||||
|
||||
payloads := make([]*PushPayload, 0, len(userIDs))
|
||||
for _, uid := range userIDs {
|
||||
payloads = append(payloads, &PushPayload{
|
||||
UserID: uid,
|
||||
Type: constants.NotifyTypeSystemBroadcast,
|
||||
Title: req.Title,
|
||||
Content: req.Content,
|
||||
ActorID: &operatorID,
|
||||
TargetType: targetType,
|
||||
TargetID: req.TargetID,
|
||||
Extra: req.Extra,
|
||||
})
|
||||
}
|
||||
s.PushBatch(ctx, payloads)
|
||||
return len(payloads), nil
|
||||
}
|
||||
66
backend/go-service/app/notify/service/pusher.go
Normal file
66
backend/go-service/app/notify/service/pusher.go
Normal file
@@ -0,0 +1,66 @@
|
||||
// Package service 提供 notify 模块的业务逻辑
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
authModel "github.com/echochat/backend/app/auth/model"
|
||||
)
|
||||
|
||||
// PushPayload 跨模块推送通知的统一入参
|
||||
// 由上游业务模块(contact/group/admin/meeting)构造并传递给 Pusher
|
||||
type PushPayload struct {
|
||||
UserID int64 // 接收者用户 ID(必填)
|
||||
Type string // 通知类型常量,见 constants.NotifyType*
|
||||
Title string // 通知标题(可选,为空时使用类型默认文案)
|
||||
Content string // 通知副文案
|
||||
ActorID *int64 // 触发主体用户 ID(申请人/邀请人等),系统广播为 nil
|
||||
TargetType string // 业务对象类型:user / group / meeting / system
|
||||
TargetID *int64 // 业务对象 ID
|
||||
Extra interface{} // 扩展数据,内部会序列化为 JSON 字符串存入 extra 列
|
||||
}
|
||||
|
||||
// Pusher 通知推送接口
|
||||
// 由 notify 模块实现,供 contact / group / admin / meeting 等上游模块注入调用
|
||||
// 实现原则:
|
||||
// 1. 入库 + WS 推送 双动作,WS 推送失败不回滚入库(降级策略)
|
||||
// 2. 同步调用可能阻塞业务,实现内部使用 goroutine 异步处理
|
||||
// 3. 一个 PushPayload 对应单个接收者;批量场景请多次调用
|
||||
type Pusher interface {
|
||||
Push(ctx context.Context, payload *PushPayload)
|
||||
PushBatch(ctx context.Context, payloads []*PushPayload)
|
||||
}
|
||||
|
||||
// UserInfoResolver 查询用户昵称 / 头像的接口,用于补全通知中的 actor 信息
|
||||
// 由 contact.FriendshipDAO 隐式实现(已有 GetUsersByIDs 方法)
|
||||
type UserInfoResolver interface {
|
||||
GetUsersByIDs(ctx context.Context, userIDs []int64) ([]authModel.User, error)
|
||||
}
|
||||
|
||||
// marshalExtra 将 Extra 字段序列化为 JSON 字符串,供 DAO 写入 jsonb 列
|
||||
// 空值返回 nil;若调用方已传入合法 JSON 字符串(string 或 *string),直接透传;其余类型走 json.Marshal
|
||||
func marshalExtra(extra interface{}) *string {
|
||||
if extra == nil {
|
||||
return nil
|
||||
}
|
||||
switch v := extra.(type) {
|
||||
case string:
|
||||
if v == "" {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
case *string:
|
||||
if v == nil || *v == "" {
|
||||
return nil
|
||||
}
|
||||
cp := *v
|
||||
return &cp
|
||||
}
|
||||
bytes, err := json.Marshal(extra)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
s := string(bytes)
|
||||
return &s
|
||||
}
|
||||
83
backend/go-service/app/notify/task/cleanup_task.go
Normal file
83
backend/go-service/app/notify/task/cleanup_task.go
Normal file
@@ -0,0 +1,83 @@
|
||||
// Package task 提供 notify 模块的后台定时任务
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/app/notify/dao"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// 默认每日凌晨 3 点执行一次,通过固定周期 24h 近似实现
|
||||
// 如需精确到凌晨可在未来引入 robfig/cron 库替换 Ticker
|
||||
const defaultInterval = 24 * time.Hour
|
||||
|
||||
// CleanupTask 过期通知清理任务
|
||||
// 周期扫描 notify_notifications,删除已读且超过 constants.NotifyRetentionDays 天的记录
|
||||
// 未读通知无论多久都不清理
|
||||
type CleanupTask struct {
|
||||
notifyDAO *dao.NotificationDAO
|
||||
interval time.Duration
|
||||
stopCh chan struct{}
|
||||
}
|
||||
|
||||
// NewCleanupTask 创建 CleanupTask 实例
|
||||
// 默认周期 24 小时
|
||||
func NewCleanupTask(notifyDAO *dao.NotificationDAO) *CleanupTask {
|
||||
return &CleanupTask{
|
||||
notifyDAO: notifyDAO,
|
||||
interval: defaultInterval,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Start 启动定时任务(非阻塞)
|
||||
// 应在 main 进程启动后调用,进程退出时调用 Stop 释放 goroutine
|
||||
func (t *CleanupTask) Start() {
|
||||
funcName := "task.cleanup_task.Start"
|
||||
logs.Info(nil, funcName, "启动通知清理任务", zap.Duration("interval", t.interval))
|
||||
|
||||
go func() {
|
||||
// 启动时延迟 30s 再执行,避免与启动迁移 / 初始化竞争资源
|
||||
warmup := time.NewTimer(30 * time.Second)
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
warmup.Stop()
|
||||
return
|
||||
case <-warmup.C:
|
||||
}
|
||||
t.runOnce()
|
||||
|
||||
ticker := time.NewTicker(t.interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
t.runOnce()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop 停止定时任务
|
||||
func (t *CleanupTask) Stop() {
|
||||
close(t.stopCh)
|
||||
}
|
||||
|
||||
// runOnce 执行一次清理,带独立超时控制
|
||||
func (t *CleanupTask) runOnce() {
|
||||
funcName := "task.cleanup_task.runOnce"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
affected, err := t.notifyDAO.DeleteExpired(ctx)
|
||||
if err != nil {
|
||||
logs.Warn(ctx, funcName, "通知清理失败", zap.Error(err))
|
||||
return
|
||||
}
|
||||
logs.Info(ctx, funcName, "通知清理完成", zap.Int64("deleted", affected))
|
||||
}
|
||||
Reference in New Issue
Block a user