app/calendar/event.go

73 lines
1.3 KiB
Go
Raw Normal View History

2021-12-21 11:44:27 +00:00
package calendar
import (
"time"
"github.com/rs/xid"
"gorm.io/gorm"
2021-12-24 08:56:16 +00:00
"kumoly.io/kumoly/app/errors"
2021-12-21 11:44:27 +00:00
)
type Event struct {
ID string `gorm:"primaryKey"`
2021-12-26 08:19:18 +00:00
Start time.Time
End time.Time
Name string `gorm:"not null"`
Location string
2021-12-24 08:56:16 +00:00
2021-12-25 09:48:33 +00:00
Color string `gorm:"-"`
IsExt bool
2021-12-21 11:44:27 +00:00
CalendarID string
2021-12-25 09:48:33 +00:00
EventGroup EventGroup `json:"Detial"`
2021-12-21 11:44:27 +00:00
EventGroupID string
CreatedAt time.Time
UpdatedAt time.Time
}
2021-12-24 08:56:16 +00:00
func (e *Event) BeforeSave(tx *gorm.DB) (err error) {
2021-12-25 09:48:33 +00:00
if e.CalendarID == "" {
return errors.ErrorBadRequest
2021-12-24 08:56:16 +00:00
}
2021-12-26 09:55:23 +00:00
if e.Location == "" {
loc := ""
tx.Raw("select name from calendars where id = ?", e.CalendarID).Scan(&loc)
e.Location = loc
}
2022-01-09 08:48:10 +00:00
// test for collide
2022-01-09 08:49:50 +00:00
cnt := ""
db.Raw(`select id from events e where
2022-01-09 08:48:10 +00:00
(? >= "start" and ? <= "end" )
or
(? >= "start" and ? <= "end" )
2022-01-10 01:53:34 +00:00
and calendar_id = ? and id <> ? limit 1`,
e.End, e.End, e.Start, e.Start, e.CalendarID, e.ID).Scan(&cnt)
2022-01-09 08:49:50 +00:00
if cnt != "" {
return errors.New(500, "event collide with existing")
}
2022-01-09 08:48:10 +00:00
2021-12-24 08:56:16 +00:00
return
}
2021-12-21 11:44:27 +00:00
func (e *Event) BeforeCreate(tx *gorm.DB) (err error) {
if e.ID == "" {
e.ID = xid.New().String()
}
2021-12-25 09:48:33 +00:00
e.IsExt = false
2021-12-21 11:44:27 +00:00
return
}
2021-12-24 08:56:16 +00:00
func (e *Event) AfterFind(tx *gorm.DB) (err error) {
2021-12-25 09:48:33 +00:00
eg := EventGroup{}
if err := tx.First(&eg, "id = ?", e.EventGroupID).Error; err != nil {
return err
2021-12-24 08:56:16 +00:00
}
2021-12-25 09:48:33 +00:00
e.EventGroup = eg
2021-12-26 08:19:18 +00:00
e.Color = Color[e.EventGroup.Color%len(Color)]
2021-12-24 08:56:16 +00:00
return
}