241 lines
6.8 KiB
Go
241 lines
6.8 KiB
Go
package wallet
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"math"
|
|
"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, page, pageSize int) (*PaginatedResult, error) {
|
|
var total int64
|
|
if err := r.db.Model(&model.WalletLedger{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
offset := (page - 1) * pageSize
|
|
var rows []model.WalletLedger
|
|
if err := r.db.Where("user_id = ?", userID).Order("id DESC").Offset(offset).Limit(pageSize).Find(&rows).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
items := make([]LedgerDTO, 0, len(rows))
|
|
for _, row := range rows {
|
|
items = append(items, toLedgerDTO(row))
|
|
}
|
|
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
|
}
|
|
|
|
func (r *Repository) Recharge(userID uint64, amount float64) (*AccountDTO, error) {
|
|
err := r.db.Transaction(func(tx *gorm.DB) error {
|
|
return AppendEntries(tx, Entry{
|
|
UserID: userID,
|
|
Direction: "in",
|
|
Amount: amount,
|
|
BalanceType: "available",
|
|
BizType: "dev_recharge",
|
|
BizNo: "DEV",
|
|
Remark: "开发环境充值",
|
|
})
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return r.Account(userID)
|
|
}
|
|
|
|
func (r *Repository) AdminLedger(query AdminLedgerQuery) (*PaginatedResult, error) {
|
|
db := r.db.Table("wallet_ledger AS wl").
|
|
Select(`wl.id, wl.ledger_no, wl.user_id, COALESCE(u.phone, '') AS user_phone,
|
|
COALESCE(u.nickname, '') AS user_nickname, wl.order_id, COALESCE(ro.order_no, '') AS order_no,
|
|
wl.direction, wl.amount, wl.balance_after, wl.balance_type, wl.biz_type, wl.biz_no,
|
|
wl.remark, wl.created_at`).
|
|
Joins("LEFT JOIN users AS u ON u.id = wl.user_id").
|
|
Joins("LEFT JOIN rental_orders AS ro ON ro.id = wl.order_id")
|
|
|
|
countDB := r.db.Model(&model.WalletLedger{})
|
|
if query.UserID > 0 {
|
|
db = db.Where("wl.user_id = ?", query.UserID)
|
|
countDB = countDB.Where("user_id = ?", query.UserID)
|
|
}
|
|
if query.OrderID > 0 {
|
|
db = db.Where("wl.order_id = ?", query.OrderID)
|
|
countDB = countDB.Where("order_id = ?", query.OrderID)
|
|
}
|
|
if query.BizType != "" {
|
|
db = db.Where("wl.biz_type = ?", query.BizType)
|
|
countDB = countDB.Where("biz_type = ?", query.BizType)
|
|
}
|
|
|
|
var total int64
|
|
if err := countDB.Count(&total).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
offset := (query.Page - 1) * query.PageSize
|
|
var items []AdminLedgerDTO
|
|
if err := db.Order("wl.id DESC").Offset(offset).Limit(query.PageSize).Scan(&items).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
|
|
}
|
|
|
|
func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
|
for _, entry := range entries {
|
|
entry.Amount = roundWalletMoney(entry.Amount)
|
|
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) {
|
|
println("DEBUG APPLY:", entry.UserID, "type:", entry.BalanceType, "dir:", entry.Direction, "amt:", fmt.Sprintf("%.2f", entry.Amount), "avail:", fmt.Sprintf("%.2f", account.AvailableBalance), "frozen:", fmt.Sprintf("%.2f", account.FrozenBalance))
|
|
entry.Amount = roundWalletMoney(entry.Amount)
|
|
account.AvailableBalance = roundWalletMoney(account.AvailableBalance)
|
|
account.FrozenBalance = roundWalletMoney(account.FrozenBalance)
|
|
switch entry.BalanceType {
|
|
case "available":
|
|
if entry.Direction == "in" {
|
|
account.AvailableBalance = roundWalletMoney(account.AvailableBalance + entry.Amount)
|
|
} else {
|
|
if account.AvailableBalance < entry.Amount {
|
|
return 0, ErrInsufficientBalance
|
|
}
|
|
account.AvailableBalance = roundWalletMoney(account.AvailableBalance - entry.Amount)
|
|
}
|
|
return account.AvailableBalance, nil
|
|
case "frozen":
|
|
if entry.Direction == "in" {
|
|
account.FrozenBalance = roundWalletMoney(account.FrozenBalance + entry.Amount)
|
|
} else {
|
|
if account.FrozenBalance < entry.Amount {
|
|
return 0, ErrInsufficientBalance
|
|
}
|
|
account.FrozenBalance = roundWalletMoney(account.FrozenBalance - entry.Amount)
|
|
}
|
|
return account.FrozenBalance, nil
|
|
default:
|
|
return 0, fmt.Errorf("unsupported balance type: %s", entry.BalanceType)
|
|
}
|
|
}
|
|
|
|
func roundWalletMoney(value float64) float64 {
|
|
return math.Round(value)
|
|
}
|
|
|
|
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
|
|
}
|