第 4 阶段:订单、交接与账务--ok
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package wallet
|
||||
|
||||
import "time"
|
||||
|
||||
type AccountDTO struct {
|
||||
UserID uint64 `json:"user_id"`
|
||||
AvailableBalance float64 `json:"available_balance"`
|
||||
FrozenBalance float64 `json:"frozen_balance"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type LedgerDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
LedgerNo string `json:"ledger_no"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
OrderID *uint64 `json:"order_id"`
|
||||
Direction string `json:"direction"`
|
||||
Amount float64 `json:"amount"`
|
||||
BalanceAfter float64 `json:"balance_after"`
|
||||
BalanceType string `json:"balance_type"`
|
||||
BizType string `json:"biz_type"`
|
||||
BizNo string `json:"biz_no"`
|
||||
Remark string `json:"remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"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 (h *Handler) Balance(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
account, err := h.service.Account(userID)
|
||||
if err != nil {
|
||||
writeWalletError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, account)
|
||||
}
|
||||
|
||||
func (h *Handler) Ledger(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
items, err := h.service.Ledger(userID)
|
||||
if err != nil {
|
||||
writeWalletError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (uint64, bool) {
|
||||
value, ok := c.Get(middleware.ContextUserID)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
userID, ok := value.(uint64)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
func writeWalletError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, ErrDependencyUnavailable):
|
||||
response.ServiceUnavailable(c, "数据库未连接")
|
||||
default:
|
||||
response.ServiceUnavailable(c, "钱包服务暂时不可用")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
type Entry struct {
|
||||
UserID uint64
|
||||
OrderID *uint64
|
||||
Direction string
|
||||
Amount float64
|
||||
BalanceType string
|
||||
BizType string
|
||||
BizNo string
|
||||
Remark string
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func (r *Repository) Account(userID uint64) (*AccountDTO, error) {
|
||||
var account model.WalletAccount
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := ensureAccount(tx, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Where("user_id = ?", userID).First(&account).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toAccountDTO(account), nil
|
||||
}
|
||||
|
||||
func (r *Repository) Ledger(userID uint64) ([]LedgerDTO, error) {
|
||||
var rows []model.WalletLedger
|
||||
if err := r.db.Where("user_id = ?", userID).Order("id DESC").Limit(100).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]LedgerDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
items = append(items, toLedgerDTO(row))
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
for _, entry := range entries {
|
||||
if entry.Amount <= 0 {
|
||||
continue
|
||||
}
|
||||
if err := ensureAccount(tx, entry.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
var account model.WalletAccount
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ?", entry.UserID).First(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
balanceAfter, err := applyEntry(&account, entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Save(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
ledgerNo, err := newLedgerNo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ledger := model.WalletLedger{
|
||||
LedgerNo: ledgerNo,
|
||||
UserID: entry.UserID,
|
||||
OrderID: entry.OrderID,
|
||||
Direction: entry.Direction,
|
||||
Amount: entry.Amount,
|
||||
BalanceAfter: balanceAfter,
|
||||
BalanceType: entry.BalanceType,
|
||||
BizType: entry.BizType,
|
||||
BizNo: entry.BizNo,
|
||||
Remark: entry.Remark,
|
||||
}
|
||||
if err := tx.Create(&ledger).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureAccount(tx *gorm.DB, userID uint64) error {
|
||||
account := model.WalletAccount{
|
||||
UserID: userID,
|
||||
AvailableBalance: 0,
|
||||
FrozenBalance: 0,
|
||||
Status: "active",
|
||||
}
|
||||
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error
|
||||
}
|
||||
|
||||
func applyEntry(account *model.WalletAccount, entry Entry) (float64, error) {
|
||||
switch entry.BalanceType {
|
||||
case "available":
|
||||
if entry.Direction == "in" {
|
||||
account.AvailableBalance += entry.Amount
|
||||
} else {
|
||||
account.AvailableBalance -= entry.Amount
|
||||
}
|
||||
return account.AvailableBalance, nil
|
||||
case "frozen":
|
||||
if entry.Direction == "in" {
|
||||
account.FrozenBalance += entry.Amount
|
||||
} else {
|
||||
account.FrozenBalance -= entry.Amount
|
||||
}
|
||||
return account.FrozenBalance, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unsupported balance type: %s", entry.BalanceType)
|
||||
}
|
||||
}
|
||||
|
||||
func toAccountDTO(account model.WalletAccount) *AccountDTO {
|
||||
return &AccountDTO{
|
||||
UserID: account.UserID,
|
||||
AvailableBalance: account.AvailableBalance,
|
||||
FrozenBalance: account.FrozenBalance,
|
||||
Status: account.Status,
|
||||
}
|
||||
}
|
||||
|
||||
func toLedgerDTO(row model.WalletLedger) LedgerDTO {
|
||||
return LedgerDTO{
|
||||
ID: row.ID,
|
||||
LedgerNo: row.LedgerNo,
|
||||
UserID: row.UserID,
|
||||
OrderID: row.OrderID,
|
||||
Direction: row.Direction,
|
||||
Amount: row.Amount,
|
||||
BalanceAfter: row.BalanceAfter,
|
||||
BalanceType: row.BalanceType,
|
||||
BizType: row.BizType,
|
||||
BizNo: row.BizNo,
|
||||
Remark: row.Remark,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func newLedgerNo() (string, error) {
|
||||
buf := make([]byte, 4)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("WL%d%s", time.Now().UnixNano(), hex.EncodeToString(buf)), nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package wallet
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
func (s *Service) Account(userID uint64) (*AccountDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Account(userID)
|
||||
}
|
||||
|
||||
func (s *Service) Ledger(userID uint64) ([]LedgerDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Ledger(userID)
|
||||
}
|
||||
Reference in New Issue
Block a user