service.go309 lines, 9.6 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "regexp" |
| 9 | "strconv" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 13 | "github.com/google/uuid" |
| 14 | "github.com/jackc/pgx/v5" |
| 15 | ) |
| 16 | |
| 17 | // SettlementAccount names the system account that funds deposits: the money |
| 18 | // we hold at our bank, one account per currency. |
| 19 | const SettlementAccount = "settlement" |
| 20 | |
| 21 | // MaxAmount caps a single deposit or transfer, in minor units: a million |
| 22 | // dollars, or a million euros. It catches typos, and keeps sums far from |
| 23 | // overflowing. |
| 24 | const MaxAmount = 100_000_000 |
| 25 | |
| 26 | // ErrWalletNotFound is returned when there's no wallet with the given ID. |
| 27 | var ErrWalletNotFound = fmt.Errorf("wallet %w", apperr.ErrNotFound) |
| 28 | |
| 29 | // Money is an amount in minor units of a currency, like cents for USD. It's |
| 30 | // an integer, never a float, and it never travels without its currency. |
| 31 | type Money struct { |
| 32 | Amount int64 `json:"amount"` |
| 33 | Currency string `json:"currency"` |
| 34 | } |
| 35 | |
| 36 | // Service is the wallet's business logic. It validates input, enforces the |
| 37 | // rules, and uses the Store to persist the results. It knows nothing about |
| 38 | // HTTP, so every way into the service gets the same rules. |
| 39 | type Service struct { |
| 40 | store *Store |
| 41 | user *uuid.UUID // set by As: the one owner whose wallets we see |
| 42 | fx FX // set by WithFX |
| 43 | } |
| 44 | |
| 45 | // NewService returns a Service that keeps its data in store. |
| 46 | func NewService(store *Store) *Service { |
| 47 | return &Service{store: store} |
| 48 | } |
| 49 | |
| 50 | // WithTx returns a Service that does all its work inside tx, the caller's |
| 51 | // database transaction. See Store.WithTx. |
| 52 | func (s *Service) WithTx(tx pgx.Tx) *Service { |
| 53 | c := *s |
| 54 | c.store = s.store.WithTx(tx) |
| 55 | return &c |
| 56 | } |
| 57 | |
| 58 | // As returns a Service that acts for a user: it only sees their wallets. The |
| 59 | // Service without a user sees everything, for our own code, like tests. |
| 60 | func (s *Service) As(user uuid.UUID) *Service { |
| 61 | c := *s |
| 62 | c.user = &user |
| 63 | return &c |
| 64 | } |
| 65 | |
| 66 | // currencyCode matches the shape of an ISO 4217 code, like USD or EUR. |
| 67 | var currencyCode = regexp.MustCompile(`^[A-Z]{3}$`) |
| 68 | |
| 69 | // CreateWallet opens a wallet for an owner, in one currency. An owner can |
| 70 | // have one wallet per currency. |
| 71 | func (s *Service) CreateWallet(ctx context.Context, ownerID, currency string) (Account, error) { |
| 72 | var v apperr.ValidationError |
| 73 | owner, err := uuid.Parse(ownerID) |
| 74 | if err != nil || owner == uuid.Nil { |
| 75 | v.Add("owner_id", "must be a UUID") |
| 76 | } |
| 77 | if !currencyCode.MatchString(currency) { |
| 78 | v.Add("currency", "must be a three-letter ISO 4217 code, like USD") |
| 79 | } |
| 80 | if err := v.Err(); err != nil { |
| 81 | return Account{}, err |
| 82 | } |
| 83 | |
| 84 | // We support a currency when we have a settlement account to fund it. |
| 85 | _, err = s.store.SystemAccount(ctx, SettlementAccount, currency) |
| 86 | if errors.Is(err, ErrAccountNotFound) { |
| 87 | v.Add("currency", "unsupported currency") |
| 88 | return Account{}, v.Err() |
| 89 | } |
| 90 | if err != nil { |
| 91 | return Account{}, err |
| 92 | } |
| 93 | |
| 94 | acc, err := s.store.CreateAccount(ctx, NewAccount{ |
| 95 | Kind: KindWallet, |
| 96 | OwnerID: &owner, |
| 97 | Name: currency + " wallet", |
| 98 | Currency: currency, |
| 99 | NormalBalance: Credit, |
| 100 | }) |
| 101 | if errors.Is(err, ErrAccountExists) { |
| 102 | return Account{}, fmt.Errorf("%w: owner already has a wallet in %s", apperr.ErrConflict, currency) |
| 103 | } |
| 104 | return acc, err |
| 105 | } |
| 106 | |
| 107 | // Wallet returns the wallet with the given ID. |
| 108 | func (s *Service) Wallet(ctx context.Context, id uuid.UUID) (Account, error) { |
| 109 | acc, err := s.store.Account(ctx, id) |
| 110 | if errors.Is(err, ErrAccountNotFound) || (err == nil && !s.sees(acc)) { |
| 111 | // System accounts are ours, and other people's wallets are theirs: to |
| 112 | // this caller, they don't exist. |
| 113 | return Account{}, ErrWalletNotFound |
| 114 | } |
| 115 | return acc, err |
| 116 | } |
| 117 | |
| 118 | // sees reports whether acc is a wallet this Service may see. |
| 119 | func (s *Service) sees(acc Account) bool { |
| 120 | if acc.Kind != KindWallet { |
| 121 | return false |
| 122 | } |
| 123 | return s.user == nil || (acc.OwnerID != nil && *acc.OwnerID == *s.user) |
| 124 | } |
| 125 | |
| 126 | // Balance returns a wallet's balance, derived from its entries. |
| 127 | func (s *Service) Balance(ctx context.Context, id uuid.UUID) (AccountBalance, error) { |
| 128 | if _, err := s.Wallet(ctx, id); err != nil { |
| 129 | return AccountBalance{}, err |
| 130 | } |
| 131 | return s.store.Balance(ctx, id) |
| 132 | } |
| 133 | |
| 134 | // Deposit adds money from outside to a wallet. It posts a balanced |
| 135 | // transaction: a debit to the settlement account, which now holds the money |
| 136 | // at our bank, and a credit to the wallet, which now owes it to the customer. |
| 137 | func (s *Service) Deposit(ctx context.Context, walletID uuid.UUID, amount Money) (Transaction, error) { |
| 138 | var v apperr.ValidationError |
| 139 | checkAmount(&v, amount.Amount) |
| 140 | |
| 141 | w, err := s.Wallet(ctx, walletID) |
| 142 | if err != nil { |
| 143 | return Transaction{}, err |
| 144 | } |
| 145 | // The client must say which currency it means, so 500 can never quietly |
| 146 | // become 500 yen in a dollar wallet. |
| 147 | if amount.Currency != w.Currency { |
| 148 | v.Add("currency", "must match the wallet's currency, "+w.Currency) |
| 149 | } |
| 150 | if err := v.Err(); err != nil { |
| 151 | return Transaction{}, err |
| 152 | } |
| 153 | |
| 154 | settlement, err := s.store.SystemAccount(ctx, SettlementAccount, w.Currency) |
| 155 | if err != nil { |
| 156 | // %v, not %w: a missing settlement account is our bug, so the client |
| 157 | // must get a 500, not a 404. |
| 158 | return Transaction{}, fmt.Errorf("settlement account for %s: %v", w.Currency, err) |
| 159 | } |
| 160 | return s.store.Deposit(ctx, settlement, w, amount.Amount) |
| 161 | } |
| 162 | |
| 163 | // checkAmount records a problem in v if amount can't be moved: money moves in |
| 164 | // positive amounts, up to MaxAmount at a time. |
| 165 | func checkAmount(v *apperr.ValidationError, amount int64) { |
| 166 | switch { |
| 167 | case amount <= 0: |
| 168 | v.Add("amount", "must be a positive number of minor units, like 1050 for 10.50") |
| 169 | case amount > MaxAmount: |
| 170 | v.Add("amount", fmt.Sprintf("must be at most %d", MaxAmount)) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // A Transfer is money that moved from one wallet to another. |
| 175 | type Transfer struct { |
| 176 | TransactionID uuid.UUID |
| 177 | From, To uuid.UUID |
| 178 | Amount Money |
| 179 | CreatedAt time.Time |
| 180 | } |
| 181 | |
| 182 | // Transfer moves money between two wallets in the same currency, as one |
| 183 | // balanced transaction: a debit to the sender, a credit to the receiver. |
| 184 | func (s *Service) Transfer(ctx context.Context, fromID, toID string, amount Money) (Transfer, error) { |
| 185 | var v apperr.ValidationError |
| 186 | checkAmount(&v, amount.Amount) |
| 187 | from, err := s.walletField(ctx, &v, "from", fromID) |
| 188 | if err != nil { |
| 189 | return Transfer{}, err |
| 190 | } |
| 191 | // Money can go to anyone's wallet: look the receiver up without a user. |
| 192 | to, err := (&Service{store: s.store}).walletField(ctx, &v, "to", toID) |
| 193 | if err != nil { |
| 194 | return Transfer{}, err |
| 195 | } |
| 196 | |
| 197 | // Compare the wallets only when both exist. |
| 198 | if from.ID != uuid.Nil && to.ID != uuid.Nil { |
| 199 | switch { |
| 200 | case from.ID == to.ID: |
| 201 | v.Add("to", "must be a different wallet") |
| 202 | case to.Currency != from.Currency: |
| 203 | v.Add("to", "must be a "+from.Currency+" wallet, like from") |
| 204 | case amount.Currency != from.Currency: |
| 205 | v.Add("currency", "must match the wallets' currency, "+from.Currency) |
| 206 | } |
| 207 | } |
| 208 | if err := v.Err(); err != nil { |
| 209 | return Transfer{}, err |
| 210 | } |
| 211 | |
| 212 | tx, err := s.store.Transfer(ctx, from, to, amount.Amount) |
| 213 | if err != nil { |
| 214 | return Transfer{}, err |
| 215 | } |
| 216 | return Transfer{ |
| 217 | TransactionID: tx.ID, |
| 218 | From: from.ID, |
| 219 | To: to.ID, |
| 220 | Amount: amount, |
| 221 | CreatedAt: tx.CreatedAt, |
| 222 | }, nil |
| 223 | } |
| 224 | |
| 225 | // walletField loads the wallet that a request field names. A malformed or |
| 226 | // unknown ID is a problem with that field, recorded in v: only unexpected |
| 227 | // errors are returned. |
| 228 | func (s *Service) walletField(ctx context.Context, v *apperr.ValidationError, field, id string) (Account, error) { |
| 229 | wid, err := uuid.Parse(id) |
| 230 | if err != nil { |
| 231 | v.Add(field, "must be a wallet ID") |
| 232 | return Account{}, nil |
| 233 | } |
| 234 | w, err := s.Wallet(ctx, wid) |
| 235 | if errors.Is(err, ErrWalletNotFound) { |
| 236 | v.Add(field, "no such wallet") |
| 237 | return Account{}, nil |
| 238 | } |
| 239 | return w, err |
| 240 | } |
| 241 | |
| 242 | // Page sizes for listing entries. |
| 243 | const ( |
| 244 | DefaultPageSize = 20 |
| 245 | MaxPageSize = 100 |
| 246 | ) |
| 247 | |
| 248 | // EntryPage is one page of a wallet's entries, newest first. NextCursor |
| 249 | // fetches the page after it, and is empty on the last page. |
| 250 | type EntryPage struct { |
| 251 | Entries []Entry |
| 252 | NextCursor string |
| 253 | } |
| 254 | |
| 255 | // Entries returns a page of a wallet's entries. An empty cursor starts at the |
| 256 | // newest entry. |
| 257 | func (s *Service) Entries(ctx context.Context, walletID uuid.UUID, cursor string, limit int) (EntryPage, error) { |
| 258 | var v apperr.ValidationError |
| 259 | if limit < 1 || limit > MaxPageSize { |
| 260 | v.Add("limit", fmt.Sprintf("must be between 1 and %d", MaxPageSize)) |
| 261 | } |
| 262 | before, err := decodeCursor(cursor) |
| 263 | if err != nil { |
| 264 | v.Add("cursor", "invalid cursor") |
| 265 | } |
| 266 | if err := v.Err(); err != nil { |
| 267 | return EntryPage{}, err |
| 268 | } |
| 269 | if _, err := s.Wallet(ctx, walletID); err != nil { |
| 270 | return EntryPage{}, err |
| 271 | } |
| 272 | |
| 273 | // Fetch one entry more than the page holds. If it comes back, there's |
| 274 | // another page, and we know without counting anything. |
| 275 | entries, err := s.store.Entries(ctx, walletID, before, int32(limit+1)) |
| 276 | if err != nil { |
| 277 | return EntryPage{}, err |
| 278 | } |
| 279 | page := EntryPage{Entries: entries} |
| 280 | if len(entries) > limit { |
| 281 | page.Entries = entries[:limit] |
| 282 | page.NextCursor = encodeCursor(entries[limit-1].ID) |
| 283 | } |
| 284 | return page, nil |
| 285 | } |
| 286 | |
| 287 | // A cursor is the ID of the last entry on the previous page, encoded so it's |
| 288 | // opaque: clients pass it back but never build one, so we can change what's |
| 289 | // inside without breaking them. |
| 290 | func encodeCursor(id int64) string { |
| 291 | return base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(id, 10))) |
| 292 | } |
| 293 | |
| 294 | func decodeCursor(cursor string) (int64, error) { |
| 295 | if cursor == "" { |
| 296 | return 0, nil // the first page |
| 297 | } |
| 298 | b, err := base64.RawURLEncoding.DecodeString(cursor) |
| 299 | if err != nil { |
| 300 | return 0, err |
| 301 | } |
| 302 | id, err := strconv.ParseInt(string(b), 10, 64) |
| 303 | // Only the one cursor we'd write for an ID: base64 has more than one |
| 304 | // spelling for the same bytes, and ParseInt takes a +, or leading zeros. |
| 305 | if err != nil || id <= 0 || encodeCursor(id) != cursor { |
| 306 | return 0, errors.New("invalid cursor") |
| 307 | } |
| 308 | return id, nil |
| 309 | } |