feat(payments): add the payments schema, currency domain and money type
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 20s
CI / ui (pull_request) Has been skipped
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m45s

Stand up the payments data foundation: a self-contained `payments` Postgres
schema for the in-game currency, wallets, benefits, catalog, orders and the
append-only operations ledger, behind a domain package — nothing wired to real
money yet.

- Migration 00010: the `payments` schema and a NOLOGIN confinement role (ALL on
  payments.*, nothing on backend); the ledger with a BEFORE UPDATE/DELETE
  append-only trigger and a partial idempotency index; the materialised
  balances/benefits; the catalog (atoms seeded) + products + per-method prices;
  the typed single-row config; orders and payment_events. There is no
  cross-schema foreign key — account_id is a plain uuid kept consistent in code,
  which keeps the domain extractable. Expand-contract and reversible.
- Money is a bigint in the currency's minor units carried by a `Money` value
  type (exact, math/big): no float ever touches an amount, and a whole-unit
  currency cannot hold a fraction.
- Extend jetgen to generate the payments schema; construct the service in the
  composition root behind a narrow interface with a boot reachability check.
- Tests: integration (role confinement via SET ROLE, the append-only trigger,
  CHECK constraints, the idempotency index, and a forward+backward migration),
  Money unit tests, and an import-boundary test keeping the payments jet code
  private to the domain.
