http.go419 lines, 13 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/csv" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/fx" |
| 11 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 12 | "github.com/fiston-user/payments/internal/platform/authn" |
| 13 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 14 | "github.com/fiston-user/payments/internal/platform/idempotency" |
| 15 | "github.com/google/uuid" |
| 16 | "github.com/jackc/pgx/v5" |
| 17 | ) |
| 18 | |
| 19 | // The API's JSON shapes. They're separate from the database models on |
| 20 | // purpose: those follow the schema, these are a contract with our clients. |
| 21 | type ( |
| 22 | walletResponse struct { |
| 23 | ID uuid.UUID `json:"id"` |
| 24 | OwnerID *uuid.UUID `json:"owner_id"` |
| 25 | Currency string `json:"currency"` |
| 26 | CreatedAt time.Time `json:"created_at"` |
| 27 | } |
| 28 | balanceResponse struct { |
| 29 | WalletID uuid.UUID `json:"wallet_id"` |
| 30 | Balance Money `json:"balance"` |
| 31 | } |
| 32 | depositResponse struct { |
| 33 | TransactionID uuid.UUID `json:"transaction_id"` |
| 34 | WalletID uuid.UUID `json:"wallet_id"` |
| 35 | Amount Money `json:"amount"` |
| 36 | CreatedAt time.Time `json:"created_at"` |
| 37 | } |
| 38 | transferResponse struct { |
| 39 | TransactionID uuid.UUID `json:"transaction_id"` |
| 40 | From uuid.UUID `json:"from"` |
| 41 | To uuid.UUID `json:"to"` |
| 42 | Amount Money `json:"amount"` |
| 43 | CreatedAt time.Time `json:"created_at"` |
| 44 | } |
| 45 | entryResponse struct { |
| 46 | ID int64 `json:"id"` |
| 47 | TransactionID uuid.UUID `json:"transaction_id"` |
| 48 | Direction Direction `json:"direction"` |
| 49 | Amount Money `json:"amount"` |
| 50 | CreatedAt time.Time `json:"created_at"` |
| 51 | } |
| 52 | entriesResponse struct { |
| 53 | Entries []entryResponse `json:"entries"` |
| 54 | NextCursor string `json:"next_cursor,omitempty"` |
| 55 | } |
| 56 | // A quote, and once it's used, a conversion: the same, with its transaction. |
| 57 | quoteResponse struct { |
| 58 | ID uuid.UUID `json:"id"` |
| 59 | Sell Money `json:"sell"` |
| 60 | Buy Money `json:"buy"` |
| 61 | Fee Money `json:"fee"` |
| 62 | Rate fx.Rate `json:"rate"` |
| 63 | ExpiresAt time.Time `json:"expires_at"` |
| 64 | TransactionID *uuid.UUID `json:"transaction_id,omitempty"` |
| 65 | } |
| 66 | ) |
| 67 | |
| 68 | func toWallet(a Account) walletResponse { |
| 69 | return walletResponse{ID: a.ID, OwnerID: a.OwnerID, Currency: a.Currency, CreatedAt: a.CreatedAt} |
| 70 | } |
| 71 | |
| 72 | // Handler serves the wallet API over HTTP. It only translates: JSON and URLs |
| 73 | // in, calls to the Service, JSON out. The rules live in the Service. |
| 74 | type Handler struct { |
| 75 | svc *Service |
| 76 | keys *idempotency.Store |
| 77 | } |
| 78 | |
| 79 | // NewHandler returns a Handler that serves svc. Requests that move money run |
| 80 | // once per idempotency key, and keys keeps those. |
| 81 | func NewHandler(svc *Service, keys *idempotency.Store) *Handler { |
| 82 | return &Handler{svc: svc, keys: keys} |
| 83 | } |
| 84 | |
| 85 | // Register adds the wallet API's routes to mux. |
| 86 | func (h *Handler) Register(mux *http.ServeMux) { |
| 87 | mux.Handle("POST /v1/wallets", httpx.HandlerFunc(h.createWallet)) |
| 88 | mux.Handle("GET /v1/wallets/{id}", httpx.HandlerFunc(h.getWallet)) |
| 89 | mux.Handle("GET /v1/wallets/{id}/balance", httpx.HandlerFunc(h.getBalance)) |
| 90 | mux.Handle("POST /v1/wallets/{id}/deposits", httpx.HandlerFunc(h.deposit)) |
| 91 | mux.Handle("GET /v1/wallets/{id}/entries", httpx.HandlerFunc(h.listEntries)) |
| 92 | mux.Handle("GET /v1/wallets/{id}/statement.csv", httpx.HandlerFunc(h.statement)) |
| 93 | mux.Handle("POST /v1/transfers", httpx.HandlerFunc(h.transfer)) |
| 94 | mux.Handle("POST /v1/fx/quotes", httpx.HandlerFunc(h.quote)) |
| 95 | mux.Handle("POST /v1/fx/conversions", httpx.HandlerFunc(h.convert)) |
| 96 | } |
| 97 | |
| 98 | // walletID reads the wallet ID from the URL. An ID that isn't a UUID can't |
| 99 | // name a wallet, so it's a 404, just like an unknown one. |
| 100 | func walletID(r *http.Request) (uuid.UUID, error) { |
| 101 | id, err := uuid.Parse(r.PathValue("id")) |
| 102 | if err != nil { |
| 103 | return uuid.Nil, ErrWalletNotFound |
| 104 | } |
| 105 | return id, nil |
| 106 | } |
| 107 | |
| 108 | // caller returns the user who sent a request, as authn.Require stored it. If a |
| 109 | // route ever misses Require, it's uuid.Nil, who owns nothing: it fails closed. |
| 110 | func caller(ctx context.Context) uuid.UUID { |
| 111 | user, _ := authn.UserID(ctx) |
| 112 | return user |
| 113 | } |
| 114 | |
| 115 | // as returns the Service acting for the user who sent r. |
| 116 | func (h *Handler) as(r *http.Request) *Service { |
| 117 | return h.svc.As(caller(r.Context())) |
| 118 | } |
| 119 | |
| 120 | // idempotent runs a request that moves money once per idempotency key. req is |
| 121 | // the decoded request body, for the key's fingerprint. do runs inside the |
| 122 | // database transaction that completes the key, with a Service bound to it, so |
| 123 | // the money moves and the key completes together, or not at all. |
| 124 | func (h *Handler) idempotent( |
| 125 | w http.ResponseWriter, r *http.Request, req any, |
| 126 | do func(svc *Service) (idempotency.Response, error), |
| 127 | ) error { |
| 128 | key, err := idempotency.NewKey(r, caller(r.Context()).String(), req) |
| 129 | if err != nil { |
| 130 | return err |
| 131 | } |
| 132 | resp, err := h.keys.Run(r.Context(), key, func(tx pgx.Tx) (idempotency.Response, error) { |
| 133 | return do(h.as(r).WithTx(tx)) |
| 134 | }) |
| 135 | if err != nil { |
| 136 | return err |
| 137 | } |
| 138 | resp.Write(w) |
| 139 | return nil |
| 140 | } |
| 141 | |
| 142 | func (h *Handler) createWallet(w http.ResponseWriter, r *http.Request) error { |
| 143 | var req struct { |
| 144 | Currency string `json:"currency"` |
| 145 | } |
| 146 | if err := httpx.DecodeJSON(w, r, &req); err != nil { |
| 147 | return err |
| 148 | } |
| 149 | acc, err := h.svc.CreateWallet(r.Context(), caller(r.Context()).String(), req.Currency) |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | w.Header().Set("Location", "/v1/wallets/"+acc.ID.String()) |
| 154 | httpx.WriteJSON(w, r, http.StatusCreated, toWallet(acc)) |
| 155 | return nil |
| 156 | } |
| 157 | |
| 158 | func (h *Handler) getWallet(w http.ResponseWriter, r *http.Request) error { |
| 159 | id, err := walletID(r) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | acc, err := h.as(r).Wallet(r.Context(), id) |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | httpx.WriteJSON(w, r, http.StatusOK, toWallet(acc)) |
| 168 | return nil |
| 169 | } |
| 170 | |
| 171 | func (h *Handler) getBalance(w http.ResponseWriter, r *http.Request) error { |
| 172 | id, err := walletID(r) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | b, err := h.as(r).Balance(r.Context(), id) |
| 177 | if err != nil { |
| 178 | return err |
| 179 | } |
| 180 | httpx.WriteJSON(w, r, http.StatusOK, balanceResponse{ |
| 181 | WalletID: b.AccountID, |
| 182 | Balance: Money{Amount: b.Balance, Currency: b.Currency}, |
| 183 | }) |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | func (h *Handler) deposit(w http.ResponseWriter, r *http.Request) error { |
| 188 | id, err := walletID(r) |
| 189 | if err != nil { |
| 190 | return err |
| 191 | } |
| 192 | var amount Money |
| 193 | if err := httpx.DecodeJSON(w, r, &amount); err != nil { |
| 194 | return err |
| 195 | } |
| 196 | return h.idempotent(w, r, amount, func(svc *Service) (idempotency.Response, error) { |
| 197 | tx, err := svc.Deposit(r.Context(), id, amount) |
| 198 | if err != nil { |
| 199 | return idempotency.Response{}, err |
| 200 | } |
| 201 | return idempotency.JSON(http.StatusCreated, depositResponse{ |
| 202 | TransactionID: tx.ID, |
| 203 | WalletID: id, |
| 204 | Amount: amount, |
| 205 | CreatedAt: tx.CreatedAt, |
| 206 | }) |
| 207 | }) |
| 208 | } |
| 209 | |
| 210 | func (h *Handler) transfer(w http.ResponseWriter, r *http.Request) error { |
| 211 | var req struct { |
| 212 | From string `json:"from"` |
| 213 | To string `json:"to"` |
| 214 | Amount int64 `json:"amount"` |
| 215 | Currency string `json:"currency"` |
| 216 | } |
| 217 | if err := httpx.DecodeJSON(w, r, &req); err != nil { |
| 218 | return err |
| 219 | } |
| 220 | return h.idempotent(w, r, req, func(svc *Service) (idempotency.Response, error) { |
| 221 | amount := Money{Amount: req.Amount, Currency: req.Currency} |
| 222 | tr, err := svc.Transfer(r.Context(), req.From, req.To, amount) |
| 223 | if err != nil { |
| 224 | return idempotency.Response{}, err |
| 225 | } |
| 226 | return idempotency.JSON(http.StatusCreated, transferResponse{ |
| 227 | TransactionID: tr.TransactionID, |
| 228 | From: tr.From, |
| 229 | To: tr.To, |
| 230 | Amount: tr.Amount, |
| 231 | CreatedAt: tr.CreatedAt, |
| 232 | }) |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | func (h *Handler) listEntries(w http.ResponseWriter, r *http.Request) error { |
| 237 | id, err := walletID(r) |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | limit, err := httpx.QueryInt(r, "limit", DefaultPageSize) |
| 242 | if err != nil { |
| 243 | return err |
| 244 | } |
| 245 | page, err := h.as(r).Entries(r.Context(), id, r.URL.Query().Get("cursor"), limit) |
| 246 | if err != nil { |
| 247 | return err |
| 248 | } |
| 249 | resp := entriesResponse{ |
| 250 | Entries: make([]entryResponse, len(page.Entries)), |
| 251 | NextCursor: page.NextCursor, |
| 252 | } |
| 253 | for i, e := range page.Entries { |
| 254 | resp.Entries[i] = entryResponse{ |
| 255 | ID: e.ID, |
| 256 | TransactionID: e.TransactionID, |
| 257 | Direction: e.Direction, |
| 258 | Amount: Money{Amount: e.Amount, Currency: e.Currency}, |
| 259 | CreatedAt: e.CreatedAt, |
| 260 | } |
| 261 | } |
| 262 | httpx.WriteJSON(w, r, http.StatusOK, resp) |
| 263 | return nil |
| 264 | } |
| 265 | |
| 266 | func toQuote(q FXQuote) quoteResponse { |
| 267 | return quoteResponse{ |
| 268 | ID: q.ID, |
| 269 | Sell: Money{Amount: q.SellAmount, Currency: q.SellCurrency}, |
| 270 | Buy: Money{Amount: q.BuyAmount, Currency: q.BuyCurrency}, |
| 271 | Fee: Money{Amount: q.Fee, Currency: q.SellCurrency}, |
| 272 | Rate: q.Rate, |
| 273 | ExpiresAt: q.ExpiresAt, |
| 274 | TransactionID: q.TransactionID, |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | func (h *Handler) quote(w http.ResponseWriter, r *http.Request) error { |
| 279 | var req QuoteRequest |
| 280 | if err := httpx.DecodeJSON(w, r, &req); err != nil { |
| 281 | return err |
| 282 | } |
| 283 | quote, err := h.svc.Quote(r.Context(), caller(r.Context()), req) |
| 284 | if err != nil { |
| 285 | return err |
| 286 | } |
| 287 | httpx.WriteJSON(w, r, http.StatusCreated, toQuote(quote)) |
| 288 | return nil |
| 289 | } |
| 290 | |
| 291 | // convert takes a quote. A retry with the same Idempotency-Key gets the same |
| 292 | // answer; a new request for a used quote gets quote_used. |
| 293 | func (h *Handler) convert(w http.ResponseWriter, r *http.Request) error { |
| 294 | var req struct { |
| 295 | QuoteID uuid.UUID `json:"quote_id"` |
| 296 | } |
| 297 | if err := httpx.DecodeJSON(w, r, &req); err != nil { |
| 298 | return err |
| 299 | } |
| 300 | return h.idempotent(w, r, req, func(svc *Service) (idempotency.Response, error) { |
| 301 | used, err := svc.Convert(r.Context(), caller(r.Context()), req.QuoteID) |
| 302 | if err != nil { |
| 303 | return idempotency.Response{}, err |
| 304 | } |
| 305 | return idempotency.JSON(http.StatusCreated, toQuote(used)) |
| 306 | }) |
| 307 | } |
| 308 | |
| 309 | // RegisterInternal adds our finance team's reports to mux. The gateway never |
| 310 | // routes /internal/: only our own network can reach it. |
| 311 | func (h *Handler) RegisterInternal(mux *http.ServeMux) { |
| 312 | mux.Handle("GET /internal/trial-balance.csv", httpx.HandlerFunc(h.trialBalance)) |
| 313 | } |
| 314 | |
| 315 | // statement sends a wallet's statement for the days from and to, as CSV. It |
| 316 | // streams: the first lines leave before the last ones are read. |
| 317 | func (h *Handler) statement(w http.ResponseWriter, r *http.Request) error { |
| 318 | id, err := walletID(r) |
| 319 | if err != nil { |
| 320 | return err |
| 321 | } |
| 322 | from, to, err := period(r) |
| 323 | if err != nil { |
| 324 | return err |
| 325 | } |
| 326 | lines, err := h.as(r).Statement(r.Context(), id, from, to) |
| 327 | if err != nil { |
| 328 | return err |
| 329 | } |
| 330 | |
| 331 | // The status goes out with the first bytes: from here on, an error can |
| 332 | // only cut the download short. |
| 333 | out := download(w, "statement-"+from.Format(time.DateOnly)+"-to-"+to.Format(time.DateOnly)+".csv") |
| 334 | out.Write(StatementHeader) |
| 335 | for line, err := range lines { |
| 336 | var rec []string |
| 337 | if err == nil { |
| 338 | rec, err = line.Record() |
| 339 | } |
| 340 | if err == nil { |
| 341 | err = out.Write(rec) |
| 342 | } |
| 343 | if err != nil { |
| 344 | abort(r, err) |
| 345 | } |
| 346 | } |
| 347 | out.Flush() |
| 348 | if err := out.Error(); err != nil { |
| 349 | abort(r, err) |
| 350 | } |
| 351 | return nil |
| 352 | } |
| 353 | |
| 354 | // download starts sending a CSV file, called name. |
| 355 | func download(w http.ResponseWriter, name string) *csv.Writer { |
| 356 | w.Header().Set("Content-Type", "text/csv; charset=utf-8") |
| 357 | w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`) |
| 358 | w.Header().Set("Cache-Control", "no-store") // someone's money: never in a shared cache |
| 359 | return csv.NewWriter(w) |
| 360 | } |
| 361 | |
| 362 | // abort ends a response that has begun: the client sees a broken download, |
| 363 | // never a short file that looks complete. |
| 364 | func abort(r *http.Request, err error) { |
| 365 | slog.ErrorContext(r.Context(), "download aborted", "path", r.URL.Path, "err", err) |
| 366 | panic(http.ErrAbortHandler) |
| 367 | } |
| 368 | |
| 369 | // date reads a query parameter that's a day, like 2026-11-30, in UTC. A |
| 370 | // problem goes into v. |
| 371 | func date(r *http.Request, key string, v *apperr.ValidationError) time.Time { |
| 372 | d, err := time.Parse(time.DateOnly, r.URL.Query().Get(key)) |
| 373 | if err != nil { |
| 374 | v.Add(key, "must be a date, like 2026-11-30") |
| 375 | } |
| 376 | return d |
| 377 | } |
| 378 | |
| 379 | // period reads a statement's first and last days, from and to, both included: |
| 380 | // a year at most. |
| 381 | func period(r *http.Request) (from, to time.Time, err error) { |
| 382 | var v apperr.ValidationError |
| 383 | from, to = date(r, "from", &v), date(r, "to", &v) |
| 384 | if v.Err() == nil && (to.Before(from) || to.After(from.AddDate(1, 0, 0))) { |
| 385 | v.Add("to", "must be on or after from, and at most a year later") |
| 386 | } |
| 387 | return from, to, v.Err() |
| 388 | } |
| 389 | |
| 390 | // trialBalance sends finance the trial balance at the end of a day, as CSV: |
| 391 | // every ledger account's debits, credits and balance, and a total for each |
| 392 | // currency, whose balance must be zero. |
| 393 | func (h *Handler) trialBalance(w http.ResponseWriter, r *http.Request) error { |
| 394 | var v apperr.ValidationError |
| 395 | day := date(r, "date", &v) |
| 396 | if err := v.Err(); err != nil { |
| 397 | return err |
| 398 | } |
| 399 | lines, err := h.svc.TrialBalance(r.Context(), day.AddDate(0, 0, 1)) |
| 400 | if err != nil { |
| 401 | return err |
| 402 | } |
| 403 | records := [][]string{{"currency", "account", "debits", "credits", "balance"}} |
| 404 | for _, l := range lines { |
| 405 | rec := []string{l.Currency, l.Account} |
| 406 | for _, amount := range []int64{l.Debits, l.Credits, l.Debits - l.Credits} { |
| 407 | s, err := fx.Format(amount, l.Currency) |
| 408 | if err != nil { |
| 409 | return err // nothing is sent yet: still a 500 |
| 410 | } |
| 411 | rec = append(rec, s) |
| 412 | } |
| 413 | records = append(records, rec) |
| 414 | } |
| 415 | if err := download(w, "trial-balance-"+day.Format(time.DateOnly)+".csv").WriteAll(records); err != nil { |
| 416 | abort(r, err) |
| 417 | } |
| 418 | return nil |
| 419 | } |