package cardobservation import ( "context" "strconv" "time" domain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation" "github.com/break/junhong_cmp_fiber/internal/model" "github.com/break/junhong_cmp_fiber/pkg/constants" "github.com/break/junhong_cmp_fiber/pkg/errors" "github.com/break/junhong_cmp_fiber/pkg/outboxid" "gorm.io/gorm" "gorm.io/gorm/clause" ) // RealnameResetCommand 描述对一张卡的二次实名清除或撤销。 type RealnameResetCommand struct { CardID uint BatchID uint OperatorID uint } // 二次实名不可执行的原因(业务可预期,按行记录,不当作系统错误)。 var ( ErrRealnameResetNotVerified = errors.New(errors.CodeInvalidStatus, "卡未实名,无需二次实名") ErrRealnameResetNoUpstream = errors.New(errors.CodeInvalidStatus, "上游未返回实名时间,不支持二次实名") ErrRealnameResetAlreadyReset = errors.New(errors.CodeInvalidStatus, "卡已在等待二次实名") ErrRealnameResetNotPending = errors.New(errors.CodeInvalidStatus, "卡不在等待二次实名,不能撤销") ) // ResetRealname 二次实名清除:卡置为未实名、当前实名时间置空,记下清除前的上游实名时间作为新旧判定基准。 // 只支持上游返回过 archiveTime 的卡;已激活套餐不回退,first_realname_at 不修改。 // 状态变化按现有流程写实名变化事件与审计,下游停复机评估与普通未实名卡一致。 func (s *Service) ResetRealname(ctx context.Context, command RealnameResetCommand) error { return s.changeRealnameForReset(ctx, command, false) } // RevertRealnameReset 撤销等待中的二次实名:卡恢复已实名,当前实名时间恢复为清除前时间。 func (s *Service) RevertRealnameReset(ctx context.Context, command RealnameResetCommand) error { return s.changeRealnameForReset(ctx, command, true) } func (s *Service) changeRealnameForReset(ctx context.Context, command RealnameResetCommand, revert bool) error { if s == nil || s.db == nil || s.eventWriter == nil || s.auditWriter == nil { return errors.New(errors.CodeInternalError, "卡实名观测能力未完整配置") } if command.CardID == 0 { return errors.New(errors.CodeInvalidParam, "卡 ID 无效") } now := time.Now() err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { var card model.IotCard if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", command.CardID).First(&card).Error; err != nil { if err == gorm.ErrRecordNotFound { return errors.New(errors.CodeNotFound, "IoT卡不存在") } return errors.Wrap(errors.CodeDatabaseError, err, "锁定IoT卡失败") } record, snapshot, err := loadRealnameTime(ctx, tx, card.ID) if err != nil { return err } if revert { return s.revertResetInTx(ctx, tx, &card, record, snapshot, command, now) } return s.resetInTx(ctx, tx, &card, record, snapshot, command, now) }) if err != nil { return err } if s.cache != nil { s.cache.Invalidate(ctx, command.CardID) } return nil } func (s *Service) resetInTx(ctx context.Context, tx *gorm.DB, card *model.IotCard, record *model.IotCardRealname, snapshot domain.RealnameTimeSnapshot, command RealnameResetCommand, now time.Time) error { if card.RealNameStatus != constants.RealNameStatusVerified { return ErrRealnameResetNotVerified } if record == nil || record.UpstreamRealnameAt == nil { return ErrRealnameResetNoUpstream } if snapshot.ResetStatus == constants.RealnameResetStatusPending { return ErrRealnameResetAlreadyReset } if err := s.updateCardRealnameStatusInTx(ctx, tx, card, constants.RealNameStatusNotVerified, now, "reset", command.BatchID); err != nil { return err } batchID := command.BatchID if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ?", record.ID).Updates(map[string]any{ "realname_at": nil, "reset_status": constants.RealnameResetStatusPending, "reset_at": now, "reset_baseline_at": *record.UpstreamRealnameAt, "reset_batch_id": batchID, "updated_at": now, }).Error; err != nil { return errors.Wrap(errors.CodeDatabaseError, err, "写入二次实名等待状态失败") } return writeResetHistory(ctx, tx, card, record.RealnameAt, nil, "", constants.RealnameChangeReset, command, now) } func (s *Service) revertResetInTx(ctx context.Context, tx *gorm.DB, card *model.IotCard, record *model.IotCardRealname, snapshot domain.RealnameTimeSnapshot, command RealnameResetCommand, now time.Time) error { if record == nil || snapshot.ResetStatus != constants.RealnameResetStatusPending { return ErrRealnameResetNotPending } if command.BatchID != 0 && (record.ResetBatchID == nil || *record.ResetBatchID != command.BatchID) { return ErrRealnameResetNotPending } if card.RealNameStatus != constants.RealNameStatusVerified { if err := s.updateCardRealnameStatusInTx(ctx, tx, card, constants.RealNameStatusVerified, now, "revert", command.BatchID); err != nil { return err } } restored := record.ResetBaselineAt if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ?", record.ID).Updates(map[string]any{ "realname_at": restored, "realname_at_source": constants.RealnameAtSourceUpstream, "reset_status": constants.RealnameResetStatusNone, "reset_at": nil, "reset_baseline_at": nil, "reset_batch_id": nil, "updated_at": now, }).Error; err != nil { return errors.Wrap(errors.CodeDatabaseError, err, "撤销二次实名等待状态失败") } return writeResetHistory(ctx, tx, card, nil, restored, constants.RealnameAtSourceUpstream, constants.RealnameChangeResetReverted, command, now) } // updateCardRealnameStatusInTx 按实名观测的同一口径更新卡实名状态,并写实名变化事件与人工审计。 func (s *Service) updateCardRealnameStatusInTx(ctx context.Context, tx *gorm.DB, card *model.IotCard, after int, now time.Time, kind string, batchID uint) error { verified := after == constants.RealNameStatusVerified result := tx.WithContext(ctx).Model(&model.IotCard{}).Where("id = ? AND real_name_status = ?", card.ID, card.RealNameStatus).Updates(map[string]any{ "real_name_status": after, "realname_reversal_count": 0, "realname_reversal_started_at": nil, "activation_status": gorm.Expr(`CASE WHEN network_status = ? AND (card_category = ? OR ?) THEN 1 ELSE 0 END`, constants.NetworkStatusOnline, constants.CardCategoryIndustry, verified), }) if result.Error != nil { return errors.Wrap(errors.CodeDatabaseError, result.Error, "更新卡实名状态失败") } if result.RowsAffected != 1 { return errors.New(errors.CodeConflict, "卡实名状态已被其他请求更新") } observationID := "realname-" + kind + ":" + strconv.FormatUint(uint64(batchID), 10) + ":" + strconv.FormatInt(now.UnixNano(), 10) eventID := outboxid.Stable("card-realname:", strconv.FormatUint(uint64(card.ID), 10)+":"+observationID+":changed") if err := s.eventWriter.AppendRealname(ctx, tx, RealnameChangedEvent{ EventID: eventID, CardID: card.ID, BeforeStatus: card.RealNameStatus, AfterStatus: after, ObservedAt: now, Source: constants.CardObservationSourceManualOverride, Scene: "realname_" + kind, CorrelationID: observationID, }); err != nil { return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名 Outbox 事件失败") } summary := "二次实名清除:卡实名状态置为未实名" if verified { summary = "二次实名撤销:卡恢复已实名" } return s.auditWriter.WriteCardStateAudit(ctx, tx, StateAudit{ ActionCode: constants.AuditActionIotCardRealnameStatusUpdated, Summary: summary, Card: card, BeforeData: map[string]any{"real_name_status": card.RealNameStatus}, AfterData: map[string]any{"real_name_status": after, "realname_reset_batch_id": batchID}, }) } func writeResetHistory(ctx context.Context, tx *gorm.DB, card *model.IotCard, before, after *time.Time, afterSource, changeType string, command RealnameResetCommand, now time.Time) error { var batchID *uint if command.BatchID != 0 { value := command.BatchID batchID = &value } history := model.IotCardRealnameHistory{ CardID: card.ID, ICCID: card.ICCID, BeforeAt: before, AfterAt: after, AfterSource: afterSource, ChangeType: changeType, ObservationSource: constants.CardObservationSourceManualOverride, ResetBatchID: batchID, OperatorID: command.OperatorID, ObservedAt: now, CreatedAt: now, } if err := tx.WithContext(ctx).Create(&history).Error; err != nil { return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名时间历史失败") } return nil }