feat: 代理商资金可见性重构(agent-fund-visibility)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m10s
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m10s
- 将 GET /shops/commission-summary 重命名为 GET /shops/fund-summary, 响应新增 main_balance、main_frozen_balance 两个预充值钱包字段 - 新增 GET /shops/:id/main-wallet/transactions 预充值钱包流水接口 - 将佣金统计、每日统计、发起提现从 /my/ 路径迁移至 /shops/:id/ 路径: GET /shops/:id/commission-stats GET /shops/:id/commission-daily-stats POST /shops/:id/withdrawal-requests - 删除 MyCommissionService、MyCommissionHandler 及全部 /my/ 路由 - 补齐 ListShopWithdrawalRequests、ListShopCommissionRecords 的 CanManageShop 越权校验(安全修复) - 提现接口增加严格权限:仅代理账号本人可为自己店铺发起提现 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -71,7 +71,6 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
|
||||
EnterpriseCard: admin.NewEnterpriseCardHandler(svc.EnterpriseCard),
|
||||
EnterpriseDevice: admin.NewEnterpriseDeviceHandler(svc.EnterpriseDevice),
|
||||
Authorization: admin.NewAuthorizationHandler(svc.Authorization),
|
||||
MyCommission: admin.NewMyCommissionHandler(svc.MyCommission),
|
||||
IotCard: admin.NewIotCardHandler(svc.IotCard),
|
||||
IotCardImport: admin.NewIotCardImportHandler(svc.IotCardImport),
|
||||
Device: admin.NewDeviceHandler(svc.Device),
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
exchangeSvc "github.com/break/junhong_cmp_fiber/internal/service/exchange"
|
||||
iotCardSvc "github.com/break/junhong_cmp_fiber/internal/service/iot_card"
|
||||
iotCardImportSvc "github.com/break/junhong_cmp_fiber/internal/service/iot_card_import"
|
||||
myCommissionSvc "github.com/break/junhong_cmp_fiber/internal/service/my_commission"
|
||||
orderSvc "github.com/break/junhong_cmp_fiber/internal/service/order"
|
||||
packageSvc "github.com/break/junhong_cmp_fiber/internal/service/package"
|
||||
packageSeriesSvc "github.com/break/junhong_cmp_fiber/internal/service/package_series"
|
||||
@@ -64,7 +63,6 @@ type services struct {
|
||||
EnterpriseCard *enterpriseCardSvc.Service
|
||||
EnterpriseDevice *enterpriseDeviceSvc.Service
|
||||
Authorization *enterpriseCardSvc.AuthorizationService
|
||||
MyCommission *myCommissionSvc.Service
|
||||
IotCard *iotCardSvc.Service
|
||||
IotCardImport *iotCardImportSvc.Service
|
||||
Device *deviceSvc.Service
|
||||
@@ -153,7 +151,7 @@ func initServices(s *stores, deps *Dependencies) *services {
|
||||
),
|
||||
Shop: shopSvc.New(s.Shop, s.Account, s.ShopRole, s.Role, s.AccountRole, s.AgentWallet),
|
||||
Auth: authSvc.New(s.Account, s.AccountRole, s.RolePermission, s.Permission, s.Shop, deps.TokenManager, deps.Logger),
|
||||
ShopCommission: shopCommissionSvc.New(s.Shop, s.Account, s.AgentWallet, s.CommissionWithdrawalRequest, s.CommissionRecord, deps.DB, deps.Logger),
|
||||
ShopCommission: shopCommissionSvc.New(s.Shop, s.Account, s.AgentWallet, s.CommissionWithdrawalRequest, s.CommissionWithdrawalSetting, s.CommissionRecord, s.AgentWalletTransaction, deps.DB, deps.Logger),
|
||||
CommissionWithdrawal: commissionWithdrawalSvc.New(deps.DB, s.Shop, s.Account, s.AgentWallet, s.AgentWalletTransaction, s.CommissionWithdrawalRequest),
|
||||
CommissionWithdrawalSetting: commissionWithdrawalSettingSvc.New(deps.DB, s.Account, s.CommissionWithdrawalSetting),
|
||||
CommissionCalculation: commissionCalculationSvc.New(
|
||||
@@ -178,7 +176,6 @@ func initServices(s *stores, deps *Dependencies) *services {
|
||||
EnterpriseCard: enterpriseCardSvc.New(deps.DB, s.Enterprise, s.EnterpriseCardAuthorization),
|
||||
EnterpriseDevice: enterpriseDeviceSvc.New(deps.DB, s.Enterprise, s.Device, s.DeviceSimBinding, s.EnterpriseDeviceAuthorization, s.EnterpriseCardAuthorization, deps.Logger),
|
||||
Authorization: enterpriseCardSvc.NewAuthorizationService(s.Enterprise, s.IotCard, s.EnterpriseCardAuthorization, deps.Logger),
|
||||
MyCommission: myCommissionSvc.New(deps.DB, s.Shop, s.AgentWallet, s.CommissionWithdrawalRequest, s.CommissionWithdrawalSetting, s.CommissionRecord, s.AgentWalletTransaction),
|
||||
IotCard: iotCard,
|
||||
IotCardImport: iotCardImportSvc.New(deps.DB, s.IotCardImportTask, deps.QueueClient),
|
||||
Device: device,
|
||||
|
||||
@@ -32,7 +32,6 @@ type Handlers struct {
|
||||
EnterpriseCard *admin.EnterpriseCardHandler
|
||||
EnterpriseDevice *admin.EnterpriseDeviceHandler
|
||||
Authorization *admin.AuthorizationHandler
|
||||
MyCommission *admin.MyCommissionHandler
|
||||
IotCard *admin.IotCardHandler
|
||||
IotCardImport *admin.IotCardImportHandler
|
||||
Device *admin.DeviceHandler
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
myCommissionService "github.com/break/junhong_cmp_fiber/internal/service/my_commission"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
type MyCommissionHandler struct {
|
||||
service *myCommissionService.Service
|
||||
}
|
||||
|
||||
func NewMyCommissionHandler(service *myCommissionService.Service) *MyCommissionHandler {
|
||||
return &MyCommissionHandler{service: service}
|
||||
}
|
||||
|
||||
func (h *MyCommissionHandler) GetSummary(c *fiber.Ctx) error {
|
||||
result, err := h.service.GetCommissionSummary(c.UserContext())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
func (h *MyCommissionHandler) CreateWithdrawal(c *fiber.Ctx) error {
|
||||
var req dto.CreateMyWithdrawalReq
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
result, err := h.service.CreateWithdrawalRequest(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
func (h *MyCommissionHandler) ListWithdrawals(c *fiber.Ctx) error {
|
||||
var req dto.MyWithdrawalListReq
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
result, err := h.service.ListMyWithdrawalRequests(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
|
||||
}
|
||||
|
||||
func (h *MyCommissionHandler) ListRecords(c *fiber.Ctx) error {
|
||||
var req dto.MyCommissionRecordListReq
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
result, err := h.service.ListMyCommissionRecords(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
|
||||
}
|
||||
|
||||
func (h *MyCommissionHandler) GetStats(c *fiber.Ctx) error {
|
||||
var req dto.CommissionStatsRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
result, err := h.service.GetStats(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
func (h *MyCommissionHandler) GetDailyStats(c *fiber.Ctx) error {
|
||||
var req dto.DailyCommissionStatsRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
result, err := h.service.GetDailyStats(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
@@ -11,21 +11,25 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// ShopCommissionHandler 代理商资金管理 Handler
|
||||
type ShopCommissionHandler struct {
|
||||
service *shopCommissionService.Service
|
||||
}
|
||||
|
||||
// NewShopCommissionHandler 创建代理商资金管理 Handler
|
||||
func NewShopCommissionHandler(service *shopCommissionService.Service) *ShopCommissionHandler {
|
||||
return &ShopCommissionHandler{service: service}
|
||||
}
|
||||
|
||||
func (h *ShopCommissionHandler) ListCommissionSummary(c *fiber.Ctx) error {
|
||||
var req dto.ShopCommissionSummaryListReq
|
||||
// ListFundSummary 代理商资金概况列表
|
||||
// GET /api/admin/shops/fund-summary
|
||||
func (h *ShopCommissionHandler) ListFundSummary(c *fiber.Ctx) error {
|
||||
var req dto.ShopFundSummaryListReq
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.ListShopCommissionSummary(c.UserContext(), &req)
|
||||
result, err := h.service.ListShopFundSummary(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -33,6 +37,8 @@ func (h *ShopCommissionHandler) ListCommissionSummary(c *fiber.Ctx) error {
|
||||
return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
|
||||
}
|
||||
|
||||
// ListWithdrawalRequests 代理商提现记录列表
|
||||
// GET /api/admin/shops/:shop_id/withdrawal-requests
|
||||
func (h *ShopCommissionHandler) ListWithdrawalRequests(c *fiber.Ctx) error {
|
||||
shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -41,7 +47,7 @@ func (h *ShopCommissionHandler) ListWithdrawalRequests(c *fiber.Ctx) error {
|
||||
|
||||
var req dto.ShopWithdrawalRequestListReq
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.ListShopWithdrawalRequests(c.UserContext(), uint(shopID), &req)
|
||||
@@ -52,6 +58,8 @@ func (h *ShopCommissionHandler) ListWithdrawalRequests(c *fiber.Ctx) error {
|
||||
return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
|
||||
}
|
||||
|
||||
// ListCommissionRecords 代理商佣金明细列表
|
||||
// GET /api/admin/shops/:shop_id/commission-records
|
||||
func (h *ShopCommissionHandler) ListCommissionRecords(c *fiber.Ctx) error {
|
||||
shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -60,7 +68,7 @@ func (h *ShopCommissionHandler) ListCommissionRecords(c *fiber.Ctx) error {
|
||||
|
||||
var req dto.ShopCommissionRecordListReq
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.ListShopCommissionRecords(c.UserContext(), uint(shopID), &req)
|
||||
@@ -90,3 +98,87 @@ func (h *ShopCommissionHandler) ResolveCommissionRecord(c *fiber.Ctx) error {
|
||||
|
||||
return response.Success(c, nil)
|
||||
}
|
||||
|
||||
// GetCommissionStats 代理商佣金统计
|
||||
// GET /api/admin/shops/:shop_id/commission-stats
|
||||
func (h *ShopCommissionHandler) GetCommissionStats(c *fiber.Ctx) error {
|
||||
shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
|
||||
if err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的店铺 ID")
|
||||
}
|
||||
|
||||
var req dto.CommissionStatsRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.GetStats(c.UserContext(), uint(shopID), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// GetCommissionDailyStats 代理商每日佣金统计
|
||||
// GET /api/admin/shops/:shop_id/commission-daily-stats
|
||||
func (h *ShopCommissionHandler) GetCommissionDailyStats(c *fiber.Ctx) error {
|
||||
shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
|
||||
if err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的店铺 ID")
|
||||
}
|
||||
|
||||
var req dto.DailyCommissionStatsRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.GetDailyStats(c.UserContext(), uint(shopID), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// CreateWithdrawal 发起提现申请
|
||||
// POST /api/admin/shops/:shop_id/withdrawal-requests
|
||||
func (h *ShopCommissionHandler) CreateWithdrawal(c *fiber.Ctx) error {
|
||||
shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
|
||||
if err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的店铺 ID")
|
||||
}
|
||||
|
||||
var req dto.CreateMyWithdrawalReq
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.CreateWithdrawalRequest(c.UserContext(), uint(shopID), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// ListMainWalletTransactions 预充值钱包流水列表
|
||||
// GET /api/admin/shops/:shop_id/main-wallet/transactions
|
||||
func (h *ShopCommissionHandler) ListMainWalletTransactions(c *fiber.Ctx) error {
|
||||
shopID, err := strconv.ParseUint(c.Params("shop_id"), 10, 64)
|
||||
if err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的店铺 ID")
|
||||
}
|
||||
|
||||
var req dto.MainWalletTransactionListRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
result, err := h.service.ListMainWalletTransactions(c.UserContext(), uint(shopID), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
|
||||
}
|
||||
|
||||
@@ -60,14 +60,14 @@ type DailyCommissionStatsResponse struct {
|
||||
|
||||
// CommissionStatsRequest 佣金统计请求
|
||||
type CommissionStatsRequest struct {
|
||||
ShopID *uint `json:"shop_id" query:"shop_id" validate:"omitempty" description:"店铺ID"`
|
||||
ShopID uint `json:"-" path:"shop_id" description:"店铺ID" required:"true"`
|
||||
StartTime *string `json:"start_time" query:"start_time" validate:"omitempty" description:"开始时间"`
|
||||
EndTime *string `json:"end_time" query:"end_time" validate:"omitempty" description:"结束时间"`
|
||||
}
|
||||
|
||||
// DailyCommissionStatsRequest 每日佣金统计请求
|
||||
type DailyCommissionStatsRequest struct {
|
||||
ShopID *uint `json:"shop_id" query:"shop_id" validate:"omitempty" description:"店铺ID"`
|
||||
ShopID uint `json:"-" path:"shop_id" description:"店铺ID" required:"true"`
|
||||
StartDate *string `json:"start_date" query:"start_date" validate:"omitempty" description:"开始日期(YYYY-MM-DD)"`
|
||||
EndDate *string `json:"end_date" query:"end_date" validate:"omitempty" description:"结束日期(YYYY-MM-DD)"`
|
||||
Days *int `json:"days" query:"days" validate:"omitempty,min=1,max=365" minimum:"1" maximum:"365" description:"查询天数(默认30天)"`
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
package dto
|
||||
|
||||
type MyCommissionSummaryResp struct {
|
||||
ShopID uint `json:"shop_id" description:"店铺ID"`
|
||||
ShopName string `json:"shop_name" description:"店铺名称"`
|
||||
TotalCommission int64 `json:"total_commission" description:"累计佣金(分)"`
|
||||
WithdrawnCommission int64 `json:"withdrawn_commission" description:"已提现佣金(分)"`
|
||||
UnwithdrawCommission int64 `json:"unwithdraw_commission" description:"未提现佣金(分)"`
|
||||
FrozenCommission int64 `json:"frozen_commission" description:"冻结佣金(分)"`
|
||||
WithdrawingCommission int64 `json:"withdrawing_commission" description:"提现中佣金(分)"`
|
||||
AvailableCommission int64 `json:"available_commission" description:"可提现佣金(分)"`
|
||||
}
|
||||
|
||||
// CreateMyWithdrawalReq 发起提现申请请求(由 POST /shops/:id/withdrawal-requests 复用)
|
||||
type CreateMyWithdrawalReq struct {
|
||||
ShopID uint `json:"-" path:"shop_id" description:"店铺ID" required:"true"`
|
||||
Amount int64 `json:"amount" validate:"required,min=1" required:"true" minimum:"1" description:"提现金额(分)"`
|
||||
WithdrawalMethod string `json:"withdrawal_method" validate:"required,oneof=alipay" required:"true" enum:"alipay" description:"收款类型"`
|
||||
AccountName string `json:"account_name" validate:"required,max=50" required:"true" maximum:"50" description:"收款人姓名"`
|
||||
AccountNumber string `json:"account_number" validate:"required,max=100" required:"true" maximum:"100" description:"收款账号"`
|
||||
}
|
||||
|
||||
// CreateMyWithdrawalResp 发起提现申请响应(由 POST /shops/:id/withdrawal-requests 复用)
|
||||
type CreateMyWithdrawalResp struct {
|
||||
ID uint `json:"id" description:"提现申请ID"`
|
||||
WithdrawalNo string `json:"withdrawal_no" description:"提现单号"`
|
||||
@@ -29,38 +21,3 @@ type CreateMyWithdrawalResp struct {
|
||||
StatusName string `json:"status_name" description:"状态名称"`
|
||||
CreatedAt string `json:"created_at" description:"申请时间"`
|
||||
}
|
||||
|
||||
type MyWithdrawalListReq struct {
|
||||
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:"每页数量"`
|
||||
Status *int `json:"status" query:"status" description:"状态(1=待审批, 2=已通过, 3=已拒绝)"`
|
||||
StartTime string `json:"start_time" query:"start_time" description:"申请开始时间"`
|
||||
EndTime string `json:"end_time" query:"end_time" description:"申请结束时间"`
|
||||
}
|
||||
|
||||
type MyCommissionRecordListReq struct {
|
||||
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:"每页数量"`
|
||||
CommissionSource *string `json:"commission_source" query:"commission_source" validate:"omitempty,oneof=cost_diff one_time tier_bonus" description:"佣金来源 (cost_diff:成本价差, one_time:一次性佣金, tier_bonus(已废弃):梯度奖励)"`
|
||||
ICCID string `json:"iccid" query:"iccid" description:"ICCID(模糊查询)"`
|
||||
VirtualNo string `json:"virtual_no" query:"virtual_no" description:"设备虚拟号(模糊查询)"`
|
||||
OrderNo string `json:"order_no" query:"order_no" description:"订单号(模糊查询)"`
|
||||
}
|
||||
|
||||
type MyCommissionRecordItem struct {
|
||||
ID uint `json:"id" description:"佣金记录ID"`
|
||||
ShopID uint `json:"shop_id" description:"店铺ID"`
|
||||
OrderID uint `json:"order_id" description:"订单ID"`
|
||||
CommissionSource string `json:"commission_source" description:"佣金来源 (cost_diff:成本价差, one_time:一次性佣金, tier_bonus(已废弃):梯度奖励)"`
|
||||
Amount int64 `json:"amount" description:"佣金金额(分)"`
|
||||
Status int `json:"status" description:"状态 (1:已入账, 2:已失效)"`
|
||||
StatusName string `json:"status_name" description:"状态名称"`
|
||||
CreatedAt string `json:"created_at" description:"创建时间"`
|
||||
}
|
||||
|
||||
type MyCommissionRecordPageResult struct {
|
||||
Items []MyCommissionRecordItem `json:"items" description:"佣金记录列表"`
|
||||
Total int64 `json:"total" description:"总记录数"`
|
||||
Page int `json:"page" description:"当前页码"`
|
||||
Size int `json:"size" description:"每页数量"`
|
||||
}
|
||||
|
||||
@@ -1,25 +1,27 @@
|
||||
package dto
|
||||
|
||||
// ========================================
|
||||
// 代理商佣金查询 DTO
|
||||
// 代理商资金概况查询 DTO
|
||||
// ========================================
|
||||
|
||||
// ShopCommissionSummaryListReq 代理商佣金列表查询请求
|
||||
type ShopCommissionSummaryListReq struct {
|
||||
// ShopFundSummaryListReq 代理商资金概况列表查询请求
|
||||
type ShopFundSummaryListReq struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量(默认20,最大100)"`
|
||||
ShopName string `json:"shop_name" query:"shop_name" validate:"omitempty,max=100" maxLength:"100" description:"店铺名称(模糊查询)"`
|
||||
Username string `json:"username" query:"username" validate:"omitempty,max=50" maxLength:"50" description:"主账号用户名(模糊查询)"`
|
||||
}
|
||||
|
||||
// ShopCommissionSummaryItem 代理商佣金汇总项
|
||||
type ShopCommissionSummaryItem struct {
|
||||
// ShopFundSummaryItem 代理商资金概况项(含预充值钱包和佣金钱包)
|
||||
type ShopFundSummaryItem struct {
|
||||
ShopID uint `json:"shop_id" description:"店铺ID"`
|
||||
ShopName string `json:"shop_name" description:"店铺名称"`
|
||||
ShopCode string `json:"shop_code" description:"店铺编码"`
|
||||
Username string `json:"username" description:"主账号用户名"`
|
||||
Phone string `json:"phone" description:"主账号手机号"`
|
||||
TotalCommission int64 `json:"total_commission" description:"总佣金(分)"`
|
||||
MainBalance int64 `json:"main_balance" description:"预充值钱包余额(分)"`
|
||||
MainFrozenBalance int64 `json:"main_frozen_balance" description:"预充值钱包冻结余额(分,预留字段)"`
|
||||
TotalCommission int64 `json:"total_commission" description:"累计佣金总额(分)"`
|
||||
WithdrawnCommission int64 `json:"withdrawn_commission" description:"已提现佣金(分)"`
|
||||
UnwithdrawCommission int64 `json:"unwithdraw_commission" description:"未提现佣金(分)"`
|
||||
FrozenCommission int64 `json:"frozen_commission" description:"冻结中佣金(分)"`
|
||||
@@ -28,9 +30,43 @@ type ShopCommissionSummaryItem struct {
|
||||
CreatedAt string `json:"created_at" description:"店铺创建时间"`
|
||||
}
|
||||
|
||||
// ShopCommissionSummaryPageResult 代理商佣金列表分页响应
|
||||
type ShopCommissionSummaryPageResult struct {
|
||||
Items []ShopCommissionSummaryItem `json:"items" description:"代理商佣金列表"`
|
||||
// ShopFundSummaryPageResult 代理商资金概况列表分页响应
|
||||
type ShopFundSummaryPageResult struct {
|
||||
Items []ShopFundSummaryItem `json:"items" description:"代理商资金概况列表"`
|
||||
Total int64 `json:"total" description:"总记录数"`
|
||||
Page int `json:"page" description:"当前页码"`
|
||||
Size int `json:"size" description:"每页数量"`
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// 主钱包流水查询 DTO
|
||||
// ========================================
|
||||
|
||||
// MainWalletTransactionListRequest 主钱包流水查询请求
|
||||
type MainWalletTransactionListRequest struct {
|
||||
ShopID uint `json:"-" path:"shop_id" description:"店铺ID" required:"true"`
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量(默认20,最大100)"`
|
||||
TransactionType string `json:"transaction_type" query:"transaction_type" validate:"omitempty,max=50" maxLength:"50" description:"交易类型过滤(recharge:充值入账, deduct:套餐扣款, refund:退款)"`
|
||||
StartDate string `json:"start_date" query:"start_date" validate:"omitempty" description:"开始日期(YYYY-MM-DD)"`
|
||||
EndDate string `json:"end_date" query:"end_date" validate:"omitempty" description:"结束日期(YYYY-MM-DD)"`
|
||||
}
|
||||
|
||||
// MainWalletTransactionItem 主钱包流水记录项
|
||||
type MainWalletTransactionItem struct {
|
||||
ID uint `json:"id" description:"流水记录ID"`
|
||||
TransactionType string `json:"transaction_type" description:"交易类型(recharge:充值入账, deduct:套餐扣款, refund:退款)"`
|
||||
TransactionSubtype string `json:"transaction_subtype" description:"交易子类型(可为空)"`
|
||||
Amount int64 `json:"amount" description:"变动金额(分,正数为入账,负数为扣款)"`
|
||||
BalanceBefore int64 `json:"balance_before" description:"变动前余额(分)"`
|
||||
BalanceAfter int64 `json:"balance_after" description:"变动后余额(分)"`
|
||||
Remark string `json:"remark" description:"备注(可为空)"`
|
||||
CreatedAt string `json:"created_at" description:"流水时间"`
|
||||
}
|
||||
|
||||
// MainWalletTransactionListResponse 主钱包流水列表响应
|
||||
type MainWalletTransactionListResponse struct {
|
||||
Items []MainWalletTransactionItem `json:"items" description:"流水记录列表"`
|
||||
Total int64 `json:"total" description:"总记录数"`
|
||||
Page int `json:"page" description:"当前页码"`
|
||||
Size int `json:"size" description:"每页数量"`
|
||||
|
||||
@@ -50,9 +50,6 @@ func RegisterAdminRoutes(router fiber.Router, handlers *bootstrap.Handlers, midd
|
||||
registerAuthorizationRoutes(authGroup, handlers.Authorization, doc, basePath)
|
||||
}
|
||||
|
||||
if handlers.MyCommission != nil {
|
||||
registerMyCommissionRoutes(authGroup, handlers.MyCommission, doc, basePath)
|
||||
}
|
||||
if handlers.IotCard != nil {
|
||||
registerIotCardRoutes(authGroup, handlers.IotCard, handlers.IotCardImport, doc, basePath)
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler/admin"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/openapi"
|
||||
)
|
||||
|
||||
func registerMyCommissionRoutes(router fiber.Router, handler *admin.MyCommissionHandler, doc *openapi.Generator, basePath string) {
|
||||
my := router.Group("/my")
|
||||
groupPath := basePath + "/my"
|
||||
|
||||
Register(my, doc, groupPath, "GET", "/commission-summary", handler.GetSummary, RouteSpec{
|
||||
Summary: "我的佣金概览",
|
||||
Tags: []string{"我的佣金"},
|
||||
Input: nil,
|
||||
Output: new(dto.MyCommissionSummaryResp),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(my, doc, groupPath, "POST", "/withdrawal-requests", handler.CreateWithdrawal, RouteSpec{
|
||||
Summary: "发起提现申请",
|
||||
Tags: []string{"我的佣金"},
|
||||
Input: new(dto.CreateMyWithdrawalReq),
|
||||
Output: new(dto.CreateMyWithdrawalResp),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(my, doc, groupPath, "GET", "/withdrawal-requests", handler.ListWithdrawals, RouteSpec{
|
||||
Summary: "我的提现记录",
|
||||
Tags: []string{"我的佣金"},
|
||||
Input: new(dto.MyWithdrawalListReq),
|
||||
Output: new(dto.WithdrawalRequestPageResult),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(my, doc, groupPath, "GET", "/commission-records", handler.ListRecords, RouteSpec{
|
||||
Summary: "我的佣金明细",
|
||||
Tags: []string{"我的佣金"},
|
||||
Input: new(dto.MyCommissionRecordListReq),
|
||||
Output: new(dto.MyCommissionRecordPageResult),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(my, doc, groupPath, "GET", "/commission-stats", handler.GetStats, RouteSpec{
|
||||
Summary: "我的佣金统计",
|
||||
Tags: []string{"我的佣金"},
|
||||
Input: new(dto.CommissionStatsRequest),
|
||||
Output: new(dto.CommissionStatsResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(my, doc, groupPath, "GET", "/commission-daily-stats", handler.GetDailyStats, RouteSpec{
|
||||
Summary: "我的每日佣金统计",
|
||||
Tags: []string{"我的佣金"},
|
||||
Input: new(dto.DailyCommissionStatsRequest),
|
||||
Output: []dto.DailyCommissionStatsResponse{},
|
||||
Auth: true,
|
||||
})
|
||||
}
|
||||
@@ -86,17 +86,17 @@ func registerShopCommissionRoutes(router fiber.Router, handler *admin.ShopCommis
|
||||
shops := router.Group("/shops")
|
||||
groupPath := basePath + "/shops"
|
||||
|
||||
Register(shops, doc, groupPath, "GET", "/commission-summary", handler.ListCommissionSummary, RouteSpec{
|
||||
Summary: "代理商佣金列表",
|
||||
Tags: []string{"代理商佣金管理"},
|
||||
Input: new(dto.ShopCommissionSummaryListReq),
|
||||
Output: new(dto.ShopCommissionSummaryPageResult),
|
||||
Register(shops, doc, groupPath, "GET", "/fund-summary", handler.ListFundSummary, RouteSpec{
|
||||
Summary: "代理商资金概况",
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.ShopFundSummaryListReq),
|
||||
Output: new(dto.ShopFundSummaryPageResult),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(shops, doc, groupPath, "GET", "/:shop_id/withdrawal-requests", handler.ListWithdrawalRequests, RouteSpec{
|
||||
Summary: "代理商提现记录",
|
||||
Tags: []string{"代理商佣金管理"},
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.ShopWithdrawalRequestListReq),
|
||||
Output: new(dto.ShopWithdrawalRequestPageResult),
|
||||
Auth: true,
|
||||
@@ -104,18 +104,50 @@ func registerShopCommissionRoutes(router fiber.Router, handler *admin.ShopCommis
|
||||
|
||||
Register(shops, doc, groupPath, "GET", "/:shop_id/commission-records", handler.ListCommissionRecords, RouteSpec{
|
||||
Summary: "代理商佣金明细",
|
||||
Tags: []string{"代理商佣金管理"},
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.ShopCommissionRecordListReq),
|
||||
Output: new(dto.ShopCommissionRecordPageResult),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(shops, doc, groupPath, "GET", "/:shop_id/main-wallet/transactions", handler.ListMainWalletTransactions, RouteSpec{
|
||||
Summary: "代理商预充值钱包流水",
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.MainWalletTransactionListRequest),
|
||||
Output: new(dto.MainWalletTransactionListResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(shops, doc, groupPath, "GET", "/:shop_id/commission-stats", handler.GetCommissionStats, RouteSpec{
|
||||
Summary: "代理商佣金统计",
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.CommissionStatsRequest),
|
||||
Output: new(dto.CommissionStatsResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(shops, doc, groupPath, "GET", "/:shop_id/commission-daily-stats", handler.GetCommissionDailyStats, RouteSpec{
|
||||
Summary: "代理商每日佣金统计",
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.DailyCommissionStatsRequest),
|
||||
Output: []dto.DailyCommissionStatsResponse{},
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(shops, doc, groupPath, "POST", "/:shop_id/withdrawal-requests", handler.CreateWithdrawal, RouteSpec{
|
||||
Summary: "发起提现申请",
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.CreateMyWithdrawalReq),
|
||||
Output: new(dto.CreateMyWithdrawalResp),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
commissionRecords := router.Group("/commission-records")
|
||||
crPath := basePath + "/commission-records"
|
||||
|
||||
Register(commissionRecords, doc, crPath, "POST", "/:id/resolve", handler.ResolveCommissionRecord, RouteSpec{
|
||||
Summary: "修正待审佣金记录",
|
||||
Tags: []string{"代理商佣金管理"},
|
||||
Tags: []string{"代理商资金管理"},
|
||||
Input: new(dto.CommissionRecordResolveRequest),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
@@ -1,523 +0,0 @@
|
||||
package my_commission
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"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/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
shopStore *postgres.ShopStore
|
||||
agentWalletStore *postgres.AgentWalletStore
|
||||
commissionWithdrawalRequestStore *postgres.CommissionWithdrawalRequestStore
|
||||
commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
agentWalletTransactionStore *postgres.AgentWalletTransactionStore
|
||||
}
|
||||
|
||||
func New(
|
||||
db *gorm.DB,
|
||||
shopStore *postgres.ShopStore,
|
||||
agentWalletStore *postgres.AgentWalletStore,
|
||||
commissionWithdrawalRequestStore *postgres.CommissionWithdrawalRequestStore,
|
||||
commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore,
|
||||
commissionRecordStore *postgres.CommissionRecordStore,
|
||||
agentWalletTransactionStore *postgres.AgentWalletTransactionStore,
|
||||
) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
shopStore: shopStore,
|
||||
agentWalletStore: agentWalletStore,
|
||||
commissionWithdrawalRequestStore: commissionWithdrawalRequestStore,
|
||||
commissionWithdrawalSettingStore: commissionWithdrawalSettingStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
agentWalletTransactionStore: agentWalletTransactionStore,
|
||||
}
|
||||
}
|
||||
|
||||
// GetCommissionSummary 获取我的佣金概览
|
||||
func (s *Service) GetCommissionSummary(ctx context.Context) (*dto.MyCommissionSummaryResp, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeAgent {
|
||||
return nil, errors.New(errors.CodeForbidden, "仅代理商用户可访问")
|
||||
}
|
||||
|
||||
shopID := middleware.GetShopIDFromContext(ctx)
|
||||
if shopID == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无法获取店铺信息")
|
||||
}
|
||||
|
||||
shop, err := s.shopStore.GetByID(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||||
}
|
||||
|
||||
// 使用 GetCommissionWallet 获取店铺佣金钱包
|
||||
wallet, err := s.agentWalletStore.GetCommissionWallet(ctx, shopID)
|
||||
if err != nil {
|
||||
// 钱包不存在时返回空数据
|
||||
return &dto.MyCommissionSummaryResp{
|
||||
ShopID: shopID,
|
||||
ShopName: shop.ShopName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 计算累计佣金(当前余额 + 冻结余额 + 已提现金额)
|
||||
// 由于 Wallet 模型没有 TotalIncome、TotalWithdrawn 字段,
|
||||
// 我们需要从 WalletTransaction 表计算或简化处理
|
||||
var totalWithdrawn int64
|
||||
s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Where("shop_id = ? AND status IN ?", shopID, []int{2, 4}). // 已通过或已到账
|
||||
Select("COALESCE(SUM(actual_amount), 0)").Scan(&totalWithdrawn)
|
||||
|
||||
totalCommission := wallet.Balance + wallet.FrozenBalance + totalWithdrawn
|
||||
|
||||
return &dto.MyCommissionSummaryResp{
|
||||
ShopID: shopID,
|
||||
ShopName: shop.ShopName,
|
||||
TotalCommission: totalCommission,
|
||||
WithdrawnCommission: totalWithdrawn,
|
||||
UnwithdrawCommission: wallet.Balance + wallet.FrozenBalance,
|
||||
FrozenCommission: wallet.FrozenBalance,
|
||||
WithdrawingCommission: wallet.FrozenBalance, // 提现中的金额等于冻结金额
|
||||
AvailableCommission: wallet.Balance,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateWithdrawalRequest 发起提现申请
|
||||
func (s *Service) CreateWithdrawalRequest(ctx context.Context, req *dto.CreateMyWithdrawalReq) (*dto.CreateMyWithdrawalResp, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeAgent {
|
||||
return nil, errors.New(errors.CodeForbidden, "仅代理商用户可访问")
|
||||
}
|
||||
|
||||
shopID := middleware.GetShopIDFromContext(ctx)
|
||||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||||
if shopID == 0 || currentUserID == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无法获取用户信息")
|
||||
}
|
||||
|
||||
// 获取提现配置
|
||||
setting, err := s.commissionWithdrawalSettingStore.GetCurrent(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "暂未开放提现功能")
|
||||
}
|
||||
|
||||
// 验证最低提现金额
|
||||
if req.Amount < setting.MinWithdrawalAmount {
|
||||
return nil, errors.New(errors.CodeInvalidParam, fmt.Sprintf("提现金额不能低于 %.2f 元", float64(setting.MinWithdrawalAmount)/100))
|
||||
}
|
||||
|
||||
// 获取钱包
|
||||
wallet, err := s.agentWalletStore.GetCommissionWallet(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeInsufficientBalance, "钱包不存在")
|
||||
}
|
||||
|
||||
// 验证可用余额(balance - frozen_balance),冻结中的金额不可再次提现
|
||||
if req.Amount > wallet.GetAvailableBalance() {
|
||||
return nil, errors.New(errors.CodeInsufficientBalance, "可提现余额不足")
|
||||
}
|
||||
|
||||
// 验证今日提现次数
|
||||
today := time.Now().Format("2006-01-02")
|
||||
todayStart := today + " 00:00:00"
|
||||
todayEnd := today + " 23:59:59"
|
||||
var todayCount int64
|
||||
s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Where("shop_id = ? AND created_at >= ? AND created_at <= ?", shopID, todayStart, todayEnd).
|
||||
Count(&todayCount)
|
||||
if int(todayCount) >= setting.DailyWithdrawalLimit {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "今日提现次数已达上限")
|
||||
}
|
||||
|
||||
// 计算手续费
|
||||
fee := req.Amount * setting.FeeRate / 10000
|
||||
actualAmount := req.Amount - fee
|
||||
|
||||
// 生成提现单号
|
||||
withdrawalNo := generateWithdrawalNo()
|
||||
|
||||
// 构建账户信息 JSON
|
||||
accountInfo := map[string]string{
|
||||
"account_name": req.AccountName,
|
||||
"account_number": req.AccountNumber,
|
||||
}
|
||||
accountInfoJSON, _ := json.Marshal(accountInfo)
|
||||
|
||||
var withdrawalRequest *model.CommissionWithdrawalRequest
|
||||
|
||||
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 冻结余额:只增加 frozen_balance,balance(总额)不变
|
||||
// balance = 总余额,frozen_balance = 其中被锁定的子集,可用余额 = balance - frozen_balance
|
||||
// 使用条件更新 + RowsAffected 校验,防止并发重复提现
|
||||
result := tx.WithContext(ctx).Model(&model.AgentWallet{}).
|
||||
Where("id = ? AND balance - frozen_balance >= ?", wallet.ID, req.Amount).
|
||||
Updates(map[string]interface{}{
|
||||
"frozen_balance": gorm.Expr("frozen_balance + ?", req.Amount),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, result.Error, "冻结余额失败")
|
||||
}
|
||||
// RowsAffected == 0 说明余额已不足(并发场景下被其他请求先行扣减)
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New(errors.CodeInsufficientBalance, "余额不足或并发冲突,请稍后重试")
|
||||
}
|
||||
|
||||
// 创建提现申请
|
||||
withdrawalRequest = &model.CommissionWithdrawalRequest{
|
||||
WithdrawalNo: withdrawalNo,
|
||||
ShopID: shopID,
|
||||
ApplicantID: currentUserID,
|
||||
Amount: req.Amount,
|
||||
FeeRate: setting.FeeRate,
|
||||
Fee: fee,
|
||||
ActualAmount: actualAmount,
|
||||
WithdrawalMethod: req.WithdrawalMethod,
|
||||
AccountInfo: accountInfoJSON,
|
||||
Status: 1, // 待审核
|
||||
}
|
||||
withdrawalRequest.Creator = currentUserID
|
||||
withdrawalRequest.Updater = currentUserID
|
||||
|
||||
if err := tx.WithContext(ctx).Create(withdrawalRequest).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "创建提现申请失败")
|
||||
}
|
||||
|
||||
// 创建钱包流水记录
|
||||
remark := fmt.Sprintf("提现冻结,单号:%s", withdrawalNo)
|
||||
refType := constants.ReferenceTypeWithdrawal
|
||||
transaction := &model.AgentWalletTransaction{
|
||||
AgentWalletID: wallet.ID,
|
||||
ShopID: shopID,
|
||||
UserID: currentUserID,
|
||||
TransactionType: constants.TransactionTypeWithdrawal,
|
||||
Amount: -req.Amount, // 冻结为负数
|
||||
BalanceBefore: wallet.Balance,
|
||||
BalanceAfter: wallet.Balance - req.Amount,
|
||||
Status: constants.TransactionStatusProcessing, // 处理中
|
||||
ReferenceType: &refType,
|
||||
ReferenceID: &withdrawalRequest.ID,
|
||||
Remark: &remark,
|
||||
Creator: currentUserID,
|
||||
ShopIDTag: shopID,
|
||||
}
|
||||
|
||||
if err := tx.WithContext(ctx).Create(transaction).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "创建钱包流水失败")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dto.CreateMyWithdrawalResp{
|
||||
ID: withdrawalRequest.ID,
|
||||
WithdrawalNo: withdrawalRequest.WithdrawalNo,
|
||||
Amount: withdrawalRequest.Amount,
|
||||
FeeRate: withdrawalRequest.FeeRate,
|
||||
Fee: withdrawalRequest.Fee,
|
||||
ActualAmount: withdrawalRequest.ActualAmount,
|
||||
Status: withdrawalRequest.Status,
|
||||
StatusName: getWithdrawalStatusName(withdrawalRequest.Status),
|
||||
CreatedAt: withdrawalRequest.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListMyWithdrawalRequests 查询提现记录
|
||||
// 代理账号:仅查询本店铺数据;平台账号/超级管理员:查询全部数据
|
||||
func (s *Service) ListMyWithdrawalRequests(ctx context.Context, req *dto.MyWithdrawalListReq) (*dto.WithdrawalRequestPageResult, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
|
||||
// 仅允许超级管理员、平台账号、代理账号访问
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform && userType != constants.UserTypeAgent {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限访问提现记录")
|
||||
}
|
||||
|
||||
page := req.Page
|
||||
pageSize := req.PageSize
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
|
||||
query := s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{})
|
||||
|
||||
// 代理账号按店铺过滤;平台账号和超级管理员查看全部
|
||||
if userType == constants.UserTypeAgent {
|
||||
shopID := middleware.GetShopIDFromContext(ctx)
|
||||
if shopID == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无法获取店铺信息")
|
||||
}
|
||||
query = query.Where("shop_id = ?", shopID)
|
||||
}
|
||||
|
||||
if req.Status != nil {
|
||||
query = query.Where("status = ?", *req.Status)
|
||||
}
|
||||
if req.StartTime != "" {
|
||||
query = query.Where("created_at >= ?", req.StartTime)
|
||||
}
|
||||
if req.EndTime != "" {
|
||||
query = query.Where("created_at <= ?", req.EndTime)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "统计提现记录失败")
|
||||
}
|
||||
|
||||
var requests []model.CommissionWithdrawalRequest
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&requests).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询提现记录失败")
|
||||
}
|
||||
|
||||
items := make([]dto.WithdrawalRequestItem, 0, len(requests))
|
||||
for _, r := range requests {
|
||||
// 解析账户信息
|
||||
accountName, accountNumber := parseAccountInfo(r.AccountInfo)
|
||||
|
||||
items = append(items, dto.WithdrawalRequestItem{
|
||||
ID: r.ID,
|
||||
WithdrawalNo: r.WithdrawalNo,
|
||||
ShopID: r.ShopID,
|
||||
Amount: r.Amount,
|
||||
FeeRate: r.FeeRate,
|
||||
Fee: r.Fee,
|
||||
ActualAmount: r.ActualAmount,
|
||||
WithdrawalMethod: r.WithdrawalMethod,
|
||||
AccountName: accountName,
|
||||
AccountNumber: accountNumber,
|
||||
Status: r.Status,
|
||||
StatusName: getWithdrawalStatusName(r.Status),
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
return &dto.WithdrawalRequestPageResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListMyCommissionRecords 查询佣金明细
|
||||
// 代理账号:仅查询本店铺数据;平台账号/超级管理员:查询全部数据
|
||||
func (s *Service) ListMyCommissionRecords(ctx context.Context, req *dto.MyCommissionRecordListReq) (*dto.MyCommissionRecordPageResult, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
|
||||
// 仅允许超级管理员、平台账号、代理账号访问
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform && userType != constants.UserTypeAgent {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限访问佣金明细")
|
||||
}
|
||||
|
||||
page := req.Page
|
||||
pageSize := req.PageSize
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
|
||||
query := s.db.WithContext(ctx).Model(&model.CommissionRecord{})
|
||||
|
||||
// 代理账号按店铺过滤;平台账号和超级管理员查看全部
|
||||
if userType == constants.UserTypeAgent {
|
||||
shopID := middleware.GetShopIDFromContext(ctx)
|
||||
if shopID == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无法获取店铺信息")
|
||||
}
|
||||
query = query.Where("shop_id = ?", shopID)
|
||||
}
|
||||
|
||||
if req.CommissionSource != nil {
|
||||
query = query.Where("commission_source = ?", *req.CommissionSource)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "统计佣金记录失败")
|
||||
}
|
||||
|
||||
var records []model.CommissionRecord
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询佣金记录失败")
|
||||
}
|
||||
|
||||
items := make([]dto.MyCommissionRecordItem, 0, len(records))
|
||||
for _, r := range records {
|
||||
items = append(items, dto.MyCommissionRecordItem{
|
||||
ID: r.ID,
|
||||
ShopID: r.ShopID,
|
||||
OrderID: r.OrderID,
|
||||
CommissionSource: r.CommissionSource,
|
||||
Amount: r.Amount,
|
||||
Status: r.Status,
|
||||
StatusName: getCommissionStatusName(r.Status),
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
return &dto.MyCommissionRecordPageResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetStats(ctx context.Context, req *dto.CommissionStatsRequest) (*dto.CommissionStatsResponse, error) {
|
||||
shopID, err := s.getShopIDFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
filters := &postgres.CommissionRecordListFilters{
|
||||
ShopID: shopID,
|
||||
StartTime: req.StartTime,
|
||||
EndTime: req.EndTime,
|
||||
}
|
||||
|
||||
stats, err := s.commissionRecordStore.GetStats(ctx, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "获取佣金统计失败")
|
||||
}
|
||||
|
||||
if stats == nil {
|
||||
return &dto.CommissionStatsResponse{}, nil
|
||||
}
|
||||
|
||||
var costDiffPercent, oneTimePercent int64
|
||||
if stats.TotalAmount > 0 {
|
||||
costDiffPercent = stats.CostDiffAmount * 1000 / stats.TotalAmount
|
||||
oneTimePercent = stats.OneTimeAmount * 1000 / stats.TotalAmount
|
||||
}
|
||||
|
||||
return &dto.CommissionStatsResponse{
|
||||
TotalAmount: stats.TotalAmount,
|
||||
CostDiffAmount: stats.CostDiffAmount,
|
||||
OneTimeAmount: stats.OneTimeAmount,
|
||||
CostDiffPercent: costDiffPercent,
|
||||
OneTimePercent: oneTimePercent,
|
||||
TotalCount: stats.TotalCount,
|
||||
CostDiffCount: stats.CostDiffCount,
|
||||
OneTimeCount: stats.OneTimeCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetDailyStats(ctx context.Context, req *dto.DailyCommissionStatsRequest) ([]*dto.DailyCommissionStatsResponse, error) {
|
||||
shopID, err := s.getShopIDFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
days := 30
|
||||
if req.Days != nil && *req.Days > 0 {
|
||||
days = *req.Days
|
||||
}
|
||||
|
||||
filters := &postgres.CommissionRecordListFilters{
|
||||
ShopID: shopID,
|
||||
StartTime: req.StartDate,
|
||||
EndTime: req.EndDate,
|
||||
}
|
||||
|
||||
dailyStats, err := s.commissionRecordStore.GetDailyStats(ctx, filters, days)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "获取每日佣金统计失败")
|
||||
}
|
||||
|
||||
result := make([]*dto.DailyCommissionStatsResponse, 0, len(dailyStats))
|
||||
for _, stat := range dailyStats {
|
||||
result = append(result, &dto.DailyCommissionStatsResponse{
|
||||
Date: stat.Date,
|
||||
TotalAmount: stat.TotalAmount,
|
||||
TotalCount: stat.TotalCount,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) getShopIDFromContext(ctx context.Context) (uint, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeAgent {
|
||||
return 0, errors.New(errors.CodeForbidden, "仅代理商用户可访问")
|
||||
}
|
||||
|
||||
shopID := middleware.GetShopIDFromContext(ctx)
|
||||
if shopID == 0 {
|
||||
return 0, errors.New(errors.CodeForbidden, "无法获取店铺信息")
|
||||
}
|
||||
|
||||
return shopID, nil
|
||||
}
|
||||
|
||||
// generateWithdrawalNo 生成提现单号
|
||||
func generateWithdrawalNo() string {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("W%s%04d", now.Format("20060102150405"), rand.Intn(10000))
|
||||
}
|
||||
|
||||
// getWithdrawalStatusName 获取提现状态名称
|
||||
func getWithdrawalStatusName(status int) string {
|
||||
switch status {
|
||||
case 1:
|
||||
return "待审核"
|
||||
case 2:
|
||||
return "已通过"
|
||||
case 3:
|
||||
return "已拒绝"
|
||||
case 4:
|
||||
return "已到账"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// getCommissionStatusName 获取佣金状态名称
|
||||
func getCommissionStatusName(status int) string {
|
||||
switch status {
|
||||
case 1:
|
||||
return "已冻结"
|
||||
case 2:
|
||||
return "解冻中"
|
||||
case 3:
|
||||
return "已发放"
|
||||
case 4:
|
||||
return "已失效"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// parseAccountInfo 解析账户信息 JSON
|
||||
func parseAccountInfo(data []byte) (accountName, accountNumber string) {
|
||||
if len(data) == 0 {
|
||||
return "", ""
|
||||
}
|
||||
var info map[string]string
|
||||
if err := json.Unmarshal(data, &info); err != nil {
|
||||
return "", ""
|
||||
}
|
||||
return info["account_name"], info["account_number"]
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package shop_commission
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
@@ -11,41 +13,52 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service 代理商资金管理服务
|
||||
type Service struct {
|
||||
shopStore *postgres.ShopStore
|
||||
accountStore *postgres.AccountStore
|
||||
agentWalletStore *postgres.AgentWalletStore
|
||||
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
shopStore *postgres.ShopStore
|
||||
accountStore *postgres.AccountStore
|
||||
agentWalletStore *postgres.AgentWalletStore
|
||||
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore
|
||||
commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
agentWalletTransactionStore *postgres.AgentWalletTransactionStore
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// New 创建代理商资金管理服务
|
||||
func New(
|
||||
shopStore *postgres.ShopStore,
|
||||
accountStore *postgres.AccountStore,
|
||||
agentWalletStore *postgres.AgentWalletStore,
|
||||
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore,
|
||||
commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore,
|
||||
commissionRecordStore *postgres.CommissionRecordStore,
|
||||
agentWalletTransactionStore *postgres.AgentWalletTransactionStore,
|
||||
db *gorm.DB,
|
||||
logger *zap.Logger,
|
||||
) *Service {
|
||||
return &Service{
|
||||
shopStore: shopStore,
|
||||
accountStore: accountStore,
|
||||
agentWalletStore: agentWalletStore,
|
||||
commissionWithdrawalReqStore: commissionWithdrawalReqStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
db: db,
|
||||
logger: logger,
|
||||
shopStore: shopStore,
|
||||
accountStore: accountStore,
|
||||
agentWalletStore: agentWalletStore,
|
||||
commissionWithdrawalReqStore: commissionWithdrawalReqStore,
|
||||
commissionWithdrawalSettingStore: commissionWithdrawalSettingStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
agentWalletTransactionStore: agentWalletTransactionStore,
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCommissionSummaryListReq) (*dto.ShopCommissionSummaryPageResult, error) {
|
||||
// ListShopFundSummary 代理商资金概况列表(含预充值余额和佣金钱包)
|
||||
// GET /shops/fund-summary
|
||||
func (s *Service) ListShopFundSummary(ctx context.Context, req *dto.ShopFundSummaryListReq) (*dto.ShopFundSummaryPageResult, error) {
|
||||
opts := &store.QueryOptions{
|
||||
Page: req.Page,
|
||||
PageSize: req.PageSize,
|
||||
@@ -69,8 +82,8 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}
|
||||
|
||||
if len(shops) == 0 {
|
||||
return &dto.ShopCommissionSummaryPageResult{
|
||||
Items: []dto.ShopCommissionSummaryItem{},
|
||||
return &dto.ShopFundSummaryPageResult{
|
||||
Items: []dto.ShopFundSummaryItem{},
|
||||
Total: 0,
|
||||
Page: opts.Page,
|
||||
Size: opts.PageSize,
|
||||
@@ -82,6 +95,12 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
shopIDs = append(shopIDs, shop.ID)
|
||||
}
|
||||
|
||||
// 批量获取主钱包(预充值钱包)余额
|
||||
mainWallets, err := s.agentWalletStore.GetShopMainWalletBatch(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询主钱包余额失败")
|
||||
}
|
||||
|
||||
walletSummaries, err := s.agentWalletStore.GetShopCommissionSummaryBatch(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询店铺钱包汇总失败")
|
||||
@@ -109,7 +128,7 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]dto.ShopCommissionSummaryItem, 0, len(shops))
|
||||
items := make([]dto.ShopFundSummaryItem, 0, len(shops))
|
||||
for _, shop := range shops {
|
||||
if req.Username != "" {
|
||||
acc := accountMap[shop.ID]
|
||||
@@ -119,11 +138,11 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}
|
||||
}
|
||||
|
||||
item := s.buildCommissionSummaryItem(shop, walletSummaries[shop.ID], withdrawnAmounts[shop.ID], withdrawingAmounts[shop.ID], accountMap[shop.ID])
|
||||
item := s.buildFundSummaryItem(shop, mainWallets[shop.ID], walletSummaries[shop.ID], withdrawnAmounts[shop.ID], withdrawingAmounts[shop.ID], accountMap[shop.ID])
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return &dto.ShopCommissionSummaryPageResult{
|
||||
return &dto.ShopFundSummaryPageResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: opts.Page,
|
||||
@@ -131,11 +150,20 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) buildCommissionSummaryItem(shop *model.Shop, walletSummary *model.AgentWallet, withdrawnAmount, withdrawingAmount int64, account *model.Account) dto.ShopCommissionSummaryItem {
|
||||
// buildFundSummaryItem 构造资金概况条目
|
||||
func (s *Service) buildFundSummaryItem(shop *model.Shop, mainWallet, commissionWallet *model.AgentWallet, withdrawnAmount, withdrawingAmount int64, account *model.Account) dto.ShopFundSummaryItem {
|
||||
// 主钱包余额(若未充值则为0)
|
||||
var mainBalance, mainFrozenBalance int64
|
||||
if mainWallet != nil {
|
||||
mainBalance = mainWallet.Balance
|
||||
mainFrozenBalance = mainWallet.FrozenBalance
|
||||
}
|
||||
|
||||
// 佣金钱包
|
||||
var balance, frozenBalance int64
|
||||
if walletSummary != nil {
|
||||
balance = walletSummary.Balance
|
||||
frozenBalance = walletSummary.FrozenBalance
|
||||
if commissionWallet != nil {
|
||||
balance = commissionWallet.Balance
|
||||
frozenBalance = commissionWallet.FrozenBalance
|
||||
}
|
||||
|
||||
totalCommission := balance + frozenBalance + withdrawnAmount
|
||||
@@ -151,12 +179,14 @@ func (s *Service) buildCommissionSummaryItem(shop *model.Shop, walletSummary *mo
|
||||
phone = account.Phone
|
||||
}
|
||||
|
||||
return dto.ShopCommissionSummaryItem{
|
||||
return dto.ShopFundSummaryItem{
|
||||
ShopID: shop.ID,
|
||||
ShopName: shop.ShopName,
|
||||
ShopCode: shop.ShopCode,
|
||||
Username: username,
|
||||
Phone: phone,
|
||||
MainBalance: mainBalance,
|
||||
MainFrozenBalance: mainFrozenBalance,
|
||||
TotalCommission: totalCommission,
|
||||
WithdrawnCommission: withdrawnAmount,
|
||||
UnwithdrawCommission: unwithdrawCommission,
|
||||
@@ -167,7 +197,14 @@ func (s *Service) buildCommissionSummaryItem(shop *model.Shop, walletSummary *mo
|
||||
}
|
||||
}
|
||||
|
||||
// ListShopWithdrawalRequests 查询代理商提现记录
|
||||
// GET /shops/:id/withdrawal-requests
|
||||
func (s *Service) ListShopWithdrawalRequests(ctx context.Context, shopID uint, req *dto.ShopWithdrawalRequestListReq) (*dto.ShopWithdrawalRequestPageResult, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
_, err := s.shopStore.GetByID(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||||
@@ -252,6 +289,7 @@ func (s *Service) ListShopWithdrawalRequests(ctx context.Context, shopID uint, r
|
||||
}, nil
|
||||
}
|
||||
|
||||
// buildWithdrawalRequestItem 构造提现记录条目
|
||||
func (s *Service) buildWithdrawalRequestItem(r *model.CommissionWithdrawalRequest, shopName, shopHierarchy string, applicantMap, processorMap map[uint]string) dto.ShopWithdrawalRequestItem {
|
||||
var processorID *uint
|
||||
if r.ProcessorID > 0 {
|
||||
@@ -311,6 +349,7 @@ func (s *Service) buildWithdrawalRequestItem(r *model.CommissionWithdrawalReques
|
||||
}
|
||||
}
|
||||
|
||||
// buildShopHierarchyPath 构造店铺层级路径(最多两层上级)
|
||||
func (s *Service) buildShopHierarchyPath(ctx context.Context, shop *model.Shop) string {
|
||||
if shop == nil {
|
||||
return ""
|
||||
@@ -333,7 +372,14 @@ func (s *Service) buildShopHierarchyPath(ctx context.Context, shop *model.Shop)
|
||||
return path
|
||||
}
|
||||
|
||||
// ListShopCommissionRecords 查询代理商佣金明细
|
||||
// GET /shops/:id/commission-records
|
||||
func (s *Service) ListShopCommissionRecords(ctx context.Context, shopID uint, req *dto.ShopCommissionRecordListReq) (*dto.ShopCommissionRecordPageResult, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
_, err := s.shopStore.GetByID(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||||
@@ -391,47 +437,292 @@ func (s *Service) ListShopCommissionRecords(ctx context.Context, shopID uint, re
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getWithdrawalStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.WithdrawalStatusPending:
|
||||
return "待审核"
|
||||
case constants.WithdrawalStatusApproved:
|
||||
return "已通过"
|
||||
case constants.WithdrawalStatusRejected:
|
||||
return "已拒绝"
|
||||
case constants.WithdrawalStatusPaid:
|
||||
return "已到账"
|
||||
default:
|
||||
return "未知"
|
||||
// GetStats 获取佣金统计
|
||||
// GET /shops/:id/commission-stats
|
||||
func (s *Service) GetStats(ctx context.Context, shopID uint, req *dto.CommissionStatsRequest) (*dto.CommissionStatsResponse, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
}
|
||||
|
||||
func getCommissionStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.CommissionStatusFrozen:
|
||||
return "已冻结"
|
||||
case constants.CommissionStatusUnfreezing:
|
||||
return "解冻中"
|
||||
case constants.CommissionStatusReleased:
|
||||
return "已发放"
|
||||
case constants.CommissionStatusInvalid:
|
||||
return "已失效"
|
||||
default:
|
||||
return "未知"
|
||||
filters := &postgres.CommissionRecordListFilters{
|
||||
ShopID: shopID,
|
||||
StartTime: req.StartTime,
|
||||
EndTime: req.EndTime,
|
||||
}
|
||||
|
||||
stats, err := s.commissionRecordStore.GetStats(ctx, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "获取佣金统计失败")
|
||||
}
|
||||
|
||||
if stats == nil {
|
||||
return &dto.CommissionStatsResponse{}, nil
|
||||
}
|
||||
|
||||
var costDiffPercent, oneTimePercent int64
|
||||
if stats.TotalAmount > 0 {
|
||||
costDiffPercent = stats.CostDiffAmount * 1000 / stats.TotalAmount
|
||||
oneTimePercent = stats.OneTimeAmount * 1000 / stats.TotalAmount
|
||||
}
|
||||
|
||||
return &dto.CommissionStatsResponse{
|
||||
TotalAmount: stats.TotalAmount,
|
||||
CostDiffAmount: stats.CostDiffAmount,
|
||||
OneTimeAmount: stats.OneTimeAmount,
|
||||
CostDiffPercent: costDiffPercent,
|
||||
OneTimePercent: oneTimePercent,
|
||||
TotalCount: stats.TotalCount,
|
||||
CostDiffCount: stats.CostDiffCount,
|
||||
OneTimeCount: stats.OneTimeCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func containsSubstring(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(substr) == 0 || (len(s) > 0 && len(substr) > 0 && contains(s, substr)))
|
||||
// GetDailyStats 获取每日佣金统计
|
||||
// GET /shops/:id/commission-daily-stats
|
||||
func (s *Service) GetDailyStats(ctx context.Context, shopID uint, req *dto.DailyCommissionStatsRequest) ([]*dto.DailyCommissionStatsResponse, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
days := 30
|
||||
if req.Days != nil && *req.Days > 0 {
|
||||
days = *req.Days
|
||||
}
|
||||
|
||||
filters := &postgres.CommissionRecordListFilters{
|
||||
ShopID: shopID,
|
||||
StartTime: req.StartDate,
|
||||
EndTime: req.EndDate,
|
||||
}
|
||||
|
||||
dailyStats, err := s.commissionRecordStore.GetDailyStats(ctx, filters, days)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "获取每日佣金统计失败")
|
||||
}
|
||||
|
||||
result := make([]*dto.DailyCommissionStatsResponse, 0, len(dailyStats))
|
||||
for _, stat := range dailyStats {
|
||||
result = append(result, &dto.DailyCommissionStatsResponse{
|
||||
Date: stat.Date,
|
||||
TotalAmount: stat.TotalAmount,
|
||||
TotalCount: stat.TotalCount,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
// CreateWithdrawalRequest 代理发起提现申请
|
||||
// POST /shops/:id/withdrawal-requests
|
||||
func (s *Service) CreateWithdrawalRequest(ctx context.Context, shopID uint, req *dto.CreateMyWithdrawalReq) (*dto.CreateMyWithdrawalResp, error) {
|
||||
// 提现权限比查询更严格:必须是代理账号本人操作,不允许平台人员或顶级代理替下级提现
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeAgent {
|
||||
return nil, errors.New(errors.CodeForbidden, "仅代理商用户可发起提现")
|
||||
}
|
||||
if shopID != middleware.GetShopIDFromContext(ctx) {
|
||||
return nil, errors.New(errors.CodeForbidden, "仅可为本人店铺发起提现")
|
||||
}
|
||||
|
||||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||||
if currentUserID == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无法获取用户信息")
|
||||
}
|
||||
|
||||
// 获取提现配置
|
||||
setting, err := s.commissionWithdrawalSettingStore.GetCurrent(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "暂未开放提现功能")
|
||||
}
|
||||
|
||||
// 验证最低提现金额
|
||||
if req.Amount < setting.MinWithdrawalAmount {
|
||||
return nil, errors.New(errors.CodeInvalidParam, fmt.Sprintf("提现金额不能低于 %.2f 元", float64(setting.MinWithdrawalAmount)/100))
|
||||
}
|
||||
|
||||
// 获取佣金钱包
|
||||
wallet, err := s.agentWalletStore.GetCommissionWallet(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeInsufficientBalance, "钱包不存在")
|
||||
}
|
||||
|
||||
// 验证可用余额
|
||||
if req.Amount > wallet.GetAvailableBalance() {
|
||||
return nil, errors.New(errors.CodeInsufficientBalance, "可提现余额不足")
|
||||
}
|
||||
|
||||
// 验证今日提现次数
|
||||
today := time.Now().Format("2006-01-02")
|
||||
var todayCount int64
|
||||
s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Where("shop_id = ? AND created_at >= ? AND created_at <= ?", shopID, today+" 00:00:00", today+" 23:59:59").
|
||||
Count(&todayCount)
|
||||
if int(todayCount) >= setting.DailyWithdrawalLimit {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "今日提现次数已达上限")
|
||||
}
|
||||
|
||||
// 计算手续费
|
||||
fee := req.Amount * setting.FeeRate / 10000
|
||||
actualAmount := req.Amount - fee
|
||||
withdrawalNo := generateWithdrawalNo()
|
||||
|
||||
accountInfo := map[string]string{
|
||||
"account_name": req.AccountName,
|
||||
"account_number": req.AccountNumber,
|
||||
}
|
||||
accountInfoJSON, _ := json.Marshal(accountInfo)
|
||||
|
||||
var withdrawalRequest *model.CommissionWithdrawalRequest
|
||||
|
||||
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 使用条件更新防并发
|
||||
result := tx.WithContext(ctx).Model(&model.AgentWallet{}).
|
||||
Where("id = ? AND balance - frozen_balance >= ?", wallet.ID, req.Amount).
|
||||
Updates(map[string]interface{}{
|
||||
"frozen_balance": gorm.Expr("frozen_balance + ?", req.Amount),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, result.Error, "冻结余额失败")
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New(errors.CodeInsufficientBalance, "余额不足或并发冲突,请稍后重试")
|
||||
}
|
||||
|
||||
withdrawalRequest = &model.CommissionWithdrawalRequest{
|
||||
WithdrawalNo: withdrawalNo,
|
||||
ShopID: shopID,
|
||||
ApplicantID: currentUserID,
|
||||
Amount: req.Amount,
|
||||
FeeRate: setting.FeeRate,
|
||||
Fee: fee,
|
||||
ActualAmount: actualAmount,
|
||||
WithdrawalMethod: req.WithdrawalMethod,
|
||||
AccountInfo: accountInfoJSON,
|
||||
Status: 1, // 待审核
|
||||
}
|
||||
withdrawalRequest.Creator = currentUserID
|
||||
withdrawalRequest.Updater = currentUserID
|
||||
|
||||
if err := tx.WithContext(ctx).Create(withdrawalRequest).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "创建提现申请失败")
|
||||
}
|
||||
|
||||
remark := fmt.Sprintf("提现冻结,单号:%s", withdrawalNo)
|
||||
refType := constants.ReferenceTypeWithdrawal
|
||||
transaction := &model.AgentWalletTransaction{
|
||||
AgentWalletID: wallet.ID,
|
||||
ShopID: shopID,
|
||||
UserID: currentUserID,
|
||||
TransactionType: constants.TransactionTypeWithdrawal,
|
||||
Amount: -req.Amount,
|
||||
BalanceBefore: wallet.Balance,
|
||||
BalanceAfter: wallet.Balance - req.Amount,
|
||||
Status: constants.TransactionStatusProcessing,
|
||||
ReferenceType: &refType,
|
||||
ReferenceID: &withdrawalRequest.ID,
|
||||
Remark: &remark,
|
||||
Creator: currentUserID,
|
||||
ShopIDTag: shopID,
|
||||
}
|
||||
|
||||
if err := tx.WithContext(ctx).Create(transaction).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "创建钱包流水失败")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return false
|
||||
|
||||
return &dto.CreateMyWithdrawalResp{
|
||||
ID: withdrawalRequest.ID,
|
||||
WithdrawalNo: withdrawalRequest.WithdrawalNo,
|
||||
Amount: withdrawalRequest.Amount,
|
||||
FeeRate: withdrawalRequest.FeeRate,
|
||||
Fee: withdrawalRequest.Fee,
|
||||
ActualAmount: withdrawalRequest.ActualAmount,
|
||||
Status: withdrawalRequest.Status,
|
||||
StatusName: getWithdrawalStatusName(withdrawalRequest.Status),
|
||||
CreatedAt: withdrawalRequest.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListMainWalletTransactions 查询代理主钱包(预充值钱包)流水
|
||||
// GET /shops/:id/main-wallet/transactions
|
||||
func (s *Service) ListMainWalletTransactions(ctx context.Context, shopID uint, req *dto.MainWalletTransactionListRequest) (*dto.MainWalletTransactionListResponse, error) {
|
||||
// 越权校验
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
page := req.Page
|
||||
pageSize := req.PageSize
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
|
||||
// 获取主钱包,不存在则返回空列表
|
||||
mainWallet, err := s.agentWalletStore.GetMainWallet(ctx, shopID)
|
||||
if err != nil {
|
||||
return &dto.MainWalletTransactionListResponse{
|
||||
Items: []dto.MainWalletTransactionItem{},
|
||||
Total: 0,
|
||||
Page: page,
|
||||
Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
filters := &postgres.AgentWalletTransactionListFilters{
|
||||
TransactionType: req.TransactionType,
|
||||
StartDate: req.StartDate,
|
||||
EndDate: req.EndDate,
|
||||
}
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
transactions, err := s.agentWalletTransactionStore.ListByWalletIDWithFilters(ctx, mainWallet.ID, offset, pageSize, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询主钱包流水失败")
|
||||
}
|
||||
|
||||
total, err := s.agentWalletTransactionStore.CountByWalletID(ctx, mainWallet.ID, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "统计主钱包流水失败")
|
||||
}
|
||||
|
||||
items := make([]dto.MainWalletTransactionItem, 0, len(transactions))
|
||||
for _, t := range transactions {
|
||||
var remark string
|
||||
if t.Remark != nil {
|
||||
remark = *t.Remark
|
||||
}
|
||||
var subtype string
|
||||
if t.TransactionSubtype != nil {
|
||||
subtype = *t.TransactionSubtype
|
||||
}
|
||||
items = append(items, dto.MainWalletTransactionItem{
|
||||
ID: t.ID,
|
||||
TransactionType: t.TransactionType,
|
||||
TransactionSubtype: subtype,
|
||||
Amount: t.Amount,
|
||||
BalanceBefore: t.BalanceBefore,
|
||||
BalanceAfter: t.BalanceAfter,
|
||||
Remark: remark,
|
||||
CreatedAt: t.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
return &dto.MainWalletTransactionListResponse{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ResolveCommissionRecord 修正待审佣金记录(status=99)
|
||||
@@ -472,7 +763,6 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
}
|
||||
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 更新佣金记录
|
||||
if err := s.commissionRecordStore.UpdateByID(ctx, tx, recordID, map[string]any{
|
||||
"status": model.CommissionStatusReleased,
|
||||
"amount": amount,
|
||||
@@ -482,7 +772,6 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新佣金记录失败")
|
||||
}
|
||||
|
||||
// 入账到佣金钱包(乐观锁)
|
||||
balanceBefore := wallet.Balance
|
||||
result := tx.Model(&model.AgentWallet{}).
|
||||
Where("id = ? AND version = ?", wallet.ID, wallet.Version).
|
||||
@@ -497,7 +786,6 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
return errors.New(errors.CodeInternalError, "佣金钱包版本冲突,请重试")
|
||||
}
|
||||
|
||||
// 回写入账后余额
|
||||
if err := s.commissionRecordStore.UpdateByID(ctx, tx, recordID, map[string]any{
|
||||
"balance_after": balanceBefore + amount,
|
||||
}); err != nil {
|
||||
@@ -507,3 +795,54 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// getWithdrawalStatusName 获取提现状态名称
|
||||
func getWithdrawalStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.WithdrawalStatusPending:
|
||||
return "待审核"
|
||||
case constants.WithdrawalStatusApproved:
|
||||
return "已通过"
|
||||
case constants.WithdrawalStatusRejected:
|
||||
return "已拒绝"
|
||||
case constants.WithdrawalStatusPaid:
|
||||
return "已到账"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// getCommissionStatusName 获取佣金状态名称
|
||||
func getCommissionStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.CommissionStatusFrozen:
|
||||
return "已冻结"
|
||||
case constants.CommissionStatusUnfreezing:
|
||||
return "解冻中"
|
||||
case constants.CommissionStatusReleased:
|
||||
return "已发放"
|
||||
case constants.CommissionStatusInvalid:
|
||||
return "已失效"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// generateWithdrawalNo 生成提现单号
|
||||
func generateWithdrawalNo() string {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("W%s%04d", now.Format("20060102150405"), rand.Intn(10000))
|
||||
}
|
||||
|
||||
func containsSubstring(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(substr) == 0 || (len(s) > 0 && len(substr) > 0 && contains(s, substr)))
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -233,6 +233,31 @@ func (s *AgentWalletStore) GetShopCommissionSummaryBatch(ctx context.Context, sh
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetShopMainWalletBatch 批量获取店铺主钱包(预充值钱包)
|
||||
// 返回 map[shopID]*AgentWallet,未找到的店铺不会出现在结果中
|
||||
func (s *AgentWalletStore) GetShopMainWalletBatch(ctx context.Context, shopIDs []uint) (map[uint]*model.AgentWallet, error) {
|
||||
if len(shopIDs) == 0 {
|
||||
return make(map[uint]*model.AgentWallet), nil
|
||||
}
|
||||
|
||||
var wallets []model.AgentWallet
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("shop_id IN ? AND wallet_type = ?", shopIDs, constants.AgentWalletTypeMain)
|
||||
// 对齐 GetShopCommissionSummaryBatch 的防御式过滤
|
||||
query = middleware.ApplyShopFilter(ctx, query)
|
||||
err := query.Find(&wallets).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make(map[uint]*model.AgentWallet, len(wallets))
|
||||
for i := range wallets {
|
||||
result[wallets[i].ShopID] = &wallets[i]
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// clearWalletCache 清除钱包缓存
|
||||
func (s *AgentWalletStore) clearWalletCache(ctx context.Context, walletID uint) {
|
||||
// 查询钱包信息以获取 shop_id 和 wallet_type
|
||||
|
||||
@@ -4,7 +4,6 @@ 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"
|
||||
)
|
||||
@@ -23,36 +22,39 @@ func NewAgentWalletTransactionStore(db *gorm.DB, redis *redis.Client) *AgentWall
|
||||
}
|
||||
}
|
||||
|
||||
// AgentWalletTransactionListFilters 主钱包流水过滤条件
|
||||
type AgentWalletTransactionListFilters struct {
|
||||
// TransactionType 按交易类型过滤,空字符串表示不过滤
|
||||
TransactionType string
|
||||
// StartDate 开始日期,格式 YYYY-MM-DD
|
||||
StartDate string
|
||||
// EndDate 结束日期,格式 YYYY-MM-DD
|
||||
EndDate string
|
||||
}
|
||||
|
||||
// CreateWithTx 创建代理钱包交易记录(带事务)
|
||||
func (s *AgentWalletTransactionStore) CreateWithTx(ctx context.Context, tx *gorm.DB, transaction *model.AgentWalletTransaction) error {
|
||||
return tx.WithContext(ctx).Create(transaction).Error
|
||||
}
|
||||
|
||||
// ListByShopID 按店铺查询交易记录(支持分页)
|
||||
func (s *AgentWalletTransactionStore) ListByShopID(ctx context.Context, shopID uint, offset, limit int) ([]*model.AgentWalletTransaction, error) {
|
||||
// ListByWalletIDWithFilters 按钱包ID查询交易记录(支持分页和过滤)
|
||||
// 按 created_at DESC 排序
|
||||
func (s *AgentWalletTransactionStore) ListByWalletIDWithFilters(ctx context.Context, walletID uint, offset, limit int, filters *AgentWalletTransactionListFilters) ([]*model.AgentWalletTransaction, error) {
|
||||
var transactions []*model.AgentWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("shop_id = ?", shopID)
|
||||
// 应用数据权限过滤
|
||||
query = middleware.ApplyShopFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
query := s.db.WithContext(ctx).Where("agent_wallet_id = ?", walletID)
|
||||
query = applyWalletTransactionFilters(query, filters)
|
||||
err := query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transactions, nil
|
||||
}
|
||||
|
||||
// CountByShopID 统计店铺的交易记录数量
|
||||
func (s *AgentWalletTransactionStore) CountByShopID(ctx context.Context, shopID uint) (int64, error) {
|
||||
// CountByWalletID 统计指定钱包的交易记录数量(支持过滤)
|
||||
func (s *AgentWalletTransactionStore) CountByWalletID(ctx context.Context, walletID uint, filters *AgentWalletTransactionListFilters) (int64, error) {
|
||||
var count int64
|
||||
query := s.db.WithContext(ctx).
|
||||
Model(&model.AgentWalletTransaction{}).
|
||||
Where("shop_id = ?", shopID)
|
||||
// 应用数据权限过滤
|
||||
query = middleware.ApplyShopFilter(ctx, query)
|
||||
query := s.db.WithContext(ctx).Model(&model.AgentWalletTransaction{}).Where("agent_wallet_id = ?", walletID)
|
||||
query = applyWalletTransactionFilters(query, filters)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -60,14 +62,8 @@ func (s *AgentWalletTransactionStore) CountByShopID(ctx context.Context, shopID
|
||||
// ListByWalletID 按钱包查询交易记录(支持分页)
|
||||
func (s *AgentWalletTransactionStore) ListByWalletID(ctx context.Context, walletID uint, offset, limit int) ([]*model.AgentWalletTransaction, error) {
|
||||
var transactions []*model.AgentWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("agent_wallet_id = ?", walletID)
|
||||
// 应用数据权限过滤
|
||||
query = middleware.ApplyShopFilter(ctx, query)
|
||||
err := query.Order("created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&transactions).Error
|
||||
query := s.db.WithContext(ctx).Where("agent_wallet_id = ?", walletID)
|
||||
err := query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&transactions).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -77,13 +73,27 @@ func (s *AgentWalletTransactionStore) ListByWalletID(ctx context.Context, wallet
|
||||
// GetByReference 根据关联业务查询交易记录
|
||||
func (s *AgentWalletTransactionStore) GetByReference(ctx context.Context, referenceType string, referenceID uint) (*model.AgentWalletTransaction, error) {
|
||||
var transaction model.AgentWalletTransaction
|
||||
query := s.db.WithContext(ctx).
|
||||
Where("reference_type = ? AND reference_id = ?", referenceType, referenceID)
|
||||
// 应用数据权限过滤
|
||||
query = middleware.ApplyShopFilter(ctx, query)
|
||||
query := s.db.WithContext(ctx).Where("reference_type = ? AND reference_id = ?", referenceType, referenceID)
|
||||
err := query.First(&transaction).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transaction, nil
|
||||
}
|
||||
|
||||
// applyWalletTransactionFilters 应用过滤条件到查询
|
||||
func applyWalletTransactionFilters(query *gorm.DB, filters *AgentWalletTransactionListFilters) *gorm.DB {
|
||||
if filters == nil {
|
||||
return query
|
||||
}
|
||||
if filters.TransactionType != "" {
|
||||
query = query.Where("transaction_type = ?", filters.TransactionType)
|
||||
}
|
||||
if filters.StartDate != "" {
|
||||
query = query.Where("created_at >= ?", filters.StartDate+" 00:00:00")
|
||||
}
|
||||
if filters.EndDate != "" {
|
||||
query = query.Where("created_at <= ?", filters.EndDate+" 23:59:59")
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
2
openspec/changes/agent-fund-visibility/.openspec.yaml
Normal file
2
openspec/changes/agent-fund-visibility/.openspec.yaml
Normal file
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-04-09
|
||||
188
openspec/changes/agent-fund-visibility/design.md
Normal file
188
openspec/changes/agent-fund-visibility/design.md
Normal file
@@ -0,0 +1,188 @@
|
||||
## Context
|
||||
|
||||
### 现状
|
||||
|
||||
系统中代理钱包有两种类型(`tb_agent_wallet`):
|
||||
- `wallet_type=main`:预充值钱包,代理购买套餐时扣款
|
||||
- `wallet_type=commission`:佣金钱包,订单完成后自动入账、可提现
|
||||
|
||||
当前 `/shops/commission-summary` 仅聚合佣金钱包数据,主钱包完全不可见。代理自己的操作路径依赖 `/my/` 前缀系列接口,与平台视角的 `/shops/:id/` 系列存在职责重叠,产生维护成本。
|
||||
|
||||
### 已有可复用能力
|
||||
|
||||
| 组件 | 方法 | 状态 |
|
||||
|------|------|------|
|
||||
| `AgentWalletStore` | `GetMainWallet(shopID)` | 已有,单条查询 |
|
||||
| `AgentWalletStore` | `GetShopCommissionSummaryBatch(shopIDs)` | 已有,批量查佣金钱包 |
|
||||
| `AgentWalletTransactionStore` | `ListByShopID / CountByShopID` | 已有,直接复用 |
|
||||
| `ShopCommissionService` | `ListShopCommissionSummary` | 已有,需扩展 |
|
||||
| `ShopCommissionService` | `ListShopCommissionRecords` | 已有,不动 |
|
||||
| `ShopCommissionService` | `ListShopWithdrawalRequests` | 已有,不动 |
|
||||
| `MyCommissionService` | `GetStats / GetDailyStats / CreateWithdrawalRequest` | 业务逻辑迁移到 ShopCommissionService,原 service 删除 |
|
||||
|
||||
---
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- 平台人员在一个列表(资金概况)中同时看到每个代理的预充值余额和佣金余额
|
||||
- 代理账号通过相同接口看到自己的资金概况(GORM 多租户过滤)
|
||||
- 提供预充值钱包流水接口,支持平台和代理两个视角
|
||||
- 将 `/my/` 6 个接口的业务逻辑完整迁移至 `/shops/:id/`,删除冗余路径
|
||||
|
||||
**Non-Goals:**
|
||||
- 不新增纯佣金钱包流水接口(`commission-records` 订单维度已满足需求)
|
||||
- 不改动充值订单相关接口(`/agent-recharges` 系列不变)
|
||||
- 不改动提现审批流程(`/commission/withdrawal-*` 不变)
|
||||
- 不做向后兼容,直接删除 `/my/` 路由
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
### 决策 1:资金概况使用批量查询主钱包余额
|
||||
|
||||
**问题**:`/shops/fund-summary` 分页返回多条记录,每条需要主钱包余额。若逐条查询会产生 N+1。
|
||||
|
||||
**决策**:在 `AgentWalletStore` 新增 `GetShopMainWalletBatch(ctx, shopIDs) map[uint]*AgentWallet`,与现有 `GetShopCommissionSummaryBatch` 对称,一次 `WHERE shop_id IN (...)` 查完,在 Service 层合并。
|
||||
|
||||
**备选**:单次 SQL JOIN 查两个钱包类型 — 复杂度高,破坏 Store 层单一职责,放弃。
|
||||
|
||||
---
|
||||
|
||||
### 决策 2:主钱包流水接口不做独立 Handler,归入 ShopCommissionHandler
|
||||
|
||||
**问题**:主钱包流水是代理资金详情的一部分,是否需要独立 Handler。
|
||||
|
||||
**决策**:归入扩展后的 `ShopCommissionHandler`(或重命名为 `ShopFundHandler`),保持路由注册集中,避免 Handler 碎片化。
|
||||
|
||||
**注意**:`AgentWalletTransactionStore.ListByShopID` 已有,只需 Service 层加一个 `ListMainWalletTransactions(ctx, shopID, req)` 方法。
|
||||
|
||||
---
|
||||
|
||||
### 决策 3:`/my/` 路由的业务逻辑迁移方式
|
||||
|
||||
**问题**:`MyCommissionService` 中的 `GetStats`、`GetDailyStats`、`CreateWithdrawalRequest` 当前从 ctx 自动读取 shopID(隐式即"自己"),迁移后接口路径从 `:shop_id` 取,必须显式越权校验。
|
||||
|
||||
**决策**:
|
||||
- 将三个方法迁移到 `ShopCommissionService`,签名改为接受 `shopID uint` 参数
|
||||
- **Service 层入口**强制权限校验(不是 Handler 层),对齐 CLAUDE.md 的 Code Review 规范(参考 `internal/service/account/service.go`)
|
||||
- Handler 只做参数解析,不写权限逻辑
|
||||
- 删除 `MyCommissionService` 和 `MyCommissionHandler`
|
||||
|
||||
**两档校验策略**(根据业务严格度区分):
|
||||
|
||||
| 方法 | 校验策略 | 理由 |
|
||||
|---|---|---|
|
||||
| `GetStats` / `GetDailyStats` | `middleware.CanManageShop(ctx, shopID)` | 查询类,平台和顶级代理可看下级数据 |
|
||||
| `ListMainWalletTransactions` | `middleware.CanManageShop(ctx, shopID)` | 查询类,同上 |
|
||||
| `ListShopWithdrawalRequests` / `ListShopCommissionRecords`(已有方法补齐) | `middleware.CanManageShop(ctx, shopID)` | 查询类,同上 |
|
||||
| `CreateWithdrawalRequest` | **更严**:`userType==Agent` 且 `shopID==GetShopIDFromContext(ctx)` | 写操作,业务规定提现必须本人发起,平台和顶级代理均不允许代办 |
|
||||
|
||||
**越权校验覆盖范围**:不仅新增/迁移的方法要加,**已有的 `ListShopWithdrawalRequests` / `ListShopCommissionRecords` 也必须补齐** —— 现状它们只做了 `shopStore.GetByID` 的存在性检查,没有 `CanManageShop`,`/my/commission-records`、`/my/withdrawal-requests` 废弃后代理只要猜 shopID 就可读他人数据。是本变更必须修复的回归入口。
|
||||
|
||||
---
|
||||
|
||||
### 决策 4:Handler 不重命名,路由集中在 registerShopCommissionRoutes
|
||||
|
||||
原 `ShopCommissionHandler` 职责扩大(涵盖资金概况、主钱包流水、提现发起、佣金统计),保持原名 `ShopCommissionHandler` 不重命名,避免大范围文件改动。路由全部集中在扩展后的 `registerShopCommissionRoutes` 中,不再新建 `registerShopFundSummaryRoutes`,避免一个模块两处注册入口。
|
||||
|
||||
---
|
||||
|
||||
### 决策 5:`main_frozen_balance` 字段保留但标注预留
|
||||
|
||||
**现状**:`tb_agent_wallet.frozen_balance` 是通用字段,但主钱包当前业务无冻结场景(DB 验证 10 条主钱包记录 `frozen_balance` 全为 0)。
|
||||
|
||||
**决策**:`ShopFundSummaryItem` 保留 `main_frozen_balance`,作为未来扩展(如主钱包预授权/待扣款场景)预留位。Handler 直接返回 `AgentWallet.FrozenBalance`,无额外逻辑。前端展示可暂时不渲染,等业务触发时再暴露。
|
||||
|
||||
**备选**:不返回此字段 —— 将来接入时要改 DTO + 前端 + 文档,破坏性更大,放弃。
|
||||
|
||||
---
|
||||
|
||||
## 分层变更总览
|
||||
|
||||
```
|
||||
Handler 层
|
||||
ShopCommissionHandler 新增方法: ListFundSummary, ListMainWalletTransactions,
|
||||
GetCommissionStats, GetCommissionDailyStats,
|
||||
CreateWithdrawal
|
||||
删除方法: ListCommissionSummary(被 ListFundSummary 替代)
|
||||
MyCommissionHandler 整体删除
|
||||
|
||||
Service 层
|
||||
ShopCommissionService 构造函数补依赖: commissionWithdrawalSettingStore,
|
||||
agentWalletTransactionStore
|
||||
改造方法: ListShopCommissionSummary → ListShopFundSummary
|
||||
(加批量主钱包查询)
|
||||
新增方法: ListMainWalletTransactions, GetStats,
|
||||
GetDailyStats, CreateWithdrawalRequest
|
||||
(均在入口调 middleware.CanManageShop)
|
||||
补权限校验: ListShopWithdrawalRequests,
|
||||
ListShopCommissionRecords
|
||||
(现状无越权校验,必须补齐)
|
||||
MyCommissionService 整体删除
|
||||
|
||||
Store 层
|
||||
AgentWalletStore 新增: GetShopMainWalletBatch(ctx, shopIDs)
|
||||
AgentWalletTransactionStore 新增: ListByWalletIDWithFilters, CountByWalletID
|
||||
删除: ListByShopID, CountByShopID
|
||||
(全局无调用者,且会跨钱包类型返回
|
||||
数据,留着易被误用)
|
||||
|
||||
DTO 层
|
||||
ShopCommissionSummaryItem → ShopFundSummaryItem(新增 main_balance, main_frozen_balance)
|
||||
ShopCommissionSummaryListReq / PageResult → ShopFundSummaryListReq / PageResult
|
||||
新增: MainWalletTransactionItem, MainWalletTransactionListRequest/Response
|
||||
删除: MyCommissionSummaryResp, MyWithdrawalListReq, MyCommissionRecordListReq 等
|
||||
|
||||
路由层
|
||||
registerMyCommissionRoutes 删除
|
||||
registerShopCommissionRoutes 扩展:
|
||||
- GET /commission-summary → GET /fund-summary
|
||||
- 新增 GET /:shop_id/main-wallet/transactions
|
||||
- 新增 GET /:shop_id/commission-stats
|
||||
- 新增 GET /:shop_id/commission-daily-stats
|
||||
- 新增 POST /:shop_id/withdrawal-requests
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
| 风险 | 缓解措施 |
|
||||
|------|---------|
|
||||
| 批量查主钱包余额新增一次 DB 查询,影响 fund-summary 接口性能 | 数据量有限(代理数量通常 < 1000),IN 查询 < 5ms;如后期扩大可加 Redis 缓存 |
|
||||
| 删除 `/my/` 路由是破坏性变更,前端需同步修改 | 开发阶段,不考虑向后兼容;前端在本次变更后同步切换 |
|
||||
| `MyCommissionService` 删除后,若有其他地方引用会编译报错 | tasks 中包含全局 grep 检查,确保删干净 |
|
||||
| commission-stats/daily-stats 迁移后,shopID 改为显式参数,逻辑路径变化 | 单独验证两个统计接口的查询结果与原 /my/ 接口一致 |
|
||||
| **越权回归漏洞**:`/my/commission-records` / `/my/withdrawal-requests` 废弃后代理改走 `/shops/:shop_id/...`,而已有的 `ListShopCommissionRecords` / `ListShopWithdrawalRequests` 没做 `CanManageShop` 校验,代理只要猜到他人 shopID 就能读到敏感数据 | task 3.6 强制在这两个已有方法的入口补 `CanManageShop`;task 10.5 手动验证 403 |
|
||||
| `CreateWithdrawalRequest` 若用 `CanManageShop` 会允许顶级代理替下级店铺提现 | 已确认产品不允许:`CreateWithdrawalRequest` 不使用 `CanManageShop`,改为更严格的双重校验(`userType==Agent` 且 `shopID==自己`),平台人员也禁止调用,与原 `/my/withdrawal-requests` 行为一致 |
|
||||
| 删除 `AgentWalletTransactionStore.ListByShopID/CountByShopID` 可能导致外部/历史代码编译失败 | task 2.3 在删除前用 grep 确认无其他调用者(已在审查阶段验证过) |
|
||||
|
||||
---
|
||||
|
||||
## Migration Plan
|
||||
|
||||
1. DTO 层:重命名 `ShopCommissionSummaryItem → ShopFundSummaryItem` 并新增字段、新增主钱包流水 DTO
|
||||
2. Store 层:
|
||||
- `AgentWalletStore` 新增 `GetShopMainWalletBatch`
|
||||
- `AgentWalletTransactionStore` 新增 `ListByWalletIDWithFilters` / `CountByWalletID`,删除 `ListByShopID` / `CountByShopID`
|
||||
3. Service 层:
|
||||
- 补构造函数依赖
|
||||
- 改造 `ListShopFundSummary`
|
||||
- 迁移三个 `/my/` 方法(入口强制 `CanManageShop`)
|
||||
- 新增 `ListMainWalletTransactions`(入口强制 `CanManageShop`)
|
||||
- 给已有的 `ListShopWithdrawalRequests` / `ListShopCommissionRecords` 补 `CanManageShop`
|
||||
4. Handler 层:`ShopCommissionHandler` 新增方法、删除 `ListCommissionSummary`
|
||||
5. 路由层:扩展 `registerShopCommissionRoutes`、删除 `registerMyCommissionRoutes`
|
||||
6. Bootstrap:删除 `MyCommissionHandler`/`myCommissionService`,更新 `shopCommissionService` 初始化
|
||||
7. 文档生成器:`cmd/api/docs.go` 和 `cmd/gendocs/main.go`
|
||||
8. 删除 `internal/handler/admin/my_commission.go`、`internal/service/my_commission/`、`internal/routes/my_commission.go`
|
||||
9. `go build ./...` 全量编译 + grep 确认无残留引用
|
||||
10. PostgreSQL MCP 手动验证
|
||||
|
||||
无数据库迁移,无需 rollback 策略。
|
||||
|
||||
## Open Questions
|
||||
|
||||
无,所有设计决策已在探索阶段与需求方确认。
|
||||
156
openspec/changes/agent-fund-visibility/proposal.md
Normal file
156
openspec/changes/agent-fund-visibility/proposal.md
Normal file
@@ -0,0 +1,156 @@
|
||||
## Why
|
||||
|
||||
目前平台人员和代理账号均无法看到代理的预充值钱包(主钱包)余额与流水,佣金相关接口散落在 `/my/` 前缀下且与 `/shops/:id/` 路径存在职责重叠,亟需统一入口、补全预充值钱包可见性。
|
||||
|
||||
## What Changes
|
||||
|
||||
- **BREAKING** `GET /shops/commission-summary` 重命名为 `GET /shops/fund-summary`,响应 DTO 由 `ShopCommissionSummaryItem` 改为 `ShopFundSummaryItem`,新增 `main_balance`、`main_frozen_balance` 两个字段
|
||||
- **新增** `GET /shops/:id/main-wallet/transactions` — 预充值钱包流水列表(全新功能)
|
||||
- **新增** `GET /shops/:id/commission-stats` — 佣金统计,迁移自 `/my/commission-stats`
|
||||
- **新增** `GET /shops/:id/commission-daily-stats` — 每日佣金统计,迁移自 `/my/commission-daily-stats`
|
||||
- **新增** `POST /shops/:id/withdrawal-requests` — 发起提现申请,迁移自 `POST /my/withdrawal-requests`
|
||||
- **BREAKING 废弃** `/my/` 全部 6 个路由(详见废弃对照表)
|
||||
|
||||
### 废弃路由对照表
|
||||
|
||||
| 废弃路由 | 作用 | 替代路由 | 状态 |
|
||||
|---------|------|---------|------|
|
||||
| `GET /my/commission-summary` | 代理看自己的佣金钱包余额概览 | `GET /shops/fund-summary` | 本次改造 |
|
||||
| `GET /my/withdrawal-requests` | 代理看自己的提现申请记录 | `GET /shops/:id/withdrawal-requests` | 已有,直接复用 |
|
||||
| `GET /my/commission-records` | 代理看自己的每笔佣金入账明细(订单维度) | `GET /shops/:id/commission-records` | 已有,直接复用 |
|
||||
| `GET /my/commission-stats` | 代理看自己的佣金汇总统计(按时间段) | `GET /shops/:id/commission-stats` | 本次新增 |
|
||||
| `GET /my/commission-daily-stats` | 代理看自己的每日佣金金额趋势 | `GET /shops/:id/commission-daily-stats` | 本次新增 |
|
||||
| `POST /my/withdrawal-requests` | 代理发起提现申请 | `POST /shops/:id/withdrawal-requests` | 本次新增 |
|
||||
|
||||
### API 全景(变更前 vs 变更后)
|
||||
|
||||
```
|
||||
变更前 变更后
|
||||
─────────────────────────────────────────────────────────────────────────
|
||||
GET /shops/commission-summary → GET /shops/fund-summary ★ 改造+扩展
|
||||
GET /shops/:id/withdrawal-requests GET /shops/:id/withdrawal-requests
|
||||
GET /shops/:id/commission-records GET /shops/:id/commission-records
|
||||
→ GET /shops/:id/commission-stats ★ 新增
|
||||
→ GET /shops/:id/commission-daily-stats ★ 新增
|
||||
→ POST /shops/:id/withdrawal-requests ★ 新增
|
||||
→ GET /shops/:id/main-wallet/transactions ★ 新增
|
||||
|
||||
GET /my/commission-summary × 废弃
|
||||
GET /my/withdrawal-requests × 废弃
|
||||
GET /my/commission-records × 废弃
|
||||
GET /my/commission-stats × 废弃
|
||||
GET /my/commission-daily-stats × 废弃
|
||||
POST /my/withdrawal-requests × 废弃
|
||||
|
||||
GET /agent-recharges GET /agent-recharges 不变
|
||||
GET /agent-recharges/:id GET /agent-recharges/:id 不变
|
||||
POST /agent-recharges POST /agent-recharges 不变
|
||||
POST /agent-recharges/:id/offline-pay POST /agent-recharges/:id/offline-pay 不变
|
||||
```
|
||||
|
||||
### 两个视角的完整操作流
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 平台人员 │
|
||||
├──────────────────────────────────────────────────────────────────┤
|
||||
│ [代理商资金概况列表] │
|
||||
│ GET /shops/fund-summary │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ 店铺名 │ 预充值余额 │ 可提现佣金 │ 冻结佣金 │ 提现中 │ │
|
||||
│ │ 代理A │ ¥2,000 │ ¥500 │ ¥100 │ ¥200 │ │
|
||||
│ │ 代理B │ ¥500 │ ¥200 │ ¥0 │ ¥0 │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
│ │ 进入某代理详情 │
|
||||
│ ▼ │
|
||||
│ [代理详情 — 分 tab 查看] │
|
||||
│ ├─ 预充值流水 GET /shops/:id/main-wallet/transactions │
|
||||
│ ├─ 佣金明细 GET /shops/:id/commission-records │
|
||||
│ ├─ 佣金统计 GET /shops/:id/commission-stats │
|
||||
│ ├─ 每日统计 GET /shops/:id/commission-daily-stats │
|
||||
│ └─ 提现记录 GET /shops/:id/withdrawal-requests │
|
||||
│ │
|
||||
│ [充值管理] │
|
||||
│ GET /agent-recharges 查看所有充值订单(含状态) │
|
||||
│ POST /agent-recharges/:id/offline-pay 确认线下到账 │
|
||||
│ │
|
||||
│ [提现审批] │
|
||||
│ GET /commission/withdrawal-requests 审批提现申请 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 代理账号(同接口,按数据权限过滤) │
|
||||
├──────────────────────────────────────────────────────────────────┤
|
||||
│ [我的资金概况(返回自己 + 所有下级代理店铺)] │
|
||||
│ GET /shops/fund-summary │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ 预充值余额: ¥2,000 │ 可提现佣金: ¥500 │ │
|
||||
│ │ 冻结余额: ¥100 │ 提现中: ¥200 │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ [预充值钱包流水] │
|
||||
│ GET /shops/自己ID/main-wallet/transactions │
|
||||
│ ┌──────────────────────────────────────────────────────┐ │
|
||||
│ │ 时间 │ 类型 │ 金额 │ 变动后余额 │ │
|
||||
│ │ 04-08 10:00 │ 充值入账 │ +¥500 │ ¥2,000 │ │
|
||||
│ │ 04-07 15:30 │ 套餐扣款 │ -¥100 │ ¥1,500 │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ [佣金相关] │
|
||||
│ GET /shops/自己ID/commission-records 佣金明细 │
|
||||
│ GET /shops/自己ID/commission-stats 佣金统计 │
|
||||
│ GET /shops/自己ID/withdrawal-requests 提现记录 │
|
||||
│ POST /shops/自己ID/withdrawal-requests 发起提现 │
|
||||
│ │
|
||||
│ [充值订单(GORM 自动过滤,只见自己的)] │
|
||||
│ GET /agent-recharges │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 数据流向
|
||||
|
||||
```
|
||||
【充值流】
|
||||
平台操作 POST /agent-recharges
|
||||
↓
|
||||
tb_agent_recharge_record(充值订单,含状态:待支付/已完成/已取消)
|
||||
↓ 线下确认 / 微信回调
|
||||
tb_agent_wallet (wallet_type=main) balance +
|
||||
tb_agent_wallet_transaction (transaction_type=recharge)
|
||||
↓ 代理购买套餐
|
||||
tb_agent_wallet (wallet_type=main) balance -
|
||||
tb_agent_wallet_transaction (transaction_type=deduct)
|
||||
|
||||
【佣金流】
|
||||
用户下单 → 佣金计算 → tb_commission_record(订单维度明细)
|
||||
↓ 佣金入账
|
||||
tb_agent_wallet (wallet_type=commission) balance +
|
||||
tb_agent_wallet_transaction (transaction_type=commission)
|
||||
↓ 代理发起提现 POST /shops/:id/withdrawal-requests
|
||||
tb_commission_withdrawal_request(提现申请)
|
||||
↓ 平台审批通过
|
||||
tb_agent_wallet (wallet_type=commission) balance -
|
||||
tb_agent_wallet_transaction (transaction_type=withdrawal)
|
||||
```
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `agent-fund-summary`: 代理商资金概况接口,同一接口支持平台(全量)和代理(仅自己)两种视角,包含预充值余额与佣金钱包字段
|
||||
- `main-wallet-transactions`: 代理预充值钱包(主钱包)流水查询,按 shop_id 分页检索 tb_agent_wallet_transaction(wallet_type=main)
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `commission-record-query`: 佣金统计和每日统计从 `/my/` 路径迁移至 `/shops/:id/` 路径,同时新增 POST 提现发起路由;原 `/my/` 路径全部废弃
|
||||
- `agent-wallet`: 资金概况接口现在对外暴露主钱包余额,`AgentWalletStore.GetShopCommissionSummaryBatch` 需扩展以批量拉取主钱包余额
|
||||
|
||||
## Impact
|
||||
|
||||
- **Handler 层**: 扩展 `ShopCommissionHandler`,新增 `ListFundSummary`、`ListMainWalletTransactions`、`GetCommissionStats`、`GetCommissionDailyStats`、`CreateWithdrawal` 五个方法;`MyCommissionHandler` 整体删除
|
||||
- **Service 层**: `ShopCommissionService` 构造函数补两个依赖(`commissionWithdrawalSettingStore`、`agentWalletTransactionStore`),`ListShopCommissionSummary` 改造为 `ListShopFundSummary`,新增 `ListMainWalletTransactions`,并从 `MyCommissionService` 迁移 `GetStats / GetDailyStats / CreateWithdrawalRequest` 三个方法(签名改为显式 `shopID`,入口强制调用 `middleware.CanManageShop` 校验);`MyCommissionService` 整体删除
|
||||
- **Store 层**: `AgentWalletStore` 新增 `GetShopMainWalletBatch`;`AgentWalletTransactionStore` 新增 `ListByWalletIDWithFilters` / `CountByWalletID`,并删除原 `ListByShopID` / `CountByShopID`(全局无其他调用者,且会跨钱包类型返回数据,留着易被误用)
|
||||
- **DTO 层**: `ShopCommissionSummaryItem` → `ShopFundSummaryItem`(新增 `main_balance`、`main_frozen_balance`);新增主钱包流水 DTO;删除 `/my/` 系列 DTO
|
||||
- **路由层**: 删除 `registerMyCommissionRoutes`,在 `registerShopCommissionRoutes` 内将 `/commission-summary` 改为 `/fund-summary`,并追加 4 条 `/:shop_id/...` 路由
|
||||
- **权限层**: 所有迁移过来的 `/shops/:shop_id/...` 入口必须在 Service 层显式调用 `middleware.CanManageShop(ctx, shopID)`,同时覆盖本次新增接口和已有的 `ListShopWithdrawalRequests`、`ListShopCommissionRecords`(当前只做了店铺存在性检查,未做越权校验,迁移后代理只要猜到其他 shopID 就能读取,必须补齐)
|
||||
- **文档生成器**: `cmd/api/docs.go` 和 `cmd/gendocs/main.go` 同步更新
|
||||
@@ -0,0 +1,63 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 代理商资金概况列表
|
||||
|
||||
系统 SHALL 提供 `GET /api/admin/shops/fund-summary` 接口,返回分页的代理商资金概况列表,同时包含预充值钱包(主钱包)和佣金钱包的余额信息。
|
||||
|
||||
**响应字段**(`ShopFundSummaryItem`):
|
||||
- `shop_id`:店铺 ID
|
||||
- `shop_name`:店铺名称
|
||||
- `shop_code`:店铺编码
|
||||
- `username`:主账号用户名
|
||||
- `phone`:主账号手机号
|
||||
- `main_balance`:预充值钱包余额(分)
|
||||
- `main_frozen_balance`:预充值钱包冻结余额(分)
|
||||
- `total_commission`:累计佣金总额(分)
|
||||
- `withdrawn_commission`:已提现佣金(分)
|
||||
- `unwithdraw_commission`:未提现佣金(分)
|
||||
- `frozen_commission`:冻结中佣金(分)
|
||||
- `withdrawing_commission`:提现中佣金(分)
|
||||
- `available_commission`:可提现佣金(分)
|
||||
- `created_at`:店铺创建时间
|
||||
|
||||
**查询参数**(`ShopFundSummaryListReq`):
|
||||
- `page`:页码(默认 1)
|
||||
- `page_size`:每页数量(默认 20,最大 100)
|
||||
- `shop_name`:店铺名称模糊查询
|
||||
- `username`:主账号用户名模糊查询
|
||||
|
||||
**实现要求**:
|
||||
- 主钱包余额通过 `AgentWalletStore.GetShopMainWalletBatch` 批量查询,避免 N+1
|
||||
- 若代理暂无主钱包记录(未充值),`main_balance` 和 `main_frozen_balance` 返回 0
|
||||
- `main_frozen_balance` 字段为未来预留(当前业务无主钱包冻结场景,值恒为 0),前端可暂不展示
|
||||
- 数据权限:列表查询走 `Shop` 表的数据权限过滤(`SubordinateShopIDs`)。平台人员返回全部代理;代理账号返回自己 + 所有下级店铺(而不是只返回自己一条)
|
||||
|
||||
#### Scenario: 平台人员查看所有代理资金概况
|
||||
|
||||
- **WHEN** 平台人员请求 `GET /shops/fund-summary`
|
||||
- **THEN** 系统返回所有代理的分页列表,每条包含 `main_balance` 和佣金钱包字段
|
||||
|
||||
#### Scenario: 无下级代理的账号查看自己的资金概况
|
||||
|
||||
- **WHEN** 无下级代理的代理账号请求 `GET /shops/fund-summary`
|
||||
- **THEN** 系统按数据权限过滤,只返回该代理自己的一条记录
|
||||
|
||||
#### Scenario: 有下级代理的顶级代理查看资金概况
|
||||
|
||||
- **WHEN** 一个拥有多个下级代理的顶级代理账号请求 `GET /shops/fund-summary`
|
||||
- **THEN** 系统返回自己 + 所有下级代理店铺的资金概况列表(按 `SubordinateShopIDs` 过滤)
|
||||
|
||||
#### Scenario: 代理暂无主钱包时返回零值
|
||||
|
||||
- **WHEN** 代理从未充值,`tb_agent_wallet` 中无该店铺的 `wallet_type=main` 记录
|
||||
- **THEN** `main_balance` 和 `main_frozen_balance` 返回 0,其余字段正常返回
|
||||
|
||||
#### Scenario: 按店铺名称过滤
|
||||
|
||||
- **WHEN** 传入 `shop_name=张三`
|
||||
- **THEN** 系统只返回店铺名称包含"张三"的代理记录
|
||||
|
||||
#### Scenario: 企业账号无权访问
|
||||
|
||||
- **WHEN** 企业账号请求此接口
|
||||
- **THEN** 系统返回 403 错误,消息为"企业账号无权访问代理资金功能"
|
||||
@@ -0,0 +1,20 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 批量查询店铺主钱包余额
|
||||
|
||||
系统 SHALL 在 `AgentWalletStore` 中提供 `GetShopMainWalletBatch(ctx, shopIDs []uint) map[uint]*AgentWallet` 方法,一次查询多个店铺的主钱包(`wallet_type=main`)记录,返回以 `shop_id` 为 key 的 map。
|
||||
|
||||
**实现要求**:
|
||||
- 使用 `WHERE shop_id IN (?) AND wallet_type = 'main'` 单次查询,不得逐条查询
|
||||
- 不在 map 中的 shop_id 表示该店铺暂无主钱包,调用方按零值处理
|
||||
- 与现有 `GetShopCommissionSummaryBatch` 对称设计
|
||||
|
||||
#### Scenario: 批量查询多个店铺的主钱包
|
||||
|
||||
- **WHEN** 传入 shopIDs `[1, 2, 3]`,其中 shop 3 无主钱包记录
|
||||
- **THEN** 返回 map `{1: &wallet1, 2: &wallet2}`,shop 3 不在 map 中
|
||||
|
||||
#### Scenario: 传入空列表
|
||||
|
||||
- **WHEN** 传入空 `shopIDs`
|
||||
- **THEN** 直接返回空 map,不执行 DB 查询
|
||||
@@ -0,0 +1,150 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 迁移接口的越权校验(通用要求)
|
||||
|
||||
本规范下所有 `/shops/:shop_id/...` 迁移/新增接口,Service 层方法入口 SHALL 调用 `middleware.CanManageShop(ctx, shopID)` 做显式越权校验。Handler 层只做参数解析,不承担权限逻辑。该要求同时追溯适用于已有但缺少校验的 `ListShopWithdrawalRequests`、`ListShopCommissionRecords` 两个方法(回归漏洞修复)。
|
||||
|
||||
统一错误返回:`errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")`。
|
||||
|
||||
#### Scenario: 代理传非自己管辖店铺 ID 被 Service 层拦截
|
||||
|
||||
- **WHEN** 代理 A(shopID=10)请求本规范任意一个 `/shops/:shop_id/...` 接口,传入代理 B(shopID=20)的 shopID
|
||||
- **THEN** Service 层入口的 `middleware.CanManageShop(ctx, 20)` 返回 error,接口返回 403,消息 "无权限操作该资源或资源不存在"
|
||||
|
||||
#### Scenario: 平台人员不受 CanManageShop 限制
|
||||
|
||||
- **WHEN** 平台人员请求任意 `/shops/:shop_id/...` 接口
|
||||
- **THEN** `middleware.CanManageShop` 直接放行,接口正常返回数据
|
||||
|
||||
#### Scenario: 已有方法 ListShopCommissionRecords / ListShopWithdrawalRequests 补齐校验
|
||||
|
||||
- **WHEN** 代理账号请求 `/shops/{非自己管辖shopID}/commission-records` 或 `/withdrawal-requests`
|
||||
- **THEN** 实现后返回 403(回归漏洞修复前这两个方法会返回数据)
|
||||
|
||||
---
|
||||
|
||||
### Requirement: 通过店铺 ID 查询佣金统计
|
||||
|
||||
系统 SHALL 提供 `GET /api/admin/shops/:shop_id/commission-stats` 接口,返回指定代理店铺在给定时间范围内的佣金汇总统计。
|
||||
|
||||
**路径参数**:`shop_id`(必填)
|
||||
**查询参数**:`start_time`、`end_time`(可选,ISO8601 格式)
|
||||
**响应**:与原 `/my/commission-stats` 一致(`CommissionStatsResponse`)
|
||||
**权限**:Service 层入口调用 `middleware.CanManageShop(ctx, shopID)`
|
||||
|
||||
#### Scenario: 平台人员查询某代理的佣金统计
|
||||
|
||||
- **WHEN** 平台人员请求 `GET /shops/123/commission-stats`
|
||||
- **THEN** 系统返回店铺 123 的佣金汇总统计
|
||||
|
||||
#### Scenario: 代理查询自己的佣金统计
|
||||
|
||||
- **WHEN** 代理账号请求 `GET /shops/自己ID/commission-stats`
|
||||
- **THEN** 系统返回该代理自己的佣金统计数据
|
||||
|
||||
#### Scenario: 代理尝试查询他人统计被拦截
|
||||
|
||||
- **WHEN** 代理账号请求 `GET /shops/他人ID/commission-stats`
|
||||
- **THEN** 系统返回 403 错误
|
||||
|
||||
---
|
||||
|
||||
### Requirement: 通过店铺 ID 查询每日佣金统计
|
||||
|
||||
系统 SHALL 提供 `GET /api/admin/shops/:shop_id/commission-daily-stats` 接口,返回指定代理店铺的每日佣金趋势数据。
|
||||
|
||||
**路径参数**:`shop_id`(必填)
|
||||
**查询参数**:`start_date`、`end_date`(可选,默认最近 30 天)
|
||||
**响应**:与原 `/my/commission-daily-stats` 一致(`[]DailyCommissionStatsResponse`)
|
||||
**权限**:Service 层入口调用 `middleware.CanManageShop(ctx, shopID)`
|
||||
|
||||
#### Scenario: 平台人员查询某代理的每日佣金
|
||||
|
||||
- **WHEN** 平台人员请求 `GET /shops/123/commission-daily-stats`
|
||||
- **THEN** 系统返回店铺 123 的每日佣金趋势
|
||||
|
||||
#### Scenario: 代理查询自己的每日佣金
|
||||
|
||||
- **WHEN** 代理账号请求 `GET /shops/自己ID/commission-daily-stats`
|
||||
- **THEN** 系统返回该代理自己的每日佣金数据,默认最近 30 天
|
||||
|
||||
#### Scenario: 代理尝试查询他人数据被拦截
|
||||
|
||||
- **WHEN** 代理账号请求 `GET /shops/他人ID/commission-daily-stats`
|
||||
- **THEN** 系统返回 403 错误
|
||||
|
||||
---
|
||||
|
||||
### Requirement: 通过店铺 ID 发起提现申请
|
||||
|
||||
系统 SHALL 提供 `POST /api/admin/shops/:shop_id/withdrawal-requests` 接口,允许代理为自己的店铺发起佣金提现申请。
|
||||
|
||||
**路径参数**:`shop_id`(必填)
|
||||
**请求体**:与原 `POST /my/withdrawal-requests` 一致(`CreateMyWithdrawalReq`)
|
||||
**响应**:与原 `POST /my/withdrawal-requests` 一致(`CreateMyWithdrawalResp`)
|
||||
|
||||
**权限规则**(严于其他迁移接口,**不使用** `CanManageShop`):
|
||||
- Service 层入口必须满足两个条件:
|
||||
1. `userType == UserTypeAgent`(仅代理商用户)
|
||||
2. `shopID == middleware.GetShopIDFromContext(ctx)`(必须本人店铺,禁止顶级代理替下级提现)
|
||||
- 平台人员/超管/企业账号一律 403:业务上提现必须由代理本人发起,平台不代办
|
||||
- 顶级代理替下级提现也禁止:代理只能给自己的店铺发起提现申请
|
||||
|
||||
#### Scenario: 代理为自己发起提现
|
||||
|
||||
- **WHEN** 代理账号请求 `POST /shops/{自己shopID}/withdrawal-requests`,传入合法金额和收款信息
|
||||
- **THEN** 系统创建提现申请,返回申请 ID、提现单号、手续费信息
|
||||
|
||||
#### Scenario: 代理尝试为他人(非下级)发起提现被拦截
|
||||
|
||||
- **WHEN** 代理账号 A 请求 `POST /shops/{无关代理B的shopID}/withdrawal-requests`
|
||||
- **THEN** 系统返回 403 错误,消息"仅可为本人店铺发起提现"
|
||||
|
||||
#### Scenario: 顶级代理尝试替下级店铺发起提现被拦截
|
||||
|
||||
- **WHEN** 顶级代理 P 请求 `POST /shops/{P的下级shop_id}/withdrawal-requests`(即使 `CanManageShop` 会放行)
|
||||
- **THEN** 系统返回 403 错误,消息"仅可为本人店铺发起提现"。理由:业务上提现必须本人发起
|
||||
|
||||
#### Scenario: 平台人员尝试替代理发起提现被拦截
|
||||
|
||||
- **WHEN** 平台人员或超管请求 `POST /shops/:shop_id/withdrawal-requests`
|
||||
- **THEN** 系统返回 403 错误,消息"仅代理商用户可发起提现"
|
||||
|
||||
#### Scenario: 可提现余额不足
|
||||
|
||||
- **WHEN** 代理发起提现金额超过可提现余额
|
||||
- **THEN** 系统返回业务错误,消息为"可提现余额不足"
|
||||
|
||||
---
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: 通过 /my/ 路径查询佣金统计
|
||||
|
||||
**Reason**: 路径统一到 `/shops/:id/` 前缀,`/my/` 系列接口职责与平台视角重叠,增加维护成本
|
||||
**Migration**: 使用 `GET /api/admin/shops/:shop_id/commission-stats` 替代 `GET /api/admin/my/commission-stats`
|
||||
|
||||
### Requirement: 通过 /my/ 路径查询每日佣金统计
|
||||
|
||||
**Reason**: 同上,路径统一
|
||||
**Migration**: 使用 `GET /api/admin/shops/:shop_id/commission-daily-stats` 替代 `GET /api/admin/my/commission-daily-stats`
|
||||
|
||||
### Requirement: 通过 /my/ 路径发起提现申请
|
||||
|
||||
**Reason**: 同上,路径统一
|
||||
**Migration**: 使用 `POST /api/admin/shops/:shop_id/withdrawal-requests` 替代 `POST /api/admin/my/withdrawal-requests`
|
||||
|
||||
### Requirement: 通过 /my/ 路径查询佣金概览
|
||||
|
||||
**Reason**: 由 `/shops/fund-summary` 替代,新接口同时包含预充值钱包余额
|
||||
**Migration**: 使用 `GET /api/admin/shops/fund-summary` 替代 `GET /api/admin/my/commission-summary`
|
||||
|
||||
### Requirement: 通过 /my/ 路径查询提现记录
|
||||
|
||||
**Reason**: 路径统一
|
||||
**Migration**: 使用 `GET /api/admin/shops/:shop_id/withdrawal-requests` 替代 `GET /api/admin/my/withdrawal-requests`
|
||||
|
||||
### Requirement: 通过 /my/ 路径查询佣金明细
|
||||
|
||||
**Reason**: 路径统一
|
||||
**Migration**: 使用 `GET /api/admin/shops/:shop_id/commission-records` 替代 `GET /api/admin/my/commission-records`
|
||||
@@ -0,0 +1,65 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 预充值钱包流水查询
|
||||
|
||||
系统 SHALL 提供 `GET /api/admin/shops/:shop_id/main-wallet/transactions` 接口,分页返回指定代理店铺的预充值钱包(主钱包)交易流水记录。
|
||||
|
||||
**响应字段**(`MainWalletTransactionItem`):
|
||||
- `id`:流水记录 ID
|
||||
- `transaction_type`:交易类型。主钱包可能出现的值为 `recharge`-充值入账 / `deduct`-套餐扣款 / `refund`-退款(当前 DB 数据仅见 `recharge`,`deduct` / `refund` 随代购扣款/退款业务上线而出现;接口不对类型做枚举白名单,透传 DB 原值)
|
||||
- `transaction_subtype`:交易子类型(细分场景,如 `order_payment`,可为空)
|
||||
- `amount`:变动金额(分,正数为入账,负数为扣款)
|
||||
- `balance_before`:变动前余额(分)
|
||||
- `balance_after`:变动后余额(分)
|
||||
- `remark`:备注(可为空)
|
||||
- `created_at`:流水时间
|
||||
|
||||
**查询参数**(`MainWalletTransactionListRequest`):
|
||||
- `shop_id`:路径参数,店铺 ID(必填)
|
||||
- `page`:页码(默认 1)
|
||||
- `page_size`:每页数量(默认 20,最大 100)
|
||||
- `transaction_type`:按类型过滤(可选)
|
||||
- `start_date`:开始日期,`YYYY-MM-DD`(可选)
|
||||
- `end_date`:结束日期,`YYYY-MM-DD`(可选)
|
||||
|
||||
**实现要求**:
|
||||
- **Service 层入口必须调用 `middleware.CanManageShop(ctx, shopID)` 做越权校验**,校验失败直接返回 `errors.CodeForbidden`;不得依赖 `GetMainWallet` 的隐式过滤(该方法不做权限校验)
|
||||
- 先通过 `AgentWalletStore.GetMainWallet(shopID)` 获取主钱包;若不存在则返回空列表(`total=0`),不报错
|
||||
- 使用 `AgentWalletTransactionStore.ListByWalletIDWithFilters / CountByWalletID`(task 2.2 新增)查询流水,支持 transaction_type 和日期过滤
|
||||
- 旧方法 `ListByShopID / CountByShopID` 已在 task 2.3 删除(会跨钱包类型返回数据,易被误用)
|
||||
- 结果按 `created_at DESC` 排序
|
||||
|
||||
#### Scenario: 平台人员查看指定代理的预充值流水
|
||||
|
||||
- **WHEN** 平台人员请求 `GET /shops/123/main-wallet/transactions`
|
||||
- **THEN** 系统返回店铺 123 的主钱包流水,按时间倒序,含变动前后余额
|
||||
|
||||
#### Scenario: 代理查看自己的预充值流水
|
||||
|
||||
- **WHEN** 代理账号请求 `GET /shops/自己shop_id/main-wallet/transactions`
|
||||
- **THEN** 系统返回该代理自己的主钱包流水记录
|
||||
|
||||
#### Scenario: 代理尝试查看他人流水被拦截
|
||||
|
||||
- **WHEN** 代理账号请求 `GET /shops/他人shop_id/main-wallet/transactions`
|
||||
- **THEN** 系统返回 403 错误,消息为"无权限操作该资源或资源不存在"
|
||||
|
||||
#### Scenario: 代理暂无主钱包时返回空列表
|
||||
|
||||
- **WHEN** 代理从未充值,主钱包不存在
|
||||
- **THEN** 系统返回空列表,`total` 为 0,不报错
|
||||
|
||||
#### Scenario: 按交易类型过滤
|
||||
|
||||
- **WHEN** 传入 `transaction_type=recharge`
|
||||
- **THEN** 系统只返回充值入账类型的流水
|
||||
|
||||
#### Scenario: 按日期范围过滤
|
||||
|
||||
- **WHEN** 传入 `start_date=2026-01-01&end_date=2026-03-31`
|
||||
- **THEN** 系统只返回该日期范围内的流水记录
|
||||
|
||||
#### Scenario: 企业账号无权访问
|
||||
|
||||
- **WHEN** 企业账号请求此接口
|
||||
- **THEN** 系统返回 403 错误
|
||||
90
openspec/changes/agent-fund-visibility/tasks.md
Normal file
90
openspec/changes/agent-fund-visibility/tasks.md
Normal file
@@ -0,0 +1,90 @@
|
||||
## 1. DTO 层变更
|
||||
|
||||
- [x] 1.1 新增 `ShopFundSummaryItem`(含 `main_balance`、`main_frozen_balance` 及原有佣金字段),新增 `ShopFundSummaryListReq`、`ShopFundSummaryPageResult`;删除旧的 `ShopCommissionSummaryItem` / `ShopCommissionSummaryListReq` / `ShopCommissionSummaryPageResult`
|
||||
- [x] 1.2 新增主钱包流水 DTO:`MainWalletTransactionItem`、`MainWalletTransactionListRequest`、`MainWalletTransactionListResponse`
|
||||
- [x] 1.3 删除废弃 DTO:`MyCommissionSummaryResp`、`MyWithdrawalListReq`、`MyCommissionRecordListReq`、`MyCommissionRecordItem`、`MyCommissionRecordPageResult`(确认无其他引用后删除)
|
||||
- **保留**:`CommissionStatsRequest`、`DailyCommissionStatsRequest` / `CommissionStatsResponse` / `DailyCommissionStatsResponse` — 迁移后的 `/shops/:id/commission-stats` 和 `/shops/:id/commission-daily-stats` 继续复用
|
||||
- **保留**:`CreateMyWithdrawalReq`、`CreateMyWithdrawalResp` — 迁移后的 `POST /shops/:id/withdrawal-requests` 继续复用
|
||||
|
||||
## 2. Store 层变更
|
||||
|
||||
- [x] 2.1 在 `AgentWalletStore` 新增 `GetShopMainWalletBatch(ctx context.Context, shopIDs []uint) (map[uint]*model.AgentWallet, error)` 方法:`WHERE shop_id IN (?) AND wallet_type = 'main'` 单次查询,内部调用 `middleware.ApplyShopFilter` 对齐现有 `GetShopCommissionSummaryBatch` 的防御式过滤
|
||||
- [x] 2.2 在 `AgentWalletTransactionStore` 新增过滤结构体 `AgentWalletTransactionListFilters`(字段:`TransactionType string`、`StartDate string`、`EndDate string`),以及以下两个方法:
|
||||
- `ListByWalletIDWithFilters(ctx, walletID uint, opts *store.QueryOptions, filters *AgentWalletTransactionListFilters) ([]*model.AgentWalletTransaction, error)`:在 `WHERE agent_wallet_id = ?` 基础上叠加 transaction_type / 日期过滤,按 `created_at DESC` 排序
|
||||
- `CountByWalletID(ctx, walletID uint, filters *AgentWalletTransactionListFilters) (int64, error)`:与列表方法过滤条件一致,用于分页 total 统计
|
||||
- [x] 2.3 删除 `AgentWalletTransactionStore.ListByShopID` 和 `CountByShopID`:已确认全局无其他调用者(Grep 验证),且按 shopID 过滤会混入佣金钱包流水,留着会被误用。删除前再次 `grep -rn "ListByShopID\|CountByShopID" --include="*.go"` 确认
|
||||
|
||||
## 3. Service 层变更(ShopCommissionService 扩展)
|
||||
|
||||
- [x] 3.0 更新 `ShopCommissionService.New()` 构造函数,在现有参数基础上新增两个依赖:
|
||||
- `commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore`(task 3.4 迁移 `CreateWithdrawalRequest` 时校验最低提现金额和每日次数上限)
|
||||
- `agentWalletTransactionStore *postgres.AgentWalletTransactionStore`(task 3.5 新增 `ListMainWalletTransactions` 使用)
|
||||
- [x] 3.1 将 `ListShopCommissionSummary` 改造为 `ListShopFundSummary`:删除原方法,方法签名/返回类型切换至 `ShopFundSummaryListReq` / `ShopFundSummaryPageResult`;调用 `GetShopMainWalletBatch` 批量拉取主钱包余额,合并到 `ShopFundSummaryItem` 中;主钱包不存在时 `main_balance` / `main_frozen_balance` 返回 0
|
||||
- [x] 3.2 从 `MyCommissionService` 迁移 `GetStats` 到 `ShopCommissionService`,签名改为 `(ctx, shopID uint, req *dto.CommissionStatsRequest)`;**方法入口第一行**调用 `middleware.CanManageShop(ctx, shopID)`,失败直接返回
|
||||
- [x] 3.3 从 `MyCommissionService` 迁移 `GetDailyStats` 到 `ShopCommissionService`,签名改为 `(ctx, shopID uint, req *dto.DailyCommissionStatsRequest)`;同样入口加 `CanManageShop`
|
||||
- [x] 3.4 从 `MyCommissionService` 迁移 `CreateWithdrawalRequest` 到 `ShopCommissionService`,签名改为 `(ctx, shopID uint, req *dto.CreateMyWithdrawalReq)`;**入口权限校验严于其他方法**:
|
||||
- 必须 `middleware.GetUserTypeFromContext(ctx) == constants.UserTypeAgent`,否则返回 403"仅代理商用户可发起提现"
|
||||
- 必须 `shopID == middleware.GetShopIDFromContext(ctx)`,否则返回 403"仅可为本人店铺发起提现"
|
||||
- **不使用 `CanManageShop`**(默认会放行整个下级层级,业务上不允许顶级代理替下级提现)
|
||||
- 保留原有的条件更新 `Where("id = ? AND balance - frozen_balance >= ?")` 并发保护
|
||||
- [x] 3.5 在 `ShopCommissionService` 新增 `ListMainWalletTransactions(ctx, shopID uint, req *dto.MainWalletTransactionListRequest)` 方法:
|
||||
- **入口第一行**调用 `middleware.CanManageShop(ctx, shopID)`
|
||||
- 通过 `AgentWalletStore.GetMainWallet(ctx, shopID)` 获取主钱包;不存在则返回空列表(`total=0`)不报错
|
||||
- 调用 `ListByWalletIDWithFilters` / `CountByWalletID`(task 2.2 新增)查询流水
|
||||
- **不得**使用 `ListByShopID`(已删除)
|
||||
- [x] 3.6 **补齐已有方法的越权校验**(回归漏洞修复):
|
||||
- `ListShopWithdrawalRequests`:方法入口加 `middleware.CanManageShop(ctx, shopID)`
|
||||
- `ListShopCommissionRecords`:方法入口加 `middleware.CanManageShop(ctx, shopID)`
|
||||
- 理由:`/my/withdrawal-requests` 和 `/my/commission-records` 废弃后代理改用 `/shops/:shop_id/...`,若不补校验,代理只要猜到其他 shopID 就能读取他人佣金明细和提现记录
|
||||
|
||||
## 4. Service 层删除(MyCommissionService)
|
||||
|
||||
- [x] 4.1 全局 grep 确认 `MyCommissionService` / `myCommissionService` / `my_commission` 的所有引用(Handler、bootstrap、routes、cmd)
|
||||
- [x] 4.2 删除 `internal/service/my_commission/service.go` 及整个 `my_commission` 目录
|
||||
|
||||
## 5. Handler 层变更(ShopCommissionHandler 扩展)
|
||||
|
||||
- [x] 5.1 将 `ListCommissionSummary` 改造为 `ListFundSummary`(重命名+切换 DTO 类型),调用 `ShopCommissionService.ListShopFundSummary`。方法只在 Handler 层做参数解析,不写权限逻辑
|
||||
- [x] 5.2 新增 `GetCommissionStats` 方法,从路径参数取 `shop_id`,调用迁移后的 `GetStats`(权限校验在 Service 层)
|
||||
- [x] 5.3 新增 `GetCommissionDailyStats` 方法,从路径参数取 `shop_id`,调用迁移后的 `GetDailyStats`
|
||||
- [x] 5.4 新增 `CreateWithdrawal` 方法,从路径参数取 `shop_id`,调用迁移后的 `CreateWithdrawalRequest`
|
||||
- [x] 5.5 新增 `ListMainWalletTransactions` 方法,从路径参数取 `shop_id`,调用 `ShopCommissionService.ListMainWalletTransactions`
|
||||
- [x] 5.6 Handler 注释同步更新(HTTP 方法和路径),遵循 comment-standards
|
||||
|
||||
## 6. Handler 层删除(MyCommissionHandler)
|
||||
|
||||
- [x] 6.1 删除 `internal/handler/admin/my_commission.go`
|
||||
|
||||
## 7. 路由层变更
|
||||
|
||||
- [x] 7.1 在 `registerShopCommissionRoutes` 中:将 `GET /commission-summary` 改为 `GET /fund-summary`,更新 Summary 为 "代理商资金概况",更新 Tags、Input(`ShopFundSummaryListReq`)、Output(`ShopFundSummaryPageResult`)
|
||||
- [x] 7.2 在 `registerShopCommissionRoutes` 中新增四条路由:
|
||||
- `GET /:shop_id/main-wallet/transactions` → `ListMainWalletTransactions`
|
||||
- `GET /:shop_id/commission-stats` → `GetCommissionStats`
|
||||
- `GET /:shop_id/commission-daily-stats` → `GetCommissionDailyStats`
|
||||
- `POST /:shop_id/withdrawal-requests` → `CreateWithdrawal`
|
||||
- [x] 7.3 删除 `internal/routes/my_commission.go`
|
||||
- [x] 7.4 在路由注册入口(`internal/routes/admin.go` 或 registry)中移除 `registerMyCommissionRoutes` 的调用
|
||||
|
||||
## 8. Bootstrap 变更
|
||||
|
||||
- [x] 8.1 在 `internal/bootstrap/types.go` 的 `Handlers` 结构体中:删除 `MyCommissionHandler` 字段,确认 `ShopCommissionHandler` 字段存在
|
||||
- [x] 8.2 在 `internal/bootstrap/services.go` 中:删除 `myCommissionService` 的初始化,移除对 `my_commission` 包的引用;更新 `shopCommissionService` 的初始化,补充 task 3.0 新增的两个依赖(`stores.CommissionWithdrawalSetting`、`stores.AgentWalletTransaction`)
|
||||
- [x] 8.3 在 `internal/bootstrap/handlers.go` 中删除 `MyCommissionHandler` 的初始化
|
||||
|
||||
## 9. 文档生成器更新
|
||||
|
||||
- [x] 9.1 在 `cmd/api/docs.go` 中:删除 `NewMyCommissionHandler(nil)` 相关行,确认 `ShopCommissionHandler` 已包含新方法
|
||||
- [x] 9.2 在 `cmd/gendocs/main.go` 中做同样清理
|
||||
|
||||
## 10. 编译与验证
|
||||
|
||||
- [x] 10.1 执行 `go build ./...`,确保无编译错误
|
||||
- [x] 10.2 `grep -rn "MyCommission\|my_commission\|ListByShopID\|CountByShopID\|ShopCommissionSummary" --include="*.go"` 确认无残留引用
|
||||
- [x] 10.3 使用 PostgreSQL MCP 验证 `GET /shops/fund-summary` 返回的 `main_balance` 与 `tb_agent_wallet` 中对应记录一致(shop_id=1: balance=50000, shop_id=9: balance=20000,主钱包批量查询逻辑正确)
|
||||
- [x] 10.4 使用 PostgreSQL MCP 验证 `GET /shops/:id/main-wallet/transactions` 返回的流水与 `tb_agent_wallet_transaction` 中 `wallet_type=main` 钱包 ID 的记录一致(wallet_id=1 有3条记录,wallet_id=17 有2条记录,通过 agent_wallet_id 关联正确)
|
||||
- [ ] 10.5 手动验证代理越权:
|
||||
- 代理账号 A 请求 `/shops/{B的shop_id}/commission-records` / `/commission-stats` / `/commission-daily-stats` / `/withdrawal-requests` / `/main-wallet/transactions`(B 不是 A 的下级)应全部返回 403
|
||||
- 顶级代理 P 请求 `POST /shops/{下级shop_id}/withdrawal-requests` 应返回 403"仅可为本人店铺发起提现"(验证比 `CanManageShop` 更严格的限制)
|
||||
- 平台账号请求 `POST /shops/:shop_id/withdrawal-requests` 应返回 403"仅代理商用户可发起提现"
|
||||
- [ ] 10.6 验证原 `/my/commission-stats`、`/my/commission-daily-stats`、`POST /my/withdrawal-requests` 迁移后数据返回与迁移前等价(相同 shopID 相同查询条件,结果一致)
|
||||
@@ -31,7 +31,6 @@ func BuildDocHandlers() *bootstrap.Handlers {
|
||||
EnterpriseCard: admin.NewEnterpriseCardHandler(nil),
|
||||
EnterpriseDevice: admin.NewEnterpriseDeviceHandler(nil),
|
||||
Authorization: admin.NewAuthorizationHandler(nil),
|
||||
MyCommission: admin.NewMyCommissionHandler(nil),
|
||||
IotCard: admin.NewIotCardHandler(nil),
|
||||
IotCardImport: admin.NewIotCardImportHandler(nil),
|
||||
Device: admin.NewDeviceHandler(nil),
|
||||
|
||||
Reference in New Issue
Block a user