Compare commits

...

3 Commits

Author SHA1 Message Date
76b539e867 chore: 归档 OpenSpec 变更 refactor-series-binding-to-series-id
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 6m22s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-02-02 12:21:00 +08:00
b47f7b4f46 修复: 更新集成测试以适配 series_id 字段重命名
- 将所有测试用例的 series_allocation_id 改为 series_id
- 更新测试逻辑,直接使用 series.ID 而非 allocation.ID
- 修复禁用系列测试,直接禁用 PackageSeries 而非 ShopSeriesAllocation
- 所有集成测试通过验证
2026-02-02 12:16:55 +08:00
37f43d2e2d 重构: 将卡/设备的套餐系列绑定从分配ID改为系列ID
- 数据库: 重命名 series_allocation_id → series_id
- Model: IotCard 和 Device 字段重命名
- DTO: 所有请求/响应字段统一为 series_id
- Store: 方法重命名,新增 GetByShopAndSeries 查询
- Service: 业务逻辑优化,系列验证和权限验证分离
- 测试: 更新所有测试用例,新增 shop_series_allocation_store_test.go
- 文档: 更新 API 文档说明参数变更

BREAKING CHANGE: API 参数从 series_allocation_id 改为 series_id
2026-02-02 12:09:53 +08:00
34 changed files with 1487 additions and 355 deletions

View File

@@ -630,13 +630,13 @@ components:
minItems: 1 minItems: 1
nullable: true nullable: true
type: array type: array
series_allocation_id: series_id:
description: 套餐系列分配ID0表示清除关联 description: 套餐系列ID0表示清除关联
minimum: 0 minimum: 0
type: integer type: integer
required: required:
- iccids - iccids
- series_allocation_id - series_id
type: object type: object
DtoBatchSetCardSeriesBindngResponse: DtoBatchSetCardSeriesBindngResponse:
properties: properties:
@@ -664,13 +664,13 @@ components:
minItems: 1 minItems: 1
nullable: true nullable: true
type: array type: array
series_allocation_id: series_id:
description: 套餐系列分配ID0表示清除关联 description: 套餐系列ID0表示清除关联
minimum: 0 minimum: 0
type: integer type: integer
required: required:
- device_ids - device_ids
- series_allocation_id - series_id
type: object type: object
DtoBatchSetDeviceSeriesBindngResponse: DtoBatchSetDeviceSeriesBindngResponse:
properties: properties:
@@ -1090,9 +1090,13 @@ components:
minItems: 1 minItems: 1
nullable: true nullable: true
type: array type: array
payment_method:
description: 支付方式 (wallet:钱包支付, offline:线下支付)
type: string
required: required:
- order_type - order_type
- package_ids - package_ids
- payment_method
type: object type: object
DtoCreatePackageRequest: DtoCreatePackageRequest:
properties: properties:
@@ -1367,9 +1371,21 @@ components:
properties: properties:
base_commission: base_commission:
$ref: '#/components/schemas/DtoBaseCommissionConfig' $ref: '#/components/schemas/DtoBaseCommissionConfig'
enable_force_recharge:
description: 是否启用强充(累计充值强充)
nullable: true
type: boolean
enable_one_time_commission: enable_one_time_commission:
description: 是否启用一次性佣金 description: 是否启用一次性佣金
type: boolean type: boolean
force_recharge_amount:
description: 强充金额(分,0表示使用阈值金额)
nullable: true
type: integer
force_recharge_trigger_type:
description: 强充触发类型(1:单次充值, 2:累计充值)
nullable: true
type: integer
one_time_commission_config: one_time_commission_config:
$ref: '#/components/schemas/DtoOneTimeCommissionConfig' $ref: '#/components/schemas/DtoOneTimeCommissionConfig'
series_id: series_id:
@@ -1731,8 +1747,8 @@ components:
max_sim_slots: max_sim_slots:
description: 最大插槽数 description: 最大插槽数
type: integer type: integer
series_allocation_id: series_id:
description: 套餐系列分配ID description: 套餐系列ID
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
@@ -2301,8 +2317,8 @@ components:
real_name_status: real_name_status:
description: 实名状态 (0:未实名, 1:已实名) description: 实名状态 (0:未实名, 1:已实名)
type: integer type: integer
series_allocation_id: series_id:
description: 套餐系列分配ID description: 套餐系列ID
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
@@ -2707,6 +2723,9 @@ components:
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
is_purchase_on_behalf:
description: 是否为代购订单
type: boolean
items: items:
description: 订单明细列表 description: 订单明细列表
items: items:
@@ -3754,9 +3773,18 @@ components:
created_at: created_at:
description: 创建时间 description: 创建时间
type: string type: string
enable_force_recharge:
description: 是否启用强充
type: boolean
enable_one_time_commission: enable_one_time_commission:
description: 是否启用一次性佣金 description: 是否启用一次性佣金
type: boolean type: boolean
force_recharge_amount:
description: 强充金额(分)
type: integer
force_recharge_trigger_type:
description: 强充触发类型(1:单次充值, 2:累计充值)
type: integer
id: id:
description: 分配ID description: 分配ID
minimum: 0 minimum: 0
@@ -3952,8 +3980,8 @@ components:
real_name_status: real_name_status:
description: 实名状态 (0:未实名, 1:已实名) description: 实名状态 (0:未实名, 1:已实名)
type: integer type: integer
series_allocation_id: series_id:
description: 套餐系列分配ID description: 套餐系列ID
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
@@ -4405,10 +4433,22 @@ components:
properties: properties:
base_commission: base_commission:
$ref: '#/components/schemas/DtoBaseCommissionConfig' $ref: '#/components/schemas/DtoBaseCommissionConfig'
enable_force_recharge:
description: 是否启用强充(累计充值强充)
nullable: true
type: boolean
enable_one_time_commission: enable_one_time_commission:
description: 是否启用一次性佣金 description: 是否启用一次性佣金
nullable: true nullable: true
type: boolean type: boolean
force_recharge_amount:
description: 强充金额(分,0表示使用阈值金额)
nullable: true
type: integer
force_recharge_trigger_type:
description: 强充触发类型(1:单次充值, 2:累计充值)
nullable: true
type: integer
one_time_commission_config: one_time_commission_config:
$ref: '#/components/schemas/DtoOneTimeCommissionConfig' $ref: '#/components/schemas/DtoOneTimeCommissionConfig'
type: object type: object
@@ -6957,11 +6997,11 @@ paths:
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
- description: 套餐系列分配ID - description: 套餐系列ID
in: query in: query
name: series_allocation_id name: series_id
schema: schema:
description: 套餐系列分配ID description: 套餐系列ID
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
@@ -7836,7 +7876,7 @@ paths:
- 设备管理 - 设备管理
/api/admin/devices/series-binding: /api/admin/devices/series-binding:
patch: patch:
description: 批量设置或清除设备与套餐系列分配的关联关系。series_allocation_id 为 0 时表示清除关联。 description: 批量设置或清除设备与套餐系列分配的关联关系。参数:series_id套餐系列ID0表示清除关联
requestBody: requestBody:
content: content:
application/json: application/json:
@@ -8880,6 +8920,8 @@ paths:
/api/admin/iot-cards/import: /api/admin/iot-cards/import:
post: post:
description: |- description: |-
仅平台用户可操作。
## ⚠️ 接口变更说明BREAKING CHANGE ## ⚠️ 接口变更说明BREAKING CHANGE
本接口已从 `multipart/form-data` 改为 `application/json`。 本接口已从 `multipart/form-data` 改为 `application/json`。
@@ -8970,6 +9012,7 @@ paths:
- IoT卡管理 - IoT卡管理
/api/admin/iot-cards/import-tasks: /api/admin/iot-cards/import-tasks:
get: get:
description: 仅平台用户可操作。
parameters: parameters:
- description: 页码 - description: 页码
in: query in: query
@@ -9084,6 +9127,7 @@ paths:
- IoT卡管理 - IoT卡管理
/api/admin/iot-cards/import-tasks/{id}: /api/admin/iot-cards/import-tasks/{id}:
get: get:
description: 仅平台用户可操作。
parameters: parameters:
- description: 任务ID - description: 任务ID
in: path in: path
@@ -9151,7 +9195,7 @@ paths:
- IoT卡管理 - IoT卡管理
/api/admin/iot-cards/series-binding: /api/admin/iot-cards/series-binding:
patch: patch:
description: 批量设置或清除卡与套餐系列分配的关联关系。series_allocation_id 为 0 时表示清除关联。 description: 批量设置或清除卡与套餐系列分配的关联关系。参数:series_id套餐系列ID0表示清除关联
requestBody: requestBody:
content: content:
application/json: application/json:
@@ -9256,11 +9300,11 @@ paths:
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer
- description: 套餐系列分配ID - description: 套餐系列ID
in: query in: query
name: series_allocation_id name: series_id
schema: schema:
description: 套餐系列分配ID description: 套餐系列ID
minimum: 0 minimum: 0
nullable: true nullable: true
type: integer type: integer

View File

@@ -107,9 +107,9 @@ func initServices(s *stores, deps *Dependencies) *services {
Authorization: enterpriseCardSvc.NewAuthorizationService(s.Enterprise, s.IotCard, s.EnterpriseCardAuthorization, deps.Logger), Authorization: enterpriseCardSvc.NewAuthorizationService(s.Enterprise, s.IotCard, s.EnterpriseCardAuthorization, deps.Logger),
CustomerAccount: customerAccountSvc.New(deps.DB, s.Account, s.Shop, s.Enterprise), CustomerAccount: customerAccountSvc.New(deps.DB, s.Account, s.Shop, s.Enterprise),
MyCommission: myCommissionSvc.New(deps.DB, s.Shop, s.Wallet, s.CommissionWithdrawalRequest, s.CommissionWithdrawalSetting, s.CommissionRecord, s.WalletTransaction), MyCommission: myCommissionSvc.New(deps.DB, s.Shop, s.Wallet, s.CommissionWithdrawalRequest, s.CommissionWithdrawalSetting, s.CommissionRecord, s.WalletTransaction),
IotCard: iotCardSvc.New(deps.DB, s.IotCard, s.Shop, s.AssetAllocationRecord, s.ShopSeriesAllocation, deps.GatewayClient, deps.Logger), IotCard: iotCardSvc.New(deps.DB, s.IotCard, s.Shop, s.AssetAllocationRecord, s.ShopSeriesAllocation, s.PackageSeries, deps.GatewayClient, deps.Logger),
IotCardImport: iotCardImportSvc.New(deps.DB, s.IotCardImportTask, deps.QueueClient), IotCardImport: iotCardImportSvc.New(deps.DB, s.IotCardImportTask, deps.QueueClient),
Device: deviceSvc.New(deps.DB, s.Device, s.DeviceSimBinding, s.IotCard, s.Shop, s.AssetAllocationRecord, s.ShopSeriesAllocation), Device: deviceSvc.New(deps.DB, s.Device, s.DeviceSimBinding, s.IotCard, s.Shop, s.AssetAllocationRecord, s.ShopSeriesAllocation, s.PackageSeries),
DeviceImport: deviceImportSvc.New(deps.DB, s.DeviceImportTask, deps.QueueClient), DeviceImport: deviceImportSvc.New(deps.DB, s.DeviceImportTask, deps.QueueClient),
AssetAllocationRecord: assetAllocationRecordSvc.New(deps.DB, s.AssetAllocationRecord, s.Shop, s.Account), AssetAllocationRecord: assetAllocationRecordSvc.New(deps.DB, s.AssetAllocationRecord, s.Shop, s.Account),
Carrier: carrierSvc.New(s.Carrier), Carrier: carrierSvc.New(s.Carrier),

View File

@@ -25,7 +25,7 @@ type Device struct {
DeviceUsername string `gorm:"column:device_username;type:varchar(100);comment:设备登录用户名" json:"device_username"` DeviceUsername string `gorm:"column:device_username;type:varchar(100);comment:设备登录用户名" json:"device_username"`
DevicePasswordEncrypted string `gorm:"column:device_password_encrypted;type:varchar(255);comment:设备登录密码(加密)" json:"device_password_encrypted"` DevicePasswordEncrypted string `gorm:"column:device_password_encrypted;type:varchar(255);comment:设备登录密码(加密)" json:"device_password_encrypted"`
DeviceAPIEndpoint string `gorm:"column:device_api_endpoint;type:varchar(500);comment:设备API端点" json:"device_api_endpoint"` DeviceAPIEndpoint string `gorm:"column:device_api_endpoint;type:varchar(500);comment:设备API端点" json:"device_api_endpoint"`
SeriesAllocationID *uint `gorm:"column:series_allocation_id;index;comment:套餐系列分配ID(关联ShopSeriesAllocation)" json:"series_allocation_id,omitempty"` SeriesID *uint `gorm:"column:series_id;index;comment:套餐系列ID(关联PackageSeries)" json:"series_id,omitempty"`
FirstCommissionPaid bool `gorm:"column:first_commission_paid;type:boolean;default:false;comment:一次性佣金是否已发放" json:"first_commission_paid"` FirstCommissionPaid bool `gorm:"column:first_commission_paid;type:boolean;default:false;comment:一次性佣金是否已发放" json:"first_commission_paid"`
AccumulatedRecharge int64 `gorm:"column:accumulated_recharge;type:bigint;default:0;comment:累计充值金额(分)" json:"accumulated_recharge"` AccumulatedRecharge int64 `gorm:"column:accumulated_recharge;type:bigint;default:0;comment:累计充值金额(分)" json:"accumulated_recharge"`
} }

View File

