/
month_config_v3.go
352 lines (308 loc) · 10.3 KB
/
month_config_v3.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
package controllers
import (
"errors"
"fmt"
"net/http"
"slices"
"github.com/envelope-zero/backend/v3/internal/types"
"github.com/envelope-zero/backend/v3/pkg/database"
"github.com/envelope-zero/backend/v3/pkg/httperrors"
"github.com/envelope-zero/backend/v3/pkg/httputil"
"github.com/envelope-zero/backend/v3/pkg/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/shopspring/decimal"
"gorm.io/gorm"
)
type MonthConfigV3 struct {
models.MonthConfig
OverspendMode string `json:"overspendMode,omitempty"` // Ignore this. It is here to override the OverspendMode from models.MonthConfigCreate and will be removed with 4.0.0
Links struct {
Self string `json:"self" example:"https://example.com/api/v3/envelopes/61027ebb-ab75-4a49-9e23-a104ddd9ba6b/2017-10"` // The Month Config itself
Envelope string `json:"envelope" example:"https://example.com/api/v3/envelopes/61027ebb-ab75-4a49-9e23-a104ddd9ba6b"` // The Envelope this config belongs to
} `json:"links"`
}
func (m *MonthConfigV3) links(c *gin.Context) {
url := c.GetString(string(database.ContextURL))
m.Links.Self = fmt.Sprintf("%s/v3/envelopes/%s/%s", url, m.EnvelopeID, m.Month)
m.Links.Envelope = fmt.Sprintf("%s/v3/envelopes/%s", url, m.EnvelopeID)
}
func (co Controller) getMonthConfigV3(c *gin.Context, id uuid.UUID, month types.Month) (MonthConfigV3, httperrors.Error) {
m, err := co.getMonthConfigModelV3(c, id, month)
if !err.Nil() {
return MonthConfigV3{}, err
}
r := MonthConfigV3{
MonthConfig: m,
}
r.links(c)
return r, httperrors.Error{}
}
func (co Controller) getMonthConfigModelV3(c *gin.Context, id uuid.UUID, month types.Month) (models.MonthConfig, httperrors.Error) {
var m models.MonthConfig
err := query(c, co.DB.First(&m, &models.MonthConfig{
EnvelopeID: id,
Month: month,
}))
if !err.Nil() {
return models.MonthConfig{}, err
}
return m, httperrors.Error{}
}
type MonthConfigResponseV3 struct {
Data *MonthConfigV3 `json:"data"` // Config for the month
Error *string `json:"error" example:"the specified resource ID is not a valid UUID"` // The error, if any occurred
}
type MonthConfigListResponseV3 struct {
Data []MonthConfigV3 `json:"data"` // List of Month Configs
Error *string `json:"error" example:"the specified resource ID is not a valid UUID"` // The error, if any occurred
Pagination *Pagination `json:"pagination"` // Pagination information
}
// RegisterMonthConfigRoutesV3 registers the routes for transactions with
// the RouterGroup that is passed.
func (co Controller) RegisterMonthConfigRoutesV3(r *gin.RouterGroup) {
r.OPTIONS("/:id/:month", co.OptionsMonthConfigDetailV3)
r.GET("/:id/:month", co.GetMonthConfigV3)
r.PATCH("/:id/:month", co.UpdateMonthConfigV3)
}
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs
// @Tags Envelopes
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Param id path string true "ID of the Envelope"
// @Param month path string true "The month in YYYY-MM format"
// @Router /v3/envelopes/{id}/{month} [options]
func (co Controller) OptionsMonthConfigDetailV3(c *gin.Context) {
_, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
c.JSON(err.Status, httperrors.HTTPError{
Error: err.Error(),
})
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
e := httperrors.Parse(c, err)
c.JSON(e.Status, httperrors.HTTPError{
Error: e.Error(),
})
return
}
httputil.OptionsGetPatch(c)
}
// @Summary Get MonthConfig
// @Description Returns configuration for a specific month
// @Tags Envelopes
// @Produce json
// @Success 200 {object} MonthConfigResponseV3
// @Failure 400 {object} MonthConfigResponseV3
// @Failure 404 {object} MonthConfigResponseV3
// @Failure 500 {object} MonthConfigResponseV3
// @Param id path string true "ID of the Envelope"
// @Param month path string true "The month in YYYY-MM format"
// @Router /v3/envelopes/{id}/{month} [get]
func (co Controller) GetMonthConfigV3(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
e := httperrors.Parse(c, err)
c.JSON(e.Status, httperrors.HTTPError{
Error: e.Error(),
})
return
}
_, err = getResourceByID[models.Envelope](c, co, id)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
mConfig, err := co.getMonthConfigV3(c, id, types.MonthOf(month.Month))
if !err.Nil() {
// If there is no MonthConfig in the database, return one with the zero values
if errors.Is(err.Err, httperrors.ErrNoResource) {
mConfig := MonthConfigV3{
MonthConfig: models.MonthConfig{
EnvelopeID: id,
Month: types.MonthOf(month.Month),
},
}
mConfig.links(c)
// Check if there is an allocation for this MonthConfig. If yes, set the value.
var a models.Allocation
err := co.DB.First(&a, models.Allocation{
AllocationCreate: models.AllocationCreate{
Month: types.MonthOf(month.Month),
EnvelopeID: id,
},
}).Error
// If there is a database error, return it
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
e := httperrors.Parse(c, err)
s := e.Error()
c.JSON(e.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
// Set the amount if there is an allocation. If not,
// the amount is 0, which is the zero value of decimal.Decimal
if err == nil {
mConfig.Allocation = a.Amount
}
c.JSON(http.StatusOK, MonthConfigResponseV3{Data: &mConfig})
return
}
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
c.JSON(http.StatusOK, MonthConfigResponseV3{Data: &mConfig})
}
// MonthConfigCreateV3 contains the fields relevant for MonthConfigs in APIv3.
type MonthConfigCreateV3 struct {
Note string `json:"note" example:"Added 200€ here because we replaced Tim's expensive vase" default:""` // A note for the month config
Allocation decimal.Decimal `json:"allocation" gorm:"-" example:"22.01" minimum:"0.00000001" maximum:"999999999999.99999999" multipleOf:"0.00000001"` // The maximum value is "999999999999.99999999", swagger unfortunately rounds this.
}
// ToCreate is used to transform the API representation into the model representation
func (m MonthConfigCreateV3) ToCreate() (create models.MonthConfigCreate) {
create.Note = m.Note
return create
}
// @Summary Update MonthConfig
// @Description Changes configuration for a Month. If there is no configuration for the month yet, this endpoint transparently creates a configuration resource.
// @Tags Envelopes
// @Produce json
// @Success 201 {object} MonthConfigResponseV3
// @Failure 400 {object} MonthConfigResponseV3
// @Failure 404 {object} MonthConfigResponseV3
// @Failure 500 {object} MonthConfigResponseV3
// @Param id path string true "ID of the Envelope"
// @Param month path string true "The month in YYYY-MM format"
// @Param monthConfig body MonthConfigCreateV3 true "MonthConfig"
// @Router /v3/envelopes/{id}/{month} [patch]
func (co Controller) UpdateMonthConfigV3(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
var month URIMonth
if err := c.BindUri(&month); err != nil {
e := httperrors.Parse(c, err)
s := e.Error()
c.JSON(e.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
_, err = getResourceByID[models.Envelope](c, co, id)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
m, err := co.getMonthConfigModelV3(c, id, types.MonthOf(month.Month))
if !err.Nil() {
// If no Month Config exists yet, create one
// If the error is another error, return it to the user
if errors.Is(err.Err, httperrors.ErrNoResource) {
e := co.DB.Create(&models.MonthConfig{
Month: types.MonthOf(month.Month),
EnvelopeID: id,
}).Error
if e != nil {
err = httperrors.Parse(c, err)
s := e.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
}
m, err = co.getMonthConfigModelV3(c, id, types.MonthOf(month.Month))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
} else {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
}
updateFields, err := httputil.GetBodyFields(c, MonthConfigCreateV3{})
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
var data MonthConfigCreateV3
err = httputil.BindData(c, &data)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
// The Allocation field does not yet exist on the MonthConfig model in the database, create
// or update the corresponding allocation resource in the meantime
if slices.Contains(updateFields, "Allocation") && data.Allocation != decimal.Zero {
var allocation models.Allocation
e := co.DB.Where(models.Allocation{AllocationCreate: models.AllocationCreate{
Month: types.MonthOf(month.Month),
EnvelopeID: id,
}}).Assign(models.Allocation{AllocationCreate: models.AllocationCreate{
Amount: data.Allocation,
}}).FirstOrCreate(&allocation).Error
if e != nil {
err = httperrors.Parse(c, err)
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
}
create := data.ToCreate()
err = query(c, co.DB.Model(&m).Select("", updateFields...).Updates(create))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
o, err := co.getMonthConfigV3(c, m.EnvelopeID, m.Month)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, MonthConfigResponseV3{
Error: &s,
})
return
}
c.JSON(http.StatusOK, MonthConfigResponseV3{Data: &o})
}