-
Notifications
You must be signed in to change notification settings - Fork 16
/
disbursement_handler.go
472 lines (404 loc) · 17.4 KB
/
disbursement_handler.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
package httphandler
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/gocarina/gocsv"
"github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/httpjson"
"github.com/stellar/stellar-disbursement-platform-backend/internal/data"
"github.com/stellar/stellar-disbursement-platform-backend/internal/monitor"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/httperror"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/httpresponse"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/middleware"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/validators"
"github.com/stellar/stellar-disbursement-platform-backend/internal/services"
"github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine/signing"
"github.com/stellar/stellar-disbursement-platform-backend/pkg/schema"
"github.com/stellar/stellar-disbursement-platform-backend/stellar-auth/pkg/auth"
)
type DisbursementHandler struct {
Models *data.Models
MonitorService monitor.MonitorServiceInterface
AuthManager auth.AuthManager
DisbursementManagementService *services.DisbursementManagementService
DistributionAccountResolver signing.DistributionAccountResolver
}
type PostDisbursementRequest struct {
Name string `json:"name"`
CountryCode string `json:"country_code"`
WalletID string `json:"wallet_id"`
AssetID string `json:"asset_id"`
VerificationField data.VerificationField `json:"verification_field"`
SMSRegistrationMessageTemplate string `json:"sms_registration_message_template"`
}
type PatchDisbursementStatusRequest struct {
Status string `json:"status"`
}
func (d DisbursementHandler) PostDisbursement(w http.ResponseWriter, r *http.Request) {
var disbursementRequest PostDisbursementRequest
err := json.NewDecoder(r.Body).Decode(&disbursementRequest)
if err != nil {
httperror.BadRequest("invalid request body", err, nil).Render(w)
return
}
v := validators.NewDisbursementRequestValidator(disbursementRequest.VerificationField)
v.Check(disbursementRequest.Name != "", "name", "name is required")
v.Check(disbursementRequest.CountryCode != "", "country_code", "country_code is required")
v.Check(disbursementRequest.WalletID != "", "wallet_id", "wallet_id is required")
v.Check(disbursementRequest.AssetID != "", "asset_id", "asset_id is required")
if v.HasErrors() {
httperror.BadRequest("Request invalid", err, v.Errors).Render(w)
return
}
verificationField := v.ValidateAndGetVerificationType()
if v.HasErrors() {
httperror.BadRequest("Verification field invalid", err, v.Errors).Render(w)
return
}
ctx := r.Context()
wallet, err := d.Models.Wallets.Get(ctx, disbursementRequest.WalletID)
if err != nil {
httperror.BadRequest("wallet ID is invalid", err, nil).Render(w)
return
}
if !wallet.Enabled {
httperror.BadRequest("wallet is not enabled", errors.New("wallet is not enabled"), nil).Render(w)
return
}
asset, err := d.Models.Assets.Get(ctx, disbursementRequest.AssetID)
if err != nil {
httperror.BadRequest("asset ID is invalid", err, nil).Render(w)
return
}
country, err := d.Models.Countries.Get(ctx, disbursementRequest.CountryCode)
if err != nil {
httperror.BadRequest("country code is invalid", err, nil).Render(w)
return
}
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
msg := fmt.Sprintf("Cannot get token from context when inserting disbursement %s", disbursementRequest.Name)
httperror.InternalError(ctx, msg, nil, nil).Render(w)
return
}
user, err := d.AuthManager.GetUser(ctx, token)
if err != nil {
msg := fmt.Sprintf("Cannot insert disbursement %s", disbursementRequest.Name)
httperror.InternalError(ctx, msg, err, nil).Render(w)
return
}
disbursement := data.Disbursement{
Name: disbursementRequest.Name,
Status: data.DraftDisbursementStatus,
StatusHistory: []data.DisbursementStatusHistoryEntry{{
Timestamp: time.Now(),
Status: data.DraftDisbursementStatus,
UserID: user.ID,
}},
Wallet: wallet,
Asset: asset,
Country: country,
VerificationField: verificationField,
SMSRegistrationMessageTemplate: disbursementRequest.SMSRegistrationMessageTemplate,
}
newId, err := d.Models.Disbursements.Insert(ctx, &disbursement)
if err != nil {
if errors.Is(data.ErrRecordAlreadyExists, err) {
httperror.Conflict("disbursement already exists", err, nil).Render(w)
} else {
httperror.BadRequest("could not create disbursement", err, nil).Render(w)
}
return
}
newDisbursement, err := d.Models.Disbursements.Get(ctx, d.Models.DBConnectionPool, newId)
if err != nil {
msg := fmt.Sprintf("Cannot retrieve disbursement for ID: %s", newId)
httperror.InternalError(ctx, msg, err, nil).Render(w)
return
}
labels := monitor.DisbursementLabels{
Asset: newDisbursement.Asset.Code,
Country: newDisbursement.Country.Code,
Wallet: newDisbursement.Wallet.Name,
}
err = d.MonitorService.MonitorCounters(monitor.DisbursementsCounterTag, labels.ToMap())
if err != nil {
log.Ctx(ctx).Errorf("Error trying to monitor disbursement counter: %s", err)
}
httpjson.RenderStatus(w, http.StatusCreated, newDisbursement, httpjson.JSON)
}
// GetDisbursements returns a paginated list of disbursements
func (d DisbursementHandler) GetDisbursements(w http.ResponseWriter, r *http.Request) {
validator := validators.NewDisbursementQueryValidator()
queryParams := validator.ParseParametersFromRequest(r)
if validator.HasErrors() {
httperror.BadRequest("request invalid", nil, validator.Errors).Render(w)
return
}
queryParams.Filters = validator.ValidateAndGetDisbursementFilters(queryParams.Filters)
if validator.HasErrors() {
httperror.BadRequest("request invalid", nil, validator.Errors).Render(w)
return
}
ctx := r.Context()
resultWithTotal, err := d.DisbursementManagementService.GetDisbursementsWithCount(ctx, queryParams)
if err != nil {
httperror.InternalError(ctx, "Cannot retrieve disbursements", err, nil).Render(w)
return
}
if resultWithTotal.Total == 0 {
httpjson.RenderStatus(w, http.StatusOK, httpresponse.NewEmptyPaginatedResponse(), httpjson.JSON)
return
}
response, errGet := httpresponse.NewPaginatedResponse(r, resultWithTotal.Result, queryParams.Page, queryParams.PageLimit, resultWithTotal.Total)
if errGet != nil {
httperror.InternalError(ctx, "Cannot write paginated response for disbursements", errGet, nil).Render(w)
return
}
httpjson.RenderStatus(w, http.StatusOK, response, httpjson.JSON)
}
func (d DisbursementHandler) PostDisbursementInstructions(w http.ResponseWriter, r *http.Request) {
disbursementID := chi.URLParam(r, "id")
// check if disbursement exists
ctx := r.Context()
disbursement, err := d.Models.Disbursements.Get(ctx, d.Models.DBConnectionPool, disbursementID)
if err != nil {
httperror.BadRequest("disbursement ID is invalid", err, nil).Render(w)
return
}
// check if disbursement is in draft, ready status
if disbursement.Status != data.DraftDisbursementStatus && disbursement.Status != data.ReadyDisbursementStatus {
httperror.BadRequest("disbursement is not in draft or ready status", nil, nil).Render(w)
return
}
// Parse uploaded CSV file
file, header, err := r.FormFile("file")
if err != nil {
httperror.BadRequest("could not parse file", err, nil).Render(w)
return
}
defer file.Close()
// TeeReader is used to read multiple times from the same reader (file)
// We read once to process the instructions, and then again to persist the file to the database
var buf bytes.Buffer
reader := io.TeeReader(file, &buf)
instructions, v := parseInstructionsFromCSV(ctx, reader, disbursement.VerificationField)
if v != nil && v.HasErrors() {
httperror.BadRequest("could not parse csv file", err, v.Errors).Render(w)
return
}
disbursementUpdate := &data.DisbursementUpdate{
ID: disbursementID,
FileName: header.Filename,
FileContent: buf.Bytes(),
}
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
msg := fmt.Sprintf("Cannot get token from context when processing instructions for disbursement with ID %s", disbursementID)
httperror.InternalError(ctx, msg, err, nil).Render(w)
return
}
user, err := d.AuthManager.GetUser(ctx, token)
if err != nil {
msg := fmt.Sprintf("Cannot get token from context when processing instructions for disbursement with ID %s", disbursementID)
httperror.InternalError(ctx, msg, err, nil).Render(w)
return
}
if err = d.Models.DisbursementInstructions.ProcessAll(ctx, user.ID, instructions, disbursement, disbursementUpdate, data.MaxInstructionsPerDisbursement); err != nil {
switch {
case errors.Is(err, data.ErrMaxInstructionsExceeded):
httperror.BadRequest(fmt.Sprintf("number of instructions exceeds maximum of : %d", data.MaxInstructionsPerDisbursement), err, nil).Render(w)
case errors.Is(err, data.ErrReceiverVerificationMismatch):
httperror.BadRequest(errors.Unwrap(err).Error(), err, nil).Render(w)
default:
httperror.InternalError(ctx, fmt.Sprintf("Cannot process instructions for disbursement with ID: %s", disbursementID), err, nil).Render(w)
}
return
}
response := map[string]string{
"message": "File uploaded successfully",
}
httpjson.Render(w, response, httpjson.JSON)
}
func (d DisbursementHandler) GetDisbursement(w http.ResponseWriter, r *http.Request) {
disbursementID := chi.URLParam(r, "id")
ctx := r.Context()
disbursement, err := d.Models.Disbursements.GetWithStatistics(ctx, disbursementID)
if err != nil {
if errors.Is(err, data.ErrRecordNotFound) {
httperror.NotFound("disbursement not found", err, nil).Render(w)
} else {
msg := fmt.Sprintf("Cannot get receivers for disbursement with ID: %s", disbursementID)
httperror.InternalError(ctx, msg, err, nil).Render(w)
}
return
}
response, err := d.DisbursementManagementService.AppendUserMetadata(ctx, []*data.Disbursement{disbursement})
if err != nil {
httperror.NotFound("disbursement user metadata not found", err, nil).Render(w)
}
if len(response) != 1 {
httperror.InternalError(
ctx, fmt.Sprintf("Size of response is unexpected: %d", len(response)), nil, nil,
).Render(w)
}
httpjson.Render(w, response[0], httpjson.JSON)
}
func (d DisbursementHandler) GetDisbursementReceivers(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
disbursementID := chi.URLParam(r, "id")
validator := validators.NewReceiverQueryValidator()
queryParams := validator.ParseParametersFromRequest(r)
if validator.HasErrors() {
httperror.BadRequest("request invalid", nil, validator.Errors).Render(w)
return
}
resultWithTotal, err := d.DisbursementManagementService.GetDisbursementReceiversWithCount(ctx, disbursementID, queryParams)
if err != nil {
if errors.Is(err, services.ErrDisbursementNotFound) {
httperror.NotFound("disbursement not found", err, nil).Render(w)
} else {
msg := fmt.Sprintf("Cannot find disbursement with ID: %s", disbursementID)
httperror.InternalError(ctx, msg, err, nil).Render(w)
}
return
}
if resultWithTotal.Total == 0 {
httpjson.RenderStatus(w, http.StatusOK, httpresponse.NewEmptyPaginatedResponse(), httpjson.JSON)
return
}
response, err := httpresponse.NewPaginatedResponse(r, resultWithTotal.Result, queryParams.Page, queryParams.PageLimit, resultWithTotal.Total)
if err != nil {
msg := fmt.Sprintf("Cannot write paginated response for disbursement with ID: %s", disbursementID)
httperror.InternalError(ctx, msg, err, nil).Render(w)
return
}
httpjson.RenderStatus(w, http.StatusOK, response, httpjson.JSON)
}
type UpdateDisbursementStatusResponseBody struct {
Message string `json:"message"`
}
// PatchDisbursementStatus updates the status of a disbursement
func (d DisbursementHandler) PatchDisbursementStatus(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var patchRequest PatchDisbursementStatusRequest
err := json.NewDecoder(r.Body).Decode(&patchRequest)
if err != nil {
httperror.BadRequest("invalid request body", err, nil).Render(w)
return
}
// validate request
toStatus, err := data.ToDisbursementStatus(patchRequest.Status)
if err != nil {
httperror.BadRequest("invalid status", err, nil).Render(w)
return
}
response := UpdateDisbursementStatusResponseBody{}
disbursementID := chi.URLParam(r, "id")
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
httperror.InternalError(ctx, "Cannot get token from context", err, nil).Render(w)
}
user, err := d.AuthManager.GetUser(ctx, token)
if err != nil {
httperror.InternalError(ctx, "Cannot get user from token", err, nil).Render(w)
}
switch toStatus {
case data.StartedDisbursementStatus:
var distributionPublicKey string
var distributionAccount *schema.DistributionAccount
if distributionAccount, err = d.DistributionAccountResolver.DistributionAccountFromContext(ctx); err != nil {
httperror.InternalError(ctx, "Cannot get distribution account", err, nil).Render(w)
return
} else if !distributionAccount.IsStellar() {
// TODO: during SDP-1177, refactor StartDisbursement to receive the whole distribution account object, rather than just the public key
msg := fmt.Sprintf("expected distribution account to be a STELLAR account but got %q", distributionAccount.Type)
httperror.BadRequest(msg, err, nil).Render(w)
return
} else {
distributionPublicKey = distributionAccount.Address
}
err = d.DisbursementManagementService.StartDisbursement(ctx, disbursementID, user, distributionPublicKey)
response.Message = "Disbursement started"
case data.PausedDisbursementStatus:
err = d.DisbursementManagementService.PauseDisbursement(ctx, disbursementID, user)
response.Message = "Disbursement paused"
default:
err = services.ErrDisbursementStatusCantBeChanged
}
var insufficientBalanceErr services.InsufficientBalanceError
if err != nil {
switch {
case errors.Is(err, services.ErrDisbursementNotFound):
httperror.NotFound(services.ErrDisbursementNotFound.Error(), err, nil).Render(w)
case errors.Is(err, services.ErrDisbursementNotReadyToStart):
httperror.BadRequest(services.ErrDisbursementNotReadyToStart.Error(), err, nil).Render(w)
case errors.Is(err, services.ErrDisbursementNotReadyToPause):
httperror.BadRequest(services.ErrDisbursementNotReadyToPause.Error(), err, nil).Render(w)
case errors.Is(err, services.ErrDisbursementStatusCantBeChanged):
httperror.BadRequest(services.ErrDisbursementStatusCantBeChanged.Error(), err, nil).Render(w)
case errors.Is(err, services.ErrDisbursementStartedByCreator):
httperror.Forbidden("Disbursement can't be started by its creator. Approval by another user is required.", err, nil).Render(w)
case errors.Is(err, services.ErrDisbursementWalletDisabled):
httperror.BadRequest(services.ErrDisbursementWalletDisabled.Error(), err, nil).Render(w)
case errors.As(err, &insufficientBalanceErr):
log.Ctx(ctx).Error(insufficientBalanceErr)
httperror.Conflict(insufficientBalanceErr.Error(), err, nil).Render(w)
default:
msg := fmt.Sprintf("Cannot update disbursementID=%s with status=%s: %v", disbursementID, toStatus, err)
httperror.InternalError(ctx, msg, err, nil).Render(w)
}
return
}
httpjson.RenderStatus(w, http.StatusOK, response, httpjson.JSON)
}
func (d DisbursementHandler) GetDisbursementInstructions(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
disbursementID := chi.URLParam(r, "id")
disbursement, err := d.Models.Disbursements.Get(ctx, d.Models.DBConnectionPool, disbursementID)
if err != nil {
httperror.NotFound("disbursement not found", err, nil).Render(w)
return
}
if len(disbursement.FileContent) == 0 {
err = fmt.Errorf("disbursement %s has no instructions file", disbursementID)
log.Ctx(ctx).Error(err)
httperror.NotFound(err.Error(), err, nil).Render(w)
return
}
// `attachment` returns a file-download prompt. change that to `inline` to open in browser
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, disbursement.FileName))
w.Header().Set("Content-Type", "text/csv")
_, err = w.Write(disbursement.FileContent)
if err != nil {
httperror.InternalError(ctx, "Cannot write disbursement instructions to response", err, nil).Render(w)
}
}
func parseInstructionsFromCSV(ctx context.Context, file io.Reader, verificationField data.VerificationField) ([]*data.DisbursementInstruction, *validators.DisbursementInstructionsValidator) {
validator := validators.NewDisbursementInstructionsValidator(verificationField)
instructions := []*data.DisbursementInstruction{}
if err := gocsv.Unmarshal(file, &instructions); err != nil {
log.Ctx(ctx).Errorf("error parsing csv file: %s", err.Error())
validator.Errors["file"] = "could not parse file"
return nil, validator
}
var sanitizedInstructions []*data.DisbursementInstruction
for i, instruction := range instructions {
sanitizedInstruction := validator.SanitizeInstruction(instruction)
lineNumber := i + 2 // +1 for header row, +1 for 0-index
validator.ValidateInstruction(sanitizedInstruction, lineNumber)
sanitizedInstructions = append(sanitizedInstructions, sanitizedInstruction)
}
validator.Check(len(sanitizedInstructions) > 0, "instructions", "no valid instructions found")
if validator.HasErrors() {
return nil, validator
}
return sanitizedInstructions, nil
}