-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
238 lines (201 loc) · 5.53 KB
/
Copy pathmain.go
File metadata and controls
238 lines (201 loc) · 5.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"context"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"time"
"cloud.google.com/go/firestore"
"github.com/gin-gonic/gin"
"google.golang.org/api/iterator"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Apartment struct {
Number int `json:"number" firestore:"number"`
Name string `json:"name" firestore:"name"`
VotedAt time.Time `json:"voted_at" firestore:"voted_at"`
}
type Vote struct {
Value string `json:"value" firestore:"value"`
RandomKey int64 `json:"-" firestore:"random_key"` // For random ordering
}
type Results struct {
For int `json:"for"`
Against int `json:"against"`
Total int `json:"total"`
Hidden bool `json:"hidden"`
}
var client *firestore.Client
var pollEndTime time.Time
var ctx = context.Background()
func initPollEndTime() {
// Default end date if environment variable is not set
defaultEndTime := "2024-04-01 23:59:59"
endTimeStr := os.Getenv("POLL_END_TIME")
if endTimeStr == "" {
endTimeStr = defaultEndTime
}
var err error
pollEndTime, err = time.ParseInLocation("2006-01-02 15:04:05", endTimeStr, time.Local)
if err != nil {
log.Printf("Error parsing POLL_END_TIME, using default: %v", err)
pollEndTime, _ = time.ParseInLocation("2006-01-02 15:04:05", defaultEndTime, time.Local)
}
}
func initFirestore() error {
var err error
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
projectID = "your-project-id" // Replace with your project ID
}
client, err = firestore.NewClient(ctx, projectID)
return err
}
func main() {
initPollEndTime()
if err := initFirestore(); err != nil {
log.Fatal(err)
}
defer client.Close()
r := gin.Default()
r.Static("/static", "./static")
r.LoadHTMLGlob("templates/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"endDate": pollEndTime.Format("2006-01-02 15:04:05"),
})
})
api := r.Group("/api")
{
api.GET("/check-apartment/:number", checkApartment)
api.POST("/vote", submitVote)
api.GET("/results", getResults)
api.GET("/poll-status", getPollStatus)
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
r.Run(":" + port)
}
func checkApartment(c *gin.Context) {
if time.Now().After(pollEndTime) {
c.JSON(http.StatusBadRequest, gin.H{"error": "ההצבעה הסתיימה"})
return
}
apartmentNumber := c.Param("number")
doc, err := client.Collection("apartments").Doc(apartmentNumber).Get(ctx)
if err != nil {
if status.Code(err) == codes.NotFound {
c.JSON(http.StatusOK, gin.H{"voted": false})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var apartment Apartment
if err := doc.DataTo(&apartment); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"voted": true,
"name": apartment.Name,
})
}
func submitVote(c *gin.Context) {
if time.Now().After(pollEndTime) {
c.JSON(http.StatusBadRequest, gin.H{"error": "ההצבעה הסתיימה"})
return
}
var input struct {
ApartmentNumber int `json:"apartment_number" binding:"required"`
VoterName string `json:"voter_name" binding:"required"`
Vote string `json:"vote" binding:"required"`
}
if err := c.BindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Start a transaction
err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
apartmentRef := client.Collection("apartments").Doc(strconv.Itoa(input.ApartmentNumber))
// Check if apartment already voted
_, err := tx.Get(apartmentRef)
if err == nil {
return &gin.Error{Err: err, Type: gin.ErrorTypeBind, Meta: "דירה זו כבר הצביעה"}
} else if status.Code(err) != codes.NotFound {
return err
}
// Record apartment vote
apartment := Apartment{
Number: input.ApartmentNumber,
Name: input.VoterName,
VotedAt: time.Now(),
}
if err := tx.Set(apartmentRef, apartment); err != nil {
return err
}
// Add vote with random key for ordering
vote := Vote{
Value: input.Vote,
RandomKey: rand.Int63(),
}
_, err = client.Collection("votes").NewDoc().Set(ctx, vote)
return err
})
if err != nil {
if ginErr, ok := err.(*gin.Error); ok {
c.JSON(http.StatusBadRequest, gin.H{"error": ginErr.Meta})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func getResults(c *gin.Context) {
if !time.Now().After(pollEndTime) {
c.JSON(http.StatusOK, gin.H{
"hidden": true,
"message": "התוצאות יפורסמו בתאריך " + pollEndTime.Format("02/01/2006") + " בשעה " + pollEndTime.Format("15:04"),
})
return
}
var results Results
iter := client.Collection("votes").Documents(ctx)
defer iter.Stop()
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var vote Vote
if err := doc.DataTo(&vote); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
results.Total++
if vote.Value == "בעד" {
results.For++
} else if vote.Value == "נגד" {
results.Against++
}
}
results.Hidden = false
c.JSON(http.StatusOK, results)
}
func getPollStatus(c *gin.Context) {
isEnded := time.Now().After(pollEndTime)
c.JSON(http.StatusOK, gin.H{
"is_ended": isEnded,
"end_date": pollEndTime.Format("2006-01-02T15:04:05"),
})
}