From e6d53c4d170036eb863e221aa81fbf97fb653e4c Mon Sep 17 00:00:00 2001 From: qowevisa Date: Thu, 28 Nov 2024 13:42:59 +0200 Subject: [PATCH] Add BeforeSave hook to db.Payment --- db/payment.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/db/payment.go b/db/payment.go index c05b47f..ec345e2 100644 --- a/db/payment.go +++ b/db/payment.go @@ -1,6 +1,7 @@ package db import ( + "errors" "time" "gorm.io/gorm" @@ -23,3 +24,26 @@ type Payment struct { } func (p Payment) __internalBelogingToPayment() {} + +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 +}