redeem_code.go 981 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package service
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "time"
  6. )
  7. type RedeemCode struct {
  8. ID int64
  9. Code string
  10. Type string
  11. Value float64
  12. Status string
  13. UsedBy *int64
  14. UsedAt *time.Time
  15. Notes string
  16. CreatedAt time.Time
  17. ExpiresAt *time.Time
  18. GroupID *int64
  19. ValidityDays int
  20. User *User
  21. Group *Group
  22. }
  23. func (r *RedeemCode) IsUsed() bool {
  24. return r.Status == StatusUsed
  25. }
  26. func (r *RedeemCode) IsExpired() bool {
  27. return r.IsExpiredAt(time.Now())
  28. }
  29. func (r *RedeemCode) IsExpiredAt(now time.Time) bool {
  30. if r == nil {
  31. return false
  32. }
  33. if r.Status == StatusExpired {
  34. return true
  35. }
  36. return r.Status == StatusUnused && r.ExpiresAt != nil && !r.ExpiresAt.After(now)
  37. }
  38. func (r *RedeemCode) CanUse() bool {
  39. return r.Status == StatusUnused && !r.IsExpired()
  40. }
  41. func GenerateRedeemCode() (string, error) {
  42. b := make([]byte, 16)
  43. if _, err := rand.Read(b); err != nil {
  44. return "", err
  45. }
  46. return hex.EncodeToString(b), nil
  47. }