feat: 增加推送通知配置

This commit is contained in:
yml2213
2026-06-19 16:28:49 +08:00
parent a4cdc3e806
commit 5ff1ea40b0
15 changed files with 1376 additions and 51 deletions
+100
View File
@@ -0,0 +1,100 @@
package adminpush
import (
"encoding/json"
"time"
)
// ── 数据库模型 ──
type pushChannel struct {
ID uint64 `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:64;not null" json:"name"`
Type string `gorm:"size:32;not null" json:"type"`
Config json.RawMessage `gorm:"type:json;not null" json:"config"`
Enabled bool `gorm:"not null;default:true" json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (pushChannel) TableName() string { return "push_channels" }
type pushRule struct {
ID uint64 `gorm:"primaryKey" json:"id"`
Event string `gorm:"size:64;not null;uniqueIndex" json:"event"`
Enabled bool `gorm:"not null;default:true" json:"enabled"`
Threshold int `gorm:"not null;default:5" json:"threshold"`
MessageTemplate string `gorm:"size:255;not null;default:''" json:"message_template"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (pushRule) TableName() string { return "push_rules" }
// ── DTO ──
type ChannelDTO struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Config json.RawMessage `json:"config"`
Enabled bool `json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type RuleDTO struct {
ID uint64 `json:"id"`
Event string `json:"event"`
Enabled bool `json:"enabled"`
Threshold int `json:"threshold"`
MessageTemplate string `json:"message_template"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ── 请求 ──
type CreateChannelRequest struct {
Name string `json:"name" binding:"required"`
Type string `json:"type" binding:"required"`
Config json.RawMessage `json:"config" binding:"required"`
}
type UpdateChannelRequest struct {
Name *string `json:"name"`
Config *json.RawMessage `json:"config"`
Enabled *bool `json:"enabled"`
}
type UpdateRuleRequest struct {
Enabled *bool `json:"enabled"`
Threshold *int `json:"threshold"`
MessageTemplate *string `json:"message_template"`
}
// ── 转换 ──
func toChannelDTO(row pushChannel) ChannelDTO {
return ChannelDTO{
ID: row.ID,
Name: row.Name,
Type: row.Type,
Config: row.Config,
Enabled: row.Enabled,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
}
func toRuleDTO(row pushRule) RuleDTO {
return RuleDTO{
ID: row.ID,
Event: row.Event,
Enabled: row.Enabled,
Threshold: row.Threshold,
MessageTemplate: row.MessageTemplate,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
}
@@ -0,0 +1,169 @@
package adminpush
import (
"errors"
"strconv"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
// ── 渠道 ──
func (h *Handler) ListChannels(c *gin.Context) {
items, err := h.service.ListChannels(c.Request.Context())
if err != nil {
writePushError(c, err)
return
}
response.OK(c, gin.H{"items": items})
}
func (h *Handler) CreateChannel(c *gin.Context) {
if _, ok := currentAdminID(c); !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
var req CreateChannelRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "名称、类型和配置不能为空")
return
}
item, err := h.service.CreateChannel(c.Request.Context(), req)
if err != nil {
writePushError(c, err)
return
}
response.Created(c, item)
}
func (h *Handler) TestChannel(c *gin.Context) {
if _, ok := currentAdminID(c); !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
id, err := parseID(c)
if err != nil {
response.BadRequest(c, "ID 不正确")
return
}
if err := h.service.TestChannel(c.Request.Context(), id); err != nil {
writePushError(c, err)
return
}
response.OK(c, gin.H{"sent": true})
}
func (h *Handler) UpdateChannel(c *gin.Context) {
if _, ok := currentAdminID(c); !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
id, err := parseID(c)
if err != nil {
response.BadRequest(c, "ID 不正确")
return
}
var req UpdateChannelRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求格式不正确")
return
}
item, err := h.service.UpdateChannel(c.Request.Context(), id, req)
if err != nil {
writePushError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) DeleteChannel(c *gin.Context) {
if _, ok := currentAdminID(c); !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
id, err := parseID(c)
if err != nil {
response.BadRequest(c, "ID 不正确")
return
}
if err := h.service.DeleteChannel(c.Request.Context(), id); err != nil {
writePushError(c, err)
return
}
response.OK(c, gin.H{"deleted": true})
}
// ── 规则 ──
func (h *Handler) ListRules(c *gin.Context) {
items, err := h.service.ListRules(c.Request.Context())
if err != nil {
writePushError(c, err)
return
}
response.OK(c, gin.H{"items": items})
}
func (h *Handler) UpdateRule(c *gin.Context) {
if _, ok := currentAdminID(c); !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
id, err := parseID(c)
if err != nil {
response.BadRequest(c, "ID 不正确")
return
}
var req UpdateRuleRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "请求格式不正确")
return
}
item, err := h.service.UpdateRule(c.Request.Context(), id, req)
if err != nil {
writePushError(c, err)
return
}
response.OK(c, item)
}
// ── 辅助 ──
func parseID(c *gin.Context) (uint64, error) {
return strconv.ParseUint(c.Param("id"), 10, 64)
}
func currentAdminID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextAdminID)
if !ok {
return 0, false
}
adminID, ok := value.(uint64)
return adminID, ok
}
func writePushError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrDependencyUnavailable):
response.ServiceUnavailable(c, "数据库未连接")
case errors.Is(err, ErrChannelNotFound):
response.NotFound(c, "推送渠道不存在")
case errors.Is(err, ErrRuleNotFound):
response.NotFound(c, "推送规则不存在")
case errors.Is(err, ErrInvalidChannel):
response.BadRequest(c, "渠道类型或配置不正确")
default:
response.InternalServerError(c, "推送服务暂时不可用")
}
}
@@ -0,0 +1,164 @@
package adminpush
import (
"context"
"encoding/json"
"errors"
"gorm.io/gorm"
)
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
// ── 渠道 CRUD ──
func (r *Repository) ListChannels(ctx context.Context) ([]ChannelDTO, error) {
var rows []pushChannel
if err := r.db.WithContext(ctx).Order("id ASC").Find(&rows).Error; err != nil {
return nil, err
}
items := make([]ChannelDTO, 0, len(rows))
for _, row := range rows {
items = append(items, toChannelDTO(row))
}
return items, nil
}
func (r *Repository) CreateChannel(ctx context.Context, req CreateChannelRequest) (*ChannelDTO, error) {
cfgJSON, err := json.Marshal(req.Config)
if err != nil {
return nil, err
}
row := pushChannel{
Name: req.Name,
Type: req.Type,
Config: cfgJSON,
Enabled: true,
}
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
return nil, err
}
dto := toChannelDTO(row)
return &dto, nil
}
func (r *Repository) UpdateChannel(ctx context.Context, id uint64, req UpdateChannelRequest) (*ChannelDTO, error) {
var row pushChannel
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrChannelNotFound
}
return nil, err
}
if req.Name != nil {
row.Name = *req.Name
}
if req.Config != nil {
cfgJSON, err := json.Marshal(req.Config)
if err != nil {
return nil, err
}
row.Config = cfgJSON
}
if req.Enabled != nil {
row.Enabled = *req.Enabled
}
if err := r.db.WithContext(ctx).Save(&row).Error; err != nil {
return nil, err
}
dto := toChannelDTO(row)
return &dto, nil
}
func (r *Repository) DeleteChannel(ctx context.Context, id uint64) error {
result := r.db.WithContext(ctx).Delete(&pushChannel{}, id)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrChannelNotFound
}
return nil
}
// ── 规则 CRUD ──
func (r *Repository) ListRules(ctx context.Context) ([]RuleDTO, error) {
var rows []pushRule
if err := r.db.WithContext(ctx).Order("id ASC").Find(&rows).Error; err != nil {
return nil, err
}
items := make([]RuleDTO, 0, len(rows))
for _, row := range rows {
items = append(items, toRuleDTO(row))
}
return items, nil
}
func (r *Repository) UpdateRule(ctx context.Context, id uint64, req UpdateRuleRequest) (*RuleDTO, error) {
var row pushRule
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrRuleNotFound
}
return nil, err
}
if req.Enabled != nil {
row.Enabled = *req.Enabled
}
if req.Threshold != nil {
row.Threshold = *req.Threshold
}
if req.MessageTemplate != nil {
row.MessageTemplate = *req.MessageTemplate
}
if err := r.db.WithContext(ctx).Save(&row).Error; err != nil {
return nil, err
}
dto := toRuleDTO(row)
return &dto, nil
}
// ── 推送调用方使用 ──
func (r *Repository) GetChannel(ctx context.Context, id uint64) (*ChannelDTO, error) {
var row pushChannel
if err := r.db.WithContext(ctx).First(&row, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrChannelNotFound
}
return nil, err
}
dto := toChannelDTO(row)
return &dto, nil
}
func (r *Repository) GetActiveChannels(ctx context.Context) ([]ChannelDTO, error) {
var rows []pushChannel
if err := r.db.WithContext(ctx).Where("enabled = ?", true).Find(&rows).Error; err != nil {
return nil, err
}
items := make([]ChannelDTO, 0, len(rows))
for _, row := range rows {
items = append(items, toChannelDTO(row))
}
return items, nil
}
func (r *Repository) GetRule(ctx context.Context, event string) (*RuleDTO, error) {
var row pushRule
if err := r.db.WithContext(ctx).Where("event = ?", event).First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
dto := toRuleDTO(row)
return &dto, nil
}
@@ -0,0 +1,149 @@
package adminpush
import (
"context"
"encoding/json"
"errors"
"strings"
"hfb_sys/backend/internal/integrations/push"
)
var (
ErrDependencyUnavailable = errors.New("dependency unavailable")
ErrChannelNotFound = errors.New("push channel not found")
ErrRuleNotFound = errors.New("push rule not found")
ErrInvalidChannel = errors.New("invalid channel type or config")
)
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) ListChannels(ctx context.Context) ([]ChannelDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.ListChannels(ctx)
}
func (s *Service) CreateChannel(ctx context.Context, req CreateChannelRequest) (*ChannelDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if req.Name == "" || req.Type == "" {
return nil, ErrInvalidChannel
}
if err := validateChannelConfig(req.Type, req.Config); err != nil {
return nil, err
}
return s.repo.CreateChannel(ctx, req)
}
func (s *Service) UpdateChannel(ctx context.Context, id uint64, req UpdateChannelRequest) (*ChannelDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if req.Config != nil {
current, err := s.repo.GetChannel(ctx, id)
if err != nil {
return nil, err
}
if err := validateChannelConfig(current.Type, *req.Config); err != nil {
return nil, err
}
}
return s.repo.UpdateChannel(ctx, id, req)
}
func (s *Service) DeleteChannel(ctx context.Context, id uint64) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
return s.repo.DeleteChannel(ctx, id)
}
func (s *Service) ListRules(ctx context.Context) ([]RuleDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.ListRules(ctx)
}
func (s *Service) UpdateRule(ctx context.Context, id uint64, req UpdateRuleRequest) (*RuleDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if req.Threshold != nil && *req.Threshold < 1 {
return nil, ErrInvalidChannel
}
return s.repo.UpdateRule(ctx, id, req)
}
func (s *Service) TestChannel(ctx context.Context, id uint64) error {
if s.repo == nil {
return ErrDependencyUnavailable
}
ch, err := s.repo.GetChannel(ctx, id)
if err != nil {
return err
}
provider, err := buildProvider(ch.Type, ch.Config)
if err != nil {
return err
}
return provider.Send(ctx, push.Message{
Title: "推送测试",
Content: "这是一条测试消息,如果你收到了说明推送配置正确。",
})
}
func validateChannelConfig(channelType string, cfg json.RawMessage) error {
switch channelType {
case "bark":
var c struct {
DeviceKey string `json:"device_key"`
}
if err := json.Unmarshal(cfg, &c); err != nil || strings.TrimSpace(c.DeviceKey) == "" {
return ErrInvalidChannel
}
case "wpush":
var c struct {
APIKey string `json:"api_key"`
}
if err := json.Unmarshal(cfg, &c); err != nil || strings.TrimSpace(c.APIKey) == "" {
return ErrInvalidChannel
}
default:
return ErrInvalidChannel
}
return nil
}
func buildProvider(channelType string, cfg json.RawMessage) (push.Provider, error) {
switch channelType {
case "bark":
var c struct {
DeviceKey string `json:"device_key"`
Server string `json:"server"`
}
if err := json.Unmarshal(cfg, &c); err != nil {
return nil, err
}
return push.NewBarkProvider(push.BarkConfig{DeviceKey: c.DeviceKey, Server: c.Server})
case "wpush":
var c struct {
APIKey string `json:"api_key"`
}
if err := json.Unmarshal(cfg, &c); err != nil {
return nil, err
}
return push.NewWPushProvider(push.WPushConfig{APIKey: c.APIKey})
default:
return nil, errors.New("unknown channel type")
}
}
+124 -51
View File
@@ -1,12 +1,16 @@
package chat
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"hfb_sys/backend/internal/integrations/push"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/supportgroup"
)
@@ -120,10 +124,17 @@ func EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, preferr
}
// 7. 库存预警检查
// 站内信在事务内写入;外部推送在事务提交后发送,避免事务回滚时误发。
// 这里通过 goroutine 延迟 1 秒发送,给事务提交留出时间。
// 极端情况下事务回滚仍可能误发,但仅是通知层面的轻微不一致,可接受。
if qrcode != nil {
if err := checkQrCodeStockAndAlert(tx, &conversation); err != nil {
// 预警失败不阻塞建群,仅记录日志
// TODO: 添加日志
if alert, err := checkQrCodeStockAndAlert(tx, &conversation); err == nil && alert != nil {
go func(a pushAlert) {
time.Sleep(time.Second)
for _, p := range a.providers {
_ = p.Send(context.Background(), a.message)
}
}(*alert)
}
}
@@ -315,72 +326,134 @@ func markQrCodeAsUsed(tx *gorm.DB, qrcodeID uint64, conversationID uint64) error
}).Error
}
func checkQrCodeStockAndAlert(tx *gorm.DB, conversation *model.ChatConversation) error {
// 获取库存阈值
// pushAlert 事务提交后需要发送的外部推送。
type pushAlert struct {
providers []push.Provider
message push.Message
}
func checkQrCodeStockAndAlert(tx *gorm.DB, conversation *model.ChatConversation) (*pushAlert, error) {
// 从 push_rules 获取规则
threshold := int64(5)
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", "chat.qrcode_low_stock_threshold").First(&cfg).Error; err == nil && cfg.Value != "" {
// 尝试解析为数字
if val, err := parseThreshold(cfg.Value); err == nil {
threshold = val
ruleEnabled := true
messageTemplate := "企业微信群二维码库存不足(剩余 {{.Count}} 张),请及时补充"
var rule struct {
Enabled bool `gorm:"column:enabled"`
Threshold int `gorm:"column:threshold"`
MessageTemplate string `gorm:"column:message_template"`
}
if err := tx.Table("push_rules").Where("event = ?", "qrcode_low_stock").First(&rule).Error; err == nil {
ruleEnabled = rule.Enabled
threshold = int64(rule.Threshold)
if rule.MessageTemplate != "" {
messageTemplate = rule.MessageTemplate
}
}
if !ruleEnabled {
return nil, nil
}
// 统计未使用的二维码数量
var count int64
if err := tx.Model(&model.ChatQrCode{}).
Where("status = ?", QrCodeStatusUnused).
Where("expires_at IS NULL OR expires_at > ?", time.Now()).
Count(&count).Error; err != nil {
return err
return nil, err
}
// 如果低于阈值,发送预警给所有客服
if count <= threshold {
// 查询所有 cs 角色的客服
var csAdmins []model.AdminUser
if err := tx.Table("admin_users").
Joins("JOIN admin_user_roles ON admin_users.id = admin_user_roles.admin_user_id").
Joins("JOIN roles ON admin_user_roles.role_id = roles.id").
Where("roles.code = ? AND admin_users.status = ?", "cs", "active").
Select("admin_users.id").
Find(&csAdmins).Error; err != nil {
return err
if count > threshold {
return nil, nil
}
// 低于阈值:写入站内信(事务内)
var csAdmins []model.AdminUser
if err := tx.Table("admin_users").
Joins("JOIN admin_user_roles ON admin_users.id = admin_user_roles.admin_user_id").
Joins("JOIN roles ON admin_user_roles.role_id = roles.id").
Where("roles.code = ? AND admin_users.status = ?", "cs", "active").
Select("admin_users.id").
Find(&csAdmins).Error; err != nil {
return nil, err
}
alertContent := strings.ReplaceAll(messageTemplate, "{{.Count}}", fmt.Sprintf("%d", count))
entries := make([]map[string]interface{}, 0, len(csAdmins))
now := time.Now()
for _, admin := range csAdmins {
entries = append(entries, map[string]interface{}{
"admin_user_id": admin.ID,
"type": "system",
"title": "二维码库存预警",
"content": alertContent,
"is_read": false,
"created_at": now,
"updated_at": now,
})
}
if len(entries) > 0 {
if err := tx.Table("admin_notifications").Create(entries).Error; err != nil {
return nil, err
}
}
// 构造预警消息
alertContent := fmt.Sprintf("企业微信群二维码库存不足(剩余 %d 张),请及时补充", count)
// 返回外部推送数据,由调用方在事务提交后发送
providers := loadPushProviders(tx)
if len(providers) == 0 {
return nil, nil
}
return &pushAlert{
providers: providers,
message: push.Message{
Title: "二维码库存预警",
Content: alertContent,
},
}, nil
}
// 发送站内信给所有客服
entries := make([]map[string]interface{}, 0, len(csAdmins))
now := time.Now()
for _, admin := range csAdmins {
entries = append(entries, map[string]interface{}{
"admin_user_id": admin.ID,
"type": "system",
"title": "二维码库存预警",
"content": alertContent,
"is_read": false,
"created_at": now,
"updated_at": now,
// loadPushProviders 从 push_channels 表读取启用的渠道并创建 providers。
func loadPushProviders(tx *gorm.DB) []push.Provider {
var providers []push.Provider
var channels []struct {
Type string `gorm:"column:type"`
Config json.RawMessage `gorm:"column:config"`
}
if err := tx.Table("push_channels").Where("enabled = ?", true).Find(&channels).Error; err != nil {
return providers
}
for _, ch := range channels {
switch ch.Type {
case "bark":
var cfg struct {
DeviceKey string `json:"device_key"`
Server string `json:"server"`
}
if err := json.Unmarshal(ch.Config, &cfg); err != nil || cfg.DeviceKey == "" {
continue
}
bark, err := push.NewBarkProvider(push.BarkConfig{
DeviceKey: cfg.DeviceKey,
Server: cfg.Server,
})
}
if len(entries) > 0 {
// 批量插入管理员通知
if err := tx.Table("admin_notifications").Create(entries).Error; err != nil {
return err
if err == nil {
providers = append(providers, bark)
}
case "wpush":
var cfg struct {
APIKey string `json:"api_key"`
}
if err := json.Unmarshal(ch.Config, &cfg); err != nil || cfg.APIKey == "" {
continue
}
wpush, err := push.NewWPushProvider(push.WPushConfig{APIKey: cfg.APIKey})
if err == nil {
providers = append(providers, wpush)
}
}
}
return nil
}
func parseThreshold(value string) (int64, error) {
var threshold int64
if _, err := fmt.Sscanf(value, "%d", &threshold); err != nil {
return 0, err
}
return threshold, nil
return providers
}