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
|
|
|
|
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)
|
|
|
|
|
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
|
|
|
|
}
|