fix: 第1批 M9 套餐临期提醒按资产、扫码进入时触发
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m17s
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 端到端验证与每日扫描验证待测试部署后完成
This commit is contained in:
@@ -68,13 +68,17 @@ func (s *ReadService) MarkPersonalRead(ctx context.Context, customerID, notifica
|
||||
constants.AuditActorPersonalCustomer, constants.AuditSourcePersonalAPI)
|
||||
}
|
||||
|
||||
// MarkAllPersonalRead 将当前个人客户可见的全部未过期通知幂等标记为已读。
|
||||
func (s *ReadService) MarkAllPersonalRead(ctx context.Context, customerID uint) (*dto.NotificationReadAllResponse, error) {
|
||||
// MarkAllPersonalRead 将当前个人客户可见的全部未过期通知幂等标记为已读;
|
||||
// 套餐临期提醒只处理当前资产的,其他资产的临期提醒保持未读。
|
||||
func (s *ReadService) MarkAllPersonalRead(ctx context.Context, customerID uint, currentAssetKey string) (*dto.NotificationReadAllResponse, error) {
|
||||
if customerID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
count, err := s.markAllRead(ctx, constants.NotificationRecipientKindPersonalCustomer, customerID, "",
|
||||
constants.AuditActorPersonalCustomer, constants.AuditSourcePersonalAPI)
|
||||
constants.AuditActorPersonalCustomer, constants.AuditSourcePersonalAPI, func(query *gorm.DB) *gorm.DB {
|
||||
return query.Where(constants.NotificationPersonalExpiringAssetCondition,
|
||||
constants.NotificationTypePackageExpiring, constants.NotificationRefTypeAsset, currentAssetKey)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -107,7 +111,7 @@ func (s *ReadService) markOneRead(ctx context.Context, recipientKind string, rec
|
||||
})
|
||||
}
|
||||
|
||||
func (s *ReadService) markAllRead(ctx context.Context, recipientKind string, recipientID uint, category, actorKind, source string) (int64, error) {
|
||||
func (s *ReadService) markAllRead(ctx context.Context, recipientKind string, recipientID uint, category, actorKind, source string, scopes ...func(*gorm.DB) *gorm.DB) (int64, error) {
|
||||
if s.auditWriter == nil {
|
||||
return 0, errors.New(errors.CodeInvalidStatus, "通知统一审计接缝未配置")
|
||||
}
|
||||
@@ -120,6 +124,9 @@ func (s *ReadService) markAllRead(ctx context.Context, recipientKind string, rec
|
||||
if category != "" {
|
||||
query = query.Where("category = ?", category)
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
query = scope(query)
|
||||
}
|
||||
if err := query.Order("id ASC").Find(¬ifications).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询批量通知已读状态失败")
|
||||
}
|
||||
|
||||
98
internal/application/packageexpiry/entry_reminder.go
Normal file
98
internal/application/packageexpiry/entry_reminder.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package packageexpiry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
packageexpiryquery "github.com/break/junhong_cmp_fiber/internal/query/packageexpiry"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// entryReminderWindowDays 临期提醒窗口:剩余 0~15 个上海自然日。
|
||||
const entryReminderWindowDays = 15
|
||||
|
||||
var entryReminderLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
// PersonalReminderPublisher 为单个个人客户幂等写一条临期通知。
|
||||
type PersonalReminderPublisher interface {
|
||||
PublishPersonal(ctx context.Context, candidate dto.ExpiringAssetItem, customerID uint) error
|
||||
}
|
||||
|
||||
// EntryReminder 在 H5 进入资产时判定并发出套餐临期提醒,同一客户、同一资产、同一上海自然日至多一次。
|
||||
type EntryReminder struct {
|
||||
redis *redis.Client
|
||||
publisher PersonalReminderPublisher
|
||||
logger *zap.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewEntryReminder 创建进入资产时的临期提醒用例。
|
||||
func NewEntryReminder(redisClient *redis.Client, publisher PersonalReminderPublisher, logger *zap.Logger) *EntryReminder {
|
||||
return &EntryReminder{redis: redisClient, publisher: publisher, logger: logger, now: time.Now}
|
||||
}
|
||||
|
||||
// Remind 返回本次应展示的临期提醒;不在窗口、当天已提醒或通知写入失败时返回 nil,不让资产信息接口失败。
|
||||
// 顺序:检查去重键 → 写通知 → SET NX → 抢到键才返回;Redis 不可用按未提醒处理,通知由事件号幂等。
|
||||
func (r *EntryReminder) Remind(ctx context.Context, customerID uint, candidate dto.ExpiringAssetItem) *dto.AssetExpiryReminder {
|
||||
if r == nil || r.publisher == nil || customerID == 0 || !inEntryReminderWindow(candidate.PackageExpiryEstimate) {
|
||||
return nil
|
||||
}
|
||||
now := r.now().In(entryReminderLocation)
|
||||
key := constants.RedisPackageExpiryEntryReminderKey(customerID, candidate.AssetType, candidate.Identifier, now.Format("20060102"))
|
||||
redisOK := r.redis != nil
|
||||
if redisOK {
|
||||
exists, err := r.redis.Exists(ctx, key).Result()
|
||||
if err != nil {
|
||||
redisOK = false
|
||||
r.warn("检查临期提醒去重键失败,按未提醒处理", err)
|
||||
} else if exists > 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := r.publisher.PublishPersonal(ctx, candidate, customerID); err != nil {
|
||||
// 写通知失败不占键、不返回字段,下次进入重试。
|
||||
r.warn("写入进入资产临期通知失败", err)
|
||||
return nil
|
||||
}
|
||||
if redisOK {
|
||||
ttl := endOfShanghaiDay(now).Sub(now) + constants.PackageExpiryEntryReminderTTLBuffer
|
||||
acquired, err := r.redis.SetNX(ctx, key, "1", ttl).Result()
|
||||
if err != nil {
|
||||
r.warn("占用临期提醒去重键失败,按未提醒处理", err)
|
||||
} else if !acquired {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
days := *candidate.DaysUntilFinalExpiry
|
||||
level, levelName := packageexpiryquery.ExpiryLevel(days)
|
||||
return &dto.AssetExpiryReminder{
|
||||
RemainingDays: days, ExpiresAt: *candidate.EstimatedFinalExpiresAt,
|
||||
Level: level, LevelName: levelName,
|
||||
}
|
||||
}
|
||||
|
||||
// inEntryReminderWindow 判断最终到期可精确推算且剩余 0~15 个上海自然日。
|
||||
func inEntryReminderWindow(estimate dto.PackageExpiryEstimate) bool {
|
||||
if estimate.ExpiryEstimateStatus != constants.PackageExpiryEstimateStatusExact ||
|
||||
estimate.DaysUntilFinalExpiry == nil || estimate.EstimatedFinalExpiresAt == nil {
|
||||
return false
|
||||
}
|
||||
days := *estimate.DaysUntilFinalExpiry
|
||||
return days >= 0 && days <= entryReminderWindowDays
|
||||
}
|
||||
|
||||
// endOfShanghaiDay 返回上海时间当天结束时刻(次日零点)。
|
||||
func endOfShanghaiDay(now time.Time) time.Time {
|
||||
year, month, day := now.In(entryReminderLocation).Date()
|
||||
return time.Date(year, month, day+1, 0, 0, 0, 0, entryReminderLocation)
|
||||
}
|
||||
|
||||
func (r *EntryReminder) warn(message string, err error) {
|
||||
if r.logger != nil {
|
||||
r.logger.Warn(message, zap.Error(err))
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
h5PopupApp "github.com/break/junhong_cmp_fiber/internal/application/h5popup"
|
||||
merchantPaymentApp "github.com/break/junhong_cmp_fiber/internal/application/merchantpayment"
|
||||
notificationApp "github.com/break/junhong_cmp_fiber/internal/application/notification"
|
||||
packageExpiryApp "github.com/break/junhong_cmp_fiber/internal/application/packageexpiry"
|
||||
roleApp "github.com/break/junhong_cmp_fiber/internal/application/role"
|
||||
shopApp "github.com/break/junhong_cmp_fiber/internal/application/shop"
|
||||
systemConfigApp "github.com/break/junhong_cmp_fiber/internal/application/systemconfig"
|
||||
@@ -21,7 +22,9 @@ import (
|
||||
auditInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/carriercallback"
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
|
||||
notificationInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/notification"
|
||||
packageExpiryInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/packageexpiry"
|
||||
systemConfigInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/systemconfig"
|
||||
wecomInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/wecom"
|
||||
pollingPkg "github.com/break/junhong_cmp_fiber/internal/polling"
|
||||
@@ -209,6 +212,9 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
|
||||
handler.SetObservationSeriesDispatcher(svc.ObservationSeries)
|
||||
handler.SetPaymentMethodPolicy(paymentMethodPolicy)
|
||||
handler.SetForceRechargeChecker(svc.Recharge)
|
||||
handler.SetExpiryReminder(packageExpiryApp.NewEntryReminder(
|
||||
deps.Redis, packageExpiryInfra.NewReminderPublisher(deps.DB, outbox.NewRepository()), deps.Logger,
|
||||
))
|
||||
return handler
|
||||
}(),
|
||||
ClientWallet: func() *app.ClientWalletHandler {
|
||||
|
||||
@@ -46,6 +46,17 @@ type ClientAssetHandler struct {
|
||||
observationSeries cardObservationApp.BestEffortSeriesDispatcher
|
||||
paymentMethodPolicy ClientPaymentMethodPolicy
|
||||
forceRechargeChecker ClientForceRechargeChecker
|
||||
expiryReminder ClientExpiryReminder
|
||||
}
|
||||
|
||||
// ClientExpiryReminder 在 H5 进入资产时判定并发出套餐临期提醒。
|
||||
type ClientExpiryReminder interface {
|
||||
Remind(ctx context.Context, customerID uint, candidate dto.ExpiringAssetItem) *dto.AssetExpiryReminder
|
||||
}
|
||||
|
||||
// SetExpiryReminder 注入进入资产时的套餐临期提醒用例。
|
||||
func (h *ClientAssetHandler) SetExpiryReminder(reminder ClientExpiryReminder) {
|
||||
h.expiryReminder = reminder
|
||||
}
|
||||
|
||||
// ClientPaymentMethodPolicy 提供 C 端支付方式读取和校验能力。
|
||||
@@ -279,6 +290,10 @@ func (h *ClientAssetHandler) GetAssetInfo(c *fiber.Ctx) error {
|
||||
BoundDeviceName: resolved.Asset.BoundDeviceName,
|
||||
}
|
||||
|
||||
if h.expiryReminder != nil {
|
||||
resp.ExpiryReminder = h.expiryReminder.Remind(c.UserContext(), resolved.CustomerID, expiringCandidateOf(resolved.Asset))
|
||||
}
|
||||
|
||||
// 调用服务层获取设备实时 Gateway 数据(per D-11)
|
||||
// Gateway 失败时 DeviceRealtime 仅含 gateway_msg,不阻断主流程(per D-06)
|
||||
if resp.AssetType == "device" {
|
||||
@@ -851,3 +866,24 @@ func mapDeviceGatewayInfoToClientInfo(g *dto.DeviceGatewayInfo) *dto.DeviceRealt
|
||||
info.GatewayMsg = g.GatewayMsg
|
||||
return info
|
||||
}
|
||||
|
||||
// expiringCandidateOf 把资产解析结果转换为临期提醒候选;资产标识与通知中心过滤口径一致(卡 ICCID;设备虚拟号,空则 IMEI)。
|
||||
func expiringCandidateOf(asset *dto.AssetResolveResponse) dto.ExpiringAssetItem {
|
||||
candidate := dto.ExpiringAssetItem{
|
||||
AssetID: asset.AssetID, ShopID: asset.ShopID, PackageExpiryEstimate: asset.PackageExpiryEstimate,
|
||||
}
|
||||
if asset.CurrentPackageUsageID != nil {
|
||||
candidate.PackageUsageID = *asset.CurrentPackageUsageID
|
||||
}
|
||||
if asset.AssetType == "device" {
|
||||
candidate.AssetType = constants.AssetTypeDevice
|
||||
candidate.Identifier = asset.VirtualNo
|
||||
if candidate.Identifier == "" {
|
||||
candidate.Identifier = asset.IMEI
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
candidate.AssetType = constants.AssetTypeIotCard
|
||||
candidate.Identifier = asset.ICCID
|
||||
return candidate
|
||||
}
|
||||
|
||||
@@ -36,7 +36,11 @@ func (h *ClientNotificationHandler) UnreadCount(c *fiber.Ctx) error {
|
||||
if !ok || customerID == 0 {
|
||||
return errors.New(errors.CodeUnauthorized)
|
||||
}
|
||||
result, err := h.query.PersonalUnreadCount(c.UserContext(), customerID)
|
||||
assetKey, err := h.currentAssetKey(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.query.PersonalUnreadCount(c.UserContext(), customerID, assetKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -61,7 +65,11 @@ func (h *ClientNotificationHandler) List(c *fiber.Ctx) error {
|
||||
if !ok || customerID == 0 {
|
||||
return errors.New(errors.CodeUnauthorized)
|
||||
}
|
||||
result, err := h.query.PersonalList(c.UserContext(), customerID, request)
|
||||
assetKey, err := h.currentAssetKey(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.query.PersonalList(c.UserContext(), customerID, assetKey, request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -75,7 +83,11 @@ func (h *ClientNotificationHandler) MarkAllRead(c *fiber.Ctx) error {
|
||||
if !ok || customerID == 0 {
|
||||
return errors.New(errors.CodeUnauthorized)
|
||||
}
|
||||
result, err := h.readService.MarkAllPersonalRead(c.UserContext(), customerID)
|
||||
assetKey, err := h.currentAssetKey(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := h.readService.MarkAllPersonalRead(c.UserContext(), customerID, assetKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -99,6 +111,15 @@ func (h *ClientNotificationHandler) MarkRead(c *fiber.Ctx) error {
|
||||
return response.Success(c, dto.NotificationReadResponse{Success: true})
|
||||
}
|
||||
|
||||
// currentAssetKey 读取令牌当前资产的通知引用标识,用于只展示当前资产的套餐临期提醒。
|
||||
func (h *ClientNotificationHandler) currentAssetKey(c *fiber.Ctx) (string, error) {
|
||||
assetType, assetID, ok := middleware.GetCurrentAsset(c)
|
||||
if !ok {
|
||||
return "", nil
|
||||
}
|
||||
return h.query.CurrentAssetRefKey(c.UserContext(), assetType, assetID)
|
||||
}
|
||||
|
||||
func logPersonalNotificationListValidationFailure(c *fiber.Ctx, request dto.PersonalNotificationListRequest, err error) {
|
||||
logger.GetAppLogger().Warn("个人客户站内通知列表参数验证失败",
|
||||
zap.String("method", c.Method()),
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
var shanghaiLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
// ReminderPublisher 将每日临期事实转换为店铺和个人客户通知 Outbox。
|
||||
// ReminderPublisher 将临期事实转换为店铺通知(每日扫描)与个人客户通知(H5 进入资产时)Outbox。
|
||||
type ReminderPublisher struct {
|
||||
db *gorm.DB
|
||||
outbox *outbox.Repository
|
||||
@@ -29,41 +29,38 @@ func NewReminderPublisher(db *gorm.DB, repository *outbox.Repository) *ReminderP
|
||||
return &ReminderPublisher{db: db, outbox: repository}
|
||||
}
|
||||
|
||||
type recipientRow struct {
|
||||
AssetID uint
|
||||
CustomerID uint
|
||||
}
|
||||
|
||||
// Publish 批量解析资产关联个人客户,并在同一事务内幂等追加店铺和个人通知事件。
|
||||
// Publish 每日扫描在同一事务内幂等追加店铺通知事件。
|
||||
// 不再给个人客户批量写临期通知:个人客户只在 H5 进入该资产时由 PublishPersonal 提醒。
|
||||
func (p *ReminderPublisher) Publish(ctx context.Context, candidates []dto.ExpiringAssetItem) error {
|
||||
if p == nil || p.db == nil || p.outbox == nil {
|
||||
return errors.New(errors.CodeInternalError, "套餐临期通知 Publisher 未配置")
|
||||
}
|
||||
recipients, err := p.loadRecipients(ctx, candidates)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, candidate := range candidates {
|
||||
if candidate.DaysUntilFinalExpiry == nil || candidate.EstimatedFinalExpiresAt == nil {
|
||||
if candidate.DaysUntilFinalExpiry == nil || candidate.EstimatedFinalExpiresAt == nil || candidate.ShopID == nil {
|
||||
continue
|
||||
}
|
||||
key := recipientKey(candidate.AssetType, candidate.AssetID)
|
||||
if candidate.ShopID != nil {
|
||||
if err := p.appendShopNotification(ctx, tx, candidate, *candidate.ShopID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for customerID := range recipients[key] {
|
||||
if err := p.appendNotification(ctx, tx, candidate, customerID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.appendShopNotification(ctx, tx, candidate, *candidate.ShopID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// PublishPersonal 为进入资产的个人客户幂等写一条临期通知;事件号含资产、到期日、剩余天数与客户。
|
||||
func (p *ReminderPublisher) PublishPersonal(ctx context.Context, candidate dto.ExpiringAssetItem, customerID uint) error {
|
||||
if p == nil || p.db == nil || p.outbox == nil {
|
||||
return errors.New(errors.CodeInternalError, "套餐临期通知 Publisher 未配置")
|
||||
}
|
||||
if candidate.DaysUntilFinalExpiry == nil || candidate.EstimatedFinalExpiresAt == nil || customerID == 0 {
|
||||
return errors.New(errors.CodeInvalidParam, "套餐临期个人通知参数不完整")
|
||||
}
|
||||
return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return p.appendNotification(ctx, tx, candidate, customerID)
|
||||
})
|
||||
}
|
||||
|
||||
// appendShopNotification 按资产所属店铺写入一条动态接收人通知事件。
|
||||
func (p *ReminderPublisher) appendShopNotification(ctx context.Context, tx *gorm.DB, candidate dto.ExpiringAssetItem, shopID uint) error {
|
||||
node := *candidate.DaysUntilFinalExpiry
|
||||
@@ -93,57 +90,6 @@ func (p *ReminderPublisher) appendShopNotification(ctx context.Context, tx *gorm
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ReminderPublisher) loadRecipients(ctx context.Context, candidates []dto.ExpiringAssetItem) (map[string]map[uint]struct{}, error) {
|
||||
cardIDs := make([]uint, 0)
|
||||
deviceIDs := make([]uint, 0)
|
||||
for _, candidate := range candidates {
|
||||
if candidate.AssetType == constants.AssetTypeIotCard {
|
||||
cardIDs = append(cardIDs, candidate.AssetID)
|
||||
} else if candidate.AssetType == constants.AssetTypeDevice {
|
||||
deviceIDs = append(deviceIDs, candidate.AssetID)
|
||||
}
|
||||
}
|
||||
result := make(map[string]map[uint]struct{})
|
||||
queries := []struct {
|
||||
assetType string
|
||||
ids []uint
|
||||
sql string
|
||||
}{
|
||||
{constants.AssetTypeIotCard, cardIDs, `
|
||||
SELECT c.id AS asset_id, b.customer_id
|
||||
FROM tb_iot_card c
|
||||
JOIN tb_personal_customer_device b ON c.virtual_no <> '' AND b.virtual_no = c.virtual_no
|
||||
WHERE c.id IN ? AND c.deleted_at IS NULL AND b.deleted_at IS NULL AND b.status = 1`},
|
||||
{constants.AssetTypeIotCard, cardIDs, `
|
||||
SELECT c.id AS asset_id, b.customer_id
|
||||
FROM tb_iot_card c
|
||||
JOIN tb_personal_customer_iccid b ON c.virtual_no = '' AND (b.iccid = c.iccid OR (b.iccid_19 <> '' AND b.iccid_19 = c.iccid_19))
|
||||
WHERE c.id IN ? AND c.deleted_at IS NULL AND b.deleted_at IS NULL AND b.status = 1`},
|
||||
{constants.AssetTypeDevice, deviceIDs, `
|
||||
SELECT d.id AS asset_id, b.customer_id
|
||||
FROM tb_device d
|
||||
JOIN tb_personal_customer_device b ON b.virtual_no = CASE WHEN d.virtual_no <> '' THEN d.virtual_no ELSE d.imei END
|
||||
WHERE d.id IN ? AND d.deleted_at IS NULL AND b.deleted_at IS NULL AND b.status = 1`},
|
||||
}
|
||||
for _, query := range queries {
|
||||
if len(query.ids) == 0 {
|
||||
continue
|
||||
}
|
||||
var rows []recipientRow
|
||||
if err := p.db.WithContext(ctx).Raw(query.sql, query.ids).Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "批量查询临期资产关联客户失败")
|
||||
}
|
||||
for _, row := range rows {
|
||||
key := recipientKey(query.assetType, row.AssetID)
|
||||
if result[key] == nil {
|
||||
result[key] = make(map[uint]struct{})
|
||||
}
|
||||
result[key][row.CustomerID] = struct{}{}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p *ReminderPublisher) appendNotification(ctx context.Context, tx *gorm.DB, candidate dto.ExpiringAssetItem, customerID uint) error {
|
||||
node := *candidate.DaysUntilFinalExpiry
|
||||
expiryDate := candidate.EstimatedFinalExpiresAt.In(shanghaiLocation).Format("20060102")
|
||||
@@ -191,7 +137,3 @@ func expiryTemplateData(candidate dto.ExpiringAssetItem) map[string]string {
|
||||
"expiry_date": expiryDate,
|
||||
}
|
||||
}
|
||||
|
||||
func recipientKey(assetType string, assetID uint) string {
|
||||
return fmt.Sprintf("%s:%d", assetType, assetID)
|
||||
}
|
||||
|
||||
@@ -13,8 +13,18 @@ type AssetInfoRequest struct {
|
||||
|
||||
// AssetInfoResponse B1 资产信息响应
|
||||
// 根据 asset_type 不同,设备专属字段或卡专属字段会分别填充(另一侧为零值/omit)
|
||||
// AssetExpiryReminder H5 进入资产时的套餐临期提醒;同一客户、同一资产、同一上海自然日至多返回一次。
|
||||
type AssetExpiryReminder struct {
|
||||
RemainingDays int `json:"remaining_days" description:"距最终到期的剩余上海自然日天数(0~15)"`
|
||||
ExpiresAt time.Time `json:"expires_at" description:"预计套餐最终到期时间"`
|
||||
Level string `json:"level" description:"提醒等级 (red:0至3天, purple:4至7天, pink:8至15天)"`
|
||||
LevelName string `json:"level_name" description:"提醒等级中文名称"`
|
||||
}
|
||||
|
||||
type AssetInfoResponse struct {
|
||||
PackageExpiryEstimate
|
||||
// ExpiryReminder 当前资产临期且当天首次进入时返回,否则不返回该字段
|
||||
ExpiryReminder *AssetExpiryReminder `json:"expiry_reminder,omitempty" description:"套餐临期提醒:当前资产剩余 0~15 天且该客户当天首次进入时返回,同时写一条该资产的临期通知;否则不返回"`
|
||||
// === 登录用户信息 ===
|
||||
BoundPhone string `json:"bound_phone" description:"当前登录用户绑定的手机号"`
|
||||
|
||||
|
||||
@@ -84,13 +84,15 @@ func (q *Query) List(ctx context.Context, recipientID uint, request dto.Notifica
|
||||
}, nil
|
||||
}
|
||||
|
||||
// PersonalUnreadCount 查询当前个人客户可见业务通知的准确未读数。
|
||||
func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.NotificationUnreadCountResponse, error) {
|
||||
// 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 {
|
||||
@@ -99,8 +101,8 @@ func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.
|
||||
return newUnreadCountResponse(count), nil
|
||||
}
|
||||
|
||||
// PersonalList 查询当前个人客户可见的未过期业务通知简化列表。
|
||||
func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.PersonalNotificationListRequest) (*dto.PersonalNotificationListResponse, error) {
|
||||
// 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)
|
||||
}
|
||||
@@ -108,7 +110,9 @@ func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.P
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC())
|
||||
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)
|
||||
}
|
||||
@@ -238,3 +242,35 @@ func popupSnapshotItem(record model.Notification) *dto.NotificationPopupSnapshot
|
||||
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
|
||||
}
|
||||
|
||||
@@ -246,7 +246,7 @@ func (q *Query) resolveCandidates(ctx context.Context, candidates []assetCandida
|
||||
if filter.PackageID != nil && usage.PackageID != *filter.PackageID {
|
||||
continue
|
||||
}
|
||||
level, levelName := expiryLevel(days)
|
||||
level, levelName := ExpiryLevel(days)
|
||||
items = append(items, dto.ExpiringAssetItem{
|
||||
AssetType: candidate.AssetType, AssetID: candidate.AssetID, Identifier: candidate.Identifier, ShopID: candidate.ShopID,
|
||||
PackageUsageID: usage.ID, PackageID: usage.PackageID, PackageName: usage.PackageName,
|
||||
@@ -363,7 +363,8 @@ func validateListFilter(filter ListFilter) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func expiryLevel(days int) (string, string) {
|
||||
// ExpiryLevel 返回临期高亮等级与中文名称:≤3 红、≤7 紫、其余粉红。
|
||||
func ExpiryLevel(days int) (string, string) {
|
||||
if days <= 3 {
|
||||
return "red", "红色"
|
||||
}
|
||||
|
||||
@@ -149,11 +149,12 @@ func RegisterPersonalCustomerRoutes(router fiber.Router, doc *openapi.Generator,
|
||||
})
|
||||
|
||||
Register(authGroup, doc, basePath, "GET", "/asset/info", handlers.ClientAsset.GetAssetInfo, RouteSpec{
|
||||
Summary: "资产信息",
|
||||
Tags: []string{"个人客户 - 资产"},
|
||||
Auth: true,
|
||||
Input: &dto.AssetInfoRequest{},
|
||||
Output: &dto.AssetInfoResponse{},
|
||||
Summary: "资产信息",
|
||||
Description: "资产剩余 0~15 个上海自然日且当前客户当天首次进入时返回 expiry_reminder,并为该客户、该资产写一条套餐临期通知;同一客户、同一资产当天只返回一次。",
|
||||
Tags: []string{"个人客户 - 资产"},
|
||||
Auth: true,
|
||||
Input: &dto.AssetInfoRequest{},
|
||||
Output: &dto.AssetInfoResponse{},
|
||||
})
|
||||
|
||||
Register(authGroup, doc, basePath, "GET", "/asset/packages", handlers.ClientAsset.GetAvailablePackages, RouteSpec{
|
||||
|
||||
@@ -15,7 +15,7 @@ func registerPersonalNotificationRoutes(router fiber.Router, handler *apphandler
|
||||
|
||||
Register(notifications, doc, groupPath, "GET", "/unread-count", handler.UnreadCount, RouteSpec{
|
||||
Summary: "查询个人客户通知未读数",
|
||||
Description: "仅查询当前认证个人客户的未过期业务通知,平台同步和系统运维通知不会进入结果。",
|
||||
Description: "仅查询当前认证个人客户的未过期业务通知,平台同步和系统运维通知不会进入结果;套餐临期提醒只计当前登录资产的。",
|
||||
Tags: []string{"个人客户 - 站内通知"},
|
||||
Output: new(dto.NotificationUnreadCountResponse),
|
||||
Auth: true,
|
||||
@@ -23,7 +23,7 @@ func registerPersonalNotificationRoutes(router fiber.Router, handler *apphandler
|
||||
|
||||
Register(notifications, doc, groupPath, "GET", "", handler.List, RouteSpec{
|
||||
Summary: "查询个人客户通知列表",
|
||||
Description: "仅返回当前认证个人客户的未过期业务通知,可按已读状态筛选,固定按创建时间和通知 ID 倒序。当前 C 端契约只承诺列表展示和未读弹窗;ref_type/ref_id/ref_key 是资源引用与展示快照,不是URL,也不承诺可直接拼接页面路由。",
|
||||
Description: "仅返回当前认证个人客户的未过期业务通知,可按已读状态筛选,固定按创建时间和通知 ID 倒序;套餐临期提醒只返回当前登录资产的(按 ref_key 匹配,卡为 ICCID、设备为虚拟号或 IMEI),其他类型不受影响。当前 C 端契约只承诺列表展示和未读弹窗;ref_type/ref_id/ref_key 是资源引用与展示快照,不是URL,也不承诺可直接拼接页面路由。",
|
||||
Tags: []string{"个人客户 - 站内通知"},
|
||||
Input: new(dto.PersonalNotificationListRequest),
|
||||
Output: new(dto.PersonalNotificationListResponse),
|
||||
@@ -33,7 +33,7 @@ func registerPersonalNotificationRoutes(router fiber.Router, handler *apphandler
|
||||
// 静态路径必须先于通知 ID 动态路径,避免被动态参数吞掉。
|
||||
Register(notifications, doc, groupPath, "PUT", "/read-all", handler.MarkAllRead, RouteSpec{
|
||||
Summary: "全部标记个人客户通知已读",
|
||||
Description: "只更新当前认证个人客户可见的未过期未读业务通知,重复调用幂等成功。",
|
||||
Description: "只更新当前认证个人客户可见的未过期未读业务通知,重复调用幂等成功;其他资产的套餐临期提醒保持未读。",
|
||||
Tags: []string{"个人客户 - 站内通知"},
|
||||
Output: new(dto.NotificationReadAllResponse),
|
||||
Auth: true,
|
||||
|
||||
Reference in New Issue
Block a user