app/calendar/event.go

70 lines
1.3 KiB
Go

package calendar
import (
"time"
"github.com/rs/xid"
"gorm.io/gorm"
"kumoly.io/kumoly/app/errors"
)
type Event struct {
ID string `gorm:"primaryKey"`
Start time.Time
End time.Time
Name string `gorm:"not null"`
Location string
Color string `gorm:"-"`
IsExt bool
CalendarID string
EventGroup EventGroup `json:"Detial"`
EventGroupID string
CreatedAt time.Time
UpdatedAt time.Time
}
func (e *Event) BeforeSave(tx *gorm.DB) (err error) {
if e.CalendarID == "" {
return errors.ErrorBadRequest
}
if e.Location == "" {
loc := ""
tx.Raw("select name from calendars where id = ?", e.CalendarID).Scan(&loc)
e.Location = loc
}
// test for collide
cnt := 0
db.Raw(`select count(*) from events e where
(? >= "start" and ? <= "end" )
or
(? >= "start" and ? <= "end" )
and calendar_id = ?`,
e.End, e.End, e.Start, e.Start, e.CalendarID).Scan(&cnt)
return
}
func (e *Event) BeforeCreate(tx *gorm.DB) (err error) {
if e.ID == "" {
e.ID = xid.New().String()
}
e.IsExt = false
return
}
func (e *Event) AfterFind(tx *gorm.DB) (err error) {
eg := EventGroup{}
if err := tx.First(&eg, "id = ?", e.EventGroupID).Error; err != nil {
return err
}
e.EventGroup = eg
e.Color = Color[e.EventGroup.Color%len(Color)]
return
}