package calendar import ( "github.com/gin-gonic/gin" "gorm.io/gorm" "kumoly.io/kumoly/app/auth" "kumoly.io/kumoly/app/errors" "kumoly.io/kumoly/app/history" "kumoly.io/kumoly/app/server" ) func ApiEventQuery(c *gin.Context) { id := c.Query("id") if id != "" { e := &Event{} err := HasEventAccess(c, e, id) if err != nil { panic(err) } server.OK(c, e) } else { grp := c.Query("grp") events := []Event{} cl, err := auth.GetContextClaims(c) if err != nil { panic(err) } var result *gorm.DB if grp != "" { if !auth.ACHas(c, auth.ADMIN, auth.SYSTEM, grp) { panic(errors.ErrorForbidden) } result = db.Find(&events, `event_group_id in ( select id from event_groups where group_id = ( select id from groups where name = ? ) )`, grp) } else if !auth.ACHas(c, auth.ADMIN, auth.SYSTEM) { result = db.Find(&events, `event_group_id in ( select eg.id from event_groups eg where eg.group_id in ( select g.id from groups g where g.name in ? ) )`, cl.Groups) } else { result = db.Find(&events) } if result.Error != nil { panic(result.Error) } server.OK(c, events) } } func ApiEventNew(c *gin.Context) { e := &Event{} if err := c.ShouldBindJSON(e); err != nil { panic(err) } if e.ID != "" { panic(errors.ErrorBadRequest) } if e.Start.IsZero() || e.End.IsZero() || e.End.Before(e.Start) { panic(ErrorInvalidTime) } cal := 0 if db.Raw("select count(id) from calendars where id = ?", e.CalendarID). Scan(&cal); cal != 1 { panic(errors.ErrorNotFound) } if !auth.ACHas(c, auth.ADMIN, auth.SYSTEM, e.EventGroup.GroupName) { panic(errors.ErrorForbidden) } if e.EventGroup.Name == "" { e.EventGroup.Name = e.Name } if err := db.Transaction(func(tx *gorm.DB) error { if err := tx.Create(e).Error; err != nil { return err } return nil }); err != nil { panic(err) } history.Send(history.Info(). Nm("Create"). Grp(e.EventGroup.GroupName).Bd(e). Iss(c.GetString(auth.GinUserKey)). Msg("Event created")) server.OK(c, e) } func ApiEventUpdate(c *gin.Context) { e := &Event{} if err := c.ShouldBindJSON(e); err != nil { panic(err) } if e.ID == "" { panic(errors.ErrorBadRequest) } if err := HasEventAccess(c, &Event{}, e.ID); err != nil { panic(errors.ErrorForbidden) } if err := db.Save(e).Error; err != nil { panic(err) } history.Send(history.Info(). Nm("Update"). Grp(e.EventGroup.GroupName).Bd(e). Iss(c.GetString(auth.GinUserKey)). Msg("Event Updated")) server.OK(c, e) } func ApiEventDelete(c *gin.Context) { id := c.Query("id") if id == "" { panic(errors.ErrorBadRequest) } e := &Event{} err := HasEventAccess(c, e, id) if err != nil { panic(err) } err = db.Delete(e, "id = ?", id).Error if err != nil { panic(errors.NewError(404, err)) } db.Exec(`delete from event_groups where id = ? and 0 = (select count(id) from events where event_group_id = ?)`, e.EventGroupID, e.EventGroupID) history.Send(history.Info(). Nm("Delete"). Grp(e.EventGroup.GroupName).Bd(e). Iss(c.GetString(auth.GinUserKey)). Msg("Event Deleted")) server.OK(c, "ok") }