package notification import ( "context" "strconv" "time" "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit" "github.com/break/junhong_cmp_fiber/internal/model" "github.com/break/junhong_cmp_fiber/pkg/constants" "github.com/break/junhong_cmp_fiber/pkg/errors" ) // PersonalDirectRequest 是当次直投或复用个人客户通知的请求参数。 // PopupSnapshot 只允许弹窗投放类型携带,其余类型必须为空。 type PersonalDirectRequest struct { NotificationType string TemplateData map[string]string RefType string RefID string RefKey string ExpiresAt *time.Time PopupSnapshot *model.NotificationPopupSnapshot } // DirectWriter 是「当次创建或复用个人客户通知」的窄接口。 // 候选查询必须当次拿到可用通知标识,不能依赖 Outbox 消费延迟,因此需要这条同步入口。 type DirectWriter interface { CreateOrGetPersonal(ctx context.Context, eventID string, customerID uint, request PersonalDirectRequest) (*model.Notification, error) } // CreateOrGetPersonal 当次渲染并幂等写入个人客户通知;事件键已存在时不重复投放,回查并返回既有行。 // 与 Outbox 消费共用同一渲染、展示期与幂等写入规则,避免两条链路规则漂移。 func (s *DeliveryService) CreateOrGetPersonal(ctx context.Context, eventID string, customerID uint, request PersonalDirectRequest) (*model.Notification, error) { if customerID == 0 || eventID == "" { return nil, errors.New(errors.CodeInvalidParam, "个人客户通知参数不完整") } delivery := deliveryRequest{ notificationType: request.NotificationType, templateData: request.TemplateData, refType: request.RefType, refID: request.RefID, refKey: request.RefKey, expiresAt: request.ExpiresAt, popupSnapshot: request.PopupSnapshot, } if err := validateDeliveryRequest(delivery); err != nil { return nil, err } // API 直投不经过 Outbox 消费,自行提供渲染结果与展示期,但仍复用同一落库规则。 // 个人客户请求上下文不携带审计上下文,直投必须显式声明操作者与入口,否则投递审计会被入口规则拒绝并静默降级。 prepared, err := s.prepareDelivery(eventID, constants.NotificationRecipientKindPersonalCustomer, delivery, deliveryOrigin{ actor: audit.ActorInput{Kind: constants.AuditActorPersonalCustomer, ID: strconv.FormatUint(uint64(customerID), 10)}, source: constants.AuditSourcePersonalAPI, }) if err != nil { return nil, err } notification, _, err := s.deliverOne(ctx, eventID, constants.NotificationRecipientKindPersonalCustomer, customerID, delivery, prepared) if err != nil { return nil, err } if notification == nil { return nil, errors.New(errors.CodeInvalidStatus, "个人客户通知接收人不可用") } return notification, nil }