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:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user