fix: 第1批 F1、M12 一资产一号与换货按手机号关联校验

- F1 一个资产同时只能有一个有效手机号关联,他号绑定返回 1192(不含号码),同号幂等
- 登录 need_bind_phone 改看资产是否已有有效关联,新增 asset_phone_bound、asset_phone_is_own;H5 绑定按客户/资产两侧状态分别写入
- 客户换号不再迁移资产关联
- M12 换货新资产有有效手机号关联即拒绝,号码只在 data.phone;换货完成清空旧资产客户绑定并失效旧资产关联(exchange_completed),均不迁移
- OpenSpec Change enforce-single-phone-per-asset:11/16,H5 短信与换货端到端验证待测试部署后完成
This commit is contained in:
邹进
2026-10-12 00:10:41 +09:00
parent 6298a9061f
commit 9ced14fa1b
19 changed files with 568 additions and 451 deletions

View File

@@ -370,6 +370,7 @@ func initServices(s *stores, deps *Dependencies) *services {
exchangeService := exchangeSvc.New(deps.DB, s.ExchangeOrder, s.IotCard, s.Device, s.AssetWallet, s.AssetWalletTransaction, s.PackageUsage, s.PackageUsageDailyRecord, s.ResourceTag, customerBinding, deps.Logger)
exchangeService.SetShippingCreatedNotifier(exchangeApp.NewShippingCreatedNotifier(exchangeInfra.NewShippingNotificationWriter(outbox.NewRepository())))
exchangeService.SetAccessAudit(auditWriter)
exchangeService.SetPhoneAssetAssociationStore(s.PhoneAssetAssociation)
assetService := assetSvc.New(deps.DB, s.Device, s.IotCard, s.PackageUsage, s.Package, s.PackageSeries, s.DeviceSimBinding, s.Shop, deps.Redis, iotCard, deps.GatewayClient, s.AssetIdentifier, s.Order, s.OrderItem, s.ExchangeOrder)
assetService.SetPhoneAssetAssociationStore(s.PhoneAssetAssociation)
assetService.SetAccessAudit(auditWriter)

View File

@@ -29,9 +29,11 @@ type WechatLoginRequest struct {
// WechatLoginResponse A2/A3 登录统一响应
type WechatLoginResponse struct {
Token string `json:"token" description:"登录JWT令牌"`
NeedBindPhone bool `json:"need_bind_phone" description:"是否需要绑定手机号"`
IsNewUser bool `json:"is_new_user" description:"是否新创建用户"`
Token string `json:"token" description:"登录JWT令牌"`
NeedBindPhone bool `json:"need_bind_phone" description:"是否需要绑定手机号(仅前端提示):强制绑定开关开启时,客户无手机号或当前资产尚无有效手机号关联为 true;开关关闭恒为 false"`
AssetPhoneBound bool `json:"asset_phone_bound" description:"当前资产是否已绑定手机号(一资产一号);不返回号码"`
AssetPhoneIsOwn bool `json:"asset_phone_is_own" description:"当前资产绑定的手机号是否为当前客户自己的手机号;不返回号码"`
IsNewUser bool `json:"is_new_user" description:"是否新创建用户"`
}
// ========================================

View File

@@ -10,10 +10,12 @@ import (
func registerAdminExchangeRoutes(router fiber.Router, handler *admin.ExchangeHandler, doc *openapi.Generator, basePath string) {
Register(router, doc, basePath, "POST", "/exchanges", handler.Create, RouteSpec{
Summary: "创建换货单",
Tags: []string{"换货管理"},
Input: new(dto.CreateExchangeRequest),
Output: new(dto.ExchangeOrderResponse),
Auth: true,
Description: "新资产存在有效手机号关联时拒绝(错误码 1202),提示先在后台解除该资产的手机号绑定;完整号码只在错误响应 data.phone 中返回,不进日志。" +
"不再以“有人扫过码”拒绝。直接换货完成时清空旧资产的个人客户绑定并失效旧资产手机号关联(exchange_completed),均不迁移到新资产。",
Tags: []string{"换货管理"},
Input: new(dto.CreateExchangeRequest),
Output: new(dto.ExchangeOrderResponse),
Auth: true,
})
Register(router, doc, basePath, "GET", "/exchanges", handler.List, RouteSpec{
@@ -43,7 +45,9 @@ func registerAdminExchangeRoutes(router fiber.Router, handler *admin.ExchangeHan
Register(router, doc, basePath, "POST", "/exchanges/:id/complete", handler.Complete, RouteSpec{
Summary: "确认换货完成",
Description: "确认换货完成;仅超级管理员或平台用户可对迁移状态为 failed 的物流换货单重试," +
"其他账号对 failed 单返回 403/1005;非 failed 单沿用既有完成权限。",
"其他账号对 failed 单返回 403/1005;非 failed 单沿用既有完成权限。" +
"新资产存在有效手机号关联时拒绝并停在已发货待确认,完整号码在错误响应 data.phone;后台解除后可重新确认。" +
"完成时清空旧资产个人客户绑定并失效旧资产手机号关联,均不迁移到新资产。",
Tags: []string{"换货管理"},
Input: new(dto.ExchangeIDRequest),
Output: nil,

View File

@@ -93,18 +93,21 @@ func RegisterPersonalCustomerRoutes(router fiber.Router, doc *openapi.Generator,
Register(authProtectedGroup, doc, basePath+authBasePath, "POST", "/bind-phone", handlers.ClientAuth.BindPhone, RouteSpec{
Summary: "绑定手机号",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.BindPhoneRequest{},
Output: &dto.BindPhoneResponse{},
Description: "客户手机号与资产手机号相互独立:无手机号且资产无关联时同时写入两者;有手机号且资产无关联时只为资产建立关联,号码可与客户手机号不同;" +
"无手机号而资产已绑定时只写客户手机号;资产已绑定其他号码时返回 1192“该资产已绑定手机号,如需更换请联系管理员”,响应不含号码。",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.BindPhoneRequest{},
Output: &dto.BindPhoneResponse{},
})
Register(authProtectedGroup, doc, basePath+authBasePath, "POST", "/change-phone", handlers.ClientAuth.ChangePhone, RouteSpec{
Summary: "更换手机号",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.ChangePhoneRequest{},
Output: &dto.ChangePhoneResponse{},
Summary: "更换手机号",
Description: "同时验证旧、新号码,只更换客户手机号,不迁移、复制或失效任何资产手机号关联。",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.ChangePhoneRequest{},
Output: &dto.ChangePhoneResponse{},
})
Register(authProtectedGroup, doc, basePath+authBasePath, "POST", "/logout", handlers.ClientAuth.Logout, RouteSpec{

View File

@@ -7,7 +7,6 @@ import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/config"
"github.com/break/junhong_cmp_fiber/pkg/errors"
@@ -88,15 +87,14 @@ func (s *Service) establishAssociation(
return s.associationWriter.Establish(ctx, tx, customer, phone, assetType, assetID)
}
// migrateAssociations 委托关联写入规则完成换绑原子迁移与上限/冲突判定。
// 开关关闭时完全短路,不迁移任何关联。
func (s *Service) migrateAssociations(
ctx context.Context,
tx *gorm.DB,
oldPhone, newPhone string,
) ([]accessauditapp.PhoneAssetAssociationChange, error) {
if !requirePhoneBinding() {
return nil, nil
// assetHasValidAssociation 判断当前访问资产是否已有任一有效手机号关联;开关关闭或无资产身份时返回 false。
func (s *Service) assetHasValidAssociation(ctx context.Context, tx *gorm.DB, assetType string, assetID uint) (bool, error) {
if !requirePhoneBinding() || assetType == "" || assetID == 0 {
return false, nil
}
return s.associationWriter.Migrate(ctx, tx, oldPhone, newPhone)
phones, err := s.associationStore.WithTx(tx).ListValidByAsset(ctx, assetType, assetID)
if err != nil {
return false, errors.Wrap(errors.CodeInternalError, err, "查询资产手机号关联失败")
}
return len(phones) > 0, nil
}

View File

@@ -197,7 +197,7 @@ func (s *Service) WechatLogin(ctx context.Context, req *dto.WechatLoginRequest,
return nil, err
}
token, needBindPhone, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
token, bindState, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
if err != nil {
return nil, err
}
@@ -208,9 +208,11 @@ func (s *Service) WechatLogin(ctx context.Context, req *dto.WechatLoginRequest,
)
return &dto.WechatLoginResponse{
Token: token,
NeedBindPhone: needBindPhone,
IsNewUser: isNewUser,
Token: token,
NeedBindPhone: bindState.NeedBindPhone,
AssetPhoneBound: bindState.AssetPhoneBound,
AssetPhoneIsOwn: bindState.AssetPhoneIsOwn,
IsNewUser: isNewUser,
}, nil
}
@@ -256,7 +258,7 @@ func (s *Service) MiniappLogin(ctx context.Context, req *dto.MiniappLoginRequest
return nil, err
}
token, needBindPhone, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
token, bindState, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
if err != nil {
return nil, err
}
@@ -267,9 +269,11 @@ func (s *Service) MiniappLogin(ctx context.Context, req *dto.MiniappLoginRequest
)
return &dto.WechatLoginResponse{
Token: token,
NeedBindPhone: needBindPhone,
IsNewUser: isNewUser,
Token: token,
NeedBindPhone: bindState.NeedBindPhone,
AssetPhoneBound: bindState.AssetPhoneBound,
AssetPhoneIsOwn: bindState.AssetPhoneIsOwn,
IsNewUser: isNewUser,
}, nil
}
@@ -299,8 +303,12 @@ func (s *Service) SendCode(ctx context.Context, req *dto.ClientSendCodeRequest,
// BindPhone A5 绑定手机号
// POST /api/c/v1/auth/bind-phone
// 无主手机号时建立账号手机号;已有主手机号且提交号码与主号一致、验证码有效时,
// 幂等建立当前访问资产与该手机号的关联且不修改账号手机号;提交号码与主号不一致仍拒绝。
// 客户手机号与资产手机号相互独立,按两侧状态分别写入:
// - 无主手机号、资产无有效关联:同时写客户手机号与资产关联;
// - 无主手机号、资产已有有效关联:只写客户手机号,不动资产关联;
// - 已有主手机号、资产无有效关联:只为资产建立关联,号码可与主号不同,不改客户手机号;
// - 已有主手机号、资产已有有效关联:同号幂等成功,其他号码按一资产一号拒绝。
//
// 请求不含当前访问资产身份时只完成账号手机号绑定,不建立关联。
func (s *Service) BindPhone(ctx context.Context, customerID uint, assetType string, assetID uint, req *dto.BindPhoneRequest) (*dto.BindPhoneResponse, error) {
if req == nil {
@@ -380,6 +388,11 @@ func (s *Service) BindPhone(ctx context.Context, customerID uint, assetType stri
)); err != nil {
return err
}
// 资产已有有效关联(无论号码属于谁)时只写客户手机号,不动资产关联。
assetBound, err := s.assetHasValidAssociation(ctx, tx, assetType, assetID)
if err != nil || assetBound {
return err
}
// 建联与账号手机号同事务:超限或写入失败时账号手机号一并回滚。
if _, err := s.establishAssociation(ctx, tx, customer, record.Phone, assetType, assetID); err != nil {
return err
@@ -397,8 +410,8 @@ func (s *Service) BindPhone(ctx context.Context, customerID uint, assetType stri
}, nil
}
// bindExistingPrimaryPhone 处理已有主手机号的绑定请求。
// 提交号码等于主号且验证码有效时幂等建立关联且不改账号手机号;号码不一致仍拒绝换号。
// bindExistingPrimaryPhone 处理已有主手机号的绑定请求:只为当前访问资产建立关联,不改账号手机号。
// 强制绑定开启且带资产身份时,资产侧号码可与主号不同;否则提交号码必须等于主号(不支持经绑定入口换号)。
func (s *Service) bindExistingPrimaryPhone(
ctx context.Context,
customer *model.PersonalCustomer,
@@ -407,7 +420,8 @@ func (s *Service) bindExistingPrimaryPhone(
assetID uint,
req *dto.BindPhoneRequest,
) (*dto.BindPhoneResponse, error) {
if primary.Phone != req.Phone {
assetBinding := requirePhoneBinding() && assetType != "" && assetID != 0
if primary.Phone != req.Phone && !assetBinding {
appErr := errors.New(errors.CodeAlreadyBoundPhone)
s.recordPersonalFailure(ctx, constants.AuditActionPersonalCustomerPhoneBound, "绑定个人手机号被拒绝", customer, primary, appErr)
return nil, appErr
@@ -421,7 +435,7 @@ func (s *Service) bindExistingPrimaryPhone(
now := time.Now()
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 固定加锁次序:先取手机号串行化点(advisory),再按 id ASC 锁行。
if err := s.lockPhoneScopesInOrder(ctx, tx, primary.Phone); err != nil {
if err := s.lockPhoneScopesInOrder(ctx, tx, req.Phone); err != nil {
return err
}
if err := s.lockPhoneRowsInIDOrder(ctx, tx, []uint{primary.ID}); err != nil {
@@ -436,11 +450,11 @@ func (s *Service) bindExistingPrimaryPhone(
}
return errors.Wrap(errors.CodeInternalError, err, "查询主手机号失败")
}
if locked.Phone != req.Phone {
if !assetBinding && locked.Phone != req.Phone {
// 并发换绑已把主号改成其他号码:提交号码不再等于账号手机号,按既有语义拒绝。
return errors.New(errors.CodeAlreadyBoundPhone)
}
_, err := s.establishAssociation(ctx, tx, customer, locked.Phone, assetType, assetID)
_, err := s.establishAssociation(ctx, tx, customer, req.Phone, assetType, assetID)
return err
})
if err != nil {
@@ -498,9 +512,8 @@ func (s *Service) ChangePhone(ctx context.Context, customerID uint, req *dto.Cha
now := time.Now()
var beforeData map[string]any
var failurePhone *model.PersonalCustomerPhone
var migrationChanges []accessauditapp.PhoneAssetAssociationChange
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 统一加锁顺序:先按手机号行 id ASC 锁定旧、新手机号行,再由关联迁移按 id ASC 锁定两侧有效关系行。
// 统一加锁顺序:先取旧、新手机号串行化点,再按手机号行 id ASC 锁定旧、新手机号行。
// 换绑两行的加锁顺序与 bind-phone 的单行加锁一致,两条路径不会形成 A→B / B→A 死锁环。
if idErr := s.lockPhoneScopesInOrder(ctx, tx, primary.Phone, req.NewPhone); idErr != nil {
return idErr
@@ -533,12 +546,7 @@ func (s *Service) ChangePhone(ctx context.Context, customerID uint, req *dto.Cha
} else if err != nil && err != gorm.ErrRecordNotFound {
return errors.Wrap(errors.CodeInternalError, err, "查询新手机号绑定关系失败")
}
// 关联迁移先于账号手机号改写:超限或与既有关系冲突时整次失败,旧、新关系均保持原状。
changes, migrateErr := s.migrateAssociations(ctx, tx, primary.Phone, req.NewPhone)
if migrateErr != nil {
return migrateErr
}
migrationChanges = changes
// 客户手机号与资产手机号相互独立:换号只改客户手机号,不迁移、复制或失效任何资产关联。
if err := tx.Model(primary).Updates(map[string]any{
"phone": req.NewPhone,
"verified_at": now,
@@ -548,22 +556,10 @@ func (s *Service) ChangePhone(ctx context.Context, customerID uint, req *dto.Cha
}
primary.Phone = req.NewPhone
primary.VerifiedAt = &now
if err := s.accessAudit.WriteAccessChange(ctx, tx, personalPhoneAudit(
return s.accessAudit.WriteAccessChange(ctx, tx, personalPhoneAudit(
constants.AuditActionPersonalCustomerPhoneChanged, "更换个人手机号", customer, primary, beforeData,
map[string]any{"phone": sanitizer.MaskPhone(primary.Phone)}, "手机号已更换", constants.AuditResultSuccess,
)); err != nil {
return err
}
if len(migrationChanges) == 0 {
return nil
}
return s.accessAudit.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
ActionCode: constants.AuditActionPhoneAssetAssociationMigrated,
Summary: "换绑手机号并迁移资产关联",
OperatorID: customer.ID, ActorKind: constants.AuditActorPersonalCustomer, ActorName: customer.Nickname,
Source: constants.AuditSourcePersonalAPI, ScopeType: constants.AuditScopePersonalCustomer,
PhoneAssociations: migrationChanges,
})
))
})
if err != nil {
if failurePhone == nil {
@@ -1014,10 +1010,10 @@ func (s *Service) bindAsset(ctx context.Context, tx *gorm.DB, customerID uint, a
// 已存在有效关系 → false。全局开关关闭时恒为 false,且不查询、不创建、不删除任何关系。
// 关联查询使用当前访问资产的 asset_type/asset_id,不使用 phone claim:phone 是登录时快照,
// 换绑后到下次登录前仍是旧号。该字段只作前端提示,不改变任何资源授权。
func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetType string, assetID uint) (string, bool, error) {
func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetType string, assetID uint) (string, loginBindState, error) {
// 查询用户已绑定的主手机号,写入 JWT,供后续接口直接从 context 取用
var boundPhone string
needBindPhone := false
state := loginBindState{}
cfg := config.Get()
requirePhoneBinding := true
if cfg != nil {
@@ -1027,30 +1023,26 @@ func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetTyp
if phoneErr == nil {
boundPhone = primaryPhone.Phone
} else if phoneErr != gorm.ErrRecordNotFound {
return "", false, errors.Wrap(errors.CodeInternalError, phoneErr, "查询手机号绑定关系失败")
return "", state, errors.Wrap(errors.CodeInternalError, phoneErr, "查询手机号绑定关系失败")
}
// 开关关闭必须完全短路:既不查询也不写任何关系,否则会出现「关闭开关却写库」的越权写入。
if requirePhoneBinding {
if boundPhone == "" {
needBindPhone = true
} else {
associated, err := s.associationStore.ExistsValid(ctx, boundPhone, assetType, assetID)
if err != nil {
return "", false, errors.Wrap(errors.CodeInternalError, err, "查询手机号资产关联失败")
}
needBindPhone = !associated
resolved, err := s.resolveLoginBindState(ctx, boundPhone, assetType, assetID)
if err != nil {
return "", state, err
}
state = resolved
}
token, err := s.jwtManager.GeneratePersonalCustomerToken(customerID, boundPhone, assetType, assetID)
if err != nil {
return "", false, errors.Wrap(errors.CodeInternalError, err, "生成登录令牌失败")
return "", state, errors.Wrap(errors.CodeInternalError, err, "生成登录令牌失败")
}
claims, err := s.jwtManager.VerifyPersonalCustomerToken(token)
if err != nil {
return "", false, errors.Wrap(errors.CodeInternalError, err, "解析登录令牌失败")
return "", state, errors.Wrap(errors.CodeInternalError, err, "解析登录令牌失败")
}
ttl := time.Until(claims.ExpiresAt.Time)
@@ -1060,10 +1052,38 @@ func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetTyp
redisKey := constants.RedisPersonalCustomerTokenKey(customerID)
if err := s.redis.Set(ctx, redisKey, token, ttl).Err(); err != nil {
return "", false, errors.Wrap(errors.CodeRedisError, err, "保存登录状态失败")
return "", state, errors.Wrap(errors.CodeRedisError, err, "保存登录状态失败")
}
return token, needBindPhone, nil
return token, state, nil
}
// loginBindState 是登录响应的手机号绑定提示,只含布尔值,不含号码。
type loginBindState struct {
NeedBindPhone bool
AssetPhoneBound bool
AssetPhoneIsOwn bool
}
// resolveLoginBindState 按客户主手机号与当前资产有效关联判定绑定提示:
// 客户无主手机号仍需绑定;资产尚无有效关联需为资产绑定;资产已有有效关联(无论号码属于谁)且客户有主手机号时不需绑定。
func (s *Service) resolveLoginBindState(ctx context.Context, boundPhone, assetType string, assetID uint) (loginBindState, error) {
state := loginBindState{}
if assetType != "" && assetID != 0 {
assetPhones, err := s.associationStore.ListValidByAsset(ctx, assetType, assetID)
if err != nil {
return state, errors.Wrap(errors.CodeInternalError, err, "查询资产手机号关联失败")
}
state.AssetPhoneBound = len(assetPhones) > 0
for _, phone := range assetPhones {
if boundPhone != "" && phone == boundPhone {
state.AssetPhoneIsOwn = true
break
}
}
}
state.NeedBindPhone = boundPhone == "" || !state.AssetPhoneBound
return state, nil
}
// DevLogin 开发环境测试登录

View File

@@ -98,58 +98,6 @@ func deviceAuditChange(device *model.Device, relation, role string, beforeData,
}
}
func (s *Service) loadAuditAssets(ctx context.Context, tx *gorm.DB, oldType string, oldID uint, newType string, newID uint) ([]accessauditapp.IotCardChange, []accessauditapp.DeviceChange, error) {
cards := make([]accessauditapp.IotCardChange, 0, 2)
devices := make([]accessauditapp.DeviceChange, 0, 2)
appendAsset := func(assetType string, assetID uint, role string) error {
switch normalizeAssetType(assetType) {
case assetTypeIotCard:
card, err := s.readCard(ctx, tx, assetID)
if err != nil {
return err
}
cards = append(cards, cardAuditChange(card, constants.AuditResourceRelationAffected, role, nil, nil))
case assetTypeDevice:
device, err := s.readDevice(ctx, tx, assetID)
if err != nil {
return err
}
devices = append(devices, deviceAuditChange(device, constants.AuditResourceRelationAffected, role, nil, nil))
default:
return errors.New(errors.CodeInvalidParam, "无效的资产类型")
}
return nil
}
if err := appendAsset(oldType, oldID, constants.AuditResourceRolePersonalCustomerOldAsset); err != nil {
return nil, nil, err
}
if err := appendAsset(newType, newID, constants.AuditResourceRolePersonalCustomerNewAsset); err != nil {
return nil, nil, err
}
return cards, devices, nil
}
func (s *Service) writeMigrationAudit(
ctx context.Context,
tx *gorm.DB,
customerID uint,
oldType string,
oldID uint,
newType string,
newID uint,
personalDevices []accessauditapp.PersonalCustomerDeviceChange,
personalICCIDs []accessauditapp.PersonalCustomerICCIDChange,
) error {
cards, devices, err := s.loadAuditAssets(ctx, tx, oldType, oldID, newType, newID)
if err != nil {
return err
}
return s.writeBindingAudit(
ctx, tx, constants.AuditActionPersonalCustomerAssetBindingMigrated, "换货迁移个人客户资产绑定",
customerID, personalDevices, personalICCIDs, cards, devices,
)
}
// UnbindByVirtualNo 按现有换货重置语义删除设备号绑定,并在同一事务记录实际删除关系。
func (s *Service) UnbindByVirtualNo(ctx context.Context, tx *gorm.DB, assetType string, assetID uint, virtualNo string) error {
if s.accessAudit == nil {

View File

@@ -349,273 +349,103 @@ func (s *Service) bindViaPCI(ctx context.Context, pci pciOps, tx *gorm.DB, custo
}, nil)
}
// Migrate 将旧资产的所有有效客户绑定迁移到新资产(换货专用)
// 无绑定时静默跳过;按旧/新资产虚拟号有无路由到 pcd 或 pci
func (s *Service) Migrate(ctx context.Context, tx *gorm.DB, oldAssetType string, oldAssetID uint, newAssetType string, newAssetID uint) error {
// ClearForExchange 换货完成时在同一事务内把旧资产的全部有效个人客户绑定置为无效,不迁移到新资产。
// 定位口径同原换货迁移:卡的虚拟号绑定与 ICCID 绑定两边都清;设备按虚拟号,无虚拟号时按 IMEI。
// 原客户之后重新扫码旧资产仍可按既有登录规则重新建立绑定。
func (s *Service) ClearForExchange(ctx context.Context, tx *gorm.DB, oldAssetType string, oldAssetID uint) error {
if s.accessAudit == nil {
return errors.New(errors.CodeInvalidStatus, "个人客户资产审计接缝未配置")
}
if tx == nil {
tx = s.db
}
pcd := s.makePCD(tx)
pci := s.makePCI(tx)
switch normalizeAssetType(oldAssetType) {
case assetTypeIotCard:
oldCard, err := s.readCard(ctx, tx, oldAssetID)
card, err := s.readCard(ctx, tx, oldAssetID)
if err != nil {
return err
}
if oldCard.VirtualNo != "" {
return s.migrateFromPCD(ctx, tx, pcd, pci, oldCard.VirtualNo, oldAssetType, oldAssetID, newAssetType, newAssetID)
assetChange := []accessauditapp.IotCardChange{cardAuditChange(card, constants.AuditResourceRelationAffected, constants.AuditResourceRolePersonalCustomerOldAsset, nil, nil)}
if card.VirtualNo != "" {
if err := s.clearDeviceBindings(ctx, tx, card.VirtualNo, assetChange, nil); err != nil {
return err
}
}
return s.migrateFromPCI(ctx, tx, pcd, pci, oldCard.ICCID, oldAssetType, oldAssetID, newAssetType, newAssetID)
return s.clearICCIDBindings(ctx, tx, card.ICCID, assetChange)
case assetTypeDevice:
oldDevice, err := s.readDevice(ctx, tx, oldAssetID)
device, err := s.readDevice(ctx, tx, oldAssetID)
if err != nil {
return err
}
key := oldDevice.VirtualNo
key := device.VirtualNo
if key == "" {
key = oldDevice.IMEI
key = device.IMEI
}
return s.migrateFromPCD(ctx, tx, pcd, pci, key, oldAssetType, oldAssetID, newAssetType, newAssetID)
if key == "" {
return nil
}
assetChange := []accessauditapp.DeviceChange{deviceAuditChange(device, constants.AuditResourceRelationAffected, constants.AuditResourceRolePersonalCustomerOldAsset, nil, nil)}
return s.clearDeviceBindings(ctx, tx, key, nil, assetChange)
}
return errors.New(errors.CodeInvalidParam)
}
// migrateFromPCD 将 tb_personal_customer_device 中 oldKey 的所有有效绑定迁移到新资产
func (s *Service) migrateFromPCD(ctx context.Context, db *gorm.DB, pcd pcdOps, pci pciOps, oldKey string, oldAssetType string, oldAssetID uint, newAssetType string, newAssetID uint) error {
records, err := pcd.GetByDeviceNo(ctx, oldKey)
// clearDeviceBindings 把按虚拟号(或 IMEI)定位的有效绑定置为无效并逐条写审计。
func (s *Service) clearDeviceBindings(ctx context.Context, tx *gorm.DB, key string, cards []accessauditapp.IotCardChange, devices []accessauditapp.DeviceChange) error {
pcd := s.makePCD(tx)
records, err := pcd.GetByDeviceNo(ctx, key)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询旧资产绑定记录失败")
return errors.Wrap(errors.CodeInternalError, err, "查询旧资产客户绑定失败")
}
// 仅处理 status=1 的有效记录
var active []*model.PersonalCustomerDevice
for _, r := range records {
if r.Status == 1 {
active = append(active, r)
for _, record := range records {
if record == nil || record.Status != 1 {
continue
}
}
if len(active) == 0 {
return nil
}
switch normalizeAssetType(newAssetType) {
case assetTypeIotCard:
newCard, err := s.readCard(ctx, db, newAssetID)
if err != nil {
if err := pcd.UpdateStatus(ctx, record.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "清空旧资产客户绑定失败")
}
if err := s.writeBindingAudit(
ctx, tx, constants.AuditActionPersonalCustomerAssetUnbound, "换货完成清空旧资产个人客户绑定", record.CustomerID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: record, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"virtual_no": record.VirtualNo, "status": record.Status},
AfterData: map[string]any{"virtual_no": record.VirtualNo, "status": 0},
}}, nil, cards, devices,
); err != nil {
return err
}
if newCard.VirtualNo != "" {
// 新卡有虚拟号:更新 pcd virtual_no
for _, rec := range active {
if err := pcd.UpdateVirtualNo(ctx, rec.ID, newCard.VirtualNo); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "迁移客户绑定关系失败")
}
after := *rec
after.VirtualNo = newCard.VirtualNo
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: &after, Role: constants.AuditResourceRolePersonalCustomerAssetBinding,
BeforeData: map[string]any{"virtual_no": rec.VirtualNo, "status": rec.Status},
AfterData: map[string]any{"virtual_no": after.VirtualNo, "status": after.Status},
}}, nil); err != nil {
return err
}
}
} else {
// 新卡无虚拟号:禁用旧 pcd + 创建新 pci
iccid19 := newCard.ICCID
if len(newCard.ICCID) == 20 {
iccid19 = newCard.ICCID[:19]
}
for _, rec := range active {
if err := pcd.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧客户绑定关系失败")
}
newPCI := &model.PersonalCustomerICCID{
CustomerID: rec.CustomerID,
ICCID: newCard.ICCID,
ICCID19: iccid19,
Status: 1,
}
if err := pci.Create(ctx, newPCI); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新客户绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"virtual_no": rec.VirtualNo, "status": rec.Status},
AfterData: map[string]any{"virtual_no": rec.VirtualNo, "status": 0},
}}, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: newPCI, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"iccid": newPCI.ICCID, "status": newPCI.Status},
}}); err != nil {
return err
}
}
}
case assetTypeDevice:
newDevice, err := s.readDevice(ctx, db, newAssetID)
if err != nil {
return err
}
newKey := newDevice.VirtualNo
if newKey == "" {
newKey = newDevice.IMEI
}
for _, rec := range active {
if err := pcd.UpdateVirtualNo(ctx, rec.ID, newKey); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "迁移设备客户绑定关系失败")
}
after := *rec
after.VirtualNo = newKey
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: &after, Role: constants.AuditResourceRolePersonalCustomerAssetBinding,
BeforeData: map[string]any{"virtual_no": rec.VirtualNo, "status": rec.Status},
AfterData: map[string]any{"virtual_no": after.VirtualNo, "status": after.Status},
}}, nil); err != nil {
return err
}
}
default:
return errors.New(errors.CodeInvalidParam)
}
return nil
}
// migrateFromPCI 将 tb_personal_customer_iccid 中 oldICCID 的所有有效绑定迁移到新资产
func (s *Service) migrateFromPCI(ctx context.Context, db *gorm.DB, pcd pcdOps, pci pciOps, oldICCID string, oldAssetType string, oldAssetID uint, newAssetType string, newAssetID uint) error {
records, err := pci.GetByICCID(ctx, oldICCID)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询旧 ICCID 绑定记录失败")
}
var active []*model.PersonalCustomerICCID
for _, r := range records {
if r.Status == 1 {
active = append(active, r)
}
}
if len(active) == 0 {
// clearICCIDBindings 把按 ICCID 定位的有效绑定置为无效并逐条写审计。
func (s *Service) clearICCIDBindings(ctx context.Context, tx *gorm.DB, iccid string, cards []accessauditapp.IotCardChange) error {
if iccid == "" {
return nil
}
switch normalizeAssetType(newAssetType) {
case assetTypeIotCard:
newCard, err := s.readCard(ctx, db, newAssetID)
if err != nil {
return err
}
if newCard.VirtualNo != "" {
// 新卡有虚拟号:禁用旧 pci + 创建新 pcd
for _, rec := range active {
if err := pci.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧 ICCID 绑定关系失败")
}
newPCD := &model.PersonalCustomerDevice{
CustomerID: rec.CustomerID,
VirtualNo: newCard.VirtualNo,
Status: 1,
}
if err := pcd.Create(ctx, newPCD); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新客户绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: newPCD, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"virtual_no": newPCD.VirtualNo, "status": newPCD.Status},
}}, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": rec.ICCID, "status": rec.Status},
AfterData: map[string]any{"iccid": rec.ICCID, "status": 0},
}}); err != nil {
return err
}
}
} else {
// 新卡也无虚拟号:禁用旧 pci + 创建新 pci(新 ICCID)
iccid19 := newCard.ICCID
if len(newCard.ICCID) == 20 {
iccid19 = newCard.ICCID[:19]
}
for _, rec := range active {
if err := pci.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧 ICCID 绑定关系失败")
}
newPCI := &model.PersonalCustomerICCID{
CustomerID: rec.CustomerID,
ICCID: newCard.ICCID,
ICCID19: iccid19,
Status: 1,
}
if err := pci.Create(ctx, newPCI); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新 ICCID 绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
nil, []accessauditapp.PersonalCustomerICCIDChange{
{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": rec.ICCID, "status": rec.Status},
AfterData: map[string]any{"iccid": rec.ICCID, "status": 0},
},
{
Binding: newPCI, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"iccid": newPCI.ICCID, "status": newPCI.Status},
},
}); err != nil {
return err
}
}
}
case assetTypeDevice:
newDevice, err := s.readDevice(ctx, db, newAssetID)
if err != nil {
return err
}
newKey := newDevice.VirtualNo
if newKey == "" {
newKey = newDevice.IMEI
}
for _, rec := range active {
if err := pci.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧 ICCID 绑定关系失败")
}
newPCD := &model.PersonalCustomerDevice{
CustomerID: rec.CustomerID,
VirtualNo: newKey,
Status: 1,
}
if err := pcd.Create(ctx, newPCD); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新客户绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: newPCD, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"virtual_no": newPCD.VirtualNo, "status": newPCD.Status},
}}, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": rec.ICCID, "status": rec.Status},
AfterData: map[string]any{"iccid": rec.ICCID, "status": 0},
}}); err != nil {
return err
}
}
default:
return errors.New(errors.CodeInvalidParam)
pci := s.makePCI(tx)
records, err := pci.GetByICCID(ctx, iccid)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询旧 ICCID 客户绑定失败")
}
for _, record := range records {
if record == nil || record.Status != 1 {
continue
}
if err := pci.UpdateStatus(ctx, record.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "清空旧 ICCID 客户绑定失败")
}
if err := s.writeBindingAudit(
ctx, tx, constants.AuditActionPersonalCustomerAssetUnbound, "换货完成清空旧资产个人客户绑定", record.CustomerID,
nil, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: record, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": record.ICCID, "status": record.Status},
AfterData: map[string]any{"iccid": record.ICCID, "status": 0},
}}, cards, nil,
); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,93 @@
package exchange
import (
"context"
"time"
"gorm.io/gorm"
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/break/junhong_cmp_fiber/pkg/sanitizer"
)
// exchangeNewAssetPhoneBoundMessage 新资产已绑定手机号时的拒绝提示,不含号码。
const exchangeNewAssetPhoneBoundMessage = "新资产已绑定手机号,请先在后台解除该资产的手机号绑定,再重新提交换货申请"
// SetPhoneAssetAssociationStore 注入手机号—资产关联存储,用于换货校验与换货完成失效旧资产关联。
func (s *Service) SetPhoneAssetAssociationStore(store *postgres.PhoneAssetAssociationStore) {
s.phoneAssociationStore = store
}
// ensureNewAssetPhoneUnboundWithTx 新资产存在有效手机号关联时拒绝换货。
// 完整号码只放在错误响应 data.phone 中,错误信息与日志不含号码。
func (s *Service) ensureNewAssetPhoneUnboundWithTx(ctx context.Context, tx *gorm.DB, newAsset *resolvedExchangeAsset) error {
if s.phoneAssociationStore == nil {
return errors.New(errors.CodeInvalidStatus, "手机号资产关联存储未配置")
}
phones, err := s.phoneAssociationStore.WithTx(tx).ListValidByAsset(ctx, newAsset.AssetType, newAsset.AssetID)
if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询新资产手机号关联失败")
}
if len(phones) == 0 {
return nil
}
return errors.NewWithData(errors.CodeExchangeStatusInvalid, map[string]any{"phone": phones[0]}, exchangeNewAssetPhoneBoundMessage)
}
// invalidateOldAssetPhoneAssociationsWithTx 换货完成时在同一事务内失效旧资产全部有效手机号关联,释放号码名额。
// 旧资产无有效关联时跳过;操作人为确认换货完成的账号,审计只写脱敏手机号。
func (s *Service) invalidateOldAssetPhoneAssociationsWithTx(ctx context.Context, tx *gorm.DB, oldAsset *resolvedExchangeAsset) error {
if s.phoneAssociationStore == nil {
return errors.New(errors.CodeInvalidStatus, "手机号资产关联存储未配置")
}
store := s.phoneAssociationStore.WithTx(tx)
rows, err := store.LockValidByAsset(ctx, tx, oldAsset.AssetType, oldAsset.AssetID)
if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "锁定旧资产手机号关联失败")
}
if len(rows) == 0 {
return nil
}
if s.auditWriter == nil {
return errors.New(errors.CodeInvalidStatus, "换货审计接缝未配置")
}
ids := make([]uint, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.ID)
}
now := time.Now()
method, reason := constants.PhoneAssetAssociationInvalidateMethodExchangeCompleted, constants.PhoneAssetAssociationExchangeCompletedReason
operatorID, operatorName := middleware.GetUserIDFromContext(ctx), middleware.GetUsernameFromContext(ctx)
affected, err := store.InvalidateByIDs(ctx, tx, ids, method, reason, operatorID, operatorName, now)
if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "失效旧资产手机号关联失败")
}
if int(affected) != len(rows) {
return errors.New(errors.CodeConflict, "旧资产手机号关联已变化,请重试")
}
changes := make([]accessauditapp.PhoneAssetAssociationChange, 0, len(rows))
for _, row := range rows {
changes = append(changes, accessauditapp.PhoneAssetAssociationChange{
AssociationID: row.ID, PhoneMasked: sanitizer.MaskPhone(row.Phone),
AssetType: row.AssetType, AssetID: row.AssetID, AssetDisplayName: oldAsset.Identifier,
Status: constants.PhoneAssetAssociationStatusInvalid, Source: row.Source,
InvalidatedAt: &now, InvalidationMethod: method, InvalidationReason: reason,
BeforeData: map[string]any{"status": constants.PhoneAssetAssociationStatusValid},
AfterData: map[string]any{
"status": constants.PhoneAssetAssociationStatusInvalid,
"invalidated_at": now, "invalidation_method": method, "invalidation_reason": reason,
},
})
}
return s.auditWriter.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
ActionCode: constants.AuditActionPhoneAssetAssociationUnbound,
Summary: "换货完成失效旧资产手机号关联",
OperatorID: operatorID, ActorKind: constants.AuditActorAccount, ActorName: operatorName,
Source: constants.AuditSourceAdminAPI, ScopeType: constants.AuditScopePlatform,
PhoneAssociations: changes,
})
}

