暂存一下,防止丢失

This commit is contained in:
2026-07-24 16:07:18 +08:00
parent 5d6e23f1a5
commit a18ed8bc8d
180 changed files with 13597 additions and 1986 deletions

View File

@@ -0,0 +1,221 @@
// 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, "查询通知列表失败")
}
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,
})
}
return &dto.NotificationListResponse{Items: items, 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())
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},
[]string{constants.NotificationTypePackageExpiring},
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,
})
}
return items
}

View File

@@ -0,0 +1,156 @@
package notification
import (
"context"
"math"
"strconv"
"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"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
)
// Target 先校验通知属于当前账号,再解析白名单结构化目标并复核当前权限。
func (q *Query) Target(ctx context.Context, recipientID, notificationID uint) (*dto.NotificationTargetResponse, error) {
result := &dto.NotificationTargetResponse{}
if recipientID == 0 || notificationID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
var record model.Notification
err := q.db.WithContext(ctx).Select("ref_type", "ref_id", "ref_key").
Where("id = ? AND recipient_kind = ? AND recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)",
notificationID, constants.NotificationRecipientKindAccount, recipientID, q.now().UTC()).Take(&record).Error
if err == gorm.ErrRecordNotFound {
return result, nil
}
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知目标失败")
}
return q.resolveTarget(ctx, record)
}
func (q *Query) resolveTarget(ctx context.Context, record model.Notification) (*dto.NotificationTargetResponse, error) {
definition, exists := notificationTargetDefinitions()[record.RefType]
if !exists {
return &dto.NotificationTargetResponse{}, nil
}
result := &dto.NotificationTargetResponse{TargetType: definition.targetType}
if definition.keyTarget {
result.TargetKey = record.RefKey
}
if definition.idTarget {
id, valid := parseNotificationTargetID(record.RefID)
if !valid {
return result, nil
}
result.TargetID = &id
}
available, err := definition.available(q, ctx, record, result.TargetID)
if err != nil {
return nil, err
}
result.Available = available
return result, nil
}
type targetDefinition struct {
targetType string
idTarget bool
keyTarget bool
available func(*Query, context.Context, model.Notification, *uint) (bool, error)
}
func notificationTargetDefinitions() map[string]targetDefinition {
return map[string]targetDefinition{
constants.NotificationRefTypeRefund: {targetType: constants.NotificationTargetTypeRefundDetail, idTarget: true, available: refundTargetAvailable},
constants.NotificationRefTypeAgentRecharge: {targetType: constants.NotificationTargetTypeAgentRechargeDetail, idTarget: true, available: unavailableFutureTarget},
constants.NotificationRefTypeWeComApproval: {targetType: constants.NotificationTargetTypeWeComApprovalDetail, idTarget: true, available: unavailableFutureTarget},
constants.NotificationRefTypeIotCard: {targetType: constants.NotificationTargetTypeIotCardDetail, idTarget: true, available: iotCardTargetAvailable},
constants.NotificationRefTypeDevice: {targetType: constants.NotificationTargetTypeDeviceDetail, idTarget: true, available: deviceTargetAvailable},
constants.NotificationRefTypeExpiringAsset: {targetType: constants.NotificationTargetTypeExpiringAssetList, idTarget: true, available: shopTargetAvailable},
constants.NotificationRefTypeShopFund: {targetType: constants.NotificationTargetTypeShopFundSummary, idTarget: true, available: shopTargetAvailable},
constants.NotificationRefTypeIntegrationLog: {targetType: constants.NotificationTargetTypeIntegrationLog, keyTarget: true, available: integrationTargetAvailable},
constants.NotificationRefTypeCardSync: {targetType: constants.NotificationTargetTypeIntegrationLog, keyTarget: true, available: integrationTargetAvailable},
constants.NotificationRefTypeSystemConfig: {targetType: constants.NotificationTargetTypeSystemConfig, keyTarget: true, available: systemConfigTargetAvailable},
}
}
func parseNotificationTargetID(value string) (uint, bool) {
parsed, err := strconv.ParseUint(value, 10, 64)
if err != nil || parsed == 0 || parsed > math.MaxInt64 {
return 0, false
}
return uint(parsed), true
}
func refundTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
query := q.db.WithContext(ctx).Model(&model.RefundRequest{}).Where("id = ?", *id)
switch middleware.GetUserTypeFromContext(ctx) {
case constants.UserTypeSuperAdmin, constants.UserTypePlatform:
case constants.UserTypeAgent:
query = query.Where("creator = ?", middleware.GetUserIDFromContext(ctx))
default:
return false, nil
}
return targetExists(query, "查询退款通知目标失败")
}
func iotCardTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
if middleware.GetUserTypeFromContext(ctx) == constants.UserTypeEnterprise {
return false, nil
}
query := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Model(&model.IotCard{})).Where("id = ?", *id)
return targetExists(query, "查询物联网卡通知目标失败")
}
func deviceTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
if middleware.GetUserTypeFromContext(ctx) == constants.UserTypeEnterprise {
return false, nil
}
query := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Model(&model.Device{})).Where("id = ?", *id)
return targetExists(query, "查询设备通知目标失败")
}
func shopTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
if err := middleware.CanManageShop(ctx, *id); err != nil {
return false, nil
}
query := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{})).Where("id = ?", *id)
return targetExists(query, "查询店铺通知目标失败")
}
func integrationTargetAvailable(q *Query, ctx context.Context, record model.Notification, _ *uint) (bool, error) {
userType := middleware.GetUserTypeFromContext(ctx)
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
return false, nil
}
if record.RefKey == "" {
return false, nil
}
query := q.db.WithContext(ctx).Model(&model.IntegrationLog{}).Where("integration_id = ?", record.RefKey)
return targetExists(query, "查询外部集成通知目标失败")
}
func systemConfigTargetAvailable(q *Query, ctx context.Context, record model.Notification, _ *uint) (bool, error) {
if middleware.GetUserTypeFromContext(ctx) != constants.UserTypeSuperAdmin || record.RefKey == "" {
return false, nil
}
query := q.db.WithContext(ctx).Model(&model.SystemConfig{}).Where("config_key = ?", record.RefKey)
return targetExists(query, "查询系统配置通知目标失败")
}
func unavailableFutureTarget(_ *Query, _ context.Context, _ model.Notification, _ *uint) (bool, error) {
return false, nil
}
func targetExists(query *gorm.DB, summary string) (bool, error) {
var count int64
if err := query.Count(&count).Error; err != nil {
return false, errors.Wrap(errors.CodeDatabaseError, err, summary)
}
return count > 0, nil
}