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.

97 lines
2.4 KiB

4 years ago
  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. "time"
  11. )
  12. func Project(g *gin.RouterGroup, db database.Database) {
  13. l := services.Loader{DB: db}
  14. g.GET("/", handler("projects", func(c *gin.Context) (interface{}, error) {
  15. filter := models.ProjectFilter{}
  16. if setting := c.Query("active"); setting != "" {
  17. active := setting == "true"
  18. filter.Active = &active
  19. }
  20. if setting := c.Query("expiring"); setting != "" {
  21. filter.Expiring = setting == "true"
  22. }
  23. return l.ListProjects(c, filter)
  24. }))
  25. g.GET("/:id", handler("project", func(c *gin.Context) (interface{}, error) {
  26. return l.FindProject(c, c.Param("id"))
  27. }))
  28. g.POST("/", handler("project", func(c *gin.Context) (interface{}, error) {
  29. project := models.Project{}
  30. err := c.BindJSON(&project)
  31. if err != nil {
  32. return nil, slerrors.BadRequest("Invalid JSON")
  33. }
  34. if project.EndTime != nil && project.EndTime.Before(time.Now()) {
  35. return nil, slerrors.BadRequest("Project end time must be later than current time.")
  36. }
  37. project.ID = generate.ProjectID()
  38. project.UserID = auth.UserID(c)
  39. project.CreatedTime = time.Now().UTC()
  40. err = db.Projects().Insert(c.Request.Context(), project)
  41. if err != nil {
  42. return nil, err
  43. }
  44. return &models.ProjectResult{
  45. Project: project,
  46. Tasks: []*models.TaskResult{},
  47. }, nil
  48. }))
  49. g.PUT("/:id", handler("project", func(c *gin.Context) (interface{}, error) {
  50. update := models.ProjectUpdate{}
  51. err := c.BindJSON(&update)
  52. if err != nil {
  53. return nil, slerrors.BadRequest("Invalid JSON")
  54. }
  55. project, err := l.FindProject(c.Request.Context(), c.Param("id"))
  56. if err != nil {
  57. return nil, err
  58. }
  59. project.Update(update)
  60. err = db.Projects().Update(c.Request.Context(), project.Project)
  61. if err != nil {
  62. return nil, err
  63. }
  64. return project, nil
  65. }))
  66. g.DELETE("/:id", handler("project", func(c *gin.Context) (interface{}, error) {
  67. project, err := l.FindProject(c.Request.Context(), c.Param("id"))
  68. if err != nil {
  69. return nil, err
  70. }
  71. if len(project.Tasks) > 0 {
  72. return nil, slerrors.Forbidden("cannot delete non-empty projects.")
  73. }
  74. err = db.Projects().Delete(c.Request.Context(), project.Project)
  75. if err != nil {
  76. return nil, err
  77. }
  78. return project, nil
  79. }))
  80. }