View File

@@ -31,6 +31,7 @@ type Service struct {
packageUsageDailyRecordStore *postgres.PackageUsageDailyRecordStore
resourceTagStore *postgres.ResourceTagStore
customerBinding *customerBindingSvc.Service
phoneAssociationStore *postgres.PhoneAssetAssociationStore
shippingCreatedNotifier *exchangeapp.ShippingCreatedNotifier
auditWriter *audit.Writer
logger *zap.Logger
@@ -1068,26 +1069,17 @@ func (s *Service) validateExchangeAssetsWithTx(ctx context.Context, tx *gorm.DB,
return nil
}
// ensureNewAssetBindingAvailableWithTx 新资产已绑定手机号时拒绝换货;不再以“有人扫过码”(客户绑定)作为拒绝依据。
func (s *Service) ensureNewAssetBindingAvailableWithTx(ctx context.Context, tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) error {
newKey := exchangeAssetBindingKey(newAsset)
// 新资产无虚拟号时不再拦截:Migrate() 已能正确处理无绑定跳过、有绑定迁移到 pci 的情形
if newKey == "" {
return nil
}
var newBindCount int64
if err := tx.WithContext(ctx).Model(&model.PersonalCustomerDevice{}).
Where("virtual_no = ? AND status = ?", newKey, constants.StatusEnabled).
Count(&newBindCount).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询新资产客户绑定失败")
}
if newBindCount > 0 {
return errors.New(errors.CodeExchangeStatusInvalid, "新资产存在有效客户绑定,不可用于换货")
}
return nil
return s.ensureNewAssetPhoneUnboundWithTx(ctx, tx, newAsset)
}
// switchCustomerBindingWithTx 换货完成时清空旧资产的客户绑定并失效旧资产手机号关联,均不迁移到新资产。
func (s *Service) switchCustomerBindingWithTx(ctx context.Context, tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) error {
return s.customerBinding.Migrate(ctx, tx, oldAsset.AssetType, oldAsset.AssetID, newAsset.AssetType, newAsset.AssetID)
if err := s.customerBinding.ClearForExchange(ctx, tx, oldAsset.AssetType, oldAsset.AssetID); err != nil {
return err
}
return s.invalidateOldAssetPhoneAssociationsWithTx(ctx, tx, oldAsset)
}
// syncNewAssetOwnershipWithTx 将新资产归属同步为旧资产当前归属。

