/
budget.go
611 lines (529 loc) · 17.3 KB
/
budget.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
package controllers
import (
"net/http"
"github.com/envelope-zero/backend/v2/internal/types"
"github.com/envelope-zero/backend/v2/pkg/httperrors"
"github.com/envelope-zero/backend/v2/pkg/httputil"
"github.com/envelope-zero/backend/v2/pkg/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/shopspring/decimal"
)
type BudgetListResponse struct {
Data []models.Budget `json:"data"`
}
type BudgetResponse struct {
Data models.Budget `json:"data"`
}
type BudgetMonthResponse struct {
Data models.BudgetMonth `json:"data"`
}
type BudgetQueryFilter struct {
Name string `form:"name" filterField:"false"`
Note string `form:"note" filterField:"false"`
Currency string `form:"currency"`
Search string `form:"search" filterField:"false"`
}
// swagger:enum AllocationMode
type AllocationMode string
const (
AllocateLastMonthBudget AllocationMode = "ALLOCATE_LAST_MONTH_BUDGET"
AllocateLastMonthSpend AllocationMode = "ALLOCATE_LAST_MONTH_SPEND"
)
type BudgetAllocationMode struct {
Mode AllocationMode `json:"mode" example:"ALLOCATE_LAST_MONTH_SPEND"`
}
// RegisterBudgetRoutes registers the routes for budgets with
// the RouterGroup that is passed.
func (co Controller) RegisterBudgetRoutes(r *gin.RouterGroup) {
// Root group
{
r.OPTIONS("", co.OptionsBudgetList)
r.GET("", co.GetBudgets)
r.POST("", co.CreateBudget)
}
// Budget with ID
{
r.OPTIONS("/:budgetId", co.OptionsBudgetDetail)
r.GET("/:budgetId", co.GetBudget)
r.OPTIONS("/:budgetId/:month", co.OptionsBudgetMonth)
r.GET("/:budgetId/:month", co.GetBudgetMonth)
r.OPTIONS("/:budgetId/:month/allocations", co.OptionsBudgetMonthAllocations)
r.POST("/:budgetId/:month/allocations", co.SetAllocationsMonth)
r.DELETE("/:budgetId/:month/allocations", co.DeleteAllocationsMonth)
r.PATCH("/:budgetId", co.UpdateBudget)
r.DELETE("/:budgetId", co.DeleteBudget)
}
}
// OptionsBudgetList returns the allowed HTTP methods
//
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs
// @Tags Budgets
// @Success 204
// @Failure 500 {object} httperrors.HTTPError
// @Router /v1/budgets [options]
func (co Controller) OptionsBudgetList(c *gin.Context) {
httputil.OptionsGetPost(c)
}
// OptionsBudgetDetail returns the allowed HTTP methods
//
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs
// @Tags Budgets
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Router /v1/budgets/{budgetId} [options]
func (co Controller) OptionsBudgetDetail(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
_, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
httputil.OptionsGetPatchDelete(c)
}
// OptionsBudgetMonth returns the allowed HTTP methods
//
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs. **Use OPTIONS /month endpoint with month and budgetId query parameters instead.**
// @Tags Budgets
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Param month path string true "The month in YYYY-MM format"
// @Router /v1/budgets/{budgetId}/{month} [options]
// @Deprecated true
func (co Controller) OptionsBudgetMonth(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
httperrors.InvalidMonth(c)
return
}
_, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
httputil.OptionsGet(c)
}
// OptionsBudgetMonthAllocations returns the allowed HTTP methods
//
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs. **Use OPTIONS /month endpoint with month and budgetId query parameters instead.**
// @Tags Budgets
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Param month path string true "The month in YYYY-MM format"
// @Router /v1/budgets/{budgetId}/{month}/allocations [options]
// @Deprecated true
func (co Controller) OptionsBudgetMonthAllocations(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
httperrors.InvalidMonth(c)
return
}
_, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
httputil.OptionsDelete(c)
}
// CreateBudget creates a new budget
//
// @Summary Create budget
// @Description Creates a new budget
// @Tags Budgets
// @Accept json
// @Produce json
// @Success 201 {object} BudgetResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 500 {object} httperrors.HTTPError
// @Param budget body models.BudgetCreate true "Budget"
// @Router /v1/budgets [post]
func (co Controller) CreateBudget(c *gin.Context) {
var budget models.Budget
if err := httputil.BindData(c, &budget); err != nil {
return
}
if !queryWithRetry(c, co.DB.Create(&budget)) {
return
}
// TODO: Delete
// budgetObject, ok := co.getBudgetResource(c, budget.ID)
// if !ok {
// return
// }
c.JSON(http.StatusCreated, BudgetResponse{Data: budget})
}
// GetBudgets returns data for all budgets filtered by the query parameters
//
// @Summary List budgets
// @Description Returns a list of budgets
// @Tags Budgets
// @Produce json
// @Success 200 {object} BudgetListResponse
// @Failure 500 {object} httperrors.HTTPError
// @Router /v1/budgets [get]
// @Param name query string false "Filter by name"
// @Param note query string false "Filter by note"
// @Param currency query string false "Filter by currency"
// @Param search query string false "Search for this text in name and note"
func (co Controller) GetBudgets(c *gin.Context) {
var filter BudgetQueryFilter
// Every parameter is bound into a string, so this will always succeed
_ = c.Bind(&filter)
// Get the fields that we're filtering for
queryFields, setFields := httputil.GetURLFields(c.Request.URL, filter)
var budgets []models.Budget
query := co.DB.Where(&models.Budget{
BudgetCreate: models.BudgetCreate{
Name: filter.Name,
Note: filter.Note,
Currency: filter.Currency,
},
}, queryFields...)
query = stringFilters(co.DB, query, setFields, filter.Name, filter.Note, filter.Search)
if !queryWithRetry(c, query.Find(&budgets)) {
return
}
// When there are no budgets, we want an empty list, not null
// Therefore, we use make to create a slice with zero elements
// which will be marshalled to an empty JSON array
if len(budgets) == 0 {
budgets = make([]models.Budget, 0)
}
c.JSON(http.StatusOK, BudgetListResponse{Data: budgets})
}
// GetBudget returns data for a single budget
//
// @Summary Get budget
// @Description Returns a specific budget
// @Tags Budgets
// @Produce json
// @Success 200 {object} BudgetResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Router /v1/budgets/{budgetId} [get]
func (co Controller) GetBudget(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
budgetObject, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
c.JSON(http.StatusOK, BudgetResponse{Data: budgetObject})
}
// GetBudgetMonth returns data for a month for a specific budget
//
// @Summary Get Budget month data
// @Description Returns data about a budget for a for a specific month. **Use GET /month endpoint with month and budgetId query parameters instead.**
// @Tags Budgets
// @Produce json
// @Success 200 {object} BudgetMonthResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Param month path string true "The month in YYYY-MM format"
// @Router /v1/budgets/{budgetId}/{month} [get]
// @Deprecated true
func (co Controller) GetBudgetMonth(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
budget, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
httperrors.InvalidMonth(c)
return
}
if month.Month.IsZero() {
httperrors.New(c, http.StatusBadRequest, "You cannot request data for no month")
return
}
var envelopes []models.Envelope
categories, _ := co.getCategoryResources(c, budget.ID)
// Get envelopes for all categories
for _, category := range categories {
var e []models.Envelope
if !queryWithRetry(c, co.DB.Where(&models.Envelope{
EnvelopeCreate: models.EnvelopeCreate{
CategoryID: category.ID,
},
}).Find(&e)) {
return
}
envelopes = append(envelopes, e...)
}
var envelopeMonths []models.EnvelopeMonth
for _, envelope := range envelopes {
envelopeMonth, _, err := envelope.Month(co.DB, types.MonthOf(month.Month))
if err != nil {
httperrors.Handler(c, err)
return
}
envelopeMonths = append(envelopeMonths, envelopeMonth)
}
// Get all allocations for all Envelopes for the month
var allocations []models.Allocation
for _, envelope := range envelopes {
var a models.Allocation
if !queryWithRetry(c, co.DB.Where(&models.Allocation{
AllocationCreate: models.AllocationCreate{
EnvelopeID: envelope.ID,
Month: types.MonthOf(month.Month),
},
}).Find(&a)) {
return
}
allocations = append(allocations, a)
}
// Calculate the budgeted sum
var budgeted decimal.Decimal
for _, allocation := range allocations {
budgeted = budgeted.Add(allocation.Amount)
}
// Calculate the income
income, err := budget.Income(co.DB, types.MonthOf(month.Month))
if err != nil {
httperrors.Handler(c, err)
return
}
// Get the available sum for budgeting
bMonth, err := budget.Month(co.DB, types.MonthOf(month.Month))
if err != nil {
httperrors.Handler(c, err)
return
}
c.JSON(http.StatusOK, BudgetMonthResponse{Data: models.BudgetMonth{
ID: budget.ID,
Name: budget.Name,
Month: types.MonthOf(month.Month),
Income: income,
Budgeted: budgeted,
Envelopes: envelopeMonths,
Available: bMonth.Available,
}})
}
// UpdateBudget updates data for a budget
//
// @Summary Update budget
// @Description Update an existing budget. Only values to be updated need to be specified.
// @Tags Budgets
// @Accept json
// @Produce json
// @Success 200 {object} BudgetResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Param budget body models.BudgetCreate true "Budget"
// @Router /v1/budgets/{budgetId} [patch]
func (co Controller) UpdateBudget(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
budget, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
updateFields, err := httputil.GetBodyFields(c, models.BudgetCreate{})
if err != nil {
return
}
var data models.Budget
if err := httputil.BindData(c, &data); err != nil {
return
}
if !queryWithRetry(c, co.DB.Model(&budget).Select("", updateFields...).Updates(data)) {
return
}
// TODO: delete
// budgetObject, ok := co.getBudgetObject(c, budget.ID)
// if !ok {
// httperrors.Handler(c, err)
// return
// }
c.JSON(http.StatusOK, BudgetResponse{Data: budget})
}
// Do stuff
//
// @Summary Delete budget
// @Description Deletes a budget
// @Tags Budgets
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param budgetId path string true "ID formatted as string"
// @Router /v1/budgets/{budgetId} [delete]
func (co Controller) DeleteBudget(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
budget, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
if !queryWithRetry(c, co.DB.Delete(&budget)) {
return
}
c.JSON(http.StatusNoContent, gin.H{})
}
// DeleteAllocationsMonth deletes all allocations for a specific month
//
// @Summary Delete allocations for a month
// @Description Deletes all allocation for the specified month. **Use DELETE /month endpoint with month and budgetId query parameters instead.**
// @Tags Budgets
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 500 {object} httperrors.HTTPError
// @Param month path string true "The month in YYYY-MM format"
// @Param budgetId path string true "Budget ID formatted as string"
// @Router /v1/budgets/{budgetId}/{month}/allocations [delete]
// @Deprecated true.
func (co Controller) DeleteAllocationsMonth(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
// If the budget does not exist, abort the request
_, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
httperrors.InvalidMonth(c)
return
}
// We query for all allocations here
var allocations []models.Allocation
if !queryWithRetry(c, co.DB.
Joins("JOIN envelopes ON envelopes.id = allocations.envelope_id").
Joins("JOIN categories ON categories.id = envelopes.category_id").
Joins("JOIN budgets on budgets.id = categories.budget_id").
Where(models.Allocation{AllocationCreate: models.AllocationCreate{Month: types.MonthOf(month.Month)}}).
Where("budgets.id = ?", id).
Find(&allocations)) {
return
}
for _, allocation := range allocations {
if !queryWithRetry(c, co.DB.Unscoped().Delete(&allocation)) {
return
}
}
c.JSON(http.StatusNoContent, gin.H{})
}
// SetAllocationsMonth sets all allocations for a specific month
//
// @Summary Set allocations for a month
// @Description Sets allocations for a month for all envelopes that do not have an allocation yet. **Use POST /month endpoint with month and budgetId query parameters instead.**
// @Tags Budgets
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 500 {object} httperrors.HTTPError
// @Param month path string true "The month in YYYY-MM format"
// @Param budgetId path string true "Budget ID formatted as string"
// @Param mode body BudgetAllocationMode true "Budget"
// @Router /v1/budgets/{budgetId}/{month}/allocations [post]
// @Deprecated true.
func (co Controller) SetAllocationsMonth(c *gin.Context) {
id, err := uuid.Parse(c.Param("budgetId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
// If the budget does not exist, abort the request
_, ok := getResourceByIDAndHandleErrors[models.Budget](c, co, id)
if !ok {
return
}
// Verify the month
var month URIMonth
if err := c.BindUri(&month); err != nil {
httperrors.InvalidMonth(c)
return
}
// Get the mode to set new allocations in
var data BudgetAllocationMode
if err := httputil.BindData(c, &data); err != nil {
return
}
if data.Mode != AllocateLastMonthBudget && data.Mode != AllocateLastMonthSpend {
httperrors.New(c, http.StatusBadRequest, "The mode must be %s or %s", AllocateLastMonthBudget, AllocateLastMonthSpend)
return
}
pastMonth := types.MonthOf(month.Month.AddDate(0, -1, 0))
queryCurrentMonth := co.DB.Select("id").Table("allocations").Where("allocations.envelope_id = envelopes.id AND allocations.month = ?", month.Month)
// Get all envelopes that do not have an allocation for the target month
// but for the month before
var envelopesAmount []struct {
EnvelopeID uuid.UUID `gorm:"column:id"`
Amount decimal.Decimal
}
// Get all envelope IDs and allocation amounts where there is no allocation
// for the request month, but one for the last month
if !queryWithRetry(c, co.DB.
Joins("JOIN allocations ON allocations.envelope_id = envelopes.id AND allocations.month = ? AND NOT EXISTS(?)", pastMonth, queryCurrentMonth).
Select("envelopes.id, allocations.amount").
Table("envelopes").
Find(&envelopesAmount)) {
return
}
// Create all new allocations
for _, allocation := range envelopesAmount {
// If the mode is the spend of last month, calculate and set it
amount := allocation.Amount
if data.Mode == AllocateLastMonthSpend {
amount = models.Envelope{DefaultModel: models.DefaultModel{ID: allocation.EnvelopeID}}.Spent(co.DB, pastMonth)
}
if !queryWithRetry(c, co.DB.Create(&models.Allocation{
AllocationCreate: models.AllocationCreate{
EnvelopeID: allocation.EnvelopeID,
Amount: amount,
Month: types.MonthOf(month.Month),
},
})) {
return
}
}
c.JSON(http.StatusNoContent, gin.H{})
}