Files
break 333ba4b647
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m23s
feat(H5弹窗): AUG26-007 风险换卡与运营弹窗投放通知
新增 000225 迁移:运营弹窗配置表 tb_h5_popup_configuration(页面/范围/优先级/频率/受控动作/启停/有效期/版本)
与 tb_notification 可空 JSONB 列 popup_snapshot。

新增通知直建窄接口 DirectWriter.CreateOrGetPersonal:与 Outbox 消费共用 prepareDelivery 的渲染、
展示期与 CreateIdempotent 规则,冲突时回查返回既有行;同步扩展个人通知查询与已读两处类型白名单,
并按个人客户入口补齐投递审计来源。

新增 H5 候选与风险换卡:GET /api/c/v1/popup-candidates 先判风险资格(广电卡 + 风险停机 +
无活动物流换货单),命中只返回风险候选;未命中再按时间/启停/页面/店铺/设备类型/卡类型范围/频率
匹配运营配置。POST /api/c/v1/risk-exchanges/:asset_id/address 锁资产行后幂等创建待发货物流换货单,
首次地址锁定,不沿用资产级群发通知。

新增后台运营弹窗配置 CRUD 与启停(仅超级管理员与平台账号),更新递增版本并刷新最近更新时间,
标题与正文统一拒绝 URL 与前端路由,全部写操作记录操作者、前后值、版本与时间。

同步 OpenAPI(cmd/gendocs、cmd/api/docs.go、pkg/openapi/handlers.go)与参数校验中文提示共用实现。
2026-09-15 15:23:52 +08:00

240 lines
9.1 KiB
Go

