app/calendar/calendar.go

67 lines
1.2 KiB
Go
Raw Normal View History

2021-12-21 11:23:34 +00:00
package calendar
2021-12-21 11:44:27 +00:00
import (
"time"
2021-12-21 11:23:34 +00:00
2021-12-21 11:44:27 +00:00
"github.com/rs/xid"
"github.com/rs/zerolog"
"gorm.io/gorm"
2021-12-24 08:56:16 +00:00
"kumoly.io/kumoly/app/auth"
"kumoly.io/kumoly/app/errors"
2021-12-21 11:44:27 +00:00
)
2021-12-21 11:23:34 +00:00
2021-12-21 11:44:27 +00:00
var l zerolog.Logger
2021-12-21 11:23:34 +00:00
2021-12-24 08:56:16 +00:00
var db *gorm.DB
2021-12-21 11:44:27 +00:00
type Calendar struct {
ID string `gorm:"primaryKey"`
2021-12-24 08:56:16 +00:00
Name string `gorm:"index:idx_cal,unique"`
Description string
Timezone string
2021-12-21 11:44:27 +00:00
Events []Event
2021-12-21 11:23:34 +00:00
2021-12-24 08:56:16 +00:00
Group auth.Group `json:"-"`
GroupName string `gorm:"-" json:"Group"`
GroupID uint `gorm:"index:idx_cal,unique" json:"-"`
2021-12-21 11:23:34 +00:00
CreatedAt time.Time
UpdatedAt time.Time
}
2021-12-24 08:56:16 +00:00
func (c *Calendar) BeforeSave(tx *gorm.DB) (err error) {
if c.GroupName != "" {
var grp_id uint
db.Raw("select id from groups where name = ?", c.GroupName).Scan(&grp_id)
if grp_id == 0 {
return errors.ErrorNotFound
}
c.GroupID = grp_id
} else {
c.GroupID = 0
}
return
}
2021-12-21 11:44:27 +00:00
func (c *Calendar) BeforeCreate(tx *gorm.DB) (err error) {
if c.ID == "" {
c.ID = xid.New().String()
}
2021-12-24 08:56:16 +00:00
if c.Timezone == "" {
c.Timezone = "Asia/Taipei"
}
return
}
func (c *Calendar) AfterFind(tx *gorm.DB) (err error) {
if c.GroupID != 0 {
var name string
db.Raw("select name from groups where id = ?", c.GroupID).Scan(&name)
c.GroupName = name
}
2021-12-21 11:44:27 +00:00
return
2021-12-21 11:23:34 +00:00
}