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
|
|
|
|
2024-10-31 22:05:38 +01:00
|
|
|
// Implements db.UserIdentifiable:1
|
|
|
|
func (c Category) GetID() uint {
|
|
|
|
return c.ID
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implements db.UserIdentifiable:2
|
|
|
|
func (c Category) GetUserID() uint {
|
|
|
|
return c.UserID
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implements db.UserIdentifiable:3
|
|
|
|
func (c *Category) SetUserID(id uint) {
|
|
|
|
c.UserID = id
|
|
|
|
}
|
|
|
|
|
2024-08-03 09:49:46 +02:00
|
|
|
var (
|
2024-10-31 22:05:18 +01:00
|
|
|
ERROR_CATEGORY_PARENT_NOT_FOUND = errors.New("Can't find Category with ParentID for user")
|
2024-08-03 09:57:13 +02:00
|
|
|
ERROR_CATEGORY_NAME_NOT_UNIQUE = errors.New("Name for Category have to be unique for user")
|
|
|
|
ERROR_CATEGORY_USER_ID_NOT_EQUAL = errors.New("ParentID is invalid for user")
|
2024-11-11 21:26:47 +01:00
|
|
|
ERROR_CATEGORY_SELF_REFERENCING = errors.New("Category can't set itself as a parent")
|
2024-08-03 09:49:46 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func (c *Category) BeforeSave(tx *gorm.DB) error {
|
2024-11-11 21:26:47 +01:00
|
|
|
if c.ParentID == c.ID {
|
|
|
|
return ERROR_CATEGORY_SELF_REFERENCING
|
|
|
|
}
|
2024-08-03 09:52:38 +02:00
|
|
|
if c.ParentID != 0 {
|
|
|
|
var parent Category
|
2024-11-11 21:26:21 +01:00
|
|
|
if err := tx.Find(&parent, c.ParentID).Error; err != nil {
|
2024-08-03 09:52:38 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if parent.ID == 0 {
|
|
|
|
return ERROR_CATEGORY_PARENT_NOT_FOUND
|
|
|
|
}
|
2024-08-03 09:57:13 +02:00
|
|
|
if parent.UserID != c.UserID {
|
|
|
|
return ERROR_CATEGORY_USER_ID_NOT_EQUAL
|
|
|
|
}
|
2024-08-03 09:49:46 +02:00
|
|
|
}
|
|
|
|
var dup Category
|
|
|
|
if err := tx.Find(&dup, Category{Name: c.Name, UserID: c.UserID}).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-11-11 21:26:21 +01:00
|
|
|
if c.ID != dup.ID && dup.ID != 0 {
|
2024-08-03 09:49:46 +02:00
|
|
|
return ERROR_CATEGORY_NAME_NOT_UNIQUE
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|