View File

@@ -2,10 +2,8 @@ package phone_asset_association
import (
"context"
stderrors "errors"
"time"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
@@ -16,11 +14,7 @@ import (
"github.com/break/junhong_cmp_fiber/pkg/sanitizer"
)
// associationUniqueConstraint 是「有效关系」部分唯一索引名。
// 换绑迁移撞上它说明新号已存在同资产有效关系,必须整次失败而不是产生并存关系。
const associationUniqueConstraint = "uq_phone_asset_association_valid"
// AssociationWriter 承载手机号—资产关联的写入规则:幂等建联、换绑迁移与十项上限。
// AssociationWriter 承载手机号—资产关联的写入规则:一资产一号、幂等建联与十项上限。
// 关联只能由 H5 短信验证建立,因此这里不提供任何后台创建入口。
type AssociationWriter struct {
store *postgres.PhoneAssetAssociationStore
@@ -32,7 +26,7 @@ func NewAssociationWriter(store *postgres.PhoneAssetAssociationStore, auditWrite
return &AssociationWriter{store: store, audit: auditWriter}
}
// Establish 建立手机号与当前访问资产的有效关联;同一关系已存在时保持幂等。
// Establish 建立手机号与当前访问资产的有效关联;同一关系已存在时保持幂等,资产已绑定其他号码时拒绝。
// 串行化点:先取手机号事务级 advisory lock,再锁定该号码现有有效关系行,
// 使「计数」与「插入」同处临界区;新号没有行可锁时仍由 advisory lock 保证串行。
// 已达十项的手机号对已关联资产重复验证必须返回成功且不产生第二条关系,
@@ -50,6 +44,20 @@ func (w *AssociationWriter) Establish(
return false, nil
}
store := w.store.WithTx(tx)
// 一资产一号:先查后写,不加资产锁(两个号码同时为同一资产完成验证属已接受的极小概率,由只读统计发现后后台解除)。
assetPhones, err := store.ListValidByAsset(ctx, assetType, assetID)
if err != nil {
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询资产有效手机号关联失败")
}
for _, bound := range assetPhones {
if bound == phone {
return false, nil
}
}
if len(assetPhones) > 0 {
// 提示与响应不含任何号码。
return false, errors.New(errors.CodeAssetPhoneAlreadyBound)
}
if err := store.LockPhoneScopes(ctx, phone); err != nil {
return false, errors.Wrap(errors.CodeDatabaseError, err, "锁定手机号串行化点失败")
}
@@ -102,64 +110,3 @@ func (w *AssociationWriter) Establish(
}
return true, nil
}
// Migrate 在同一事务内把旧号全部有效关联原子迁移到新号。
// 串行化点:先按号码字符串升序取旧、新手机号 advisory lock,再按 id ASC 锁定两侧有效关系行。
// 迁移前比较「新号现有有效关系数 + 旧号待迁移有效关系数」:超过十项整次失败,旧、新关系均不变。
// 与「新号已存在的同资产有效关系」冲突时整次失败回滚,不产生并存的有效关系。
// 返回每次迁移的审计事实;无有效关系时返回空。
func (w *AssociationWriter) Migrate(ctx context.Context, tx *gorm.DB, oldPhone, newPhone string) ([]accessauditapp.PhoneAssetAssociationChange, error) {
store := w.store.WithTx(tx)
if err := store.LockPhoneScopes(ctx, oldPhone, newPhone); err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "锁定手机号串行化点失败")
}
locked, err := store.LockValidByPhones(ctx, oldPhone, newPhone)
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "锁定手机号关联资产失败")
}
pending := make([]*model.PhoneAssetAssociation, 0, len(locked))
newPhoneValidCount := 0
for _, row := range locked {
if row.Phone == oldPhone {
pending = append(pending, row)
continue
}
newPhoneValidCount++
}
if newPhoneValidCount+len(pending) > constants.PhoneAssetAssociationMaxValidPerPhone {
return nil, errors.New(errors.CodeInvalidStatus, constants.PhoneAssetAssociationLimitMessage)
}
if len(pending) == 0 {
return nil, nil
}
now := time.Now()
if err := tx.WithContext(ctx).Model(&model.PhoneAssetAssociation{}).
Where("phone = ? AND status = ?", oldPhone, constants.PhoneAssetAssociationStatusValid).
Updates(map[string]any{"phone": newPhone, "updated_at": now}).Error; err != nil {
if isAssociationUniqueViolation(err) {
return nil, errors.New(errors.CodeInvalidStatus, "新手机号已存在与待迁移资产相同的有效关联,换绑已回滚")
}
return nil, errors.Wrap(errors.CodeDatabaseError, err, "迁移手机号资产关联失败")
}
oldPhoneMasked, newPhoneMasked := sanitizer.MaskPhone(oldPhone), sanitizer.MaskPhone(newPhone)
changes := make([]accessauditapp.PhoneAssetAssociationChange, 0, len(pending))
for _, row := range pending {
changes = append(changes, accessauditapp.PhoneAssetAssociationChange{
AssociationID: row.ID, PhoneMasked: newPhoneMasked,
AssetType: row.AssetType, AssetID: row.AssetID,
Status: constants.PhoneAssetAssociationStatusValid, Source: row.Source,
BeforeData: map[string]any{"phone_masked": oldPhoneMasked},
AfterData: map[string]any{"phone_masked": newPhoneMasked},
})
}
return changes, nil
}
// isAssociationUniqueViolation 判断错误是否为有效关系部分唯一索引冲突。
func isAssociationUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
if !stderrors.As(err, &pgErr) {
return false
}
return pgErr.Code == "23505" && pgErr.ConstraintName == associationUniqueConstraint
}