fin-check-api/db/payment.go

50 lines
1.1 KiB
Go
Raw Normal View History

2024-08-01 23:02:55 +02:00
package db
import (
2024-11-28 12:42:59 +01:00
"errors"
2024-08-01 23:02:55 +02:00
"time"
"gorm.io/gorm"
)
// For grocery payment
type Payment struct {
gorm.Model
2024-08-03 07:05:46 +02:00
CardID uint
Card *Card
2024-08-01 23:02:55 +02:00
CategoryID uint
Category *Category
2024-11-01 21:54:29 +01:00
UserID uint
User *User
2024-11-01 08:30:51 +01:00
Title string
2024-08-01 23:02:55 +02:00
Descr string
Note string
Items []ItemBought `gorm:"constraint:OnDelete:CASCADE;"`
2024-08-01 23:02:55 +02:00
Date time.Time
}
func (p Payment) __internalBelogingToPayment() {}
2024-11-28 12:42:59 +01:00
var (
ERROR_PAYMENT_INVALID_CARD_USERID = errors.New("Payment's `UserID` and Card's `UserID` are not equal")
ERROR_PAYMENT_INVALID_CATEGORY_USERID = errors.New("Payment's `UserID` and Category's `UserID` are not equal")
)
func (p *Payment) BeforeSave(tx *gorm.DB) error {
paymentCard := &Card{}
if err := tx.Find(paymentCard, p.CardID).Error; err != nil {
return err
}
if paymentCard.UserID != p.UserID {
return ERROR_PAYMENT_INVALID_CARD_USERID
}
paymentCategory := &Category{}
if err := tx.Find(paymentCategory, p.CategoryID).Error; err != nil {
return err
}
if paymentCategory.UserID != p.UserID {
return ERROR_PAYMENT_INVALID_CATEGORY_USERID
}
return nil
}