fin-check-api/db/category.go

41 lines
852 B
Go
Raw Normal View History

2024-08-01 23:02:55 +02:00
package db
2024-08-03 09:49:46 +02:00
import (
"errors"
"gorm.io/gorm"
)
2024-08-01 23:02:55 +02:00
type Category struct {
gorm.Model
Name string
// Parent is used as a infinite sub-category structure
ParentID uint
Parent *Category
2024-08-03 09:46:15 +02:00
UserID uint
User *User
2024-08-01 23:02:55 +02:00
}
2024-08-03 09:49:46 +02:00
var (
ERROR_CATEGORY_PARENT_NOT_FOUND = errors.New("ParentID is invalid for user")
ERROR_CATEGORY_NAME_NOT_UNIQUE = errors.New("Name for Category have to be unique for user")
)
func (c *Category) BeforeSave(tx *gorm.DB) error {
var parent Category
if err := tx.Find(&parent, Category{ParentID: c.ParentID, UserID: c.UserID}).Error; err != nil {
return err
}
if parent.ID == 0 {
return ERROR_CATEGORY_PARENT_NOT_FOUND
}
var dup Category
if err := tx.Find(&dup, Category{Name: c.Name, UserID: c.UserID}).Error; err != nil {
return err
}
if dup.ID != 0 {
return ERROR_CATEGORY_NAME_NOT_UNIQUE
}
return nil
}