/
account.go
486 lines (432 loc) · 12.7 KB
/
account.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
package v4
import (
"net/http"
"github.com/envelope-zero/backend/v4/pkg/httperrors"
"github.com/envelope-zero/backend/v4/pkg/httputil"
"github.com/envelope-zero/backend/v4/pkg/models"
"github.com/gin-gonic/gin"
"golang.org/x/exp/slices"
)
// RegisterAccountRoutes registers the routes for accounts with
// the RouterGroup that is passed.
func RegisterAccountRoutes(r *gin.RouterGroup) {
// Root group
{
r.OPTIONS("", OptionsAccountList)
r.GET("", GetAccounts)
r.POST("", CreateAccounts)
}
// Account with ID
{
r.OPTIONS("/:id", OptionsAccountDetail)
r.GET("/:id", GetAccount)
r.GET("/:id/recent-envelopes", GetAccountRecentEnvelopes)
r.POST("/computed", GetAccountData) // This is a POST endpoints because some clients don't allow GET requests to have bodies
r.PATCH("/:id", UpdateAccount)
r.DELETE("/:id", DeleteAccount)
}
}
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs
// @Tags Accounts
// @Success 204
// @Router /v4/accounts [options]
func OptionsAccountList(c *gin.Context) {
httputil.OptionsGetPost(c)
}
// @Summary Allowed HTTP verbs
// @Description Returns an empty response with the HTTP Header "allow" set to the allowed HTTP verbs
// @Tags Accounts
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404 {object} httperrors.HTTPError
// @Failure 500 {object} httperrors.HTTPError
// @Param id path string true "ID formatted as string"
// @Router /v4/accounts/{id} [options]
func OptionsAccountDetail(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
c.JSON(err.Status, httperrors.HTTPError{
Error: err.Error(),
})
return
}
_, err = getModelByID[models.Account](c, id)
if !err.Nil() {
c.JSON(err.Status, httperrors.HTTPError{
Error: err.Error(),
})
return
}
httputil.OptionsGetPatchDelete(c)
}
// @Summary Creates accounts
// @Description Creates new accounts
// @Tags Accounts
// @Produce json
// @Success 201 {object} AccountCreateResponse
// @Failure 400 {object} AccountCreateResponse
// @Failure 404 {object} AccountCreateResponse
// @Failure 500 {object} AccountCreateResponse
// @Param accounts body []AccountEditable true "Accounts"
// @Router /v4/accounts [post]
func CreateAccounts(c *gin.Context) {
var editables []AccountEditable
// Bind data and return error if not possible
err := httputil.BindData(c, &editables)
if !err.Nil() {
e := err.Error()
c.JSON(err.Status, AccountCreateResponse{
Error: &e,
})
return
}
// The final http status. Will be modified when errors occur
status := http.StatusCreated
r := AccountCreateResponse{}
for _, editable := range editables {
account := editable.model()
// Verify that budget exists. If not, append the error
// and move to the next account
_, err := getModelByID[models.Budget](c, editable.BudgetID)
if !err.Nil() {
status = r.appendError(err, status)
continue
}
dbErr := models.DB.Create(&account).Error
if dbErr != nil {
err := httperrors.GenericDBError[models.Account](account, c, dbErr)
status = r.appendError(err, status)
continue
}
data := newAccount(c, account)
r.Data = append(r.Data, AccountResponse{Data: &data})
}
c.JSON(status, r)
}
// @Summary List accounts
// @Description Returns a list of accounts
// @Tags Accounts
// @Produce json
// @Success 200 {object} AccountListResponse
// @Failure 400 {object} AccountListResponse
// @Failure 500 {object} AccountListResponse
// @Router /v4/accounts [get]
// @Param name query string false "Filter by name"
// @Param note query string false "Filter by note"
// @Param budget query string false "Filter by budget ID"
// @Param onBudget query bool false "Is the account on-budget?"
// @Param external query bool false "Is the account external?"
// @Param archived query bool false "Is the account archived?"
// @Param search query string false "Search for this text in name and note"
// @Param offset query uint false "The offset of the first Account returned. Defaults to 0."
// @Param limit query int false "Maximum number of Accounts to return. Defaults to 50."
func GetAccounts(c *gin.Context) {
var filter AccountQueryFilter
if err := c.Bind(&filter); err != nil {
httperrors.InvalidQueryString(c)
return
}
// Get the set parameters in the query string
queryFields, setFields := httputil.GetURLFields(c.Request.URL, filter)
// Convert the QueryFilter to a Create struct
model, err := filter.model()
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountListResponse{
Error: &s,
})
return
}
q := models.DB.
Order("name ASC").
Where(&model, queryFields...)
q = stringFilters(models.DB, q, setFields, filter.Name, filter.Note, filter.Search)
// Set the offset. Does not need checking since the default is 0
q = q.Offset(int(filter.Offset))
// Default to 50 Accounts and set the limit
limit := 50
if slices.Contains(setFields, "Limit") {
limit = filter.Limit
}
q = q.Limit(limit)
var accounts []models.Account
err = query(c, q.Find(&accounts))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountListResponse{
Error: &s,
})
return
}
var count int64
err = query(c, q.Limit(-1).Offset(-1).Count(&count))
if !err.Nil() {
e := err.Error()
c.JSON(err.Status, AccountListResponse{
Error: &e,
})
return
}
// When there are no resources, 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
data := make([]Account, 0)
for _, account := range accounts {
data = append(data, newAccount(c, account))
}
c.JSON(http.StatusOK, AccountListResponse{
Data: data,
Pagination: &Pagination{
Count: len(data),
Total: count,
Offset: filter.Offset,
Limit: limit,
},
})
}
// @Summary Get account
// @Description Returns a specific account
// @Tags Accounts
// @Produce json
// @Success 200 {object} AccountResponse
// @Failure 400 {object} AccountResponse
// @Failure 404 {object} AccountResponse
// @Failure 500 {object} AccountResponse
// @Param id path string true "ID formatted as string"
// @Router /v4/accounts/{id} [get]
func GetAccount(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
account, err := getModelByID[models.Account](c, id)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
data := newAccount(c, account)
c.JSON(http.StatusOK, AccountResponse{Data: &data})
}
// @Summary Get recent envelopes
// @Description Returns a list of objects representing recent envelopes
// @Tags Accounts
// @Produce json
// @Success 200 {object} RecentEnvelopesResponse
// @Failure 400 {object} RecentEnvelopesResponse
// @Failure 404 {object} RecentEnvelopesResponse
// @Failure 500 {object} RecentEnvelopesResponse
// @Param id path string true "ID formatted as string"
// @Router /v4/accounts/{id}/recent-envelopes [get]
func GetAccountRecentEnvelopes(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, RecentEnvelopesResponse{
Error: &s,
})
return
}
account, err := getModelByID[models.Account](c, id)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, RecentEnvelopesResponse{
Error: &s,
})
return
}
var recentEnvelopes []RecentEnvelope
// Get the Envelope IDs for the 50 latest transactions
latest := models.DB.
Model(&models.Transaction{}).
Joins("LEFT JOIN envelopes ON envelopes.id = transactions.envelope_id AND envelopes.deleted_at IS NULL").
Select("envelopes.id as e_id, envelopes.name as name, datetime(envelopes.created_at) as created").
Where(&models.Transaction{
DestinationAccountID: account.ID,
}).
Order("datetime(transactions.date) DESC").
Limit(50)
// Group by frequency
dbErr := models.DB.
Table("(?)", latest).
// Set the nil UUID as ID if the envelope ID is NULL, since count() only counts non-null values
Select("IIF(e_id IS NOT NULL, e_id, NULL) as id, name").
Group("id").
Order("count(IIF(e_id IS NOT NULL, e_id, '0')) DESC"). // Order with a different IIF since NULL is ignored for count
Order("created ASC").
Limit(5).
Find(&recentEnvelopes).Error
if dbErr != nil {
err = httperrors.Parse(c, err)
s := err.Error()
c.JSON(err.Status, RecentEnvelopesResponse{
Error: &s,
})
return
}
c.JSON(http.StatusOK, RecentEnvelopesResponse{Data: recentEnvelopes})
}
// @Summary Get Account data
// @Description Returns calculated data for the account, e.g. balances
// @Tags Accounts
// @Produce json
// @Success 200 {object} AccountComputedDataResponse
// @Failure 400 {object} AccountComputedDataResponse
// @Failure 404 {object} AccountComputedDataResponse
// @Failure 500 {object} AccountComputedDataResponse
// @Param request body AccountComputedRequest true "Time and IDs of requested accounts"
// @Router /v4/accounts/computed [post]
func GetAccountData(c *gin.Context) {
var request AccountComputedRequest
// Bind data and return error if not possible
err := httputil.BindData(c, &request)
if !err.Nil() {
e := err.Error()
c.JSON(err.Status, AccountComputedDataResponse{
Error: &e,
})
return
}
data := make([]AccountComputedData, 0)
for _, idString := range request.IDs {
id, err := httputil.UUIDFromString(idString)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountComputedDataResponse{
Error: &s,
})
return
}
account, err := getModelByID[models.Account](c, id)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountComputedDataResponse{
Error: &s,
})
return
}
// Balance
balance, dbErr := account.Balance(models.DB, request.Time)
if dbErr != nil {
e := httperrors.Parse(c, dbErr)
s := e.Error()
c.JSON(err.Status, AccountComputedDataResponse{
Error: &s,
})
return
}
// Reconciled Balance
reconciledBalance, dbErr := account.ReconciledBalance(models.DB, request.Time)
if dbErr != nil {
e := httperrors.Parse(c, dbErr)
s := e.Error()
c.JSON(err.Status, AccountComputedDataResponse{
Error: &s,
})
return
}
data = append(data, AccountComputedData{
ID: id,
Balance: balance,
ReconciledBalance: reconciledBalance,
})
}
c.JSON(http.StatusOK, AccountComputedDataResponse{Data: data})
}
// @Summary Update account
// @Description Updates an account. Only values to be updated need to be specified.
// @Tags Accounts
// @Produce json
// @Success 200 {object} AccountResponse
// @Failure 400 {object} AccountResponse
// @Failure 404 {object} AccountResponse
// @Failure 500 {object} AccountResponse
// @Param id path string true "ID formatted as string"
// @Param account body AccountEditable true "Account"
// @Router /v4/accounts/{id} [patch]
func UpdateAccount(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
account, err := getModelByID[models.Account](c, id)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
updateFields, err := httputil.GetBodyFields(c, AccountEditable{})
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
var data AccountEditable
err = httputil.BindData(c, &data)
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
err = query(c, models.DB.Model(&account).Select("", updateFields...).Updates(data.model()))
if !err.Nil() {
s := err.Error()
c.JSON(err.Status, AccountResponse{
Error: &s,
})
return
}
apiResource := newAccount(c, account)
c.JSON(http.StatusOK, AccountResponse{Data: &apiResource})
}
// @Summary Delete account
// @Description Deletes an account
// @Tags Accounts
// @Produce json
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404 {object} httperrors.HTTPError
// @Failure 500 {object} httperrors.HTTPError
// @Param id path string true "ID formatted as string"
// @Router /v4/accounts/{id} [delete]
func DeleteAccount(c *gin.Context) {
id, err := httputil.UUIDFromString(c.Param("id"))
if !err.Nil() {
c.JSON(err.Status, httperrors.HTTPError{
Error: err.Error(),
})
return
}
account, err := getModelByID[models.Account](c, id)
if !err.Nil() {
c.JSON(err.Status, httperrors.HTTPError{
Error: err.Error(),
})
return
}
err = query(c, models.DB.Delete(&account))
if !err.Nil() {
c.JSON(err.Status, httperrors.HTTPError{
Error: err.Error(),
})
return
}
c.JSON(http.StatusNoContent, nil)
}