2024-08-01 23:02:55 +02:00
|
|
|
package db
|
|
|
|
|
2024-08-03 09:44:06 +02:00
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
2024-08-01 23:02:55 +02:00
|
|
|
|
2024-08-03 07:05:46 +02:00
|
|
|
// Card can be either card or wallet
|
|
|
|
type Card struct {
|
2024-08-01 23:02:55 +02:00
|
|
|
gorm.Model
|
|
|
|
Name string
|
2024-11-20 19:59:48 +01:00
|
|
|
LastDigits string
|
2024-11-01 08:26:37 +01:00
|
|
|
Balance uint64
|
2024-08-01 23:02:55 +02:00
|
|
|
HaveCreditLine bool
|
|
|
|
CreditLine uint64
|
2024-11-20 19:59:48 +01:00
|
|
|
CurrencyID uint
|
|
|
|
Currency *Currency
|
2024-08-03 07:06:46 +02:00
|
|
|
UserID uint
|
|
|
|
User *User
|
2024-08-01 23:02:55 +02:00
|
|
|
}
|
2024-08-03 09:44:06 +02:00
|
|
|
|
2024-10-31 09:09:38 +01:00
|
|
|
// Implements db.UserIdentifiable:1
|
|
|
|
func (c Card) GetID() uint {
|
|
|
|
return c.ID
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implements db.UserIdentifiable:2
|
|
|
|
func (c Card) GetUserID() uint {
|
|
|
|
return c.UserID
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implements db.UserIdentifiable:3
|
|
|
|
func (c *Card) SetUserID(id uint) {
|
|
|
|
c.UserID = id
|
|
|
|
}
|
|
|
|
|
2024-08-03 09:44:06 +02:00
|
|
|
var (
|
2024-10-31 10:05:06 +01:00
|
|
|
ERROR_CARD_NAME_EMPTY = errors.New("The 'Name' field for 'Card' cannot be empty")
|
|
|
|
ERROR_CARD_NAME_NOT_UNIQUE = errors.New("The 'Name' field for 'Card' have to be unique for user")
|
2024-11-20 19:59:48 +01:00
|
|
|
ERROR_CARD_CANT_FIND_CURR = errors.New("The 'CurrencyID' field for 'Card' is invalid")
|
2024-08-03 09:44:06 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func (c *Card) BeforeSave(tx *gorm.DB) error {
|
|
|
|
if c.Name == "" {
|
|
|
|
return ERROR_CARD_NAME_EMPTY
|
|
|
|
}
|
|
|
|
|
|
|
|
var dup Card
|
2024-08-03 09:45:09 +02:00
|
|
|
if err := tx.Find(&dup, Card{Name: c.Name, UserID: c.UserID}).Error; err != nil {
|
2024-08-03 09:44:06 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-10-31 09:09:50 +01:00
|
|
|
if c.ID != dup.ID && dup.ID != 0 {
|
2024-08-03 09:44:06 +02:00
|
|
|
return ERROR_CARD_NAME_NOT_UNIQUE
|
|
|
|
}
|
2024-11-20 19:59:48 +01:00
|
|
|
if c.CurrencyID != 0 {
|
|
|
|
var currency Currency
|
|
|
|
if err := tx.Find(¤cy, c.CurrencyID).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if currency.ID == 0 {
|
|
|
|
return ERROR_CARD_CANT_FIND_CURR
|
|
|
|
}
|
|
|
|
}
|
2024-08-03 09:44:06 +02:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|