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 := "" db.Raw(`select id from events e where (? >= "start" and ? <= "end" ) or (? >= "start" and ? <= "end" ) and calendar_id = ? and id <> ? limit 1`, e.End, e.End, e.Start, e.Start, e.CalendarID, e.ID).Scan(&cnt) if cnt != "" { return errors.New(500, "event collide with existing") } 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 }