feat: 卡实名时间以上游 archiveTime 为准并记录实名时间历史,新增二次实名批次
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled

This commit is contained in:
邹进
2026-11-08 19:12:46 +09:00
parent 94f86ab217
commit 4967f4df43
32 changed files with 1885 additions and 47 deletions

View File

@@ -20,10 +20,11 @@ import (
// RealnameChangedEvent 是卡实名状态变化的可靠领域事实。
type RealnameChangedEvent struct {
EventID string `json:"event_id"`
CardID uint `json:"card_id"`
BeforeStatus int `json:"before_status"`
AfterStatus int `json:"after_status"`
EventID string `json:"event_id"`
CardID uint `json:"card_id"`
BeforeStatus int `json:"before_status"`
AfterStatus int `json:"after_status"`
// FirstVerified 表示需要触发实名激活:首次实名,或二次实名完成(此时 first_realname_at 不变)。
FirstVerified bool `json:"first_verified"`
ObservedAt time.Time `json:"observed_at"`
Source string `json:"source"`
@@ -175,6 +176,27 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
stale = true
return nil
}
realnameRecord, realnameSnapshot, loadErr := loadRealnameTime(ctx, tx, card.ID)
if loadErr != nil {
return loadErr
}
resetGate := domain.EvaluateRealnameResetGate(realnameSnapshot, observation)
if resetGate == domain.RealnameResetGateBlocked {
// 等待二次实名期间读到的仍是旧实名(上游实名时间不晚于清除前时间,或没有上游时间):不改实名状态,只记检查时间。
decision = domain.RealnameDecision{BeforeStatus: card.RealNameStatus, AfterStatus: card.RealNameStatus,
ReversalCount: card.RealnameReversalCount, ReversalStartedAt: card.RealnameReversalStartedAt}
checked := map[string]any{"last_real_name_check_at": observation.Metadata.ObservedAt}
if observation.Metadata.Source != constants.CardObservationSourceManualOverride {
checked["last_sync_time"] = observation.Metadata.ObservedAt
}
if err := tx.Model(&model.IotCard{}).Where("id = ?", card.ID).Updates(checked).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "更新卡实名检查时间失败")
}
s.warnLogger().Info("等待二次实名的卡读到旧实名,不覆盖",
zap.Uint("card_id", card.ID), zap.String("observation_id", observation.Metadata.ObservationID),
zap.Timep("upstream_realname_at", observation.UpstreamRealnameAt), zap.Timep("baseline_at", realnameSnapshot.ResetBaselineAt))
return nil
}
nextDecision, decisionErr := domain.ApplyRealname(domain.CardRealnameSnapshot{
CardID: card.ID, Status: card.RealNameStatus, FirstRealnameAt: card.FirstRealnameAt,
ReversalCount: card.RealnameReversalCount, ReversalStartedAt: card.RealnameReversalStartedAt,
@@ -207,11 +229,16 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
if result.RowsAffected != 1 {
return errors.New(errors.CodeConflict, "卡实名状态已被其他请求更新")
}
if observation.Verified && decision.AfterStatus == constants.RealNameStatusVerified {
if err := applyRealnameTime(ctx, tx, &card, realnameRecord, observation, resetGate); err != nil {
return err
}
}
if decision.StatusChanged {
eventID := realnameChangedEventID(card.ID, observation.Metadata.ObservationID)
if err := s.eventWriter.AppendRealname(ctx, tx, RealnameChangedEvent{
EventID: eventID, CardID: card.ID, BeforeStatus: card.RealNameStatus, AfterStatus: decision.AfterStatus,
FirstVerified: decision.FirstVerified, ObservedAt: observation.Metadata.ObservedAt,
FirstVerified: decision.FirstVerified || resetGate == domain.RealnameResetGateCompleted, ObservedAt: observation.Metadata.ObservedAt,
Source: observation.Metadata.Source, Scene: observation.Metadata.Scene,
RequestID: observation.Metadata.RequestID, CorrelationID: observation.Metadata.CorrelationID,
}); err != nil {

View File

@@ -0,0 +1,177 @@
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
}

View File

@@ -0,0 +1,96 @@
package cardobservation
import (
"context"
"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"
"gorm.io/gorm"
)
// loadRealnameTime 在调用方事务中读取卡当前实名记录;调用方已锁定卡行,同一张卡的写入因此串行。
func loadRealnameTime(ctx context.Context, tx *gorm.DB, cardID uint) (*model.IotCardRealname, domain.RealnameTimeSnapshot, error) {
var record model.IotCardRealname
err := tx.WithContext(ctx).Where("card_id = ?", cardID).Take(&record).Error
if err == gorm.ErrRecordNotFound {
return nil, domain.RealnameTimeSnapshot{}, nil
}
if err != nil {
return nil, domain.RealnameTimeSnapshot{}, errors.Wrap(errors.CodeDatabaseError, err, "查询卡当前实名记录失败")
}
return &record, realnameTimeSnapshot(&record), nil
}
func realnameTimeSnapshot(record *model.IotCardRealname) domain.RealnameTimeSnapshot {
if record == nil {
return domain.RealnameTimeSnapshot{}
}
return domain.RealnameTimeSnapshot{
Exists: true, RealnameAt: record.RealnameAt, RealnameAtSource: record.RealnameAtSource,
UpstreamRealnameAt: record.UpstreamRealnameAt, FirstObservedAt: record.FirstObservedAt,
ResetStatus: record.ResetStatus, ResetBaselineAt: record.ResetBaselineAt,
}
}
// applyRealnameTime 在卡已被采纳为已实名后更新当前实名记录;只有实名时间变化才写历史。
func applyRealnameTime(ctx context.Context, tx *gorm.DB, card *model.IotCard, record *model.IotCardRealname,
observation domain.RealnameObservation, gate domain.RealnameResetGate) error {
decision := domain.DecideRealnameTime(realnameTimeSnapshot(record), observation, gate)
if !decision.Changed {
return nil
}
now := time.Now()
var resetBatchID *uint
if record != nil {
resetBatchID = record.ResetBatchID
}
if record == nil {
created := model.IotCardRealname{
CardID: card.ID, RealnameAt: decision.RealnameAt, RealnameAtSource: decision.Source,
UpstreamRealnameAt: decision.UpstreamRealnameAt, FirstObservedAt: decision.FirstObservedAt,
ResetStatus: constants.RealnameResetStatusNone, CreatedAt: now, UpdatedAt: now,
}
if err := tx.WithContext(ctx).Create(&created).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "创建卡当前实名记录失败")
}
} else {
updates := map[string]any{
"realname_at": decision.RealnameAt, "realname_at_source": decision.Source,
"upstream_realname_at": decision.UpstreamRealnameAt, "first_observed_at": decision.FirstObservedAt,
"updated_at": now,
}
if decision.ClearReset {
updates["reset_status"] = constants.RealnameResetStatusNone
updates["reset_at"] = nil
updates["reset_baseline_at"] = nil
updates["reset_batch_id"] = nil
}
if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ?", record.ID).Updates(updates).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "更新卡当前实名记录失败")
}
}
if decision.ClearReset && resetBatchID != nil {
if err := tx.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{}).Where("id = ?", *resetBatchID).
Updates(map[string]any{"completed_count": gorm.Expr("completed_count + 1"), "updated_at": now}).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "更新二次实名批次完成数失败")
}
}
if !decision.WriteHistory {
return nil
}
history := model.IotCardRealnameHistory{
CardID: card.ID, ICCID: card.ICCID, BeforeAt: decision.BeforeAt, AfterAt: decision.RealnameAt,
AfterSource: decision.Source, ChangeType: decision.ChangeType, ObservationSource: observation.Metadata.Source,
ObservedAt: observation.Metadata.ObservedAt, CreatedAt: now,
}
if decision.ClearReset {
history.ResetBatchID = resetBatchID
}
if err := tx.WithContext(ctx).Create(&history).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名时间历史失败")
}
return nil
}

