You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
2.5 KiB
93 lines
2.5 KiB
package api
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gissleh/stufflog/database"
|
|
"github.com/gissleh/stufflog/internal/auth"
|
|
"github.com/gissleh/stufflog/internal/generate"
|
|
"github.com/gissleh/stufflog/internal/slerrors"
|
|
"github.com/gissleh/stufflog/models"
|
|
"github.com/gissleh/stufflog/services"
|
|
)
|
|
|
|
func ProjectGroup(g *gin.RouterGroup, db database.Database) {
|
|
l := services.Loader{DB: db}
|
|
|
|
g.GET("/", handler("projectGroups", func(c *gin.Context) (interface{}, error) {
|
|
return l.ListProjectGroups(c)
|
|
}))
|
|
|
|
g.GET("/:id", handler("projectGroup", func(c *gin.Context) (interface{}, error) {
|
|
return l.FindProject(c, c.Param("id"))
|
|
}))
|
|
|
|
g.POST("/", handler("projectGroup", func(c *gin.Context) (interface{}, error) {
|
|
group := models.ProjectGroup{}
|
|
err := c.BindJSON(&group)
|
|
if err != nil {
|
|
return nil, slerrors.BadRequest("Invalid JSON")
|
|
}
|
|
if group.Abbreviation == "" || group.Name == "" {
|
|
return nil, slerrors.BadRequest("Abbreviation and name cannot be left empty.")
|
|
}
|
|
|
|
group.ID = generate.ProjectGroupID()
|
|
group.UserID = auth.UserID(c)
|
|
if group.CategoryNames == nil {
|
|
group.CategoryNames = make(map[string]string)
|
|
}
|
|
|
|
err = db.ProjectGroups().Insert(c.Request.Context(), group)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &group, nil
|
|
}))
|
|
|
|
g.PUT("/:id", handler("projectGroup", func(c *gin.Context) (interface{}, error) {
|
|
update := models.ProjectGroupUpdate{}
|
|
err := c.BindJSON(&update)
|
|
if err != nil {
|
|
return nil, slerrors.BadRequest("Invalid JSON")
|
|
}
|
|
if (update.Name != nil && *update.Name == "") || (update.Abbreviation != nil && *update.Abbreviation == "") {
|
|
return nil, slerrors.BadRequest("Abbreviation and name cannot be left empty.")
|
|
}
|
|
|
|
group, err := db.ProjectGroups().Find(c, c.Param("id"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if group.UserID != auth.UserID(c) {
|
|
return nil, slerrors.NotFound("Project group")
|
|
}
|
|
|
|
group.Update(update)
|
|
|
|
err = db.ProjectGroups().Update(c.Request.Context(), *group)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return group, nil
|
|
}))
|
|
|
|
g.DELETE("/:id", handler("project", func(c *gin.Context) (interface{}, error) {
|
|
group, err := l.FindProjectGroup(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(group.Projects) > 0 {
|
|
return nil, slerrors.Forbidden("You cannot delete non-empty project group.")
|
|
}
|
|
|
|
err = db.ProjectGroups().Delete(c.Request.Context(), group.ProjectGroup)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return group, nil
|
|
}))
|
|
}
|