handlers.go (view raw)
1package main
2
3import (
4 "errors"
5 "fmt"
6 "net/http"
7 "time"
8
9 "github.com/gin-gonic/gin"
10)
11
12func validateDate(month, day int) error {
13 if month < 1 || month > 12 {
14 return errors.New("invalid month: must be between 1 and 12")
15 }
16
17 if day < 1 || day > 31 {
18 return errors.New("invalid day: must be between 1 and 31")
19 }
20
21 // Construct a date and use time package to validate
22 dateStr := fmt.Sprintf("2023-%02d-%02d", month, day)
23 _, err := time.Parse("2006-01-02", dateStr)
24 if err != nil {
25 return errors.New("invalid day for the given month")
26 }
27
28 return nil
29}
30
31func addOccurrence(c *gin.Context) {
32 var input Occurrence
33 if err := c.ShouldBindJSON(&input); err != nil {
34 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
35 return
36 }
37
38 var isDateValid = false
39 // Validate date
40 if input.Day != 0 || input.Month != 0 {
41 if err := validateDate(input.Month, input.Day); err != nil {
42 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
43 return
44 }
45 isDateValid = true
46 }
47
48 var occurrence Occurrence
49 if input.ID != 0 {
50 if err := db.First(&occurrence, input.ID).Error; err != nil {
51 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
52 return
53 }
54
55 // Update existing record with new values
56 if isDateValid {
57 occurrence.Month = input.Month
58 occurrence.Day = input.Day
59 }
60 if input.Name != "" {
61 occurrence.Name = input.Name
62 }
63 if input.Description != "" {
64 occurrence.Description = input.Description
65 }
66 occurrence.Notify = input.Notify
67 occurrence.Notified = input.Notified
68 db.Save(&occurrence)
69 c.JSON(http.StatusOK, occurrence)
70 return
71 }
72
73 // Create a new record if no existing record is found
74 if !isDateValid {
75 c.JSON(http.StatusBadRequest, gin.H{"error": "invalid date"})
76 return
77 }
78
79 occurrence = input
80 occurrence.Notified = false
81 db.Create(&occurrence)
82 c.JSON(http.StatusOK, occurrence)
83}
84
85func getOccurrences(c *gin.Context) {
86 var occurrences []Occurrence
87 db.Find(&occurrences)
88 c.JSON(http.StatusOK, occurrences)
89}
90
91func deleteOccurrence(c *gin.Context) {
92 id := c.Param("id")
93 var occurrence Occurrence
94
95 if err := db.First(&occurrence, id).Error; err != nil {
96 c.JSON(http.StatusNotFound, gin.H{"error": "Occurrence not found"})
97 return
98 }
99
100 db.Delete(&occurrence)
101 c.JSON(http.StatusOK, gin.H{"message": "Occurrence deleted"})
102}