All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m17s
- 每日扫描不再给个人客户写临期通知,店铺通知不变 - H5 资产信息在当前资产剩余 0~15 天且当天首次进入时返回 expiry_reminder,并为该客户、该资产写一条临期通知(Redis 去重,失败不占键) - 个人通知列表、未读数、全部已读中临期提醒只处理当前资产(按 ref_key) - OpenSpec Change scope-expiry-reminder-to-current-asset:6/9,临期 fixture 端到端验证与每日扫描验证待测试部署后完成
277 lines
11 KiB
Go
277 lines
11 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, currentAssetKey string) (*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(constants.NotificationPersonalExpiringAssetCondition,
|
||
constants.NotificationTypePackageExpiring, constants.NotificationRefTypeAsset, currentAssetKey).
|
||
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, currentAssetKey string, 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()).
|
||
Where(constants.NotificationPersonalExpiringAssetCondition,
|
||
constants.NotificationTypePackageExpiring, constants.NotificationRefTypeAsset, currentAssetKey)
|
||
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,
|
||
constants.NotificationTypeAssetAutoRenewalFailed,
|
||
},
|
||
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,
|
||
}
|
||
}
|
||
|
||
// CurrentAssetRefKey 返回个人客户令牌当前资产的通知引用标识:卡为 ICCID;设备优先虚拟号,为空则 IMEI。
|
||
// 资产不存在或类型未知时返回空串,此时个人通知中心不展示任何套餐临期提醒。
|
||
func (q *Query) CurrentAssetRefKey(ctx context.Context, assetType string, assetID uint) (string, error) {
|
||
if assetID == 0 {
|
||
return "", nil
|
||
}
|
||
var row struct {
|
||
ICCID string `gorm:"column:iccid"`
|
||
VirtualNo string `gorm:"column:virtual_no"`
|
||
IMEI string `gorm:"column:imei"`
|
||
}
|
||
var result *gorm.DB
|
||
switch assetType {
|
||
case constants.AssetTypeIotCard, "card":
|
||
result = q.db.WithContext(ctx).Model(&model.IotCard{}).Select("iccid").Where("id = ?", assetID).Limit(1).Scan(&row)
|
||
case constants.AssetTypeDevice:
|
||
result = q.db.WithContext(ctx).Model(&model.Device{}).Select("virtual_no", "imei").Where("id = ?", assetID).Limit(1).Scan(&row)
|
||
default:
|
||
return "", nil
|
||
}
|
||
if result.Error != nil {
|
||
return "", errors.Wrap(errors.CodeDatabaseError, result.Error, "查询当前资产标识失败")
|
||
}
|
||
if row.ICCID != "" {
|
||
return row.ICCID, nil
|
||
}
|
||
if row.VirtualNo != "" {
|
||
return row.VirtualNo, nil
|
||
}
|
||
return row.IMEI, nil
|
||
}
|