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

  1. package api
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/gissleh/stufflog/database"
  5. "github.com/gissleh/stufflog/internal/auth"
  6. "github.com/gissleh/stufflog/internal/generate"
  7. "github.com/gissleh/stufflog/internal/slerrors"
  8. "github.com/gissleh/stufflog/models"
  9. "github.com/gissleh/stufflog/services"
  10. )
  11. func ProjectGroup(g *gin.RouterGroup, db database.Database) {
  12. l := services.Loader{DB: db}
  13. g.GET("/", handler("projectGroups", func(c *gin.Context) (interface{}, error) {
  14. return l.ListProjectGroups(c)
  15. }))
  16. g.GET("/:id", handler("projectGroup", func(c *gin.Context) (interface{}, error) {
  17. return l.FindProject(c, c.Param("id"))
  18. }))
  19. g.POST("/", handler("projectGroup", func(c *gin.Context) (interface{}, error) {
  20. group := models.ProjectGroup{}
  21. err := c.BindJSON(&group)
  22. if err != nil {
  23. return nil, slerrors.BadRequest("Invalid JSON")
  24. }
  25. if group.Abbreviation == "" || group.Name == "" {
  26. return nil, slerrors.BadRequest("Abbreviation and name cannot be left empty.")
  27. }
  28. group.ID = generate.ProjectGroupID()
  29. group.UserID = auth.UserID(c)
  30. if group.CategoryNames == nil {
  31. group.CategoryNames = make(map[string]string)
  32. }
  33. err = db.ProjectGroups().Insert(c.Request.Context(), group)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return &group, nil
  38. }))
  39. g.PUT("/:id", handler("projectGroup", func(c *gin.Context) (interface{}, error) {
  40. update := models.ProjectGroupUpdate{}
  41. err := c.BindJSON(&update)
  42. if err != nil {
  43. return nil, slerrors.BadRequest("Invalid JSON")
  44. }
  45. if (update.Name != nil && *update.Name == "") || (update.Abbreviation != nil && *update.Abbreviation == "") {
  46. return nil, slerrors.BadRequest("Abbreviation and name cannot be left empty.")
  47. }
  48. group, err := db.ProjectGroups().Find(c, c.Param("id"))
  49. if err != nil {
  50. return nil, err
  51. }
  52. if group.UserID != auth.UserID(c) {
  53. return nil, slerrors.NotFound("Project group")
  54. }
  55. group.Update(update)
  56. err = db.ProjectGroups().Update(c.Request.Context(), *group)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return group, nil
  61. }))
  62. g.DELETE("/:id", handler("project", func(c *gin.Context) (interface{}, error) {
  63. group, err := l.FindProjectGroup(c.Request.Context(), c.Param("id"))
  64. if err != nil {
  65. return nil, err
  66. }
  67. if len(group.Projects) > 0 {
  68. return nil, slerrors.Forbidden("You cannot delete non-empty project group.")
  69. }
  70. err = db.ProjectGroups().Delete(c.Request.Context(), group.ProjectGroup)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return group, nil
  75. }))
  76. }