74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
"time"
|
||
|
||
"silk-server-go/internal/middleware"
|
||
"silk-server-go/internal/model"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
// RegisterNotificationRoutes 注册通知路由
|
||
func RegisterNotificationRoutes(rg *gin.RouterGroup, db *gorm.DB) {
|
||
readPerm := middleware.RequirePermission(db, "alarm:read")
|
||
rg.GET("/notifications", readPerm, listNotifications(db))
|
||
rg.POST("/notifications", readPerm, createNotification(db))
|
||
}
|
||
|
||
// listNotifications 通知列表(上限200)
|
||
func listNotifications(db *gorm.DB) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
var list []model.Notification
|
||
q := db.Order("created_at DESC").Limit(200)
|
||
if !hasGlobalAccess(c) {
|
||
if userID := currentUserID(c); userID != nil {
|
||
q = q.Where("user_id = ?", *userID)
|
||
} else {
|
||
q = q.Where("1 = 0")
|
||
}
|
||
}
|
||
q.Find(&list)
|
||
c.JSON(http.StatusOK, list)
|
||
}
|
||
}
|
||
|
||
// createNotification 手动发通知
|
||
func createNotification(db *gorm.DB) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
var body struct {
|
||
Channel string `json:"channel"`
|
||
Target string `json:"target"`
|
||
Title string `json:"title"`
|
||
Body string `json:"body"`
|
||
}
|
||
if err := c.ShouldBindJSON(&body); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
|
||
ntf := model.Notification{
|
||
UserID: currentUserID(c),
|
||
Channel: body.Channel,
|
||
Target: body.Target,
|
||
Title: body.Title,
|
||
Body: body.Body,
|
||
Status: "sent",
|
||
NextAttemptAt: time.Now(),
|
||
}
|
||
if ntf.Channel == "" {
|
||
ntf.Channel = "manual"
|
||
}
|
||
if ntf.Target == "" {
|
||
ntf.Target = "all"
|
||
}
|
||
if err := db.Create(&ntf).Error; err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建通知失败"})
|
||
return
|
||
}
|
||
c.JSON(http.StatusCreated, ntf)
|
||
}
|
||
}
|