// Package notification 提供当前接收人的 PostgreSQL 站内通知读取投影。
package notification
import (
"context"
"strconv"
"strings"
"time"
"gorm.io/gorm"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
)
// Query 提供后台账号未读数和基础列表查询。
type Query struct {
db *gorm.DB
now func() time.Time
}
// NewQuery 创建后台通知查询。
func NewQuery(db *gorm.DB) *Query {
return &Query{db: db, now: time.Now}
}
// UnreadCount 从 PostgreSQL 查询当前后台账号的准确未读数。
func (q *Query) UnreadCount(ctx context.Context, recipientID uint) (*dto.NotificationUnreadCountResponse, error) {
if recipientID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
var count int64
now := q.now().UTC()
err := q.db.WithContext(ctx).Model(&model.Notification{}).
Where("recipient_kind = ? AND recipient_id = ? AND is_read = ? AND (expires_at IS NULL OR expires_at > ?)",
constants.NotificationRecipientKindAccount, recipientID, false, now).
Count(&count).Error
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知未读数失败")
}
return newUnreadCountResponse(count), nil
}
// List 按创建时间和 ID 倒序查询当前后台账号的未过期通知。
func (q *Query) List(ctx context.Context, recipientID uint, request dto.NotificationListRequest) (*dto.NotificationListResponse, error) {
if recipientID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
page, pageSize, offset, err := normalizeNotificationPagination(request.Page, request.PageSize)
if err != nil {
return nil, err
}
if !isNotificationCategory(request.Category) || !isNotificationSeverity(request.Severity) || len(request.Type) > 100 || strings.TrimSpace(request.Type) != request.Type {
return nil, errors.New(errors.CodeInvalidParam)
}
now := q.now().UTC()
base := q.db.WithContext(ctx).Model(&model.Notification{}).
Where("recipient_kind = ? AND recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)",
constants.NotificationRecipientKindAccount, recipientID, now)
if request.Category != "" {
base = base.Where("category = ?", request.Category)
}
if request.Type != "" {
base = base.Where("type = ?", request.Type)
}
if request.Severity != "" {
base = base.Where("severity = ?", request.Severity)
}
if request.IsRead != nil {
base = base.Where("is_read = ?", *request.IsRead)
}
var total int64
if err := base.Count(&total).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知总数失败")
}
var records []model.Notification
if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&records).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知列表失败")
}
return &dto.NotificationListResponse{
Items: notificationItems(records), Total: total, Page: page, Size: pageSize,
}, nil
}
// PersonalUnreadCount 查询当前个人客户可见业务通知的准确未读数。
func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.NotificationUnreadCountResponse, error) {
if customerID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
var count int64
err := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC()).
Where("is_read = ?", false).
Count(&count).Error
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知未读数失败")
}
return newUnreadCountResponse(count), nil
}
// PersonalList 查询当前个人客户可见的未过期业务通知简化列表。
func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.PersonalNotificationListRequest) (*dto.PersonalNotificationListResponse, error) {
if customerID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
page, pageSize, offset, err := normalizeNotificationPagination(request.Page, request.PageSize)
if err != nil {
return nil, err
}
base := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC())
if request.IsRead != nil {
base = base.Where("is_read = ?", *request.IsRead)
}
var total int64
if err := base.Count(&total).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知总数失败")
}
var records []model.Notification
if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&records).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知列表失败")
}
return &dto.PersonalNotificationListResponse{
Items: notificationItems(records), Total: total, Page: page, Size: pageSize,
}, nil
}
// UnreadSummary 使用单条 PostgreSQL 查询返回当前后台账号的固定分类汇总。
func (q *Query) UnreadSummary(ctx context.Context, recipientID uint) (*dto.NotificationUnreadSummaryResponse, error) {
if recipientID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
var summary dto.NotificationUnreadSummaryResponse
err := q.db.WithContext(ctx).Model(&model.Notification{}).
Select(`COUNT(*) AS total,
COUNT(*) FILTER (WHERE category = ?) AS approval,
COUNT(*) FILTER (WHERE category = ?) AS expiry,
COUNT(*) FILTER (WHERE category = ?) AS sync,
COUNT(*) FILTER (WHERE category = ?) AS system`,
constants.NotificationCategoryApproval,
constants.NotificationCategoryExpiry,
constants.NotificationCategorySync,
constants.NotificationCategorySystem).
Where("recipient_kind = ? AND recipient_id = ? AND is_read = ? AND (expires_at IS NULL OR expires_at > ?)",
constants.NotificationRecipientKindAccount, recipientID, false, q.now().UTC()).
Scan(&summary).Error
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知未读汇总失败")
}
return &summary, nil
}
func isNotificationCategory(category string) bool {
switch category {
case "", constants.NotificationCategoryApproval, constants.NotificationCategoryExpiry,
constants.NotificationCategorySync, constants.NotificationCategorySystem:
return true
default:
return false
}
}
func isNotificationSeverity(severity string) bool {
switch severity {
case "", constants.NotificationSeverityInfo, constants.NotificationSeverityWarning,
constants.NotificationSeverityError, constants.NotificationSeverityCritical:
return true
default:
return false
}
}
func normalizeNotificationPagination(page, pageSize int) (int, int, int, error) {
if page <= 0 {
page = 1
}
if page > constants.NotificationMaxPage {
return 0, 0, 0, errors.New(errors.CodeInvalidParam)
}
if pageSize <= 0 {
pageSize = constants.NotificationDefaultPageSize
}
if pageSize > constants.NotificationMaxPageSize {
return 0, 0, 0, errors.New(errors.CodeInvalidParam)
}
return page, pageSize, (page - 1) * pageSize, nil
}
func personalNotificationScope(db *gorm.DB, customerID uint, now time.Time) *gorm.DB {
return db.Where(`recipient_kind = ? AND recipient_id = ?
AND category IN ? AND type IN ? AND (expires_at IS NULL OR expires_at > ?)`,
constants.NotificationRecipientKindPersonalCustomer,
customerID,
[]string{constants.NotificationCategoryApproval, constants.NotificationCategoryExpiry, constants.NotificationCategorySystem},
[]string{
constants.NotificationTypePackageExpiring,
constants.NotificationTypeExchangeShippingCreated,
constants.NotificationTypeH5PopupRiskExchange,
constants.NotificationTypeH5PopupOperation,
},
now,
)
}
func newUnreadCountResponse(count int64) *dto.NotificationUnreadCountResponse {
displayCount := strconv.FormatInt(count, 10)
if count > 99 {
displayCount = "99+"
}
return &dto.NotificationUnreadCountResponse{Count: count, DisplayCount: displayCount}
}
func notificationItems(records []model.Notification) []dto.NotificationItem {
items := make([]dto.NotificationItem, 0, len(records))
for _, record := range records {
items = append(items, dto.NotificationItem{
ID: record.ID, Category: record.Category, Type: record.Type, Severity: record.Severity,
Title: record.Title, Body: record.Body, RefType: record.RefType, RefID: record.RefID,
RefKey: record.RefKey, IsRead: record.IsRead, ReadAt: record.ReadAt, CreatedAt: record.CreatedAt,
PopupSnapshot: popupSnapshotItem(record),
})
}
return items
}
// popupSnapshotItem 只对弹窗投放类型投影投放快照,其他类型(含历史数据)一律为空。
// 快照只含配置标识、资产关联与受控动作,不含任何 URL 或前端路由。
func popupSnapshotItem(record model.Notification) *dto.NotificationPopupSnapshotItem {
if !constants.IsH5PopupNotificationType(record.Type) || record.PopupSnapshot == nil {
return nil
}
return &dto.NotificationPopupSnapshotItem{
ConfigID: record.PopupSnapshot.ConfigID,
ConfigVersion: record.PopupSnapshot.ConfigVersion,
AssetType: record.PopupSnapshot.AssetType,
AssetID: record.PopupSnapshot.AssetID,
ActionType: record.PopupSnapshot.ActionType,
}
}