View File

@@ -223,6 +223,10 @@ func (r *Resolver) applyExpire(ctx context.Context, tx *gorm.DB, usage *model.Pa
return ResolveResult{Decision: packagedomain.SilenceDecisionExpire, Changed: true, Status: constants.SilenceStatusExpired}, nil
}
// cardRealnameAtExpr 是卡当前实名时间:取卡当前实名记录的实名时间(上游 archiveTime 优先,见 add-realname-time-history);
// 还没有当前实名记录的卡(上线迁移前后的空窗)回退到 first_realname_at。
const cardRealnameAtExpr = "CASE WHEN r.id IS NULL THEN c.first_realname_at ELSE r.realname_at END"
// realnameFacts 是判定所需的资产实名事实(技术方案 §5.1)。
type realnameFacts struct {
realnamed bool
@@ -239,15 +243,16 @@ type boundCardRow struct {
}
// loadRealnameFacts 读取实名事实:
// - 卡:first_realname_at;已实名但时间为空时视为期内实名并补写。
// - 卡:当前实名时间;已实名但时间为空时视为期内实名并补写。
// - 设备:所有已绑定且已实名卡中 max(卡实名时间, 绑定时间) 的最小值,使截止后才绑定的已实名卡不能倒推为期内实名;
// 卡实名时间为空时按绑定时间计并补写卡的实名时间。
func loadRealnameFacts(ctx context.Context, tx *gorm.DB, usage *model.PackageUsage) (realnameFacts, error) {
if usage.DeviceID > 0 {
var rows []boundCardRow
err := tx.WithContext(ctx).Table("tb_device_sim_binding AS b").
Select("c.id AS card_id, c.real_name_status, c.first_realname_at, b.bind_time, b.created_at AS bind_created_at").
Select("c.id AS card_id, c.real_name_status, "+cardRealnameAtExpr+" AS first_realname_at, b.bind_time, b.created_at AS bind_created_at").
Joins("JOIN tb_iot_card AS c ON c.id = b.iot_card_id AND c.deleted_at IS NULL").
Joins("LEFT JOIN tb_iot_card_realname AS r ON r.card_id = c.id").
Where("b.device_id = ? AND b.bind_status = ? AND b.deleted_at IS NULL", usage.DeviceID, constants.BindStatusBound).
Where("c.real_name_status = ?", constants.RealNameStatusVerified).
Scan(&rows).Error
@@ -277,22 +282,25 @@ func loadRealnameFacts(ctx context.Context, tx *gorm.DB, usage *model.PackageUsa
if usage.IotCardID == 0 {
return realnameFacts{}, nil
}
var card model.IotCard
if err := tx.WithContext(ctx).Select("id", "real_name_status", "first_realname_at").
Where("id = ?", usage.IotCardID).First(&card).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return realnameFacts{}, nil
}
var cards []boundCardRow
if err := tx.WithContext(ctx).Table("tb_iot_card AS c").
Select("c.id AS card_id, c.real_name_status, "+cardRealnameAtExpr+" AS first_realname_at").
Joins("LEFT JOIN tb_iot_card_realname AS r ON r.card_id = c.id").
Where("c.id = ?", usage.IotCardID).Limit(1).Scan(&cards).Error; err != nil {
return realnameFacts{}, errors.Wrap(errors.CodeDatabaseError, err, "查询卡实名事实失败")
}
if len(cards) == 0 {
return realnameFacts{}, nil
}
card := cards[0]
facts := realnameFacts{realnamed: card.RealNameStatus == constants.RealNameStatusVerified, realnameAt: card.FirstRealnameAt}
if facts.realnamed && card.FirstRealnameAt == nil {
facts.backfillCardIDs = []uint{card.ID}
facts.backfillCardIDs = []uint{card.CardID}
}
return facts, nil
}
// backfillRealnameAt 为已实名但实名时间为空的卡补写 first_realname_at(只写为空的,返回补写数量)。
// backfillRealnameAt 为已实名但实名时间为空的卡补写实名时间(first_realname_at 与当前实名记录都只写为空的,返回补写数量)。
func backfillRealnameAt(ctx context.Context, tx *gorm.DB, facts realnameFacts, now time.Time) (int64, error) {
if len(facts.backfillCardIDs) == 0 {
return 0, nil
@@ -303,6 +311,9 @@ func backfillRealnameAt(ctx context.Context, tx *gorm.DB, facts realnameFacts, n
if result.Error != nil {
return 0, errors.Wrap(errors.CodeDatabaseError, result.Error, "补写卡实名时间失败")
}
if err := backfillCurrentRealnameAt(ctx, tx, facts.backfillCardIDs, now); err != nil {
return 0, err
}
return result.RowsAffected, nil
}
@@ -326,3 +337,44 @@ func (r *Resolver) AllowActivationInTx(ctx context.Context, tx *gorm.DB, usage *
}
return !result.Blocked(), nil
}
// backfillCurrentRealnameAt 为已实名但当前实名时间为空的卡写入当前实名记录(来源"首次读到",取判定时间)并记一条首次实名历史。
// 二次实名等待中的卡是未实名状态,不会进入这里。
func backfillCurrentRealnameAt(ctx context.Context, tx *gorm.DB, cardIDs []uint, now time.Time) error {
var rows []struct {
CardID uint `gorm:"column:card_id"`
ICCID string `gorm:"column:iccid"`
RecordID *uint `gorm:"column:record_id"`
Realname *time.Time `gorm:"column:realname_at"`
}
if err := tx.WithContext(ctx).Table("tb_iot_card AS c").
Select("c.id AS card_id, c.iccid, r.id AS record_id, r.realname_at").
Joins("LEFT JOIN tb_iot_card_realname AS r ON r.card_id = c.id").
Where("c.id IN ? AND c.real_name_status = ?", cardIDs, constants.RealNameStatusVerified).
Scan(&rows).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询卡当前实名记录失败")
}
for _, row := range rows {
if row.Realname != nil {
continue
}
updates := map[string]any{"realname_at": now, "realname_at_source": constants.RealnameAtSourceFirstObserved, "updated_at": now}
if row.RecordID == nil {
record := model.IotCardRealname{CardID: row.CardID, RealnameAt: &now, RealnameAtSource: constants.RealnameAtSourceFirstObserved,
FirstObservedAt: &now, ResetStatus: constants.RealnameResetStatusNone, CreatedAt: now, UpdatedAt: now}
if err := tx.WithContext(ctx).Create(&record).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "补写卡当前实名记录失败")
}
} else if err := tx.WithContext(ctx).Model(&model.IotCardRealname{}).Where("id = ? AND realname_at IS NULL", *row.RecordID).
Updates(updates).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "补写卡当前实名时间失败")
}
history := model.IotCardRealnameHistory{CardID: row.CardID, ICCID: row.ICCID, AfterAt: &now,
AfterSource: constants.RealnameAtSourceFirstObserved, ChangeType: constants.RealnameChangeFirst,
ObservationSource: "package_silence", ObservedAt: now, CreatedAt: now}
if err := tx.WithContext(ctx).Create(&history).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入卡实名时间历史失败")
}
}
return nil
}

