chore(init): 初始化解忧商行项目并完成 Phase 0 基座
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// 管理员查询提现列表
|
||||
func (r *Repository) AdminList(ctx context.Context, query AdminListQuery) (*AdminPaginatedResult, error) {
|
||||
db := r.db.WithContext(ctx).Model(&model.WithdrawalRequest{})
|
||||
|
||||
if query.Status != "" {
|
||||
db = db.Where("status = ?", query.Status)
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("user_id = ?", query.UserID)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
offset := (query.Page - 1) * query.Size
|
||||
var withdrawals []model.WithdrawalRequest
|
||||
if err := db.Order("created_at DESC").
|
||||
Offset(offset).Limit(query.Size).
|
||||
Find(&withdrawals).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]WithdrawalDetailDTO, 0, len(withdrawals))
|
||||
for _, w := range withdrawals {
|
||||
dto, err := r.toDetailDTO(ctx, w)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
items = append(items, *dto)
|
||||
}
|
||||
|
||||
return &AdminPaginatedResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: query.Page,
|
||||
PageSize: query.Size,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 管理员查询提现详情
|
||||
|
||||
// 管理员查询提现详情
|
||||
func (r *Repository) AdminFindByID(ctx context.Context, id uint64) (*WithdrawalDetailDTO, error) {
|
||||
var withdrawal model.WithdrawalRequest
|
||||
if err := r.db.WithContext(ctx).First(&withdrawal, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrWithdrawalNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return r.toDetailDTO(ctx, withdrawal)
|
||||
}
|
||||
|
||||
// 管理员审核提现
|
||||
|
||||
// 管理员审核提现
|
||||
func (r *Repository) Review(ctx context.Context, adminID, id uint64, req ReviewWithdrawalRequest) (*WithdrawalDetailDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var withdrawal model.WithdrawalRequest
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&withdrawal, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrWithdrawalNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// 事务内加行锁后重新校验,只有待审核状态可以审核,避免并发重复处理
|
||||
if withdrawal.Status != "pending" {
|
||||
return ErrWithdrawalLocked
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
approved := *req.Approved
|
||||
if approved {
|
||||
// 审核通过,进入处理中状态
|
||||
withdrawal.Status = "processing"
|
||||
} else {
|
||||
// 审核拒绝,解冻余额
|
||||
withdrawal.Status = "rejected"
|
||||
}
|
||||
withdrawal.ReviewedBy = &adminID
|
||||
withdrawal.ReviewedAt = &now
|
||||
withdrawal.ReviewRemark = req.Remark
|
||||
|
||||
if err := tx.Save(&withdrawal).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 如果拒绝,解冻余额
|
||||
if !approved {
|
||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||
UserID: withdrawal.UserID,
|
||||
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||
Direction: "out",
|
||||
AmountCent: withdrawal.AmountCent,
|
||||
BalanceType: "frozen",
|
||||
BizType: "withdraw_reject",
|
||||
BizNo: withdrawal.WithdrawNo,
|
||||
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
|
||||
}, wallet.Entry{
|
||||
UserID: withdrawal.UserID,
|
||||
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||
Direction: "in",
|
||||
AmountCent: withdrawal.AmountCent,
|
||||
BalanceType: "available",
|
||||
BizType: "withdraw_reject",
|
||||
BizNo: withdrawal.WithdrawNo,
|
||||
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return r.AdminFindByID(ctx, id)
|
||||
}
|
||||
|
||||
// 管理员确认打款
|
||||
|
||||
// 管理员确认打款
|
||||
func (r *Repository) ConfirmPayment(ctx context.Context, adminID, id uint64, req ConfirmPaymentRequest) (*WithdrawalDetailDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var withdrawal model.WithdrawalRequest
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&withdrawal, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrWithdrawalNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// 事务内加行锁后重新校验,只有处理中状态可以确认打款,避免并发重复扣减冻结余额
|
||||
if withdrawal.Status != "processing" {
|
||||
return ErrWithdrawalLocked
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
withdrawal.Status = "completed"
|
||||
withdrawal.PaidBy = &adminID
|
||||
withdrawal.PaidAt = &now
|
||||
withdrawal.PaymentProofURL = req.PaymentProofURL
|
||||
withdrawal.PaymentRemark = req.Remark
|
||||
|
||||
if err := tx.Save(&withdrawal).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 扣除冻结余额
|
||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||
UserID: withdrawal.UserID,
|
||||
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||
Direction: "out",
|
||||
AmountCent: withdrawal.AmountCent,
|
||||
BalanceType: "frozen",
|
||||
BizType: "withdraw_complete",
|
||||
BizNo: withdrawal.WithdrawNo,
|
||||
Remark: "提现完成",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return r.AdminFindByID(ctx, id)
|
||||
}
|
||||
|
||||
// 转换为用户DTO
|
||||
@@ -0,0 +1,96 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// 用户端 DTO
|
||||
type WithdrawalDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
WithdrawNo string `json:"withdraw_no"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
FeeCent int64 `json:"fee_cent"`
|
||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||
AccountType string `json:"account_type"`
|
||||
AccountName string `json:"account_name"`
|
||||
AccountNo string `json:"account_no"` // 脱敏
|
||||
BankName string `json:"bank_name"`
|
||||
Status string `json:"status"`
|
||||
ReviewRemark string `json:"review_remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
PaidAt *time.Time `json:"paid_at"`
|
||||
}
|
||||
|
||||
// 管理员端详细 DTO
|
||||
type WithdrawalDetailDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
WithdrawNo string `json:"withdraw_no"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
DistributionSiteName string `json:"distribution_site_name"`
|
||||
DistributionSiteCode string `json:"distribution_site_code"`
|
||||
UserNickname string `json:"user_nickname"`
|
||||
UserPhone string `json:"user_phone"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
FeeCent int64 `json:"fee_cent"`
|
||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||
PaymentAccountID *uint64 `json:"payment_account_id"`
|
||||
AccountType string `json:"account_type"`
|
||||
AccountName string `json:"account_name"`
|
||||
AccountNo string `json:"account_no"` // 管理员可见完整账号
|
||||
BankName string `json:"bank_name"`
|
||||
BankBranch string `json:"bank_branch"`
|
||||
CertificateURLs []string `json:"certificate_urls"` // 收款二维码图片
|
||||
Status string `json:"status"`
|
||||
ReviewedBy *uint64 `json:"reviewed_by"`
|
||||
ReviewedByName string `json:"reviewed_by_name"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
ReviewRemark string `json:"review_remark"`
|
||||
PaidBy *uint64 `json:"paid_by"`
|
||||
PaidByName string `json:"paid_by_name"`
|
||||
PaidAt *time.Time `json:"paid_at"`
|
||||
PaymentProofURL string `json:"payment_proof_url"`
|
||||
PaymentRemark string `json:"payment_remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type CreateWithdrawalRequest struct {
|
||||
PaymentAccountID uint64 `json:"payment_account_id" binding:"required"`
|
||||
AmountCent int64 `json:"amount_cent" binding:"required,gt=0"`
|
||||
}
|
||||
|
||||
type ReviewWithdrawalRequest struct {
|
||||
Approved *bool `json:"approved" binding:"required"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
type ConfirmPaymentRequest struct {
|
||||
PaymentProofURL string `json:"payment_proof_url"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
type PaginatedResult struct {
|
||||
Items []WithdrawalDTO `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type AdminPaginatedResult struct {
|
||||
Items []WithdrawalDetailDTO `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type AdminListQuery struct {
|
||||
Status string `form:"status"`
|
||||
UserID uint64 `form:"user_id"`
|
||||
Page int `form:"page"`
|
||||
Size int `form:"page_size"`
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestReviewWithdrawalRequestBindApprovedFalse(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("POST", "/admin/withdrawals/1/review", strings.NewReader(`{"approved":false,"remark":"资料不符"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var req ReviewWithdrawalRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
t.Fatalf("approved=false 应该通过参数绑定: %v", err)
|
||||
}
|
||||
if req.Approved == nil {
|
||||
t.Fatal("approved 字段应该被识别为已传入")
|
||||
}
|
||||
if *req.Approved {
|
||||
t.Fatal("approved=false 不应该被绑定成 true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewWithdrawalRequestBindMissingApproved(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("POST", "/admin/withdrawals/1/review", strings.NewReader(`{"remark":"资料不符"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var req ReviewWithdrawalRequest
|
||||
if err := c.ShouldBindJSON(&req); err == nil {
|
||||
t.Fatal("缺少 approved 字段时应该参数绑定失败")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateCertificateURLs(t *testing.T) {
|
||||
values := privateCertificateURLs([]string{
|
||||
"/api/public/files/object?key=payment-cert%2F2026%2F09%2F16%2Fqr.webp",
|
||||
"/api/public/files/object?key=avatar%2Fuser.jpg",
|
||||
"/api/files/object?key=payment-cert%2Falready_private.webp",
|
||||
})
|
||||
if values[0] != "/api/files/object?key=payment-cert%2F2026%2F09%2F16%2Fqr.webp" {
|
||||
t.Fatalf("expected private URL for payment-cert, got %q", values[0])
|
||||
}
|
||||
if values[1] != "/api/public/files/object?key=avatar%2Fuser.jpg" {
|
||||
t.Fatalf("non-payment-cert URL should not be changed, got %q", values[1])
|
||||
}
|
||||
if values[2] != "/api/files/object?key=payment-cert%2Falready_private.webp" {
|
||||
t.Fatalf("already private URL should not be changed, got %q", values[2])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
func parseSiteCode(c *gin.Context) string {
|
||||
return sitecode.FromRequest(c)
|
||||
}
|
||||
|
||||
// ========== 用户端接口 ==========
|
||||
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateWithdrawalRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "请求参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
siteCode := parseSiteCode(c)
|
||||
withdrawal, err := h.service.Create(c.Request.Context(), userID, req, siteCode)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, withdrawal)
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
siteCode := parseSiteCode(c)
|
||||
result, err := h.service.List(c.Request.Context(), userID, page, pageSize, siteCode)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) FindByID(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := parseID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
withdrawal, err := h.service.FindByID(c.Request.Context(), userID, id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, withdrawal)
|
||||
}
|
||||
|
||||
func (h *Handler) Cancel(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := parseID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.Cancel(c.Request.Context(), userID, id); err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"cancelled": true})
|
||||
}
|
||||
|
||||
// ========== 管理员端接口 ==========
|
||||
|
||||
func (h *Handler) AdminList(c *gin.Context) {
|
||||
var query AdminListQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
query.Page = 1
|
||||
query.Size = 20
|
||||
}
|
||||
|
||||
result, err := h.service.AdminList(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) AdminFindByID(c *gin.Context) {
|
||||
id, ok := parseID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
withdrawal, err := h.service.AdminFindByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, withdrawal)
|
||||
}
|
||||
|
||||
func (h *Handler) Review(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := parseID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var req ReviewWithdrawalRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "请求参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
withdrawal, err := h.service.Review(c.Request.Context(), adminID, id, req)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, withdrawal)
|
||||
}
|
||||
|
||||
func (h *Handler) ConfirmPayment(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := parseID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var req ConfirmPaymentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "请求参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
withdrawal, err := h.service.ConfirmPayment(c.Request.Context(), adminID, id, req)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, withdrawal)
|
||||
}
|
||||
|
||||
// ========== 辅助函数 ==========
|
||||
|
||||
func currentUserID(c *gin.Context) (uint64, bool) {
|
||||
val, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
userID, ok := val.(uint64)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
func currentAdminID(c *gin.Context) (uint64, bool) {
|
||||
val, exists := c.Get("admin_id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
adminID, ok := val.(uint64)
|
||||
return adminID, ok
|
||||
}
|
||||
|
||||
func parseID(c *gin.Context) (uint64, bool) {
|
||||
idStr := c.Param("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "无效的ID")
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func writeError(c *gin.Context, err error) {
|
||||
response.RecordError(c, err)
|
||||
switch err {
|
||||
case ErrWithdrawalNotFound:
|
||||
response.NotFound(c, "提现申请不存在")
|
||||
case ErrInvalidAmount:
|
||||
response.BadRequest(c, "提现金额无效")
|
||||
case ErrInsufficientBalance:
|
||||
response.BadRequest(c, "余额不足")
|
||||
case ErrMinWithdrawalAmount:
|
||||
response.BadRequest(c, "提现金额低于最小限额")
|
||||
case ErrMaxWithdrawalAmount:
|
||||
response.BadRequest(c, "提现金额超过最大限额")
|
||||
case ErrWithdrawalLocked:
|
||||
response.BadRequest(c, "提现申请状态已锁定,无法操作")
|
||||
case ErrInvalidReviewAction:
|
||||
response.BadRequest(c, "审核参数无效")
|
||||
case ErrUnauthorized:
|
||||
response.Unauthorized(c, "无权限操作")
|
||||
default:
|
||||
response.InternalServerError(c, "操作失败")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 生成提现单号
|
||||
func generateWithdrawNo() (string, error) {
|
||||
buf := make([]byte, 8)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("WD%d%s", time.Now().Unix(), hex.EncodeToString(buf)[:8]), nil
|
||||
}
|
||||
|
||||
// 账号脱敏
|
||||
|
||||
// 账号脱敏
|
||||
func maskAccountNo(accountNo, accountType string) string {
|
||||
length := len(accountNo)
|
||||
if length <= 4 {
|
||||
return accountNo
|
||||
}
|
||||
|
||||
switch accountType {
|
||||
case "alipay", "wechat":
|
||||
if length == 11 {
|
||||
return accountNo[:3] + "****" + accountNo[7:]
|
||||
}
|
||||
return accountNo[:2] + "****" + accountNo[length-2:]
|
||||
case "bank":
|
||||
if length > 8 {
|
||||
return accountNo[:4] + "****" + accountNo[length-4:]
|
||||
}
|
||||
return accountNo[:2] + "****" + accountNo[length-2:]
|
||||
}
|
||||
return accountNo
|
||||
}
|
||||
|
||||
// 简化的解密函数(实际应该调用 paymentaccount 模块的解密)
|
||||
|
||||
// 简化的解密函数(实际应该调用 paymentaccount 模块的解密)
|
||||
func (r *Repository) decryptAccountNo(encrypted string) (string, error) {
|
||||
// 这里应该调用 paymentaccount 包的解密函数
|
||||
// 为了简化,直接返回(实际使用时需要正确实现)
|
||||
return encrypted, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
// 转换为用户DTO
|
||||
func toDTO(w model.WithdrawalRequest) WithdrawalDTO {
|
||||
return WithdrawalDTO{
|
||||
ID: w.ID,
|
||||
WithdrawNo: w.WithdrawNo,
|
||||
UserID: w.UserID,
|
||||
DistributionSiteID: w.DistributionSiteID,
|
||||
AmountCent: w.AmountCent,
|
||||
FeeCent: w.FeeCent,
|
||||
ActualAmountCent: w.ActualAmountCent,
|
||||
AccountType: w.AccountType,
|
||||
AccountName: w.AccountName,
|
||||
AccountNo: w.AccountNo,
|
||||
BankName: w.BankName,
|
||||
Status: w.Status,
|
||||
ReviewRemark: w.ReviewRemark,
|
||||
CreatedAt: w.CreatedAt,
|
||||
UpdatedAt: w.UpdatedAt,
|
||||
ReviewedAt: w.ReviewedAt,
|
||||
PaidAt: w.PaidAt,
|
||||
}
|
||||
}
|
||||
|
||||
// 转换为管理员详细DTO
|
||||
|
||||
// 转换为管理员详细DTO
|
||||
func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest) (*WithdrawalDetailDTO, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
// 查询用户信息
|
||||
var user model.User
|
||||
db.Select("nickname, phone").First(&user, w.UserID)
|
||||
|
||||
// 查询审核人信息
|
||||
var reviewedByName string
|
||||
if w.ReviewedBy != nil {
|
||||
var admin model.AdminUser
|
||||
if err := db.Select("nickname").First(&admin, *w.ReviewedBy).Error; err == nil {
|
||||
reviewedByName = admin.Nickname
|
||||
}
|
||||
}
|
||||
|
||||
// 查询打款人信息
|
||||
var paidByName string
|
||||
if w.PaidBy != nil {
|
||||
var admin model.AdminUser
|
||||
if err := db.Select("nickname").First(&admin, *w.PaidBy).Error; err == nil {
|
||||
paidByName = admin.Nickname
|
||||
}
|
||||
}
|
||||
|
||||
// 获取完整账号和收款二维码(管理员可见)
|
||||
fullAccountNo := w.AccountNo
|
||||
var certificateURLs []string
|
||||
if w.PaymentAccountID != nil {
|
||||
var paymentAccount model.UserPaymentAccount
|
||||
if err := db.First(&paymentAccount, *w.PaymentAccountID).Error; err == nil {
|
||||
// 解密账号
|
||||
decrypted, err := r.encryptor.Decrypt(paymentAccount.AccountNo)
|
||||
if err == nil {
|
||||
fullAccountNo = decrypted
|
||||
}
|
||||
// 解析收款二维码
|
||||
if paymentAccount.CertificateURLs != nil {
|
||||
json.Unmarshal(paymentAccount.CertificateURLs, &certificateURLs)
|
||||
}
|
||||
certificateURLs = privateCertificateURLs(certificateURLs)
|
||||
}
|
||||
}
|
||||
|
||||
var siteName, siteCode string
|
||||
if w.DistributionSiteID > 0 {
|
||||
var site model.DistributionSite
|
||||
if err := db.Select("site_name, site_code").First(&site, w.DistributionSiteID).Error; err == nil {
|
||||
siteName = site.SiteName
|
||||
siteCode = site.SiteCode
|
||||
}
|
||||
}
|
||||
|
||||
return &WithdrawalDetailDTO{
|
||||
ID: w.ID,
|
||||
WithdrawNo: w.WithdrawNo,
|
||||
UserID: w.UserID,
|
||||
DistributionSiteID: w.DistributionSiteID,
|
||||
DistributionSiteName: siteName,
|
||||
DistributionSiteCode: siteCode,
|
||||
UserNickname: user.Nickname,
|
||||
UserPhone: user.Phone,
|
||||
AmountCent: w.AmountCent,
|
||||
FeeCent: w.FeeCent,
|
||||
ActualAmountCent: w.ActualAmountCent,
|
||||
PaymentAccountID: w.PaymentAccountID,
|
||||
AccountType: w.AccountType,
|
||||
AccountName: w.AccountName,
|
||||
AccountNo: fullAccountNo,
|
||||
BankName: w.BankName,
|
||||
BankBranch: w.BankBranch,
|
||||
CertificateURLs: certificateURLs,
|
||||
Status: w.Status,
|
||||
ReviewedBy: w.ReviewedBy,
|
||||
ReviewedByName: reviewedByName,
|
||||
ReviewedAt: w.ReviewedAt,
|
||||
ReviewRemark: w.ReviewRemark,
|
||||
PaidBy: w.PaidBy,
|
||||
PaidByName: paidByName,
|
||||
PaidAt: w.PaidAt,
|
||||
PaymentProofURL: w.PaymentProofURL,
|
||||
PaymentRemark: w.PaymentRemark,
|
||||
CreatedAt: w.CreatedAt,
|
||||
UpdatedAt: w.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// privateCertificateURLs 兼容历史公开收款凭证 URL,统一经私有对象接口读取。
|
||||
func privateCertificateURLs(values []string) []string {
|
||||
for index, value := range values {
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil || parsed.Path != "/api/public/files/object" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(parsed.Query().Get("key"), "payment-cert/") {
|
||||
continue
|
||||
}
|
||||
parsed.Path = "/api/files/object"
|
||||
values[index] = parsed.String()
|
||||
}
|
||||
return values
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
walletRepo *wallet.Repository
|
||||
encryptor crypto.Encryptor
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB, walletRepo *wallet.Repository, encryptor crypto.Encryptor) *Repository {
|
||||
if encryptor == nil {
|
||||
encryptor = &crypto.MockEncryptor{}
|
||||
}
|
||||
return &Repository{
|
||||
db: db,
|
||||
walletRepo: walletRepo,
|
||||
encryptor: encryptor,
|
||||
}
|
||||
}
|
||||
|
||||
// 用户创建提现申请
|
||||
@@ -0,0 +1,200 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type withdrawalFixture struct {
|
||||
db *gorm.DB
|
||||
repo *Repository
|
||||
userID uint64
|
||||
adminID uint64
|
||||
accountID uint64
|
||||
}
|
||||
|
||||
func newWithdrawalFixture(t *testing.T) withdrawalFixture {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.AdminUser{},
|
||||
&model.UserPaymentAccount{},
|
||||
&model.WithdrawalRequest{},
|
||||
&model.WalletAccount{},
|
||||
&model.WalletLedger{},
|
||||
); err != nil {
|
||||
t.Fatalf("migrate fixture: %v", err)
|
||||
}
|
||||
|
||||
user := model.User{Phone: "13800000001", Nickname: "test-user", Status: "active"}
|
||||
admin := model.AdminUser{Username: "reviewer", PasswordHash: "test", Nickname: "reviewer", Status: "active"}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
if err := db.Create(&admin).Error; err != nil {
|
||||
t.Fatalf("create admin: %v", err)
|
||||
}
|
||||
account := model.UserPaymentAccount{
|
||||
UserID: user.ID, AccountType: "bank", AccountName: "Test User",
|
||||
AccountNo: "6222021234567890", BankName: "Test Bank", Status: "active",
|
||||
}
|
||||
if err := db.Create(&account).Error; err != nil {
|
||||
t.Fatalf("create payment account: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.WalletAccount{
|
||||
UserID: user.ID, AvailableBalanceCent: 100_000, Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create wallet: %v", err)
|
||||
}
|
||||
|
||||
return withdrawalFixture{
|
||||
db: db, repo: NewRepository(db, wallet.NewRepository(db), &crypto.MockEncryptor{}),
|
||||
userID: user.ID, adminID: admin.ID, accountID: account.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func (f withdrawalFixture) create(t *testing.T, amountCent int64) *WithdrawalDTO {
|
||||
t.Helper()
|
||||
dto, err := f.repo.Create(context.Background(), f.userID, CreateWithdrawalRequest{
|
||||
PaymentAccountID: f.accountID,
|
||||
AmountCent: amountCent,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create: %v", err)
|
||||
}
|
||||
return dto
|
||||
}
|
||||
|
||||
func (f withdrawalFixture) assertBalance(t *testing.T, available, frozen int64) {
|
||||
t.Helper()
|
||||
var account model.WalletAccount
|
||||
if err := f.db.Where("user_id = ?", f.userID).First(&account).Error; err != nil {
|
||||
t.Fatalf("load wallet: %v", err)
|
||||
}
|
||||
if account.AvailableBalanceCent != available || account.FrozenBalanceCent != frozen {
|
||||
t.Fatalf("balance = available:%d frozen:%d, want available:%d frozen:%d",
|
||||
account.AvailableBalanceCent, account.FrozenBalanceCent, available, frozen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithdrawalCreateAndCancelPreservesBalance(t *testing.T) {
|
||||
f := newWithdrawalFixture(t)
|
||||
dto := f.create(t, 20_000)
|
||||
if dto.Status != "pending" || dto.FeeCent != 0 || dto.ActualAmountCent != 20_000 {
|
||||
t.Fatalf("created withdrawal = %+v", dto)
|
||||
}
|
||||
f.assertBalance(t, 80_000, 20_000)
|
||||
|
||||
if err := f.repo.Cancel(context.Background(), f.userID, dto.ID); err != nil {
|
||||
t.Fatalf("Cancel: %v", err)
|
||||
}
|
||||
f.assertBalance(t, 100_000, 0)
|
||||
if err := f.repo.Cancel(context.Background(), f.userID, dto.ID); !errors.Is(err, ErrWithdrawalLocked) {
|
||||
t.Fatalf("second Cancel error = %v, want ErrWithdrawalLocked", err)
|
||||
}
|
||||
f.assertBalance(t, 100_000, 0)
|
||||
}
|
||||
|
||||
func TestWithdrawalRejectedReturnsFrozenBalanceOnce(t *testing.T) {
|
||||
f := newWithdrawalFixture(t)
|
||||
dto := f.create(t, 30_000)
|
||||
approved := false
|
||||
result, err := f.repo.Review(context.Background(), f.adminID, dto.ID, ReviewWithdrawalRequest{
|
||||
Approved: &approved,
|
||||
Remark: "account mismatch",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Review rejected: %v", err)
|
||||
}
|
||||
if result.Status != "rejected" || result.ReviewedByName != "reviewer" {
|
||||
t.Fatalf("review result = %+v", result)
|
||||
}
|
||||
f.assertBalance(t, 100_000, 0)
|
||||
if _, err := f.repo.Review(context.Background(), f.adminID, dto.ID, ReviewWithdrawalRequest{Approved: &approved}); !errors.Is(err, ErrWithdrawalLocked) {
|
||||
t.Fatalf("second Review error = %v, want ErrWithdrawalLocked", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithdrawalApprovedAndPaidConsumesFrozenBalanceOnce(t *testing.T) {
|
||||
f := newWithdrawalFixture(t)
|
||||
dto := f.create(t, 40_000)
|
||||
approved := true
|
||||
if _, err := f.repo.Review(context.Background(), f.adminID, dto.ID, ReviewWithdrawalRequest{Approved: &approved}); err != nil {
|
||||
t.Fatalf("Review approved: %v", err)
|
||||
}
|
||||
f.assertBalance(t, 60_000, 40_000)
|
||||
|
||||
result, err := f.repo.ConfirmPayment(context.Background(), f.adminID, dto.ID, ConfirmPaymentRequest{
|
||||
PaymentProofURL: "proof/test.png",
|
||||
Remark: "paid",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ConfirmPayment: %v", err)
|
||||
}
|
||||
if result.Status != "completed" || result.PaidByName != "reviewer" {
|
||||
t.Fatalf("payment result = %+v", result)
|
||||
}
|
||||
f.assertBalance(t, 60_000, 0)
|
||||
if _, err := f.repo.ConfirmPayment(context.Background(), f.adminID, dto.ID, ConfirmPaymentRequest{}); !errors.Is(err, ErrWithdrawalLocked) {
|
||||
t.Fatalf("second ConfirmPayment error = %v, want ErrWithdrawalLocked", err)
|
||||
}
|
||||
f.assertBalance(t, 60_000, 0)
|
||||
}
|
||||
|
||||
func TestWithdrawalCreateRollsBackWhenBalanceIsInsufficient(t *testing.T) {
|
||||
f := newWithdrawalFixture(t)
|
||||
_, err := f.repo.Create(context.Background(), f.userID, CreateWithdrawalRequest{
|
||||
PaymentAccountID: f.accountID,
|
||||
AmountCent: 100_001,
|
||||
})
|
||||
if !errors.Is(err, wallet.ErrInsufficientBalance) {
|
||||
t.Fatalf("Create error = %v, want ErrInsufficientBalance", err)
|
||||
}
|
||||
var count int64
|
||||
if err := f.db.Model(&model.WithdrawalRequest{}).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count withdrawals: %v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("withdrawal count = %d, want 0", count)
|
||||
}
|
||||
f.assertBalance(t, 100_000, 0)
|
||||
}
|
||||
|
||||
func TestWithdrawalDetailIncludesDistributionSiteInfo(t *testing.T) {
|
||||
f := newWithdrawalFixture(t)
|
||||
if err := f.db.AutoMigrate(&model.DistributionSite{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
site := model.DistributionSite{SiteCode: "sub_site", SiteName: "分销子站", Domain: "sub.example.com", Status: "active"}
|
||||
if err := f.db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wReq := model.WithdrawalRequest{
|
||||
WithdrawNo: "WD2026TESTSITE",
|
||||
UserID: f.userID,
|
||||
DistributionSiteID: site.ID,
|
||||
AmountCent: 5000,
|
||||
ActualAmountCent: 5000,
|
||||
Status: "pending",
|
||||
}
|
||||
if err := f.db.Create(&wReq).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
detail, err := f.repo.AdminFindByID(context.Background(), wReq.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("AdminFindByID failed: %v", err)
|
||||
}
|
||||
if detail.DistributionSiteID != site.ID || detail.DistributionSiteName != "分销子站" || detail.DistributionSiteCode != "sub_site" {
|
||||
t.Fatalf("unexpected detail site info: %+v", detail)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrWithdrawalNotFound = errors.New("withdrawal not found")
|
||||
ErrInvalidAmount = errors.New("invalid amount")
|
||||
ErrInsufficientBalance = errors.New("insufficient balance")
|
||||
ErrMinWithdrawalAmount = errors.New("amount below minimum withdrawal")
|
||||
ErrMaxWithdrawalAmount = errors.New("amount exceeds maximum withdrawal")
|
||||
ErrWithdrawalLocked = errors.New("withdrawal status locked")
|
||||
ErrInvalidReviewAction = errors.New("invalid review action")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
const (
|
||||
MinWithdrawalAmountCent = 1000 // 最低提现金额:10元 = 1000分
|
||||
MaxWithdrawalAmountCent = 500000 // 单笔最高提现金额:5000元 = 500000分
|
||||
WithdrawalFeeRate = 0.0 // 手续费率(暂时0%)
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
// 用户端方法
|
||||
func (s *Service) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest, siteCode ...string) (*WithdrawalDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
|
||||
// 验证金额
|
||||
if req.AmountCent < MinWithdrawalAmountCent {
|
||||
return nil, ErrMinWithdrawalAmount
|
||||
}
|
||||
if req.AmountCent > MaxWithdrawalAmountCent {
|
||||
return nil, ErrMaxWithdrawalAmount
|
||||
}
|
||||
|
||||
return s.repo.Create(ctx, userID, req, siteCode...)
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
return s.repo.List(ctx, userID, page, pageSize, siteCode...)
|
||||
}
|
||||
|
||||
func (s *Service) FindByID(ctx context.Context, userID, id uint64) (*WithdrawalDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.FindByID(ctx, userID, id)
|
||||
}
|
||||
|
||||
func (s *Service) Cancel(ctx context.Context, userID, id uint64) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Cancel(ctx, userID, id)
|
||||
}
|
||||
|
||||
// 管理员端方法
|
||||
func (s *Service) AdminList(ctx context.Context, query AdminListQuery) (*AdminPaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if query.Page < 1 {
|
||||
query.Page = 1
|
||||
}
|
||||
if query.Size < 1 || query.Size > 100 {
|
||||
query.Size = 20
|
||||
}
|
||||
return s.repo.AdminList(ctx, query)
|
||||
}
|
||||
|
||||
func (s *Service) AdminFindByID(ctx context.Context, id uint64) (*WithdrawalDetailDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.AdminFindByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) Review(ctx context.Context, adminID, id uint64, req ReviewWithdrawalRequest) (*WithdrawalDetailDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if req.Approved == nil {
|
||||
return nil, ErrInvalidReviewAction
|
||||
}
|
||||
return s.repo.Review(ctx, adminID, id, req)
|
||||
}
|
||||
|
||||
func (s *Service) ConfirmPayment(ctx context.Context, adminID, id uint64, req ConfirmPaymentRequest) (*WithdrawalDetailDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.ConfirmPayment(ctx, adminID, id, req)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package withdrawal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func (r *Repository) resolveSiteID(ctx context.Context, siteCode string) (uint64, error) {
|
||||
siteCode = strings.TrimSpace(siteCode)
|
||||
if siteCode == "" {
|
||||
return 0, nil
|
||||
}
|
||||
var site model.DistributionSite
|
||||
if err := r.db.WithContext(ctx).Where("site_code = ? AND status = 'active'", siteCode).First(&site).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return 0, errors.New("distribution site unavailable")
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return site.ID, nil
|
||||
}
|
||||
|
||||
// 用户创建提现申请
|
||||
func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest, siteCode ...string) (*WithdrawalDTO, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
// 验证收款账号
|
||||
var paymentAccount model.UserPaymentAccount
|
||||
if err := db.Where("id = ? AND user_id = ? AND status = ?", req.PaymentAccountID, userID, "active").
|
||||
First(&paymentAccount).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("payment account not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var code string
|
||||
if len(siteCode) > 0 {
|
||||
code = siteCode[0]
|
||||
}
|
||||
siteID, err := r.resolveSiteID(ctx, code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 计算手续费和实际到账金额(分)
|
||||
feeCent := int64(float64(req.AmountCent) * WithdrawalFeeRate)
|
||||
actualAmountCent := req.AmountCent - feeCent
|
||||
|
||||
// 生成提现单号
|
||||
withdrawNo, err := generateWithdrawNo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 解密账号(用于存储快照)
|
||||
decryptedNo, err := r.decryptAccountNo(paymentAccount.AccountNo)
|
||||
if err != nil {
|
||||
decryptedNo = paymentAccount.AccountNo
|
||||
}
|
||||
|
||||
withdrawal := model.WithdrawalRequest{
|
||||
WithdrawNo: withdrawNo,
|
||||
UserID: userID,
|
||||
DistributionSiteID: siteID,
|
||||
AmountCent: req.AmountCent,
|
||||
FeeCent: feeCent,
|
||||
ActualAmountCent: actualAmountCent,
|
||||
PaymentAccountID: &req.PaymentAccountID,
|
||||
AccountType: paymentAccount.AccountType,
|
||||
AccountName: paymentAccount.AccountName,
|
||||
AccountNo: maskAccountNo(decryptedNo, paymentAccount.AccountType),
|
||||
BankName: paymentAccount.BankName,
|
||||
BankBranch: paymentAccount.BankBranch,
|
||||
Status: "pending",
|
||||
}
|
||||
|
||||
// 事务处理
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
// 创建提现申请
|
||||
if err := tx.Create(&withdrawal).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 冻结用户余额
|
||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: siteID,
|
||||
Direction: "out",
|
||||
AmountCent: req.AmountCent,
|
||||
BalanceType: "available",
|
||||
BizType: "withdraw_freeze",
|
||||
BizNo: withdrawNo,
|
||||
Remark: "提现冻结",
|
||||
}, wallet.Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: siteID,
|
||||
Direction: "in",
|
||||
AmountCent: req.AmountCent,
|
||||
BalanceType: "frozen",
|
||||
BizType: "withdraw_freeze",
|
||||
BizNo: withdrawNo,
|
||||
Remark: "提现冻结",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return r.FindByID(ctx, userID, withdrawal.ID)
|
||||
}
|
||||
|
||||
// 用户查询提现列表
|
||||
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
var code string
|
||||
if len(siteCode) > 0 {
|
||||
code = siteCode[0]
|
||||
}
|
||||
siteID, err := r.resolveSiteID(ctx, code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
countDB := db.Model(&model.WithdrawalRequest{}).Where("user_id = ?", userID)
|
||||
dataDB := db.Where("user_id = ?", userID)
|
||||
if siteID > 0 {
|
||||
countDB = countDB.Where("distribution_site_id = ?", siteID)
|
||||
dataDB = dataDB.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
countDB = countDB.Where("distribution_site_id = 0 OR distribution_site_id IS NULL")
|
||||
dataDB = dataDB.Where("distribution_site_id = 0 OR distribution_site_id IS NULL")
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := countDB.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
var withdrawals []model.WithdrawalRequest
|
||||
if err := dataDB.Order("created_at DESC").
|
||||
Offset(offset).Limit(pageSize).
|
||||
Find(&withdrawals).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]WithdrawalDTO, 0, len(withdrawals))
|
||||
for _, w := range withdrawals {
|
||||
items = append(items, toDTO(w))
|
||||
}
|
||||
|
||||
return &PaginatedResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 用户查询提现详情
|
||||
|
||||
// 用户查询提现详情
|
||||
func (r *Repository) FindByID(ctx context.Context, userID, id uint64) (*WithdrawalDTO, error) {
|
||||
var withdrawal model.WithdrawalRequest
|
||||
if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ?", id, userID).
|
||||
First(&withdrawal).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrWithdrawalNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto := toDTO(withdrawal)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// 用户取消提现
|
||||
|
||||
// 用户取消提现
|
||||
func (r *Repository) Cancel(ctx context.Context, userID, id uint64) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var withdrawal model.WithdrawalRequest
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("id = ? AND user_id = ?", id, userID).
|
||||
First(&withdrawal).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrWithdrawalNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// 事务内加行锁后重新校验,只有待审核状态可以取消,避免与管理员审核并发重复解冻
|
||||
if withdrawal.Status != "pending" {
|
||||
return ErrWithdrawalLocked
|
||||
}
|
||||
|
||||
// 更新状态
|
||||
if err := tx.Model(&withdrawal).Update("status", "cancelled").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解冻余额
|
||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||
Direction: "out",
|
||||
AmountCent: withdrawal.AmountCent,
|
||||
BalanceType: "frozen",
|
||||
BizType: "withdraw_cancel",
|
||||
BizNo: withdrawal.WithdrawNo,
|
||||
Remark: "用户取消提现",
|
||||
}, wallet.Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||
Direction: "in",
|
||||
AmountCent: withdrawal.AmountCent,
|
||||
BalanceType: "available",
|
||||
BizType: "withdraw_cancel",
|
||||
BizNo: withdrawal.WithdrawNo,
|
||||
Remark: "用户取消提现",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// 管理员查询提现列表
|
||||
Reference in New Issue
Block a user