-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
receipts.go
425 lines (362 loc) · 11.4 KB
/
receipts.go
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package handlers
import (
"database/sql"
"net/http"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/gin-gonic/gin"
"github.com/jkomyno/nanoid"
)
// ReceiptsGetQuery : Structure that should be used for getting query data on get request for receipts
type ReceiptsGetQuery struct {
PublicID string `form:"id"`
LocationID string `form:"locationId"`
}
// ReceiptsPostBody : Structure that should be used for getting json from body of a post request for receipts
type ReceiptsPostBody struct {
LocationPublicID string `json:"id" validate:"required"`
CreatedAt string `json:"createdAt"`
}
// ReceiptsPutBody : Structure that should be used for getting json from body of a put request for receipts
type ReceiptsPutBody struct {
PublicID string `json:"id" validate:"required"`
LocationID string `json:"locationId"`
}
// ReceiptsDeleteBody : Structure that should be used for getting json data from body of a delete request for items
type ReceiptsDeleteBody struct {
PublicID string `json:"id" validate:"required"`
}
// Receipt : Structure that should be used for getting receipt information from database
type Receipt struct {
PublicID string `db:"public_id" json:"id"`
LocationID string `db:"location_id" json:"locationId"`
CreatedBy string `db:"created_by" json:"createdBy"`
CreatedAt time.Time `db:"created_at" json:"createdAt"`
UpdatedAt time.Time `db:"updated_at" json:"updatedAt"`
}
// ReceiptWithData : Structure that should be used for getting receipt information including names, addresses, and everything else from receipts location from database
type ReceiptWithData struct {
PublicID string `json:"id" graphql:"id"`
CreatedBy string `json:"createdBy" graphql:"createdBy"`
Location Location `json:"location" graphql:"location"`
TotalPrice float64 `json:"totalPrice" graphql:"totalPrice"`
CreatedAt time.Time `json:"createdAt" grpahql:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" graphql:"updatedAt"`
}
// GetReceipts handles get requests for receipts
func (o Options) GetReceipts() gin.HandlerFunc {
return func(ctx *gin.Context) {
createdBy, createdByExists := GetUserID(ctx)
if !createdByExists {
ctx.JSON(http.StatusUnauthorized, gin.H{
"message": "user id not found in authorization token",
})
return
}
var searchQuery ReceiptsGetQuery
if err := ctx.ShouldBindQuery(&searchQuery); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if searchQuery.PublicID == "" && createdBy.PublicID == "" && searchQuery.LocationID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": "No search parameters specified!",
})
return
}
if searchQuery.PublicID != "" && searchQuery.LocationID != "" {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": "Too many parameters specified!",
})
return
}
query := sq.Select("receipts.public_id, locations.public_id AS location_id, users.public_id AS created_by, locations.name AS name, locations.address AS address, receipts.created_at, receipts.updated_at, SUM(items.price * items_in_receipt.amount) AS total_price").From("receipts").Join("locations ON locations.id = receipts.location_id").Join("users ON users.id = receipts.created_by").LeftJoin("items_in_receipt ON items_in_receipt.receipt_id = receipts.id").LeftJoin("items ON items.id = items_in_receipt.item_id").GroupBy("receipts.id")
if searchQuery.PublicID != "" {
query = query.Where(sq.Eq{"receipts.public_id": searchQuery.PublicID})
} else {
if createdBy.PublicID != "" {
query = query.Where(sq.Eq{"users.public_id": createdBy.PublicID})
}
if searchQuery.LocationID != "" {
query = query.Where(sq.Eq{"locations.public_id": searchQuery.LocationID})
}
}
queryString, queryStringArgs, err := query.ToSql()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
receipts := []ReceiptWithData{}
rows, err := o.DB.Queryx(queryString, queryStringArgs...)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
for rows.Next() {
receipt := ReceiptWithData{}
var totalPrice sql.NullFloat64
err := rows.Scan(&receipt.PublicID, &receipt.Location.PublicID, &receipt.CreatedBy, &receipt.Location.Name, &receipt.Location.Address, &receipt.CreatedAt, &receipt.UpdatedAt, &totalPrice)
// If database is unable to get the total price that means there are no
// items in the receipt and the default result for that will be an invalid
// flag in sql.NullFloat64 type and a 0 (zero) in Float64 value. This is
// nice for us since we just wan't that, the result and if there are no
// receipts the result is 0.
receipt.TotalPrice = totalPrice.Float64
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
receipts = append(receipts, receipt)
}
ctx.JSON(http.StatusOK, receipts)
}
}
// PostReceipts handles post requests for receipts
func (o Options) PostReceipts() gin.HandlerFunc {
return func(ctx *gin.Context) {
createdBy, createdByExists := GetUserID(ctx)
if !createdByExists {
ctx.JSON(http.StatusUnauthorized, gin.H{
"message": "user id not found in authorization token",
})
return
}
var receiptData ReceiptsPostBody
if err := ctx.ShouldBindJSON(&receiptData); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
err := o.V.Struct(receiptData)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
locationIDQuery := sq.Select("id").From("locations").Where(sq.Eq{"public_id": receiptData.LocationPublicID})
locationIDQueryString, locationIDQueryStringArgs, err := locationIDQuery.ToSql()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
location := StructID{}
if err := o.DB.Get(&location, locationIDQueryString, locationIDQueryStringArgs...); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
user, err := createdBy.PrivateID(o.DB)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
uuid, err := nanoid.Nanoid()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
createdAt, updatedAt := time.Now(), time.Now()
if receiptData.CreatedAt != "" {
createdAt, err = time.Parse(time.RFC3339, receiptData.CreatedAt)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
updatedAt, err = time.Parse(time.RFC3339, receiptData.CreatedAt)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
}
query := sq.Insert("receipts").Columns("public_id", "location_id", "created_by", "created_at", "updated_at").Values(uuid, location.ID, user.ID, createdAt, updatedAt)
queryString, queryStringArgs, err := query.ToSql()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
tx, err := o.DB.Begin()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
if _, err := tx.Exec(queryString, queryStringArgs...); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
if err := tx.Commit(); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
ctx.Status(http.StatusOK)
}
}
// PutReceipts handles put requests for receipts
func (o Options) PutReceipts() gin.HandlerFunc {
return func(ctx *gin.Context) {
createdBy, createdByExists := GetUserID(ctx)
if !createdByExists {
ctx.JSON(http.StatusUnauthorized, gin.H{
"message": "user id not found in authorization token",
})
return
}
var receiptData ReceiptsPutBody
if err := ctx.ShouldBindJSON(&receiptData); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
err := o.V.Struct(receiptData)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
user, err := createdBy.PrivateID(o.DB)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
query := sq.Update("receipts")
if receiptData.LocationID != "" {
locationQuery := sq.Select("id").From("locations").Where(sq.Eq{"public_id": receiptData.LocationID})
locationQueryString, locationQueryStringArgs, err := locationQuery.ToSql()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
location := StructID{}
if err := o.DB.Get(&location, locationQueryString, locationQueryStringArgs...); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
query = query.Set("location_id", location.ID)
}
query = query.Set("updated_at", time.Now()).Where(sq.Eq{"public_id": receiptData.PublicID, "created_by": user.ID})
queryString, queryStringArgs, err := query.ToSql()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
tx, err := o.DB.Begin()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
if _, err := tx.Exec(queryString, queryStringArgs...); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
if err := tx.Commit(); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
ctx.Status(http.StatusOK)
}
}
// DeleteReceipts handlers delete requests for receipts
func (o Options) DeleteReceipts() gin.HandlerFunc {
return func(ctx *gin.Context) {
createdBy, createdByExists := GetUserID(ctx)
if !createdByExists {
ctx.JSON(http.StatusUnauthorized, gin.H{
"message": "user id not found in authorization token",
})
return
}
var receiptData ReceiptsDeleteBody
if err := ctx.ShouldBindJSON(&receiptData); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
err := o.V.Struct(receiptData)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
user, err := createdBy.PrivateID(o.DB)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
query := sq.Delete("receipts").Where(sq.Eq{"public_id": receiptData.PublicID, "created_by": user.ID})
queryString, queryStringArgs, err := query.ToSql()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
tx, err := o.DB.Begin()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
if _, err := tx.Exec(queryString, queryStringArgs...); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
if err := tx.Commit(); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
ctx.Status(http.StatusOK)
}
}