points_consumption_log.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package models
  2. import "time"
  3. // PointsConsumptionLog 积分消费记录
  4. type PointsConsumptionLog struct {
  5. ID uint `gorm:"primarykey;autoIncrement" json:"id"`
  6. UserID string `gorm:"type:varchar(255);not null;index" json:"user_id"`
  7. FileName string `gorm:"type:varchar(500);not null" json:"file_name"`
  8. FileURL string `gorm:"type:text" json:"file_url"`
  9. PointsConsumed int `gorm:"not null;default:10" json:"points_consumed"`
  10. BalanceAfter int `gorm:"not null" json:"balance_after"`
  11. CreatedAt *time.Time `gorm:"column:created_at" json:"created_at"`
  12. }
  13. // TableName 指定表名
  14. func (PointsConsumptionLog) TableName() string {
  15. return "points_consumption_log"
  16. }
  17. // CreateConsumptionLog 创建消费记录
  18. func CreateConsumptionLog(log *PointsConsumptionLog) error {
  19. // 使用原始SQL插入,避免GORM的时间字段处理问题
  20. result := DB.Exec(
  21. "INSERT INTO points_consumption_log (user_id, file_name, file_url, points_consumed, balance_after) VALUES (?, ?, ?, ?, ?)",
  22. log.UserID, log.FileName, log.FileURL, log.PointsConsumed, log.BalanceAfter,
  23. )
  24. return result.Error
  25. }
  26. // GetConsumptionHistory 获取用户消费记录(按时间倒序)
  27. func GetConsumptionHistory(userID string, page, pageSize int) ([]PointsConsumptionLog, int64, error) {
  28. var logs []PointsConsumptionLog
  29. var total int64
  30. DB.Model(&PointsConsumptionLog{}).Where("user_id = ?", userID).Count(&total)
  31. offset := (page - 1) * pageSize
  32. err := DB.Where("user_id = ?", userID).
  33. Order("created_at DESC").
  34. Offset(offset).
  35. Limit(pageSize).
  36. Find(&logs).Error
  37. return logs, total, err
  38. }