-
Notifications
You must be signed in to change notification settings - Fork 3
/
account.go
330 lines (285 loc) · 8.77 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
package controllers
import (
"fmt"
"net/http"
"github.com/envelope-zero/backend/pkg/httperrors"
"github.com/envelope-zero/backend/pkg/httputil"
"github.com/envelope-zero/backend/pkg/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type AccountListResponse struct {
Data []Account `json:"data"`
}
type AccountResponse struct {
Data Account `json:"data"`
}
type Account struct {
models.Account
Links AccountLinks `json:"links"`
}
type AccountLinks struct {
Self string `json:"self" example:"https://example.com/api/v1/accounts/af892e10-7e0a-4fb8-b1bc-4b6d88401ed2"`
Transactions string `json:"transactions" example:"https://example.com/api/v1/transactions?account=af892e10-7e0a-4fb8-b1bc-4b6d88401ed2"`
}
type AccountQueryFilter struct {
Name string `form:"name"`
Note string `form:"note"`
BudgetID string `form:"budget"`
OnBudget bool `form:"onBudget"`
External bool `form:"external"`
}
func (a AccountQueryFilter) ToCreate(c *gin.Context) (models.AccountCreate, bool) {
budgetID, ok := httputil.UUIDFromString(c, a.BudgetID)
if !ok {
return models.AccountCreate{}, false
}
return models.AccountCreate{
Name: a.Name,
Note: a.Note,
BudgetID: budgetID,
OnBudget: a.OnBudget,
External: a.External,
}, true
}
// RegisterAccountRoutes registers the routes for accounts with
// the RouterGroup that is passed.
func (co Controller) RegisterAccountRoutes(r *gin.RouterGroup) {
// Root group
{
r.OPTIONS("", co.OptionsAccountList)
r.GET("", co.GetAccounts)
r.POST("", co.CreateAccount)
}
// Account with ID
{
r.OPTIONS("/:accountId", co.OptionsAccountDetail)
r.GET("/:accountId", co.GetAccount)
r.PATCH("/:accountId", co.UpdateAccount)
r.DELETE("/:accountId", co.DeleteAccount)
}
}
// OptionsAccountList returns the allowed HTTP verbs
//
// @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
// @Router /v1/accounts [options]
func (co Controller) OptionsAccountList(c *gin.Context) {
httputil.OptionsGetPost(c)
}
// OptionsAccountDetail returns the allowed HTTP verbs
//
// @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
// @Param accountId path string true "ID formatted as string"
// @Router /v1/accounts/{accountId} [options]
func (co Controller) OptionsAccountDetail(c *gin.Context) {
p, err := uuid.Parse(c.Param("accountId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
_, ok := co.getAccountObject(c, p)
if !ok {
return
}
httputil.OptionsGetPatchDelete(c)
}
// CreateAccount creates a new account
//
// @Summary Create account
// @Description Creates a new account
// @Tags Accounts
// @Produce json
// @Success 201 {object} AccountResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param account body models.AccountCreate true "Account"
// @Router /v1/accounts [post]
func (co Controller) CreateAccount(c *gin.Context) {
var account models.Account
if err := httputil.BindData(c, &account); err != nil {
return
}
// Check if the budget that the account shoud belong to exists
_, ok := co.getBudgetResource(c, account.BudgetID)
if !ok {
return
}
if !queryWithRetry(c, co.DB.Create(&account)) {
return
}
accountObject, _ := co.getAccountObject(c, account.ID)
c.JSON(http.StatusCreated, AccountResponse{Data: accountObject})
}
// GetAccounts returns a list of all accounts matching the filter parameters
//
// @Summary List accounts
// @Description Returns a list of accounts
// @Tags Accounts
// @Produce json
// @Success 200 {object} AccountListResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Router /v1/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 "Filter by on/off-budget"
// @Param external query bool false "Filter internal/external"
func (co Controller) 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 := httputil.GetURLFields(c.Request.URL, filter)
// Convert the QueryFilter to a Create struct
create, ok := filter.ToCreate(c)
if !ok {
return
}
var accounts []models.Account
if !queryWithRetry(c, co.DB.Where(&models.Account{
AccountCreate: create,
}, queryFields...).Find(&accounts)) {
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
accountObjects := make([]Account, 0)
for _, account := range accounts {
o, _ := co.getAccountObject(c, account.ID)
accountObjects = append(accountObjects, o)
}
c.JSON(http.StatusOK, AccountListResponse{Data: accountObjects})
}
// GetAccount returns data for a specific account
//
// @Summary Get account
// @Description Returns a specific account
// @Tags Accounts
// @Produce json
// @Success 200 {object} AccountResponse
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param accountId path string true "ID formatted as string"
// @Router /v1/accounts/{accountId} [get]
func (co Controller) GetAccount(c *gin.Context) {
p, err := uuid.Parse(c.Param("accountId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
accountObject, ok := co.getAccountObject(c, p)
if !ok {
return
}
c.JSON(http.StatusOK, AccountResponse{Data: accountObject})
}
// UpdateAccount updates data for a specific account
//
// @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} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param accountId path string true "ID formatted as string"
// @Param account body models.AccountCreate true "Account"
// @Router /v1/accounts/{accountId} [patch]
func (co Controller) UpdateAccount(c *gin.Context) {
p, err := uuid.Parse(c.Param("accountId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
account, ok := co.getAccountResource(c, p)
if !ok {
return
}
updateFields, err := httputil.GetBodyFields(c, models.AccountCreate{})
if err != nil {
return
}
var data models.Account
if err := httputil.BindData(c, &data); err != nil {
return
}
if !queryWithRetry(c, co.DB.Model(&account).Select("", updateFields...).Updates(data)) {
return
}
accountObject, _ := co.getAccountObject(c, account.ID)
c.JSON(http.StatusOK, AccountResponse{Data: accountObject})
}
// DeleteAccount deletes an account
//
// @Summary Delete account
// @Description Deletes an account
// @Tags Accounts
// @Produce json
// @Success 204
// @Failure 400 {object} httperrors.HTTPError
// @Failure 404
// @Failure 500 {object} httperrors.HTTPError
// @Param accountId path string true "ID formatted as string"
// @Router /v1/accounts/{accountId} [delete]
func (co Controller) DeleteAccount(c *gin.Context) {
p, err := uuid.Parse(c.Param("accountId"))
if err != nil {
httperrors.InvalidUUID(c)
return
}
account, ok := co.getAccountResource(c, p)
if !ok {
return
}
if !queryWithRetry(c, co.DB.Delete(&account)) {
return
}
c.JSON(http.StatusNoContent, gin.H{})
}
// getAccountResource is the internal helper to verify permissions and return an account.
func (co Controller) getAccountResource(c *gin.Context, id uuid.UUID) (models.Account, bool) {
if id == uuid.Nil {
httperrors.New(c, http.StatusBadRequest, "no account ID specified")
return models.Account{}, false
}
var account models.Account
if !queryWithRetry(c, co.DB.Where(&models.Account{
DefaultModel: models.DefaultModel{
ID: id,
},
}).First(&account), "No account found for the specified ID") {
return models.Account{}, false
}
return account, true
}
func (co Controller) getAccountObject(c *gin.Context, id uuid.UUID) (Account, bool) {
resource, ok := co.getAccountResource(c, id)
if !ok {
return Account{}, false
}
return Account{
resource.WithCalculations(co.DB),
AccountLinks{
Self: fmt.Sprintf("%s/v1/accounts/%s", c.GetString("baseURL"), resource.ID),
Transactions: fmt.Sprintf("%s/v1/transactions?account=%s", c.GetString("baseURL"), resource.ID),
},
}, true
}