- Docs: PLAN.md, docs/PAYMENTS.md (+ _ru mirror) updated to the built model.
This commit is contained in:
Ilia Denisov
2026-07-08 01:07:56 +02:00
parent d9bc7596c6
commit ce8b5026c1
34 changed files with 2243 additions and 78 deletions
@@ -0,0 +1,57 @@
package payments
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"runtime"
"strings"
"testing"
)
// TestPaymentsSchemaImportBoundary enforces that only this package reaches the
// payments jet code. The payments schema is isolated behind this domain; the
// application connects to Postgres as a superuser that bypasses the schema
// grants, so the runtime wall that keeps every other package out of payments.*
// is this import boundary, not the DB privileges. If another package imported
// the generated payments tables it could issue SQL against the schema directly,
// breaking the single-writer guarantee and the domain's extractability.
func TestPaymentsSchemaImportBoundary(t *testing.T) {
const jetPkg = "scrabble/backend/internal/postgres/jet/payments"
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot resolve the test file path")
}
// thisFile = .../backend/internal/payments/boundary_test.go
backendRoot := filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", ".."))
allowedPrefix := filepath.Join(backendRoot, "internal", "payments") + string(filepath.Separator)
fset := token.NewFileSet()
walkErr := filepath.WalkDir(backendRoot, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(path, ".go") {
return nil
}
file, perr := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
if perr != nil {
return perr
}
for _, imp := range file.Imports {
p := strings.Trim(imp.Path.Value, `"`)
if p != jetPkg && !strings.HasPrefix(p, jetPkg+"/") {
continue
}
if !strings.HasPrefix(path, allowedPrefix) {
t.Errorf("%s imports %s — only internal/payments may reach the payments jet code", path, p)
}
}
return nil
})
if walkErr != nil {
t.Fatalf("walk backend tree: %v", walkErr)
}
}
+136
View File
@@ -0,0 +1,136 @@
package payments
import "testing"
func TestMoneyFromMinor(t *testing.T) {
m, err := MoneyFromMinor(14950, CurrencyRUB)
if err != nil {
t.Fatalf("MoneyFromMinor: %v", err)
}
if m.Minor() != 14950 || m.Currency() != CurrencyRUB {
t.Fatalf("got minor=%d currency=%s", m.Minor(), m.Currency())
}
if _, err := MoneyFromMinor(1, Currency("EUR")); err == nil {
t.Fatal("expected an error for an unknown currency")
}
}
func TestMoneyFromMajor(t *testing.T) {
cases := []struct {
major int64
cur Currency
minor int64
}{
{149, CurrencyRUB, 14900}, // roubles scale to kopecks
{250, CurrencyStar, 250}, // Stars are whole units
{7, CurrencyVote, 7},
{50, CurrencyChip, 50},
}
for _, c := range cases {
m, err := MoneyFromMajor(c.major, c.cur)
if err != nil {
t.Fatalf("MoneyFromMajor(%d,%s): %v", c.major, c.cur, err)
}
if m.Minor() != c.minor {
t.Errorf("MoneyFromMajor(%d,%s): minor=%d, want %d", c.major, c.cur, m.Minor(), c.minor)
}
}
if _, err := MoneyFromMajor(1<<62, CurrencyRUB); err == nil {
t.Fatal("expected an overflow error")
}
}
func TestParseMoneyExact(t *testing.T) {
cases := []struct {
text string
cur Currency
minor int64
}{
{"149.50", CurrencyRUB, 14950},
{"149", CurrencyRUB, 14900},
{"0.01", CurrencyRUB, 1},
{"0.10", CurrencyRUB, 10}, // 0.1 is inexact as a float; big.Rat keeps it exact
{"-5.00", CurrencyRUB, -500},
{"250", CurrencyStar, 250},
{"7", CurrencyVote, 7},
{"50", CurrencyChip, 50},
}
for _, c := range cases {
m, err := ParseMoney(c.text, c.cur)
if err != nil {
t.Fatalf("ParseMoney(%q,%s): %v", c.text, c.cur, err)
}
if m.Minor() != c.minor {
t.Errorf("ParseMoney(%q,%s): minor=%d, want %d", c.text, c.cur, m.Minor(), c.minor)
}
}
}
func TestParseMoneyRejectsFraction(t *testing.T) {
// A whole-unit currency (Vote/Star/chip) must never accept a fraction, and
// the rouble must never accept finer than a kopeck — the no-float gate.
bad := []struct {
text string
cur Currency
}{
{"250.5", CurrencyStar},
{"1.5", CurrencyChip},
{"7.01", CurrencyVote},
{"1.999", CurrencyRUB},
{"0.001", CurrencyRUB},
{"abc", CurrencyRUB},
{"12.34", Currency("EUR")}, // unknown currency
}
for _, c := range bad {
if m, err := ParseMoney(c.text, c.cur); err == nil {
t.Errorf("ParseMoney(%q,%s) = %d, want an error", c.text, c.cur, m.Minor())
}
}
}
func TestMoneyAddCmp(t *testing.T) {
a, _ := MoneyFromMinor(14900, CurrencyRUB)
b, _ := MoneyFromMinor(50, CurrencyRUB)
sum, err := a.Add(b)
if err != nil || sum.Minor() != 14950 {
t.Fatalf("Add: minor=%d err=%v", sum.Minor(), err)
}
if c, err := a.Cmp(b); err != nil || c != 1 {
t.Fatalf("Cmp a>b: got %d err=%v", c, err)
}
if c, err := b.Cmp(a); err != nil || c != -1 {
t.Fatalf("Cmp b<a: got %d err=%v", c, err)
}
if c, err := a.Cmp(a); err != nil || c != 0 {
t.Fatalf("Cmp a==a: got %d err=%v", c, err)
}
// Cross-currency arithmetic is refused, not silently coerced.
star, _ := MoneyFromMinor(1, CurrencyStar)
if _, err := a.Add(star); err == nil {
t.Error("Add across currencies: expected an error")
}
if _, err := a.Cmp(star); err == nil {
t.Error("Cmp across currencies: expected an error")
}
}
func TestMoneyString(t *testing.T) {
cases := []struct {
minor int64
cur Currency
want string
}{
{14900, CurrencyRUB, "149.00 RUB"},
{14950, CurrencyRUB, "149.50 RUB"},
{1, CurrencyRUB, "0.01 RUB"},
{-500, CurrencyRUB, "-5.00 RUB"},
{250, CurrencyStar, "250 XTR"},
{5, CurrencyChip, "5 CHIP"},
}
for _, c := range cases {
m, _ := MoneyFromMinor(c.minor, c.cur)
if got := m.String(); got != c.want {
t.Errorf("Money{%d,%s}.String() = %q, want %q", c.minor, c.cur, got, c.want)
}
}
}
+171
View File
@@ -0,0 +1,171 @@
// Package payments is the in-game currency, wallet, benefit and catalog domain.
//
// It owns its own Postgres schema (payments) and is the only backend package
// that issues SQL against it — an import-boundary test forbids any other package
// from importing the payments jet code, which keeps the domain extractable into
// its own database or process later. There is no cross-schema foreign key to the
// account schema: an account id is a plain uuid here, kept referentially honest
// in code.
//
// Money is carried exclusively by [Money] — an exact integer amount in a
// currency's minor units — so no floating-point value ever reaches a monetary
// amount, and a whole-unit currency (Vote, Star, chip) can never hold a
// fraction. This file is the data-foundation layer: the currency value type; the
// wallet mechanics build on the schema and this package later.
package payments
import (
"fmt"
"math/big"
)
// Currency identifies the unit a monetary amount is denominated in.
type Currency string
const (
// CurrencyRUB is the Russian rouble; its minor unit is the kopeck (1/100).
CurrencyRUB Currency = "RUB"
// CurrencyVote is the VK Vote — a whole unit with no sub-unit.
CurrencyVote Currency = "VOTE"
// CurrencyStar is the Telegram Star (XTR) — a whole unit with no sub-unit.
CurrencyStar Currency = "XTR"
// CurrencyChip is the in-game chip, the unit a value's price is quoted in —
// a whole unit with no sub-unit.
CurrencyChip Currency = "CHIP"
)
// minorPerUnit reports how many minor units make one major unit of the currency.
// Every currency except the rouble is a whole-unit currency (scale 1), so an
// amount in it structurally cannot carry a fraction.
func (c Currency) minorPerUnit() int64 {
if c == CurrencyRUB {
return 100
}
return 1
}
// Valid reports whether the currency is one of the known units.
func (c Currency) Valid() bool {
switch c {
case CurrencyRUB, CurrencyVote, CurrencyStar, CurrencyChip:
return true
default:
return false
}
}
// Money is an exact monetary amount: a signed integer count of a currency's
// minor units (rouble kopecks; Vote/Star/chip whole units). It is the sole
// carrier of money in the payments domain — construction, arithmetic and
// formatting all go through it, so no float ever reaches an amount and a
// whole-unit currency can never hold a fraction. The zero value has an empty,
// invalid currency; build a value with [MoneyFromMinor], [MoneyFromMajor] or
// [ParseMoney].
type Money struct {
minor int64
currency Currency
}
// MoneyFromMinor builds a Money from a raw count of the currency's minor units
// (kopecks for the rouble, whole units otherwise). It errors on an unknown
// currency.
func MoneyFromMinor(minor int64, c Currency) (Money, error) {
if !c.Valid() {
return Money{}, fmt.Errorf("payments: unknown currency %q", c)
}
return Money{minor: minor, currency: c}, nil
}
// MoneyFromMajor builds a Money from a whole number of major units (roubles,
// Votes, Stars, chips). It errors on an unknown currency or on overflow.
func MoneyFromMajor(major int64, c Currency) (Money, error) {
if !c.Valid() {
return Money{}, fmt.Errorf("payments: unknown currency %q", c)
}
scaled := new(big.Int).Mul(big.NewInt(major), big.NewInt(c.minorPerUnit()))
if !scaled.IsInt64() {
return Money{}, fmt.Errorf("payments: %d %s overflows", major, c)
}
return Money{minor: scaled.Int64(), currency: c}, nil
}
// ParseMoney parses a decimal amount (e.g. "149.50", "250") in the currency,
// exactly and without floating point (via math/big). It rejects a value with
// finer precision than the currency allows — in particular, any fractional part
// for a whole-unit currency — which is the gate that keeps a fraction out of an
// integer currency.
func ParseMoney(text string, c Currency) (Money, error) {
if !c.Valid() {
return Money{}, fmt.Errorf("payments: unknown currency %q", c)
}
r, ok := new(big.Rat).SetString(text)
if !ok {
return Money{}, fmt.Errorf("payments: %q is not a valid amount", text)
}
scaled := new(big.Rat).Mul(r, new(big.Rat).SetInt64(c.minorPerUnit()))
if !scaled.IsInt() {
return Money{}, fmt.Errorf("payments: %q has finer precision than %s allows", text, c)
}
num := scaled.Num() // the denominator is 1 once scaled to an integer
if !num.IsInt64() {
return Money{}, fmt.Errorf("payments: %q overflows %s", text, c)
}
return Money{minor: num.Int64(), currency: c}, nil
}
// Minor returns the amount as a count of the currency's minor units — the value
// persisted to an amount column.
func (m Money) Minor() int64 { return m.minor }
// Currency returns the amount's currency.
func (m Money) Currency() Currency { return m.currency }
// IsZero reports whether the amount is zero.
func (m Money) IsZero() bool { return m.minor == 0 }
// Add returns the sum of the two amounts. It errors when the currencies differ.
func (m Money) Add(o Money) (Money, error) {
if m.currency != o.currency {
return Money{}, fmt.Errorf("payments: cannot add %s to %s", o.currency, m.currency)
}
return Money{minor: m.minor + o.minor, currency: m.currency}, nil
}
// Cmp compares the two amounts, returning -1, 0 or +1. It errors when the
// currencies differ.
func (m Money) Cmp(o Money) (int, error) {
if m.currency != o.currency {
return 0, fmt.Errorf("payments: cannot compare %s to %s", o.currency, m.currency)
}
switch {
case m.minor < o.minor:
return -1, nil
case m.minor > o.minor:
return 1, nil
default:
return 0, nil
}
}
// String renders the amount as "<value> <currency>", with the currency's
// fractional digits and no floating point (e.g. "149.50 RUB", "250 XTR").
func (m Money) String() string {
scale := m.currency.minorPerUnit()
if scale == 1 {
return fmt.Sprintf("%d %s", m.minor, m.currency)
}
neg := m.minor < 0
abs := m.minor
if neg {
abs = -abs
}
width := 0
for s := scale; s > 1; s /= 10 {
width++
}
sign := ""
if neg {
sign = "-"
}
return fmt.Sprintf("%s%d.%0*d %s", sign, abs/scale, width, abs%scale, m.currency)
}
+17
View File
@@ -0,0 +1,17 @@
package payments
import "context"
// Service is the payments domain's application layer — the narrow surface other
// domains depend on, keeping the schema reachable through one seam. The
// data-foundation layer exposes only a health check; the wallet, benefit and
// store-compliance operations arrive with the currency mechanics.
type Service struct {
store *Store
}
// NewService constructs a Service over store.
func NewService(store *Store) *Service { return &Service{store: store} }
// Ping reports whether the payments schema is reachable.
func (s *Service) Ping(ctx context.Context) error { return s.store.Ping(ctx) }
+37
View File
@@ -0,0 +1,37 @@
package payments
import (
"context"
"database/sql"
"fmt"
"github.com/go-jet/jet/v2/postgres"
"scrabble/backend/internal/postgres/jet/payments/model"
"scrabble/backend/internal/postgres/jet/payments/table"
)
// Store is the Postgres-backed query surface for the payments schema. It is the
// only place in the backend that issues SQL against payments.* (an
// import-boundary test enforces it), so the domain stays extractable into its
// own database.
type Store struct {
db *sql.DB
}
// NewStore constructs a Store wrapping db.
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
// Ping verifies the payments schema is reachable by reading the singleton config
// row. It is the data-foundation health check; the wallet query surface arrives
// with the currency mechanics.
func (s *Store) Ping(ctx context.Context) error {
var row model.Config
if err := postgres.SELECT(table.Config.AllColumns).
FROM(table.Config).
LIMIT(1).
QueryContext(ctx, s.db, &row); err != nil {
return fmt.Errorf("payments: ping: %w", err)
}
return nil
}