From 9cd9b201634849574190c0d2adc3085f17e89bf9 Mon Sep 17 00:00:00 2001 From: qowevisa Date: Wed, 20 Nov 2024 18:19:19 +0200 Subject: [PATCH] Add db hooks for Item --- db/item.go | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/db/item.go b/db/item.go index 3dff6e4..a9c1501 100644 --- a/db/item.go +++ b/db/item.go @@ -1,6 +1,10 @@ package db -import "gorm.io/gorm" +import ( + "errors" + + "gorm.io/gorm" +) type Item struct { gorm.Model @@ -73,3 +77,35 @@ func GetItemToRootCat(id uint, preloadPrices bool) (*Item, error) { }).Preload("CurrentPrice").First(&item, id).Error return &item, err } + +var ( + ERROR_ITEM_PRICE_ISZERO = errors.New("Item's Price is zero") + ERROR_ITEM_ITEMPRICE_INTERR = errors.New("Item's ItemPrice ID is zero after creating") +) + +func (i *Item) BeforeCreate(tx *gorm.DB) error { + if i.Price == 0 { + return ERROR_ITEM_PRICE_ISZERO + } + return nil +} + +func (i *Item) AfterCreate(tx *gorm.DB) error { + if i.CurrentPriceID == 0 { + itemPrice := &ItemPrice{ + ItemID: i.ID, + Price: i.Price, + } + if err := tx.Create(itemPrice).Error; err != nil { + return err + } + if itemPrice.ID == 0 { + return ERROR_ITEM_ITEMPRICE_INTERR + } + i.CurrentPriceID = itemPrice.ID + if err := tx.Save(i).Error; err != nil { + return err + } + } + return nil +}