View File

@@ -0,0 +1,259 @@
// Package realnamereset 提供二次实名批次的导入与撤销用例。
// 二次实名:清除卡的实名状态与当前实名时间,之后只有上游 archiveTime 晚于清除前时间才算重新实名(见 add-realname-time-history)。
package realnamereset
import (
"context"
"crypto/rand"
"fmt"
"math/big"
"strings"
"time"
"github.com/bytedance/sonic"
"gorm.io/gorm"
cardobservationapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
"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"
)
// CardResetter 执行单卡二次实名清除与撤销。
type CardResetter interface {
ResetRealname(ctx context.Context, command cardobservationapp.RealnameResetCommand) error
RevertRealnameReset(ctx context.Context, command cardobservationapp.RealnameResetCommand) error
}
// PermissionChecker 校验后台账号权限点。
type PermissionChecker interface {
CheckPermission(ctx context.Context, userID uint, permCode string, platform string) (bool, error)
}
// Service 是二次实名批次用例。
type Service struct {
db *gorm.DB
resetter CardResetter
perms PermissionChecker
now func() time.Time
}
// NewService 创建二次实名批次用例。
func NewService(db *gorm.DB, resetter CardResetter, perms PermissionChecker) *Service {
return &Service{db: db, resetter: resetter, perms: perms, now: time.Now}
}
// resetTarget 是一行资产号展开出的一张卡。
type resetTarget struct {
CardID uint `gorm:"column:id"`
ICCID string `gorm:"column:iccid"`
}
// Import 导入二次实名名单:逐行展开为卡并逐卡清除,不合格的行记录原因跳过,不影响其他行。
func (s *Service) Import(ctx context.Context, req dto.RealnameResetImportRequest) (*dto.RealnameResetBatchResponse, error) {
operatorID, err := s.authorize(ctx)
if err != nil {
return nil, err
}
identifiers := normalizeIdentifiers(req.Identifiers)
if len(identifiers) == 0 {
return nil, errors.New(errors.CodeInvalidParam, "请导入至少一个资产号")
}
if len(identifiers) > constants.RealnameResetBatchMaxRows {
return nil, errors.New(errors.CodeInvalidParam, fmt.Sprintf("单批最多导入 %d 个资产号", constants.RealnameResetBatchMaxRows))
}
now := s.now()
batch := &model.IotCardRealnameResetBatch{
BatchNo: generateBatchNo(now), ImportFileKey: strings.TrimSpace(req.ImportFileKey), Reason: strings.TrimSpace(req.Reason),
Items: []byte("[]"), OperatorID: operatorID, OperatorName: middleware.GetUsernameFromContext(ctx), CreatedAt: now, UpdatedAt: now,
}
if err := s.db.WithContext(ctx).Create(batch).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "创建二次实名批次失败")
}
items := make([]dto.RealnameResetItem, 0, len(identifiers))
seen := make(map[uint]bool)
succeeded, skipped := 0, 0
for index, identifier := range identifiers {
rowNo := index + 1
targets, resolveErr := s.resolveTargets(ctx, identifier)
if resolveErr != nil {
return nil, resolveErr
}
if len(targets) == 0 {
items = append(items, skippedItem(rowNo, identifier, resetTarget{}, "资产不存在或设备未绑定卡"))
skipped++
continue
}
for _, target := range targets {
if seen[target.CardID] {
items = append(items, skippedItem(rowNo, identifier, target, "同一张卡在名单中重复"))
skipped++
continue
}
seen[target.CardID] = true
resetErr := s.resetter.ResetRealname(ctx, cardobservationapp.RealnameResetCommand{CardID: target.CardID, BatchID: batch.ID, OperatorID: operatorID})
switch {
case resetErr == nil:
items = append(items, dto.RealnameResetItem{RowNo: rowNo, Input: identifier, CardID: target.CardID, ICCID: target.ICCID,
Result: constants.RealnameResetItemPending})
succeeded++
case isExpectedResetError(resetErr):
items = append(items, skippedItem(rowNo, identifier, target, errorMessage(resetErr)))
skipped++
default:
items = append(items, dto.RealnameResetItem{RowNo: rowNo, Input: identifier, CardID: target.CardID, ICCID: target.ICCID,
Result: constants.RealnameResetItemFailed, Reason: errorMessage(resetErr)})
skipped++
}
}
}
encoded, err := sonic.Marshal(items)
if err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "编码二次实名批次结果失败")
}
batch.Items, batch.TotalCount, batch.SucceededCount, batch.SkippedCount = encoded, len(items), succeeded, skipped
if err := s.db.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{}).Where("id = ?", batch.ID).Updates(map[string]any{
"items": encoded, "total_count": len(items), "succeeded_count": succeeded, "skipped_count": skipped, "updated_at": s.now(),
}).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "更新二次实名批次结果失败")
}
return &dto.RealnameResetBatchResponse{
ID: batch.ID, BatchNo: batch.BatchNo, Reason: batch.Reason, ImportFileKey: batch.ImportFileKey,
TotalCount: len(items), SucceededCount: succeeded, SkippedCount: skipped, PendingCount: succeeded,
OperatorID: operatorID, OperatorName: batch.OperatorName, CreatedAt: batch.CreatedAt, Items: withResultNames(items),
}, nil
}
// Revert 撤销批次中仍在等待二次实名的卡;card_ids 为空时撤销整批。
func (s *Service) Revert(ctx context.Context, req dto.RealnameResetRevertRequest) (*dto.RealnameResetRevertResponse, error) {
operatorID, err := s.authorize(ctx)
if err != nil {
return nil, err
}
var batch model.IotCardRealnameResetBatch
if err := s.db.WithContext(ctx).Select("id").Where("id = ?", req.ID).Take(&batch).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeNotFound, "二次实名批次不存在")
}
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询二次实名批次失败")
}
query := s.db.WithContext(ctx).Model(&model.IotCardRealname{}).
Where("reset_batch_id = ? AND reset_status = ?", batch.ID, constants.RealnameResetStatusPending)
if len(req.CardIDs) > 0 {
query = query.Where("card_id IN ?", req.CardIDs)
}
var cardIDs []uint
if err := query.Pluck("card_id", &cardIDs).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询等待二次实名的卡失败")
}
result := &dto.RealnameResetRevertResponse{}
for _, cardID := range cardIDs {
if err := s.resetter.RevertRealnameReset(ctx, cardobservationapp.RealnameResetCommand{CardID: cardID, BatchID: batch.ID, OperatorID: operatorID}); err != nil {
result.FailedCount++
result.Failures = append(result.Failures, fmt.Sprintf("卡 %d:%s", cardID, errorMessage(err)))
continue
}
result.RevertedCount++
}
if result.RevertedCount > 0 {
if err := s.db.WithContext(ctx).Model(&model.IotCardRealnameResetBatch{}).Where("id = ?", batch.ID).Updates(map[string]any{
"reverted_count": gorm.Expr("reverted_count + ?", result.RevertedCount), "updated_at": s.now(),
}).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "更新二次实名批次撤销数失败")
}
}
return result, nil
}
// authorize 二次实名只允许平台账号,且需要 iot_card:realname_reset 权限(超级管理员不受限)。
func (s *Service) authorize(ctx context.Context) (uint, error) {
operatorID := middleware.GetUserIDFromContext(ctx)
switch middleware.GetUserTypeFromContext(ctx) {
case constants.UserTypeSuperAdmin:
return operatorID, nil
case constants.UserTypePlatform:
default:
return 0, errors.New(errors.CodeForbidden, "仅平台账号可办理二次实名")
}
if s.perms == nil {
return 0, errors.New(errors.CodeForbidden)
}
allowed, err := s.perms.CheckPermission(ctx, operatorID, constants.PermissionIotCardRealnameReset, constants.PlatformWeb)
if err != nil {
return 0, err
}
if !allowed {
return 0, errors.New(errors.CodeForbidden, "无二次实名权限")
}
return operatorID, nil
}
// resolveTargets 把资产号展开为卡:先按卡 ICCID / 虚拟号,再按设备虚拟号 / IMEI 取设备当前全部绑定卡。
func (s *Service) resolveTargets(ctx context.Context, identifier string) ([]resetTarget, error) {
var cards []resetTarget
if err := s.db.WithContext(ctx).Table("tb_iot_card").Select("id, iccid").
Where("deleted_at IS NULL AND (iccid = ? OR virtual_no = ?)", identifier, identifier).
Order("id").Limit(1).Scan(&cards).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "按资产号查询卡失败")
}
if len(cards) > 0 {
return cards, nil
}
if err := s.db.WithContext(ctx).Table("tb_device AS d").Select("c.id, c.iccid").
Joins("JOIN tb_device_sim_binding AS b ON b.device_id = d.id AND b.bind_status = ? AND b.deleted_at IS NULL", constants.BindStatusBound).
Joins("JOIN tb_iot_card AS c ON c.id = b.iot_card_id AND c.deleted_at IS NULL").
Where("d.deleted_at IS NULL AND (d.virtual_no = ? OR d.imei = ?)", identifier, identifier).
Order("c.id").Scan(&cards).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "按资产号查询设备绑定卡失败")
}
return cards, nil
}
func normalizeIdentifiers(raw []string) []string {
result := make([]string, 0, len(raw))
seen := make(map[string]bool, len(raw))
for _, value := range raw {
value = strings.TrimSpace(value)
if value == "" || seen[value] {
continue
}
seen[value] = true
result = append(result, value)
}
return result
}
func isExpectedResetError(err error) bool {
return err == cardobservationapp.ErrRealnameResetNotVerified || err == cardobservationapp.ErrRealnameResetNoUpstream ||
err == cardobservationapp.ErrRealnameResetAlreadyReset
}
func errorMessage(err error) string {
if appErr, ok := err.(*errors.AppError); ok && appErr.Message != "" {
return appErr.Message
}
return err.Error()
}
func skippedItem(rowNo int, input string, target resetTarget, reason string) dto.RealnameResetItem {
return dto.RealnameResetItem{RowNo: rowNo, Input: input, CardID: target.CardID, ICCID: target.ICCID,
Result: constants.RealnameResetItemSkipped, Reason: reason}
}
// withResultNames 补结果中文名。
func withResultNames(items []dto.RealnameResetItem) []dto.RealnameResetItem {
for index := range items {
items[index].ResultName = constants.RealnameResetItemName(items[index].Result)
}
return items
}
func generateBatchNo(now time.Time) string {
suffix, err := rand.Int(rand.Reader, big.NewInt(10000))
if err != nil {
suffix = big.NewInt(now.UnixNano() % 10000)
}
return fmt.Sprintf("%s%s%04d", constants.RealnameResetBatchNoPrefix, now.Format("20060102150405"), suffix.Int64())
}