createEvent.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "GoApi/internal/repository"
  6. )
  7. // Novo controller dedicado para criação de eventos
  8. type CreateEventController struct {
  9. Repo repository.EventRepository
  10. }
  11. func NewCreateEventController(repo repository.EventRepository) CreateEventController {
  12. return CreateEventController{Repo: repo}
  13. }
  14. type CreateEventRequest struct {
  15. Name string `json:"name"`
  16. Date string `json:"date"`
  17. PassageValue string `json:"passage_value"`
  18. HotelValue string `json:"hotel_value"`
  19. GiftValue string `json:"gift_value"`
  20. TeamValue string `json:"team_value"`
  21. SponsorValue string `json:"sponsor_value"`
  22. TotalValue string `json:"total_value"`
  23. CollaboratorIDs []int64 `json:"collaborator_ids"`
  24. }
  25. func (c *CreateEventController) CreateEventHandler(w http.ResponseWriter, r *http.Request) {
  26. if r.Method != http.MethodPost {
  27. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  28. return
  29. }
  30. // Decodifica o JSON do corpo da requisição
  31. var req CreateEventRequest
  32. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  33. http.Error(w, "Invalid request body", http.StatusBadRequest)
  34. return
  35. }
  36. // Valida os campos obrigatórios
  37. if req.Name == "" || req.Date == "" || req.TotalValue == "" {
  38. http.Error(w, "Name, date and total value are required fields", http.StatusBadRequest)
  39. return
  40. }
  41. // Cria o objeto de evento
  42. event := &repository.Event{
  43. Name: req.Name,
  44. Date: req.Date,
  45. PassageValue: req.PassageValue,
  46. HotelValue: req.HotelValue,
  47. GiftValue: req.GiftValue,
  48. TeamValue: req.TeamValue,
  49. SponsorValue: req.SponsorValue,
  50. TotalValue: req.TotalValue,
  51. CollaboratorIDs: req.CollaboratorIDs,
  52. }
  53. // Chama o repositório para criar o evento
  54. eventID, err := c.Repo.CreateEvent(event)
  55. if err != nil {
  56. http.Error(w, "Failed to create event: "+err.Error(), http.StatusInternalServerError)
  57. return
  58. }
  59. // Retorna o ID do evento criado
  60. w.Header().Set("Content-Type", "application/json")
  61. w.WriteHeader(http.StatusCreated)
  62. json.NewEncoder(w).Encode(map[string]interface{}{
  63. "id": eventID,
  64. "message": "Event created successfully",
  65. })
  66. }