fix: 换货迁移按套餐是否已开始与新资产占位决定主套餐状态
- 未开始的主套餐(无生效、到期时间且无用量)迁移为待生效,新资产不满足实名条件(行业卡/已实名/无需实名)时标记等实名激活 - 已开始的主套餐在新资产无当前主套餐时原样迁移;新资产已有当前主套餐时改为待生效排队、清空周期与用量 - 迁移后重排新资产主套餐优先级,保证同一载体只有一个当前主套餐 - 换货审计记录套餐状态、优先级、用量的前后值 OpenSpec: fix-exchange-migration-package-state Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -216,7 +216,7 @@ func (s *Service) buildCardExchangeCompletionResources(
|
||||
return nil, err
|
||||
}
|
||||
resources = append(resources, transactionResources...)
|
||||
usageResources, err := loadCardExchangePackageUsageResources(ctx, tx, migration.PackageUsageIDs, oldCard.ID, newCard.ID)
|
||||
usageResources, err := loadCardExchangePackageUsageResources(ctx, tx, migration.PackageUsageIDs, migration.PackageUsageChanges, oldCard.ID, newCard.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -377,24 +377,46 @@ func loadExchangeTransactionResources(ctx context.Context, tx *gorm.DB, exchange
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
func loadCardExchangePackageUsageResources(ctx context.Context, tx *gorm.DB, ids []uint, oldCardID, newCardID uint) ([]audit.ResourceInput, error) {
|
||||
return loadExchangePackageUsageResources(ctx, tx, ids, "iot_card_id", oldCardID, newCardID, constants.AuditResourceRoleCardExchangePackageUsage, "卡")
|
||||
func loadCardExchangePackageUsageResources(ctx context.Context, tx *gorm.DB, ids []uint, changes map[uint]*packageUsageStateChange, oldCardID, newCardID uint) ([]audit.ResourceInput, error) {
|
||||
return loadExchangePackageUsageResources(ctx, tx, ids, changes, "iot_card_id", oldCardID, newCardID, constants.AuditResourceRoleCardExchangePackageUsage, "卡")
|
||||
}
|
||||
|
||||
func loadExchangePackageUsageResources(ctx context.Context, tx *gorm.DB, ids []uint, assetIDField string, oldAssetID, newAssetID uint, role, assetName string) ([]audit.ResourceInput, error) {
|
||||
if len(ids) == 0 {
|
||||
func loadExchangePackageUsageResources(ctx context.Context, tx *gorm.DB, ids []uint, changes map[uint]*packageUsageStateChange, assetIDField string, oldAssetID, newAssetID uint, role, assetName string) ([]audit.ResourceInput, error) {
|
||||
migrated := make(map[uint]bool, len(ids))
|
||||
allIDs := make([]uint, 0, len(ids)+len(changes))
|
||||
for _, id := range ids {
|
||||
migrated[id] = true
|
||||
allIDs = append(allIDs, id)
|
||||
}
|
||||
for id := range changes {
|
||||
if !migrated[id] {
|
||||
allIDs = append(allIDs, id)
|
||||
}
|
||||
}
|
||||
if len(allIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var rows []model.PackageUsage
|
||||
if err := tx.WithContext(ctx).Where("id IN ?", ids).Order("id ASC").Find(&rows).Error; err != nil {
|
||||
if err := tx.WithContext(ctx).Where("id IN ?", allIDs).Order("id ASC").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询"+assetName+"换货套餐权益失败")
|
||||
}
|
||||
orderIDs := make(map[uint]struct{}, len(rows))
|
||||
packageIDs := make(map[uint]struct{}, len(rows))
|
||||
resources := make([]audit.ResourceInput, 0, len(rows)*3)
|
||||
for _, row := range rows {
|
||||
resource := audit.PackageUsageResource(&row, constants.AuditResourceRelationAffected, role,
|
||||
map[string]any{assetIDField: oldAssetID}, map[string]any{assetIDField: newAssetID})
|
||||
beforeData, afterData := map[string]any{}, map[string]any{}
|
||||
if migrated[row.ID] {
|
||||
beforeData[assetIDField], afterData[assetIDField] = oldAssetID, newAssetID
|
||||
}
|
||||
if change := changes[row.ID]; change != nil {
|
||||
for key, value := range change.Before {
|
||||
beforeData[key] = value
|
||||
}
|
||||
for key, value := range change.After {
|
||||
afterData[key] = value
|
||||
}
|
||||
}
|
||||
resource := audit.PackageUsageResource(&row, constants.AuditResourceRelationAffected, role, beforeData, afterData)
|
||||
resource.SubjectVisibility = constants.AuditSubjectInternalOnly
|
||||
resources = append(resources, resource)
|
||||
orderIDs[row.OrderID] = struct{}{}
|
||||
|
||||
@@ -229,7 +229,7 @@ func (s *Service) buildDeviceExchangeCompletionResources(
|
||||
return nil, err
|
||||
}
|
||||
resources = append(resources, transactions...)
|
||||
usages, err := loadDeviceExchangePackageUsageResources(ctx, tx, migration.PackageUsageIDs, oldDevice.ID, newDevice.ID)
|
||||
usages, err := loadDeviceExchangePackageUsageResources(ctx, tx, migration.PackageUsageIDs, migration.PackageUsageChanges, oldDevice.ID, newDevice.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -337,8 +337,8 @@ func loadDeviceExchangeTransactionResources(ctx context.Context, tx *gorm.DB, ex
|
||||
return loadExchangeTransactionResources(ctx, tx, exchangeNo, constants.AuditResourceRoleDeviceExchangeWalletTransaction, "设备")
|
||||
}
|
||||
|
||||
func loadDeviceExchangePackageUsageResources(ctx context.Context, tx *gorm.DB, ids []uint, oldDeviceID, newDeviceID uint) ([]audit.ResourceInput, error) {
|
||||
return loadExchangePackageUsageResources(ctx, tx, ids, "device_id", oldDeviceID, newDeviceID, constants.AuditResourceRoleDeviceExchangePackageUsage, "设备")
|
||||
func loadDeviceExchangePackageUsageResources(ctx context.Context, tx *gorm.DB, ids []uint, changes map[uint]*packageUsageStateChange, oldDeviceID, newDeviceID uint) ([]audit.ResourceInput, error) {
|
||||
return loadExchangePackageUsageResources(ctx, tx, ids, changes, "device_id", oldDeviceID, newDeviceID, constants.AuditResourceRoleDeviceExchangePackageUsage, "设备")
|
||||
}
|
||||
|
||||
func (s *Service) recordExchangeOrderFailure(ctx context.Context, cardActionCode, summary string, order *model.ExchangeOrder, businessErr error) {
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
type exchangeMigrationResult struct {
|
||||
Balance int64
|
||||
PackageUsageIDs []uint
|
||||
// PackageUsageChanges 记录因迁移规则改变状态、优先级或用量的套餐使用记录(含新资产原有主套餐)
|
||||
PackageUsageChanges map[uint]*packageUsageStateChange
|
||||
}
|
||||
|
||||
func (s *Service) executeMigrationWithTx(ctx context.Context, tx *gorm.DB, order *model.ExchangeOrder, oldAsset, newAsset *resolvedExchangeAsset) (*exchangeMigrationResult, error) {
|
||||
@@ -22,7 +24,7 @@ func (s *Service) executeMigrationWithTx(ctx context.Context, tx *gorm.DB, order
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeExchangeMigrationFailed, err, "执行钱包迁移失败")
|
||||
}
|
||||
usageIDs, err := s.migratePackageUsageWithTx(ctx, tx, oldAsset, newAsset)
|
||||
usageIDs, usageChanges, err := s.migratePackageUsageWithTx(ctx, tx, oldAsset, newAsset)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeExchangeMigrationFailed, err, "迁移套餐使用记录失败")
|
||||
}
|
||||
@@ -32,7 +34,7 @@ func (s *Service) executeMigrationWithTx(ctx context.Context, tx *gorm.DB, order
|
||||
if err = s.copyResourceTagsWithTx(ctx, tx, oldAsset, newAsset); err != nil {
|
||||
return nil, errors.Wrap(errors.CodeExchangeMigrationFailed, err, "复制资产标签失败")
|
||||
}
|
||||
return &exchangeMigrationResult{Balance: migrationBalance, PackageUsageIDs: usageIDs}, nil
|
||||
return &exchangeMigrationResult{Balance: migrationBalance, PackageUsageIDs: usageIDs, PackageUsageChanges: usageChanges}, nil
|
||||
}
|
||||
|
||||
func (s *Service) transferWalletBalanceWithTx(ctx context.Context, tx *gorm.DB, order *model.ExchangeOrder, oldAsset, newAsset *resolvedExchangeAsset) (int64, error) {
|
||||
@@ -101,39 +103,79 @@ func (s *Service) transferWalletBalanceWithTx(ctx context.Context, tx *gorm.DB,
|
||||
return migrationBalance, nil
|
||||
}
|
||||
|
||||
func (s *Service) migratePackageUsageWithTx(ctx context.Context, tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) ([]uint, error) {
|
||||
query := tx.WithContext(ctx).Model(&model.PackageUsage{}).Where("status IN ?", []int{constants.PackageUsageStatusPending, constants.PackageUsageStatusActive, constants.PackageUsageStatusDepleted})
|
||||
if oldAsset.AssetType == constants.ExchangeAssetTypeIotCard {
|
||||
query = query.Where("iot_card_id = ?", oldAsset.AssetID)
|
||||
} else {
|
||||
query = query.Where("device_id = ?", oldAsset.AssetID)
|
||||
// migratePackageUsageWithTx 把旧资产待生效、生效中、已用完的套餐使用记录迁到新资产,
|
||||
// 并按"是否已开始、新资产实名条件、新资产是否已有当前主套餐"决定主套餐迁移后的状态与排队顺序。
|
||||
func (s *Service) migratePackageUsageWithTx(ctx context.Context, tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) ([]uint, map[uint]*packageUsageStateChange, error) {
|
||||
column := carrierColumn(oldAsset.AssetType)
|
||||
oldUsages, err := lockLiveUsagesWithTx(ctx, tx, column, oldAsset.AssetID, false)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(oldUsages) == 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
newMains, err := lockLiveUsagesWithTx(ctx, tx, carrierColumn(newAsset.AssetType), newAsset.AssetID, true)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var usageIDs []uint
|
||||
if err := query.Pluck("id", &usageIDs).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐使用记录失败")
|
||||
usageIDs := make([]uint, 0, len(oldUsages))
|
||||
oldMains := make([]*model.PackageUsage, 0, len(oldUsages))
|
||||
for _, usage := range oldUsages {
|
||||
usageIDs = append(usageIDs, usage.ID)
|
||||
if usage.MasterUsageID == nil {
|
||||
oldMains = append(oldMains, usage)
|
||||
}
|
||||
}
|
||||
|
||||
if len(usageIDs) == 0 {
|
||||
if err = tx.WithContext(ctx).Model(&model.PackageUsage{}).Where("id IN ?", usageIDs).
|
||||
Updates(map[string]any{column: newAsset.AssetID, "updated_at": time.Now()}).Error; err != nil {
|
||||
return nil, nil, errors.Wrap(errors.CodeDatabaseError, err, "迁移套餐使用记录失败")
|
||||
}
|
||||
if err = tx.WithContext(ctx).Model(&model.PackageUsageDailyRecord{}).Where("package_usage_id IN ?", usageIDs).Update("updated_at", gorm.Expr("updated_at")).Error; err != nil {
|
||||
return nil, nil, errors.Wrap(errors.CodeDatabaseError, err, "迁移套餐日记录失败")
|
||||
}
|
||||
|
||||
changes, err := s.arrangeMigratedMainsWithTx(ctx, tx, oldMains, newMains, newAsset)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return usageIDs, changes, nil
|
||||
}
|
||||
|
||||
// arrangeMigratedMainsWithTx 决定迁入主套餐状态并重排新资产主套餐优先级,保证同一载体最多一个当前主套餐。
|
||||
func (s *Service) arrangeMigratedMainsWithTx(ctx context.Context, tx *gorm.DB, oldMains, newMains []*model.PackageUsage, newAsset *resolvedExchangeAsset) (map[uint]*packageUsageStateChange, error) {
|
||||
if len(oldMains) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
updates := map[string]any{"updated_at": time.Now()}
|
||||
if oldAsset.AssetType == constants.ExchangeAssetTypeIotCard {
|
||||
updates["iot_card_id"] = newAsset.AssetID
|
||||
} else {
|
||||
updates["device_id"] = newAsset.AssetID
|
||||
now := time.Now()
|
||||
dailyRecords, err := loadDailyRecordUsageIDsWithTx(ctx, tx, oldMains)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.WithContext(ctx).Model(&model.PackageUsage{}).Where("id IN ?", usageIDs).Updates(updates).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "迁移套餐使用记录失败")
|
||||
newHasCurrent := false
|
||||
for _, usage := range newMains {
|
||||
if isCurrentMainUsage(usage, now) {
|
||||
newHasCurrent = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.WithContext(ctx).Model(&model.PackageUsageDailyRecord{}).Where("package_usage_id IN ?", usageIDs).Update("updated_at", gorm.Expr("updated_at")).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "迁移套餐日记录失败")
|
||||
var realnameChecked, realnameOK bool
|
||||
realnameSatisfied := func() (bool, error) {
|
||||
if !realnameChecked {
|
||||
ok, checkErr := newAssetRealnameSatisfiedWithTx(ctx, tx, newAsset)
|
||||
if checkErr != nil {
|
||||
return false, checkErr
|
||||
}
|
||||
realnameChecked, realnameOK = true, ok
|
||||
}
|
||||
return realnameOK, nil
|
||||
}
|
||||
|
||||
return usageIDs, nil
|
||||
plans, promoted, err := planMigratedMains(oldMains, dailyRecords, newHasCurrent, now, realnameSatisfied)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return applyMigratedMainPlansWithTx(ctx, tx, plans, buildMainQueueOrder(newMains, promoted, plans, now))
|
||||
}
|
||||
|
||||
func (s *Service) copyAccumulatedFieldsWithTx(tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) error {
|
||||
|
||||
289
internal/service/exchange/package_migration.go
Normal file
289
internal/service/exchange/package_migration.go
Normal file
@@ -0,0 +1,289 @@
|
||||
package exchange
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// packageUsageStateChange 记录换货迁移中套餐使用记录状态字段的前后值,供换货审计使用。
|
||||
type packageUsageStateChange struct {
|
||||
Before map[string]any
|
||||
After map[string]any
|
||||
}
|
||||
|
||||
// migratedMainPlan 是旧资产主套餐迁移后的目标状态。
|
||||
type migratedMainPlan struct {
|
||||
usage *model.PackageUsage
|
||||
updates map[string]any // 为空表示状态字段原样保留
|
||||
pending bool // 迁移后为待生效,参与排队
|
||||
}
|
||||
|
||||
func carrierColumn(assetType string) string {
|
||||
if assetType == constants.ExchangeAssetTypeIotCard {
|
||||
return "iot_card_id"
|
||||
}
|
||||
return "device_id"
|
||||
}
|
||||
|
||||
func liveUsageStatuses() []int {
|
||||
return []int{constants.PackageUsageStatusPending, constants.PackageUsageStatusActive, constants.PackageUsageStatusDepleted}
|
||||
}
|
||||
|
||||
// lockLiveUsagesWithTx 锁定载体上待生效、生效中、已用完的套餐使用记录,按优先级、创建时间、标识排序。
|
||||
func lockLiveUsagesWithTx(ctx context.Context, tx *gorm.DB, column string, assetID uint, mainOnly bool) ([]*model.PackageUsage, error) {
|
||||
query := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where(column+" = ?", assetID).
|
||||
Where("status IN ?", liveUsageStatuses())
|
||||
if mainOnly {
|
||||
query = query.Where("master_usage_id IS NULL")
|
||||
}
|
||||
var rows []*model.PackageUsage
|
||||
if err := query.Order("priority ASC, created_at ASC, id ASC").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "锁定套餐使用记录失败")
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// isCurrentMainUsage 与 FindCurrentMainPackageForQueue 口径一致:生效中或已用完且未到期。
|
||||
func isCurrentMainUsage(usage *model.PackageUsage, now time.Time) bool {
|
||||
if usage.Status != constants.PackageUsageStatusActive && usage.Status != constants.PackageUsageStatusDepleted {
|
||||
return false
|
||||
}
|
||||
return usage.ExpiresAt == nil || usage.ExpiresAt.After(now)
|
||||
}
|
||||
|
||||
func isExpiredOccupyingUsage(usage *model.PackageUsage, now time.Time) bool {
|
||||
return (usage.Status == constants.PackageUsageStatusActive || usage.Status == constants.PackageUsageStatusDepleted) &&
|
||||
!isCurrentMainUsage(usage, now)
|
||||
}
|
||||
|
||||
// isUsageStarted 判断套餐是否已开始:有生效时间、有到期时间、有用量、有日流量记录或已用完。
|
||||
// 老系统迁移数据可能只有固定到期时间、没有生效时间,按已开始处理以保留原到期日。
|
||||
func isUsageStarted(usage *model.PackageUsage, hasDailyRecord bool) bool {
|
||||
return usage.ActivatedAt != nil || usage.ExpiresAt != nil || usage.DataUsageMB > 0 || hasDailyRecord ||
|
||||
usage.Status == constants.PackageUsageStatusDepleted
|
||||
}
|
||||
|
||||
func loadDailyRecordUsageIDsWithTx(ctx context.Context, tx *gorm.DB, usages []*model.PackageUsage) (map[uint]bool, error) {
|
||||
result := make(map[uint]bool)
|
||||
if len(usages) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
ids := make([]uint, 0, len(usages))
|
||||
for _, usage := range usages {
|
||||
ids = append(ids, usage.ID)
|
||||
}
|
||||
var withRecords []uint
|
||||
if err := tx.WithContext(ctx).Model(&model.PackageUsageDailyRecord{}).
|
||||
Where("package_usage_id IN ?", ids).Distinct().Pluck("package_usage_id", &withRecords).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询套餐日流量记录失败")
|
||||
}
|
||||
for _, id := range withRecords {
|
||||
result[id] = true
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// resetToPendingUpdates 生成"改为待生效并清空生效周期"的字段更新。
|
||||
func resetToPendingUpdates(pendingRealname, clearUsage bool) map[string]any {
|
||||
updates := map[string]any{
|
||||
"status": constants.PackageUsageStatusPending,
|
||||
"activated_at": nil,
|
||||
"expires_at": nil,
|
||||
"last_reset_at": nil,
|
||||
"next_reset_at": nil,
|
||||
"pending_realname_activation": pendingRealname,
|
||||
}
|
||||
if clearUsage {
|
||||
updates["data_usage_mb"] = int64(0)
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
// isCleanPendingUsage 判断记录是否已是目标待生效状态,避免无变化的写入与审计。
|
||||
func isCleanPendingUsage(usage *model.PackageUsage, pendingRealname bool) bool {
|
||||
return usage.Status == constants.PackageUsageStatusPending && usage.PendingRealnameActivation == pendingRealname &&
|
||||
usage.ActivatedAt == nil && usage.ExpiresAt == nil && usage.LastResetAt == nil && usage.NextResetAt == nil
|
||||
}
|
||||
|
||||
// planMigratedMains 按"是否已开始、新资产实名条件、新资产是否已有当前主套餐"决定旧资产主套餐的迁移状态。
|
||||
// realnameSatisfied 仅在存在未开始的主套餐时被调用。
|
||||
func planMigratedMains(oldMains []*model.PackageUsage, dailyRecords map[uint]bool, newHasCurrent bool, now time.Time,
|
||||
realnameSatisfied func() (bool, error)) ([]migratedMainPlan, *model.PackageUsage, error) {
|
||||
plans := make([]migratedMainPlan, 0, len(oldMains))
|
||||
var promoted *model.PackageUsage
|
||||
for _, usage := range oldMains {
|
||||
if isExpiredOccupyingUsage(usage, now) {
|
||||
plans = append(plans, migratedMainPlan{usage: usage})
|
||||
continue
|
||||
}
|
||||
if !isUsageStarted(usage, dailyRecords[usage.ID]) {
|
||||
satisfied, err := realnameSatisfied()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var updates map[string]any
|
||||
if !isCleanPendingUsage(usage, !satisfied) {
|
||||
updates = resetToPendingUpdates(!satisfied, false)
|
||||
}
|
||||
plans = append(plans, migratedMainPlan{usage: usage, updates: updates, pending: true})
|
||||
continue
|
||||
}
|
||||
if !newHasCurrent && promoted == nil && isCurrentMainUsage(usage, now) {
|
||||
promoted = usage
|
||||
plans = append(plans, migratedMainPlan{usage: usage})
|
||||
continue
|
||||
}
|
||||
plans = append(plans, migratedMainPlan{usage: usage, updates: resetToPendingUpdates(false, true), pending: true})
|
||||
}
|
||||
return plans, promoted, nil
|
||||
}
|
||||
|
||||
// buildMainQueueOrder 迁移后新资产主套餐顺序:当前主套餐 → 新资产原有待生效 → 迁入的待生效。
|
||||
func buildMainQueueOrder(newMains []*model.PackageUsage, promoted *model.PackageUsage, plans []migratedMainPlan, now time.Time) []*model.PackageUsage {
|
||||
ordered := make([]*model.PackageUsage, 0, len(newMains)+len(plans))
|
||||
for _, usage := range newMains {
|
||||
if isCurrentMainUsage(usage, now) {
|
||||
ordered = append(ordered, usage)
|
||||
}
|
||||
}
|
||||
if promoted != nil {
|
||||
ordered = append(ordered, promoted)
|
||||
}
|
||||
for _, usage := range newMains {
|
||||
if usage.Status == constants.PackageUsageStatusPending {
|
||||
ordered = append(ordered, usage)
|
||||
}
|
||||
}
|
||||
for _, plan := range plans {
|
||||
if plan.pending {
|
||||
ordered = append(ordered, plan.usage)
|
||||
}
|
||||
}
|
||||
return ordered
|
||||
}
|
||||
|
||||
func usageStateSnapshot(usage *model.PackageUsage) map[string]any {
|
||||
return map[string]any{
|
||||
"status": usage.Status, "priority": usage.Priority, "data_usage_mb": usage.DataUsageMB,
|
||||
"activated_at": usage.ActivatedAt, "expires_at": usage.ExpiresAt,
|
||||
"last_reset_at": usage.LastResetAt, "next_reset_at": usage.NextResetAt,
|
||||
"pending_realname_activation": usage.PendingRealnameActivation,
|
||||
}
|
||||
}
|
||||
|
||||
func recordStateChange(changes map[uint]*packageUsageStateChange, usage *model.PackageUsage, updates map[string]any) {
|
||||
change, ok := changes[usage.ID]
|
||||
if !ok {
|
||||
change = &packageUsageStateChange{Before: usageStateSnapshot(usage), After: usageStateSnapshot(usage)}
|
||||
changes[usage.ID] = change
|
||||
}
|
||||
for key, value := range updates {
|
||||
change.After[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
func applyUsageUpdatesWithTx(ctx context.Context, tx *gorm.DB, id uint, updates map[string]any) error {
|
||||
values := make(map[string]any, len(updates)+1)
|
||||
for key, value := range updates {
|
||||
values[key] = value
|
||||
}
|
||||
values["updated_at"] = time.Now()
|
||||
if err := tx.WithContext(ctx).Model(&model.PackageUsage{}).Where("id = ?", id).Updates(values).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新迁移套餐状态失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyMigratedMainPlansWithTx 写入迁移主套餐的目标状态并重排新资产主套餐优先级。
|
||||
func applyMigratedMainPlansWithTx(ctx context.Context, tx *gorm.DB, plans []migratedMainPlan, ordered []*model.PackageUsage) (map[uint]*packageUsageStateChange, error) {
|
||||
changes := make(map[uint]*packageUsageStateChange)
|
||||
pendingUpdates := make(map[uint]map[string]any)
|
||||
for _, plan := range plans {
|
||||
if len(plan.updates) > 0 {
|
||||
pendingUpdates[plan.usage.ID] = plan.updates
|
||||
recordStateChange(changes, plan.usage, plan.updates)
|
||||
}
|
||||
}
|
||||
for index, usage := range ordered {
|
||||
priority := index + 1
|
||||
if usage.Priority == priority {
|
||||
continue
|
||||
}
|
||||
updates := pendingUpdates[usage.ID]
|
||||
if updates == nil {
|
||||
updates = make(map[string]any)
|
||||
pendingUpdates[usage.ID] = updates
|
||||
}
|
||||
updates["priority"] = priority
|
||||
recordStateChange(changes, usage, map[string]any{"priority": priority})
|
||||
}
|
||||
for id, updates := range pendingUpdates {
|
||||
if err := applyUsageUpdatesWithTx(ctx, tx, id, updates); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// newAssetRealnameSatisfiedWithTx 判断新资产是否满足实名条件。
|
||||
// 口径同 StopResumeService.isRealnameOK:行业卡、已实名、或适用实名策略为无需实名;设备看自身策略与已绑定卡。
|
||||
func newAssetRealnameSatisfiedWithTx(ctx context.Context, tx *gorm.DB, asset *resolvedExchangeAsset) (bool, error) {
|
||||
if asset.AssetType == constants.ExchangeAssetTypeIotCard {
|
||||
return cardRealnameSatisfiedWithTx(ctx, tx, asset.AssetID)
|
||||
}
|
||||
return deviceRealnameSatisfiedWithTx(ctx, tx, asset.AssetID)
|
||||
}
|
||||
|
||||
func cardRealnameSatisfiedWithTx(ctx context.Context, tx *gorm.DB, cardID uint) (bool, error) {
|
||||
var card model.IotCard
|
||||
if err := tx.WithContext(ctx).Select("id", "card_category", "real_name_status", "realname_policy", "is_standalone").
|
||||
First(&card, cardID).Error; err != nil {
|
||||
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询新卡实名条件失败")
|
||||
}
|
||||
if card.CardCategory == constants.CardCategoryIndustry || card.RealNameStatus == constants.RealNameStatusVerified {
|
||||
return true, nil
|
||||
}
|
||||
if card.IsStandalone {
|
||||
return card.RealnamePolicy == constants.RealnamePolicyNone, nil
|
||||
}
|
||||
var device model.Device
|
||||
err := tx.WithContext(ctx).Select("devices.realname_policy").Table("tb_device AS devices").
|
||||
Joins("JOIN tb_device_sim_binding AS bindings ON bindings.device_id = devices.id").
|
||||
Where("bindings.iot_card_id = ? AND bindings.bind_status = ? AND bindings.deleted_at IS NULL", cardID, constants.BindStatusBound).
|
||||
Where("devices.deleted_at IS NULL").
|
||||
Take(&device).Error
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return card.RealnamePolicy == constants.RealnamePolicyNone, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询新卡绑定设备实名策略失败")
|
||||
}
|
||||
return device.RealnamePolicy == constants.RealnamePolicyNone, nil
|
||||
}
|
||||
|
||||
func deviceRealnameSatisfiedWithTx(ctx context.Context, tx *gorm.DB, deviceID uint) (bool, error) {
|
||||
var device model.Device
|
||||
if err := tx.WithContext(ctx).Select("id", "realname_policy").First(&device, deviceID).Error; err != nil {
|
||||
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询新设备实名条件失败")
|
||||
}
|
||||
if device.RealnamePolicy == constants.RealnamePolicyNone {
|
||||
return true, nil
|
||||
}
|
||||
var count int64
|
||||
if err := tx.WithContext(ctx).Model(&model.IotCard{}).
|
||||
Joins("JOIN tb_device_sim_binding AS bindings ON bindings.iot_card_id = tb_iot_card.id").
|
||||
Where("bindings.device_id = ? AND bindings.bind_status = ? AND bindings.deleted_at IS NULL", deviceID, constants.BindStatusBound).
|
||||
Where("tb_iot_card.card_category = ? OR tb_iot_card.real_name_status = ?", constants.CardCategoryIndustry, constants.RealNameStatusVerified).
|
||||
Count(&count).Error; err != nil {
|
||||
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询新设备绑定卡实名条件失败")
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
Reference in New Issue
Block a user