Compare commits
10 Commits
0ef136f008
...
e45610661e
| Author | SHA1 | Date | |
|---|---|---|---|
| e45610661e | |||
| d85d7bffd6 | |||
| fe77d9ca72 | |||
| 9b83f92fb6 | |||
| 2248558bd3 | |||
| 2aae31ac5f | |||
| 5031bf15b9 | |||
| 9c768e0719 | |||
| b6c379265d | |||
| 4156bfc9dd |
@@ -520,8 +520,9 @@ components:
|
||||
DtoAssetPackageResponse:
|
||||
properties:
|
||||
activated_at:
|
||||
description: 激活时间
|
||||
description: 激活时间(待生效套餐为空)
|
||||
format: date-time
|
||||
nullable: true
|
||||
type: string
|
||||
created_at:
|
||||
description: 创建时间
|
||||
@@ -534,8 +535,9 @@ components:
|
||||
description: 已用真流量(MB)
|
||||
type: integer
|
||||
expires_at:
|
||||
description: 到期时间
|
||||
description: 到期时间(待生效套餐为空)
|
||||
format: date-time
|
||||
nullable: true
|
||||
type: string
|
||||
master_usage_id:
|
||||
description: 主套餐ID(加油包时有值)
|
||||
@@ -759,6 +761,105 @@ components:
|
||||
description: 虚拟号
|
||||
type: string
|
||||
type: object
|
||||
DtoAssetWalletResponse:
|
||||
properties:
|
||||
available_balance:
|
||||
description: 可用余额 = balance - frozen_balance(分)
|
||||
type: integer
|
||||
balance:
|
||||
description: 总余额(分)
|
||||
type: integer
|
||||
created_at:
|
||||
description: 创建时间(RFC3339)
|
||||
format: date-time
|
||||
type: string
|
||||
currency:
|
||||
description: 币种,目前固定 CNY
|
||||
type: string
|
||||
frozen_balance:
|
||||
description: 冻结余额(分)
|
||||
type: integer
|
||||
resource_id:
|
||||
description: 对应卡或设备的数据库ID
|
||||
minimum: 0
|
||||
type: integer
|
||||
resource_type:
|
||||
description: 资源类型:iot_card 或 device
|
||||
type: string
|
||||
status:
|
||||
description: 钱包状态:1-正常 2-冻结 3-关闭
|
||||
type: integer
|
||||
status_text:
|
||||
description: 状态文本
|
||||
type: string
|
||||
updated_at:
|
||||
description: 更新时间(RFC3339)
|
||||
format: date-time
|
||||
type: string
|
||||
wallet_id:
|
||||
description: 钱包数据库ID
|
||||
minimum: 0
|
||||
type: integer
|
||||
type: object
|
||||
DtoAssetWalletTransactionItem:
|
||||
properties:
|
||||
amount:
|
||||
description: 变动金额(分),充值为正数,扣款/退款为负数
|
||||
type: integer
|
||||
balance_after:
|
||||
description: 变动后余额(分)
|
||||
type: integer
|
||||
balance_before:
|
||||
description: 变动前余额(分)
|
||||
type: integer
|
||||
created_at:
|
||||
description: 流水创建时间(RFC3339)
|
||||
format: date-time
|
||||
type: string
|
||||
id:
|
||||
description: 流水记录ID
|
||||
minimum: 0
|
||||
type: integer
|
||||
reference_no:
|
||||
description: 关联业务编号:充值单号(CRCH…)或订单号(ORD…)(可空)
|
||||
nullable: true
|
||||
type: string
|
||||
reference_type:
|
||||
description: 关联业务类型:recharge 或 order(可空)
|
||||
nullable: true
|
||||
type: string
|
||||
remark:
|
||||
description: 备注(可空)
|
||||
nullable: true
|
||||
type: string
|
||||
transaction_type:
|
||||
description: 交易类型:recharge/deduct/refund
|
||||
type: string
|
||||
transaction_type_text:
|
||||
description: 交易类型文本:充值/扣款/退款
|
||||
type: string
|
||||
type: object
|
||||
DtoAssetWalletTransactionListResponse:
|
||||
properties:
|
||||
list:
|
||||
description: 流水列表
|
||||
items:
|
||||
$ref: '#/components/schemas/DtoAssetWalletTransactionItem'
|
||||
nullable: true
|
||||
type: array
|
||||
page:
|
||||
description: 当前页码
|
||||
type: integer
|
||||
page_size:
|
||||
description: 每页数量
|
||||
type: integer
|
||||
total:
|
||||
description: 总记录数
|
||||
type: integer
|
||||
total_pages:
|
||||
description: 总页数
|
||||
type: integer
|
||||
type: object
|
||||
DtoAssignPermissionsParams:
|
||||
properties:
|
||||
perm_ids:
|
||||
@@ -3365,6 +3466,9 @@ components:
|
||||
virtual_data_mb:
|
||||
description: 虚流量额度(MB)
|
||||
type: integer
|
||||
virtual_ratio:
|
||||
description: 虚流量比例(real_data_mb/virtual_data_mb),启用虚流量时计算,否则为1.0
|
||||
type: number
|
||||
type: object
|
||||
DtoPackageSeriesPageResult:
|
||||
properties:
|
||||
@@ -7141,6 +7245,191 @@ paths:
|
||||
summary: 刷新资产状态
|
||||
tags:
|
||||
- 资产管理
|
||||
/api/admin/assets/{asset_type}/{id}/wallet:
|
||||
get:
|
||||
description: 查询指定卡或设备的钱包余额概况。企业账号禁止调用。
|
||||
parameters:
|
||||
- description: 资产类型:card 或 device
|
||||
in: path
|
||||
name: asset_type
|
||||
required: true
|
||||
schema:
|
||||
description: 资产类型:card 或 device
|
||||
type: string
|
||||
- description: 资产ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
description: 资产ID
|
||||
minimum: 0
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
code:
|
||||
description: 响应码
|
||||
example: 0
|
||||
type: integer
|
||||
data:
|
||||
$ref: '#/components/schemas/DtoAssetWalletResponse'
|
||||
msg:
|
||||
description: 响应消息
|
||||
example: success
|
||||
type: string
|
||||
timestamp:
|
||||
description: 时间戳
|
||||
format: date-time
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- msg
|
||||
- data
|
||||
- timestamp
|
||||
type: object
|
||||
description: 成功
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 请求参数错误
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 未认证或认证已过期
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 无权访问
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 服务器内部错误
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: 资产钱包概况
|
||||
tags:
|
||||
- 资产管理
|
||||
/api/admin/assets/{asset_type}/{id}/wallet/transactions:
|
||||
get:
|
||||
description: 分页查询指定资产的钱包收支流水,含充值/扣款来源编号。企业账号禁止调用。
|
||||
parameters:
|
||||
- description: 页码,默认1
|
||||
in: query
|
||||
name: page
|
||||
schema:
|
||||
description: 页码,默认1
|
||||
type: integer
|
||||
- description: 每页数量,默认20,最大100
|
||||
in: query
|
||||
name: page_size
|
||||
schema:
|
||||
description: 每页数量,默认20,最大100
|
||||
type: integer
|
||||
- description: 交易类型过滤:recharge/deduct/refund
|
||||
in: query
|
||||
name: transaction_type
|
||||
schema:
|
||||
description: 交易类型过滤:recharge/deduct/refund
|
||||
nullable: true
|
||||
type: string
|
||||
- description: 开始时间(RFC3339)
|
||||
in: query
|
||||
name: start_time
|
||||
schema:
|
||||
description: 开始时间(RFC3339)
|
||||
format: date-time
|
||||
nullable: true
|
||||
type: string
|
||||
- description: 结束时间(RFC3339)
|
||||
in: query
|
||||
name: end_time
|
||||
schema:
|
||||
description: 结束时间(RFC3339)
|
||||
format: date-time
|
||||
nullable: true
|
||||
type: string
|
||||
- description: 资产类型:card 或 device
|
||||
in: path
|
||||
name: asset_type
|
||||
required: true
|
||||
schema:
|
||||
description: 资产类型:card 或 device
|
||||
type: string
|
||||
- description: 资产ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
description: 资产ID
|
||||
minimum: 0
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
code:
|
||||
description: 响应码
|
||||
example: 0
|
||||
type: integer
|
||||
data:
|
||||
$ref: '#/components/schemas/DtoAssetWalletTransactionListResponse'
|
||||
msg:
|
||||
description: 响应消息
|
||||
example: success
|
||||
type: string
|
||||
timestamp:
|
||||
description: 时间戳
|
||||
format: date-time
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- msg
|
||||
- data
|
||||
- timestamp
|
||||
type: object
|
||||
description: 成功
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 请求参数错误
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 未认证或认证已过期
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 无权访问
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
description: 服务器内部错误
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: 资产钱包流水列表
|
||||
tags:
|
||||
- 资产管理
|
||||
/api/admin/assets/card/{iccid}/start:
|
||||
post:
|
||||
description: 手动复机单张卡(通过ICCID)。受设备保护期约束。
|
||||
|
||||
@@ -56,5 +56,6 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
|
||||
PollingCleanup: admin.NewPollingCleanupHandler(svc.PollingCleanup),
|
||||
PollingManualTrigger: admin.NewPollingManualTriggerHandler(svc.PollingManualTrigger),
|
||||
Asset: admin.NewAssetHandler(svc.Asset, svc.Device, svc.StopResumeService),
|
||||
AssetWallet: admin.NewAssetWalletHandler(svc.AssetWallet),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
commissionWithdrawalSettingSvc "github.com/break/junhong_cmp_fiber/internal/service/commission_withdrawal_setting"
|
||||
|
||||
assetSvc "github.com/break/junhong_cmp_fiber/internal/service/asset"
|
||||
assetWalletSvc "github.com/break/junhong_cmp_fiber/internal/service/asset_wallet"
|
||||
deviceSvc "github.com/break/junhong_cmp_fiber/internal/service/device"
|
||||
deviceImportSvc "github.com/break/junhong_cmp_fiber/internal/service/device_import"
|
||||
enterpriseSvc "github.com/break/junhong_cmp_fiber/internal/service/enterprise"
|
||||
@@ -79,6 +80,7 @@ type services struct {
|
||||
PollingCleanup *pollingSvc.CleanupService
|
||||
PollingManualTrigger *pollingSvc.ManualTriggerService
|
||||
Asset *assetSvc.Service
|
||||
AssetWallet *assetWalletSvc.Service
|
||||
StopResumeService *iotCardSvc.StopResumeService
|
||||
}
|
||||
|
||||
@@ -140,8 +142,8 @@ func initServices(s *stores, deps *Dependencies) *services {
|
||||
ShopSeriesGrant: shopSeriesGrantSvc.New(deps.DB, s.ShopSeriesAllocation, s.ShopPackageAllocation, s.ShopPackageAllocationPriceHistory, s.Shop, s.Package, s.PackageSeries, deps.Logger),
|
||||
CommissionStats: commissionStatsSvc.New(s.ShopSeriesCommissionStats),
|
||||
PurchaseValidation: purchaseValidation,
|
||||
Order: orderSvc.New(deps.DB, deps.Redis, s.Order, s.OrderItem, s.AgentWallet, s.CardWallet, purchaseValidation, s.ShopPackageAllocation, s.ShopSeriesAllocation, s.IotCard, s.Device, s.PackageSeries, s.PackageUsage, s.Package, deps.WechatPayment, deps.QueueClient, deps.Logger),
|
||||
Recharge: rechargeSvc.New(deps.DB, s.CardRecharge, s.CardWallet, s.CardWalletTransaction, s.IotCard, s.Device, s.ShopSeriesAllocation, s.PackageSeries, s.CommissionRecord, deps.Logger),
|
||||
Order: orderSvc.New(deps.DB, deps.Redis, s.Order, s.OrderItem, s.AgentWallet, s.AssetWallet, purchaseValidation, s.ShopPackageAllocation, s.ShopSeriesAllocation, s.IotCard, s.Device, s.PackageSeries, s.PackageUsage, s.Package, deps.WechatPayment, deps.QueueClient, deps.Logger),
|
||||
Recharge: rechargeSvc.New(deps.DB, s.AssetRecharge, s.AssetWallet, s.AssetWalletTransaction, s.IotCard, s.Device, s.ShopSeriesAllocation, s.PackageSeries, s.CommissionRecord, deps.Logger),
|
||||
PollingConfig: pollingSvc.NewConfigService(s.PollingConfig),
|
||||
PollingConcurrency: pollingSvc.NewConcurrencyService(s.PollingConcurrencyConfig, deps.Redis),
|
||||
PollingMonitoring: pollingSvc.NewMonitoringService(deps.Redis),
|
||||
@@ -149,6 +151,7 @@ func initServices(s *stores, deps *Dependencies) *services {
|
||||
PollingCleanup: pollingSvc.NewCleanupService(s.DataCleanupConfig, s.DataCleanupLog, deps.Logger),
|
||||
PollingManualTrigger: pollingSvc.NewManualTriggerService(s.PollingManualTriggerLog, s.IotCard, deps.Redis, deps.Logger),
|
||||
Asset: assetSvc.New(deps.DB, s.Device, s.IotCard, s.PackageUsage, s.Package, s.PackageSeries, s.DeviceSimBinding, s.Shop, deps.Redis, iotCard),
|
||||
AssetWallet: assetWalletSvc.New(s.AssetWallet, s.AssetWalletTransaction),
|
||||
StopResumeService: iotCardSvc.NewStopResumeService(deps.DB, deps.Redis, s.IotCard, s.DeviceSimBinding, deps.GatewayClient, deps.Logger),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,10 +49,10 @@ type stores struct {
|
||||
AgentWallet *postgres.AgentWalletStore
|
||||
AgentWalletTransaction *postgres.AgentWalletTransactionStore
|
||||
AgentRecharge *postgres.AgentRechargeStore
|
||||
// 卡钱包系统
|
||||
CardWallet *postgres.CardWalletStore
|
||||
CardWalletTransaction *postgres.CardWalletTransactionStore
|
||||
CardRecharge *postgres.CardRechargeStore
|
||||
// 资产钱包系统
|
||||
AssetWallet *postgres.AssetWalletStore
|
||||
AssetWalletTransaction *postgres.AssetWalletTransactionStore
|
||||
AssetRecharge *postgres.AssetRechargeStore
|
||||
}
|
||||
|
||||
func initStores(deps *Dependencies) *stores {
|
||||
@@ -101,9 +101,9 @@ func initStores(deps *Dependencies) *stores {
|
||||
AgentWallet: postgres.NewAgentWalletStore(deps.DB, deps.Redis),
|
||||
AgentWalletTransaction: postgres.NewAgentWalletTransactionStore(deps.DB, deps.Redis),
|
||||
AgentRecharge: postgres.NewAgentRechargeStore(deps.DB, deps.Redis),
|
||||
// 卡钱包系统
|
||||
CardWallet: postgres.NewCardWalletStore(deps.DB, deps.Redis),
|
||||
CardWalletTransaction: postgres.NewCardWalletTransactionStore(deps.DB, deps.Redis),
|
||||
CardRecharge: postgres.NewCardRechargeStore(deps.DB, deps.Redis),
|
||||
// 资产钱包系统
|
||||
AssetWallet: postgres.NewAssetWalletStore(deps.DB, deps.Redis),
|
||||
AssetWalletTransaction: postgres.NewAssetWalletTransactionStore(deps.DB, deps.Redis),
|
||||
AssetRecharge: postgres.NewAssetRechargeStore(deps.DB, deps.Redis),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ type Handlers struct {
|
||||
PollingCleanup *admin.PollingCleanupHandler
|
||||
PollingManualTrigger *admin.PollingManualTriggerHandler
|
||||
Asset *admin.AssetHandler
|
||||
AssetWallet *admin.AssetWalletHandler
|
||||
}
|
||||
|
||||
// Middlewares 封装所有中间件
|
||||
|
||||
@@ -85,7 +85,7 @@ func initWorkerServices(stores *queue.WorkerStores, deps *WorkerDependencies) *q
|
||||
stores.Order,
|
||||
stores.OrderItem,
|
||||
stores.AgentWallet,
|
||||
stores.CardWallet,
|
||||
stores.AssetWallet,
|
||||
nil, // purchaseValidationService: 超时取消不需要
|
||||
stores.ShopPackageAllocation,
|
||||
stores.ShopSeriesAllocation,
|
||||
|
||||
@@ -28,7 +28,7 @@ type workerStores struct {
|
||||
DataCleanupLog *postgres.DataCleanupLogStore
|
||||
AgentWallet *postgres.AgentWalletStore
|
||||
AgentWalletTransaction *postgres.AgentWalletTransactionStore
|
||||
CardWallet *postgres.CardWalletStore
|
||||
AssetWallet *postgres.AssetWalletStore
|
||||
}
|
||||
|
||||
func initWorkerStores(deps *WorkerDependencies) *queue.WorkerStores {
|
||||
@@ -55,7 +55,7 @@ func initWorkerStores(deps *WorkerDependencies) *queue.WorkerStores {
|
||||
DataCleanupLog: postgres.NewDataCleanupLogStore(deps.DB),
|
||||
AgentWallet: postgres.NewAgentWalletStore(deps.DB, deps.Redis),
|
||||
AgentWalletTransaction: postgres.NewAgentWalletTransactionStore(deps.DB, deps.Redis),
|
||||
CardWallet: postgres.NewCardWalletStore(deps.DB, deps.Redis),
|
||||
AssetWallet: postgres.NewAssetWalletStore(deps.DB, deps.Redis),
|
||||
}
|
||||
|
||||
return &queue.WorkerStores{
|
||||
@@ -81,6 +81,6 @@ func initWorkerStores(deps *WorkerDependencies) *queue.WorkerStores {
|
||||
DataCleanupLog: stores.DataCleanupLog,
|
||||
AgentWallet: stores.AgentWallet,
|
||||
AgentWalletTransaction: stores.AgentWalletTransaction,
|
||||
CardWallet: stores.CardWallet,
|
||||
AssetWallet: stores.AssetWallet,
|
||||
}
|
||||
}
|
||||
|
||||
88
internal/handler/admin/asset_wallet.go
Normal file
88
internal/handler/admin/asset_wallet.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
assetWalletSvc "github.com/break/junhong_cmp_fiber/internal/service/asset_wallet"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// AssetWalletHandler 资产钱包处理器
|
||||
// 提供管理端资产(卡/设备)钱包概况和流水查询接口
|
||||
type AssetWalletHandler struct {
|
||||
service *assetWalletSvc.Service
|
||||
}
|
||||
|
||||
// NewAssetWalletHandler 创建资产钱包处理器
|
||||
func NewAssetWalletHandler(svc *assetWalletSvc.Service) *AssetWalletHandler {
|
||||
return &AssetWalletHandler{service: svc}
|
||||
}
|
||||
|
||||
// GetWallet 查询资产钱包概况
|
||||
// GET /api/admin/assets/:asset_type/:id/wallet
|
||||
func (h *AssetWalletHandler) GetWallet(c *fiber.Ctx) error {
|
||||
userType := middleware.GetUserTypeFromContext(c.UserContext())
|
||||
if userType == constants.UserTypeEnterprise {
|
||||
return errors.New(errors.CodeForbidden, "企业账号无权查看钱包信息")
|
||||
}
|
||||
|
||||
assetType := c.Params("asset_type")
|
||||
if assetType != "card" && assetType != "device" {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的资产类型")
|
||||
}
|
||||
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的资产ID")
|
||||
}
|
||||
|
||||
result, err := h.service.GetWallet(c.UserContext(), assetType, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListTransactions 查询资产钱包流水列表
|
||||
// GET /api/admin/assets/:asset_type/:id/wallet/transactions
|
||||
func (h *AssetWalletHandler) ListTransactions(c *fiber.Ctx) error {
|
||||
userType := middleware.GetUserTypeFromContext(c.UserContext())
|
||||
if userType == constants.UserTypeEnterprise {
|
||||
return errors.New(errors.CodeForbidden, "企业账号无权查看钱包信息")
|
||||
}
|
||||
|
||||
assetType := c.Params("asset_type")
|
||||
if assetType != "card" && assetType != "device" {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的资产类型")
|
||||
}
|
||||
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的资产ID")
|
||||
}
|
||||
|
||||
var req dto.AssetWalletTransactionListRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
if req.PageSize > 100 {
|
||||
return errors.New(errors.CodeInvalidParam, "每页数量不能超过100")
|
||||
}
|
||||
|
||||
result, err := h.service.ListTransactions(c.UserContext(), assetType, uint(id), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CardWallet 卡钱包模型
|
||||
// AssetWallet 资产钱包模型
|
||||
// 管理物联网卡和设备级别的钱包
|
||||
type CardWallet struct {
|
||||
type AssetWallet struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
ResourceType string `gorm:"column:resource_type;type:varchar(20);not null;index;comment:资源类型(iot_card-物联网卡 | device-设备)" json:"resource_type"`
|
||||
ResourceID uint `gorm:"column:resource_id;not null;index;comment:资源ID(关联tb_iot_card.id或tb_device.id)" json:"resource_id"`
|
||||
@@ -25,20 +25,20 @@ type CardWallet struct {
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
func (CardWallet) TableName() string {
|
||||
return "tb_card_wallet"
|
||||
func (AssetWallet) TableName() string {
|
||||
return "tb_asset_wallet"
|
||||
}
|
||||
|
||||
// GetAvailableBalance 获取可用余额 = balance - frozen_balance
|
||||
func (w *CardWallet) GetAvailableBalance() int64 {
|
||||
func (w *AssetWallet) GetAvailableBalance() int64 {
|
||||
return w.Balance - w.FrozenBalance
|
||||
}
|
||||
|
||||
// CardWalletTransaction 卡钱包交易记录模型
|
||||
// 记录所有卡钱包余额变动
|
||||
type CardWalletTransaction struct {
|
||||
// AssetWalletTransaction 资产钱包交易记录模型
|
||||
// 记录所有资产钱包余额变动
|
||||
type AssetWalletTransaction struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
CardWalletID uint `gorm:"column:card_wallet_id;not null;index;comment:卡钱包ID" json:"card_wallet_id"`
|
||||
AssetWalletID uint `gorm:"column:asset_wallet_id;not null;index;comment:资产钱包ID" json:"asset_wallet_id"`
|
||||
ResourceType string `gorm:"column:resource_type;type:varchar(20);not null;index;comment:资源类型(冗余字段,便于查询)" json:"resource_type"`
|
||||
ResourceID uint `gorm:"column:resource_id;not null;index;comment:资源ID(冗余字段,便于查询)" json:"resource_id"`
|
||||
UserID uint `gorm:"column:user_id;not null;comment:操作人用户ID" json:"user_id"`
|
||||
@@ -47,8 +47,8 @@ type CardWalletTransaction struct {
|
||||
BalanceBefore int64 `gorm:"column:balance_before;type:bigint;not null;comment:变动前余额(单位:分)" json:"balance_before"`
|
||||
BalanceAfter int64 `gorm:"column:balance_after;type:bigint;not null;comment:变动后余额(单位:分)" json:"balance_after"`
|
||||
Status int `gorm:"column:status;type:int;not null;default:1;comment:交易状态(1-成功 2-失败 3-处理中)" json:"status"`
|
||||
ReferenceType *string `gorm:"column:reference_type;type:varchar(50);comment:关联业务类型(order | topup)" json:"reference_type,omitempty"`
|
||||
ReferenceID *uint `gorm:"column:reference_id;comment:关联业务ID" json:"reference_id,omitempty"`
|
||||
ReferenceType *string `gorm:"column:reference_type;type:varchar(50);comment:关联业务类型(order | recharge)" json:"reference_type,omitempty"`
|
||||
ReferenceNo *string `gorm:"column:reference_no;type:varchar(50);comment:关联业务编号(充值单号CRCH…或订单号ORD…)" json:"reference_no,omitempty"`
|
||||
Remark *string `gorm:"column:remark;type:text;comment:备注" json:"remark,omitempty"`
|
||||
Metadata *string `gorm:"column:metadata;type:jsonb;comment:扩展信息(如套餐信息、支付方式等)" json:"metadata,omitempty"`
|
||||
Creator uint `gorm:"column:creator;not null;comment:创建人ID" json:"creator"`
|
||||
@@ -60,16 +60,16 @@ type CardWalletTransaction struct {
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
func (CardWalletTransaction) TableName() string {
|
||||
return "tb_card_wallet_transaction"
|
||||
func (AssetWalletTransaction) TableName() string {
|
||||
return "tb_asset_wallet_transaction"
|
||||
}
|
||||
|
||||
// CardRechargeRecord 卡充值记录模型
|
||||
// 记录所有卡充值操作
|
||||
type CardRechargeRecord struct {
|
||||
// AssetRechargeRecord 资产充值记录模型
|
||||
// 记录所有资产钱包充值操作
|
||||
type AssetRechargeRecord struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
UserID uint `gorm:"column:user_id;not null;index;comment:操作人用户ID" json:"user_id"`
|
||||
CardWalletID uint `gorm:"column:card_wallet_id;not null;comment:卡钱包ID" json:"card_wallet_id"`
|
||||
AssetWalletID uint `gorm:"column:asset_wallet_id;not null;comment:资产钱包ID" json:"asset_wallet_id"`
|
||||
ResourceType string `gorm:"column:resource_type;type:varchar(20);not null;index;comment:资源类型(冗余字段)" json:"resource_type"`
|
||||
ResourceID uint `gorm:"column:resource_id;not null;index;comment:资源ID(冗余字段)" json:"resource_id"`
|
||||
RechargeNo string `gorm:"column:recharge_no;type:varchar(50);not null;uniqueIndex;comment:充值订单号(格式:CRCH+时间戳+随机数)" json:"recharge_no"`
|
||||
@@ -88,6 +88,6 @@ type CardRechargeRecord struct {
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
func (CardRechargeRecord) TableName() string {
|
||||
return "tb_card_recharge_record"
|
||||
func (AssetRechargeRecord) TableName() string {
|
||||
return "tb_asset_recharge_record"
|
||||
}
|
||||
52
internal/model/dto/asset_wallet_dto.go
Normal file
52
internal/model/dto/asset_wallet_dto.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// AssetWalletResponse 资产钱包概况响应
|
||||
type AssetWalletResponse struct {
|
||||
WalletID uint `json:"wallet_id" description:"钱包数据库ID"`
|
||||
ResourceType string `json:"resource_type" description:"资源类型:iot_card 或 device"`
|
||||
ResourceID uint `json:"resource_id" description:"对应卡或设备的数据库ID"`
|
||||
Balance int64 `json:"balance" description:"总余额(分)"`
|
||||
FrozenBalance int64 `json:"frozen_balance" description:"冻结余额(分)"`
|
||||
AvailableBalance int64 `json:"available_balance" description:"可用余额 = balance - frozen_balance(分)"`
|
||||
Currency string `json:"currency" description:"币种,目前固定 CNY"`
|
||||
Status int `json:"status" description:"钱包状态:1-正常 2-冻结 3-关闭"`
|
||||
StatusText string `json:"status_text" description:"状态文本"`
|
||||
CreatedAt time.Time `json:"created_at" description:"创建时间(RFC3339)"`
|
||||
UpdatedAt time.Time `json:"updated_at" description:"更新时间(RFC3339)"`
|
||||
}
|
||||
|
||||
// AssetWalletTransactionListRequest 资产钱包流水列表请求(路径参数 + 查询参数)
|
||||
type AssetWalletTransactionListRequest struct {
|
||||
AssetType string `path:"asset_type" description:"资产类型:card 或 device" required:"true"`
|
||||
ID uint `path:"id" description:"资产ID" required:"true"`
|
||||
Page int `json:"page" query:"page" description:"页码,默认1"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" description:"每页数量,默认20,最大100"`
|
||||
TransactionType *string `json:"transaction_type" query:"transaction_type" validate:"omitempty,oneof=recharge deduct refund" description:"交易类型过滤:recharge/deduct/refund"`
|
||||
StartTime *time.Time `json:"start_time" query:"start_time" description:"开始时间(RFC3339)"`
|
||||
EndTime *time.Time `json:"end_time" query:"end_time" description:"结束时间(RFC3339)"`
|
||||
}
|
||||
|
||||
// AssetWalletTransactionItem 单条流水记录
|
||||
type AssetWalletTransactionItem struct {
|
||||
ID uint `json:"id" description:"流水记录ID"`
|
||||
TransactionType string `json:"transaction_type" description:"交易类型:recharge/deduct/refund"`
|
||||
TransactionTypeText string `json:"transaction_type_text" description:"交易类型文本:充值/扣款/退款"`
|
||||
Amount int64 `json:"amount" description:"变动金额(分),充值为正数,扣款/退款为负数"`
|
||||
BalanceBefore int64 `json:"balance_before" description:"变动前余额(分)"`
|
||||
BalanceAfter int64 `json:"balance_after" description:"变动后余额(分)"`
|
||||
ReferenceType *string `json:"reference_type,omitempty" description:"关联业务类型:recharge 或 order(可空)"`
|
||||
ReferenceNo *string `json:"reference_no,omitempty" description:"关联业务编号:充值单号(CRCH…)或订单号(ORD…)(可空)"`
|
||||
Remark *string `json:"remark,omitempty" description:"备注(可空)"`
|
||||
CreatedAt time.Time `json:"created_at" description:"流水创建时间(RFC3339)"`
|
||||
}
|
||||
|
||||
// AssetWalletTransactionListResponse 资产钱包流水列表响应
|
||||
type AssetWalletTransactionListResponse struct {
|
||||
List []*AssetWalletTransactionItem `json:"list" description:"流水列表"`
|
||||
Total int64 `json:"total" description:"总记录数"`
|
||||
Page int `json:"page" description:"当前页码"`
|
||||
PageSize int `json:"page_size" description:"每页数量"`
|
||||
TotalPages int `json:"total_pages" description:"总页数"`
|
||||
}
|
||||
@@ -108,6 +108,6 @@ func RegisterAdminRoutes(router fiber.Router, handlers *bootstrap.Handlers, midd
|
||||
registerPollingManualTriggerRoutes(authGroup, handlers.PollingManualTrigger, doc, basePath)
|
||||
}
|
||||
if handlers.Asset != nil {
|
||||
registerAssetRoutes(authGroup, handlers.Asset, doc, basePath)
|
||||
registerAssetRoutes(authGroup, handlers.Asset, handlers.AssetWallet, doc, basePath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/pkg/openapi"
|
||||
)
|
||||
|
||||
func registerAssetRoutes(router fiber.Router, handler *admin.AssetHandler, doc *openapi.Generator, basePath string) {
|
||||
func registerAssetRoutes(router fiber.Router, handler *admin.AssetHandler, walletHandler *admin.AssetWalletHandler, doc *openapi.Generator, basePath string) {
|
||||
assets := router.Group("/assets")
|
||||
groupPath := basePath + "/assets"
|
||||
|
||||
@@ -91,4 +91,22 @@ func registerAssetRoutes(router fiber.Router, handler *admin.AssetHandler, doc *
|
||||
Output: nil,
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(assets, doc, groupPath, "GET", "/:asset_type/:id/wallet", walletHandler.GetWallet, RouteSpec{
|
||||
Summary: "资产钱包概况",
|
||||
Description: "查询指定卡或设备的钱包余额概况。企业账号禁止调用。",
|
||||
Tags: []string{"资产管理"},
|
||||
Input: new(dto.AssetTypeIDRequest),
|
||||
Output: new(dto.AssetWalletResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(assets, doc, groupPath, "GET", "/:asset_type/:id/wallet/transactions", walletHandler.ListTransactions, RouteSpec{
|
||||
Summary: "资产钱包流水列表",
|
||||
Description: "分页查询指定资产的钱包收支流水,含充值/扣款来源编号。企业账号禁止调用。",
|
||||
Tags: []string{"资产管理"},
|
||||
Input: new(dto.AssetWalletTransactionListRequest),
|
||||
Output: new(dto.AssetWalletTransactionListResponse),
|
||||
Auth: true,
|
||||
})
|
||||
}
|
||||
|
||||
162
internal/service/asset_wallet/service.go
Normal file
162
internal/service/asset_wallet/service.go
Normal file
@@ -0,0 +1,162 @@
|
||||
package asset_wallet
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service 资产钱包业务服务
|
||||
// 负责管理端资产(卡/设备)钱包概况查询和流水列表查询
|
||||
type Service struct {
|
||||
assetWalletStore *postgres.AssetWalletStore
|
||||
assetWalletTransactionStore *postgres.AssetWalletTransactionStore
|
||||
}
|
||||
|
||||
// New 创建资产钱包服务实例
|
||||
func New(assetWalletStore *postgres.AssetWalletStore, assetWalletTransactionStore *postgres.AssetWalletTransactionStore) *Service {
|
||||
return &Service{
|
||||
assetWalletStore: assetWalletStore,
|
||||
assetWalletTransactionStore: assetWalletTransactionStore,
|
||||
}
|
||||
}
|
||||
|
||||
// GetWallet 查询资产钱包概况
|
||||
// assetType 为 card 或 device,映射到 resourceType = iot_card 或 device
|
||||
func (s *Service) GetWallet(ctx context.Context, assetType string, assetID uint) (*dto.AssetWalletResponse, error) {
|
||||
resourceType, err := mapAssetTypeToResourceType(assetType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wallet, err := s.assetWalletStore.GetByResourceTypeAndID(ctx, resourceType, assetID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeNotFound, "该资产暂无钱包记录")
|
||||
}
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询钱包失败")
|
||||
}
|
||||
|
||||
statusText := walletStatusText(wallet.Status)
|
||||
|
||||
return &dto.AssetWalletResponse{
|
||||
WalletID: wallet.ID,
|
||||
ResourceType: wallet.ResourceType,
|
||||
ResourceID: wallet.ResourceID,
|
||||
Balance: wallet.Balance,
|
||||
FrozenBalance: wallet.FrozenBalance,
|
||||
AvailableBalance: wallet.Balance - wallet.FrozenBalance,
|
||||
Currency: wallet.Currency,
|
||||
Status: wallet.Status,
|
||||
StatusText: statusText,
|
||||
CreatedAt: wallet.CreatedAt,
|
||||
UpdatedAt: wallet.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListTransactions 查询资产钱包流水列表(分页)
|
||||
func (s *Service) ListTransactions(ctx context.Context, assetType string, assetID uint, req *dto.AssetWalletTransactionListRequest) (*dto.AssetWalletTransactionListResponse, error) {
|
||||
resourceType, err := mapAssetTypeToResourceType(assetType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page := req.Page
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := req.PageSize
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
transactions, err := s.assetWalletTransactionStore.ListByResourceIDWithFilter(
|
||||
ctx, resourceType, assetID, req.TransactionType, req.StartTime, req.EndTime, offset, pageSize,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询流水列表失败")
|
||||
}
|
||||
|
||||
total, err := s.assetWalletTransactionStore.CountByResourceIDWithFilter(
|
||||
ctx, resourceType, assetID, req.TransactionType, req.StartTime, req.EndTime,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "统计流水数量失败")
|
||||
}
|
||||
|
||||
list := make([]*dto.AssetWalletTransactionItem, 0, len(transactions))
|
||||
for _, tx := range transactions {
|
||||
list = append(list, &dto.AssetWalletTransactionItem{
|
||||
ID: tx.ID,
|
||||
TransactionType: tx.TransactionType,
|
||||
TransactionTypeText: transactionTypeText(tx.TransactionType),
|
||||
Amount: tx.Amount,
|
||||
BalanceBefore: tx.BalanceBefore,
|
||||
BalanceAfter: tx.BalanceAfter,
|
||||
ReferenceType: tx.ReferenceType,
|
||||
ReferenceNo: tx.ReferenceNo,
|
||||
Remark: tx.Remark,
|
||||
CreatedAt: tx.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
totalPages := int(total) / pageSize
|
||||
if int(total)%pageSize > 0 {
|
||||
totalPages++
|
||||
}
|
||||
|
||||
return &dto.AssetWalletTransactionListResponse{
|
||||
List: list,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
TotalPages: totalPages,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// mapAssetTypeToResourceType 将路由参数 assetType(card/device)映射到数据库资源类型
|
||||
func mapAssetTypeToResourceType(assetType string) (string, error) {
|
||||
switch assetType {
|
||||
case "card":
|
||||
return "iot_card", nil
|
||||
case "device":
|
||||
return "device", nil
|
||||
default:
|
||||
return "", errors.New(errors.CodeInvalidParam, "无效的资产类型,仅支持 card 或 device")
|
||||
}
|
||||
}
|
||||
|
||||
// walletStatusText 翻译钱包状态文本
|
||||
func walletStatusText(status int) string {
|
||||
switch status {
|
||||
case 1:
|
||||
return "正常"
|
||||
case 2:
|
||||
return "冻结"
|
||||
case 3:
|
||||
return "关闭"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// transactionTypeText 翻译交易类型文本
|
||||
func transactionTypeText(transactionType string) string {
|
||||
switch transactionType {
|
||||
case "recharge":
|
||||
return "充值"
|
||||
case "deduct":
|
||||
return "扣款"
|
||||
case "refund":
|
||||
return "退款"
|
||||
default:
|
||||
return transactionType
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ type Service struct {
|
||||
orderStore *postgres.OrderStore
|
||||
orderItemStore *postgres.OrderItemStore
|
||||
agentWalletStore *postgres.AgentWalletStore
|
||||
cardWalletStore *postgres.CardWalletStore
|
||||
assetWalletStore *postgres.AssetWalletStore
|
||||
purchaseValidationService *purchase_validation.Service
|
||||
shopPackageAllocationStore *postgres.ShopPackageAllocationStore
|
||||
shopSeriesAllocationStore *postgres.ShopSeriesAllocationStore
|
||||
@@ -51,7 +51,7 @@ func New(
|
||||
orderStore *postgres.OrderStore,
|
||||
orderItemStore *postgres.OrderItemStore,
|
||||
agentWalletStore *postgres.AgentWalletStore,
|
||||
cardWalletStore *postgres.CardWalletStore,
|
||||
assetWalletStore *postgres.AssetWalletStore,
|
||||
purchaseValidationService *purchase_validation.Service,
|
||||
shopPackageAllocationStore *postgres.ShopPackageAllocationStore,
|
||||
shopSeriesAllocationStore *postgres.ShopSeriesAllocationStore,
|
||||
@@ -70,7 +70,7 @@ func New(
|
||||
orderStore: orderStore,
|
||||
orderItemStore: orderItemStore,
|
||||
agentWalletStore: agentWalletStore,
|
||||
cardWalletStore: cardWalletStore,
|
||||
assetWalletStore: assetWalletStore,
|
||||
purchaseValidationService: purchaseValidationService,
|
||||
shopPackageAllocationStore: shopPackageAllocationStore,
|
||||
shopSeriesAllocationStore: shopSeriesAllocationStore,
|
||||
@@ -326,18 +326,35 @@ func (s *Service) CreateAdminOrder(ctx context.Context, req *dto.CreateAdminOrde
|
||||
var validationResult *purchase_validation.PurchaseValidationResult
|
||||
var err error
|
||||
|
||||
if req.OrderType == model.OrderTypeSingleCard {
|
||||
if req.IotCardID == nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "单卡购买必须指定IoT卡ID")
|
||||
if req.PaymentMethod == model.PaymentMethodOffline {
|
||||
// offline 订单:绕过代理 Allocation 上架检查,仅验证套餐全局状态
|
||||
if req.OrderType == model.OrderTypeSingleCard {
|
||||
if req.IotCardID == nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "单卡购买必须指定IoT卡ID")
|
||||
}
|
||||
validationResult, err = s.purchaseValidationService.ValidateAdminOfflineCardPurchase(ctx, *req.IotCardID, req.PackageIDs)
|
||||
} else if req.OrderType == model.OrderTypeDevice {
|
||||
if req.DeviceID == nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "设备购买必须指定设备ID")
|
||||
}
|
||||
validationResult, err = s.purchaseValidationService.ValidateAdminOfflineDevicePurchase(ctx, *req.DeviceID, req.PackageIDs)
|
||||
} else {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "无效的订单类型")
|
||||
}
|
||||
validationResult, err = s.purchaseValidationService.ValidateCardPurchase(ctx, *req.IotCardID, req.PackageIDs)
|
||||
} else if req.OrderType == model.OrderTypeDevice {
|
||||
if req.DeviceID == nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "设备购买必须指定设备ID")
|
||||
}
|
||||
validationResult, err = s.purchaseValidationService.ValidateDevicePurchase(ctx, *req.DeviceID, req.PackageIDs)
|
||||
} else {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "无效的订单类型")
|
||||
if req.OrderType == model.OrderTypeSingleCard {
|
||||
if req.IotCardID == nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "单卡购买必须指定IoT卡ID")
|
||||
}
|
||||
validationResult, err = s.purchaseValidationService.ValidateCardPurchase(ctx, *req.IotCardID, req.PackageIDs)
|
||||
} else if req.OrderType == model.OrderTypeDevice {
|
||||
if req.DeviceID == nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "设备购买必须指定设备ID")
|
||||
}
|
||||
validationResult, err = s.purchaseValidationService.ValidateDevicePurchase(ctx, *req.DeviceID, req.PackageIDs)
|
||||
} else {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "无效的订单类型")
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -362,9 +379,12 @@ func (s *Service) CreateAdminOrder(ctx context.Context, req *dto.CreateAdminOrde
|
||||
lockKey := constants.RedisOrderCreateLockKey(carrierType, carrierID)
|
||||
defer s.redis.Del(ctx, lockKey)
|
||||
|
||||
forceRechargeCheck := s.checkForceRechargeRequirement(ctx, validationResult)
|
||||
if forceRechargeCheck.NeedForceRecharge && validationResult.TotalPrice < forceRechargeCheck.ForceRechargeAmount {
|
||||
return nil, errors.New(errors.CodeForceRechargeRequired, "首次购买需满足最低充值要求")
|
||||
// offline 订单不检查强充:平台直接操作,不涉及消费者支付门槛,不产生一次性佣金触发条件
|
||||
if req.PaymentMethod != model.PaymentMethodOffline {
|
||||
forceRechargeCheck := s.checkForceRechargeRequirement(ctx, validationResult)
|
||||
if forceRechargeCheck.NeedForceRecharge && validationResult.TotalPrice < forceRechargeCheck.ForceRechargeAmount {
|
||||
return nil, errors.New(errors.CodeForceRechargeRequired, "首次购买需满足最低充值要求")
|
||||
}
|
||||
}
|
||||
|
||||
userID := middleware.GetUserIDFromContext(ctx)
|
||||
@@ -1271,12 +1291,12 @@ func (s *Service) unfreezeWalletForCancel(ctx context.Context, tx *gorm.DB, orde
|
||||
} else {
|
||||
return errors.New(errors.CodeInternalError, "无法确定钱包归属")
|
||||
}
|
||||
wallet, err := s.cardWalletStore.GetByResourceTypeAndID(ctx, resourceType, resourceID)
|
||||
wallet, err := s.assetWalletStore.GetByResourceTypeAndID(ctx, resourceType, resourceID)
|
||||
if err != nil {
|
||||
return errors.Wrap(errors.CodeWalletNotFound, err, "查询卡钱包失败")
|
||||
return errors.Wrap(errors.CodeWalletNotFound, err, "查询资产钱包失败")
|
||||
}
|
||||
// 卡钱包解冻:直接减少冻结余额
|
||||
result := tx.Model(&model.CardWallet{}).
|
||||
// 资产钱包解冻:直接减少冻结余额
|
||||
result := tx.Model(&model.AssetWallet{}).
|
||||
Where("id = ? AND frozen_balance >= ?", wallet.ID, order.TotalAmount).
|
||||
Updates(map[string]any{
|
||||
"frozen_balance": gorm.Expr("frozen_balance - ?", order.TotalAmount),
|
||||
@@ -1393,8 +1413,8 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
|
||||
return s.activatePackage(ctx, tx, order)
|
||||
})
|
||||
} else {
|
||||
// 卡钱包系统(iot_card 或 device)
|
||||
wallet, err := s.cardWalletStore.GetByResourceTypeAndID(ctx, resourceType, resourceID)
|
||||
// 资产钱包系统(iot_card 或 device)
|
||||
wallet, err := s.assetWalletStore.GetByResourceTypeAndID(ctx, resourceType, resourceID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return errors.New(errors.CodeWalletNotFound, "钱包不存在")
|
||||
@@ -1437,7 +1457,10 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
|
||||
}
|
||||
}
|
||||
|
||||
walletResult := tx.Model(&model.CardWallet{}).
|
||||
// 扣款前记录余额快照,用于写入流水
|
||||
balanceBefore := wallet.Balance
|
||||
|
||||
walletResult := tx.Model(&model.AssetWallet{}).
|
||||
Where("id = ? AND balance >= ? AND version = ?", wallet.ID, order.TotalAmount, wallet.Version).
|
||||
Updates(map[string]any{
|
||||
"balance": gorm.Expr("balance - ?", order.TotalAmount),
|
||||
@@ -1450,6 +1473,27 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
|
||||
return errors.New(errors.CodeInsufficientBalance, "余额不足或并发冲突")
|
||||
}
|
||||
|
||||
// 扣款成功后补写扣款流水,填补流水表中扣款记录缺失的问题
|
||||
deductTx := &model.AssetWalletTransaction{
|
||||
AssetWalletID: wallet.ID,
|
||||
ResourceType: resourceType,
|
||||
ResourceID: resourceID,
|
||||
UserID: buyerID,
|
||||
TransactionType: "deduct",
|
||||
Amount: -order.TotalAmount,
|
||||
BalanceBefore: balanceBefore,
|
||||
BalanceAfter: balanceBefore - order.TotalAmount,
|
||||
Status: 1,
|
||||
ReferenceType: strPtr("order"),
|
||||
ReferenceNo: &order.OrderNo,
|
||||
Remark: strPtr("钱包支付套餐"),
|
||||
ShopIDTag: wallet.ShopIDTag,
|
||||
EnterpriseIDTag: wallet.EnterpriseIDTag,
|
||||
}
|
||||
if err := tx.Create(deductTx).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "创建扣款流水失败")
|
||||
}
|
||||
|
||||
return s.activatePackage(ctx, tx, order)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,3 +173,56 @@ func (s *Service) GetPurchasePrice(ctx context.Context, pkg *model.Package, buye
|
||||
return pkg.SuggestedRetailPrice
|
||||
}
|
||||
|
||||
// ValidateAdminOfflineCardPurchase 后台 offline 订单专用卡验证
|
||||
// 绕过代理 Allocation 上架检查,仅验证套餐全局状态
|
||||
func (s *Service) ValidateAdminOfflineCardPurchase(ctx context.Context, cardID uint, packageIDs []uint) (*PurchaseValidationResult, error) {
|
||||
card, err := s.iotCardStore.GetByID(ctx, cardID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeIotCardNotFound, "IoT卡不存在")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if card.SeriesID == nil || *card.SeriesID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "该卡未关联套餐系列,无法购买套餐")
|
||||
}
|
||||
|
||||
packages, totalPrice, err := s.validatePackages(ctx, packageIDs, *card.SeriesID, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &PurchaseValidationResult{
|
||||
Card: card,
|
||||
Packages: packages,
|
||||
TotalPrice: totalPrice,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateAdminOfflineDevicePurchase 后台 offline 订单专用设备验证
|
||||
// 绕过代理 Allocation 上架检查,仅验证套餐全局状态
|
||||
func (s *Service) ValidateAdminOfflineDevicePurchase(ctx context.Context, deviceID uint, packageIDs []uint) (*PurchaseValidationResult, error) {
|
||||
device, err := s.deviceStore.GetByID(ctx, deviceID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeNotFound, "设备不存在")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if device.SeriesID == nil || *device.SeriesID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "该设备未关联套餐系列,无法购买套餐")
|
||||
}
|
||||
|
||||
packages, totalPrice, err := s.validatePackages(ctx, packageIDs, *device.SeriesID, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &PurchaseValidationResult{
|
||||
Device: device,
|
||||
Packages: packages,
|
||||
TotalPrice: totalPrice,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -29,26 +29,26 @@ type ForceRechargeRequirement struct {
|
||||
}
|
||||
|
||||
// Service 充值服务
|
||||
// 负责卡钱包(IoT卡/设备)的充值订单创建、预检、支付回调处理等业务逻辑
|
||||
// 负责资产钱包(IoT卡/设备)的充值订单创建、预检、支付回调处理等业务逻辑
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
cardRechargeStore *postgres.CardRechargeStore
|
||||
cardWalletStore *postgres.CardWalletStore
|
||||
cardWalletTransactionStore *postgres.CardWalletTransactionStore
|
||||
iotCardStore *postgres.IotCardStore
|
||||
deviceStore *postgres.DeviceStore
|
||||
shopSeriesAllocationStore *postgres.ShopSeriesAllocationStore
|
||||
packageSeriesStore *postgres.PackageSeriesStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
logger *zap.Logger
|
||||
db *gorm.DB
|
||||
assetRechargeStore *postgres.AssetRechargeStore
|
||||
assetWalletStore *postgres.AssetWalletStore
|
||||
assetWalletTransactionStore *postgres.AssetWalletTransactionStore
|
||||
iotCardStore *postgres.IotCardStore
|
||||
deviceStore *postgres.DeviceStore
|
||||
shopSeriesAllocationStore *postgres.ShopSeriesAllocationStore
|
||||
packageSeriesStore *postgres.PackageSeriesStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// New 创建充值服务实例
|
||||
func New(
|
||||
db *gorm.DB,
|
||||
cardRechargeStore *postgres.CardRechargeStore,
|
||||
cardWalletStore *postgres.CardWalletStore,
|
||||
cardWalletTransactionStore *postgres.CardWalletTransactionStore,
|
||||
assetRechargeStore *postgres.AssetRechargeStore,
|
||||
assetWalletStore *postgres.AssetWalletStore,
|
||||
assetWalletTransactionStore *postgres.AssetWalletTransactionStore,
|
||||
iotCardStore *postgres.IotCardStore,
|
||||
deviceStore *postgres.DeviceStore,
|
||||
shopSeriesAllocationStore *postgres.ShopSeriesAllocationStore,
|
||||
@@ -57,16 +57,16 @@ func New(
|
||||
logger *zap.Logger,
|
||||
) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
cardRechargeStore: cardRechargeStore,
|
||||
cardWalletStore: cardWalletStore,
|
||||
cardWalletTransactionStore: cardWalletTransactionStore,
|
||||
iotCardStore: iotCardStore,
|
||||
deviceStore: deviceStore,
|
||||
shopSeriesAllocationStore: shopSeriesAllocationStore,
|
||||
packageSeriesStore: packageSeriesStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
logger: logger,
|
||||
db: db,
|
||||
assetRechargeStore: assetRechargeStore,
|
||||
assetWalletStore: assetWalletStore,
|
||||
assetWalletTransactionStore: assetWalletTransactionStore,
|
||||
iotCardStore: iotCardStore,
|
||||
deviceStore: deviceStore,
|
||||
shopSeriesAllocationStore: shopSeriesAllocationStore,
|
||||
packageSeriesStore: packageSeriesStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,13 +82,13 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateRechargeRequest, us
|
||||
}
|
||||
|
||||
// 2. 获取资源(卡或设备)钱包
|
||||
var wallet *model.CardWallet
|
||||
var wallet *model.AssetWallet
|
||||
var err error
|
||||
|
||||
if req.ResourceType == "iot_card" {
|
||||
wallet, err = s.cardWalletStore.GetByResourceTypeAndID(ctx, "iot_card", req.ResourceID)
|
||||
wallet, err = s.assetWalletStore.GetByResourceTypeAndID(ctx, "iot_card", req.ResourceID)
|
||||
} else if req.ResourceType == "device" {
|
||||
wallet, err = s.cardWalletStore.GetByResourceTypeAndID(ctx, "device", req.ResourceID)
|
||||
wallet, err = s.assetWalletStore.GetByResourceTypeAndID(ctx, "device", req.ResourceID)
|
||||
} else {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "无效的资源类型")
|
||||
}
|
||||
@@ -115,9 +115,9 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateRechargeRequest, us
|
||||
rechargeNo := s.generateRechargeNo()
|
||||
|
||||
// 5. 创建充值订单
|
||||
recharge := &model.CardRechargeRecord{
|
||||
recharge := &model.AssetRechargeRecord{
|
||||
UserID: userID,
|
||||
CardWalletID: wallet.ID,
|
||||
AssetWalletID: wallet.ID,
|
||||
ResourceType: req.ResourceType,
|
||||
ResourceID: req.ResourceID,
|
||||
RechargeNo: rechargeNo,
|
||||
@@ -128,7 +128,7 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateRechargeRequest, us
|
||||
EnterpriseIDTag: wallet.EnterpriseIDTag,
|
||||
}
|
||||
|
||||
if err := s.cardRechargeStore.Create(ctx, recharge); err != nil {
|
||||
if err := s.assetRechargeStore.Create(ctx, recharge); err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "创建充值订单失败")
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ func (s *Service) GetRechargeCheck(ctx context.Context, resourceType string, res
|
||||
// GetByID 根据ID查询充值订单详情
|
||||
// 支持数据权限过滤
|
||||
func (s *Service) GetByID(ctx context.Context, id uint, userID uint) (*dto.RechargeResponse, error) {
|
||||
recharge, err := s.cardRechargeStore.GetByID(ctx, id)
|
||||
recharge, err := s.assetRechargeStore.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, errors.New(errors.CodeRechargeNotFound, "充值订单不存在")
|
||||
@@ -201,10 +201,10 @@ func (s *Service) List(ctx context.Context, req *dto.RechargeListRequest, userID
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
|
||||
params := &postgres.ListCardRechargeParams{
|
||||
params := &postgres.ListAssetRechargeParams{
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
UserID: &userID, // 数据权限:只能查看自己的
|
||||
UserID: &userID,
|
||||
}
|
||||
|
||||
if req.Status != nil {
|
||||
@@ -212,7 +212,7 @@ func (s *Service) List(ctx context.Context, req *dto.RechargeListRequest, userID
|
||||
}
|
||||
if req.WalletID != nil {
|
||||
walletID := *req.WalletID
|
||||
params.CardWalletID = &walletID
|
||||
params.AssetWalletID = &walletID
|
||||
}
|
||||
if req.StartTime != nil {
|
||||
params.StartTime = req.StartTime
|
||||
@@ -221,7 +221,7 @@ func (s *Service) List(ctx context.Context, req *dto.RechargeListRequest, userID
|
||||
params.EndTime = req.EndTime
|
||||
}
|
||||
|
||||
recharges, total, err := s.cardRechargeStore.List(ctx, params)
|
||||
recharges, total, err := s.assetRechargeStore.List(ctx, params)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询充值订单列表失败")
|
||||
}
|
||||
@@ -249,7 +249,7 @@ func (s *Service) List(ctx context.Context, req *dto.RechargeListRequest, userID
|
||||
// 支持幂等性检查、事务处理、更新余额、触发佣金
|
||||
func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string, paymentMethod string, paymentTransactionID string) error {
|
||||
// 1. 查询充值订单
|
||||
recharge, err := s.cardRechargeStore.GetByRechargeNo(ctx, rechargeNo)
|
||||
recharge, err := s.assetRechargeStore.GetByRechargeNo(ctx, rechargeNo)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return errors.New(errors.CodeRechargeNotFound, "充值订单不存在")
|
||||
@@ -272,7 +272,7 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
}
|
||||
|
||||
// 4. 获取钱包信息
|
||||
wallet, err := s.cardWalletStore.GetByID(ctx, recharge.CardWalletID)
|
||||
wallet, err := s.assetWalletStore.GetByID(ctx, recharge.AssetWalletID)
|
||||
if err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询钱包失败")
|
||||
}
|
||||
@@ -286,7 +286,7 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 6.1 更新充值订单状态(带状态检查,实现乐观锁)
|
||||
oldStatus := constants.RechargeStatusPending
|
||||
if err := s.cardRechargeStore.UpdateStatusWithOptimisticLock(ctx, recharge.ID, &oldStatus, constants.RechargeStatusPaid, &now, nil); err != nil {
|
||||
if err := s.assetRechargeStore.UpdateStatusWithOptimisticLock(ctx, recharge.ID, &oldStatus, constants.RechargeStatusPaid, &now, nil); err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
// 状态已变更,幂等处理
|
||||
return nil
|
||||
@@ -295,13 +295,13 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
}
|
||||
|
||||
// 6.2 更新支付信息
|
||||
if err := s.cardRechargeStore.UpdatePaymentInfo(ctx, recharge.ID, &paymentMethod, &paymentTransactionID); err != nil {
|
||||
if err := s.assetRechargeStore.UpdatePaymentInfo(ctx, recharge.ID, &paymentMethod, &paymentTransactionID); err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新支付信息失败")
|
||||
}
|
||||
|
||||
// 6.3 增加钱包余额(使用乐观锁)
|
||||
balanceBefore := wallet.Balance
|
||||
result := tx.Model(&model.CardWallet{}).
|
||||
result := tx.Model(&model.AssetWallet{}).
|
||||
Where("id = ? AND version = ?", wallet.ID, wallet.Version).
|
||||
Updates(map[string]any{
|
||||
"balance": gorm.Expr("balance + ?", recharge.Amount),
|
||||
@@ -314,11 +314,11 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
return errors.New(errors.CodeInternalError, "钱包版本冲突,请重试")
|
||||
}
|
||||
|
||||
// 6.4 创建钱包交易记录
|
||||
// 6.4 创建钱包交易记录(reference_no 存储充值单号,便于前端跳转)
|
||||
remark := "钱包充值"
|
||||
refType := "recharge"
|
||||
transaction := &model.CardWalletTransaction{
|
||||
CardWalletID: wallet.ID,
|
||||
transaction := &model.AssetWalletTransaction{
|
||||
AssetWalletID: wallet.ID,
|
||||
ResourceType: resourceType,
|
||||
ResourceID: resourceID,
|
||||
UserID: recharge.UserID,
|
||||
@@ -328,7 +328,7 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
BalanceAfter: balanceBefore + recharge.Amount,
|
||||
Status: 1,
|
||||
ReferenceType: &refType,
|
||||
ReferenceID: &recharge.ID,
|
||||
ReferenceNo: &recharge.RechargeNo,
|
||||
Remark: &remark,
|
||||
ShopIDTag: wallet.ShopIDTag,
|
||||
EnterpriseIDTag: wallet.EnterpriseIDTag,
|
||||
@@ -348,7 +348,7 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
}
|
||||
|
||||
// 6.7 更新充值订单状态为已完成
|
||||
if err := tx.Model(&model.CardRechargeRecord{}).
|
||||
if err := tx.Model(&model.AssetRechargeRecord{}).
|
||||
Where("id = ?", recharge.ID).
|
||||
Update("status", constants.RechargeStatusCompleted).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新充值订单完成状态失败")
|
||||
@@ -729,7 +729,7 @@ func (s *Service) generateRechargeNo() string {
|
||||
}
|
||||
|
||||
// buildRechargeResponse 构建充值订单响应
|
||||
func (s *Service) buildRechargeResponse(recharge *model.CardRechargeRecord) *dto.RechargeResponse {
|
||||
func (s *Service) buildRechargeResponse(recharge *model.AssetRechargeRecord) *dto.RechargeResponse {
|
||||
statusText := ""
|
||||
switch recharge.Status {
|
||||
case constants.RechargeStatusPending:
|
||||
@@ -748,7 +748,7 @@ func (s *Service) buildRechargeResponse(recharge *model.CardRechargeRecord) *dto
|
||||
ID: recharge.ID,
|
||||
RechargeNo: recharge.RechargeNo,
|
||||
UserID: recharge.UserID,
|
||||
WalletID: recharge.CardWalletID,
|
||||
WalletID: recharge.AssetWalletID,
|
||||
Amount: recharge.Amount,
|
||||
PaymentMethod: recharge.PaymentMethod,
|
||||
PaymentChannel: recharge.PaymentChannel,
|
||||
|
||||
@@ -8,33 +8,33 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CardRechargeStore 卡充值记录数据访问层
|
||||
type CardRechargeStore struct {
|
||||
// AssetRechargeStore 资产充值记录数据访问层
|
||||
type AssetRechargeStore struct {
|
||||
db *gorm.DB
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
// NewCardRechargeStore 创建卡充值记录 Store
|
||||
func NewCardRechargeStore(db *gorm.DB, redis *redis.Client) *CardRechargeStore {
|
||||
return &CardRechargeStore{
|
||||
// NewAssetRechargeStore 创建资产充值记录 Store
|
||||
func NewAssetRechargeStore(db *gorm.DB, redis *redis.Client) *AssetRechargeStore {
|
||||
return &AssetRechargeStore{
|
||||
db: db,
|
||||
redis: redis,
|
||||
}
|
||||
}
|
||||
|
||||
// Create 创建充值记录
|
||||
func (s *CardRechargeStore) Create(ctx context.Context, record *model.CardRechargeRecord) error {
|
||||
func (s *AssetRechargeStore) Create(ctx context.Context, record *model.AssetRechargeRecord) error {
|
||||
return s.db.WithContext(ctx).Create(record).Error
|
||||
}
|
||||
|
||||
// CreateWithTx 创建充值记录(带事务)
|
||||
func (s *CardRechargeStore) CreateWithTx(ctx context.Context, tx *gorm.DB, record *model.CardRechargeRecord) error {
|
||||
func (s *AssetRechargeStore) CreateWithTx(ctx context.Context, tx *gorm.DB, record *model.AssetRechargeRecord) error {
|
||||
return tx.WithContext(ctx).Create(record).Error
|
||||
}
|
||||
|
||||
// GetByRechargeNo 根据充值订单号查询
|
||||
func (s *CardRechargeStore) GetByRechargeNo(ctx context.Context, rechargeNo string) (*model.CardRechargeRecord, error) {
|
||||
var record model.CardRechargeRecord
|
||||
func (s *AssetRechargeStore) GetByRechargeNo(ctx context.Context, rechargeNo string) (*model.AssetRechargeRecord, error) {
|
||||
var record model.AssetRechargeRecord
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("recharge_no = ?", rechargeNo).
|
||||
First(&record).Error
|
||||
@@ -45,8 +45,8 @@ func (s *CardRechargeStore) GetByRechargeNo(ctx context.Context, rechargeNo stri
|
||||
}
|
||||
|
||||
// GetByID 根据 ID 查询
|
||||
func (s *CardRechargeStore) GetByID(ctx context.Context, id uint) (*model.CardRechargeRecord, error) {
|
||||
var record model.CardRechargeRecord
|
||||
func (s *AssetRechargeStore) GetByID(ctx context.Context, id uint) (*model.AssetRechargeRecord, error) {
|
||||
var record model.AssetRechargeRecord
|
||||
if err := s.db.WithContext(ctx).First(&record, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -54,34 +54,34 @@ func (s *CardRechargeStore) GetByID(ctx context.Context, id uint) (*model.CardRe
|
||||
}
|
||||
|
||||
// UpdateStatus 更新充值状态
|
||||
func (s *CardRechargeStore) UpdateStatus(ctx context.Context, id uint, status int) error {
|
||||
func (s *AssetRechargeStore) UpdateStatus(ctx context.Context, id uint, status int) error {
|
||||
return s.db.WithContext(ctx).
|
||||
Model(&model.CardRechargeRecord{}).
|
||||
Model(&model.AssetRechargeRecord{}).
|
||||
Where("id = ?", id).
|
||||
Update("status", status).Error
|
||||
}
|
||||
|
||||
// UpdateStatusWithTx 更新充值状态(带事务)
|
||||
func (s *CardRechargeStore) UpdateStatusWithTx(ctx context.Context, tx *gorm.DB, id uint, status int) error {
|
||||
func (s *AssetRechargeStore) UpdateStatusWithTx(ctx context.Context, tx *gorm.DB, id uint, status int) error {
|
||||
return tx.WithContext(ctx).
|
||||
Model(&model.CardRechargeRecord{}).
|
||||
Model(&model.AssetRechargeRecord{}).
|
||||
Where("id = ?", id).
|
||||
Update("status", status).Error
|
||||
}
|
||||
|
||||
// Update 更新充值记录
|
||||
func (s *CardRechargeStore) Update(ctx context.Context, record *model.CardRechargeRecord) error {
|
||||
func (s *AssetRechargeStore) Update(ctx context.Context, record *model.AssetRechargeRecord) error {
|
||||
return s.db.WithContext(ctx).Save(record).Error
|
||||
}
|
||||
|
||||
// UpdateWithTx 更新充值记录(带事务)
|
||||
func (s *CardRechargeStore) UpdateWithTx(ctx context.Context, tx *gorm.DB, record *model.CardRechargeRecord) error {
|
||||
func (s *AssetRechargeStore) UpdateWithTx(ctx context.Context, tx *gorm.DB, record *model.AssetRechargeRecord) error {
|
||||
return tx.WithContext(ctx).Save(record).Error
|
||||
}
|
||||
|
||||
// ListByResourceID 按资源查询充值记录(支持分页)
|
||||
func (s *CardRechargeStore) ListByResourceID(ctx context.Context, resourceType string, resourceID uint, offset, limit int) ([]*model.CardRechargeRecord, error) {
|
||||
var records []*model.CardRechargeRecord
|
||||
func (s *AssetRechargeStore) ListByResourceID(ctx context.Context, resourceType string, resourceID uint, offset, limit int) ([]*model.AssetRechargeRecord, error) {
|
||||
var records []*model.AssetRechargeRecord
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID).
|
||||
Order("created_at DESC").
|
||||
@@ -95,8 +95,8 @@ func (s *CardRechargeStore) ListByResourceID(ctx context.Context, resourceType s
|
||||
}
|
||||
|
||||
// ListByUserID 按用户查询充值记录(支持分页)
|
||||
func (s *CardRechargeStore) ListByUserID(ctx context.Context, userID uint, offset, limit int) ([]*model.CardRechargeRecord, error) {
|
||||
var records []*model.CardRechargeRecord
|
||||
func (s *AssetRechargeStore) ListByUserID(ctx context.Context, userID uint, offset, limit int) ([]*model.AssetRechargeRecord, error) {
|
||||
var records []*model.AssetRechargeRecord
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("user_id = ?", userID).
|
||||
Order("created_at DESC").
|
||||
@@ -110,8 +110,8 @@ func (s *CardRechargeStore) ListByUserID(ctx context.Context, userID uint, offse
|
||||
}
|
||||
|
||||
// ListByStatus 按状态查询充值记录(支持分页)
|
||||
func (s *CardRechargeStore) ListByStatus(ctx context.Context, status int, offset, limit int) ([]*model.CardRechargeRecord, error) {
|
||||
var records []*model.CardRechargeRecord
|
||||
func (s *AssetRechargeStore) ListByStatus(ctx context.Context, status int, offset, limit int) ([]*model.AssetRechargeRecord, error) {
|
||||
var records []*model.AssetRechargeRecord
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("status = ?", status).
|
||||
Order("created_at DESC").
|
||||
@@ -124,31 +124,31 @@ func (s *CardRechargeStore) ListByStatus(ctx context.Context, status int, offset
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// ListRechargeParams 充值记录列表查询参数
|
||||
type ListCardRechargeParams struct {
|
||||
Page int
|
||||
PageSize int
|
||||
UserID *uint
|
||||
CardWalletID *uint
|
||||
ResourceType *string
|
||||
ResourceID *uint
|
||||
Status *int
|
||||
StartTime interface{}
|
||||
EndTime interface{}
|
||||
// ListAssetRechargeParams 充值记录列表查询参数
|
||||
type ListAssetRechargeParams struct {
|
||||
Page int
|
||||
PageSize int
|
||||
UserID *uint
|
||||
AssetWalletID *uint
|
||||
ResourceType *string
|
||||
ResourceID *uint
|
||||
Status *int
|
||||
StartTime interface{}
|
||||
EndTime interface{}
|
||||
}
|
||||
|
||||
// List 查询充值记录列表(支持分页和筛选)
|
||||
func (s *CardRechargeStore) List(ctx context.Context, params *ListCardRechargeParams) ([]*model.CardRechargeRecord, int64, error) {
|
||||
var records []*model.CardRechargeRecord
|
||||
func (s *AssetRechargeStore) List(ctx context.Context, params *ListAssetRechargeParams) ([]*model.AssetRechargeRecord, int64, error) {
|
||||
var records []*model.AssetRechargeRecord
|
||||
var total int64
|
||||
|
||||
query := s.db.WithContext(ctx).Model(&model.CardRechargeRecord{})
|
||||
query := s.db.WithContext(ctx).Model(&model.AssetRechargeRecord{})
|
||||
|
||||
if params.UserID != nil {
|
||||
query = query.Where("user_id = ?", *params.UserID)
|
||||
}
|
||||
if params.CardWalletID != nil {
|
||||
query = query.Where("card_wallet_id = ?", *params.CardWalletID)
|
||||
if params.AssetWalletID != nil {
|
||||
query = query.Where("asset_wallet_id = ?", *params.AssetWalletID)
|
||||
}
|
||||
if params.ResourceType != nil {
|
||||
query = query.Where("resource_type = ?", *params.ResourceType)
|
||||
@@ -188,7 +188,7 @@ func (s *CardRechargeStore) List(ctx context.Context, params *ListCardRechargePa
|
||||
}
|
||||
|
||||
// UpdatePaymentInfo 更新支付信息
|
||||
func (s *CardRechargeStore) UpdatePaymentInfo(ctx context.Context, id uint, paymentMethod *string, paymentTransactionID *string) error {
|
||||
func (s *AssetRechargeStore) UpdatePaymentInfo(ctx context.Context, id uint, paymentMethod *string, paymentTransactionID *string) error {
|
||||
updates := map[string]interface{}{}
|
||||
if paymentMethod != nil {
|
||||
updates["payment_method"] = paymentMethod
|
||||
@@ -201,7 +201,7 @@ func (s *CardRechargeStore) UpdatePaymentInfo(ctx context.Context, id uint, paym
|
||||
return nil
|
||||
}
|
||||
|
||||
result := s.db.WithContext(ctx).Model(&model.CardRechargeRecord{}).Where("id = ?", id).Updates(updates)
|
||||
result := s.db.WithContext(ctx).Model(&model.AssetRechargeRecord{}).Where("id = ?", id).Updates(updates)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -212,7 +212,7 @@ func (s *CardRechargeStore) UpdatePaymentInfo(ctx context.Context, id uint, paym
|
||||
}
|
||||
|
||||
// UpdateStatusWithOptimisticLock 更新充值状态(支持乐观锁)
|
||||
func (s *CardRechargeStore) UpdateStatusWithOptimisticLock(ctx context.Context, id uint, oldStatus *int, newStatus int, paidAt interface{}, completedAt interface{}) error {
|
||||
func (s *AssetRechargeStore) UpdateStatusWithOptimisticLock(ctx context.Context, id uint, oldStatus *int, newStatus int, paidAt interface{}, completedAt interface{}) error {
|
||||
updates := map[string]interface{}{
|
||||
"status": newStatus,
|
||||
}
|
||||
@@ -223,7 +223,7 @@ func (s *CardRechargeStore) UpdateStatusWithOptimisticLock(ctx context.Context,
|
||||
updates["completed_at"] = completedAt
|
||||
}
|
||||
|
||||
query := s.db.WithContext(ctx).Model(&model.CardRechargeRecord{}).Where("id = ?", id)
|
||||
query := s.db.WithContext(ctx).Model(&model.AssetRechargeRecord{}).Where("id = ?", id)
|
||||
|
||||
if oldStatus != nil {
|
||||
query = query.Where("status = ?", *oldStatus)
|
||||
@@ -11,23 +11,23 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CardWalletStore 卡钱包数据访问层
|
||||
type CardWalletStore struct {
|
||||
// AssetWalletStore 资产钱包数据访问层
|
||||
type AssetWalletStore struct {
|
||||
db *gorm.DB
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
// NewCardWalletStore 创建卡钱包 Store
|
||||
func NewCardWalletStore(db *gorm.DB, redis *redis.Client) *CardWalletStore {
|
||||
return &CardWalletStore{
|
||||
// NewAssetWalletStore 创建资产钱包 Store
|
||||
func NewAssetWalletStore(db *gorm.DB, redis *redis.Client) *AssetWalletStore {
|
||||
return &AssetWalletStore{
|
||||
db: db,
|
||||
redis: redis,
|
||||
}
|
||||
}
|
||||
|
||||
// GetByResourceTypeAndID 根据资源类型和 ID 查询钱包
|
||||
func (s *CardWalletStore) GetByResourceTypeAndID(ctx context.Context, resourceType string, resourceID uint) (*model.CardWallet, error) {
|
||||
var wallet model.CardWallet
|
||||
func (s *AssetWalletStore) GetByResourceTypeAndID(ctx context.Context, resourceType string, resourceID uint) (*model.AssetWallet, error) {
|
||||
var wallet model.AssetWallet
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
@@ -40,8 +40,8 @@ func (s *CardWalletStore) GetByResourceTypeAndID(ctx context.Context, resourceTy
|
||||
}
|
||||
|
||||
// GetByID 根据钱包 ID 查询
|
||||
func (s *CardWalletStore) GetByID(ctx context.Context, id uint) (*model.CardWallet, error) {
|
||||
var wallet model.CardWallet
|
||||
func (s *AssetWalletStore) GetByID(ctx context.Context, id uint) (*model.AssetWallet, error) {
|
||||
var wallet model.AssetWallet
|
||||
query := s.db.WithContext(ctx).Where("id = ?", id)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
@@ -51,20 +51,20 @@ func (s *CardWalletStore) GetByID(ctx context.Context, id uint) (*model.CardWall
|
||||
return &wallet, nil
|
||||
}
|
||||
|
||||
// Create 创建卡钱包
|
||||
func (s *CardWalletStore) Create(ctx context.Context, wallet *model.CardWallet) error {
|
||||
// Create 创建资产钱包
|
||||
func (s *AssetWalletStore) Create(ctx context.Context, wallet *model.AssetWallet) error {
|
||||
return s.db.WithContext(ctx).Create(wallet).Error
|
||||
}
|
||||
|
||||
// CreateWithTx 创建卡钱包(带事务)
|
||||
func (s *CardWalletStore) CreateWithTx(ctx context.Context, tx *gorm.DB, wallet *model.CardWallet) error {
|
||||
// CreateWithTx 创建资产钱包(带事务)
|
||||
func (s *AssetWalletStore) CreateWithTx(ctx context.Context, tx *gorm.DB, wallet *model.AssetWallet) error {
|
||||
return tx.WithContext(ctx).Create(wallet).Error
|
||||
}
|
||||
|
||||
// DeductBalanceWithTx 扣款(带事务,使用乐观锁)
|
||||
func (s *CardWalletStore) DeductBalanceWithTx(ctx context.Context, tx *gorm.DB, walletID uint, amount int64, version int) error {
|
||||
func (s *AssetWalletStore) DeductBalanceWithTx(ctx context.Context, tx *gorm.DB, walletID uint, amount int64, version int) error {
|
||||
// 使用乐观锁,检查可用余额是否充足
|
||||
result := tx.WithContext(ctx).Model(&model.CardWallet{}).
|
||||
result := tx.WithContext(ctx).Model(&model.AssetWallet{}).
|
||||
Where("id = ? AND balance - frozen_balance >= ? AND version = ?", walletID, amount, version).
|
||||
Updates(map[string]interface{}{
|
||||
"balance": gorm.Expr("balance - ?", amount),
|
||||
@@ -77,18 +77,17 @@ func (s *CardWalletStore) DeductBalanceWithTx(ctx context.Context, tx *gorm.DB,
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return gorm.ErrRecordNotFound // 余额不足或版本冲突
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
// 删除缓存
|
||||
s.clearWalletCache(ctx, walletID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddBalanceWithTx 增加余额(带事务)
|
||||
func (s *CardWalletStore) AddBalanceWithTx(ctx context.Context, tx *gorm.DB, walletID uint, amount int64) error {
|
||||
result := tx.WithContext(ctx).Model(&model.CardWallet{}).
|
||||
func (s *AssetWalletStore) AddBalanceWithTx(ctx context.Context, tx *gorm.DB, walletID uint, amount int64) error {
|
||||
result := tx.WithContext(ctx).Model(&model.AssetWallet{}).
|
||||
Where("id = ?", walletID).
|
||||
Updates(map[string]interface{}{
|
||||
"balance": gorm.Expr("balance + ?", amount),
|
||||
@@ -103,20 +102,18 @@ func (s *CardWalletStore) AddBalanceWithTx(ctx context.Context, tx *gorm.DB, wal
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
// 删除缓存
|
||||
s.clearWalletCache(ctx, walletID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearWalletCache 清除钱包缓存
|
||||
func (s *CardWalletStore) clearWalletCache(ctx context.Context, walletID uint) {
|
||||
// 查询钱包信息以获取 resource_type 和 resource_id
|
||||
var wallet model.CardWallet
|
||||
func (s *AssetWalletStore) clearWalletCache(ctx context.Context, walletID uint) {
|
||||
var wallet model.AssetWallet
|
||||
if err := s.db.WithContext(ctx).Select("resource_type, resource_id").First(&wallet, walletID).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
cacheKey := constants.RedisCardWalletBalanceKey(wallet.ResourceType, wallet.ResourceID)
|
||||
cacheKey := constants.RedisAssetWalletBalanceKey(wallet.ResourceType, wallet.ResourceID)
|
||||
_ = s.redis.Del(ctx, cacheKey).Err()
|
||||
}
|
||||
123
internal/store/postgres/asset_wallet_transaction_store.go
Normal file
123
internal/store/postgres/asset_wallet_transaction_store.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AssetWalletTransactionStore 资产钱包交易记录数据访问层
|
||||
type AssetWalletTransactionStore struct {
|
||||
db *gorm.DB
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
// NewAssetWalletTransactionStore 创建资产钱包交易记录 Store
|
||||
func NewAssetWalletTransactionStore(db *gorm.DB, redis *redis.Client) *AssetWalletTransactionStore {
|
||||
return &AssetWalletTransactionStore{
|
||||
db: db,
|
||||
redis: redis,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateWithTx 创建资产钱包交易记录(带事务)
|
||||
func (s *AssetWalletTransactionStore) CreateWithTx(ctx context.Context, tx *gorm.DB, transaction *model.AssetWalletTransaction) error {
|
||||
return tx.WithContext(ctx).Create(transaction).Error
|
||||
}
|
||||
|
||||
// ListByResourceID 按资源查询交易记录(支持分页)
|
||||
func (s *AssetWalletTransactionStore) ListByResourceID(ctx context.Context, resourceType string, resourceID uint, offset, limit int) ([]*model.AssetWalletTransaction, error) {
|
||||
var transactions []*model.AssetWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// CountByResourceID 统计资源的交易记录数量
|
||||
func (s *AssetWalletTransactionStore) CountByResourceID(ctx context.Context, resourceType string, resourceID uint) (int64, error) {
|
||||
var count int64
|
||||
query := s.db.WithContext(ctx).
|
||||
Model(&model.AssetWalletTransaction{}).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListByWalletID 按钱包查询交易记录(支持分页)
|
||||
func (s *AssetWalletTransactionStore) ListByWalletID(ctx context.Context, walletID uint, offset, limit int) ([]*model.AssetWalletTransaction, error) {
|
||||
var transactions []*model.AssetWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("asset_wallet_id = ?", walletID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// ListByResourceIDWithFilter 按资源查询交易记录(支持 transaction_type 和时间范围过滤,分页)
|
||||
func (s *AssetWalletTransactionStore) ListByResourceIDWithFilter(ctx context.Context, resourceType string, resourceID uint, transactionType *string, startTime, endTime *time.Time, offset, limit int) ([]*model.AssetWalletTransaction, error) {
|
||||
var transactions []*model.AssetWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
if transactionType != nil {
|
||||
query = query.Where("transaction_type = ?", *transactionType)
|
||||
}
|
||||
if startTime != nil {
|
||||
query = query.Where("created_at >= ?", *startTime)
|
||||
}
|
||||
if endTime != nil {
|
||||
query = query.Where("created_at <= ?", *endTime)
|
||||
}
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// CountByResourceIDWithFilter 统计资源的交易记录数量(支持 transaction_type 和时间范围过滤)
|
||||
func (s *AssetWalletTransactionStore) CountByResourceIDWithFilter(ctx context.Context, resourceType string, resourceID uint, transactionType *string, startTime, endTime *time.Time) (int64, error) {
|
||||
var count int64
|
||||
query := s.db.WithContext(ctx).
|
||||
Model(&model.AssetWalletTransaction{}).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
if transactionType != nil {
|
||||
query = query.Where("transaction_type = ?", *transactionType)
|
||||
}
|
||||
if startTime != nil {
|
||||
query = query.Where("created_at >= ?", *startTime)
|
||||
}
|
||||
if endTime != nil {
|
||||
query = query.Where("created_at <= ?", *endTime)
|
||||
}
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CardWalletTransactionStore 卡钱包交易记录数据访问层
|
||||
type CardWalletTransactionStore struct {
|
||||
db *gorm.DB
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
// NewCardWalletTransactionStore 创建卡钱包交易记录 Store
|
||||
func NewCardWalletTransactionStore(db *gorm.DB, redis *redis.Client) *CardWalletTransactionStore {
|
||||
return &CardWalletTransactionStore{
|
||||
db: db,
|
||||
redis: redis,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateWithTx 创建卡钱包交易记录(带事务)
|
||||
func (s *CardWalletTransactionStore) CreateWithTx(ctx context.Context, tx *gorm.DB, transaction *model.CardWalletTransaction) error {
|
||||
return tx.WithContext(ctx).Create(transaction).Error
|
||||
}
|
||||
|
||||
// ListByResourceID 按资源查询交易记录(支持分页)
|
||||
func (s *CardWalletTransactionStore) ListByResourceID(ctx context.Context, resourceType string, resourceID uint, offset, limit int) ([]*model.CardWalletTransaction, error) {
|
||||
var transactions []*model.CardWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// CountByResourceID 统计资源的交易记录数量
|
||||
func (s *CardWalletTransactionStore) CountByResourceID(ctx context.Context, resourceType string, resourceID uint) (int64, error) {
|
||||
var count int64
|
||||
query := s.db.WithContext(ctx).
|
||||
Model(&model.CardWalletTransaction{}).
|
||||
Where("resource_type = ? AND resource_id = ?", resourceType, resourceID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListByWalletID 按钱包查询交易记录(支持分页)
|
||||
func (s *CardWalletTransactionStore) ListByWalletID(ctx context.Context, walletID uint, offset, limit int) ([]*model.CardWalletTransaction, error) {
|
||||
var transactions []*model.CardWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("card_wallet_id = ?", walletID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// GetByReference 根据关联业务查询交易记录
|
||||
func (s *CardWalletTransactionStore) GetByReference(ctx context.Context, referenceType string, referenceID uint) (*model.CardWalletTransaction, error) {
|
||||
var transaction model.CardWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("reference_type = ? AND reference_id = ?", referenceType, referenceID)
|
||||
// 应用数据权限过滤(使用 shop_id_tag 字段)
|
||||
query = middleware.ApplyShopTagFilter(ctx, query)
|
||||
err := query.First(&transaction).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transaction, nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE tb_asset_recharge_record RENAME TO tb_card_recharge_record;
|
||||
ALTER TABLE tb_asset_wallet_transaction RENAME TO tb_card_wallet_transaction;
|
||||
ALTER TABLE tb_asset_wallet RENAME TO tb_card_wallet;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- 将卡钱包相关表统一改名为资产钱包,使命名与实际承载的两种资产(iot_card + device)一致
|
||||
-- tb_card_wallet → tb_asset_wallet
|
||||
ALTER TABLE tb_card_wallet RENAME TO tb_asset_wallet;
|
||||
|
||||
-- tb_card_wallet_transaction → tb_asset_wallet_transaction
|
||||
ALTER TABLE tb_card_wallet_transaction RENAME TO tb_asset_wallet_transaction;
|
||||
|
||||
-- tb_card_recharge_record → tb_asset_recharge_record
|
||||
ALTER TABLE tb_card_recharge_record RENAME TO tb_asset_recharge_record;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE tb_asset_wallet_transaction ALTER COLUMN reference_no TYPE BIGINT USING reference_no::BIGINT;
|
||||
ALTER TABLE tb_asset_wallet_transaction RENAME COLUMN reference_no TO reference_id;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- 将流水记录中的关联ID字段从 bigint 类型的 reference_id 改为 varchar(50) 的 reference_no
|
||||
-- 用于存储可读的业务编号:充值单号(CRCH…)或订单号(ORD…)
|
||||
ALTER TABLE tb_asset_wallet_transaction RENAME COLUMN reference_id TO reference_no;
|
||||
ALTER TABLE tb_asset_wallet_transaction ALTER COLUMN reference_no TYPE VARCHAR(50) USING reference_no::VARCHAR(50);
|
||||
@@ -130,18 +130,18 @@ func RedisAgentWalletLockKey(shopID uint, walletType string) string {
|
||||
return fmt.Sprintf("agent_wallet:lock:%d:%s", shopID, walletType)
|
||||
}
|
||||
|
||||
// RedisCardWalletBalanceKey 卡钱包余额缓存 Key
|
||||
// 格式:card_wallet:balance:{resource_type}:{resource_id}
|
||||
// RedisAssetWalletBalanceKey 资产钱包余额缓存 Key
|
||||
// 格式:asset_wallet:balance:{resource_type}:{resource_id}
|
||||
// TTL:180 秒(3 分钟)
|
||||
func RedisCardWalletBalanceKey(resourceType string, resourceID uint) string {
|
||||
return fmt.Sprintf("card_wallet:balance:%s:%d", resourceType, resourceID)
|
||||
func RedisAssetWalletBalanceKey(resourceType string, resourceID uint) string {
|
||||
return fmt.Sprintf("asset_wallet:balance:%s:%d", resourceType, resourceID)
|
||||
}
|
||||
|
||||
// RedisCardWalletLockKey 卡钱包分布式锁 Key
|
||||
// 格式:card_wallet:lock:{resource_type}:{resource_id}
|
||||
// RedisAssetWalletLockKey 资产钱包分布式锁 Key
|
||||
// 格式:asset_wallet:lock:{resource_type}:{resource_id}
|
||||
// TTL:10 秒
|
||||
func RedisCardWalletLockKey(resourceType string, resourceID uint) string {
|
||||
return fmt.Sprintf("card_wallet:lock:%s:%d", resourceType, resourceID)
|
||||
func RedisAssetWalletLockKey(resourceType string, resourceID uint) string {
|
||||
return fmt.Sprintf("asset_wallet:lock:%s:%d", resourceType, resourceID)
|
||||
}
|
||||
|
||||
// ========== 兼容性别名(待清理)==========
|
||||
|
||||
@@ -53,5 +53,6 @@ func BuildDocHandlers() *bootstrap.Handlers {
|
||||
PollingCleanup: admin.NewPollingCleanupHandler(nil),
|
||||
PollingManualTrigger: admin.NewPollingManualTriggerHandler(nil),
|
||||
Asset: admin.NewAssetHandler(nil, nil, nil),
|
||||
AssetWallet: admin.NewAssetWalletHandler(nil),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,10 +39,9 @@ type WorkerStores struct {
|
||||
PollingAlertHistory *postgres.PollingAlertHistoryStore
|
||||
DataCleanupConfig *postgres.DataCleanupConfigStore
|
||||
DataCleanupLog *postgres.DataCleanupLogStore
|
||||
// 新增代理钱包 Store
|
||||
AgentWallet *postgres.AgentWalletStore
|
||||
AgentWalletTransaction *postgres.AgentWalletTransactionStore
|
||||
CardWallet *postgres.CardWalletStore // 卡钱包 Store(用于订单取消时解冻)
|
||||
AgentWallet *postgres.AgentWalletStore
|
||||
AgentWalletTransaction *postgres.AgentWalletTransactionStore
|
||||
AssetWallet *postgres.AssetWalletStore
|
||||
}
|
||||
|
||||
// WorkerServices Worker 侧所有 Service 的集合
|
||||
|
||||
Reference in New Issue
Block a user