Files
tyapi-server/internal/domains/finance/entities/wallet.go
2025-07-11 21:05:58 +08:00

72 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package entities
import (
"fmt"
"time"
"github.com/shopspring/decimal"
"gorm.io/gorm"
)
// Wallet 钱包实体
// 用户数字钱包的核心信息,支持多种钱包类型和精确的余额管理
// 使用decimal类型确保金额计算的精确性避免浮点数精度问题
type Wallet struct {
// 基础标识
ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"钱包唯一标识"`
UserID string `gorm:"type:varchar(36);not null;uniqueIndex" json:"user_id" comment:"关联用户ID"`
// 钱包状态 - 钱包的基本状态信息
IsActive bool `gorm:"default:true" json:"is_active" comment:"钱包是否激活"`
Balance decimal.Decimal `gorm:"type:decimal(20,8);default:0" json:"balance" comment:"钱包余额(精确到8位小数)"`
// 钱包信息 - 钱包的详细配置信息
WalletAddress string `gorm:"type:varchar(255)" json:"wallet_address,omitempty" comment:"钱包地址"`
WalletType string `gorm:"type:varchar(50);default:'MAIN'" json:"wallet_type" comment:"钱包类型(MAIN/DEPOSIT/WITHDRAWAL)"` // MAIN, DEPOSIT, WITHDRAWAL
// 时间戳字段
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"`
}
// TableName 指定数据库表名
func (Wallet) TableName() string {
return "wallets"
}
// IsZeroBalance 检查余额是否为零
// 判断钱包余额是否为零,用于业务逻辑判断
func (w *Wallet) IsZeroBalance() bool {
return w.Balance.IsZero()
}
// HasSufficientBalance 检查是否有足够余额
// 判断钱包余额是否足够支付指定金额,用于交易前的余额验证
func (w *Wallet) HasSufficientBalance(amount decimal.Decimal) bool {
return w.Balance.GreaterThanOrEqual(amount)
}
// AddBalance 增加余额
// 向钱包增加指定金额,用于充值、收入等场景
func (w *Wallet) AddBalance(amount decimal.Decimal) {
w.Balance = w.Balance.Add(amount)
}
// SubtractBalance 减少余额
// 从钱包扣除指定金额,用于消费、转账等场景
// 如果余额不足会返回错误,确保资金安全
func (w *Wallet) SubtractBalance(amount decimal.Decimal) error {
if !w.HasSufficientBalance(amount) {
return fmt.Errorf("余额不足")
}
w.Balance = w.Balance.Sub(amount)
return nil
}
// GetFormattedBalance 获取格式化的余额字符串
// 将decimal类型的余额转换为字符串格式便于显示和传输
func (w *Wallet) GetFormattedBalance() string {
return w.Balance.String()
}