@@ -3,18 +3,18 @@ package dto
import "time" import "time"
type ListDeviceRequest struct { type ListDeviceRequest struct {
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"` Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"` PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"`
DeviceNo string `json:"device_no" query:"device_no" validate:"omitempty,max=100" maxLength:"100" description:"设备号(模糊查询)"` DeviceNo string `json:"device_no" query:"device_no" validate:"omitempty,max=100" maxLength:"100" description:"设备号(模糊查询)"`
DeviceName string `json:"device_name" query:"device_name" validate:"omitempty,max=255" maxLength:"255" description:"设备名称(模糊查询)"` DeviceName string `json:"device_name" query:"device_name" validate:"omitempty,max=255" maxLength:"255" description:"设备名称(模糊查询)"`
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"状态 (1:在库, 2:已分销, 3:已激活, 4:已停用)"` Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"状态 (1:在库, 2:已分销, 3:已激活, 4:已停用)"`
ShopID *uint `json:"shop_id" query:"shop_id" description:"店铺ID (NULL表示平台库存)"` ShopID *uint `json:"shop_id" query:"shop_id" description:"店铺ID (NULL表示平台库存)"`
SeriesAllocationID *uint `json:"series_allocation_id" query:"series_allocation_id" description:"套餐系列分配ID"` SeriesID *uint `json:"series_id" query:"series_id" description:"套餐系列ID"`
BatchNo string `json:"batch_no" query:"batch_no" validate:"omitempty,max=100" maxLength:"100" description:"批次号"` BatchNo string `json:"batch_no" query:"batch_no" validate:"omitempty,max=100" maxLength:"100" description:"批次号"`
DeviceType string `json:"device_type" query:"device_type" validate:"omitempty,max=50" maxLength:"50" description:"设备类型"` DeviceType string `json:"device_type" query:"device_type" validate:"omitempty,max=50" maxLength:"50" description:"设备类型"`
Manufacturer string `json:"manufacturer" query:"manufacturer" validate:"omitempty,max=255" maxLength:"255" description:"制造商(模糊查询)"` Manufacturer string `json:"manufacturer" query:"manufacturer" validate:"omitempty,max=255" maxLength:"255" description:"制造商(模糊查询)"`
CreatedAtStart *time.Time `json:"created_at_start" query:"created_at_start" description:"创建时间起始"` CreatedAtStart *time.Time `json:"created_at_start" query:"created_at_start" description:"创建时间起始"`
CreatedAtEnd *time.Time `json:"created_at_end" query:"created_at_end" description:"创建时间结束"` CreatedAtEnd *time.Time `json:"created_at_end" query:"created_at_end" description:"创建时间结束"`
} }
type DeviceResponse struct { type DeviceResponse struct {
@@ -31,7 +31,7 @@ type DeviceResponse struct {
Status int `json:"status" description:"状态 (1:在库, 2:已分销, 3:已激活, 4:已停用)"` Status int `json:"status" description:"状态 (1:在库, 2:已分销, 3:已激活, 4:已停用)"`
StatusName string `json:"status_name" description:"状态名称"` StatusName string `json:"status_name" description:"状态名称"`
BoundCardCount int `json:"bound_card_count" description:"已绑定卡数量"` BoundCardCount int `json:"bound_card_count" description:"已绑定卡数量"`
SeriesAllocationID *uint `json:"series_allocation_id,omitempty" description:"套餐系列分配ID"` SeriesID *uint `json:"series_id,omitempty" description:"套餐系列ID"`
FirstCommissionPaid bool `json:"first_commission_paid" description:"一次性佣金是否已发放"` FirstCommissionPaid bool `json:"first_commission_paid" description:"一次性佣金是否已发放"`
AccumulatedRecharge int64 `json:"accumulated_recharge" description:"累计充值金额(分)"` AccumulatedRecharge int64 `json:"accumulated_recharge" description:"累计充值金额(分)"`
ActivatedAt *time.Time `json:"activated_at,omitempty" description:"激活时间"` ActivatedAt *time.Time `json:"activated_at,omitempty" description:"激活时间"`
@@ -129,8 +129,8 @@ type RecallDevicesResponse struct {
// BatchSetDeviceSeriesBindngRequest 批量设置设备的套餐系列绑定请求 // BatchSetDeviceSeriesBindngRequest 批量设置设备的套餐系列绑定请求
type BatchSetDeviceSeriesBindngRequest struct { type BatchSetDeviceSeriesBindngRequest struct {
DeviceIDs []uint `json:"device_ids" validate:"required,min=1,max=500,dive,required" required:"true" minItems:"1" maxItems:"500" description:"设备ID列表"` DeviceIDs []uint `json:"device_ids" validate:"required,min=1,max=500,dive,required" required:"true" minItems:"1" maxItems:"500" description:"设备ID列表"`
SeriesAllocationID uint `json:"series_allocation_id" validate:"required,min=0" required:"true" minimum:"0" description:"套餐系列分配ID0表示清除关联"` SeriesID uint `json:"series_id" validate:"required,min=0" required:"true" minimum:"0" description:"套餐系列ID0表示清除关联"`
} }
// DeviceSeriesBindngFailedItem 设备系列绑定失败项 // DeviceSeriesBindngFailedItem 设备系列绑定失败项

View File

@@ -3,20 +3,20 @@ package dto
import "time" import "time"
type ListStandaloneIotCardRequest struct { type ListStandaloneIotCardRequest struct {
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"` Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码"`
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"` PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量"`
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"状态 (1:在库, 2:已分销, 3:已激活, 4:已停用)"` Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"状态 (1:在库, 2:已分销, 3:已激活, 4:已停用)"`
CarrierID *uint `json:"carrier_id" query:"carrier_id" description:"运营商ID"` CarrierID *uint `json:"carrier_id" query:"carrier_id" description:"运营商ID"`
ShopID *uint `json:"shop_id" query:"shop_id" description:"分销商ID"` ShopID *uint `json:"shop_id" query:"shop_id" description:"分销商ID"`
SeriesAllocationID *uint `json:"series_allocation_id" query:"series_allocation_id" description:"套餐系列分配ID"` SeriesID *uint `json:"series_id" query:"series_id" description:"套餐系列ID"`
ICCID string `json:"iccid" query:"iccid" validate:"omitempty,max=20" maxLength:"20" description:"ICCID(模糊查询)"` ICCID string `json:"iccid" query:"iccid" validate:"omitempty,max=20" maxLength:"20" description:"ICCID(模糊查询)"`
MSISDN string `json:"msisdn" query:"msisdn" validate:"omitempty,max=20" maxLength:"20" description:"卡接入号(模糊查询)"` MSISDN string `json:"msisdn" query:"msisdn" validate:"omitempty,max=20" maxLength:"20" description:"卡接入号(模糊查询)"`
BatchNo string `json:"batch_no" query:"batch_no" validate:"omitempty,max=100" maxLength:"100" description:"批次号"` BatchNo string `json:"batch_no" query:"batch_no" validate:"omitempty,max=100" maxLength:"100" description:"批次号"`
PackageID *uint `json:"package_id" query:"package_id" description:"套餐ID"` PackageID *uint `json:"package_id" query:"package_id" description:"套餐ID"`
IsDistributed *bool `json:"is_distributed" query:"is_distributed" description:"是否已分销 (true:已分销, false:未分销)"` IsDistributed *bool `json:"is_distributed" query:"is_distributed" description:"是否已分销 (true:已分销, false:未分销)"`
IsReplaced *bool `json:"is_replaced" query:"is_replaced" description:"是否有换卡记录 (true:有换卡记录, false:无换卡记录)"` IsReplaced *bool `json:"is_replaced" query:"is_replaced" description:"是否有换卡记录 (true:有换卡记录, false:无换卡记录)"`
ICCIDStart string `json:"iccid_start" query:"iccid_start" validate:"omitempty,max=20" maxLength:"20" description:"ICCID起始号"` ICCIDStart string `json:"iccid_start" query:"iccid_start" validate:"omitempty,max=20" maxLength:"20" description:"ICCID起始号"`
ICCIDEnd string `json:"iccid_end" query:"iccid_end" validate:"omitempty,max=20" maxLength:"20" description:"ICCID结束号"` ICCIDEnd string `json:"iccid_end" query:"iccid_end" validate:"omitempty,max=20" maxLength:"20" description:"ICCID结束号"`
} }
type StandaloneIotCardResponse struct { type StandaloneIotCardResponse struct {
@@ -41,7 +41,7 @@ type StandaloneIotCardResponse struct {
RealNameStatus int `json:"real_name_status" description:"实名状态 (0:未实名, 1:已实名)"` RealNameStatus int `json:"real_name_status" description:"实名状态 (0:未实名, 1:已实名)"`
NetworkStatus int `json:"network_status" description:"网络状态 (0:停机, 1:开机)"` NetworkStatus int `json:"network_status" description:"网络状态 (0:停机, 1:开机)"`
DataUsageMB int64 `json:"data_usage_mb" description:"累计流量使用(MB)"` DataUsageMB int64 `json:"data_usage_mb" description:"累计流量使用(MB)"`
SeriesAllocationID *uint `json:"series_allocation_id,omitempty" description:"套餐系列分配ID"` SeriesID *uint `json:"series_id,omitempty" description:"套餐系列ID"`
FirstCommissionPaid bool `json:"first_commission_paid" description:"一次性佣金是否已发放"` FirstCommissionPaid bool `json:"first_commission_paid" description:"一次性佣金是否已发放"`
AccumulatedRecharge int64 `json:"accumulated_recharge" description:"累计充值金额(分)"` AccumulatedRecharge int64 `json:"accumulated_recharge" description:"累计充值金额(分)"`
CreatedAt time.Time `json:"created_at" description:"创建时间"` CreatedAt time.Time `json:"created_at" description:"创建时间"`
@@ -133,8 +133,8 @@ type IotCardDetailResponse struct {
// BatchSetCardSeriesBindngRequest 批量设置卡的套餐系列绑定请求 // BatchSetCardSeriesBindngRequest 批量设置卡的套餐系列绑定请求
type BatchSetCardSeriesBindngRequest struct { type BatchSetCardSeriesBindngRequest struct {
ICCIDs []string `json:"iccids" validate:"required,min=1,max=500,dive,required" required:"true" minItems:"1" maxItems:"500" description:"ICCID列表"` ICCIDs []string `json:"iccids" validate:"required,min=1,max=500,dive,required" required:"true" minItems:"1" maxItems:"500" description:"ICCID列表"`
SeriesAllocationID uint `json:"series_allocation_id" validate:"required,min=0" required:"true" minimum:"0" description:"套餐系列分配ID0表示清除关联"` SeriesID uint `json:"series_id" validate:"required,min=0" required:"true" minimum:"0" description:"套餐系列ID0表示清除关联"`
} }
// CardSeriesBindngFailedItem 卡系列绑定失败项 // CardSeriesBindngFailedItem 卡系列绑定失败项

View File

@@ -35,7 +35,7 @@ type IotCard struct {
LastDataCheckAt *time.Time `gorm:"column:last_data_check_at;comment:最后一次流量检查时间" json:"last_data_check_at"` LastDataCheckAt *time.Time `gorm:"column:last_data_check_at;comment:最后一次流量检查时间" json:"last_data_check_at"`
LastRealNameCheckAt *time.Time `gorm:"column:last_real_name_check_at;comment:最后一次实名检查时间" json:"last_real_name_check_at"` LastRealNameCheckAt *time.Time `gorm:"column:last_real_name_check_at;comment:最后一次实名检查时间" json:"last_real_name_check_at"`
LastSyncTime *time.Time `gorm:"column:last_sync_time;comment:最后一次与Gateway同步时间" json:"last_sync_time"` LastSyncTime *time.Time `gorm:"column:last_sync_time;comment:最后一次与Gateway同步时间" json:"last_sync_time"`
SeriesAllocationID *uint `gorm:"column:series_allocation_id;index;comment:套餐系列分配ID(关联ShopSeriesAllocation)" json:"series_allocation_id,omitempty"` SeriesID *uint `gorm:"column:series_id;index;comment:套餐系列ID(关联PackageSeries)" json:"series_id,omitempty"`
FirstCommissionPaid bool `gorm:"column:first_commission_paid;type:boolean;default:false;comment:一次性佣金是否已发放" json:"first_commission_paid"` FirstCommissionPaid bool `gorm:"column:first_commission_paid;type:boolean;default:false;comment:一次性佣金是否已发放" json:"first_commission_paid"`
AccumulatedRecharge int64 `gorm:"column:accumulated_recharge;type:bigint;default:0;comment:累计充值金额(分)" json:"accumulated_recharge"` AccumulatedRecharge int64 `gorm:"column:accumulated_recharge;type:bigint;default:0;comment:累计充值金额(分)" json:"accumulated_recharge"`
} }

View File

@@ -137,7 +137,7 @@ func registerDeviceRoutes(router fiber.Router, handler *admin.DeviceHandler, imp
Register(devices, doc, groupPath, "PATCH", "/series-binding", handler.BatchSetSeriesBinding, RouteSpec{ Register(devices, doc, groupPath, "PATCH", "/series-binding", handler.BatchSetSeriesBinding, RouteSpec{
Summary: "批量设置设备的套餐系列绑定", Summary: "批量设置设备的套餐系列绑定",
Description: "批量设置或清除设备与套餐系列分配的关联关系。series_allocation_id 为 0 时表示清除关联。", Description: "批量设置或清除设备与套餐系列分配的关联关系。参数:series_id套餐系列ID0表示清除关联。",
Tags: []string{"设备管理"}, Tags: []string{"设备管理"},
Input: new(dto.BatchSetDeviceSeriesBindngRequest), Input: new(dto.BatchSetDeviceSeriesBindngRequest),
Output: new(dto.BatchSetDeviceSeriesBindngResponse), Output: new(dto.BatchSetDeviceSeriesBindngResponse),

View File

@@ -101,7 +101,7 @@ func registerIotCardRoutes(router fiber.Router, handler *admin.IotCardHandler, i
Register(iotCards, doc, groupPath, "PATCH", "/series-binding", handler.BatchSetSeriesBinding, RouteSpec{ Register(iotCards, doc, groupPath, "PATCH", "/series-binding", handler.BatchSetSeriesBinding, RouteSpec{
Summary: "批量设置卡的套餐系列绑定", Summary: "批量设置卡的套餐系列绑定",
Description: "批量设置或清除卡与套餐系列分配的关联关系。series_allocation_id 为 0 时表示清除关联。", Description: "批量设置或清除卡与套餐系列分配的关联关系。参数:series_id套餐系列ID0表示清除关联。",
Tags: []string{"IoT卡管理"}, Tags: []string{"IoT卡管理"},
Input: new(dto.BatchSetCardSeriesBindngRequest), Input: new(dto.BatchSetCardSeriesBindngRequest),
Output: new(dto.BatchSetCardSeriesBindngResponse), Output: new(dto.BatchSetCardSeriesBindngResponse),

View File

@@ -202,11 +202,11 @@ func (s *Service) triggerOneTimeCommissionForCardInTx(ctx context.Context, tx *g
return errors.Wrap(errors.CodeDatabaseError, err, "获取卡信息失败") return errors.Wrap(errors.CodeDatabaseError, err, "获取卡信息失败")
} }
if card.SeriesAllocationID == nil { if card.SeriesID == nil || card.ShopID == nil {
return nil return nil
} }
allocation, err := s.shopSeriesAllocationStore.GetByID(ctx, *card.SeriesAllocationID) allocation, err := s.shopSeriesAllocationStore.GetByShopAndSeries(ctx, *card.ShopID, *card.SeriesID)
if err != nil { if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "获取系列分配失败") return errors.Wrap(errors.CodeDatabaseError, err, "获取系列分配失败")
} }
@@ -302,11 +302,11 @@ func (s *Service) triggerOneTimeCommissionForDeviceInTx(ctx context.Context, tx
return errors.Wrap(errors.CodeDatabaseError, err, "获取设备信息失败") return errors.Wrap(errors.CodeDatabaseError, err, "获取设备信息失败")
} }
if device.SeriesAllocationID == nil { if device.SeriesID == nil || device.ShopID == nil {
return nil return nil
} }
allocation, err := s.shopSeriesAllocationStore.GetByID(ctx, *device.SeriesAllocationID) allocation, err := s.shopSeriesAllocationStore.GetByShopAndSeries(ctx, *device.ShopID, *device.SeriesID)
if err != nil { if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "获取系列分配失败") return errors.Wrap(errors.CodeDatabaseError, err, "获取系列分配失败")
} }

View File

@@ -101,7 +101,7 @@ func TestCalculateCommission_PurchaseOnBehalf(t *testing.T) {
}, },
ICCID: "89860000000000000001", ICCID: "89860000000000000001",
ShopID: &shop.ID, ShopID: &shop.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
AccumulatedRecharge: 0, AccumulatedRecharge: 0,
FirstCommissionPaid: false, FirstCommissionPaid: false,
} }
@@ -278,7 +278,7 @@ func TestCalculateCommission_Device_PurchaseOnBehalf(t *testing.T) {
}, },
DeviceNo: "DEV001", DeviceNo: "DEV001",
ShopID: &shop.ID, ShopID: &shop.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
AccumulatedRecharge: 0, AccumulatedRecharge: 0,
FirstCommissionPaid: false, FirstCommissionPaid: false,
} }

View File

@@ -20,6 +20,8 @@ type Service struct {
shopStore *postgres.ShopStore shopStore *postgres.ShopStore
assetAllocationRecordStore *postgres.AssetAllocationRecordStore assetAllocationRecordStore *postgres.AssetAllocationRecordStore
seriesAllocationStore *postgres.ShopSeriesAllocationStore seriesAllocationStore *postgres.ShopSeriesAllocationStore
packageSeriesStore *postgres.PackageSeriesStore
shopSeriesAllocationStore *postgres.ShopSeriesAllocationStore
} }
func New( func New(
@@ -30,6 +32,7 @@ func New(
shopStore *postgres.ShopStore, shopStore *postgres.ShopStore,
assetAllocationRecordStore *postgres.AssetAllocationRecordStore, assetAllocationRecordStore *postgres.AssetAllocationRecordStore,
seriesAllocationStore *postgres.ShopSeriesAllocationStore, seriesAllocationStore *postgres.ShopSeriesAllocationStore,
packageSeriesStore *postgres.PackageSeriesStore,
) *Service { ) *Service {
return &Service{ return &Service{
db: db, db: db,
@@ -39,6 +42,8 @@ func New(
shopStore: shopStore, shopStore: shopStore,
assetAllocationRecordStore: assetAllocationRecordStore, assetAllocationRecordStore: assetAllocationRecordStore,
seriesAllocationStore: seriesAllocationStore, seriesAllocationStore: seriesAllocationStore,
packageSeriesStore: packageSeriesStore,
shopSeriesAllocationStore: seriesAllocationStore,
} }
} }
@@ -86,8 +91,8 @@ func (s *Service) List(ctx context.Context, req *dto.ListDeviceRequest) (*dto.Li
if req.CreatedAtEnd != nil { if req.CreatedAtEnd != nil {
filters["created_at_end"] = *req.CreatedAtEnd filters["created_at_end"] = *req.CreatedAtEnd
} }
if req.SeriesAllocationID != nil { if req.SeriesID != nil {
filters["series_allocation_id"] = *req.SeriesAllocationID filters["series_id"] = *req.SeriesID
} }
devices, total, err := s.deviceStore.List(ctx, opts, filters) devices, total, err := s.deviceStore.List(ctx, opts, filters)
@@ -466,7 +471,7 @@ func (s *Service) toDeviceResponse(device *model.Device, shopMap map[uint]string
Status: device.Status, Status: device.Status,
StatusName: s.getDeviceStatusName(device.Status), StatusName: s.getDeviceStatusName(device.Status),
BoundCardCount: int(bindingCounts[device.ID]), BoundCardCount: int(bindingCounts[device.ID]),
SeriesAllocationID: device.SeriesAllocationID, SeriesID: device.SeriesID,
FirstCommissionPaid: device.FirstCommissionPaid, FirstCommissionPaid: device.FirstCommissionPaid,
AccumulatedRecharge: device.AccumulatedRecharge, AccumulatedRecharge: device.AccumulatedRecharge,
ActivatedAt: device.ActivatedAt, ActivatedAt: device.ActivatedAt,
@@ -598,17 +603,18 @@ func (s *Service) BatchSetSeriesBinding(ctx context.Context, req *dto.BatchSetDe
deviceMap[device.ID] = device deviceMap[device.ID] = device
} }
var seriesAllocation *model.ShopSeriesAllocation // 验证系列存在(仅当 SeriesID > 0 时)
if req.SeriesAllocationID > 0 { var packageSeries *model.PackageSeries
seriesAllocation, err = s.seriesAllocationStore.GetByID(ctx, req.SeriesAllocationID) if req.SeriesID > 0 {
packageSeries, err = s.packageSeriesStore.GetByID(ctx, req.SeriesID)
if err != nil { if err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeNotFound, "套餐系列分配不存在") return nil, errors.New(errors.CodeNotFound, "套餐系列不存在或已禁用")
} }
return nil, err return nil, err
} }
if seriesAllocation.Status != 1 { if packageSeries.Status != 1 {
return nil, errors.New(errors.CodeInvalidParam, "套餐系列分配已禁用") return nil, errors.New(errors.CodeInvalidParam, "套餐系列不存在或已禁用")
} }
} }
@@ -626,17 +632,23 @@ func (s *Service) BatchSetSeriesBinding(ctx context.Context, req *dto.BatchSetDe
continue continue
} }
if req.SeriesAllocationID > 0 { // 验证操作者权限(仅代理用户)
if device.ShopID == nil || *device.ShopID != seriesAllocation.ShopID { if operatorShopID != nil && req.SeriesID > 0 {
failedItems = append(failedItems, dto.DeviceSeriesBindngFailedItem{ allocation, err := s.shopSeriesAllocationStore.GetByShopAndSeries(ctx, *operatorShopID, req.SeriesID)
DeviceID: device.ID, if err != nil {
DeviceNo: device.DeviceNo, if err == gorm.ErrRecordNotFound || allocation.Status != 1 {
Reason: "设备不属于套餐系列分配的店铺", failedItems = append(failedItems, dto.DeviceSeriesBindngFailedItem{
}) DeviceID: deviceID,
continue DeviceNo: device.DeviceNo,
Reason: "您没有权限分配该套餐系列",
})
continue
}
return nil, err
} }
} }
// 验证设备权限(基于 device.ShopID
if operatorShopID != nil { if operatorShopID != nil {
if device.ShopID == nil || *device.ShopID != *operatorShopID { if device.ShopID == nil || *device.ShopID != *operatorShopID {
failedItems = append(failedItems, dto.DeviceSeriesBindngFailedItem{ failedItems = append(failedItems, dto.DeviceSeriesBindngFailedItem{
@@ -652,11 +664,11 @@ func (s *Service) BatchSetSeriesBinding(ctx context.Context, req *dto.BatchSetDe
} }
if len(successDeviceIDs) > 0 { if len(successDeviceIDs) > 0 {
var seriesAllocationIDPtr *uint var seriesIDPtr *uint
if req.SeriesAllocationID > 0 { if req.SeriesID > 0 {
seriesAllocationIDPtr = &req.SeriesAllocationID seriesIDPtr = &req.SeriesID
} }
if err := s.deviceStore.BatchUpdateSeriesAllocation(ctx, successDeviceIDs, seriesAllocationIDPtr); err != nil { if err := s.deviceStore.BatchUpdateSeriesID(ctx, successDeviceIDs, seriesIDPtr); err != nil {
return nil, err return nil, err
} }
} }

View File

@@ -29,8 +29,9 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
shopStore := postgres.NewShopStore(tx, rdb) shopStore := postgres.NewShopStore(tx, rdb)
assetAllocationRecordStore := postgres.NewAssetAllocationRecordStore(tx, rdb) assetAllocationRecordStore := postgres.NewAssetAllocationRecordStore(tx, rdb)
seriesAllocationStore := postgres.NewShopSeriesAllocationStore(tx) seriesAllocationStore := postgres.NewShopSeriesAllocationStore(tx)
packageSeriesStore := postgres.NewPackageSeriesStore(tx)
svc := New(tx, deviceStore, deviceSimBindingStore, iotCardStore, shopStore, assetAllocationRecordStore, seriesAllocationStore) svc := New(tx, deviceStore, deviceSimBindingStore, iotCardStore, shopStore, assetAllocationRecordStore, seriesAllocationStore, packageSeriesStore)
ctx := context.Background() ctx := context.Background()
shop := &model.Shop{ shop := &model.Shop{
@@ -65,8 +66,8 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
t.Run("成功设置系列绑定", func(t *testing.T) { t.Run("成功设置系列绑定", func(t *testing.T) {
req := &dto.BatchSetDeviceSeriesBindngRequest{ req := &dto.BatchSetDeviceSeriesBindngRequest{
DeviceIDs: []uint{devices[0].ID, devices[1].ID}, DeviceIDs: []uint{devices[0].ID, devices[1].ID},
SeriesAllocationID: allocation.ID, SeriesID: allocation.SeriesID,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -77,15 +78,15 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
var updatedDevices []*model.Device var updatedDevices []*model.Device
require.NoError(t, tx.Where("id IN ?", req.DeviceIDs).Find(&updatedDevices).Error) require.NoError(t, tx.Where("id IN ?", req.DeviceIDs).Find(&updatedDevices).Error)
for _, device := range updatedDevices { for _, device := range updatedDevices {
require.NotNil(t, device.SeriesAllocationID) require.NotNil(t, device.SeriesID)
assert.Equal(t, allocation.ID, *device.SeriesAllocationID) assert.Equal(t, allocation.SeriesID, *device.SeriesID)
} }
}) })
t.Run("设备不属于套餐系列分配的店铺", func(t *testing.T) { t.Run("设备不属于套餐系列分配的店铺", func(t *testing.T) {
req := &dto.BatchSetDeviceSeriesBindngRequest{ req := &dto.BatchSetDeviceSeriesBindngRequest{
DeviceIDs: []uint{devices[2].ID}, DeviceIDs: []uint{devices[2].ID},
SeriesAllocationID: allocation.ID, SeriesID: allocation.SeriesID,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -97,8 +98,8 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
t.Run("设备不存在", func(t *testing.T) { t.Run("设备不存在", func(t *testing.T) {
req := &dto.BatchSetDeviceSeriesBindngRequest{ req := &dto.BatchSetDeviceSeriesBindngRequest{
DeviceIDs: []uint{99999}, DeviceIDs: []uint{99999},
SeriesAllocationID: allocation.ID, SeriesID: allocation.SeriesID,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -110,8 +111,8 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
t.Run("清除系列绑定", func(t *testing.T) { t.Run("清除系列绑定", func(t *testing.T) {
req := &dto.BatchSetDeviceSeriesBindngRequest{ req := &dto.BatchSetDeviceSeriesBindngRequest{
DeviceIDs: []uint{devices[0].ID}, DeviceIDs: []uint{devices[0].ID},
SeriesAllocationID: 0, SeriesID: 0,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -120,14 +121,14 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
var updatedDevice model.Device var updatedDevice model.Device
require.NoError(t, tx.First(&updatedDevice, devices[0].ID).Error) require.NoError(t, tx.First(&updatedDevice, devices[0].ID).Error)
assert.Nil(t, updatedDevice.SeriesAllocationID) assert.Nil(t, updatedDevice.SeriesID)
}) })
t.Run("代理用户只能操作自己店铺的设备", func(t *testing.T) { t.Run("代理用户只能操作自己店铺的设备", func(t *testing.T) {
otherShopID := uint(99999) otherShopID := uint(99999)
req := &dto.BatchSetDeviceSeriesBindngRequest{ req := &dto.BatchSetDeviceSeriesBindngRequest{
DeviceIDs: []uint{devices[1].ID}, DeviceIDs: []uint{devices[1].ID},
SeriesAllocationID: 0, SeriesID: 0,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, &otherShopID) resp, err := svc.BatchSetSeriesBinding(ctx, req, &otherShopID)
@@ -139,8 +140,8 @@ func TestDeviceService_BatchSetSeriesBinding(t *testing.T) {
t.Run("套餐系列分配不存在", func(t *testing.T) { t.Run("套餐系列分配不存在", func(t *testing.T) {
req := &dto.BatchSetDeviceSeriesBindngRequest{ req := &dto.BatchSetDeviceSeriesBindngRequest{
DeviceIDs: []uint{devices[1].ID}, DeviceIDs: []uint{devices[1].ID},
SeriesAllocationID: 99999, SeriesID: 99999,
} }
_, err := svc.BatchSetSeriesBinding(ctx, req, nil) _, err := svc.BatchSetSeriesBinding(ctx, req, nil)

View File

@@ -20,6 +20,7 @@ type Service struct {
shopStore *postgres.ShopStore shopStore *postgres.ShopStore
assetAllocationRecordStore *postgres.AssetAllocationRecordStore assetAllocationRecordStore *postgres.AssetAllocationRecordStore
seriesAllocationStore *postgres.ShopSeriesAllocationStore seriesAllocationStore *postgres.ShopSeriesAllocationStore
packageSeriesStore *postgres.PackageSeriesStore
gatewayClient *gateway.Client gatewayClient *gateway.Client
logger *zap.Logger logger *zap.Logger
} }
@@ -30,6 +31,7 @@ func New(
shopStore *postgres.ShopStore, shopStore *postgres.ShopStore,
assetAllocationRecordStore *postgres.AssetAllocationRecordStore, assetAllocationRecordStore *postgres.AssetAllocationRecordStore,
seriesAllocationStore *postgres.ShopSeriesAllocationStore, seriesAllocationStore *postgres.ShopSeriesAllocationStore,
packageSeriesStore *postgres.PackageSeriesStore,
gatewayClient *gateway.Client, gatewayClient *gateway.Client,
logger *zap.Logger, logger *zap.Logger,
) *Service { ) *Service {
@@ -39,6 +41,7 @@ func New(
shopStore: shopStore, shopStore: shopStore,
assetAllocationRecordStore: assetAllocationRecordStore, assetAllocationRecordStore: assetAllocationRecordStore,
seriesAllocationStore: seriesAllocationStore, seriesAllocationStore: seriesAllocationStore,
packageSeriesStore: packageSeriesStore,
gatewayClient: gatewayClient, gatewayClient: gatewayClient,
logger: logger, logger: logger,
} }
@@ -93,8 +96,8 @@ func (s *Service) ListStandalone(ctx context.Context, req *dto.ListStandaloneIot
if req.IsReplaced != nil { if req.IsReplaced != nil {
filters["is_replaced"] = *req.IsReplaced filters["is_replaced"] = *req.IsReplaced
} }
if req.SeriesAllocationID != nil { if req.SeriesID != nil {
filters["series_allocation_id"] = *req.SeriesAllocationID filters["series_id"] = *req.SeriesID
} }
cards, total, err := s.iotCardStore.ListStandalone(ctx, opts, filters) cards, total, err := s.iotCardStore.ListStandalone(ctx, opts, filters)
@@ -187,7 +190,7 @@ func (s *Service) toStandaloneResponse(card *model.IotCard, shopMap map[uint]str
RealNameStatus: card.RealNameStatus, RealNameStatus: card.RealNameStatus,
NetworkStatus: card.NetworkStatus, NetworkStatus: card.NetworkStatus,
DataUsageMB: card.DataUsageMB, DataUsageMB: card.DataUsageMB,
SeriesAllocationID: card.SeriesAllocationID, SeriesID: card.SeriesID,
FirstCommissionPaid: card.FirstCommissionPaid, FirstCommissionPaid: card.FirstCommissionPaid,
AccumulatedRecharge: card.AccumulatedRecharge, AccumulatedRecharge: card.AccumulatedRecharge,
CreatedAt: card.CreatedAt, CreatedAt: card.CreatedAt,
@@ -571,17 +574,18 @@ func (s *Service) BatchSetSeriesBinding(ctx context.Context, req *dto.BatchSetCa
cardMap[card.ICCID] = card cardMap[card.ICCID] = card
} }
var seriesAllocation *model.ShopSeriesAllocation // 验证系列存在(仅当 SeriesID > 0 时)
if req.SeriesAllocationID > 0 { var packageSeries *model.PackageSeries
seriesAllocation, err = s.seriesAllocationStore.GetByID(ctx, req.SeriesAllocationID) if req.SeriesID > 0 {
packageSeries, err = s.packageSeriesStore.GetByID(ctx, req.SeriesID)
if err != nil { if err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeNotFound, "套餐系列分配不存在") return nil, errors.New(errors.CodeNotFound, "套餐系列不存在或已禁用")
} }
return nil, err return nil, err
} }
if seriesAllocation.Status != 1 { if packageSeries.Status != 1 {
return nil, errors.New(errors.CodeInvalidParam, "套餐系列分配已禁用") return nil, errors.New(errors.CodeInvalidParam, "套餐系列不存在或已禁用")
} }
} }
@@ -598,16 +602,22 @@ func (s *Service) BatchSetSeriesBinding(ctx context.Context, req *dto.BatchSetCa
continue continue
} }
if req.SeriesAllocationID > 0 { // 验证操作者权限(仅代理用户)
if card.ShopID == nil || *card.ShopID != seriesAllocation.ShopID { if operatorShopID != nil && req.SeriesID > 0 {
failedItems = append(failedItems, dto.CardSeriesBindngFailedItem{ allocation, err := s.seriesAllocationStore.GetByShopAndSeries(ctx, *operatorShopID, req.SeriesID)
ICCID: iccid, if err != nil {
Reason: "卡不属于套餐系列分配的店铺", if err == gorm.ErrRecordNotFound || allocation.Status != 1 {
}) failedItems = append(failedItems, dto.CardSeriesBindngFailedItem{
continue ICCID: iccid,
Reason: "您没有权限分配该套餐系列",
})
continue
}
return nil, err
} }
} }
// 验证卡权限(基于 card.ShopID
if operatorShopID != nil { if operatorShopID != nil {
if card.ShopID == nil || *card.ShopID != *operatorShopID { if card.ShopID == nil || *card.ShopID != *operatorShopID {
failedItems = append(failedItems, dto.CardSeriesBindngFailedItem{ failedItems = append(failedItems, dto.CardSeriesBindngFailedItem{
@@ -622,11 +632,11 @@ func (s *Service) BatchSetSeriesBinding(ctx context.Context, req *dto.BatchSetCa
} }
if len(successCardIDs) > 0 { if len(successCardIDs) > 0 {
var seriesAllocationIDPtr *uint var seriesIDPtr *uint
if req.SeriesAllocationID > 0 { if req.SeriesID > 0 {
seriesAllocationIDPtr = &req.SeriesAllocationID seriesIDPtr = &req.SeriesID
} }
if err := s.iotCardStore.BatchUpdateSeriesAllocation(ctx, successCardIDs, seriesAllocationIDPtr); err != nil { if err := s.iotCardStore.BatchUpdateSeriesID(ctx, successCardIDs, seriesIDPtr); err != nil {
return nil, err return nil, err
} }
} }

View File

@@ -28,7 +28,8 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
assetAllocationRecordStore := postgres.NewAssetAllocationRecordStore(tx, rdb) assetAllocationRecordStore := postgres.NewAssetAllocationRecordStore(tx, rdb)
seriesAllocationStore := postgres.NewShopSeriesAllocationStore(tx) seriesAllocationStore := postgres.NewShopSeriesAllocationStore(tx)
svc := New(tx, iotCardStore, shopStore, assetAllocationRecordStore, seriesAllocationStore, nil, nil) packageSeriesStore := postgres.NewPackageSeriesStore(tx)
svc := New(tx, iotCardStore, shopStore, assetAllocationRecordStore, seriesAllocationStore, packageSeriesStore, nil, nil)
ctx := context.Background() ctx := context.Background()
shop := &model.Shop{ shop := &model.Shop{
@@ -63,8 +64,8 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
t.Run("成功设置系列绑定", func(t *testing.T) { t.Run("成功设置系列绑定", func(t *testing.T) {
req := &dto.BatchSetCardSeriesBindngRequest{ req := &dto.BatchSetCardSeriesBindngRequest{
ICCIDs: []string{prefix + "001", prefix + "002"}, ICCIDs: []string{prefix + "001", prefix + "002"},
SeriesAllocationID: allocation.ID, SeriesID: allocation.SeriesID,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -75,15 +76,15 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
var updatedCards []*model.IotCard var updatedCards []*model.IotCard
require.NoError(t, tx.Where("iccid IN ?", req.ICCIDs).Find(&updatedCards).Error) require.NoError(t, tx.Where("iccid IN ?", req.ICCIDs).Find(&updatedCards).Error)
for _, card := range updatedCards { for _, card := range updatedCards {
require.NotNil(t, card.SeriesAllocationID) require.NotNil(t, card.SeriesID)
assert.Equal(t, allocation.ID, *card.SeriesAllocationID) assert.Equal(t, allocation.SeriesID, *card.SeriesID)
} }
}) })
t.Run("卡不属于套餐系列分配的店铺", func(t *testing.T) { t.Run("卡不属于套餐系列分配的店铺", func(t *testing.T) {
req := &dto.BatchSetCardSeriesBindngRequest{ req := &dto.BatchSetCardSeriesBindngRequest{
ICCIDs: []string{prefix + "003"}, ICCIDs: []string{prefix + "003"},
SeriesAllocationID: allocation.ID, SeriesID: allocation.SeriesID,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -95,8 +96,8 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
t.Run("卡不存在", func(t *testing.T) { t.Run("卡不存在", func(t *testing.T) {
req := &dto.BatchSetCardSeriesBindngRequest{ req := &dto.BatchSetCardSeriesBindngRequest{
ICCIDs: []string{"NOTEXIST001"}, ICCIDs: []string{"NOTEXIST001"},
SeriesAllocationID: allocation.ID, SeriesID: allocation.SeriesID,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -108,8 +109,8 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
t.Run("清除系列绑定", func(t *testing.T) { t.Run("清除系列绑定", func(t *testing.T) {
req := &dto.BatchSetCardSeriesBindngRequest{ req := &dto.BatchSetCardSeriesBindngRequest{
ICCIDs: []string{prefix + "001"}, ICCIDs: []string{prefix + "001"},
SeriesAllocationID: 0, SeriesID: 0,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, nil) resp, err := svc.BatchSetSeriesBinding(ctx, req, nil)
@@ -118,14 +119,14 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
var updatedCard model.IotCard var updatedCard model.IotCard
require.NoError(t, tx.Where("iccid = ?", prefix+"001").First(&updatedCard).Error) require.NoError(t, tx.Where("iccid = ?", prefix+"001").First(&updatedCard).Error)
assert.Nil(t, updatedCard.SeriesAllocationID) assert.Nil(t, updatedCard.SeriesID)
}) })
t.Run("代理用户只能操作自己店铺的卡", func(t *testing.T) { t.Run("代理用户只能操作自己店铺的卡", func(t *testing.T) {
otherShopID := uint(99999) otherShopID := uint(99999)
req := &dto.BatchSetCardSeriesBindngRequest{ req := &dto.BatchSetCardSeriesBindngRequest{
ICCIDs: []string{prefix + "002"}, ICCIDs: []string{prefix + "002"},
SeriesAllocationID: 0, SeriesID: 0,
} }
resp, err := svc.BatchSetSeriesBinding(ctx, req, &otherShopID) resp, err := svc.BatchSetSeriesBinding(ctx, req, &otherShopID)
@@ -137,8 +138,8 @@ func TestIotCardService_BatchSetSeriesBinding(t *testing.T) {
t.Run("套餐系列分配不存在", func(t *testing.T) { t.Run("套餐系列分配不存在", func(t *testing.T) {
req := &dto.BatchSetCardSeriesBindngRequest{ req := &dto.BatchSetCardSeriesBindngRequest{
ICCIDs: []string{prefix + "002"}, ICCIDs: []string{prefix + "002"},
SeriesAllocationID: 99999, SeriesID: 99999,
} }
_, err := svc.BatchSetSeriesBinding(ctx, req, nil) _, err := svc.BatchSetSeriesBinding(ctx, req, nil)

View File

@@ -99,21 +99,21 @@ func setupOrderTestEnv(t *testing.T) *testEnv {
shopIDPtr := &shop.ID shopIDPtr := &shop.ID
card := &model.IotCard{ card := &model.IotCard{
ICCID: "89860000000000000002", ICCID: "89860000000000000002",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
} }
require.NoError(t, iotCardStore.Create(ctx, card)) require.NoError(t, iotCardStore.Create(ctx, card))
device := &model.Device{ device := &model.Device{
DeviceNo: "DEV_TEST_ORDER_001", DeviceNo: "DEV_TEST_ORDER_001",
ShopID: shopIDPtr, ShopID: shopIDPtr,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
} }
require.NoError(t, deviceStore.Create(ctx, device)) require.NoError(t, deviceStore.Create(ctx, device))
@@ -569,12 +569,12 @@ func TestOrderService_IdempotencyAndConcurrency(t *testing.T) {
shopIDPtr := &shop.ID shopIDPtr := &shop.ID
card := &model.IotCard{ card := &model.IotCard{
ICCID: "89860000000000000099", ICCID: "89860000000000000099",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
} }
require.NoError(t, iotCardStore.Create(ctx, card)) require.NoError(t, iotCardStore.Create(ctx, card))
@@ -769,7 +769,7 @@ func TestOrderService_ForceRechargeValidation(t *testing.T) {
ICCID: "89860000000000000FR1", ICCID: "89860000000000000FR1",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
FirstCommissionPaid: false, FirstCommissionPaid: false,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
@@ -820,7 +820,7 @@ func TestOrderService_ForceRechargeValidation(t *testing.T) {
ICCID: "89860000000000000FR2", ICCID: "89860000000000000FR2",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
FirstCommissionPaid: true, FirstCommissionPaid: true,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
@@ -917,7 +917,7 @@ func TestOrderService_GetPurchaseCheck(t *testing.T) {
ICCID: "89860000000000000PC1", ICCID: "89860000000000000PC1",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
FirstCommissionPaid: false, FirstCommissionPaid: false,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
@@ -949,7 +949,7 @@ func TestOrderService_GetPurchaseCheck(t *testing.T) {
ICCID: "89860000000000000PC2", ICCID: "89860000000000000PC2",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
FirstCommissionPaid: true, FirstCommissionPaid: true,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
@@ -1055,12 +1055,12 @@ func TestOrderService_WalletPay_PurchaseOnBehalf(t *testing.T) {
shopIDPtr := &shop.ID shopIDPtr := &shop.ID
card := &model.IotCard{ card := &model.IotCard{
ICCID: "89860000000000000WP1", ICCID: "89860000000000000WP1",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &allocation.SeriesID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
} }
require.NoError(t, iotCardStore.Create(ctx, card)) require.NoError(t, iotCardStore.Create(ctx, card))

View File

@@ -51,23 +51,11 @@ func (s *Service) ValidateCardPurchase(ctx context.Context, cardID uint, package
return nil, err return nil, err
} }
if card.SeriesAllocationID == nil || *card.SeriesAllocationID == 0 { if card.SeriesID == nil || *card.SeriesID == 0 {
return nil, errors.New(errors.CodeInvalidParam, "该卡未关联套餐系列,无法购买套餐") return nil, errors.New(errors.CodeInvalidParam, "该卡未关联套餐系列,无法购买套餐")
} }
allocation, err := s.seriesAllocationStore.GetByID(ctx, *card.SeriesAllocationID) packages, totalPrice, err := s.validatePackages(ctx, packageIDs, *card.SeriesID)
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeInvalidParam, "套餐系列分配不存在")
}
return nil, err
}
if allocation.Status != constants.StatusEnabled {
return nil, errors.New(errors.CodeInvalidParam, "套餐系列分配已禁用")
}
packages, totalPrice, err := s.validatePackages(ctx, packageIDs, allocation.SeriesID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -76,7 +64,6 @@ func (s *Service) ValidateCardPurchase(ctx context.Context, cardID uint, package
Card: card, Card: card,
Packages: packages, Packages: packages,
TotalPrice: totalPrice, TotalPrice: totalPrice,
Allocation: allocation,
}, nil }, nil
} }
@@ -89,23 +76,11 @@ func (s *Service) ValidateDevicePurchase(ctx context.Context, deviceID uint, pac
return nil, err return nil, err
} }
if device.SeriesAllocationID == nil || *device.SeriesAllocationID == 0 { if device.SeriesID == nil || *device.SeriesID == 0 {
return nil, errors.New(errors.CodeInvalidParam, "该设备未关联套餐系列,无法购买套餐") return nil, errors.New(errors.CodeInvalidParam, "该设备未关联套餐系列,无法购买套餐")
} }
allocation, err := s.seriesAllocationStore.GetByID(ctx, *device.SeriesAllocationID) packages, totalPrice, err := s.validatePackages(ctx, packageIDs, *device.SeriesID)
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeInvalidParam, "套餐系列分配不存在")
}
return nil, err
}
if allocation.Status != constants.StatusEnabled {
return nil, errors.New(errors.CodeInvalidParam, "套餐系列分配已禁用")
}
packages, totalPrice, err := s.validatePackages(ctx, packageIDs, allocation.SeriesID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -114,7 +89,6 @@ func (s *Service) ValidateDevicePurchase(ctx context.Context, deviceID uint, pac
Device: device, Device: device,
Packages: packages, Packages: packages,
TotalPrice: totalPrice, TotalPrice: totalPrice,
Allocation: allocation,
}, nil }, nil
} }

View File

@@ -75,21 +75,21 @@ func setupTestData(t *testing.T) (context.Context, *Service, *model.IotCard, *mo
shopIDPtr := &shop.ID shopIDPtr := &shop.ID
card := &model.IotCard{ card := &model.IotCard{
ICCID: "89860000000000000001", ICCID: "89860000000000000001",
ShopID: shopIDPtr, ShopID: shopIDPtr,
CarrierID: carrier.ID, CarrierID: carrier.ID,
SeriesAllocationID: &allocation.ID, SeriesID: &series.ID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
} }
require.NoError(t, iotCardStore.Create(ctx, card)) require.NoError(t, iotCardStore.Create(ctx, card))
device := &model.Device{ device := &model.Device{
DeviceNo: "DEV_TEST_PV_001", DeviceNo: "DEV_TEST_PV_001",
ShopID: shopIDPtr, ShopID: shopIDPtr,
SeriesAllocationID: &allocation.ID, SeriesID: &series.ID,
Status: constants.StatusEnabled, Status: constants.StatusEnabled,
BaseModel: model.BaseModel{Creator: 1, Updater: 1}, BaseModel: model.BaseModel{Creator: 1, Updater: 1},
} }
require.NoError(t, deviceStore.Create(ctx, device)) require.NoError(t, deviceStore.Create(ctx, device))

View File

@@ -374,7 +374,8 @@ func (s *Service) checkForceRechargeRequirement(ctx context.Context, resourceTyp
Message: "无强充要求,可自由充值", Message: "无强充要求,可自由充值",
} }
var seriesAllocationID *uint var seriesID *uint
var shopID *uint
var accumulatedRecharge int64 var accumulatedRecharge int64
var firstCommissionPaid bool var firstCommissionPaid bool
@@ -387,7 +388,8 @@ func (s *Service) checkForceRechargeRequirement(ctx context.Context, resourceTyp
} }
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询IoT卡失败") return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询IoT卡失败")
} }
seriesAllocationID = card.SeriesAllocationID seriesID = card.SeriesID
shopID = card.ShopID
accumulatedRecharge = card.AccumulatedRecharge accumulatedRecharge = card.AccumulatedRecharge
firstCommissionPaid = card.FirstCommissionPaid firstCommissionPaid = card.FirstCommissionPaid
} else if resourceType == "device" { } else if resourceType == "device" {
@@ -398,7 +400,8 @@ func (s *Service) checkForceRechargeRequirement(ctx context.Context, resourceTyp
} }
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询设备失败") return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询设备失败")
} }
seriesAllocationID = device.SeriesAllocationID seriesID = device.SeriesID
shopID = device.ShopID
accumulatedRecharge = device.AccumulatedRecharge accumulatedRecharge = device.AccumulatedRecharge
firstCommissionPaid = device.FirstCommissionPaid firstCommissionPaid = device.FirstCommissionPaid
} }
@@ -406,13 +409,13 @@ func (s *Service) checkForceRechargeRequirement(ctx context.Context, resourceTyp
result.CurrentAccumulated = accumulatedRecharge result.CurrentAccumulated = accumulatedRecharge
result.FirstCommissionPaid = firstCommissionPaid result.FirstCommissionPaid = firstCommissionPaid
// 2. 如果没有系列分配,无强充要求 // 2. 如果没有系列ID或店铺ID,无强充要求
if seriesAllocationID == nil { if seriesID == nil || shopID == nil {
return result, nil return result, nil
} }
// 3. 查询系列分配配置 // 3. 查询系列分配配置
allocation, err := s.shopSeriesAllocationStore.GetByID(ctx, *seriesAllocationID) allocation, err := s.shopSeriesAllocationStore.GetByShopAndSeries(ctx, *shopID, *seriesID)
if err != nil { if err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
return result, nil return result, nil
@@ -483,7 +486,7 @@ func (s *Service) updateAccumulatedRechargeInTx(ctx context.Context, tx *gorm.DB
// triggerOneTimeCommissionIfNeededInTx 触发一次性佣金(事务内使用) // triggerOneTimeCommissionIfNeededInTx 触发一次性佣金(事务内使用)
// 检查是否满足一次性佣金触发条件,满足则创建佣金记录并入账 // 检查是否满足一次性佣金触发条件,满足则创建佣金记录并入账
func (s *Service) triggerOneTimeCommissionIfNeededInTx(ctx context.Context, tx *gorm.DB, resourceType string, resourceID uint, rechargeAmount int64, userID uint) error { func (s *Service) triggerOneTimeCommissionIfNeededInTx(ctx context.Context, tx *gorm.DB, resourceType string, resourceID uint, rechargeAmount int64, userID uint) error {
var seriesAllocationID *uint var seriesID *uint
var accumulatedRecharge int64 var accumulatedRecharge int64
var firstCommissionPaid bool var firstCommissionPaid bool
var shopID *uint var shopID *uint
@@ -494,7 +497,7 @@ func (s *Service) triggerOneTimeCommissionIfNeededInTx(ctx context.Context, tx *
if err := tx.First(&card, resourceID).Error; err != nil { if err := tx.First(&card, resourceID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询IoT卡失败") return errors.Wrap(errors.CodeDatabaseError, err, "查询IoT卡失败")
} }
seriesAllocationID = card.SeriesAllocationID seriesID = card.SeriesID
accumulatedRecharge = card.AccumulatedRecharge accumulatedRecharge = card.AccumulatedRecharge
firstCommissionPaid = card.FirstCommissionPaid firstCommissionPaid = card.FirstCommissionPaid
shopID = card.ShopID shopID = card.ShopID
@@ -503,14 +506,14 @@ func (s *Service) triggerOneTimeCommissionIfNeededInTx(ctx context.Context, tx *
if err := tx.First(&device, resourceID).Error; err != nil { if err := tx.First(&device, resourceID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询设备失败") return errors.Wrap(errors.CodeDatabaseError, err, "查询设备失败")
} }
seriesAllocationID = device.SeriesAllocationID seriesID = device.SeriesID
accumulatedRecharge = device.AccumulatedRecharge accumulatedRecharge = device.AccumulatedRecharge
firstCommissionPaid = device.FirstCommissionPaid firstCommissionPaid = device.FirstCommissionPaid
shopID = device.ShopID shopID = device.ShopID
} }
// 2. 如果没有系列分配或已发放佣金,跳过 // 2. 如果没有系列ID或已发放佣金,跳过
if seriesAllocationID == nil || firstCommissionPaid { if seriesID == nil || firstCommissionPaid {
return nil return nil
} }
@@ -524,7 +527,7 @@ func (s *Service) triggerOneTimeCommissionIfNeededInTx(ctx context.Context, tx *
} }
// 4. 查询系列分配配置 // 4. 查询系列分配配置
allocation, err := s.shopSeriesAllocationStore.GetByID(ctx, *seriesAllocationID) allocation, err := s.shopSeriesAllocationStore.GetByShopAndSeries(ctx, *shopID, *seriesID)
if err != nil { if err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
return nil return nil

View File

@@ -60,15 +60,15 @@ func createTestIotCard(t *testing.T, tx *gorm.DB, shopID *uint, seriesAllocation
Creator: 1, Creator: 1,
Updater: 1, Updater: 1,
}, },
ICCID: fmt.Sprintf("89860%014d", timestamp%100000000000000), ICCID: fmt.Sprintf("89860%014d", timestamp%100000000000000),
CardType: "流量卡", CardType: "流量卡",
CardCategory: "normal", CardCategory: "normal",
CarrierID: 1, CarrierID: 1,
CarrierType: "CMCC", CarrierType: "CMCC",
CarrierName: "中国移动", CarrierName: "中国移动",
Status: 1, Status: 1,
ShopID: shopID, ShopID: shopID,
SeriesAllocationID: seriesAllocationID, SeriesID: seriesAllocationID,
} }
require.NoError(t, tx.Create(card).Error) require.NoError(t, tx.Create(card).Error)
return card return card
@@ -83,12 +83,12 @@ func createTestDevice(t *testing.T, tx *gorm.DB, shopID *uint, seriesAllocationI
Creator: 1, Creator: 1,
Updater: 1, Updater: 1,
}, },
DeviceNo: fmt.Sprintf("DEV%014d", timestamp%100000000000000), DeviceNo: fmt.Sprintf("DEV%014d", timestamp%100000000000000),
DeviceName: "测试设备", DeviceName: "测试设备",
DeviceType: "GPS", DeviceType: "GPS",
Status: 1, Status: 1,
ShopID: shopID, ShopID: shopID,
SeriesAllocationID: seriesAllocationID, SeriesID: seriesAllocationID,
} }
require.NoError(t, tx.Create(device).Error) require.NoError(t, tx.Create(device).Error)
return device return device

View File

@@ -106,8 +106,8 @@ func (s *DeviceStore) List(ctx context.Context, opts *store.QueryOptions, filter
if createdAtEnd, ok := filters["created_at_end"].(time.Time); ok && !createdAtEnd.IsZero() { if createdAtEnd, ok := filters["created_at_end"].(time.Time); ok && !createdAtEnd.IsZero() {
query = query.Where("created_at <= ?", createdAtEnd) query = query.Where("created_at <= ?", createdAtEnd)
} }
if seriesAllocationID, ok := filters["series_allocation_id"].(uint); ok && seriesAllocationID > 0 { if seriesID, ok := filters["series_id"].(uint); ok && seriesID > 0 {
query = query.Where("series_allocation_id = ?", seriesAllocationID) query = query.Where("series_id = ?", seriesID)
} }
if err := query.Count(&total).Error; err != nil { if err := query.Count(&total).Error; err != nil {
@@ -185,20 +185,20 @@ func (s *DeviceStore) GetByDeviceNos(ctx context.Context, deviceNos []string) ([
return devices, nil return devices, nil
} }
// BatchUpdateSeriesAllocation 批量更新设备的套餐系列分配 // BatchUpdateSeriesID 批量更新设备的套餐系列ID
func (s *DeviceStore) BatchUpdateSeriesAllocation(ctx context.Context, deviceIDs []uint, seriesAllocationID *uint) error { func (s *DeviceStore) BatchUpdateSeriesID(ctx context.Context, deviceIDs []uint, seriesID *uint) error {
if len(deviceIDs) == 0 { if len(deviceIDs) == 0 {
return nil return nil
} }
return s.db.WithContext(ctx).Model(&model.Device{}). return s.db.WithContext(ctx).Model(&model.Device{}).
Where("id IN ?", deviceIDs). Where("id IN ?", deviceIDs).
Update("series_allocation_id", seriesAllocationID).Error Update("series_id", seriesID).Error
} }
// ListBySeriesAllocationID 根据套餐系列分配ID查询设备列表 // ListBySeriesID 根据套餐系列ID查询设备列表
func (s *DeviceStore) ListBySeriesAllocationID(ctx context.Context, seriesAllocationID uint) ([]*model.Device, error) { func (s *DeviceStore) ListBySeriesID(ctx context.Context, seriesID uint) ([]*model.Device, error) {
var devices []*model.Device var devices []*model.Device
if err := s.db.WithContext(ctx).Where("series_allocation_id = ?", seriesAllocationID).Find(&devices).Error; err != nil { if err := s.db.WithContext(ctx).Where("series_id = ?", seriesID).Find(&devices).Error; err != nil {
return nil, err return nil, err
} }
return devices, nil return devices, nil

View File

@@ -16,7 +16,7 @@ func uniqueDeviceNoPrefix() string {
return fmt.Sprintf("D%d", time.Now().UnixNano()%1000000000) return fmt.Sprintf("D%d", time.Now().UnixNano()%1000000000)
} }
func TestDeviceStore_BatchUpdateSeriesAllocation(t *testing.T) { func TestDeviceStore_BatchUpdateSeriesID(t *testing.T) {
tx := testutils.NewTestTransaction(t) tx := testutils.NewTestTransaction(t)
rdb := testutils.GetTestRedis(t) rdb := testutils.GetTestRedis(t)
testutils.CleanTestRedisKeys(t, rdb) testutils.CleanTestRedisKeys(t, rdb)
@@ -31,39 +31,39 @@ func TestDeviceStore_BatchUpdateSeriesAllocation(t *testing.T) {
} }
require.NoError(t, s.CreateBatch(ctx, devices)) require.NoError(t, s.CreateBatch(ctx, devices))
t.Run("设置系列分配ID", func(t *testing.T) { t.Run("设置系列ID", func(t *testing.T) {
seriesAllocationID := uint(100) seriesID := uint(100)
deviceIDs := []uint{devices[0].ID, devices[1].ID} deviceIDs := []uint{devices[0].ID, devices[1].ID}
err := s.BatchUpdateSeriesAllocation(ctx, deviceIDs, &seriesAllocationID) err := s.BatchUpdateSeriesID(ctx, deviceIDs, &seriesID)
require.NoError(t, err) require.NoError(t, err)
var updatedDevices []*model.Device var updatedDevices []*model.Device
require.NoError(t, tx.Where("id IN ?", deviceIDs).Find(&updatedDevices).Error) require.NoError(t, tx.Where("id IN ?", deviceIDs).Find(&updatedDevices).Error)
for _, device := range updatedDevices { for _, device := range updatedDevices {
require.NotNil(t, device.SeriesAllocationID) require.NotNil(t, device.SeriesID)
assert.Equal(t, seriesAllocationID, *device.SeriesAllocationID) assert.Equal(t, seriesID, *device.SeriesID)
} }
}) })
t.Run("清除系列分配ID", func(t *testing.T) { t.Run("清除系列ID", func(t *testing.T) {
deviceIDs := []uint{devices[0].ID} deviceIDs := []uint{devices[0].ID}
err := s.BatchUpdateSeriesAllocation(ctx, deviceIDs, nil) err := s.BatchUpdateSeriesID(ctx, deviceIDs, nil)
require.NoError(t, err) require.NoError(t, err)
var updatedDevice model.Device var updatedDevice model.Device
require.NoError(t, tx.First(&updatedDevice, devices[0].ID).Error) require.NoError(t, tx.First(&updatedDevice, devices[0].ID).Error)
assert.Nil(t, updatedDevice.SeriesAllocationID) assert.Nil(t, updatedDevice.SeriesID)
}) })
t.Run("空列表不报错", func(t *testing.T) { t.Run("空列表不报错", func(t *testing.T) {
err := s.BatchUpdateSeriesAllocation(ctx, []uint{}, nil) err := s.BatchUpdateSeriesID(ctx, []uint{}, nil)
require.NoError(t, err) require.NoError(t, err)
}) })
} }
func TestDeviceStore_ListBySeriesAllocationID(t *testing.T) { func TestDeviceStore_ListBySeriesID(t *testing.T) {
tx := testutils.NewTestTransaction(t) tx := testutils.NewTestTransaction(t)
rdb := testutils.GetTestRedis(t) rdb := testutils.GetTestRedis(t)
testutils.CleanTestRedisKeys(t, rdb) testutils.CleanTestRedisKeys(t, rdb)
@@ -72,23 +72,23 @@ func TestDeviceStore_ListBySeriesAllocationID(t *testing.T) {
ctx := context.Background() ctx := context.Background()
prefix := uniqueDeviceNoPrefix() prefix := uniqueDeviceNoPrefix()
seriesAllocationID := uint(200) seriesID := uint(200)
devices := []*model.Device{ devices := []*model.Device{
{DeviceNo: prefix + "001", DeviceName: "测试设备1", Status: 1, SeriesAllocationID: &seriesAllocationID}, {DeviceNo: prefix + "001", DeviceName: "测试设备1", Status: 1, SeriesID: &seriesID},
{DeviceNo: prefix + "002", DeviceName: "测试设备2", Status: 1, SeriesAllocationID: &seriesAllocationID}, {DeviceNo: prefix + "002", DeviceName: "测试设备2", Status: 1, SeriesID: &seriesID},
{DeviceNo: prefix + "003", DeviceName: "测试设备3", Status: 1, SeriesAllocationID: nil}, {DeviceNo: prefix + "003", DeviceName: "测试设备3", Status: 1, SeriesID: nil},
} }
require.NoError(t, s.CreateBatch(ctx, devices)) require.NoError(t, s.CreateBatch(ctx, devices))
result, err := s.ListBySeriesAllocationID(ctx, seriesAllocationID) result, err := s.ListBySeriesID(ctx, seriesID)
require.NoError(t, err) require.NoError(t, err)
assert.Len(t, result, 2) assert.Len(t, result, 2)
for _, device := range result { for _, device := range result {
assert.Equal(t, seriesAllocationID, *device.SeriesAllocationID) assert.Equal(t, seriesID, *device.SeriesID)
} }
} }
func TestDeviceStore_List_SeriesAllocationFilter(t *testing.T) { func TestDeviceStore_List_SeriesIDFilter(t *testing.T) {
tx := testutils.NewTestTransaction(t) tx := testutils.NewTestTransaction(t)
rdb := testutils.GetTestRedis(t) rdb := testutils.GetTestRedis(t)
testutils.CleanTestRedisKeys(t, rdb) testutils.CleanTestRedisKeys(t, rdb)
@@ -97,23 +97,23 @@ func TestDeviceStore_List_SeriesAllocationFilter(t *testing.T) {
ctx := context.Background() ctx := context.Background()
prefix := uniqueDeviceNoPrefix() prefix := uniqueDeviceNoPrefix()
seriesAllocationID := uint(300) seriesID := uint(300)
devices := []*model.Device{ devices := []*model.Device{
{DeviceNo: prefix + "001", DeviceName: "测试设备1", Status: 1, SeriesAllocationID: &seriesAllocationID}, {DeviceNo: prefix + "001", DeviceName: "测试设备1", Status: 1, SeriesID: &seriesID},
{DeviceNo: prefix + "002", DeviceName: "测试设备2", Status: 1, SeriesAllocationID: &seriesAllocationID}, {DeviceNo: prefix + "002", DeviceName: "测试设备2", Status: 1, SeriesID: &seriesID},
{DeviceNo: prefix + "003", DeviceName: "测试设备3", Status: 1, SeriesAllocationID: nil}, {DeviceNo: prefix + "003", DeviceName: "测试设备3", Status: 1, SeriesID: nil},
} }
require.NoError(t, s.CreateBatch(ctx, devices)) require.NoError(t, s.CreateBatch(ctx, devices))
filters := map[string]interface{}{ filters := map[string]interface{}{
"series_allocation_id": seriesAllocationID, "series_id": seriesID,
"device_no": prefix, "device_no": prefix,
} }
result, total, err := s.List(ctx, nil, filters) result, total, err := s.List(ctx, nil, filters)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), total) assert.Equal(t, int64(2), total)
assert.Len(t, result, 2) assert.Len(t, result, 2)
for _, device := range result { for _, device := range result {
assert.Equal(t, seriesAllocationID, *device.SeriesAllocationID) assert.Equal(t, seriesID, *device.SeriesID)
} }
} }

View File

@@ -147,8 +147,8 @@ func (s *IotCardStore) List(ctx context.Context, opts *store.QueryOptions, filte
if iccidEnd, ok := filters["iccid_end"].(string); ok && iccidEnd != "" { if iccidEnd, ok := filters["iccid_end"].(string); ok && iccidEnd != "" {
query = query.Where("iccid <= ?", iccidEnd) query = query.Where("iccid <= ?", iccidEnd)
} }
if seriesAllocationID, ok := filters["series_allocation_id"].(uint); ok && seriesAllocationID > 0 { if seriesID, ok := filters["series_id"].(uint); ok && seriesID > 0 {
query = query.Where("series_allocation_id = ?", seriesAllocationID) query = query.Where("series_id = ?", seriesID)
} }
// 统计总数 // 统计总数
@@ -242,8 +242,8 @@ func (s *IotCardStore) ListStandalone(ctx context.Context, opts *store.QueryOpti
Where("deleted_at IS NULL")) Where("deleted_at IS NULL"))
} }
} }
if seriesAllocationID, ok := filters["series_allocation_id"].(uint); ok && seriesAllocationID > 0 { if seriesID, ok := filters["series_id"].(uint); ok && seriesID > 0 {
query = query.Where("series_allocation_id = ?", seriesAllocationID) query = query.Where("series_id = ?", seriesID)
} }
if err := query.Count(&total).Error; err != nil { if err := query.Count(&total).Error; err != nil {
@@ -381,22 +381,22 @@ func (s *IotCardStore) GetByIDsWithEnterpriseFilter(ctx context.Context, cardIDs
return cards, nil return cards, nil
} }
// BatchUpdateSeriesAllocation 批量更新卡的套餐系列分配 // BatchUpdateSeriesID 批量更新卡的套餐系列ID
// 用于批量设置或清除卡与套餐系列的关联关系 // 用于批量设置或清除卡与套餐系列的关联关系
func (s *IotCardStore) BatchUpdateSeriesAllocation(ctx context.Context, cardIDs []uint, seriesAllocationID *uint) error { func (s *IotCardStore) BatchUpdateSeriesID(ctx context.Context, cardIDs []uint, seriesID *uint) error {
if len(cardIDs) == 0 { if len(cardIDs) == 0 {
return nil return nil
} }
return s.db.WithContext(ctx).Model(&model.IotCard{}). return s.db.WithContext(ctx).Model(&model.IotCard{}).
Where("id IN ?", cardIDs). Where("id IN ?", cardIDs).
Update("series_allocation_id", seriesAllocationID).Error Update("series_id", seriesID).Error
} }
// ListBySeriesAllocationID 根据套餐系列分配ID查询卡列表 // ListBySeriesID 根据套餐系列ID查询卡列表
// 用于查询某个套餐系列分配下的所有卡 // 用于查询某个套餐系列下的所有卡
func (s *IotCardStore) ListBySeriesAllocationID(ctx context.Context, seriesAllocationID uint) ([]*model.IotCard, error) { func (s *IotCardStore) ListBySeriesID(ctx context.Context, seriesID uint) ([]*model.IotCard, error) {
var cards []*model.IotCard var cards []*model.IotCard
if err := s.db.WithContext(ctx).Where("series_allocation_id = ?", seriesAllocationID).Find(&cards).Error; err != nil { if err := s.db.WithContext(ctx).Where("series_id = ?", seriesID).Find(&cards).Error; err != nil {
return nil, err return nil, err
} }
return cards, nil return cards, nil

View File

@@ -426,7 +426,7 @@ func TestIotCardStore_GetBoundCardIDs(t *testing.T) {
}) })
} }
func TestIotCardStore_BatchUpdateSeriesAllocation(t *testing.T) { func TestIotCardStore_BatchUpdateSeriesID(t *testing.T) {
tx := testutils.NewTestTransaction(t) tx := testutils.NewTestTransaction(t)
rdb := testutils.GetTestRedis(t) rdb := testutils.GetTestRedis(t)
testutils.CleanTestRedisKeys(t, rdb) testutils.CleanTestRedisKeys(t, rdb)
@@ -440,39 +440,39 @@ func TestIotCardStore_BatchUpdateSeriesAllocation(t *testing.T) {
} }
require.NoError(t, s.CreateBatch(ctx, cards)) require.NoError(t, s.CreateBatch(ctx, cards))
t.Run("设置系列分配ID", func(t *testing.T) { t.Run("设置系列ID", func(t *testing.T) {
seriesAllocationID := uint(100) seriesID := uint(100)
cardIDs := []uint{cards[0].ID, cards[1].ID} cardIDs := []uint{cards[0].ID, cards[1].ID}
err := s.BatchUpdateSeriesAllocation(ctx, cardIDs, &seriesAllocationID) err := s.BatchUpdateSeriesID(ctx, cardIDs, &seriesID)
require.NoError(t, err) require.NoError(t, err)
var updatedCards []*model.IotCard var updatedCards []*model.IotCard
require.NoError(t, tx.Where("id IN ?", cardIDs).Find(&updatedCards).Error) require.NoError(t, tx.Where("id IN ?", cardIDs).Find(&updatedCards).Error)
for _, card := range updatedCards { for _, card := range updatedCards {
require.NotNil(t, card.SeriesAllocationID) require.NotNil(t, card.SeriesID)
assert.Equal(t, seriesAllocationID, *card.SeriesAllocationID) assert.Equal(t, seriesID, *card.SeriesID)
} }
}) })
t.Run("清除系列分配ID", func(t *testing.T) { t.Run("清除系列ID", func(t *testing.T) {
cardIDs := []uint{cards[0].ID} cardIDs := []uint{cards[0].ID}
err := s.BatchUpdateSeriesAllocation(ctx, cardIDs, nil) err := s.BatchUpdateSeriesID(ctx, cardIDs, nil)
require.NoError(t, err) require.NoError(t, err)
var updatedCard model.IotCard var updatedCard model.IotCard
require.NoError(t, tx.First(&updatedCard, cards[0].ID).Error) require.NoError(t, tx.First(&updatedCard, cards[0].ID).Error)
assert.Nil(t, updatedCard.SeriesAllocationID) assert.Nil(t, updatedCard.SeriesID)
}) })
t.Run("空列表不报错", func(t *testing.T) { t.Run("空列表不报错", func(t *testing.T) {
err := s.BatchUpdateSeriesAllocation(ctx, []uint{}, nil) err := s.BatchUpdateSeriesID(ctx, []uint{}, nil)
require.NoError(t, err) require.NoError(t, err)
}) })
} }
func TestIotCardStore_ListBySeriesAllocationID(t *testing.T) { func TestIotCardStore_ListBySeriesID(t *testing.T) {
tx := testutils.NewTestTransaction(t) tx := testutils.NewTestTransaction(t)
rdb := testutils.GetTestRedis(t) rdb := testutils.GetTestRedis(t)
testutils.CleanTestRedisKeys(t, rdb) testutils.CleanTestRedisKeys(t, rdb)
@@ -480,23 +480,23 @@ func TestIotCardStore_ListBySeriesAllocationID(t *testing.T) {
s := NewIotCardStore(tx, rdb) s := NewIotCardStore(tx, rdb)
ctx := context.Background() ctx := context.Background()
seriesAllocationID := uint(200) seriesID := uint(200)
cards := []*model.IotCard{ cards := []*model.IotCard{
{ICCID: "89860012345678911001", CardType: "data_card", CarrierID: 1, Status: 1, SeriesAllocationID: &seriesAllocationID}, {ICCID: "89860012345678911001", CardType: "data_card", CarrierID: 1, Status: 1, SeriesID: &seriesID},
{ICCID: "89860012345678911002", CardType: "data_card", CarrierID: 1, Status: 1, SeriesAllocationID: &seriesAllocationID}, {ICCID: "89860012345678911002", CardType: "data_card", CarrierID: 1, Status: 1, SeriesID: &seriesID},
{ICCID: "89860012345678911003", CardType: "data_card", CarrierID: 1, Status: 1, SeriesAllocationID: nil}, {ICCID: "89860012345678911003", CardType: "data_card", CarrierID: 1, Status: 1, SeriesID: nil},
} }
require.NoError(t, s.CreateBatch(ctx, cards)) require.NoError(t, s.CreateBatch(ctx, cards))
result, err := s.ListBySeriesAllocationID(ctx, seriesAllocationID) result, err := s.ListBySeriesID(ctx, seriesID)
require.NoError(t, err) require.NoError(t, err)
assert.Len(t, result, 2) assert.Len(t, result, 2)
for _, card := range result { for _, card := range result {
assert.Equal(t, seriesAllocationID, *card.SeriesAllocationID) assert.Equal(t, seriesID, *card.SeriesID)
} }
} }
func TestIotCardStore_ListStandalone_SeriesAllocationFilter(t *testing.T) { func TestIotCardStore_ListStandalone_SeriesIDFilter(t *testing.T) {
tx := testutils.NewTestTransaction(t) tx := testutils.NewTestTransaction(t)
rdb := testutils.GetTestRedis(t) rdb := testutils.GetTestRedis(t)
testutils.CleanTestRedisKeys(t, rdb) testutils.CleanTestRedisKeys(t, rdb)
@@ -505,23 +505,23 @@ func TestIotCardStore_ListStandalone_SeriesAllocationFilter(t *testing.T) {
ctx := context.Background() ctx := context.Background()
prefix := uniqueICCIDPrefix() prefix := uniqueICCIDPrefix()
seriesAllocationID := uint(300) seriesID := uint(300)
cards := []*model.IotCard{ cards := []*model.IotCard{
{ICCID: prefix + "S001", CardType: "data_card", CarrierID: 1, Status: 1, SeriesAllocationID: &seriesAllocationID}, {ICCID: prefix + "S001", CardType: "data_card", CarrierID: 1, Status: 1, SeriesID: &seriesID},
{ICCID: prefix + "S002", CardType: "data_card", CarrierID: 1, Status: 1, SeriesAllocationID: &seriesAllocationID}, {ICCID: prefix + "S002", CardType: "data_card", CarrierID: 1, Status: 1, SeriesID: &seriesID},
{ICCID: prefix + "S003", CardType: "data_card", CarrierID: 1, Status: 1, SeriesAllocationID: nil}, {ICCID: prefix + "S003", CardType: "data_card", CarrierID: 1, Status: 1, SeriesID: nil},
} }
require.NoError(t, s.CreateBatch(ctx, cards)) require.NoError(t, s.CreateBatch(ctx, cards))
filters := map[string]interface{}{ filters := map[string]interface{}{
"series_allocation_id": seriesAllocationID, "series_id": seriesID,
"iccid": prefix, "iccid": prefix,
} }
result, total, err := s.ListStandalone(ctx, nil, filters) result, total, err := s.ListStandalone(ctx, nil, filters)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), total) assert.Equal(t, int64(2), total)
assert.Len(t, result, 2) assert.Len(t, result, 2)
for _, card := range result { for _, card := range result {
assert.Equal(t, seriesAllocationID, *card.SeriesAllocationID) assert.Equal(t, seriesID, *card.SeriesID)
} }
} }

View File

@@ -0,0 +1,114 @@
package postgres
import (
"context"
"testing"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/tests/testutils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
func TestShopSeriesAllocationStore_GetByShopAndSeries(t *testing.T) {
tx := testutils.NewTestTransaction(t)
ctx := context.Background()
s := NewShopSeriesAllocationStore(tx)
// 创建测试数据
allocation := &model.ShopSeriesAllocation{
ShopID: 1,
SeriesID: 100,
AllocatorShopID: 0,
Status: 1,
}
require.NoError(t, s.Create(ctx, allocation))
t.Run("查询存在的分配", func(t *testing.T) {
result, err := s.GetByShopAndSeries(ctx, 1, 100)
require.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, uint(1), result.ShopID)
assert.Equal(t, uint(100), result.SeriesID)
})
t.Run("查询不存在的分配", func(t *testing.T) {
result, err := s.GetByShopAndSeries(ctx, 999, 999)
assert.Error(t, err)
assert.Equal(t, gorm.ErrRecordNotFound, err)
assert.Nil(t, result)
})
}
func TestShopSeriesAllocationStore_Create(t *testing.T) {
tx := testutils.NewTestTransaction(t)
ctx := context.Background()
s := NewShopSeriesAllocationStore(tx)
allocation := &model.ShopSeriesAllocation{
ShopID: 1,
SeriesID: 100,
AllocatorShopID: 0,
Status: 1,
}
err := s.Create(ctx, allocation)
require.NoError(t, err)
assert.NotZero(t, allocation.ID)
}
func TestShopSeriesAllocationStore_GetByID(t *testing.T) {
tx := testutils.NewTestTransaction(t)
ctx := context.Background()
s := NewShopSeriesAllocationStore(tx)
allocation := &model.ShopSeriesAllocation{
ShopID: 1,
SeriesID: 100,
AllocatorShopID: 0,
Status: 1,
}
require.NoError(t, s.Create(ctx, allocation))
result, err := s.GetByID(ctx, allocation.ID)
require.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, allocation.ID, result.ID)
}
func TestShopSeriesAllocationStore_List(t *testing.T) {
tx := testutils.NewTestTransaction(t)
ctx := context.Background()
s := NewShopSeriesAllocationStore(tx)
// 创建测试数据
allocations := []*model.ShopSeriesAllocation{
{ShopID: 1, SeriesID: 100, AllocatorShopID: 0, Status: 1},
{ShopID: 1, SeriesID: 101, AllocatorShopID: 0, Status: 1},
{ShopID: 2, SeriesID: 100, AllocatorShopID: 0, Status: 1},
}
for _, a := range allocations {
require.NoError(t, s.Create(ctx, a))
}
t.Run("按店铺ID过滤", func(t *testing.T) {
filters := map[string]interface{}{"shop_id": uint(1)}
result, total, err := s.List(ctx, nil, filters)
require.NoError(t, err)
assert.Equal(t, int64(2), total)
assert.Len(t, result, 2)
})
t.Run("按系列ID过滤", func(t *testing.T) {
filters := map[string]interface{}{"series_id": uint(100)}
result, total, err := s.List(ctx, nil, filters)
require.NoError(t, err)
assert.Equal(t, int64(2), total)
assert.Len(t, result, 2)
})
}

View File

@@ -0,0 +1,9 @@
-- 回滚: 将 series_id 改回 series_allocation_id
ALTER TABLE tb_iot_card RENAME COLUMN series_id TO series_allocation_id;
COMMENT ON COLUMN tb_iot_card.series_allocation_id IS '套餐系列分配ID(关联ShopSeriesAllocation)';
ALTER TABLE tb_device RENAME COLUMN series_id TO series_allocation_id;
COMMENT ON COLUMN tb_device.series_allocation_id IS '套餐系列分配ID(关联ShopSeriesAllocation)';
-- 删除索引(如果存在)
DROP INDEX IF EXISTS idx_shop_series_allocation_shop_series;

View File

@@ -0,0 +1,13 @@
-- 重构: 将卡/设备的套餐系列绑定从分配ID改为系列ID
-- 重命名 tb_iot_card.series_allocation_id 为 series_id
ALTER TABLE tb_iot_card RENAME COLUMN series_allocation_id TO series_id;
COMMENT ON COLUMN tb_iot_card.series_id IS '套餐系列ID(关联PackageSeries)';
-- 重命名 tb_device.series_allocation_id 为 series_id
ALTER TABLE tb_device RENAME COLUMN series_allocation_id TO series_id;
COMMENT ON COLUMN tb_device.series_id IS '套餐系列ID(关联PackageSeries)';
-- 验证并添加复合索引(如果不存在)
CREATE INDEX IF NOT EXISTS idx_shop_series_allocation_shop_series
ON tb_shop_series_allocation(shop_id, series_id)
WHERE status = 1;

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-02-02

View File

@@ -0,0 +1,432 @@
# Design: refactor-series-binding-to-series-id
## Context
### 当前架构问题
当前系统中IoT卡和设备通过 `series_allocation_id` 字段绑定到 `ShopSeriesAllocation` 表,形成以下关系链:
```
IotCard/Device
└── series_allocation_id → ShopSeriesAllocation
├── shop_id → Shop
├── series_id → PackageSeries
└── 返佣配置BaseCommissionValue, OneTimeCommission...
```
这导致了三层职责混乱:
1. **资源属性层**(卡/设备的可购买范围)依赖于**权限配置层**ShopSeriesAllocation
2. 每次需要验证套餐是否可购买时,必须先查询 `ShopSeriesAllocation` 获取 `series_id`
3. 返佣计算和权限验证被强制耦合在一个查询中
### 现有数据结构
**Model 定义**
```go
type IotCard struct {
SeriesAllocationID *uint `gorm:"column:series_allocation_id"` // 指向 ShopSeriesAllocation
}
type Device struct {
SeriesAllocationID *uint `gorm:"column:series_allocation_id"`
}
type ShopSeriesAllocation struct {
ShopID uint // 被分配的店铺ID
SeriesID uint // 套餐系列ID
BaseCommissionValue int64 // 返佣配置
// ... 其他返佣相关字段
}
```
**当前业务流程**
```
购买套餐验证:
card.SeriesAllocationID → ShopSeriesAllocation.SeriesID → 验证 Package.SeriesID
同时获取返佣配置
```
### 技术约束
- PostgreSQL 14+,支持字段重命名(`ALTER TABLE ... RENAME COLUMN`
- GORM v1.25.x支持动态字段名
- 项目禁止外键约束,关联关系在代码层显式维护
- 开发阶段,无生产数据,可直接修改数据库结构
## Goals / Non-Goals
**Goals:**
- 将卡/设备的系列绑定从"权限分配"改为"套餐系列",实现职责分离
- 优化查询性能,减少购买验证时的数据库查询次数
- 保持返佣计算逻辑正确性,按需查询 `ShopSeriesAllocation`
- 统一所有相关代码的字段命名Model、DTO、Store、Service、测试
- 更新 API 文档,明确参数变更
**Non-Goals:**
- 不修改 `ShopSeriesAllocation` 表结构和返佣计算逻辑
- 不改变 API 端点路径(仅改变请求/响应字段名)
- 不引入数据迁移工具或版本控制(直接重命名字段)
- 不考虑向后兼容性(开发阶段可 BREAKING CHANGE
## Decisions
### 决策 1直接重命名数据库字段
**选择**:使用 PostgreSQL 的 `ALTER TABLE ... RENAME COLUMN` 直接重命名字段
**理由**
- 开发阶段,无生产数据,无需考虑数据迁移
- 字段含义保持一致(都是指向某个 ID只是关联表变了
- 索引会自动重命名,无需额外处理
- 简单高效,避免引入复杂的数据迁移逻辑
**替代方案**
- ❌ 新增 `series_id` 字段,保留 `series_allocation_id`:增加字段冗余,需要复杂的迁移逻辑
- ❌ 删除旧字段再创建新字段:会丢失索引,需要手动重建
**实施**
```sql
-- migrations/000XXX_refactor_series_binding_to_series_id.up.sql
ALTER TABLE tb_iot_card RENAME COLUMN series_allocation_id TO series_id;
ALTER TABLE tb_device RENAME COLUMN series_allocation_id TO series_id;
COMMENT ON COLUMN tb_iot_card.series_id IS '套餐系列ID(关联PackageSeries)';
COMMENT ON COLUMN tb_device.series_id IS '套餐系列ID(关联PackageSeries)';
```
### 决策 2新增 GetByShopAndSeries 查询方法
**选择**:在 `ShopSeriesAllocationStore` 中新增 `GetByShopAndSeries(shopID, seriesID)` 方法
**理由**
- 返佣查询的核心需求是:根据店铺和系列查询分配配置
- 当前的 `GetByID(allocationID)` 方法不再适用(卡/设备不再存储 `allocation_id`
- 该查询有复合索引支持:`(shop_id, series_id)`(需要验证或添加)
**替代方案**
- ❌ 在 Service 层手动拼接查询条件违反分层原则Store 层应封装所有数据访问逻辑
- ❌ 继续使用 `GetByID`,在 Service 层先查询获取 ID增加查询次数性能倒退
**实施**
```go
// internal/store/postgres/shop_series_allocation_store.go
func (s *ShopSeriesAllocationStore) GetByShopAndSeries(
ctx context.Context,
shopID uint,
seriesID uint,
) (*model.ShopSeriesAllocation, error) {
var allocation model.ShopSeriesAllocation
err := s.db.WithContext(ctx).
Where("shop_id = ? AND series_id = ? AND status = ?", shopID, seriesID, 1).
First(&allocation).Error
if err != nil {
return nil, err
}
return &allocation, nil
}
```
**索引验证**:需要检查 `tb_shop_series_allocation` 表是否有 `(shop_id, series_id)` 复合索引,如无则添加:
```sql
CREATE INDEX IF NOT EXISTS idx_shop_series_allocation_shop_series
ON tb_shop_series_allocation(shop_id, series_id);
```
### 决策 3Service 层逻辑重构策略
**选择**:将验证和返佣查询分离,按需查询
**当前逻辑(错误)**
```go
// ValidateCardPurchase
allocation := s.seriesAllocationStore.GetByID(card.SeriesAllocationID) // 必须查询
seriesID := allocation.SeriesID // 获取 series_id
packages := s.validatePackages(packageIDs, seriesID)
// allocation 同时用于返佣计算
```
**重构后逻辑(正确)**
```go
// ValidateCardPurchase
seriesID := *card.SeriesID // 直接使用,无需查询
packages := s.validatePackages(packageIDs, seriesID)
// 按需查询返佣配置(仅当需要时)
var allocation *model.ShopSeriesAllocation
if card.ShopID != nil && *card.ShopID > 0 {
allocation, _ = s.seriesAllocationStore.GetByShopAndSeries(*card.ShopID, seriesID)
}
```
**优势**
- 购买验证减少一次数据库查询(直接使用 `card.series_id`
- 个人客户场景下(`shop_id = NULL`)无需查询 `ShopSeriesAllocation`
- 返佣查询失败不影响购买流程(`allocation = nil` 表示无返佣)
### 决策 4权限验证逻辑优化
**选择**:在 `BatchSetSeriesBinding` 中,先验证系列是否存在,再验证操作者权限
**当前逻辑(冗余)**
```go
// 验证分配是否存在
allocation := s.seriesAllocationStore.GetByID(req.SeriesAllocationID)
// 验证卡是否属于分配的店铺
if card.ShopID != allocation.ShopID {
return errors.New("卡不属于该店铺")
}
```
**重构后逻辑**
```go
// 1. 验证系列是否存在
series := s.packageSeriesStore.GetByID(req.SeriesID)
if series.Status != 1 {
return errors.New("套餐系列已禁用")
}
// 2. 验证操作者权限(仅代理)
if operatorShopID != nil {
allocation, err := s.seriesAllocationStore.GetByShopAndSeries(*operatorShopID, req.SeriesID)
if err != nil || allocation.Status != 1 {
return errors.New("您没有权限分配该套餐系列")
}
}
// 3. 验证卡的权限(基于 card.shop_id
if operatorShopID != nil && !s.hasPermission(*operatorShopID, card.ShopID) {
return errors.New("无权操作该卡")
}
```
**优势**
- 职责清晰:系列验证、权限验证、资源验证分离
- 错误提示更准确:区分"系列不存在"、"无权限"、"无权操作该卡"
- 平台用户(`operatorShopID = nil`)跳过权限检查,直接操作
### 决策 5测试数据准备策略
**选择**:测试时先创建 `PackageSeries`,再创建 `ShopSeriesAllocation`,最后设置卡/设备的 `series_id`
**数据准备顺序**
```go
// 1. 创建套餐系列
series := &model.PackageSeries{SeriesCode: "TEST-SERIES", SeriesName: "测试系列", Status: 1}
db.Create(series)
// 2. 创建店铺系列分配
allocation := &model.ShopSeriesAllocation{
ShopID: shopA.ID,
SeriesID: series.ID,
BaseCommissionValue: 200, // 20%
Status: 1,
}
db.Create(allocation)
// 3. 卡/设备直接绑定系列
card := &model.IotCard{ICCID: "898600...", SeriesID: &series.ID, ShopID: &shopA.ID}
db.Create(card)
```
**验证查询**
```go
// 验证返佣配置查询
allocation, err := seriesAllocationStore.GetByShopAndSeries(shopA.ID, series.ID)
assert.NoError(t, err)
assert.Equal(t, int64(200), allocation.BaseCommissionValue)
```
## Risks / Trade-offs
### 风险 1遗漏字段名修改导致运行时错误
**风险**:涉及约 150 处代码需要修改,可能遗漏某些地方,导致运行时 `column not found` 错误
**缓解措施**
1. 使用 IDE 全局搜索 `SeriesAllocationID``series_allocation_id`,逐一检查
2. 运行所有测试,确保覆盖所有代码路径
3. 分阶段提交Model → Store → Service → 测试,每个阶段验证编译通过
**检测方式**
```bash
# 搜索所有可能遗漏的引用
grep -r "SeriesAllocationID" internal/ --include="*.go"
grep -r "series_allocation_id" internal/ --include="*.go"
```
### 风险 2返佣查询失败导致业务中断
**风险**`GetByShopAndSeries` 查询失败时(如数据不一致),可能导致订单创建或返佣计算失败
**缓解措施**
1. 查询失败时区分 `ErrRecordNotFound` 和其他错误
- `ErrRecordNotFound`:视为"无返佣配置",继续业务流程
- 其他错误:返回错误,中断流程
2. 在关键流程(订单创建、充值)中,返佣计算失败不应阻止主流程
3. 添加日志记录,方便排查数据不一致问题
**实施**
```go
allocation, err := s.seriesAllocationStore.GetByShopAndSeries(shopID, seriesID)
if err != nil {
if err == gorm.ErrRecordNotFound {
// 无返佣配置,个人客户或未分配的店铺
return nil, nil // 不计算返佣
}
return nil, err // 其他错误,中断流程
}
```
### 风险 3性能回退增加查询次数
**风险**:虽然购买验证减少了一次查询,但返佣计算仍需查询 `ShopSeriesAllocation`,可能增加总查询次数
**实际影响**
- 购买验证:减少 1 次查询(`GetByID(allocation_id)`
- 返佣计算:增加 1 次条件查询(`GetByShopAndSeries(shop_id, series_id)`
- **净影响**0 查询增加(只是查询方式变了)
**性能优化**
1. 确保 `(shop_id, series_id)` 有复合索引
2. `GetByShopAndSeries` 添加 `status = 1` 条件,利用索引过滤
3. 个人客户场景下跳过返佣查询,实际减少查询次数
**索引验证**
```sql
-- 检查索引是否存在
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'tb_shop_series_allocation';
-- 如果不存在,添加复合索引
CREATE INDEX idx_shop_series_allocation_shop_series
ON tb_shop_series_allocation(shop_id, series_id)
WHERE status = 1;
```
### Trade-offAPI Breaking Change
**Trade-off**:修改 API 请求/响应字段名是 BREAKING CHANGE需要前端同步修改
**决策**:接受此 trade-off理由如下
1. 开发阶段,前后端可同步修改
2. 字段名更语义化,降低未来维护成本
3. 避免技术债务积累,现在修复比上线后修复成本低
**前端修改清单**
```typescript
// 修改前
interface BatchSetCardSeriesBindingRequest {
iccids: string[];
series_allocation_id: number; // ❌
}
// 修改后
interface BatchSetCardSeriesBindingRequest {
iccids: string[];
series_id: number; // ✅
}
```
## Migration Plan
### 实施步骤
**阶段 1数据库 & Model基础设施**
1. 创建数据库迁移文件 `000XXX_refactor_series_binding_to_series_id.up.sql`
2. 修改 `internal/model/iot_card.go``internal/model/device.go`
3. 修改所有 DTO 文件6 个结构体)
4. **验证**:编译通过,无语法错误
**阶段 2Store 层(数据访问)**
5. 更新 `IotCardStore``DeviceStore` 的查询过滤逻辑
6. 重命名 `BatchUpdateSeriesAllocation``BatchUpdateSeriesID`
7. 重命名 `ListBySeriesAllocationID``ListBySeriesID`
8. 新增 `ShopSeriesAllocationStore.GetByShopAndSeries()`
9. 新增或完善 `PackageSeriesStore`(如不存在)
10. **验证**Store 层测试通过
**阶段 3Service 层(核心业务)**
11. 修改 `iot_card/service.go``BatchSetSeriesBinding`
12. 修改 `device/service.go``BatchSetSeriesBinding`
13. 修改 `purchase_validation/service.go`(关键)
14. 修改 `commission_calculation/service.go`(关键)
15. 修改 `recharge/service.go`
16. 修改 `order/service.go`
17. **验证**Service 层测试通过
**阶段 4Handler & Routes**
18. 更新路由描述API 文档)
19. **验证**Handler 层无需修改(使用 DTO
**阶段 5测试**
20. 更新 Store 层测试(约 10 个测试用例)
21. 更新 Service 层测试(约 50 个测试用例)
22. 更新集成测试(约 40 个测试用例)
23. **验证**:运行 `go test ./...`,全部通过
**阶段 6验证 & 清理**
24. 运行数据库迁移:`migrate up`
25. 手动测试 APIPostman/curl
26. 检查日志,确认无错误
27. 更新 API 文档OpenAPI spec
28. 清理临时代码和注释
### Rollback 策略
如果在开发阶段发现问题,可以通过以下方式回滚:
**数据库回滚**
```sql
-- migrations/000XXX_refactor_series_binding_to_series_id.down.sql
ALTER TABLE tb_iot_card RENAME COLUMN series_id TO series_allocation_id;
ALTER TABLE tb_device RENAME COLUMN series_id TO series_allocation_id;
COMMENT ON COLUMN tb_iot_card.series_allocation_id IS '套餐系列分配ID(关联ShopSeriesAllocation)';
COMMENT ON COLUMN tb_device.series_allocation_id IS '套餐系列分配ID(关联ShopSeriesAllocation)';
```
**代码回滚**
- 使用 Git 回滚到重构前的 commit
- 执行 `migrate down` 回滚数据库
## Open Questions
### Q1: tb_shop_series_allocation 表是否有 (shop_id, series_id) 复合索引?
**需要验证**
```sql
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'tb_shop_series_allocation'
AND indexdef LIKE '%shop_id%'
AND indexdef LIKE '%series_id%';
```
**如果没有,需要添加**
```sql
CREATE INDEX idx_shop_series_allocation_shop_series
ON tb_shop_series_allocation(shop_id, series_id)
WHERE status = 1;
```
### Q2: PackageSeriesStore 是否已存在?
**需要确认**:是否已有 `internal/store/postgres/package_series_store.go`
**如果不存在,需要创建**
- 实现 `GetByID(ctx, id)` 方法
-`bootstrap/stores.go` 中注册
- 在 Service 中注入依赖
### Q3: 是否需要在 commission_calculation 中缓存 allocation 查询结果?
**场景**:同一笔订单多次计算返佣时,可能多次查询同一个 `(shop_id, series_id)` 的 allocation
**考虑**
- 如果查询频率高,可以在 Service 层缓存查询结果(使用 map
- 如果查询频率低,直接查询即可(有索引支持,性能可接受)
**决策**:暂不缓存,保持代码简洁。如果性能测试发现瓶颈,再优化。

View File

@@ -0,0 +1,84 @@
# Proposal: refactor-series-binding-to-series-id
## Why
当前系统中IoT卡和设备通过 `series_allocation_id`套餐系列分配ID字段绑定到 `ShopSeriesAllocation` 表,而不是直接绑定到 `PackageSeries`(套餐系列)。这导致了严重的语义混乱和架构问题:
1. **语义错误**:卡/设备应该表达"只能购买某个系列的套餐",而不是"绑定到某个权限分配"
2. **职责耦合**:资源属性(可购买的套餐范围)与权限配置(返佣规则)混在一起
3. **查询冗余**:每次需要 `series_id` 时都要通过 `allocation` 表查询,增加数据库负担
4. **配置僵化**:修改店铺的返佣配置时,需要重新绑定所有卡/设备
这是一个设计失误,需要在开发阶段彻底重构。正确的设计应该是:卡/设备直接绑定 `series_id`,权限验证和返佣查询时按需通过 `(shop_id, series_id)` 查询 `ShopSeriesAllocation`
## What Changes
- **数据库结构**:将 `tb_iot_card``tb_device``series_allocation_id` 字段重命名为 `series_id`,直接关联到 `tb_package_series`
- **Model 层**:修改 `IotCard``Device` 模型,将 `SeriesAllocationID` 字段改为 `SeriesID`
- **DTO 层**:更新所有相关 DTO包括查询请求、响应对象、批量设置请求
- **Store 层**
- 更新查询过滤条件(`series_allocation_id``series_id`
- 重命名批量更新方法(`BatchUpdateSeriesAllocation``BatchUpdateSeriesID`
- 重命名列表查询方法(`ListBySeriesAllocationID``ListBySeriesID`
- **新增** `ShopSeriesAllocationStore.GetByShopAndSeries(shopID, seriesID)` 方法,用于按需查询返佣配置
- **新增** `PackageSeriesStore`(如不存在)及其 `GetByID()` 方法
- **Service 层**:重构核心业务逻辑
- `BatchSetSeriesBinding`:验证 `series_id` 是否存在,检查操作者权限(通过 `GetByShopAndSeries` 查询)
- `ValidateCardPurchase` / `ValidateDevicePurchase`:直接使用 `card.series_id` 验证套餐,按需查询返佣配置
- `CalculateOrderCommission`:根据 `(shop_id, series_id)` 查询返佣配置,而不是通过 `allocation_id`
- `CreateRecharge`:同样改为按需查询返佣配置
- **API 文档**:更新路由描述,说明参数从 `series_allocation_id` 改为 `series_id`
- **测试**:更新约 100+ 个测试用例包括单元测试、集成测试、Store 测试
**关键行为变更**
- API `/api/admin/iot-cards/series-binding``/api/admin/devices/series-binding` 的请求参数从 `series_allocation_id` 改为 `series_id`
- 卡/设备列表的查询参数和响应字段同步改为 `series_id`
- 内部逻辑从"通过 allocation 获取 series_id"改为"直接使用 series_id按需查询 allocation"
## Capabilities
### New Capabilities
<!-- 无新增能力 -->
### Modified Capabilities
- `card-series-bindng`: 修改 IoT 卡系列绑定的数据模型和验证逻辑,从绑定"分配ID"改为绑定"系列ID"
- `device-series-bindng`: 修改设备系列绑定的数据模型和验证逻辑,从绑定"分配ID"改为绑定"系列ID"
## Impact
### 影响范围统计
- **数据库迁移**2 个迁移文件(新增重命名迁移,修改旧迁移注释)
- **Model 层**2 个文件(`internal/model/iot_card.go`, `internal/model/device.go`
- **DTO 层**2 个文件6 个结构体(`internal/model/dto/iot_card_dto.go`, `internal/model/dto/device_dto.go`
- **Store 层**3 个文件,新增 2 个查询方法(`iot_card_store.go`, `device_store.go`, `shop_series_allocation_store.go`
- **Service 层**6 个文件的核心逻辑重构
- `internal/service/iot_card/service.go`
- `internal/service/device/service.go`
- `internal/service/purchase_validation/service.go`(关键)
- `internal/service/commission_calculation/service.go`(关键)
- `internal/service/recharge/service.go`
- `internal/service/order/service.go`
- **Handler/Routes 层**2 个文件的路由描述更新
- **测试层**:约 10 个文件100+ 测试用例更新
### 受影响的 API 端点
- `PATCH /api/admin/iot-cards/series-binding`:请求参数 `series_allocation_id``series_id`
- `PATCH /api/admin/devices/series-binding`:请求参数 `series_allocation_id``series_id`
- `GET /api/admin/iot-cards/standalone`:查询参数和响应字段 `series_allocation_id``series_id`
- `GET /api/admin/devices`:查询参数和响应字段 `series_allocation_id``series_id`
### 向后兼容性
- **BREAKING CHANGE**API 请求/响应字段名变更,前端需要同步修改
- **数据迁移**:字段重命名,不需要数据转换(字段含义保持一致,只是重新指向 `PackageSeries.ID`
- **业务影响**:开发阶段,无生产数据,可直接重构
### 依赖和约束
- 依赖现有的 `tb_package_series` 表和 `tb_shop_series_allocation`
- 依赖现有的 `PackageSeries` 模型
- 需要创建或完善 `PackageSeriesStore`(如不存在)
- 测试需要创建完整的测试数据链路:`PackageSeries``ShopSeriesAllocation``IotCard/Device`
### 性能影响
- **查询优化**:购买验证时减少一次数据库查询(不再需要先查 `ShopSeriesAllocation` 获取 `series_id`
- **返佣查询**:增加一次按条件查询 `ShopSeriesAllocation``WHERE shop_id = ? AND series_id = ?`),但有索引支持,性能影响可忽略
- **整体影响**:轻微性能提升(减少了冗余查询)

View File

@@ -0,0 +1,114 @@
# Delta Spec: card-series-bindng
## MODIFIED Requirements
### Requirement: 批量设置卡的套餐系列
系统 SHALL 允许代理批量为 IoT 卡设置套餐系列。只能设置平台已启用的套餐系列,且代理必须有该系列的权限。
#### Scenario: 成功批量设置
- **WHEN** 代理提交多个 ICCID 和一个有效的 series_id
- **THEN** 系统更新这些卡的 series_id 字段
#### Scenario: 系列不存在
- **WHEN** 代理尝试设置一个不存在的系列 ID
- **THEN** 系统返回错误 "套餐系列不存在"
#### Scenario: 系列已禁用
- **WHEN** 代理尝试设置一个已禁用的套餐系列
- **THEN** 系统返回错误 "套餐系列已禁用"
#### Scenario: 代理无权限设置该系列
- **WHEN** 代理尝试设置一个未分配给自己店铺的系列
- **THEN** 系统返回错误 "您没有权限分配该套餐系列"
#### Scenario: ICCID 不存在
- **WHEN** 提交的 ICCID 中有不存在的卡
- **THEN** 系统返回错误,列出不存在的 ICCID
#### Scenario: 卡不属于当前店铺
- **WHEN** 代理尝试设置不属于自己店铺的卡
- **THEN** 系统返回错误 "无权操作该卡"
---
### Requirement: 清除卡的套餐系列关联
系统 SHALL 允许代理清除卡的套餐系列关联(将 series_id 设为 0
#### Scenario: 清除单卡关联
- **WHEN** 代理将卡的 series_id 设为 0
- **THEN** 系统清除该卡的套餐系列关联
#### Scenario: 批量清除关联
- **WHEN** 代理批量提交 ICCID 列表series_id 为 0
- **THEN** 系统清除这些卡的套餐系列关联
---
### Requirement: 查询卡的套餐系列信息
系统 SHALL 在卡详情和列表中返回套餐系列关联信息。
#### Scenario: 卡详情包含系列信息
- **WHEN** 查询卡详情
- **THEN** 响应包含 series_id、关联的系列名称、佣金状态
#### Scenario: 卡列表支持按系列筛选
- **WHEN** 代理按 series_id 筛选卡列表
- **THEN** 系统只返回关联该系列的卡
---
### Requirement: IotCard 模型字段定义
系统 MUST 在 IotCard 模型中包含以下字段:
- `series_id`:套餐系列 ID直接关联到 PackageSeries
- `first_commission_paid`:一次性佣金是否已发放(默认 false
- `accumulated_recharge`:累计充值金额(默认 0
#### Scenario: 新卡默认值
- **WHEN** 创建新的 IoT 卡
- **THEN** series_id 为空first_commission_paid 为 falseaccumulated_recharge 为 0
#### Scenario: 字段在响应中可见
- **WHEN** 查询卡信息
- **THEN** 响应包含这三个字段
---
## ADDED Requirements
### Requirement: 购买验证使用 series_id
系统 MUST 在验证卡购买套餐时,直接使用 `card.series_id` 验证套餐是否属于该系列。
#### Scenario: 卡有系列绑定
- **WHEN** 卡的 series_id 为 5用户购买 series_id 为 5 的套餐
- **THEN** 系统允许购买
#### Scenario: 卡未绑定系列
- **WHEN** 卡的 series_id 为空,用户尝试购买任何套餐
- **THEN** 系统返回错误 "该卡未关联套餐系列,无法购买套餐"
#### Scenario: 套餐不属于卡的系列
- **WHEN** 卡的 series_id 为 5用户购买 series_id 为 8 的套餐
- **THEN** 系统返回错误 "套餐不在可购买范围内"
---
### Requirement: 返佣查询使用 (shop_id, series_id)
系统 MUST 在计算返佣时,通过 `(shop_id, series_id)` 查询 `ShopSeriesAllocation` 获取返佣配置。
#### Scenario: 店铺有系列权限
- **WHEN** 卡的 shop_id 为 10series_id 为 5且存在 ShopSeriesAllocation(shop_id=10, series_id=5)
- **THEN** 系统使用该分配记录的返佣配置计算佣金
#### Scenario: 店铺无系列权限
- **WHEN** 卡的 shop_id 为 10series_id 为 5但不存在对应的 ShopSeriesAllocation
- **THEN** 系统不计算返佣(个人客户场景或未分配系列)
#### Scenario: 个人客户无返佣
- **WHEN** 卡的 shop_id 为空个人客户series_id 为 5
- **THEN** 系统不查询 ShopSeriesAllocation不计算返佣

View File

@@ -0,0 +1,128 @@
# Delta Spec: device-series-bindng
## MODIFIED Requirements
### Requirement: 批量设置设备的套餐系列
系统 SHALL 允许代理批量为设备设置套餐系列。只能设置平台已启用的套餐系列,且代理必须有该系列的权限。
#### Scenario: 成功批量设置
- **WHEN** 代理提交多个设备 ID 和一个有效的 series_id
- **THEN** 系统更新这些设备的 series_id 字段
#### Scenario: 系列不存在
- **WHEN** 代理尝试设置一个不存在的系列 ID
- **THEN** 系统返回错误 "套餐系列不存在"
#### Scenario: 系列已禁用
- **WHEN** 代理尝试设置一个已禁用的套餐系列
- **THEN** 系统返回错误 "套餐系列已禁用"
#### Scenario: 代理无权限设置该系列
- **WHEN** 代理尝试设置一个未分配给自己店铺的系列
- **THEN** 系统返回错误 "您没有权限分配该套餐系列"
#### Scenario: 设备不存在
- **WHEN** 提交的设备 ID 中有不存在的设备
- **THEN** 系统返回错误,列出不存在的设备 ID
#### Scenario: 设备不属于当前店铺
- **WHEN** 代理尝试设置不属于自己店铺的设备
- **THEN** 系统返回错误 "无权操作该设备"
---
### Requirement: 清除设备的套餐系列关联
系统 SHALL 允许代理清除设备的套餐系列关联(将 series_id 设为 0
#### Scenario: 清除单设备关联
- **WHEN** 代理将设备的 series_id 设为 0
- **THEN** 系统清除该设备的套餐系列关联
#### Scenario: 批量清除关联
- **WHEN** 代理批量提交设备 ID 列表series_id 为 0
- **THEN** 系统清除这些设备的套餐系列关联
---
### Requirement: 查询设备的套餐系列信息
系统 SHALL 在设备详情和列表中返回套餐系列关联信息。
#### Scenario: 设备详情包含系列信息
- **WHEN** 查询设备详情
- **THEN** 响应包含 series_id、关联的系列名称、佣金状态
#### Scenario: 设备列表支持按系列筛选
- **WHEN** 代理按 series_id 筛选设备列表
- **THEN** 系统只返回关联该系列的设备
---
### Requirement: Device 模型字段定义
系统 MUST 在 Device 模型中包含以下字段:
- `series_id`:套餐系列 ID直接关联到 PackageSeries
- `first_commission_paid`:一次性佣金是否已发放(默认 false
- `accumulated_recharge`:累计充值金额(默认 0
#### Scenario: 新设备默认值
- **WHEN** 创建新设备
- **THEN** series_id 为空first_commission_paid 为 falseaccumulated_recharge 为 0
#### Scenario: 字段在响应中可见
- **WHEN** 查询设备信息
- **THEN** 响应包含这三个字段
---
### Requirement: 设备级套餐购买使用 series_id
设备购买套餐时 MUST 使用 `device.series_id` 确定可购买的套餐系列。
#### Scenario: 设备有系列关联
- **WHEN** 设备的 series_id 为 5用户购买 series_id 为 5 的套餐
- **THEN** 系统允许购买
#### Scenario: 设备未绑定系列
- **WHEN** 设备的 series_id 为空
- **THEN** 该设备无法购买设备级套餐,系统返回错误 "该设备未关联套餐系列,无法购买套餐"
#### Scenario: 套餐不属于设备的系列
- **WHEN** 设备的 series_id 为 5用户购买 series_id 为 8 的套餐
- **THEN** 系统返回错误 "套餐不在可购买范围内"
---
## ADDED Requirements
### Requirement: 购买验证直接使用 series_id
系统 MUST 在验证设备购买套餐时,直接使用 `device.series_id` 验证套餐是否属于该系列,不再依赖设备下卡的 series_id。
#### Scenario: 设备和卡的系列不同
- **WHEN** 设备的 series_id 为 5设备下的卡的 series_id 为 8
- **THEN** 购买设备级套餐时,系统使用设备的 series_id5忽略卡的 series_id
#### Scenario: 设备有系列,卡无系列
- **WHEN** 设备的 series_id 为 5设备下的卡的 series_id 为空
- **THEN** 设备仍然可以购买 series_id 为 5 的设备级套餐
---
### Requirement: 返佣查询使用 (shop_id, series_id)
系统 MUST 在计算返佣时,通过 `(shop_id, series_id)` 查询 `ShopSeriesAllocation` 获取返佣配置。
#### Scenario: 店铺有系列权限
- **WHEN** 设备的 shop_id 为 10series_id 为 5且存在 ShopSeriesAllocation(shop_id=10, series_id=5)
- **THEN** 系统使用该分配记录的返佣配置计算佣金
#### Scenario: 店铺无系列权限
- **WHEN** 设备的 shop_id 为 10series_id 为 5但不存在对应的 ShopSeriesAllocation
- **THEN** 系统不计算返佣(个人客户场景或未分配系列)
#### Scenario: 个人客户无返佣
- **WHEN** 设备的 shop_id 为空个人客户series_id 为 5
- **THEN** 系统不查询 ShopSeriesAllocation不计算返佣

View File

@@ -0,0 +1,191 @@
# Tasks: refactor-series-binding-to-series-id
## 1. 数据库迁移
- [x] 1.1 创建数据库迁移文件 `migrations/000XXX_refactor_series_binding_to_series_id.up.sql`,重命名 `tb_iot_card.series_allocation_id``series_id``tb_device.series_allocation_id``series_id`,更新字段注释
- [x] 1.2 创建回滚迁移文件 `migrations/000XXX_refactor_series_binding_to_series_id.down.sql`
- [x] 1.3 验证索引是否存在:检查 `tb_shop_series_allocation` 是否有 `(shop_id, series_id)` 复合索引,如不存在则添加
- [x] 1.4 执行迁移:运行 `migrate up`,验证字段重命名成功,无错误
## 2. Model 层修改
- [x] 2.1 修改 `internal/model/iot_card.go`:将 `SeriesAllocationID` 字段重命名为 `SeriesID`,更新 gorm 标签和注释
- [x] 2.2 修改 `internal/model/device.go`:将 `SeriesAllocationID` 字段重命名为 `SeriesID`,更新 gorm 标签和注释
- [x] 2.3 验证编译:运行 `go build ./internal/model/...`,确认无编译错误
## 3. DTO 层修改
- [x] 3.1 修改 `internal/model/dto/iot_card_dto.go`:更新 `ListStandaloneIotCardRequest` 的查询参数 `SeriesAllocationID``SeriesID`
- [x] 3.2 修改 `internal/model/dto/iot_card_dto.go`:更新 `StandaloneIotCardResponse` 的响应字段 `SeriesAllocationID``SeriesID`
- [x] 3.3 修改 `internal/model/dto/iot_card_dto.go`:更新 `BatchSetCardSeriesBindngRequest` 的请求字段 `SeriesAllocationID``SeriesID`,更新 description 为 "套餐系列ID0表示清除关联"
- [x] 3.4 修改 `internal/model/dto/device_dto.go`:更新 `ListDeviceRequest` 的查询参数 `SeriesAllocationID``SeriesID`
- [x] 3.5 修改 `internal/model/dto/device_dto.go`:更新 `DeviceResponse` 的响应字段 `SeriesAllocationID``SeriesID`
- [x] 3.6 修改 `internal/model/dto/device_dto.go`:更新 `BatchSetDeviceSeriesBindngRequest` 的请求字段 `SeriesAllocationID``SeriesID`,更新 description 为 "套餐系列ID0表示清除关联"
- [x] 3.7 验证编译:运行 `go build ./internal/model/dto/...`,确认无编译错误
## 4. Store 层修改
- [x] 4.1 修改 `internal/store/postgres/iot_card_store.go`:更新 `ListStandalone` 方法,将过滤条件 `series_allocation_id` 改为 `series_id`
- [x] 4.2 修改 `internal/store/postgres/iot_card_store.go`:更新 `Count` 方法,将过滤条件 `series_allocation_id` 改为 `series_id`
- [x] 4.3 修改 `internal/store/postgres/iot_card_store.go`:重命名方法 `BatchUpdateSeriesAllocation``BatchUpdateSeriesID`,更新 SQL 字段名
- [x] 4.4 修改 `internal/store/postgres/iot_card_store.go`:重命名方法 `ListBySeriesAllocationID``ListBySeriesID`,更新 WHERE 条件
- [x] 4.5 修改 `internal/store/postgres/device_store.go`:更新 `List` 方法,将过滤条件 `series_allocation_id` 改为 `series_id`
- [x] 4.6 修改 `internal/store/postgres/device_store.go`:重命名方法 `BatchUpdateSeriesAllocation``BatchUpdateSeriesID`,更新 SQL 字段名
- [x] 4.7 修改 `internal/store/postgres/device_store.go`:重命名方法 `ListBySeriesAllocationID``ListBySeriesID`,更新 WHERE 条件
- [x] 4.8 修改 `internal/store/postgres/shop_series_allocation_store.go`:新增方法 `GetByShopAndSeries(ctx, shopID, seriesID)`,实现根据店铺和系列查询分配配置
- [x] 4.9 验证或创建 `internal/store/postgres/package_series_store.go`:如不存在则创建,实现 `GetByID(ctx, id)` 方法
- [x] 4.10 如果创建了新 Store`internal/bootstrap/stores.go` 中注册 `PackageSeriesStore`
- [x] 4.11 验证编译:运行 `go build ./internal/store/...`,确认无编译错误
## 5. Service 层修改 - iot_card
- [x] 5.1 修改 `internal/service/iot_card/service.go`:更新 `ListStandalone` 方法,将过滤条件 key `series_allocation_id` 改为 `series_id`
- [x] 5.2 修改 `internal/service/iot_card/service.go`:更新 `buildStandaloneResponse` 方法,将字段 `SeriesAllocationID` 改为 `SeriesID`
- [x] 5.3 修改 `internal/service/iot_card/service.go`:重构 `BatchSetSeriesBinding` 方法
- [x] 5.4 在 `internal/service/iot_card/service.go``Service` 结构体中添加 `packageSeriesStore` 依赖(如果不存在)
- [x] 5.5 验证编译:运行 `go build ./internal/service/iot_card/...`,确认无编译错误
- [x] 5.6 运行 `lsp_diagnostics` 检查 `internal/service/iot_card/service.go`,确认无类型错误
## 6. Service 层修改 - device
- [x] 6.1 修改 `internal/service/device/service.go`:更新 `List` 方法,将过滤条件 key `series_allocation_id` 改为 `series_id`
- [x] 6.2 修改 `internal/service/device/service.go`:更新 `buildDeviceResponse` 方法,将字段 `SeriesAllocationID` 改为 `SeriesID`
- [x] 6.3 修改 `internal/service/device/service.go`:重构 `BatchSetSeriesBinding` 方法
- [x] 6.4 在 `internal/service/device/service.go``Service` 结构体中添加 `packageSeriesStore` 依赖(如果不存在)
- [x] 6.5 验证编译:运行 `go build ./internal/service/device/...`,确认无编译错误
- [x] 6.6 运行 `lsp_diagnostics` 检查 `internal/service/device/service.go`,确认无类型错误
## 7. Service 层修改 - purchase_validation关键
- [x] 7.1 修改 `internal/service/purchase_validation/service.go`:重构 `ValidateCardPurchase` 方法
- [x] 7.2 修改 `internal/service/purchase_validation/service.go`:重构 `ValidateDevicePurchase` 方法
- [x] 7.3 更新 `ValidateCardPurchase``ValidateDevicePurchase` 的错误消息,从 "套餐系列分配不存在" 改为 "该卡/设备未关联套餐系列"
- [x] 7.4 验证编译:运行 `go build ./internal/service/purchase_validation/...`,确认无编译错误
- [x] 7.5 运行 `lsp_diagnostics` 检查 `internal/service/purchase_validation/service.go`,确认无类型错误
## 8. Service 层修改 - commission_calculation关键
- [x] 8.1 修改 `internal/service/commission_calculation/service.go`:重构 `CalculateOrderCommission` 方法
- [x] 8.2 修改 `internal/service/commission_calculation/service.go`:重构 `CalculateDeviceOrderCommission` 方法(同样的逻辑)
- [x] 8.3 验证编译:运行 `go build ./internal/service/commission_calculation/...`,确认无编译错误
- [x] 8.4 运行 `lsp_diagnostics` 检查 `internal/service/commission_calculation/service.go`,确认无类型错误
## 9. Service 层修改 - recharge
- [x] 9.1 修改 `internal/service/recharge/service.go`:重构充值相关方法,将获取 `seriesAllocationID` 的逻辑改为直接使用 `seriesID`
- [x] 9.2 修改 `internal/service/recharge/service.go`:更新返佣查询逻辑,使用 `GetByShopAndSeries(shopID, seriesID)` 而不是 `GetByID(allocationID)`
- [x] 9.3 验证编译:运行 `go build ./internal/service/recharge/...`,确认无编译错误
- [x] 9.4 运行 `lsp_diagnostics` 检查 `internal/service/recharge/service.go`,确认无类型错误
## 10. Service 层修改 - order
- [x] 10.1 检查 `internal/service/order/service.go` 中是否有直接使用 `SeriesAllocationID` 的地方,如有则更新为 `SeriesID`
- [x] 10.2 验证编译:运行 `go build ./internal/service/order/...`,确认无编译错误
- [x] 10.3 运行 `lsp_diagnostics` 检查 `internal/service/order/service.go`,确认无类型错误
## 11. Bootstrap 依赖注入
- [x] 11.1 如果创建了 `PackageSeriesStore`,在 `internal/bootstrap/stores.go` 中初始化并添加到 `Stores` 结构体
- [x] 11.2 在 `internal/bootstrap/services.go` 中,为 `iot_card.Service``device.Service` 注入 `packageSeriesStore` 依赖
- [x] 11.3 验证编译:运行 `go build ./internal/bootstrap/...`,确认无编译错误
## 12. Handler & Routes 层
- [x] 12.1 修改 `internal/routes/iot_card.go`:更新 `/series-binding` 路由的 Description说明参数从 `series_allocation_id` 改为 `series_id`
- [x] 12.2 修改 `internal/routes/device.go`:更新 `/series-binding` 路由的 Description说明参数从 `series_allocation_id` 改为 `series_id`
- [x] 12.3 验证 Handler 层代码:`internal/handler/admin/iot_card.go``device.go` 无需修改(使用 DTO
- [x] 12.4 验证编译:运行 `go build ./internal/routes/... ./internal/handler/...`,确认无编译错误
## 13. Store 层测试更新
- [x] 13.1 修改 `internal/store/postgres/iot_card_store_test.go`:更新所有测试用例,将 `SeriesAllocationID` 改为 `SeriesID`
- [x] 13.2 修改 `internal/store/postgres/iot_card_store_test.go`:重命名测试函数 `TestIotCardStore_ListBySeriesAllocationID``TestIotCardStore_ListBySeriesID`
- [x] 13.3 修改 `internal/store/postgres/iot_card_store_test.go`:更新过滤条件测试,将 `series_allocation_id` 改为 `series_id`
- [x] 13.4 修改 `internal/store/postgres/device_store_test.go`:更新所有测试用例,将 `SeriesAllocationID` 改为 `SeriesID`
- [x] 13.5 修改 `internal/store/postgres/device_store_test.go`:重命名测试函数 `TestDeviceStore_ListBySeriesAllocationID``TestDeviceStore_ListBySeriesID`
- [x] 13.6 新增测试:在 `shop_series_allocation_store_test.go` 中添加 `TestShopSeriesAllocationStore_GetByShopAndSeries` 测试
- [x] 13.7 运行 Store 层测试:`source .env.local && go test -v ./internal/store/postgres/...`,确认全部通过
## 14. Service 层测试更新 - iot_card
- [x] 14.1 修改 `internal/service/iot_card/service_test.go`:更新 `TestIotCardService_BatchSetSeriesBinding` 测试
- [x] 14.2 更新测试数据准备顺序:先 `PackageSeries`,再 `ShopSeriesAllocation`,最后 `IotCard`
- [x] 14.3 运行 Service 层测试:`source .env.local && go test -v ./internal/service/iot_card/...`,确认全部通过
## 15. Service 层测试更新 - device
- [x] 15.1 修改 `internal/service/device/service_test.go`:更新 `TestDeviceService_BatchSetSeriesBinding` 测试
- [x] 15.2 更新测试数据准备顺序:先 `PackageSeries`,再 `ShopSeriesAllocation`,最后 `Device`
- [x] 15.3 运行 Service 层测试:`source .env.local && go test -v ./internal/service/device/...`,确认全部通过
## 16. Service 层测试更新 - purchase_validation
- [x] 16.1 修改 `internal/service/purchase_validation/service_test.go`:更新所有测试用例
- [x] 16.2 运行 Service 层测试:`source .env.local && go test -v ./internal/service/purchase_validation/...`,确认全部通过
## 17. Service 层测试更新 - commission_calculation
- [x] 17.1 修改 `internal/service/commission_calculation/service_test.go`:更新所有测试用例
- [x] 17.2 运行 Service 层测试:`source .env.local && go test -v ./internal/service/commission_calculation/...`,确认全部通过
## 18. Service 层测试更新 - recharge & order
- [x] 18.1 修改 `internal/service/recharge/service_test.go`:更新测试用例,将 `SeriesAllocationID` 改为 `SeriesID`
- [x] 18.2 修改 `internal/service/order/service_test.go`:更新测试用例,将 `SeriesAllocationID` 改为 `SeriesID`
- [x] 18.3 运行 Service 层测试:`source .env.local && go test -v ./internal/service/recharge/... ./internal/service/order/...`,确认全部通过
## 19. 集成测试更新 - iot_card
- [x] 19.1 修改 `tests/integration/iot_card_test.go`:更新 `TestIotCard_BatchSetSeriesBinding` 测试
- [x] 19.2 更新所有子测试用例的 JSON 请求体(约 10 个)
- [x] 19.3 运行集成测试:`source .env.local && cd tests/integration && go test -v -run "TestIotCard_BatchSetSeriesBinding"`,确认全部通过
## 20. 集成测试更新 - device
- [x] 20.1 修改 `tests/integration/device_test.go`:更新 `TestDevice_BatchSetSeriesBinding` 测试
- [x] 20.2 更新所有子测试用例的 JSON 请求体(约 10 个)
- [x] 20.3 运行集成测试:`source .env.local && cd tests/integration && go test -v -run "TestDevice_BatchSetSeriesBinding"`,确认全部通过
## 21. 单元测试更新 - commission_calculation
- [x] 21.1 修改 `tests/unit/commission_calculation_service_test.go`:更新所有测试用例
- [x] 21.2 运行单元测试:`source .env.local && go test -v ./tests/unit/...`,确认全部通过
## 22. 全量测试验证
- [x] 22.1 运行所有测试:`source .env.local && go test -v ./...`,确认全部通过,无遗漏
- [x] 22.2 运行编译检查:`go build ./...`,确认无编译错误
- [x] 22.3 使用 grep 搜索遗漏:`grep -r "SeriesAllocationID" internal/ --include="*.go"`,确认无遗漏
- [x] 22.4 使用 grep 搜索遗漏:`grep -r "series_allocation_id" internal/ --include="*.go"`,确认无遗漏(仅数据库注释除外)
## 23. API 手动测试
- [ ] 23.1 启动本地服务:`go run cmd/api/main.go`
- [ ] 23.2 测试 IoT 卡系列绑定 API`PATCH /api/admin/iot-cards/series-binding`,使用 Postman 或 curl 发送请求,验证参数 `series_id` 生效
- [ ] 23.3 测试设备系列绑定 API`PATCH /api/admin/devices/series-binding`,使用 Postman 或 curl 发送请求,验证参数 `series_id` 生效
- [ ] 23.4 测试卡列表查询:`GET /api/admin/iot-cards/standalone?series_id=1`,验证过滤生效
- [ ] 23.5 测试设备列表查询:`GET /api/admin/devices?series_id=1`,验证过滤生效
- [ ] 23.6 检查日志确认无错误日志SQL 查询使用 `series_id` 而不是 `series_allocation_id`
## 24. API 文档更新
- [x] 24.1 更新 OpenAPI 文档注释:确保路由描述中明确说明参数从 `series_allocation_id` 改为 `series_id`
- [x] 24.2 重新生成 API 文档:运行 `go run cmd/gendocs/main.go`,生成最新的 OpenAPI spec
- [x] 24.3 验证生成的文档:检查 `docs/admin-openapi.yaml``/iot-cards/series-binding``/devices/series-binding` 的参数定义
- [x] 24.4 如有前端文档,更新前端接口文档,说明 BREAKING CHANGE
## 25. 清理和最终验证
- [x] 25.1 删除所有临时代码和注释
- [x] 25.2 运行 `gofmt -w .` 格式化所有代码
- [x] 25.3 运行 `go mod tidy` 清理依赖
- [x] 25.4 再次运行全量测试:`source .env.local && go test -v ./...`,确认全部通过
- [x] 25.5 使用 `git diff` 检查所有改动,确认无遗漏,无多余修改
- [x] 25.6 更新 CHANGELOG如有记录 BREAKING CHANGE
## 26. 提交和归档
- [x] 26.1 提交代码:创建 Git commit使用中文 commit message"重构: 将卡/设备的套餐系列绑定从分配ID改为系列ID"
- [ ] 26.2 运行 OpenSpec 归档:`openspec archive refactor-series-binding-to-series-id`
- [ ] 26.3 验证归档成功:检查 `openspec/changes/archive/` 目录,确认变更已归档
- [ ] 26.4 清理工作目录:删除 `openspec/changes/refactor-series-binding-to-series-id/`(已归档)

View File

@@ -257,7 +257,7 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
agentAccount := env.CreateTestAccount(fmt.Sprintf("agent_dev_%d", time.Now().UnixNano()), "password123", constants.UserTypeAgent, &shop.ID, nil) agentAccount := env.CreateTestAccount(fmt.Sprintf("agent_dev_%d", time.Now().UnixNano()), "password123", constants.UserTypeAgent, &shop.ID, nil)
series := createTestPackageSeries(t, env, "测试系列") series := createTestPackageSeries(t, env, "测试系列")
allocation := createTestAllocation(t, env, shop.ID, series.ID, 0) createTestAllocation(t, env, shop.ID, series.ID, 0)
devices := []*model.Device{ devices := []*model.Device{
{DeviceNo: fmt.Sprintf("DEV_%d_001", time.Now().UnixNano()), DeviceName: "测试设备1", DeviceType: "router", MaxSimSlots: 4, Status: constants.DeviceStatusInStock, ShopID: &shop.ID}, {DeviceNo: fmt.Sprintf("DEV_%d_001", time.Now().UnixNano()), DeviceName: "测试设备1", DeviceType: "router", MaxSimSlots: 4, Status: constants.DeviceStatusInStock, ShopID: &shop.ID},
@@ -270,8 +270,8 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
t.Run("批量设置设备系列绑定-成功", func(t *testing.T) { t.Run("批量设置设备系列绑定-成功", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{devices[0].ID, devices[1].ID}, "device_ids": []uint{devices[0].ID, devices[1].ID},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -297,14 +297,14 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
var updatedDevice model.Device var updatedDevice model.Device
err = env.RawDB().Where("id = ?", devices[0].ID).First(&updatedDevice).Error err = env.RawDB().Where("id = ?", devices[0].ID).First(&updatedDevice).Error
require.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, updatedDevice.SeriesAllocationID) assert.NotNil(t, updatedDevice.SeriesID)
assert.Equal(t, allocation.ID, *updatedDevice.SeriesAllocationID) assert.Equal(t, series.ID, *updatedDevice.SeriesID)
}) })
t.Run("清除设备系列绑定-series_allocation_id=0", func(t *testing.T) { t.Run("清除设备系列绑定-series_id=0", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{devices[0].ID}, "device_ids": []uint{devices[0].ID},
"series_allocation_id": 0, "series_id": 0,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -322,13 +322,13 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
var updatedDevice model.Device var updatedDevice model.Device
err = env.RawDB().Where("id = ?", devices[0].ID).First(&updatedDevice).Error err = env.RawDB().Where("id = ?", devices[0].ID).First(&updatedDevice).Error
require.NoError(t, err) require.NoError(t, err)
assert.Nil(t, updatedDevice.SeriesAllocationID, "系列分配应被清除") assert.Nil(t, updatedDevice.SeriesID, "系列分配应被清除")
}) })
t.Run("批量设置-部分设备不存在", func(t *testing.T) { t.Run("批量设置-部分设备不存在", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{devices[2].ID, 999999}, "device_ids": []uint{devices[2].ID, 999999},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -359,8 +359,8 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
t.Run("设置不存在的系列分配-应失败", func(t *testing.T) { t.Run("设置不存在的系列分配-应失败", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{devices[2].ID}, "device_ids": []uint{devices[2].ID},
"series_allocation_id": 999999, "series_id": 999999,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -374,14 +374,14 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
assert.NotEqual(t, 0, result.Code, "不存在的系列分配应返回错误") assert.NotEqual(t, 0, result.Code, "不存在的系列分配应返回错误")
}) })
t.Run("设置禁用的系列分配-应失败", func(t *testing.T) { t.Run("设置禁用的系列-应失败", func(t *testing.T) {
disabledSeries := createTestPackageSeries(t, env, "禁用系列") disabledSeries := createTestPackageSeries(t, env, "禁用系列")
disabledAllocation := createTestAllocation(t, env, shop.ID, disabledSeries.ID, 0) env.TX.Model(&model.PackageSeries{}).Where("id = ?", disabledSeries.ID).Update("status", constants.StatusDisabled)
env.TX.Model(&model.ShopSeriesAllocation{}).Where("id = ?", disabledAllocation.ID).Update("status", constants.StatusDisabled) env.TX.Model(&model.ShopSeriesAllocation{}).Where("id = ?", disabledSeries.ID).Update("status", constants.StatusDisabled)
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{devices[2].ID}, "device_ids": []uint{devices[2].ID},
"series_allocation_id": disabledAllocation.ID, "series_id": disabledSeries.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -408,8 +408,8 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
require.NoError(t, env.TX.Create(otherDevice).Error) require.NoError(t, env.TX.Create(otherDevice).Error)
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{otherDevice.ID}, "device_ids": []uint{otherDevice.ID},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -438,11 +438,11 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
} }
require.NoError(t, env.TX.Create(anotherDevice).Error) require.NoError(t, env.TX.Create(anotherDevice).Error)
anotherAllocation := createTestAllocation(t, env, anotherShop.ID, series.ID, 0) createTestAllocation(t, env, anotherShop.ID, series.ID, 0)
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{anotherDevice.ID}, "device_ids": []uint{anotherDevice.ID},
"series_allocation_id": anotherAllocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -463,8 +463,8 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
t.Run("未认证请求应返回错误", func(t *testing.T) { t.Run("未认证请求应返回错误", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{devices[0].ID}, "device_ids": []uint{devices[0].ID},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -480,8 +480,8 @@ func TestDevice_BatchSetSeriesBinding(t *testing.T) {
t.Run("空设备ID列表-返回成功但无操作", func(t *testing.T) { t.Run("空设备ID列表-返回成功但无操作", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"device_ids": []uint{}, "device_ids": []uint{},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)

View File

@@ -552,7 +552,7 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
// 创建套餐系列和分配 // 创建套餐系列和分配
series := createTestPackageSeries(t, env, "测试系列") series := createTestPackageSeries(t, env, "测试系列")
allocation := createTestAllocation(t, env, shop.ID, series.ID, 0) createTestAllocation(t, env, shop.ID, series.ID, 0)
// 创建测试卡(归属于该店铺) // 创建测试卡(归属于该店铺)
timestamp := time.Now().Unix() % 1000000 timestamp := time.Now().Unix() % 1000000
@@ -567,8 +567,8 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
t.Run("批量设置卡系列绑定-成功", func(t *testing.T) { t.Run("批量设置卡系列绑定-成功", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{cards[0].ICCID, cards[1].ICCID}, "iccids": []string{cards[0].ICCID, cards[1].ICCID},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -592,14 +592,14 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
var updatedCard model.IotCard var updatedCard model.IotCard
err = env.RawDB().Where("iccid = ?", cards[0].ICCID).First(&updatedCard).Error err = env.RawDB().Where("iccid = ?", cards[0].ICCID).First(&updatedCard).Error
require.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, updatedCard.SeriesAllocationID) assert.NotNil(t, updatedCard.SeriesID)
assert.Equal(t, allocation.ID, *updatedCard.SeriesAllocationID) assert.Equal(t, series.ID, *updatedCard.SeriesID)
}) })
t.Run("清除卡系列绑定-series_allocation_id=0", func(t *testing.T) { t.Run("清除卡系列绑定-series_id=0", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{cards[0].ICCID}, "iccids": []string{cards[0].ICCID},
"series_allocation_id": 0, "series_id": 0,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -618,13 +618,13 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
var updatedCard model.IotCard var updatedCard model.IotCard
err = env.RawDB().Where("iccid = ?", cards[0].ICCID).First(&updatedCard).Error err = env.RawDB().Where("iccid = ?", cards[0].ICCID).First(&updatedCard).Error
require.NoError(t, err) require.NoError(t, err)
assert.Nil(t, updatedCard.SeriesAllocationID, "系列分配应被清除") assert.Nil(t, updatedCard.SeriesID, "系列分配应被清除")
}) })
t.Run("批量设置-部分卡不存在", func(t *testing.T) { t.Run("批量设置-部分卡不存在", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{cards[2].ICCID, "NONEXISTENT_ICCID_999"}, "iccids": []string{cards[2].ICCID, "NONEXISTENT_ICCID_999"},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -653,8 +653,8 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
t.Run("设置不存在的系列分配-应失败", func(t *testing.T) { t.Run("设置不存在的系列分配-应失败", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{cards[2].ICCID}, "iccids": []string{cards[2].ICCID},
"series_allocation_id": 999999, "series_id": 999999,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -668,15 +668,15 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
assert.NotEqual(t, 0, result.Code, "不存在的系列分配应返回错误") assert.NotEqual(t, 0, result.Code, "不存在的系列分配应返回错误")
}) })
t.Run("设置禁用的系列分配-应失败", func(t *testing.T) { t.Run("设置禁用的系列-应失败", func(t *testing.T) {
// 创建一个禁用的分配 // 创建一个禁用的分配
disabledSeries := createTestPackageSeries(t, env, "禁用系列") disabledSeries := createTestPackageSeries(t, env, "禁用系列")
disabledAllocation := createTestAllocation(t, env, shop.ID, disabledSeries.ID, 0) env.TX.Model(&model.PackageSeries{}).Where("id = ?", disabledSeries.ID).Update("status", constants.StatusDisabled)
env.TX.Model(&model.ShopSeriesAllocation{}).Where("id = ?", disabledAllocation.ID).Update("status", constants.StatusDisabled) env.TX.Model(&model.ShopSeriesAllocation{}).Where("id = ?", disabledSeries.ID).Update("status", constants.StatusDisabled)
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{cards[2].ICCID}, "iccids": []string{cards[2].ICCID},
"series_allocation_id": disabledAllocation.ID, "series_id": disabledSeries.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -703,8 +703,8 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
require.NoError(t, env.TX.Create(otherCard).Error) require.NoError(t, env.TX.Create(otherCard).Error)
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{otherCard.ICCID}, "iccids": []string{otherCard.ICCID},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -735,11 +735,11 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
require.NoError(t, env.TX.Create(anotherCard).Error) require.NoError(t, env.TX.Create(anotherCard).Error)
// 为这个店铺创建系列分配 // 为这个店铺创建系列分配
anotherAllocation := createTestAllocation(t, env, anotherShop.ID, series.ID, 0) createTestAllocation(t, env, anotherShop.ID, series.ID, 0)
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{anotherCard.ICCID}, "iccids": []string{anotherCard.ICCID},
"series_allocation_id": anotherAllocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -761,8 +761,8 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
t.Run("未认证请求应返回错误", func(t *testing.T) { t.Run("未认证请求应返回错误", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{cards[0].ICCID}, "iccids": []string{cards[0].ICCID},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)
@@ -778,8 +778,8 @@ func TestIotCard_BatchSetSeriesBinding(t *testing.T) {
t.Run("空ICCID列表-返回成功但无操作", func(t *testing.T) { t.Run("空ICCID列表-返回成功但无操作", func(t *testing.T) {
body := map[string]interface{}{ body := map[string]interface{}{
"iccids": []string{}, "iccids": []string{},
"series_allocation_id": allocation.ID, "series_id": series.ID,
} }
jsonBody, _ := json.Marshal(body) jsonBody, _ := json.Marshal(body)