Compare commits

...

46 Commits

Author SHA1 Message Date
developer 68c937f3b6 Merge pull request 'feat(payments): refund engine (best-effort revoke, never negative)' (#227) from feature/payment-intake-refunds into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 11s
CI / integration (push) Successful in 21s
CI / ui (push) Has been skipped
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m54s
2026-07-09 21:26:33 +00:00
Ilia Denisov 21fb14facf feat(payments): refund engine (best-effort revoke, never negative)
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 18s
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
The last money-intake slice: reverse a paid order best-effort, exactly once. All
refunds are admin-triggered (E7) — no rail pushes an unsolicited refund (Robokassa
via its refund API / cabinet, VK via support, Telegram via refundStarPayment), so
this ships the engine they all converge on, not a webhook.

The Refund method matches the paid order, appends a refund ledger row (idempotent on
(provider, provider_refund_id) — distinct from the fund's payment id, so both
coexist), and revokes the funded chips floored at 0 (never negative — D27,
balances_chips_chk). When the chips were already spent, the unrecoverable remainder
is recorded as a per-account loss + abuse flag in the new additive
payments.account_risk table (read by the E7 report). The refund ledger row's chip
delta is what was actually reclaimed (the ledger stays reconcilable); the full
reversal rides in the snapshot; the order stays paid.

Additive migration (a new table only) -> rollback-safe, no contour wipe. Robokassa
refund-status polling is deferred (a worker not worth it at low chargeback volume);
failed events are not wired (no rail signals a hard post-charge server decline).

Tests: integration (full revoke; revoke-after-spend = floor-0 + loss + abuse;
duplicate idempotent; unpaid-order guard). Docs: PAYMENTS(+ru) §9, PLAN (E5 -> DONE).
2026-07-09 23:21:10 +02:00
developer ee9924c313 Merge pull request 'feat(payments): Telegram Stars payment rail' (#226) from feature/payment-intake-tg-stars into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 11s
CI / integration (push) Successful in 23s
CI / ui (push) Successful in 1m10s
CI / conformance (push) Successful in 9s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m53s
2026-07-09 20:44:06 +00:00
Ilia Denisov e10f3beed5 chore(ui): raise the app bundle budget 123->125 for the payment intake rails
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 24s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 11s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m50s
The wallet order flow plus the Telegram Stars openInvoice / VK order-box launch
and the per-button in-flight state ride the always-loaded Wallet screen, which
crossed the 123 KB gzip ceiling. Bump to 125 (matching the established
feature-driven budget history in the comment) with ~2 KB of headroom.
2026-07-09 22:37:30 +02:00
Ilia Denisov 55dbb1005e fix(ui): scope the wallet buy-button busy dim to the tapped button
CI / changes (pull_request) Successful in 1s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Failing after 11s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Failing after 0s
CI / deploy (pull_request) Has been skipped
Tapping one pack's Buy dimmed every buy button at once (the shared busy
flag drove disabled + the :disabled opacity on all of them), so it looked
like both packs reacted to one tap. Track the in-flight product id
(busyId): the concurrency guard stays global, but the pressed/dimmed look
is now scoped to the tapped button. Payments were never affected.
2026-07-09 22:26:28 +02:00
Ilia Denisov 219fc7c827 chore(deploy): re-roll the test contour to pick up the TEST_AWG_CONF DNS fix
CI / changes (pull_request) Successful in 1s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m55s
The contour VPN sidecar's netns resolv.conf was pinned to 1.1.1.1 by a DNS=
directive in TEST_AWG_CONF, so internal names (gateway, otelcol) did not resolve
and the bot-link had been down since ~2026-06-29. The directive is removed; this
empty commit re-rolls the contour so the vpn recreates with Docker's 127.0.0.11
resolver and the bot-link (and the Stars rail over it) comes up.
2026-07-09 21:55:53 +02:00
Ilia Denisov 6e03ce0131 feat(payments): Telegram Stars payment rail
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 22s
CI / integration (pull_request) Successful in 20s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m57s
Accept real money via Telegram Stars (XTR) — the third intake rail
alongside Robokassa (direct) and VK Votes.

Only the bot reaches Telegram, so the rail funnels through the reverse
mTLS bot-link:
- the gateway mints the invoice on a CreateInvoice command (the bot
  calls createInvoiceLink, XTR; the link goes to WebApp.openInvoice);
- the bot gates each pre_checkout_query via a ValidatePreCheckout unary
  (the order must exist, be still creditable and not already paid — the
  reusable-invoice double-pay guard; the decline reason is localised to
  the order account's language);
- a completed successful_payment is queued in a durable pure-Go SQLite
  outbox and forwarded via a ForwardPayment unary, credited once
  (idempotent on telegram_payment_charge_id, honours an expired order),
  re-driven on restart and every 30s.

The rail is wired by TELEGRAM_STARS_OUTBOX_DIR (default /data) but stays
inert until a chip pack carries an XTR price, so seeding a Stars price in
the admin is the go-live.

Tests: backend integration (order->forward->credit once, duplicate,
pre_checkout gate) + bot outbox unit (idempotent, restart re-drive) +
executor createInvoice. Docs: PAYMENTS(+ru) §9, ARCHITECTURE, the
platform/telegram README, PLAN.
2026-07-09 21:35:29 +02:00
developer 5612bb624d Merge pull request 'fix(ui): VK-iOS store link from the deployment origin' (#225) from fix/vk-ios-link-origin into development
CI / changes (push) Successful in 2s
CI / unit (push) Has been skipped
CI / integration (push) Has been skipped
CI / ui (push) Successful in 1m9s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m47s
2026-07-09 18:30:54 +00:00
Ilia Denisov 8230253142 fix(ui): derive the VK-iOS store link from the deployment origin
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Has been skipped
CI / integration (pull_request) Has been skipped
CI / ui (pull_request) Successful in 1m8s
CI / conformance (pull_request) Successful in 11s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m57s
Replace the hardcoded erudit-game.ru host with location.origin, so the iOS
store note's "other version" link points at this deployment's own site root
(prod or the contour) without a hardcoded host or build-arg wiring.
2026-07-09 20:26:25 +02:00
developer 890a887257 Merge pull request 'feat(payments): VK Votes payment rail' (#224) from feature/payment-intake-vk into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 20s
CI / ui (push) Successful in 1m9s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m56s
2026-07-09 18:23:24 +00:00
Ilia Denisov e33b9864c8 fix(ui): point the VK-iOS "other version" link at the site root
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 1m23s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m55s
The landing at / lists every version's entry; /app/ dropped the player straight
into the web game. Link the iOS store note to the root instead.
2026-07-09 20:18:42 +02:00
Ilia Denisov f6aa0ba4b0 fix(ui): correct the VK-iOS purchase block + add an iOS store note
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 21s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m59s
The VK-iOS detection used platformSubtype(), which is server-derived for VK and
so never reported iOS on the client — the pack CTA stayed active and a tap hit a
403 with a generic error. Read the device family from the signed vk_platform
launch param (normalizeSubtype(vkPlatform())) instead. Under the store header on
VK-iOS, add a note that purchases are prohibited by Apple policy, linking to the
web version (opened through VK's external-link route).
2026-07-09 20:11:35 +02:00
Ilia Denisov f48ebf2151 fix(ui): VK-iOS shows the pack CTA disabled with a toast, not a failed buy
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 22s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m55s
Money purchases are not permitted in the VK iOS app (Apple ToS), and the backend
already refuses them (the CreateOrder VK-iOS freeze). Show the pack "Buy" muted
there and explain on tap ("purchases are not available on this platform"),
instead of letting the tap hit a 403 and a generic error toast. The storefront
still lists the packs.
2026-07-09 19:57:10 +02:00
Ilia Denisov 3bb9f10fad feat(payments): VK Votes payment rail
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m45s
Wire the VK Mini Apps ("голоса") rail end to end, reusing the intake engine. The
wallet.order endpoint branches by rail: a VK context opens a pending order
(provider vk) and returns its id, which the client passes to VKWebAppShowOrderBox.
VK's two-phase payment callback is verified at the gateway with the app protected
key (GATEWAY_VK_APP_SECRET) and proxied to a backend intake handler: get_item
returns the ordered pack's title and vote price; a chargeable order_status_change
credits the vk segment exactly once (the same Fund, idempotent on VK's own order
id) and records a succeeded event, so the dispatcher push refreshes the wallet.
Integration test for the VK order->credit path.
2026-07-09 19:27:57 +02:00
Ilia Denisov 3e0763463f feat(gateway): VK payment callback signature verifier
Add the vkpay package: verify a VK Mini Apps payment ("голоса") callback
signature — MD5 (mandated by VK's payment protocol) of the sig-excluded
parameters, sorted by name and concatenated key=value, with the app secret
appended; case-insensitive over the hex digest. Unit-tested (valid / tampered /
wrong-secret / missing). First piece of the VK rail; the two-phase callback
handler, the VK order branch and the client bridge follow.
2026-07-09 18:56:00 +02:00
developer 96adf98e1d Merge pull request 'feat(payments): Robokassa direct-rail payment intake' (#223) from feature/payment-intake-robokassa into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 11s
CI / integration (push) Successful in 19s
CI / ui (push) Successful in 1m8s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m50s
2026-07-09 16:33:12 +00:00
Ilia Denisov 3367cc2bf1 feat(payments): payment-event dispatcher + the provider-return UX
CI / changes (pull_request) Successful in 3s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 22s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m45s
Deliver payment_events to connected clients as an in-app wallet-refresh push: a
background dispatcher drains undispatched events and publishes a KindNotification
"payment" signal, marking each delivered; the client bumps a wallet-refresh
counter the open Wallet screen watches, re-fetching in place. A return-focus
refetch is the fallback. The Robokassa Success/Fail return now serves a
self-closing page (the payment opens in a separate window) so the customer drops
back into the live app instead of a cold start. Integration test for the event
drain/mark queue.
2026-07-09 18:26:06 +02:00
Ilia Denisov 04435a3283 docs(payments): bake the E5 direct-rail decisions + a /pay/ CI probe
CI / changes (pull_request) Successful in 3s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 25s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 2m40s
Record the E5 delivery and resolved decisions in PLAN.md (Shp_order matching,
order-id idempotency, cabinet-side receipt, never-negative → schema-free) and
mark the stage WIP. Add a CI probe asserting /pay/robokassa/result reaches the
gateway rather than the landing catch-all.
2026-07-09 17:48:29 +02:00
Ilia Denisov be0e4995f3 feat(deploy): wire the Robokassa direct rail into the contour
Map the Robokassa merchant login + Password1/Password2 into the backend
container env from the deploy secrets (TEST_BACKEND_ROBOKASSA_*), and force
IsTest on the test contour so it can never take real money. An empty login
leaves the direct order + callback endpoints unregistered.
2026-07-09 17:45:54 +02:00
Ilia Denisov 936a70ab94 feat(ui): wire the chip-pack purchase to Robokassa
Replace the disabled "Soon" pack action with a real purchase: the Wallet opens a
money order (wallet.order) and sends the player to the provider's hosted-payment
page (window.open via openExternalUrl); the chips are credited later by the
verified server callback. Add a public-offer link under the packs (paying
accepts the offer). Codec order round-trip unit test + a mock-e2e purchase test;
the Google Play stub and the chip-spend paths are unchanged.
2026-07-09 17:43:02 +02:00
Ilia Denisov 4f6c22d669 feat(gateway): the Robokassa /pay/ edge routes
Add the public /pay/robokassa/result callback proxy (rate-limited; forwards the
provider's form parameters to the backend intake, the single writer, and echoes
its "OK<InvId>" back to Robokassa) and the /pay/robokassa/{success,fail}
browser-return redirects into the app. Route /pay/* to the gateway in the
contour Caddyfile so the callback reaches the edge, not the landing catch-all.
The backend intake now returns the echo body as JSON for the gateway to relay.
2026-07-09 17:33:22 +02:00
Ilia Denisov 2a6dc5a304 feat(gateway): wire the wallet.order edge call for the direct rail
Add the WalletOrderRequest / WalletOrderResponse FlatBuffers messages and the
wallet.order Connect op: the gateway decodes the order request, forwards it to
the backend POST /wallet/order and returns the created order id plus the
provider launch URL the client opens. Regenerate the committed Go and TS
FlatBuffers code.
2026-07-09 17:30:39 +02:00
Ilia Denisov a66a5bfa08 test(payments): integration coverage for the intake credit path
Cover the order→callback→credit path over Postgres: a funded order credits its
segment exactly once; a replayed callback for the same order credits nothing
(the ledger idempotency index holds); a mismatched paid amount is refused with
no write; an expired pending order is still honoured by a late valid callback.
2026-07-09 17:04:14 +02:00
Ilia Denisov 36a5730e52 feat(payments): direct-rail order + intake handlers, config and reaper
Wire the Robokassa direct rail into the backend transport. POST
/api/v1/user/wallet/order (walletGate + a D36 confirmed-email gate for the
direct rail) opens a pending order and returns the signed Robokassa payment
URL. The internal, gateway-only /payments/robokassa/result endpoint verifies
the Result signature, credits the matched order exactly once via Fund (honoured
even if expired), records a succeeded payment event, and answers Robokassa's
"OK<InvId>". Add the Robokassa env config, an account HasConfirmedEmail check
(D36), the payment_events writer, and a periodic pending-order reaper. The
routes register only when a Robokassa merchant login is configured.
2026-07-09 16:59:34 +02:00
Ilia Denisov 7860efce48 feat(payments): order-flow and fund credit engine + the Robokassa adapter
Add the payment-intake write path (provider-agnostic) and the Robokassa
direct-rail glue, both unit-tested; transport, wire and UI follow.

- payments: extend the ledger insert to thread order_id/provider/
  provider_payment_id (spend/grant pass nil); add the order store
  (create/read/expire + a pack-price loader) and the fund credit — a
  fund ledger row + a guarded balance upsert + mark-paid in one tx,
  idempotent on the (provider, provider_payment_id) unique index, cache
  invalidated after commit. A valid callback is honoured even on an
  expired order. Service CreateOrder/Fund/ExpireOrders; Money.Major for
  the provider amount field.
- robokassa: build the signed hosted-payment URL (SHA-256, order id via
  Shp_order, InvId unused) and verify the Result callback signature
  (Password2), extracting the order and amount. Receipt/fiscalisation is
  configured shop-side, so no Receipt parameter is sent.
2026-07-09 16:48:48 +02:00
developer ca60025fbe Merge pull request 'feat(ui): public offer page at /offer/ with a landing footer link' (#222) from feature/public-offer-page into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 11s
CI / integration (push) Successful in 18s
CI / ui (push) Successful in 1m9s
CI / conformance (push) Successful in 9s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m38s
2026-07-09 14:12:28 +00:00
Ilia Denisov 0bdc034f7a chore: offer formatting
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 1m8s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s
2026-07-09 16:04:56 +02:00
Ilia Denisov 625fc3135a feat(ui): serve the public offer at /offer/ with a landing footer link
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s
The offer is the legal document a purchase accepts, needed before real-money
intake goes live. Convert the source PDF to an editable ui/legal/offer_ru.md and
render it to a standalone static dist/offer/index.html at build (a vite
emit-offer plugin using marked); the landing container serves it at /offer/,
with a bare /offer redirecting in. Add a small centered "Публичная оферта"
footer link on the landing (ru/en) and a CI probe asserting /offer/ serves the
page rather than silently falling through to the landing shell.
2026-07-09 16:03:50 +02:00
developer a118c63411 Merge pull request 'fix(deploy): run the base-backup timer's pgBackRest as the postgres role' (#221) from feature/pitr-timer-fix into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 11s
CI / integration (push) Successful in 19s
CI / ui (push) Successful in 1m8s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m41s
2026-07-09 00:07:52 +00:00
Ilia Denisov 7123ba439d fix(deploy): run the base-backup timer's pgBackRest as the postgres role
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m46s
docker exec defaults to root, so the systemd base-backup timer connected to the
database as role "root" (then "postgres") — neither exists; the superuser role is
POSTGRES_USER (scrabble). Run the timer's pgBackRest as the postgres OS user (-u postgres,
for lock-dir/PGDATA consistency with archive-push) and connect with --pg1-user=scrabble.
archive_command (run by the postgres server process) was already correct.

Also record the point-in-time-recovery arming + restore drill in deploy/README.md
(correct the runbook commands to the same invocation, fill the drill log) and mark the
durability work done in PLAN.md.
2026-07-09 02:03:59 +02:00
developer 850884d077 Merge pull request 'feat(deploy): continuous WAL archiving to S3 for point-in-time recovery' (#219) from feature/postgres-pitr-archiving into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 21s
CI / ui (push) Successful in 1m9s
CI / conformance (push) Successful in 10s
CI / changes (pull_request) Successful in 1s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m42s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m8s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Has been skipped
2026-07-08 23:35:07 +00:00
Ilia Denisov a58f2ce0e4 fix(deploy): support a non-standard S3 port for the pgBackRest endpoint
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 1m8s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 1s
CI / deploy (pull_request) Successful in 1m43s
The S3 endpoint is a host only; some providers publish a separate, non-443
port. Add an optional PGBACKREST_S3_PORT (default 443) alongside the endpoint
host, wired through the prod overlay, write-prod-env.sh and both prod workflows,
and clarify in the docs that the endpoint variable takes the host alone.
2026-07-09 01:14:05 +02:00
Ilia Denisov e922f5f3b9 feat(deploy): continuous WAL archiving to S3 for point-in-time recovery
CI / changes (pull_request) Successful in 4s
CI / unit (pull_request) Successful in 12s
CI / integration (pull_request) Successful in 24s
CI / ui (pull_request) Successful in 1m9s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s
Add pgBackRest-based PITR for the production database, shipped disarmed
(archive_mode and the base-backup timer gated off) so it stays inert until the
operator arms it before real payments — an un-armed deploy cannot pile WAL onto
the disk.

- Postgres now builds from a thin image carrying pgBackRest (archive_command runs
  in-process); the prod overlay wires an encrypted (AES-256-CBC), path-style S3
  repository with 30-day retention and a daily full base-backup systemd timer.
- Repository config/secrets flow through the PROD_PGBACKREST_* Gitea set and
  write-prod-env.sh; prod-rollback re-renders the same env so a rollback cannot
  disarm archiving.
- Grafana alerts watch pg_stat_archiver (failing / stalled), absent-safe on the
  test contour, which never archives.
- Fix the pre-migration pg_dump to snapshot the whole database (was backend-only,
  silently excluding payments).
- Document the PITR runbook, the arming sequence and the restore drill in
  deploy/README.md; record the measured cost/perf assessment.
2026-07-09 00:58:04 +02:00
developer 04976a64e8 Merge pull request 'feat(payments): wallet screen with balances, benefits and storefront' (#218) from feature/payments-wallet-ui into development
CI / changes (push) Successful in 3s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 19s
CI / ui (push) Successful in 1m8s
CI / conformance (push) Successful in 9s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m40s
2026-07-08 16:44:06 +00:00
Ilia Denisov 4aa6174968 feat(payments): wallet screen with balances, benefits and storefront
CI / changes (pull_request) Successful in 3s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 19s
CI / ui (pull_request) Successful in 1m8s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m39s
Add the "Кошелёк" section to the settings hub: context-visible chip
balances, active benefits (no-ads term/forever, hints) and a storefront of
chip-priced values and money-priced chip packs. Guests have no wallet; the
Google Play build hides the money purchases behind a RuStore stub; a web
purchase that would draw VK/Telegram chips warns first.

Add the catalog read path the storefront needs — a context-projected
GET /api/v1/user/wallet/catalog (payments service + store, gateway op
wallet.catalog, FBS Catalog/CatalogProduct/CatalogAtom, client decode) —
plus the client leg for the existing wallet.get/buy ops. Value spends reuse
the existing spend path; the chip-pack purchase (money order flow) arrives
with payment intake, so its action is a disabled placeholder for now.

Covered by Go unit (catalog projection) + integration (/wallet/catalog over
Postgres), vitest (formatting, spendable selection, web-spend warning, GP
flag, codec + gateway encode round-trips) and Playwright mock e2e (render,
guest-hidden, GP stub, warning) on Chromium + WebKit.
2026-07-08 12:37:32 +02:00
developer 41f4fd3497 Merge pull request 'feat(payments): chip wallet, store-compliance gate and benefit application' (#217) from feature/payments-currency-benefit-core into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 21s
CI / ui (push) Successful in 1m7s
CI / conformance (push) Successful in 9s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m45s
2026-07-08 05:53:24 +00:00
Ilia Denisov 1c06d1d0d1 feat(payments): chip wallet, store-compliance gate and benefit application
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 22s
CI / ui (pull_request) Successful in 1m7s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s
Stand up the internal chip/benefit mechanic behind the narrow payments interface:
context-aware balances and benefits, an atomic chip spend, admin grants as
zero-price value sales, the one-directional store-compliance gate (VK/TG same-
origin only, web draws direct→vk→tg, VK-iOS frozen, untrusted fail-closed), and
per-origin hint and no-ads application with term stacking. Reads are served from
an in-process, account-keyed write-through cache (mirroring the suspension gate),
so hot paths issue no query to the payments schema.

Flip the online-game hint wallet and the ad-banner suppression from the deprecated
accounts.hint_balance / paid_account columns to the payments benefit (a hint
balance no longer suppresses the banner — only a no-ads benefit does), and fold
chip segments and benefits by origin on account merge, inside the merge tx. Add
the GET/POST /api/v1/user/wallet edge chain (REST → Connect → FlatBuffers) plus
its codec unit test; no wallet UI yet.

Bring the frozen owner decisions log into the repo at
docs/PAYMENTS_DECISIONS_ru.md (it was untracked under .vscode) and reference it
from PLAN.md; record the read-cache design and the present-sources interface in
PLAN.md and docs/PAYMENTS.md (+ RU mirror).
2026-07-08 06:06:40 +02:00
developer 711fabe9cc Merge pull request 'feat(payments): trusted platform signal on the session' (#216) from feature/trusted-platform-signal into development
CI / changes (push) Successful in 1s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 21s
CI / ui (push) Successful in 1m7s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m44s
2026-07-08 01:37:39 +00:00
Ilia Denisov 92633f935e feat(payments): trusted platform signal on the session
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m7s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m42s
Record the execution platform (kind vk|telegram|direct + device subtype
ios|android|web) on each session, captured at creation and carried
gateway->backend as a trusted X-Platform header, so the upcoming
store-compliance gate has an unforgeable execution context.

- backend.sessions gains nullable platform_kind/platform_subtype columns
  (migration 00011, CHECK-constrained, jet regenerated); session.Platform
  captures them at mint, resolve returns them, middleware exposes platform(c).
  kind is derived from the establish endpoint, never a client field; the
  account-merge session mint inherits the caller's platform.
- gateway derives the platform (VK subtype from the signed vk_platform via
  vkauth, Telegram/direct best-effort from the client) and injects X-Platform
  on every authenticated backend call through the request context.
- ui submits a best-effort device subtype on the telegram/guest/email login
  requests (new FBS subtype field); VK is server-derived from the signed params.
- an unattributed session is untrusted (view-only); VK/TG self-heal on the next
  cold-start re-mint, direct/email on re-login.

Signal plumbing only, no user-visible change; X-Platform is inert until the
gate consumes it.
2026-07-08 03:31:51 +02:00
developer 07815c5a30 Merge pull request 'feat(payments): payments schema, currency domain and money type' (#215) from feature/payments-data-foundation into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 18s
CI / ui (push) Has been skipped
CI / conformance (push) Successful in 9s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m44s
2026-07-07 23:21:43 +00:00
Ilia Denisov bab57343e1 chore(jet): regenerate the backend jet to match the migrations
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 19s
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 1m43s
The committed go-jet code had drifted from the schema: robot_blocks and
robot_friend_requests (created in the baseline) had no generated tables, the
feedback_messages model was missing app_version/browser_tz (added in 00003 and
00004), and UseSchema omitted account_best_move and the two robot tables.
Regenerate so the jet layer mirrors the migrations again.

Additive only — two nullable columns appended to feedback_messages plus two new
tables; the full build, vet, unit and integration suites stay green.
2026-07-08 01:18:36 +02:00
Ilia Denisov ce8b5026c1 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.
2026-07-08 01:07:56 +02:00
developer d9bc7596c6 Merge pull request 'docs(payments): monetization spec and implementation plan' (#213) from feature/payments-docs into development
CI / changes (push) Successful in 1s
CI / unit (push) Has been skipped
CI / integration (push) Has been skipped
CI / ui (push) Has been skipped
CI / conformance (push) Has been skipped
CI / gate (push) Successful in 0s
CI / deploy (push) Has been skipped
2026-07-07 21:31:31 +00:00
developer 3ad3b1dd7f Merge pull request 'ci: skip the test-contour deploy on a no-code change' (#214) from feature/ci-skip-deploy-on-docs into development
CI / changes (push) Successful in 1s
CI / unit (push) Successful in 9s
CI / integration (push) Successful in 15s
CI / ui (push) Successful in 1m6s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m39s
2026-07-07 21:27:46 +00:00
Ilia Denisov 4d1f389cf1 ci: skip the test-contour deploy on a no-code change
CI / changes (pull_request) Successful in 1s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 1m6s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m44s
The deploy job gated only on the event/ref, so a docs-only PR into
development (where unit/integration/ui/conformance path-skip) still
redeployed the test contour for nothing. Gate it on the `changes` job
too: deploy only when the Go or UI side changed. `changes` still
defaults both true when the diff is uncomputable, and a workflow/deploy
edit forces both true, so ambiguous or infra changes still deploy.
2026-07-07 23:22:29 +02:00
Ilia Denisov 4c7bc7baa9 docs(payments): add monetization spec and implementation plan
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Has been skipped
CI / integration (pull_request) Has been skipped
CI / ui (pull_request) Has been skipped
CI / conformance (pull_request) Has been skipped
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m45s
Add docs/PAYMENTS.md (+ docs/PAYMENTS_ru.md mirror) — the monetization
mechanics specification: two-tier «Фишка» currency, per-source wallet
segments, per-origin benefits with the one-directional store-compliance
gate, order-flow payment intake, VK ads, configurable catalog,
append-only ledger, taxes, and native-Android distribution.

Add PLAN.md — the staged technical implementation plan with per-step
touch-points, tests, and done-criteria.
2026-07-07 23:11:49 +02:00
200 changed files with 14652 additions and 378 deletions
+46 -3
View File
@@ -316,9 +316,13 @@ jobs:
# Auto test-deploy on a PR into development and on the push that merges it.
# A PR into master is test-only (this job is skipped); prod deploy is manual.
# Gates on `gate` (so a real test failure blocks the deploy) but runs even when
# some test jobs were path-skipped.
needs: [gate]
if: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/development') || (github.event_name == 'pull_request' && github.base_ref == 'development') }}
# some test jobs were path-skipped. Skipped entirely when neither the Go nor the
# UI side changed (e.g. a docs-only change): the contour image is unchanged, so
# there is nothing to redeploy. `changes` still defaults both to true when the
# diff is uncomputable, and a workflow/deploy edit forces both true, so an
# ambiguous or infra change still deploys as a safety net.
needs: [changes, gate]
if: ${{ (needs.changes.outputs.go == 'true' || needs.changes.outputs.ui == 'true') && ((github.event_name == 'push' && github.ref == 'refs/heads/development') || (github.event_name == 'pull_request' && github.base_ref == 'development')) }}
runs-on: ubuntu-latest
defaults:
run:
@@ -362,6 +366,13 @@ jobs:
SMTP_RELAY_HOST: ${{ vars.SMTP_RELAY_HOST }}
SMTP_RELAY_PORT: ${{ vars.SMTP_RELAY_PORT }}
SMTP_RELAY_TLS: ${{ vars.SMTP_RELAY_TLS }}
# Direct-rail (Robokassa) sandbox intake on the contour: the test shop's merchant login +
# Password1/Password2. IsTest is forced to 1 below so the contour can never take real money
# (independent of the shop's own mode). Empty login leaves the direct rail off.
ROBOKASSA_MERCHANT_LOGIN: ${{ secrets.TEST_BACKEND_ROBOKASSA_MERCHANT_LOGIN }}
ROBOKASSA_PASSWORD1: ${{ secrets.TEST_BACKEND_ROBOKASSA_PASSWORD1 }}
ROBOKASSA_PASSWORD2: ${{ secrets.TEST_BACKEND_ROBOKASSA_PASSWORD2 }}
ROBOKASSA_TEST: "1"
SMTP_RELAY_FROM: ${{ vars.TEST_SMTP_RELAY_FROM }}
# Operator alerts: backend admin emails (new feedback / complaints) + Grafana
# infra alerts. Distinct senders + recipients; Grafana uses the relay's STARTTLS
@@ -493,6 +504,38 @@ jobs:
docker logs --tail 50 scrabble-backend || true
exit 1
- name: Probe the /offer/ public offer page is served
run: |
set -u
# /offer/ is a static page baked into the landing image (rendered from
# ui/legal/offer_ru.md). If the landing Caddyfile stops routing it, the request
# silently falls through to the landing shell (also 200) — so assert offer-specific
# content, never just the status.
out="$(docker run --rm --network edge alpine:3.20 wget -q -O - http://scrabble/offer/ 2>&1 || true)"
if echo "$out" | grep -q "290210610742"; then
echo "ok: /offer/ serves the public offer page"
else
echo "FAIL: /offer/ did not serve the offer page (fell through to the landing shell?)"
docker logs --tail 50 scrabble-landing || true
exit 1
fi
- name: Probe the /pay/ callback route reaches the gateway
run: |
set -u
# /pay/robokassa/result must reach the gateway, not fall to the landing catch-all. An
# unsigned probe is rejected downstream, so the gateway answers a 4xx/5xx (never a 200 or
# a 404 landing.html), which proves the edge route is wired.
out="$(docker run --rm --network edge alpine:3.20 wget -S -q -O /dev/null http://scrabble/pay/robokassa/result 2>&1 || true)"
echo "$out" | grep -E "HTTP/" || true
if echo "$out" | grep -qE "HTTP/1\.1 (4|5)[0-9][0-9]"; then
echo "ok: /pay/ reaches the gateway (non-landing response)"
else
echo "FAIL: /pay/robokassa/result did not reach the gateway (landing catch-all?)"
docker logs --tail 50 scrabble-gateway || true
exit 1
fi
- name: Probe the /dict edge route reaches the gateway
run: |
set -u
+13 -1
View File
@@ -77,7 +77,7 @@ jobs:
# The main-stack images via compose (reuses the build args, incl. VERSION);
# the bot separately, since it is profiled out of the prod compose.
docker compose -f docker-compose.yml -f docker-compose.prod.yml build
docker compose -f docker-compose.yml -f docker-compose.prod.yml push backend gateway landing validator renderer
docker compose -f docker-compose.yml -f docker-compose.prod.yml push postgres backend gateway landing validator renderer
docker build -f ../platform/telegram/Dockerfile --target bot --build-arg VERSION="$TAG" -t "$REGISTRY/scrabble-telegram-bot:$TAG" ..
docker push "$REGISTRY/scrabble-telegram-bot:$TAG"
@@ -135,6 +135,18 @@ jobs:
DICT_VERSION: ${{ vars.DICT_VERSION }}
POSTGRES_DB: ${{ vars.PROD_POSTGRES_DB }}
POSTGRES_USER: ${{ vars.PROD_POSTGRES_USER }}
# Point-in-time recovery (pgBackRest -> S3), prod main host only. Endpoint/bucket/
# region + the archive-mode switch are variables; the S3 keys + the repository cipher
# passphrase are secrets. All empty/off until the operator arms archiving; flipping
# PROD_PGBACKREST_ARCHIVE_MODE=on activates it (deploy/README.md, arming).
PGBACKREST_ARCHIVE_MODE: ${{ vars.PROD_PGBACKREST_ARCHIVE_MODE }}
PGBACKREST_S3_ENDPOINT: ${{ vars.PROD_PGBACKREST_S3_ENDPOINT }}
PGBACKREST_S3_PORT: ${{ vars.PROD_PGBACKREST_S3_PORT }}
PGBACKREST_S3_BUCKET: ${{ vars.PROD_PGBACKREST_S3_BUCKET }}
PGBACKREST_S3_REGION: ${{ vars.PROD_PGBACKREST_S3_REGION }}
PGBACKREST_S3_KEY: ${{ secrets.PROD_PGBACKREST_S3_KEY }}
PGBACKREST_S3_KEY_SECRET: ${{ secrets.PROD_PGBACKREST_S3_KEY_SECRET }}
PGBACKREST_CIPHER_PASS: ${{ secrets.PROD_PGBACKREST_CIPHER_PASS }}
# TELEGRAM_MINIAPP_URL and GRAFANA_ROOT_URL are derived from PUBLIC_BASE_URL in
# deploy/write-prod-env.sh, not stored variables.
steps:
+10
View File
@@ -77,6 +77,16 @@ jobs:
SERVICE_EMAIL: ${{ vars.PROD_SERVICE_EMAIL }}
GRAFANA_SMTP_PORT: ${{ vars.GRAFANA_SMTP_PORT }}
GF_SMTP_ENABLED: ${{ vars.PROD_GF_SMTP_ENABLED }}
# PITR archiving parity: a rollback must re-render the SAME env.sh, else it would
# silently disarm WAL archiving (PGBACKREST_ARCHIVE_MODE would fall back to off).
PGBACKREST_ARCHIVE_MODE: ${{ vars.PROD_PGBACKREST_ARCHIVE_MODE }}
PGBACKREST_S3_ENDPOINT: ${{ vars.PROD_PGBACKREST_S3_ENDPOINT }}
PGBACKREST_S3_PORT: ${{ vars.PROD_PGBACKREST_S3_PORT }}
PGBACKREST_S3_BUCKET: ${{ vars.PROD_PGBACKREST_S3_BUCKET }}
PGBACKREST_S3_REGION: ${{ vars.PROD_PGBACKREST_S3_REGION }}
PGBACKREST_S3_KEY: ${{ secrets.PROD_PGBACKREST_S3_KEY }}
PGBACKREST_S3_KEY_SECRET: ${{ secrets.PROD_PGBACKREST_S3_KEY_SECRET }}
PGBACKREST_CIPHER_PASS: ${{ secrets.PROD_PGBACKREST_CIPHER_PASS }}
INPUT_TARGET: ${{ inputs.target_version }}
steps:
- uses: actions/checkout@v4
+761
View File
@@ -0,0 +1,761 @@
# PLAN — monetization implementation
Technical, step-by-step implementation of the monetization domain. Business mechanics and
the rationale for every rule live in [`docs/PAYMENTS.md`](docs/PAYMENTS.md) (RU mirror
[`docs/PAYMENTS_ru.md`](docs/PAYMENTS_ru.md)); the frozen owner agreements they both derive
from (the `D1``D41` decisions log) live in
[`docs/PAYMENTS_DECISIONS_ru.md`](docs/PAYMENTS_DECISIONS_ru.md) — the authority when a rule
is disputed. This file is the *how*. Each stage is written to be self-sufficient: returning
to it gives full context — goal, exact touch-points, tests, done-criteria, and current
status — without re-deriving decisions.
## How to use this file
- **Stage granularity (E0E9) is fixed.** Do not split or merge stages. Plan each stage
densely enough to execute whole.
- **Never leak stage ids into the product.** Code, comments, commit messages, PR
titles/descriptions must read as finalized feature copy — never "E5", "stage 3", etc.
Stage ids exist only in this file.
- **Deviations are allowed** when new unknowns surface, but the plan is then edited **whole
and in agreement** (not piecemeal), keeping it coherent, and `docs/PAYMENTS.md` updated in
step.
- **Status marks:** each stage header carries `Status: TODO | WIP | DONE`. When a stage
lands, flip it to DONE and note the PR. The **Progress** table is the at-a-glance index.
- **Per-change discipline** (repo `CLAUDE.md`): update tests at the layers `docs/TESTING.md`
calls out, bake doc updates into the same PR, run local full verification before pushing,
feature branch → PR into `development`.
## Progress
| Stage | Title | Release | Status |
|-------|-------|---------|--------|
| E0 | Payments data foundation | 1 | DONE |
| E1 | Trusted platform signal | 1 | DONE |
| E2 | Currency + benefit core | 1 | DONE |
| E3 | Wallet UI | 1 | DONE |
| E4 | Durability (PITR) | 2 | DONE |
| E5 | Payment intake | 2 | DONE |
| E6 | Ads | 2 | TODO |
| E7 | Admin & reports | 2 | TODO |
| E8 | Guest limits | — | TODO |
| E9 | Tournament fee | future | TODO |
**Release 1** = full mechanics with no real money, exercised via `admin_grant` (E0→E1→E2→E3).
**Release 2** = money (E4→E5→E6→E7). E8 is standalone (game-behaviour change, can run in
parallel). E9 is future.
---
## Architecture baseline (applies to all stages)
Read once; individual stages assume it.
### Schema & isolation
- The payments domain owns its **own Postgres schema `payments`** in the shared instance
(`scrabble` DB). All payments tables are `payments.*`. `backend` schema is untouched
except for the deprecation of two legacy columns (E2).
- **DB role.** A dedicated **NOLOGIN** role holds ALL privileges on `payments.*` and
**nothing** on `backend` — grant-based confinement, asserted by a `SET ROLE` isolation
test. The application still connects on its single (superuser) pool, so these grants are a
stepping-stone to a real separate login/process, not the runtime wall. The **runtime wall
is code-level**: only the `internal/payments` package imports the payments jet code and
issues `payments.*` SQL (an **import-boundary test** enforces it); every other domain
reaches payments through the narrow Go interface.
- **No cross-schema link at all.** There is **no** foreign key from `payments.*` to
`backend.accounts`: `account_id` is a plain `uuid`, kept referentially honest in code and
joined to the tombstoned account / `retained_identities` dossier by the stable id. This
keeps the spend transaction (ledger INSERT + balance UPDATE + benefit UPDATE) fully
**within `payments`** and the domain extractable into its own database later. Benefits move
**into** `payments` (they no longer live on `accounts` — see E2); game code reads them
through the payments **Go interface**, never via SQL.
- **Money.** Monetary amounts are a single **`bigint` in the currency's minor units** (RUB
kopecks; Votes/Stars/chips are whole units, scale 1) carried in Go by the `payments.Money`
value type — the sole constructor/formatter/arithmetic, so **no `float64` ever touches an
amount** and a whole-unit currency structurally cannot hold a fraction. `chip_rate` is not a
table: a chip pack is a product, so its per-method rate **is** `product_price`.
### Domain boundary
- New package `backend/internal/payments/``payments.go` (types + `Service`),
`store.go` (`type Store struct{ db *sql.DB }`, go-jet against `internal/postgres/jet/
payments`), following the `ads` domain shape (`backend/internal/ads/{ads,service,store}.go`).
- Wired in `backend/cmd/backend/main.go` `run()` (construct after `account`, before
`server.New`), handed into `server.Deps` (`server.go`), routes registered in
`registerRoutes` gated `if s.payments != nil`, admin section in `registerConsole` gated
`if s.payments != nil`.
- Game/other domains depend on payments only through a **narrow interface** (e.g.
`AdFree(ctx, account, platform, present) bool`, `SpendHint(ctx, account, platform, present)
error`, `Balances(ctx, account, platform, present) …`), where `present` is the set of
identity sources the account currently holds (`vk`→vk, `telegram`→telegram, `email`→direct;
`robot` ignored), computed by the caller from `account.Identities` — payments carries no
cross-schema identity knowledge, so unlink/re-link availability (D14) falls out live. Keep
the surface small; this is the seam that lets payments become a separate process later
without touching callers.
- **Read model.** Hot reads (`AdFree`/`HintsAvailable`/`Balances` and the gate) are served
from an in-process, account-keyed, write-through cache inside the payments package
(mirroring `account/suspension.go`), invalidated on every payments mutation
(spend/grant/fund/refund/merge); the payments DB is touched only on a cache miss, so the
steady-state hot path issues no query to the `payments` schema. The D39 materialized
`balances`/`benefits` tables stay the in-transaction write target the cache fronts.
Single-instance, matching the deployment (a multi-instance backend would need a shared
cache).
### Migrations & codegen
- Migrations: same goose dir `backend/internal/postgres/migrations/`, sequential
`0000N_*.sql`, `-- +goose Up/Down`, schema-qualified, **expand-contract mandatory**
(image rollback must stay DB-safe). First payments migration does `CREATE SCHEMA IF NOT
EXISTS payments`, creates the role, grants.
- **jetgen** (`backend/cmd/jetgen/main.go`) is currently hardwired to `schema=backend`.
Extend it to also generate `schema=payments` into `internal/postgres/jet/payments/
{model,table}` (committed). Regenerate only after a payments migration; revert unrelated
`backend`-schema churn (jetgen may reorder untouched tables — commit only intended diffs).
- Transactions: reuse the local `withTx(ctx, db, fn)` idiom. Balance/benefit mutations are
guarded single-row atomic UPDATEs (mirror `account.SpendHint`); the ledger INSERT +
materialized-cache UPDATE go in one `withTx`. Default Read-Committed is sufficient given
the guarded updates + unique idempotency keys; do not reach for Serializable without a
demonstrated need.
### Transport
- client ↔ gateway: Connect-RPC + FlatBuffers (h2c). gateway ↔ backend: REST/JSON +
`X-User-ID` via `gateway/internal/backendclient`. Any user-facing payments call needs the
full chain: backend REST handler (`u := s.user` group) → `backendclient` method →
Connect-RPC method + transcode (`gateway/internal/transcode/`) → FlatBuffers schema
(`pkg/fbs/…`, regen with `make -C pkg fbs` + `pnpm -C ui codegen`).
- Provider webhooks (Robokassa/VK) do NOT use the Connect path — model on the existing
public HMAC-signed route `s.public.GET("/dl/:id/:kind", …)` (`handlers.go`): a public
route with signature verification, proxied by the gateway/Caddy `@gateway` matcher
(`deploy/caddy/Caddyfile` — a new edge route MUST be added there or it falls to the
landing catch-all).
### Testing layers (`docs/TESTING.md`)
- **unit** (Go `_test.go`, TS vitest): gate-by-context, no-ads stacking, priority draw,
rate math, idempotency keys, catalog snapshotting. UI logic must be extracted out of
`.svelte` into `ui/src/lib/*` to be unit-testable.
- **integration** (`backend/internal/inttest/`, `//go:build integration`, Postgres-backed):
atomic chip↔benefit spend, callback idempotency, order-flow, TG outbox delivery, merge/
unlink of segments.
- **UI** (Playwright mock e2e, Chromium+WebKit): Wallet screen, warnings, guest-hidden, GP
stub. Mock e2e bypasses codec — wire bugs need codec unit tests.
- Local full verification before push: integration (`-tags=integration` + DAWG sibling +
Ryuk-off), UI check/test/build, codegen (`make -C pkg proto fbs`, `pnpm -C ui codegen`).
---
## E0 — Payments data foundation
**Status:** DONE · **Release 1** · depends on: none · mechanics: PAYMENTS §14, §7, §11.
**Goal.** Stand up the `payments` schema, its confinement role, the jetgen target, the domain
package skeleton and all core tables — nothing wired to real money yet. This is the substrate
every later stage builds on.
**Migration `00010_payments_foundation.sql` (`payments` schema).**
- `CREATE SCHEMA payments`; an idempotent `DO $$` block creates a **NOLOGIN** `payments` role;
`GRANT USAGE` + `GRANT ALL ON ALL TABLES` (+ `ALTER DEFAULT PRIVILEGES … GRANT ALL`) confine it
to `payments.*` with nothing on `backend`. No `REFERENCES` grant (there is no cross-schema FK).
- `payments.ledger` — append-only. `ledger_id` (uuid PK, app-generated v7), `account_id` (plain
`uuid`, **no FK**), `kind` (`fund|spend|admin_grant|refund`), `source`/`origin` (nullable,
`vk|telegram|direct`), `chips_delta` (signed int, 0 for a grant), `product_id` (nullable
FK→product), `order_id` (nullable FK→orders), `provider` + `provider_payment_id` (nullable),
`snapshot` (jsonb, written from E2), `created_at`. Immutability is a **`BEFORE UPDATE OR DELETE`
trigger** (a superuser bypasses a privilege REVOKE). Unique **partial** index on `(provider,
provider_payment_id) WHERE provider_payment_id IS NOT NULL` — the idempotency key.
- `payments.balances``(account_id, source)` PK, `chips int CHECK (>=0)`, `updated_at`. Created
**lazily** on first fund (up to three rows/account, absent = zero).
- `payments.benefits``(account_id, origin)` PK, `ads_paid_until timestamptz` null,
`ads_forever bool`, `hints int CHECK (>=0)`, `updated_at`. Created lazily.
- `payments.catalog_atom``atom_type` PK (`chips|hints|noads_days|tournament`); the four atoms
are **seeded** here (the `tournament` atom is provisioned for E9).
- `payments.product` (`product_id` PK, `title`, `active bool` soft-delete, timestamps);
`payments.product_item` (`(product_id, atom_type)` PK → `quantity`); `payments.product_price`
(`(product_id, COALESCE(method,''), currency)` unique → `amount bigint` minor units): a chip
pack carries a money price per `method` (`vk|telegram|direct`), a value carries one
`currency='CHIP', method=NULL` row. `currency ∈ {RUB, VOTE, XTR, CHIP}`; `amount CHECK (>=0)`.
- `payments.config` — a single typed row (`only_row bool PK CHECK`): `rewarded_payout_chips`,
`cooldown_global_seconds` (300), `cooldown_vs_ai_seconds` (1800), `cooldown_hint_seconds` (60),
`order_ttl_seconds` (1800). No `chip_rate` table — the pack rate is `product_price`.
- `payments.orders``order_id` (uuid PK), `account_id`, `platform`, `product_id` (FK),
`expected_amount bigint` + `currency`, `origin`, `status` (`pending|paid|expired`), `provider`,
`provider_payment_id` (nullable), timestamps. Index `(status, created_at)` for the pending sweep.
- `payments.payment_events``event_id` (uuid PK), `account_id`, `order_id` (nullable FK), `type`
(`succeeded|failed|refunded`), `payload jsonb`, `created_at`, `dispatched_at` (nullable, partial
index for the dispatch queue).
- Full `-- +goose Down` (DROP SCHEMA CASCADE + DROP OWNED BY + DROP ROLE); expand-contract, proven
reversible by an integration test.
**Backend.**
- `backend/internal/payments/{payments,service,store}.go` — the `Money` value type + `Currency`
(bigint minor units, exact, no float); `Store{db *sql.DB}` with a `Ping` health read via jet;
`Service` over the store. (`withTx` arrives with E2's first transaction.)
- `cmd/jetgen` generates the `payments` schema into `internal/postgres/jet/payments/` (a second
`GenerateDB` call); committed. Constructed in `cmd/backend/main.go` and passed to `server.Deps`
(`Payments`) with a boot-time reachability check; its routes are registered from E2.
**Legacy deprecation (expand phase only).** A `--` header note marks `accounts.hint_balance` and
`accounts.paid_account` deprecated; they are **not** dropped (the DROP is the contract phase after
E2 flips reads and after Release 2). Reads still use the old columns until E2.
**Tests.**
- integration (`inttest`): schema + role + seeds present; `SET ROLE payments` cannot read
`backend.accounts` (grant confinement); ledger rejects UPDATE/DELETE (trigger); idempotency
partial index holds (NULL-keyed rows repeat); balance/benefit/amount/enum CHECKs bite; migration
applies forward **and backward** on a throwaway PG.
- unit: `Money` — exact round-trip, per-currency scale, no-float parse rejecting a fraction for a
whole-unit currency, arithmetic, formatting. Import-boundary test: only `internal/payments`
imports the payments jet code.
**Done-criteria (met).** Migrations apply forward+backward on a throwaway PG 17; `go build
./backend/...` + `go vet` + `gofmt -l .` clean; committed `jet/payments/`; all tests green; no
behaviour change for users.
**Notes.** jetgen regenerates the whole `backend` schema; its committed jet had drifted from the
migrations (`robot_blocks`, `robot_friend_requests`, the `feedback_messages` `app_version` /
`browser_tz` columns, and `UseSchema` gaps), so this change also **regenerates and commits
`jet/backend`** to bring it back in sync (additive only — all suites stay green). The `payments`
role creation is idempotent (`DO $$` / `IF NOT EXISTS`) for fresh volumes.
---
## E1 — Trusted platform signal
**Status:** DONE · **Release 1** · depends on: none (parallel to E0) · mechanics: PAYMENTS §8.
**Goal.** Make the server know the execution platform from a trusted, unforgeable source,
carried on the session. This is the foundation the gate (E2) stands on; without it the gate is
meaningless. Signal plumbing only — no user-visible change.
**Model.** `platform = {kind: vk|telegram|direct, subtype: ios|android|web}` is a property of
the **session**, captured at creation. `kind` is always trusted — the gateway derives it from
the validated establish path (VK launch / TG initData / a web-native session), never a client
field. `subtype` is **cryptographically trusted only for VK** (it rides inside the signed
`vk_platform` launch param); for telegram and direct it is client-reported best-effort, and the
gate never relies on it (only the VK-iOS-frozen case is compliance-critical, and VK subtype is
trusted). VK/TG re-mint a session on **every cold start**, so their platform is re-captured each
launch; web/direct/email reuse the stored token, so their platform is captured once at creation
(`direct` needs no signature).
**Validation stays at the gateway.** Both wrapper verifiers already live there and the backend
cannot import either (separate modules under `internal/`, and the VK app secret is gateway-only):
VK launch params via the in-process `gateway/internal/vkauth.Verify` (HMAC-SHA256 over the signed
`vk_*` params under `GATEWAY_VK_APP_SECRET`, extended here to expose the signed `vk_platform`
a trusted `Subtype()`), TG `initData` via the validator RPC. The gateway hands the derived
platform to the backend at establish; the backend persists it and returns it on resolve.
**Backend.**
- `backend.sessions` gains nullable `platform_kind` + `platform_subtype` columns (migration
`00011`, CHECK-constrained, jet regenerated). A `session.Platform` value type + `session.Create`
captures it; `Session` carries it through the store and the warm cache.
- `handleResolveSession``resolveResponse` (`dto.go`) returns the platform; the establish
handlers set `kind` from their own endpoint (`/sessions/telegram|vk|guest|email/*`) and
`subtype` from the request (VK: gateway-extracted from the signed params; TG/direct: the client
best-effort field, defaulting web). The account-merge session mint (`link.merge`) inherits the
caller's platform from the request context.
- Middleware (`middleware.go`) parses the gateway-injected `X-Platform` into the request context
on the `s.user` group; `platform(c)` exposes it. Absent ⇒ untrusted (fail-closed).
**Gateway.**
- `backendclient.WithPlatform(ctx, "<kind>/<subtype>")` + `do`/`getRaw` inject `X-Platform` on
every authenticated backend call; `connectsrv.Execute` enriches the request context from the
resolved session's platform (carried through the gateway session cache + `ResolveSession`).
Never from a client request body.
**Client (`ui/`).** `platformSubtype()` (`ui/src/lib/platform.ts`) supplies a best-effort device
subtype on the `auth.telegram` / `auth.guest` / `auth.email.login` requests (new FBS `subtype`
field): Telegram's `WebApp.platform` inside a Mini App, else the Capacitor/web channel. VK sends
nothing (the gateway derives the trusted subtype from the signed launch params).
**Tests.**
- unit (Go): `vkauth` exposes the signed `vk_platform` and maps iPhone/iPad → ios (the frozen
case); the `X-Platform` middleware round-trips + reports untrusted when absent; the backend
client injects `X-Platform` from the context and omits it when untrusted.
- integration: a session carries its platform through create + a cold-cache (DB) resolve for each
kind; an unattributed session is untrusted; the CHECK constraints bite; migration `00011`
applies forward **and backward** on a throwaway PG.
- UI: subtype normalization (vitest) + the new `subtype` field on the wire (codec unit test).
**Done-criteria (met).** A VK/TG session resolves to a trusted `{kind, subtype}`; a forged body
cannot change `kind` (nor the VK subtype); `direct` sessions resolve to `direct`; the untrusted
path is reachable and observable via `platform(c)`. No user-visible change; all layers green.
**Notes/risks.** High blast-radius (auth/session table + broad gateway header threading): additive
migration, no mixed-in refactors, `X-Platform` inert until E2 consumes it. **Sessions minted before
E1 carry no platform → untrusted (view-only) until re-login**; VK/TG self-heal on the next
cold-start re-mint, direct/email do not (accepted: Release 1 has no money, sessions cycle by
Release 2). TG/direct subtype is not cryptographically trusted — E2 must keep the gate on `kind`
+ the trusted VK subtype only.
---
## E2 — Currency + benefit core
**Status:** DONE · **Release 1** · depends on: E0, E1 · mechanics: PAYMENTS §2–§6, §11.
**Goal.** The full internal money mechanic, exercisable end-to-end **without real money**
via `admin_grant`: chip balances, spend→benefit atomically, the compliance gate by context,
benefit application (no-ads stacking, hints per-origin), the legacy migration, and the
`SpendHint` rewrite. This is the heart.
**Payments service (Go).** Every read/gate method also takes `present` (the account's live
identity sources, see *Domain boundary*) and is served from the read cache.
- `Balances(ctx, account, platform, present)` → per-segment `{source, chips, spendable}` for
the context (VK→vk spendable, direct/tg hidden; TG→tg; direct→direct+vk+tg by priority;
VK-iOS→vk shown as a **frozen** number, none spendable; untrusted→view-only, none spendable).
- `Spend(ctx, account, platform, present, productID)` → gate-checked purchase of a **value**
(CHIP price, `method=NULL`; never a chip pack) with chips: resolve spendable segments by
context, draw by priority direct→vk→tg, write a `spend` ledger row (+ a catalog **snapshot**
of atoms+price) + decrement balance + apply benefit (extend `ads_paid_until[origin]` from
`max(now,end)` / set `ads_forever` / add hints) **in one tx**, stamping `origin` = platform
context. Refuse if untrusted (fail-closed) or funds insufficient.
- `Grant(ctx, account, origin, atoms)` → a **0-price sale of a value**: an `admin_grant`
ledger row (`chips_delta=0`, + snapshot), same benefit application; concrete values only,
never chips (no chips move — it neither requires nor touches a balance). Origin chosen by
the admin. In E2 this is the Go service method only, exercised by tests; the admin grant UI
+ catalog editor are E7.
- `AdFree(ctx, account, platform, present)` / `HintsAvailable(…)` / `SpendHint(…)` → apply
the one-directional origin rule: in context P, usable origins = {P} plus, when P is
web/native, {vk,tg} (relaxation outward); in VK only vk; in TG only tg. Hint consumption
draws by the same priority direct→vk→tg.
- `Merge` / `Unlink` hooks: extend `accountmerge` to merge segments **and** benefits by origin
(same-origin add — chips sum, terms extend per origin; different origins coexist) in the
caller's tx (`MergeTx`), and make **both** segment *and* benefit availability follow
identity presence — unlink sleeps the balance *and* the benefit, re-link wakes them (D14),
resolved live from `present`. Warn-before-unlink surfaces the balance via the interface; the
warning UI itself is not E2.
**Backend wiring & migration.**
- Deprecate-and-flip `accounts.hint_balance` / `accounts.paid_account`: E0 added the tables;
here, move reads/writes to `payments.benefits`. `SpendHint` (`game/service.go` ~:1147) and
`ads.Eligible` (`ads/ads.go` :107) call the payments interface instead of the account
columns. Legacy values were never set in prod → zero them; the DROP is the contract phase
(guarded, after Release 2 — keep columns until then for rollback safety).
- `vs_ai` hints stay free/unlimited (unchanged 30-min gate); only online-game hint spend
routes through the segmented, context-aware path.
**API (user-facing, Connect chain).** Read-only wallet view + spend:
`GET /api/v1/user/wallet` (balances+benefits for the context), `POST /api/v1/user/wallet/
buy` (spend chips on a product). Add the backend handlers (`u := s.user`), `backendclient`
methods, Connect methods + transcode + FBS. Admin grant is internal/admin (E7 UI).
**Tests.**
- unit (Go): gate-by-context matrix (every row of PAYMENTS §4, incl. VK-iOS frozen +
untrusted); priority draw; no-ads stacking (`+=` from max(now,end)) + forever override;
per-origin hint applicability + direct→vk→tg draw; merge/unlink segment+benefit math;
catalog snapshotting; read-cache invalidation on each mutation.
- integration: atomic spend (ledger+balance+benefit in one tx; failure rolls all back);
admin_grant credits values not chips; legacy migration zeroes and flips reads; merge/
unlink over Postgres.
- UI: none new (E3 builds the screen); wallet DTO covered by codec unit tests.
**Done-criteria.** `admin_grant` applies no-ads/hints directly (a 0-price sale of a value —
no chips involved); the player chip-spend path (`Spend`) is proven by unit/integration tests
(balance seeded in-test, since a legitimate chip source arrives only with Release 2); the gate
blocks cross-context spend and cross-origin application; the ads gate reads the new benefit;
`SpendHint` uses segments; the hot read paths hit the read cache, not the `payments` schema;
all layers green; **compliance regression** (a `direct` benefit never activates inside VK/TG)
is a named test.
**Notes/risks.** This is the high-blast-radius core (money semantics + a live path
`SpendHint`/`ads.Eligible`). Minimize surface, keep the interface narrow, no mixed-in
refactors. The legacy flip is expand-contract: reads move first, DROP much later.
---
## E3 — Wallet UI
**Status:** DONE · **Release 1** · depends on: E2 · mechanics: PAYMENTS §1, §7, §6, §13, §4.
**Goal.** The user-facing "Кошелёк" (Wallet) section: balances + active benefits + the
catalog storefront, honouring guest-hidden, GP-stub, and the web-spend warning.
**Backend + wire (catalog read — new).** E2 shipped `wallet.get` / `wallet.buy` (segments +
benefits + a chip spend) but no way to *list* the catalog; the storefront needs one, so E3 adds a
read path following the E2 shape:
- `payments.Service.Catalog(ctx, cxt)` + `store.loadCatalog` (`internal/payments/{catalog,
store_catalog}.go`) read every **active** product with atoms and prices and project them to the
context (`projectCatalog`, pure + unit-tested): a **value** (no `chips` atom) carries its CHIP
price and shows everywhere; a **chip pack** (`chips` atom) carries the money price for the
context method (`cxt.Kind`: vk→VOTE, telegram→XTR, direct→RUB) and shows only where that method
is priced. Read **uncached** (the catalog is small and rarely edited — unlike the per-account
balances/benefits the read cache fronts).
- REST `GET /api/v1/user/wallet/catalog` (`handleWalletCatalog`, gated by `walletGate`) →
`catalogDTO`; gateway op `wallet.catalog` (`transcode.go` + `encodeCatalog`), `backendclient.
Catalog`; FBS `Catalog`/`CatalogProduct`/`CatalogAtom` (`pkg/fbs/scrabble.fbs`), client
`decodeCatalog`.
**UI (`ui/`).**
- New `'wallet'` tab in `ui/src/screens/SettingsHub.svelte` — `SettingsTab` union, tab button
**between Friends and About** (guest-hidden like Friends, offline-disabled like Profile/Friends),
body branch, `'wallet'` route in `ui/src/lib/routeparse.ts` + `ui/src/App.svelte`.
- `Wallet.svelte` screen: context-available chip balances + active benefits (no-ads until date /
forever, hints count). **No history feed** (PAYMENTS §11 — noise). Storefront: values priced in
chips (buyable with `wallet.buy`), chip packs priced per method.
- **Guest:** section hidden entirely (durable-only).
- **GP build:** the chip-pack purchases are hidden behind a RuStore stub; spending earned chips on
values still works (PAYMENTS §13). Detected by a build-time flag `VITE_GP_BUILD`
(`ui/src/lib/distribution.ts`), forcible under the mock e2e with `?gp`.
- **Web-spend warning:** before a value spend that would draw vk/tg chips in a direct context, an
own `Modal` (not `showPopup`) warns the benefit will be web/native-only. The context is inferred
client-side (`executionContext` — VK/Telegram/direct); the server enforces the real gate on
`wallet.buy` (fail-closed), so no wallet-DTO change was needed.
- Logic extracted to `ui/src/lib/{wallet,distribution}.ts` (unit-testable); `.svelte` stays thin.
**Pack purchase is display-only in E3.** Buying a chip pack needs the money order flow, which is
**E5**; here a pack card shows its price with a disabled **"Soon"** action. E5 replaces that with the
launch/order CTA. Value spends are wired now (E2 `wallet.buy`), though a Release-1 durable account
has 0 chips until funding exists (E5/E6), so a real value spend returns insufficient-funds until then.
**Tests.**
- unit (Go): `projectCatalog` context matrix (value everywhere; pack per context method; misconfig
omitted). unit (vitest): money/price formatting, spendable-segment selection, warning trigger,
the GP flag; `decodeCatalog` codec round-trip (mock e2e bypasses the codec).
- integration (`inttest`): `/wallet/catalog` returns active products with the context-correct price
over Postgres; soft-deleted excluded.
- UI (Playwright mock, Chromium+WebKit): Wallet renders between Friends/About; guest hides it
(`?guest` seam); GP stub (`?gp`); warning modal on a vk-drawing web spend, no warning on a
direct-covered spend. Mock overlay stays instant under `MODE==='mock'` (or it intercepts taps).
**Done-criteria (met).** Balances/benefits/storefront render per context; guest/GP/warning paths
verified by unit + integration + mock e2e on both engines. **A *populated* contour review depends
on later stages** (no products until the E7 catalog editor, no chip funding until E5/E6, no grant
UI until E7): on the contour E3 shows the correct **empty** wallet/storefront states; the populated
UI is proven by the mock e2e. (This replaces the earlier "demonstrable end-to-end via `admin_grant`"
line — the grant UI is E7.)
**Notes/risks.** No global `.btn`/`.ghost` in `ui/` — styled per-component with scoped CSS + tokens
(mirror NewGame `.invite`). Product titles are single-language catalog data (E0 `product.title`),
shown verbatim; currency/chip words are i18n, counts follow the app's label+number convention (no
noun agreement). Svelte whitespace/`$state` naming gotchas apply.
---
## E4 — Durability (PITR)
**Status:** DONE — armed + restore-drilled on prod (v1.13.0, 2026-07-09). · **Release 2** ·
depends on: E0 (schema exists) · mechanics: PAYMENTS §14 (D4).
**Goal.** Continuous WAL archiving with point-in-time recovery, armed **before the first
real money** is accepted (E5 prod). Protects both money and game data.
**Locked decisions (this stage).**
- **Tool: pgBackRest.** **Destination: Selectel S3** object storage (encrypted AES-256-CBC,
path-style addressing), **prod main host only** — the test contour never archives. (D4 left
the tool + destination open; resolved here. Warm replica stays deferred, per D4.)
- **Retention 30 days**, **daily full base backup** (a systemd timer) + continuous WAL
(`archive_command`, a 5-minute forced switch bounds the recovery point). Assessment
(owner-reviewed prod gate): measured prod WAL **~0.77 MB/day**, DB **~9.6 MB** → archive
**< 1 ₽/month** on Selectel S3, **negligible** perf impact. Recorded in `deploy/README.md`.
- **Archiving ships gated OFF** (`PGBACKREST_ARCHIVE_MODE` on the DB, `pitr_enabled` for the
timer — both default off), so the merged/redeployed artifact is inert until armed and an
un-armed prod deploy **cannot** pile WAL onto the disk.
**Work (landed in the artifacts PR into `development`).**
- pgBackRest in the DB image (`deploy/postgres/Dockerfile`); postgres becomes a built + pushed
image (prod overlay `image:` + `prod-deploy.yaml` build/push list).
- Repository config + `archive_mode` via `PGBACKREST_*` env on the prod-overlay postgres
service; secrets/vars rendered by `deploy/write-prod-env.sh` from the `PROD_PGBACKREST_*`
Gitea set; **parity added to `prod-rollback.yaml`** (a rollback must not disarm archiving).
- Daily base-backup systemd timer (Ansible `main` role, gated by `pitr_enabled`).
- Two Grafana alerts on the exporter's `pg_stat_archiver` metrics (failing / stalled),
absent/NaN-safe on the contour.
- Belt-and-braces `pg_dump` fixed to dump the **whole DB** (`deploy/prod-deploy.sh` was
`-n backend`, silently excluding `payments`); manual-restore runbook updated.
- Full PITR runbook + arming sequence + recorded assessment in `deploy/README.md`.
**Prod arming (completed 2026-07-09 with the v1.13.0 release).** Owner created the Selectel S3
bucket (`erudite`, ru-6) + the `PROD_PGBACKREST_*` secrets/variables (incl. `ARCHIVE_MODE=on`);
promoted `development → master` → `prod-deploy` (archive_mode on behind the maintenance window),
then `stanza-create` + first base backup (31.9 MB cluster → 3.7 MB in the repo) + `check`, the
Ansible `-e pitr_enabled=true` timer, and a restore drill on an isolated one-shot target (data
intact, then wiped). Exact steps: `deploy/README.md` (point-in-time recovery — arming).
**Tests.** Restore drill on an isolated one-shot instance (base + WAL → target timestamp),
recorded in `deploy/README.md`. No app-level tests. Local verification: `docker compose config`
valid + the custom PG image builds (archiving inert on the contour).
**Done-criteria (met).** WAL archiving live on prod PG (v1.13.0); a restore verified on an
isolated one-shot target; cost + perf assessment reviewed; runbook current in
`deploy/README.md`.
**Notes/risks.** The repository **cipher passphrase is unrecoverable if lost** — stored apart
from the S3 keys. Manual/timer pgBackRest runs use `docker exec -u postgres … --pg1-user=scrabble`
(docker exec is root; the DB superuser role is `scrabble`, not `postgres`) — the systemd timer
+ the runbook carry this. Enabling `archive_mode` restarts postgres (rode the prod-deploy
maintenance window). Migrations stay expand-contract so image rollback remains DB-safe with PITR.
---
## E5 — Payment intake
**Status:** DONE · **Release 2** · depends on: E0, E1, E2, E4 · mechanics: PAYMENTS §9, §12.
**Delivery & baked decisions.** Shipped as a linear PR stack (owner's choice), Robokassa first.
Resolved: match the order by a Robokassa **`Shp_order`** custom parameter, not the numeric `InvId`
(an order id is a uuid); idempotency key = the order id (`provider_payment_id = order_id`); the НПД
receipt is formed **shop-side in the Robokassa cabinet**, so no `Receipt` parameter is sent; a
chargeback **never drives the balance negative** (D27 stands, `balances_chips_chk` kept), so E5 is
**schema-free** (no migration, no contour wipe). Delivered on `feature/payment-intake-robokassa`:
the offer page (`/offer/`), the order/`fund` engine (idempotent, honours an expired order), the
`internal/robokassa` adapter, the `POST /wallet/order` + internal Result-callback handlers (a D36
confirmed-email gate on `direct`), the pending reaper, the `wallet.order` edge wire + the public
`/pay/*` routes, the Wallet purchase CTA, the contour deploy env (IsTest forced), and the
`payment_events` dispatcher — an in-app wallet-refresh push (KindNotification `"payment"`) with a
self-closing provider-return page (the payment opens in a separate window) and a return-focus
refetch fallback. The **VK Votes rail** is delivered too: the client opens
`VKWebAppShowOrderBox({item: order_id})`; a two-phase signed server callback (`get_item` → the pack
title + vote price; a chargeable `order_status_change` → the same `Fund` with source=`vk`, idempotent
on VK's own order id) is verified at the gateway with the app protected key (`GATEWAY_VK_APP_SECRET`,
already deployed) and proxied to the backend intake. The **Telegram Stars rail** is delivered on
`feature/payment-intake-tg-stars`: only the bot reaches Telegram, so the **invoice is minted by the
bot** — on the `wallet.order` path the gateway sends a new `CreateInvoice` command over the reverse
bot-link and the bot returns the `createInvoiceLink` (XTR) in its Ack, handed to the client's
`WebApp.openInvoice`. The bot answers `pre_checkout_query` via a new bot→gateway **`ValidatePreCheckout`**
unary (backed by the backend: the order must exist, be still creditable and **not already paid** — the
reusable-invoice double-pay guard — with a matching amount); the decline reason is localised to the
order account's language. A completed `successful_payment` is persisted to a pure-Go **SQLite outbox**
(`modernc.org/sqlite`) then forwarded by a new bot→gateway **`ForwardPayment`** unary into the same
`Fund` (source=`telegram`, idempotent on `telegram_payment_charge_id`, honours an expired order),
re-driven at startup and every 30 s. The rail is wired by `TELEGRAM_STARS_OUTBOX_DIR` (defaults to the
bot `/data` volume) but stays **inert until a chip pack carries an XTR price**, so seeding a Stars price
in the admin is the go-live. Finally **refunds** are delivered on `feature/payment-intake-refunds`: a
single `Refund` engine (`internal/payments`) reverses a paid order best-effort, exactly once —
idempotent on `(provider, provider_refund_id)`, revoking the funded chips **floored at 0** (never
negative, D27), and recording the unrecoverable remainder (chips already spent) as a per-account
**loss + abuse flag** in the new additive `payments.account_risk` table (read by the E7 report). The
refund ledger row's chip delta is what was actually reclaimed (the ledger stays reconcilable); the
full reversal rides in its snapshot; the order stays `paid`. **No rail pushes an unsolicited refund**
— all are admin-triggered (E7): Robokassa refund API / cabinet (auto-polling deferred — a worker not
worth it at low chargeback volume), VK via support, Telegram `refundStarPayment`. `failed` events are
not wired (no rail signals a hard post-charge server decline). The migration is **additive** (a new
table only), so E5 stays rollback-safe / no contour wipe. That closes E5. Deferred to a later stage:
hiding the ad banner on a no-ads purchase (a spend-path `NotifyBanner`, with the owner's agreement).
**Goal.** Accept real money on all three rails into the payments domain: order-flow,
verified provider callbacks, idempotency, the TG bot SQLite outbox, the event dispatcher,
receipts, and refunds.
**Order-flow & intake (single writer).**
- `POST /api/v1/user/wallet/order` → create `order(pending)` (account/platform/product/
expected amount/origin), return the provider-specific launch payload with `order_id`
threaded in (Robokassa `InvId` / TG `invoice_payload` / VK `item`). The storefront's chip-pack
card wires its purchase CTA to this here, **replacing the disabled "Soon" placeholder E3 left**
(`ui/src/screens/Wallet.svelte`).
- Robokassa + VK **public webhooks**: new edge routes (add to `deploy/caddy/Caddyfile`
`@gateway` matcher — or they fall to the landing catch-all), signature/HMAC verified,
proxied into a payments intake handler. Match by `order_id`, verify amount, credit
(ledger `fund` + balance UPDATE in one tx), mark order `paid`, emit `payment_event`.
Idempotent by `(provider, provider_payment_id)`.
- **Pending sweep:** background reaper expires pending orders after the configured timeout
(~30 min). Expiry is cosmetic — a later valid callback still credits (revive/honour).
**TG bot outbox (`platform/telegram/`).**
- The bot receives `successful_payment` (and `pre_checkout_query`) via Bot API. A **SQLite**
store on the bot's disk (`internal/outbox`): on receipt, persist → forward over the reverse
mTLS bot-link to the **gateway** (a `ForwardPayment` unary; the bot cannot dial the backend
directly) → the gateway proxies to the backend payments-intake REST → on a durable response,
mark `forwarded`. Re-drive undelivered on startup and on a 30 s tick. Backend intake dedups by
`telegram_payment_charge_id`.
- Invoice creation (Stars) is minted by the bot (`createInvoiceLink`, XTR) on the gateway's
`CreateInvoice` bot-link command, returned to the Mini App as the `openInvoice` link.
**Events & notifications.**
- `payment_events` dispatcher: `succeeded`/`failed`/`refunded` → live gRPC stream if the
user is connected, else `botlink` push / email relay (existing). "failed" = an active
provider decline (not an abandoned pending) surfaced to the user; "succeeded" hook
(email/bot message).
**Receipts (§12).** Robokassa self-employed НПД receipt on payment (provider config); VK
handles Votes tax itself; TG Stars — no receipt.
**Refunds (§9).** ToS non-refundable. **All refunds are admin-triggered** (E7): no rail pushes an
unsolicited refund — Robokassa refund API / cabinet (auto-polling deferred as a low-value worker),
VK via support, Telegram `refundStarPayment`. One `Refund` engine reverses a paid order best-effort,
exactly once (idempotent on `(provider, provider_refund_id)`): revoke floored at 0 (never negative),
unrecoverable remainder → per-account loss + abuse flag (`payments.account_risk`), a `refund` ledger
row (chip delta = revoked, full reversal in the snapshot). `failed` events are not wired (no rail
signals a hard post-charge server decline). Ledger export-ready (reconciliation not built).
**Tests.**
- unit: signature/HMAC verifiers per rail; order-id matching; idempotency-key dedup.
- integration: full order→callback→credit per rail; duplicate callback credits once; expired
order still honoured on late callback; TG outbox store→forward→ack→cleanup + restart
re-drive; refund revoke best-effort/never-negative.
- UI: purchase flow reaches the provider launch (mock); success/failure surfaced.
**Done-criteria.** A real (sandbox) payment on each rail credits chips exactly once; a
replayed callback does not double-credit; the TG outbox survives a bot restart mid-flight;
failed/succeeded events reach the user; refund path exercised. **PITR (E4) armed and the
cost/perf assessment reviewed before this goes to prod.**
**Notes/risks.** Manual `docker run -p` boot tests fail from the shell — verify the runnable
artifact via the testcontainers integration suite. Distroless services run UID 65532;
bind-mounted secrets must be 0644. Edge routes silently fall through if not added to the
Caddyfile — add a CI probe. The prod rolling deploy skips caddy on config-only changes —
force-recreate when the Caddyfile changes.
---
## E6 — Ads
**Status:** TODO · **Release 2** · depends on: E2 (chips), E5 (rewarded credits via intake) ·
mechanics: PAYMENTS §10.
**Goal.** VK video ads: the post-move interstitial (frequency-gated) and the rewarded video
(credits chips via server verify), plus extending the existing banner suppression to
per-origin.
**Work.**
- **Provider abstraction:** a small ads-network interface (VK impl now) so a future network
for other platforms slots in without rework. VK integration via `ui/src/lib/vk.ts`.
- **Rewarded:** voluntary view → the network's **server verify callback** → payments intake
credits chips to the `vk` segment (client not believed, like a payment). On-launch
anti-fraud = provider verify only (no own daily cap; abstraction allows later).
- **Interstitial** (post-move fullscreen), configurable server values (from `payments`
config): global per-user cooldown across all games (default 5 min); `vs_ai` 30 min; a hint
application triggers a post-move interstitial independently with its own 1-min cooldown;
offline banner-only; respect VK's own frequency caps. Cooldown state tracked server-side
(per user) or client-mirrored from a server value — pick and document at implementation.
- **Banner suppression:** extend `ads.Eligible` (`backend/internal/ads/ads.go` :107) to gate
on the **origin benefit applicable in the current context** (E2 interface) instead of the
single legacy flag. No-ads suppresses banner + interstitial; rewarded never suppressed.
**Tests.**
- unit: cooldown logic (global 5m / vs_ai 30m / hint-trigger 1m independence); rewarded
credit path; banner eligibility per context.
- integration: rewarded verify → credit exactly once (idempotent like a payment).
- UI: interstitial shows/respects cooldown (mock); rewarded button; no-ads hides banner +
interstitial; rewarded still available under no-ads.
**Done-criteria.** VK rewarded credits chips once per verified view; interstitial respects
all cooldowns incl. the hint trigger; no-ads suppresses banner+interstitial but not
rewarded; offline shows banner only.
**Notes/risks.** Crypto-payout networks stay rejected. Rewarded-without-payout is pointless —
only enable where the network pays (VK). Keep the interstitial frequency as server config so
it tunes without a store release.
---
## E7 — Admin & reports
**Status:** TODO · **Release 2** · depends on: E2 (ledger/grant), E5 (payments/refunds) ·
mechanics: PAYMENTS §11.
**Goal.** The admin console financial surface: per-user report, admin grant UI, manual
refund UI, ledger export.
**Work (`/_gm`, `backend/internal/server/handlers_admin_console.go` + `adminconsole/`).**
- **Per-user financial panel** on the existing user card (`consoleUserDetail` :343,
`UserDetailView`): segment balances, payments, spends, grants, refunds, full history —
read from the append-only ledger + materialized cache.
- **Admin grant** action (mirror the existing `POST /_gm/users/:id/grant-hints`): grant
concrete values (no-ads days / hints), **origin picker**, **never chips**; writes an
`admin_grant` ledger row (E2 `Grant`).
- **Manual refund** action: admin-initiated refund of a specific order (ties to the refund
path); records a `refund` ledger row; best-effort benefit revoke.
- **Ledger export**: CSV/JSON export of the ledger for tax reporting + future Robokassa
reconciliation (export-ready schema; reconciliation itself not built).
- Auth unchanged: gateway Basic-Auth in front of `/_gm` + backend same-origin CSRF on POSTs.
**Tests.**
- unit: report view assembly; grant refuses chips; export shape.
- integration: grant/refund write correct ledger rows; report reflects balances+history.
**Done-criteria.** An operator can see a user's full financial picture, grant concrete
values (origin-picked, never chips), issue a manual refund, and export the ledger.
**Notes/risks.** `/_gm` per-user detail already surfaces `PaidAccount`/`HintBalance` — replace
those with the segmented view as the legacy columns retire.
---
## E8 — Guest limits
**Status:** TODO · **standalone** (game-behaviour change; can run in parallel) · depends on:
none · mechanics: PAYMENTS §6.
**Goal.** A registration funnel: cap what a guest can do, enforced **server-side** (today the
gating is UI-only).
**Finding (verified).** The friend/invitation paths do **not** check `is_guest` on the
server — only the UI hides them: `social/friends.go:50` `SendFriendRequest`,
`robotfriends.go:41` `RequestInGame`, `friendcodes.go:67` `RedeemFriendCode`,
`lobby/invitations.go:208` `CreateInvitation`. A guest with a valid `X-User-ID` can call them
in the UI's stead.
**Work.**
- **Server guest gate** on friend-request / redeem-code / invitation-create: refuse when the
caller `is_guest` (add an `ErrGuestForbidden`-style guard, as `feedback` already has).
- **Active-game limits** for guests: at most **1 random-opponent game + 1 vs_ai** concurrently
(enforce on game/invitation creation in `lobby`/`game`; today no such limit exists).
- Keep the existing UI gating; this adds the server as the source of truth.
**Tests.**
- integration: guest is refused friend/redeem/invitation server-side; guest blocked from a
2nd random / 2nd vs_ai; durable account unaffected.
- UI: guest sees the funnel (existing hides + any new messaging).
**Done-criteria.** Guests are server-limited to 1 random + 1 vs_ai and cannot friend/invite;
durable accounts unchanged; regression that this does not break existing durable flows.
**Notes/risks.** This changes existing game behaviour — its own tests, its own PR, no
mixed-in payments changes. Decide whether a guest may finish an already-started game (limit
on creation, not mid-game) at implementation and record it here.
---
## E9 — Tournament fee (future)
**Status:** TODO · **future** · depends on: E0 (atom provisioned), tournament feature ·
mechanics: PAYMENTS §5, §7.
**Goal.** Charge a chip entry fee for tournaments. The `tournament` atom + a catalog product
are provisioned in E0/E7; the spend mechanic reuses E2 (`Spend`). The actual tournament
feature and its coupling to entry are out of scope until the tournament feature exists.
**Done-criteria.** Deferred — revisit when tournaments are built.
---
## Verification & CI (all stages)
- Per-stage tests at the layers above; **compliance-gate regression is mandatory** (a
`direct` benefit must never activate inside VK/TG) and runs from E2 onward.
- Local full verification before every push: `go build/vet ./backend/... && gofmt -l .`,
integration (`-tags=integration` + DAWG sibling + Ryuk-off), `pnpm -C ui check/test:unit/
build`, Playwright mock e2e, codegen (`make -C pkg proto fbs`, `pnpm -C ui codegen`).
- Contour: each PR into `development` auto-deploys the test contour; owner does visual sign-
off there (not local). Keep a multi-PR batch a linear stack (one shared contour,
last-deploy-wins).
- Prod (Release 2): expand-contract migrations only (image rollback DB-safe); PITR armed +
the E4 cost/perf assessment reviewed **before** the first money; new edge routes added to
the Caddyfile with a CI probe; caddy force-recreated on config-only changes.
- Release framing: **shipped docs/code/commits/PRs carry no stage ids** — finalize copy for
the release, not the plan.
+4 -1
View File
@@ -100,7 +100,10 @@ state, lobby enqueue, chat). The social/account/history operations under
`/api/v1/user`: `friends/*` (request/respond/cancel/unfriend,
list/incoming, the one-time `code` issue/redeem), `blocks/*`, `invitations/*`
(create/accept/decline/cancel/list), `PUT profile`, `email/{request,confirm}`,
`stats`, and `games/:id/gcg` (finished-only). The `internal/notify` hub feeds a
`stats`, `games/:id/gcg` (finished-only), and the payments `wallet` /
`wallet/catalog` (`GET` — the context-visible chip segments + benefits, and the
storefront catalog) / `wallet/buy` (`POST` — a chip spend on a value), served by
`internal/payments` behind the store-compliance gate. The `internal/notify` hub feeds a
second listener — `internal/pushgrpc`, a gRPC server (`BACKEND_GRPC_ADDR`) streaming
live events (your-turn, opponent-moved, chat, nudge, match-found, notify) to the
gateway. The gateway-only `POST /api/v1/internal/push-target` (a user's
+73 -1
View File
@@ -31,6 +31,7 @@ import (
"scrabble/backend/internal/link"
"scrabble/backend/internal/lobby"
"scrabble/backend/internal/notify"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/postgres"
"scrabble/backend/internal/pushgrpc"
"scrabble/backend/internal/ratewatch"
@@ -194,7 +195,8 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
emails.SetSendLimiter(account.NewSendLimiter(time.Minute, 5))
// Account linking & merge: the orchestrator over the account, merge and
// session layers. Wired to the /api/v1/user/link REST surface below.
links := link.NewService(emails, accounts, accountmerge.NewMerger(db), sessions)
merger := accountmerge.NewMerger(db)
links := link.NewService(emails, accounts, merger, sessions)
socialSvc := social.NewService(social.NewStore(db), accounts, games)
socialSvc.SetNotifier(hub)
socialSvc.SetMetrics(tel.MeterProvider().Meter("scrabble/backend/social"))
@@ -260,6 +262,21 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
// block and the banner admin console section.
adsSvc := ads.NewService(ads.NewStore(db))
// In-game currency domain (data foundation): the payments schema behind a
// narrow interface. A boot-time reachability check fails fast if the schema
// did not migrate; the wallet routes are registered when that surface lands.
paymentsSvc := payments.NewService(payments.NewStore(db))
if err := paymentsSvc.Ping(ctx); err != nil {
return fmt.Errorf("payments schema unreachable: %w", err)
}
logger.Info("payments domain ready")
// Wire the payments surface into the domains that consume it: the online-game hint wallet
// and the account-merge wallet fold. Done after the reachability check so a broken payments
// schema fails boot before anything depends on it.
games.SetHintWallet(paymentsSvc)
merger.SetPayments(paymentsSvc)
// The image-render sidecar client for the PNG export artifact; nil (PNG
// download answers 404) when BACKEND_RENDERER_URL is unset.
var renderer *render.Client
@@ -287,9 +304,11 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
RateWatch: rateWatch,
BanView: banView,
Ads: adsSvc,
Payments: paymentsSvc,
Notifier: hub,
ExportSignKey: cfg.ExportSignKey,
Renderer: renderer,
Robokassa: cfg.Robokassa,
})
pushSrv := pushgrpc.NewServer(cfg.GRPCAddr, hub, logger)
@@ -298,6 +317,13 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
logger.Info("servers starting",
zap.String("http_addr", cfg.HTTPAddr),
zap.String("grpc_addr", cfg.GRPCAddr))
// Sweep expired pending payment orders on a cadence (cosmetic hygiene; a late valid callback
// still credits). Runs until ctx is cancelled.
go runOrderReaper(ctx, paymentsSvc, logger)
// Deliver pending payment_events to connected clients as an in-app wallet-refresh push (the
// credit already landed in the ledger; a return-focus poll is the client-side fallback).
go runPaymentDispatcher(ctx, paymentsSvc, hub, logger)
errc := make(chan error, 2)
go func() { errc <- pushSrv.Run(ctx) }()
go func() { errc <- srv.Run(ctx) }()
@@ -307,6 +333,52 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
return err
}
// runOrderReaper periodically expires pending payment orders past their configured lifetime, until
// ctx is cancelled. Expiry is cosmetic: a later valid provider callback still credits an expired
// order.
func runOrderReaper(ctx context.Context, p *payments.Service, log *zap.Logger) {
t := time.NewTicker(5 * time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if n, err := p.ExpireOrders(ctx); err != nil {
log.Warn("order reaper: sweep failed", zap.Error(err))
} else if n > 0 {
log.Info("order reaper: expired pending orders", zap.Int("count", n))
}
}
}
}
// runPaymentDispatcher delivers pending payment_events to connected clients as a wallet-refresh
// signal (KindNotification / "payment"), marking each delivered, until ctx is cancelled. The credit
// already committed to the ledger; this is only the in-app push so an open wallet updates in place.
func runPaymentDispatcher(ctx context.Context, p *payments.Service, pub notify.Publisher, log *zap.Logger) {
t := time.NewTicker(3 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
evs, err := p.UndispatchedEvents(ctx, 50)
if err != nil {
log.Warn("payment dispatcher: read failed", zap.Error(err))
continue
}
for _, e := range evs {
pub.Publish(notify.Notification(e.AccountID, notify.NotifyPayment))
if err := p.MarkEventDispatched(ctx, e.EventID); err != nil {
log.Warn("payment dispatcher: mark failed", zap.String("event", e.EventID.String()), zap.Error(err))
}
}
}
}
}
// newMailer builds the confirm-code mailer: an SMTP relay when a host is
// configured, otherwise the development log mailer (the code is logged, not sent).
func newMailer(cfg account.SMTPConfig, logger *zap.Logger) account.Mailer {
+12 -5
View File
@@ -9,7 +9,8 @@
// 1. start a postgres:17-alpine container via testcontainers-go
// 2. open it with search_path=backend and apply the embedded goose migrations
// 3. drop goose's bookkeeping table so jet does not generate a model for it
// 4. run jet's PostgreSQL generator for schema=backend into internal/postgres/jet
// 4. run jet's PostgreSQL generator for the backend and payments schemas into
// internal/postgres/jet (one subdirectory per schema)
package main
import (
@@ -36,6 +37,7 @@ const (
superuserPassword = "scrabble"
superuserDatabase = "scrabble_backend"
backendSchema = "backend"
paymentsSchema = "payments"
containerStartup = 90 * time.Second
jetOutputDirSuffix = "internal/postgres/jet"
)
@@ -105,11 +107,16 @@ func run(ctx context.Context) error {
return fmt.Errorf("drop goose_db_version: %w", err)
}
if err := jetpostgres.GenerateDB(db, backendSchema, outputDir); err != nil {
return fmt.Errorf("jet generate: %w", err)
// Each schema generates into its own jet/<schema>/ subdirectory (the
// generator wipes only that subtree), so the two calls do not clobber each
// other. GenerateDB takes the schema explicitly, so the connection's
// search_path=backend does not affect the payments introspection.
for _, schema := range []string{backendSchema, paymentsSchema} {
if err := jetpostgres.GenerateDB(db, schema, outputDir); err != nil {
return fmt.Errorf("jet generate schema=%s: %w", schema, err)
}
log.Printf("jetgen: generated jet code into %s (schema=%s)", outputDir, schema)
}
log.Printf("jetgen: generated jet code into %s (schema=%s)", outputDir, backendSchema)
return nil
}
+15
View File
@@ -393,6 +393,21 @@ func (s *Store) Identities(ctx context.Context, accountID uuid.UUID) ([]Identity
return out, nil
}
// HasConfirmedEmail reports whether the account owns a confirmed email identity — the direct-rail
// recovery anchor a first purchase requires (D36).
func (s *Store) HasConfirmedEmail(ctx context.Context, accountID uuid.UUID) (bool, error) {
ids, err := s.Identities(ctx, accountID)
if err != nil {
return false, err
}
for _, id := range ids {
if id.Kind == "email" && id.Confirmed {
return true, nil
}
}
return false, nil
}
// ListAccounts returns accounts for the admin user list, newest first, paginated
// by limit and offset.
func (s *Store) ListAccounts(ctx context.Context, limit, offset int) ([]Account, error) {
+40 -20
View File
@@ -51,8 +51,24 @@ var ErrSameAccount = errors.New("accountmerge: primary and secondary are the sam
type Merger struct {
db *sql.DB
now func() time.Time
// payments, when set, merges the two accounts' chip segments and benefits by origin inside
// the merge transaction (SetPayments). Nil leaves payments untouched (tests that do not
// exercise the wallet).
payments PaymentsMerger
}
// PaymentsMerger is the payments surface the account merge enlists: fold the secondary's
// segments and benefits into the primary within the merge transaction, then invalidate the
// affected read caches after the commit. *payments.Service satisfies it.
type PaymentsMerger interface {
MergeTx(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID) error
Invalidate(ids ...uuid.UUID)
}
// SetPayments installs the payments merge hook. It must be called during startup wiring; the
// default (nil) merges no wallet state.
func (m *Merger) SetPayments(p PaymentsMerger) { m.payments = p }
// NewMerger constructs a Merger over db.
func NewMerger(db *sql.DB) *Merger {
return &Merger{db: db, now: func() time.Time { return time.Now().UTC() }}
@@ -67,7 +83,7 @@ func (m *Merger) Merge(ctx context.Context, primary, secondary uuid.UUID) error
return ErrSameAccount
}
now := m.now()
return withTx(ctx, m.db, func(tx *sql.Tx) error {
if err := withTx(ctx, m.db, func(tx *sql.Tx) error {
if err := guardActiveSharedGame(ctx, tx, primary, secondary); err != nil {
return err
}
@@ -107,8 +123,21 @@ func (m *Merger) Merge(ctx context.Context, primary, secondary uuid.UUID) error
if err := deleteEphemerals(ctx, tx, secondary); err != nil {
return err
}
if m.payments != nil {
if err := m.payments.MergeTx(ctx, tx, primary, secondary); err != nil {
return fmt.Errorf("accountmerge: payments: %w", err)
}
}
return tombstone(ctx, tx, primary, secondary, now)
})
}); err != nil {
return err
}
// The payments read cache is invalidated only after the merge commits, so a read racing the
// transaction cannot re-cache pre-merge state (both accounts' rows are moved or dropped).
if m.payments != nil {
m.payments.Invalidate(primary, secondary)
}
return nil
}
// guardActiveSharedGame returns ErrActiveGameConflict when primary and secondary
@@ -248,25 +277,16 @@ func mergeBestMoves(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUI
return nil
}
// mergeAccountFields adds secondary's hint wallet to primary and ORs the paid flag;
// all other profile fields stay the primary's.
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
var sec model.Accounts
if err := postgres.SELECT(table.Accounts.AllColumns).
FROM(table.Accounts).
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(secondary))).
QueryContext(ctx, tx, &sec); err != nil {
return fmt.Errorf("accountmerge: load secondary account: %w", err)
}
upd := table.Accounts.UPDATE(
table.Accounts.HintBalance, table.Accounts.PaidAccount, table.Accounts.UpdatedAt,
).SET(
table.Accounts.HintBalance.ADD(postgres.Int(int64(sec.HintBalance))),
table.Accounts.PaidAccount.OR(postgres.Bool(sec.PaidAccount)),
postgres.TimestampzT(now),
).WHERE(table.Accounts.AccountID.EQ(postgres.UUID(primary)))
// mergeAccountFields bumps the primary account's updated_at to reflect the merge. The former
// hint-wallet and paid-flag merge moved to the payments domain, where segments and benefits
// merge by origin (see the payments MergeTx step and docs/PAYMENTS.md §6); the legacy
// accounts.hint_balance / paid_account columns are deprecated and no longer read or written.
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, _ uuid.UUID, now time.Time) error {
upd := table.Accounts.UPDATE(table.Accounts.UpdatedAt).
SET(postgres.TimestampzT(now)).
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(primary)))
if _, err := upd.ExecContext(ctx, tx); err != nil {
return fmt.Errorf("accountmerge: update primary account: %w", err)
return fmt.Errorf("accountmerge: touch primary account: %w", err)
}
return nil
}
-8
View File
@@ -100,14 +100,6 @@ type ActiveCampaign struct {
OverrideDark *ColorSet
}
// Eligible reports whether an account should be shown the advertising banner: a
// free account (not paid) with an empty hint wallet and without the no_banner
// role. The no_banner role suppresses the banner unconditionally; buying a paid
// account or any hints also removes it.
func Eligible(paidAccount bool, hintBalance int, hasNoBanner bool) bool {
return !paidAccount && hintBalance <= 0 && !hasNoBanner
}
// computeActiveSet builds the resolved rotation feed from the enabled campaigns
// at time now, in language lang, and reports whether the feed is an urgent one.
// Campaigns outside their validity window, and campaigns with no messages, are
-24
View File
@@ -6,30 +6,6 @@ import (
"time"
)
func TestEligible(t *testing.T) {
tests := []struct {
name string
paidAccount bool
hintBalance int
hasNoBanner bool
want bool
}{
{name: "free, empty wallet, no role", want: true},
{name: "paid", paidAccount: true, want: false},
{name: "has hints", hintBalance: 3, want: false},
{name: "no_banner role", hasNoBanner: true, want: false},
{name: "paid and has hints", paidAccount: true, hintBalance: 5, want: false},
{name: "no_banner overrides everything", hasNoBanner: true, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Eligible(tt.paidAccount, tt.hintBalance, tt.hasNoBanner); got != tt.want {
t.Errorf("Eligible(%v,%d,%v) = %v, want %v", tt.paidAccount, tt.hintBalance, tt.hasNoBanner, got, tt.want)
}
})
}
}
func TestComputeActiveSet(t *testing.T) {
now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.UTC)
past := now.Add(-24 * time.Hour)
+15
View File
@@ -14,6 +14,7 @@ import (
"scrabble/backend/internal/lobby"
"scrabble/backend/internal/postgres"
"scrabble/backend/internal/ratewatch"
"scrabble/backend/internal/robokassa"
"scrabble/backend/internal/robot"
"scrabble/backend/internal/telemetry"
)
@@ -64,6 +65,9 @@ type Config struct {
// RendererURL is the base URL of the internal image-render sidecar (e.g.
// http://renderer:8090). Empty disables the PNG export artifact.
RendererURL string
// Robokassa configures the direct-rail (RUB) payment provider. An empty MerchantLogin
// leaves the direct order and Result-callback endpoints unregistered.
Robokassa robokassa.Config
}
// Defaults applied when the corresponding environment variable is unset.
@@ -153,6 +157,13 @@ func Load() (Config, error) {
AdminTo: os.Getenv("BACKEND_ADMIN_EMAIL"),
}
robo := robokassa.Config{
MerchantLogin: os.Getenv("BACKEND_ROBOKASSA_MERCHANT_LOGIN"),
Password1: os.Getenv("BACKEND_ROBOKASSA_PASSWORD1"),
Password2: os.Getenv("BACKEND_ROBOKASSA_PASSWORD2"),
IsTest: os.Getenv("BACKEND_ROBOKASSA_TEST") == "1",
}
c := Config{
HTTPAddr: envOr("BACKEND_HTTP_ADDR", defaultHTTPAddr),
GRPCAddr: envOr("BACKEND_GRPC_ADDR", defaultGRPCAddr),
@@ -170,6 +181,7 @@ func Load() (Config, error) {
GuestRetention: guestRetention,
ExportSignKey: os.Getenv("BACKEND_EXPORT_SIGN_KEY"),
RendererURL: os.Getenv("BACKEND_RENDERER_URL"),
Robokassa: robo,
}
if err := c.validate(); err != nil {
return Config{}, err
@@ -222,6 +234,9 @@ func (c Config) validate() error {
return fmt.Errorf("config: BACKEND_PUBLIC_BASE_URL %q must be an absolute URL (scheme://host)", c.PublicBaseURL)
}
}
if c.Robokassa.MerchantLogin != "" && (c.Robokassa.Password1 == "" || c.Robokassa.Password2 == "") {
return fmt.Errorf("config: BACKEND_ROBOKASSA_PASSWORD1 and BACKEND_ROBOKASSA_PASSWORD2 must be set when BACKEND_ROBOKASSA_MERCHANT_LOGIN is")
}
return nil
}
+51 -4
View File
@@ -18,6 +18,8 @@ import (
"scrabble/backend/internal/account"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/notify"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/session"
)
// Service is the game domain: it drives the engine over a single match, persists
@@ -50,6 +52,11 @@ type Service struct {
// its asynchronous TriggerMove); nil disables the fast path (the scan still covers
// these games). Kept as a func so the game package never imports the robot package.
aiTrigger func(gameID uuid.UUID)
// hintWallet is the payments surface the online-game hint path spends against (the
// segmented, context-aware hint balance). It is set by SetHintWallet during wiring; when
// nil, only the free per-game allowance is served (no purchased hints). vs_ai hints are
// wallet-free and never touch it.
hintWallet HintWallet
// clearNudges, when set, marks the actor's pending nudges in a game read once they
// have committed a move (a nudge answered by moving stops counting as unread). It is
// best-effort and kept as a func so the game package never imports the social package.
@@ -105,6 +112,39 @@ func (svc *Service) SetAITrigger(trigger func(gameID uuid.UUID)) {
svc.aiTrigger = trigger
}
// HintWallet is the payments surface the online-game hint path uses: the context-aware hint
// balance (HintsAvailable) and a one-hint spend (SpendHint), both keyed by the trusted execution
// context and the account's present identity sources. *payments.Service satisfies it.
type HintWallet interface {
HintsAvailable(ctx context.Context, accountID uuid.UUID, cxt payments.Context, present []payments.Source) (int, error)
SpendHint(ctx context.Context, accountID uuid.UUID, cxt payments.Context, present []payments.Source) (bool, error)
}
// SetHintWallet installs the payments hint wallet the online-game hint path spends against. It
// must be called during startup wiring; the default (nil) serves only the free per-game allowance.
func (svc *Service) SetHintWallet(w HintWallet) {
svc.hintWallet = w
}
// walletContext resolves the payments gate inputs for an account on the current request: the
// trusted execution context (from the session platform carried on ctx; absent ⇒ untrusted) and
// the account's present identity sources (which chip/benefit segments are awake, §6).
func (svc *Service) walletContext(ctx context.Context, accountID uuid.UUID) (payments.Context, []payments.Source, error) {
var cxt payments.Context
if p, ok := session.PlatformFromContext(ctx); ok {
cxt = payments.NewContext(p.Kind, p.Subtype)
}
ids, err := svc.accounts.Identities(ctx, accountID)
if err != nil {
return payments.Context{}, nil, err
}
kinds := make([]string, len(ids))
for i, id := range ids {
kinds[i] = id.Kind
}
return cxt, payments.PresentSources(kinds), nil
}
// SetNudgeClearer installs the hook that marks a mover's pending nudges read after
// their move commits. It must be called during startup wiring; the default (nil)
// leaves nudges to be cleared only when the recipient opens the move history or chat.
@@ -1121,13 +1161,20 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
}
return HintResult{Move: move}, nil
}
acc, err := svc.accounts.GetByID(ctx, accountID)
cxt, present, err := svc.walletContext(ctx, accountID)
if err != nil {
return HintResult{}, err
}
wallet := 0
if svc.hintWallet != nil {
wallet, err = svc.hintWallet.HintsAvailable(ctx, accountID, cxt, present)
if err != nil {
return HintResult{}, err
}
}
used := pre.Seats[seat].HintsUsed
fromAllowance := used < pre.HintsPerPlayer
if !fromAllowance && acc.HintBalance <= 0 {
if !fromAllowance && wallet <= 0 {
return HintResult{}, ErrNoHintsLeft
}
@@ -1142,9 +1189,9 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
return HintResult{}, ErrNoHintAvailable
}
walletAfter := acc.HintBalance
walletAfter := wallet
if !fromAllowance {
spent, err := svc.accounts.SpendHint(ctx, accountID)
spent, err := svc.hintWallet.SpendHint(ctx, accountID, cxt, present)
if err != nil {
return HintResult{}, err
}
+48 -15
View File
@@ -15,13 +15,15 @@ import (
"scrabble/backend/internal/account"
"scrabble/backend/internal/ads"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/server"
)
// bannerServer assembles a console-capable server with the ads domain wired.
func bannerServer(t *testing.T) (*server.Server, *ads.Service) {
func bannerServer(t *testing.T) (*server.Server, *ads.Service, *payments.Service) {
t.Helper()
adsSvc := ads.NewService(ads.NewStore(testDB))
paySvc := newPaymentsService()
srv := server.New(":0", server.Deps{
Logger: zap.NewNop(),
Accounts: account.NewStore(testDB),
@@ -29,8 +31,9 @@ func bannerServer(t *testing.T) (*server.Server, *ads.Service) {
Registry: testRegistry,
DictDir: dictDir(),
Ads: adsSvc,
Payments: paySvc,
})
return srv, adsSvc
return srv, adsSvc, paySvc
}
// findCampaign returns the id of the campaign with the given name, or fails.
@@ -71,7 +74,7 @@ func defaultCampaign(t *testing.T, svc *ads.Service) ads.Campaign {
// reorder/delete.
func TestBannerConsoleCRUD(t *testing.T) {
ctx := context.Background()
srv, adsSvc := bannerServer(t)
srv, adsSvc, _ := bannerServer(t)
h := srv.Handler()
base := "http://admin.test/_gm"
const origin = "http://admin.test"
@@ -151,7 +154,7 @@ func TestBannerConsoleCRUD(t *testing.T) {
// unrelated campaign's URL must be refused.
func TestBannerMessageOwnership(t *testing.T) {
ctx := context.Background()
srv, adsSvc := bannerServer(t)
srv, adsSvc, _ := bannerServer(t)
h := srv.Handler()
base := "http://admin.test/_gm"
const origin = "http://admin.test"
@@ -207,10 +210,11 @@ type profileBanner struct {
// wallet each suppress it.
func TestBannerProfileEligibility(t *testing.T) {
ctx := context.Background()
srv, _ := bannerServer(t)
srv, _, pay := bannerServer(t)
accounts := account.NewStore(testDB)
id := provisionAccount(t)
// getBanner fetches the profile banner with no platform header (an untrusted context).
getBanner := func() profileBanner {
t.Helper()
rec := userGet(t, srv, "/api/v1/user/profile", id)
@@ -223,10 +227,27 @@ func TestBannerProfileEligibility(t *testing.T) {
}
return p
}
// getBannerTG fetches the profile banner in a trusted Telegram context — the account's
// telegram identity makes telegram the applicable origin for its benefits.
getBannerTG := func() profileBanner {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/user/profile", nil)
req.Header.Set("X-User-ID", id.String())
req.Header.Set("X-Platform", "telegram/android")
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("profile = %d, want 200", rec.Code)
}
var p profileBanner
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
t.Fatalf("decode profile: %v", err)
}
return p
}
// A free account with an empty hint wallet and no role is eligible.
p := getBanner()
if p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
// A free account with no role and no benefit is eligible.
if p := getBanner(); p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
t.Fatalf("eligible account: banner=%v", p.Banner)
}
@@ -241,19 +262,31 @@ func TestBannerProfileEligibility(t *testing.T) {
t.Fatalf("revoke role: %v", err)
}
// A non-empty hint wallet suppresses it.
if _, err := accounts.GrantHints(ctx, id, 5); err != nil {
// A hint wallet no longer suppresses the banner — hints and no-ads are distinct benefits now.
if err := pay.Grant(ctx, id, payments.SourceTelegram, 5, 0, false); err != nil {
t.Fatalf("grant hints: %v", err)
}
if p := getBanner(); p.Banner != nil {
t.Fatal("a non-empty hint wallet still shows the banner")
if p := getBannerTG(); p.Banner == nil {
t.Fatal("a hint wallet must NOT suppress the banner")
}
// An active no-ads benefit applicable in the context suppresses the banner.
if err := pay.Grant(ctx, id, payments.SourceTelegram, 0, 30, false); err != nil {
t.Fatalf("grant no-ads: %v", err)
}
if p := getBannerTG(); p.Banner != nil {
t.Fatal("an active no-ads benefit must suppress the banner")
}
// Fail-closed: without a trusted platform the same benefit does not apply, so the banner shows.
if p := getBanner(); p.Banner == nil {
t.Fatal("an untrusted context must not apply the no-ads benefit (banner should show)")
}
}
// TestBannerSurvivesProfileUpdate guards that a profile update (e.g. a language switch) returns the
// banner block too, so the client's profile keeps the banner instead of losing it until reload.
func TestBannerSurvivesProfileUpdate(t *testing.T) {
srv, _ := bannerServer(t)
srv, _, _ := bannerServer(t)
id := provisionAccount(t)
body := `{"display_name":"Tester","preferred_language":"ru","time_zone":"UTC","away_start":"00:00",` +
@@ -283,7 +316,7 @@ func TestBannerSurvivesProfileUpdate(t *testing.T) {
// default campaign stays plain (colours + urgent are ignored for it).
func TestBannerConsoleColorsAndUrgent(t *testing.T) {
ctx := context.Background()
srv, adsSvc := bannerServer(t)
srv, adsSvc, _ := bannerServer(t)
h := srv.Handler()
base := "http://admin.test/_gm"
const origin = "http://admin.test"
@@ -351,7 +384,7 @@ func TestBannerConsoleColorsAndUrgent(t *testing.T) {
// otherwise suppress the banner.
func TestBannerUrgentBypassesEligibility(t *testing.T) {
ctx := context.Background()
srv, adsSvc := bannerServer(t)
srv, adsSvc, _ := bannerServer(t)
accounts := account.NewStore(testDB)
id := provisionAccount(t)
+13 -10
View File
@@ -14,6 +14,8 @@ import (
"scrabble/backend/internal/account"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/game"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/session"
)
// TestListForAccount checks the lobby "my games" query: it returns exactly the
@@ -401,8 +403,13 @@ func gameStatus(t *testing.T, svc *game.Service, id uuid.UUID) (status, endReaso
// TestHintPolicy exercises the per-game allowance, the profile wallet and the
// disabled switch.
func TestHintPolicy(t *testing.T) {
ctx := context.Background()
// A trusted platform context so the online hint wallet (payments) is reachable; a provisioned
// account carries a telegram identity, so the telegram origin is the applicable one here.
ctx := session.WithPlatform(context.Background(),
session.Platform{Kind: session.PlatformKindTelegram, Subtype: session.SubtypeAndroid})
svc := newGameService()
pay := newPaymentsService()
svc.SetHintWallet(pay) // share the handle so a grant invalidates the wallet the game reads
seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)}
seed := openingSeed(t)
g, err := svc.Create(ctx, game.CreateParams{
@@ -428,7 +435,11 @@ func TestHintPolicy(t *testing.T) {
if _, err := svc.Hint(ctx, g.ID, seats[0]); !errors.Is(err, game.ErrNoHintsLeft) {
t.Fatalf("second hint = %v, want ErrNoHintsLeft", err)
}
setHintBalance(t, seats[0], 2)
// Grant 2 hints on the telegram origin through the service so its read cache is invalidated
// (a raw insert would leave the cache warmed at zero by the allowance hint above).
if err := pay.Grant(ctx, seats[0], payments.SourceTelegram, 2, 0, false); err != nil {
t.Fatalf("grant hints: %v", err)
}
res, err := svc.Hint(ctx, g.ID, seats[0]) // spends the wallet
if err != nil {
t.Fatalf("wallet hint: %v", err)
@@ -603,14 +614,6 @@ func setAway(t *testing.T, id uuid.UUID, tz, start, end string) {
}
}
func setHintBalance(t *testing.T, id uuid.UUID, n int) {
t.Helper()
if _, err := testDB.ExecContext(context.Background(),
`UPDATE backend.accounts SET hint_balance = $1 WHERE account_id = $2`, n, id); err != nil {
t.Fatalf("set hint balance: %v", err)
}
}
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
+34
View File
@@ -17,6 +17,7 @@ import (
"scrabble/backend/internal/engine"
"scrabble/backend/internal/game"
"scrabble/backend/internal/lobby"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/robot"
"scrabble/backend/internal/social"
)
@@ -42,9 +43,42 @@ func newGameService() *game.Service {
zap.NewNop(),
)
svc.SetFirstMoveEntropy(seatZeroFirstMove)
svc.SetHintWallet(newPaymentsService())
return svc
}
// newPaymentsService builds a payments service over the shared pool (its own in-process read
// cache), for wiring the game hint wallet and the account-merge fold in the integration suite.
func newPaymentsService() *payments.Service {
return payments.NewService(payments.NewStore(testDB))
}
// seedBenefit writes a payments benefit row for an account+origin directly (bypassing the
// service), used to stand up wallet state a test then spends or merges. A non-zero hints count
// and/or the forever flag are set; a caller wanting a no-ads term sets it via seedBenefitUntil.
func seedBenefit(t *testing.T, id uuid.UUID, origin string, hints int, forever bool) {
t.Helper()
if _, err := testDB.ExecContext(context.Background(),
`INSERT INTO payments.benefits (account_id, origin, hints, ads_forever) VALUES ($1,$2,$3,$4)
ON CONFLICT (account_id, origin) DO UPDATE SET hints = EXCLUDED.hints, ads_forever = EXCLUDED.ads_forever`,
id, origin, hints, forever); err != nil {
t.Fatalf("seed benefit: %v", err)
}
}
// readBenefit reads an account's benefit row for an origin: the hint count and the forever flag
// (both zero/false when the row is absent).
func readBenefit(t *testing.T, id uuid.UUID, origin string) (hints int, forever bool) {
t.Helper()
err := testDB.QueryRowContext(context.Background(),
`SELECT hints, ads_forever FROM payments.benefits WHERE account_id=$1 AND origin=$2`, id, origin).
Scan(&hints, &forever)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("read benefit: %v", err)
}
return hints, forever
}
// seatZeroFirstMove is a first-move-draw entropy factory that always elects the first
// listed account as the leader, keeping the integration suite's turn order stable
// despite the real draw's randomness: the first contender draws a blank — the best
+9 -18
View File
@@ -58,14 +58,6 @@ func bestMoveCount(t *testing.T, id uuid.UUID) int {
return n
}
func setWallet(t *testing.T, id uuid.UUID, hints int, paid bool) {
t.Helper()
if _, err := testDB.ExecContext(context.Background(),
`UPDATE backend.accounts SET hint_balance=$2, paid_account=$3 WHERE account_id=$1`, id, hints, paid); err != nil {
t.Fatalf("set wallet: %v", err)
}
}
func bindEmailIdentity(t *testing.T, acc uuid.UUID, email string) {
t.Helper()
if _, err := testDB.ExecContext(context.Background(),
@@ -131,6 +123,7 @@ func TestAccountMergeCore(t *testing.T) {
ctx := context.Background()
store := account.NewStore(testDB)
merger := accountmerge.NewMerger(testDB)
merger.SetPayments(newPaymentsService())
primary := provisionAccount(t)
secondary := provisionAccount(t)
@@ -140,8 +133,8 @@ func TestAccountMergeCore(t *testing.T) {
setStats(t, secondary, 3, 1, 2, 400, 80)
setStatsCounts(t, primary, 100, 5)
setStatsCounts(t, secondary, 50, 8)
setWallet(t, primary, 2, false)
setWallet(t, secondary, 5, true)
seedBenefit(t, primary, "telegram", 2, false)
seedBenefit(t, secondary, "telegram", 5, true) // hints sum, forever OR-s on merge
// Best moves: secondary's scrabble_en (80) beats primary's (50) and is kept; secondary's
// scrabble_ru (30) is new to primary and carried over.
setBestMove(t, primary, "scrabble_en", 50)
@@ -165,15 +158,13 @@ func TestAccountMergeCore(t *testing.T) {
t.Error("secondary stats row should be deleted after merge")
}
acc, err := store.GetByID(ctx, primary)
if err != nil {
t.Fatalf("get primary: %v", err)
// The payments wallet merged by origin: hints sum (2+5) and the forever flag OR-s; the
// deprecated accounts.hint_balance / paid_account columns are no longer touched by a merge.
if hints, forever := readBenefit(t, primary, "telegram"); hints != 7 || !forever {
t.Errorf("merged telegram benefit = hints %d forever %v, want 7/true", hints, forever)
}
if acc.HintBalance != 7 {
t.Errorf("hint balance = %d, want 7", acc.HintBalance)
}
if !acc.PaidAccount {
t.Error("paid_account should be true (ORed from secondary)")
if hints, _ := readBenefit(t, secondary, "telegram"); hints != 0 {
t.Errorf("secondary benefit should be cleared after merge, got hints %d", hints)
}
if owner, ok, _ := store.AccountIDByIdentity(ctx, account.KindEmail, email); !ok || owner != primary {
@@ -0,0 +1,113 @@
//go:build integration
package inttest
import (
"context"
"testing"
"github.com/google/uuid"
"scrabble/backend/internal/payments"
)
// methodPrice is one per-method money price for a seeded chip pack.
type methodPrice struct {
method string
currency string
amount int64
}
// seedPackProduct creates an active chip pack: a product carrying the chips atom and a money price
// per method. It returns the product id.
func seedPackProduct(t *testing.T, chips int, prices ...methodPrice) uuid.UUID {
t.Helper()
ctx := context.Background()
prod := uuid.New()
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product (product_id, title, active) VALUES ($1,'test pack',true)`, prod); err != nil {
t.Fatalf("seed pack product: %v", err)
}
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product_item (product_id, atom_type, quantity) VALUES ($1,'chips',$2)`, prod, chips); err != nil {
t.Fatalf("seed chips item: %v", err)
}
for _, p := range prices {
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product_price (product_id, method, currency, amount) VALUES ($1,$2,$3,$4)`,
prod, p.method, p.currency, p.amount); err != nil {
t.Fatalf("seed pack price %s: %v", p.method, err)
}
}
return prod
}
// findCatalogProduct returns the projected storefront product for id in the context (the catalog
// is global, so tests assert by id rather than count — testDB is shared).
func findCatalogProduct(t *testing.T, svc *payments.Service, cxt payments.Context, id uuid.UUID) (payments.CatalogProduct, bool) {
t.Helper()
view, err := svc.Catalog(context.Background(), cxt)
if err != nil {
t.Fatalf("catalog: %v", err)
}
for _, p := range view.Products {
if p.ProductID == id.String() {
return p, true
}
}
return payments.CatalogProduct{}, false
}
// TestPaymentsCatalogByContext verifies the storefront projects a value at its chip price in every
// context and a chip pack at the context method's money price, over Postgres.
func TestPaymentsCatalogByContext(t *testing.T) {
svc := newPaymentsService()
value := seedValueProduct(t, 500, 250, 0)
pack := seedPackProduct(t, 100,
methodPrice{"vk", "VOTE", 20},
methodPrice{"telegram", "XTR", 25},
methodPrice{"direct", "RUB", 14900},
)
for _, kind := range []string{"vk", "telegram", "direct"} {
v, ok := findCatalogProduct(t, svc, payments.NewContext(kind, "web"), value)
if !ok {
t.Fatalf("value missing in %s context", kind)
}
if v.Kind != "value" || v.Chips != 500 || v.MoneyCurrency != "" {
t.Errorf("value in %s = %+v, want kind=value chips=500 no money", kind, v)
}
}
cases := []struct {
kind string
amount int64
currency string
}{
{"vk", 20, "VOTE"},
{"telegram", 25, "XTR"},
{"direct", 14900, "RUB"},
}
for _, tc := range cases {
p, ok := findCatalogProduct(t, svc, payments.NewContext(tc.kind, "web"), pack)
if !ok {
t.Fatalf("pack missing in %s context", tc.kind)
}
if p.Kind != "pack" || p.Chips != 0 || p.MoneyAmount != tc.amount || p.MoneyCurrency != tc.currency {
t.Errorf("pack in %s = %+v, want kind=pack amount=%d currency=%s", tc.kind, p, tc.amount, tc.currency)
}
}
}
// TestPaymentsCatalogExcludesDeactivated verifies a soft-deleted product drops out of the storefront.
func TestPaymentsCatalogExcludesDeactivated(t *testing.T) {
svc := newPaymentsService()
prod := seedValueProduct(t, 100, 10, 0)
if _, err := testDB.ExecContext(context.Background(),
`UPDATE payments.product SET active=false WHERE product_id=$1`, prod); err != nil {
t.Fatalf("deactivate: %v", err)
}
if _, ok := findCatalogProduct(t, svc, payments.NewContext("direct", "web"), prod); ok {
t.Error("deactivated product must not appear in the storefront")
}
}
@@ -0,0 +1,469 @@
//go:build integration
package inttest
import (
"context"
"database/sql"
"errors"
"testing"
"github.com/google/uuid"
"scrabble/backend/internal/payments"
)
// orderStatus reads an order's status.
func orderStatus(t *testing.T, orderID uuid.UUID) string {
t.Helper()
var status string
if err := testDB.QueryRowContext(context.Background(),
`SELECT status FROM payments.orders WHERE order_id=$1`, orderID).Scan(&status); err != nil {
t.Fatalf("read order status: %v", err)
}
return status
}
// readRisk reads an account's payment-risk row (abuse flag + accumulated loss), or (false, 0) when
// none exists.
func readRisk(t *testing.T, acc uuid.UUID) (abuse bool, loss int64) {
t.Helper()
err := testDB.QueryRowContext(context.Background(),
`SELECT abuse, loss_chips FROM payments.account_risk WHERE account_id=$1`, acc).Scan(&abuse, &loss)
if errors.Is(err, sql.ErrNoRows) {
return false, 0
}
if err != nil {
t.Fatalf("read risk: %v", err)
}
return abuse, loss
}
// TestPaymentsOrderFundCreditsOnce verifies the intake path over Postgres: creating an order then
// funding it credits the funded segment exactly once, and a replayed callback (the same order)
// credits nothing more — the ledger idempotency index holds.
func TestPaymentsOrderFundCreditsOnce(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
prod := seedPackProduct(t, 100, methodPrice{method: "direct", currency: "RUB", amount: 14900}) // 149.00 RUB funds 100 chips
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
if err != nil {
t.Fatalf("create order: %v", err)
}
if res.Amount.Minor() != 14900 || res.Amount.Currency() != payments.CurrencyRUB {
t.Fatalf("order amount = %s, want 149.00 RUB", res.Amount)
}
if orderStatus(t, res.OrderID) != "pending" {
t.Errorf("new order status = %s, want pending", orderStatus(t, res.OrderID))
}
paid, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
out, err := svc.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), paid)
if err != nil {
t.Fatalf("fund: %v", err)
}
if out.AlreadyCredited || out.Chips != 100 || out.Source != payments.SourceDirect {
t.Fatalf("fund outcome = %+v, want 100 chips to direct, not already-credited", out)
}
if got := readBalance(t, acc, "direct"); got != 100 {
t.Errorf("balance after fund = %d, want 100", got)
}
if ledgerRows(t, acc, "fund") != 1 {
t.Errorf("fund ledger rows = %d, want 1", ledgerRows(t, acc, "fund"))
}
if orderStatus(t, res.OrderID) != "paid" {
t.Errorf("order status after fund = %s, want paid", orderStatus(t, res.OrderID))
}
// A replayed callback for the same order is rejected by the unique index: no second credit.
out2, err := svc.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), paid)
if err != nil {
t.Fatalf("duplicate fund: %v", err)
}
if !out2.AlreadyCredited {
t.Error("duplicate callback not flagged AlreadyCredited")
}
if got := readBalance(t, acc, "direct"); got != 100 {
t.Errorf("balance after duplicate = %d, want 100 (credited once)", got)
}
if ledgerRows(t, acc, "fund") != 1 {
t.Error("duplicate callback wrote a second fund ledger row")
}
}
// TestPaymentsVKOrderFundCredits exercises the VK Votes rail over Postgres: a VK order prices the
// pack in votes; the get_item lookup returns its title and vote price; a chargeable
// order_status_change credits the vk segment exactly once (idempotent on VK's own order id).
func TestPaymentsVKOrderFundCredits(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
prod := seedPackProduct(t, 200, methodPrice{method: "vk", currency: "VOTE", amount: 30})
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("vk", "web"), []payments.Source{payments.SourceVK}, prod, "vk")
if err != nil {
t.Fatalf("create vk order: %v", err)
}
if res.Amount.Currency() != payments.CurrencyVote || res.Amount.Minor() != 30 {
t.Fatalf("vk order amount = %s, want 30 VOTE", res.Amount)
}
// get_item phase: title + vote price.
title, amount, err := svc.OrderItem(ctx, res.OrderID)
if err != nil {
t.Fatalf("order item: %v", err)
}
if title == "" || amount.Minor() != 30 || amount.Currency() != payments.CurrencyVote {
t.Errorf("order item = %q / %s, want a title + 30 VOTE", title, amount)
}
// order_status_change phase: VK's own order id is the idempotency key.
paid, _ := payments.MoneyFromMinor(30, payments.CurrencyVote)
out, err := svc.Fund(ctx, res.OrderID, "vk", "vk-order-777", paid)
if err != nil {
t.Fatalf("vk fund: %v", err)
}
if out.AlreadyCredited || out.Chips != 200 || out.Source != payments.SourceVK {
t.Fatalf("vk fund outcome = %+v, want 200 chips credited to vk", out)
}
if got := readBalance(t, acc, "vk"); got != 200 {
t.Errorf("vk balance after fund = %d, want 200", got)
}
// A duplicate VK callback (same VK order id) credits nothing more.
out2, err := svc.Fund(ctx, res.OrderID, "vk", "vk-order-777", paid)
if err != nil {
t.Fatalf("duplicate vk fund: %v", err)
}
if !out2.AlreadyCredited {
t.Error("duplicate VK callback not flagged AlreadyCredited")
}
if got := readBalance(t, acc, "vk"); got != 200 {
t.Errorf("vk balance after duplicate = %d, want 200 (credited once)", got)
}
}
// TestPaymentsTelegramStarsRail exercises the Telegram Stars rail over Postgres: an order prices the
// pack in whole stars (XTR); a pre_checkout on the pending order is approved; the forwarded payment
// credits the telegram segment exactly once (idempotent on the Telegram charge id); and a
// pre_checkout after the order is paid is declined (a reusable invoice link paid twice).
func TestPaymentsTelegramStarsRail(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
prod := seedPackProduct(t, 50, methodPrice{method: "telegram", currency: "XTR", amount: 40}) // 40 stars fund 50 chips
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("telegram", "android"), []payments.Source{payments.SourceTelegram}, prod, "telegram")
if err != nil {
t.Fatalf("create telegram order: %v", err)
}
if res.Amount.Currency() != payments.CurrencyStar || res.Amount.Minor() != 40 {
t.Fatalf("telegram order amount = %s, want 40 XTR", res.Amount)
}
// pre_checkout on the pending order: approved, and it reports the account for reason localisation.
starAmt, _ := payments.MoneyFromMinor(40, payments.CurrencyStar)
pc, err := svc.ValidatePreCheckout(ctx, res.OrderID, starAmt)
if err != nil {
t.Fatalf("pre_checkout: %v", err)
}
if !pc.OK || pc.AccountID != acc {
t.Fatalf("pre_checkout = %+v, want approved for account %s", pc, acc)
}
// The forwarded successful_payment credits once, idempotent on the Telegram charge id.
out, err := svc.Fund(ctx, res.OrderID, "telegram", "tg-charge-1", starAmt)
if err != nil {
t.Fatalf("telegram fund: %v", err)
}
if out.AlreadyCredited || out.Chips != 50 || out.Source != payments.SourceTelegram {
t.Fatalf("telegram fund outcome = %+v, want 50 chips credited to telegram", out)
}
if got := readBalance(t, acc, "telegram"); got != 50 {
t.Errorf("telegram balance after fund = %d, want 50", got)
}
// A retried forward (same charge id, e.g. a lost ack) credits nothing more.
out2, err := svc.Fund(ctx, res.OrderID, "telegram", "tg-charge-1", starAmt)
if err != nil {
t.Fatalf("duplicate telegram fund: %v", err)
}
if !out2.AlreadyCredited {
t.Error("retried forward not flagged AlreadyCredited")
}
if got := readBalance(t, acc, "telegram"); got != 50 {
t.Errorf("telegram balance after retry = %d, want 50 (credited once)", got)
}
// pre_checkout after the order is paid: declined (the reusable-link double-pay guard).
pc2, err := svc.ValidatePreCheckout(ctx, res.OrderID, starAmt)
if err != nil {
t.Fatalf("pre_checkout after paid: %v", err)
}
if pc2.OK || pc2.Reason != payments.PreCheckoutAlreadyPaid {
t.Errorf("pre_checkout after paid = %+v, want a decline with already_paid", pc2)
}
}
// TestPaymentsTelegramPreCheckoutDeclines covers the pre_checkout decline reasons: an unknown order
// and an amount that no longer matches.
func TestPaymentsTelegramPreCheckoutDeclines(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
starAmt, _ := payments.MoneyFromMinor(40, payments.CurrencyStar)
// An unknown order id declines as gone, with no account to localise against.
pc, err := svc.ValidatePreCheckout(ctx, uuid.New(), starAmt)
if err != nil {
t.Fatalf("pre_checkout unknown: %v", err)
}
if pc.OK || pc.Reason != payments.PreCheckoutGone || pc.AccountID != (uuid.UUID{}) {
t.Errorf("pre_checkout unknown = %+v, want a gone decline with no account", pc)
}
// A pending order validated at the wrong amount declines as price-changed.
acc := uuid.New()
prod := seedPackProduct(t, 100, methodPrice{method: "telegram", currency: "XTR", amount: 80})
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("telegram", "android"), []payments.Source{payments.SourceTelegram}, prod, "telegram")
if err != nil {
t.Fatalf("create telegram order: %v", err)
}
wrong, _ := payments.MoneyFromMinor(40, payments.CurrencyStar)
pc2, err := svc.ValidatePreCheckout(ctx, res.OrderID, wrong)
if err != nil {
t.Fatalf("pre_checkout mismatch: %v", err)
}
if pc2.OK || pc2.Reason != payments.PreCheckoutPriceChanged {
t.Errorf("pre_checkout mismatch = %+v, want a price_changed decline", pc2)
}
}
// TestPaymentsFundAmountMismatch verifies a callback whose paid amount does not match the order is
// refused and credits nothing (§9: verify the amount after matching by order id).
func TestPaymentsFundAmountMismatch(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
prod := seedPackProduct(t, 100, methodPrice{method: "direct", currency: "RUB", amount: 14900})
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
if err != nil {
t.Fatalf("create order: %v", err)
}
underpaid, _ := payments.MoneyFromMinor(100, payments.CurrencyRUB)
if _, err := svc.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), underpaid); !errors.Is(err, payments.ErrAmountMismatch) {
t.Fatalf("fund = %v, want ErrAmountMismatch", err)
}
if got := readBalance(t, acc, "direct"); got != 0 {
t.Errorf("balance = %d, want 0 (nothing credited on mismatch)", got)
}
if ledgerRows(t, acc, "fund") != 0 {
t.Error("fund ledger row written on an amount mismatch")
}
}
// TestPaymentsEventDispatchDrain verifies the payment_events dispatcher queue: a recorded event is
// returned as undispatched until marked, then drops out (so the dispatcher delivers it once).
func TestPaymentsEventDispatchDrain(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
if err := svc.RecordPaymentEvent(ctx, acc, nil, "succeeded", []byte(`{"chips":10,"source":"direct"}`)); err != nil {
t.Fatalf("record event: %v", err)
}
// testDB is shared, so filter the queue to our account.
find := func() *payments.PaymentEvent {
evs, err := svc.UndispatchedEvents(ctx, 100)
if err != nil {
t.Fatalf("undispatched: %v", err)
}
for i := range evs {
if evs[i].AccountID == acc {
return &evs[i]
}
}
return nil
}
mine := find()
if mine == nil {
t.Fatal("recorded event not in the undispatched queue")
}
if mine.Type != "succeeded" {
t.Errorf("event type = %s, want succeeded", mine.Type)
}
if err := svc.MarkEventDispatched(ctx, mine.EventID); err != nil {
t.Fatalf("mark dispatched: %v", err)
}
if find() != nil {
t.Error("event still undispatched after MarkEventDispatched")
}
}
// TestPaymentsExpiredOrderStillCredits verifies an expired pending order is still honoured by a
// later valid callback (§9/D23: expiry is cosmetic, the money is real).
func TestPaymentsExpiredOrderStillCredits(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
prod := seedPackProduct(t, 100, methodPrice{method: "direct", currency: "RUB", amount: 14900})
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
if err != nil {
t.Fatalf("create order: %v", err)
}
// Age the order well past the configured TTL, then sweep it to expired.
if _, err := testDB.ExecContext(ctx,
`UPDATE payments.orders SET created_at = now() - interval '1 day' WHERE order_id=$1`, res.OrderID); err != nil {
t.Fatalf("age order: %v", err)
}
if n, err := svc.ExpireOrders(ctx); err != nil || n < 1 {
t.Fatalf("expire orders = %d (err %v), want at least 1", n, err)
}
if orderStatus(t, res.OrderID) != "expired" {
t.Fatalf("order status = %s, want expired before the late callback", orderStatus(t, res.OrderID))
}
paid, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
out, err := svc.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), paid)
if err != nil {
t.Fatalf("fund after expiry: %v", err)
}
if out.AlreadyCredited || out.Chips != 100 {
t.Fatalf("fund outcome = %+v, want a fresh 100-chip credit", out)
}
if got := readBalance(t, acc, "direct"); got != 100 {
t.Errorf("balance = %d, want 100 (expired order honoured)", got)
}
if orderStatus(t, res.OrderID) != "paid" {
t.Errorf("order status = %s, want paid after the honoured callback", orderStatus(t, res.OrderID))
}
}
// fundedOrder creates and funds an order for chips in the direct rail, returning its id and account.
func fundedOrder(t *testing.T, svc *payments.Service, chips int, priceMinor int64) (uuid.UUID, uuid.UUID) {
t.Helper()
ctx := context.Background()
acc := uuid.New()
prod := seedPackProduct(t, chips, methodPrice{method: "direct", currency: "RUB", amount: priceMinor})
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
if err != nil {
t.Fatalf("create order: %v", err)
}
paid, _ := payments.MoneyFromMinor(priceMinor, payments.CurrencyRUB)
if _, err := svc.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), paid); err != nil {
t.Fatalf("fund: %v", err)
}
return res.OrderID, acc
}
// TestPaymentsRefundFull reverses a fully-unspent order: all chips are clawed back, no loss/abuse.
func TestPaymentsRefundFull(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
orderID, acc := fundedOrder(t, svc, 100, 14900)
refunded, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
out, err := svc.Refund(ctx, orderID, "robokassa", "rk-refund-1", refunded)
if err != nil {
t.Fatalf("refund: %v", err)
}
if out.AlreadyRefunded || out.Revoked != 100 || out.Loss != 0 || out.Source != payments.SourceDirect {
t.Fatalf("refund outcome = %+v, want 100 revoked, 0 loss", out)
}
if got := readBalance(t, acc, "direct"); got != 0 {
t.Errorf("balance after refund = %d, want 0", got)
}
if ledgerRows(t, acc, "refund") != 1 {
t.Errorf("refund ledger rows = %d, want 1", ledgerRows(t, acc, "refund"))
}
if abuse, loss := readRisk(t, acc); abuse || loss != 0 {
t.Errorf("risk = (%v, %d), want (false, 0) — nothing was spent", abuse, loss)
}
// The order stays 'paid' — the refund lives in the ledger, not in the order status.
if orderStatus(t, orderID) != "paid" {
t.Errorf("order status = %s, want paid (refund is ledger-only)", orderStatus(t, orderID))
}
}
// TestPaymentsRefundAfterSpend reverses an order whose chips were partly spent: the reversal floors
// at 0 (never negative), and the unrecoverable remainder is recorded as a loss + abuse flag.
func TestPaymentsRefundAfterSpend(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
orderID, acc := fundedOrder(t, svc, 100, 14900)
// Simulate 70 chips already spent, leaving 30 in the funded segment.
if _, err := testDB.ExecContext(ctx,
`UPDATE payments.balances SET chips = 30 WHERE account_id = $1 AND source = 'direct'`, acc); err != nil {
t.Fatalf("simulate spend: %v", err)
}
refunded, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
out, err := svc.Refund(ctx, orderID, "robokassa", "rk-refund-2", refunded)
if err != nil {
t.Fatalf("refund: %v", err)
}
if out.Revoked != 30 || out.Loss != 70 {
t.Fatalf("refund outcome = %+v, want 30 revoked / 70 loss", out)
}
if got := readBalance(t, acc, "direct"); got != 0 {
t.Errorf("balance after refund = %d, want 0 (floored, never negative)", got)
}
if abuse, loss := readRisk(t, acc); !abuse || loss != 70 {
t.Errorf("risk = (%v, %d), want (true, 70)", abuse, loss)
}
}
// TestPaymentsRefundIdempotent verifies a replayed refund (same provider refund id) reverses nothing
// more — the ledger idempotency index holds.
func TestPaymentsRefundIdempotent(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
orderID, acc := fundedOrder(t, svc, 100, 14900)
refunded, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
if _, err := svc.Refund(ctx, orderID, "robokassa", "rk-refund-dup", refunded); err != nil {
t.Fatalf("first refund: %v", err)
}
// Re-credit the segment to prove the duplicate does not revoke again.
if _, err := testDB.ExecContext(ctx,
`UPDATE payments.balances SET chips = 100 WHERE account_id = $1 AND source = 'direct'`, acc); err != nil {
t.Fatalf("re-credit: %v", err)
}
out2, err := svc.Refund(ctx, orderID, "robokassa", "rk-refund-dup", refunded)
if err != nil {
t.Fatalf("duplicate refund: %v", err)
}
if !out2.AlreadyRefunded {
t.Error("duplicate refund not flagged AlreadyRefunded")
}
if got := readBalance(t, acc, "direct"); got != 100 {
t.Errorf("balance after duplicate refund = %d, want 100 (not revoked twice)", got)
}
if ledgerRows(t, acc, "refund") != 1 {
t.Errorf("refund ledger rows = %d, want 1 (duplicate wrote none)", ledgerRows(t, acc, "refund"))
}
}
// TestPaymentsRefundUnpaidOrder refuses to refund an order that was never funded.
func TestPaymentsRefundUnpaidOrder(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
prod := seedPackProduct(t, 100, methodPrice{method: "direct", currency: "RUB", amount: 14900})
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
if err != nil {
t.Fatalf("create order: %v", err)
}
refunded, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
if _, err := svc.Refund(ctx, res.OrderID, "robokassa", "rk-refund-x", refunded); !errors.Is(err, payments.ErrOrderNotPaid) {
t.Fatalf("refund of a pending order = %v, want ErrOrderNotPaid", err)
}
if abuse, loss := readRisk(t, acc); abuse || loss != 0 {
t.Errorf("risk = (%v, %d), want (false, 0) — no reversal on an unpaid order", abuse, loss)
}
}
+263
View File
@@ -0,0 +1,263 @@
//go:build integration
package inttest
import (
"context"
"database/sql"
"errors"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"github.com/pressly/goose/v3"
testcontainers "github.com/testcontainers/testcontainers-go"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
"scrabble/backend/internal/postgres"
"scrabble/backend/internal/postgres/migrations"
)
// isPgCode reports whether err is a PostgreSQL server error with the given
// SQLSTATE code.
func isPgCode(err error, code string) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == code
}
// TestPaymentsSchemaAndSeeds checks the payments schema, its role and the fixed
// seed rows are present after migration.
func TestPaymentsSchemaAndSeeds(t *testing.T) {
ctx := context.Background()
var atoms int
if err := testDB.QueryRowContext(ctx, "SELECT count(*) FROM payments.catalog_atom").Scan(&atoms); err != nil {
t.Fatalf("count catalog_atom: %v", err)
}
if atoms != 4 {
t.Errorf("catalog_atom rows = %d, want 4 (chips/hints/noads_days/tournament)", atoms)
}
var cfg int
if err := testDB.QueryRowContext(ctx, "SELECT count(*) FROM payments.config").Scan(&cfg); err != nil {
t.Fatalf("count config: %v", err)
}
if cfg != 1 {
t.Errorf("config rows = %d, want the single seeded row", cfg)
}
var roleExists bool
if err := testDB.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'payments')").Scan(&roleExists); err != nil {
t.Fatalf("check payments role: %v", err)
}
if !roleExists {
t.Error("payments role missing")
}
}
// TestPaymentsRoleConfinement proves the payments role is confined to its own
// schema: it can read payments.* but is denied on backend.*. The application
// itself connects as a superuser (which bypasses this), so this asserts the
// grants are correct as the stepping-stone to a real separate login; the runtime
// wall for the superuser pool is the import-boundary test in the payments package.
func TestPaymentsRoleConfinement(t *testing.T) {
ctx := context.Background()
tx, err := testDB.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("begin tx: %v", err)
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, "SET LOCAL ROLE payments"); err != nil {
t.Fatalf("SET LOCAL ROLE payments: %v", err)
}
// The payments role can read its own schema.
var n int
if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM payments.config").Scan(&n); err != nil {
t.Errorf("payments role denied on payments.config (grants wrong): %v", err)
}
// The payments role must NOT reach the backend schema.
err = tx.QueryRowContext(ctx, "SELECT count(*) FROM backend.accounts").Scan(&n)
if err == nil {
t.Fatal("payments role could read backend.accounts — cross-schema isolation broken")
}
if !isPgCode(err, "42501") {
t.Errorf("reading backend.accounts as payments: got %v, want permission-denied (42501)", err)
}
}
// TestPaymentsLedgerAppendOnly verifies the append-only trigger rejects any
// UPDATE or DELETE on the ledger (a superuser is bound by the trigger, unlike a
// mere privilege REVOKE).
func TestPaymentsLedgerAppendOnly(t *testing.T) {
ctx := context.Background()
id := uuid.New()
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.ledger (ledger_id, account_id, kind, chips_delta) VALUES ($1, $2, 'admin_grant', 0)`,
id, uuid.New()); err != nil {
t.Fatalf("insert ledger row: %v", err)
}
if _, err := testDB.ExecContext(ctx, `UPDATE payments.ledger SET chips_delta = 1 WHERE ledger_id = $1`, id); err == nil {
t.Error("UPDATE on payments.ledger succeeded — append-only violated")
} else if !isPgCode(err, "P0001") {
t.Errorf("UPDATE ledger: got %v, want the append-only exception (P0001)", err)
}
if _, err := testDB.ExecContext(ctx, `DELETE FROM payments.ledger WHERE ledger_id = $1`, id); err == nil {
t.Error("DELETE on payments.ledger succeeded — append-only violated")
} else if !isPgCode(err, "P0001") {
t.Errorf("DELETE ledger: got %v, want the append-only exception (P0001)", err)
}
}
// TestPaymentsCheckConstraints verifies the domain CHECKs bite: non-negative
// balances/hints/amount and the enum-like columns.
func TestPaymentsCheckConstraints(t *testing.T) {
ctx := context.Background()
prod := uuid.New()
if _, err := testDB.ExecContext(ctx, `INSERT INTO payments.product (product_id, title) VALUES ($1, 'test')`, prod); err != nil {
t.Fatalf("insert product: %v", err)
}
cases := []struct {
name string
sql string
args []any
}{
{"balances chips negative", `INSERT INTO payments.balances (account_id, source, chips) VALUES ($1, 'vk', -1)`, []any{uuid.New()}},
{"balances bad source", `INSERT INTO payments.balances (account_id, source, chips) VALUES ($1, 'nope', 0)`, []any{uuid.New()}},
{"benefits hints negative", `INSERT INTO payments.benefits (account_id, origin, hints) VALUES ($1, 'vk', -1)`, []any{uuid.New()}},
{"ledger bad kind", `INSERT INTO payments.ledger (ledger_id, account_id, kind) VALUES ($1, $2, 'bogus')`, []any{uuid.New(), uuid.New()}},
{"product_price amount negative", `INSERT INTO payments.product_price (product_id, method, currency, amount) VALUES ($1, 'direct', 'RUB', -1)`, []any{prod}},
{"product_price bad currency", `INSERT INTO payments.product_price (product_id, method, currency, amount) VALUES ($1, 'direct', 'EUR', 100)`, []any{prod}},
}
for _, c := range cases {
if _, err := testDB.ExecContext(ctx, c.sql, c.args...); err == nil {
t.Errorf("%s: insert succeeded, want a CHECK violation", c.name)
} else if !isPgCode(err, "23514") {
t.Errorf("%s: got %v, want check_violation (23514)", c.name, err)
}
}
}
// TestPaymentsLedgerIdempotencyIndex verifies the partial unique index makes a
// (provider, provider_payment_id) pair collide once but leaves NULL-keyed rows
// unconstrained.
func TestPaymentsLedgerIdempotencyIndex(t *testing.T) {
ctx := context.Background()
insert := func(ppid *string) error {
_, err := testDB.ExecContext(ctx,
`INSERT INTO payments.ledger (ledger_id, account_id, kind, provider, provider_payment_id) VALUES ($1, $2, 'fund', 'robokassa', $3)`,
uuid.New(), uuid.New(), ppid)
return err
}
ppid := "inv-" + uuid.NewString()
if err := insert(&ppid); err != nil {
t.Fatalf("first insert: %v", err)
}
if err := insert(&ppid); err == nil {
t.Error("duplicate (provider, provider_payment_id) inserted — idempotency index missing")
} else if !isPgCode(err, "23505") {
t.Errorf("duplicate insert: got %v, want unique_violation (23505)", err)
}
// A NULL provider_payment_id is outside the partial index — repeats allowed.
if err := insert(nil); err != nil {
t.Fatalf("first null-ppid insert: %v", err)
}
if err := insert(nil); err != nil {
t.Errorf("second null-ppid insert should be allowed by the partial index: %v", err)
}
}
// TestPaymentsMigrationReversible proves the migration is expand-contract: it
// applies, rolls fully back (schema, role, trigger and all), and re-applies
// cleanly — so a backend image rollback stays DB-safe. It uses its own container
// so the Down does not disturb the shared suite database.
func TestPaymentsMigrationReversible(t *testing.T) {
ctx := context.Background()
container, err := tcpostgres.Run(ctx, pgImage,
tcpostgres.WithDatabase(pgDatabase),
tcpostgres.WithUsername(pgUser),
tcpostgres.WithPassword(pgPassword),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(containerStartup),
),
)
if err != nil {
t.Fatalf("start container: %v", err)
}
defer func() { _ = container.Terminate(context.Background()) }()
baseDSN, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatalf("connection string: %v", err)
}
dsn, err := withSearchPath(baseDSN, pgSchema)
if err != nil {
t.Fatalf("search path: %v", err)
}
cfg := postgres.DefaultConfig()
cfg.DSN = dsn
db, err := postgres.Open(ctx, cfg)
if err != nil {
t.Fatalf("open pool: %v", err)
}
defer func() { _ = db.Close() }()
// Up: apply every migration, including the payments foundation.
if err := postgres.ApplyMigrations(ctx, db); err != nil {
t.Fatalf("apply up: %v", err)
}
if !schemaExists(ctx, t, db, "payments") {
t.Fatal("payments schema absent after up")
}
// Down the payments migration and assert a clean teardown.
goose.SetBaseFS(migrations.Migrations())
defer goose.SetBaseFS(nil)
if err := goose.SetDialect("postgres"); err != nil {
t.Fatalf("set dialect: %v", err)
}
if err := goose.DownToContext(ctx, db, ".", 9); err != nil {
t.Fatalf("down to 9: %v", err)
}
if schemaExists(ctx, t, db, "payments") {
t.Error("payments schema survived the down migration")
}
var roleExists bool
if err := db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'payments')").Scan(&roleExists); err != nil {
t.Fatalf("check role after down: %v", err)
}
if roleExists {
t.Error("payments role survived the down migration")
}
// Re-apply and assert it comes back cleanly.
if err := goose.UpContext(ctx, db, "."); err != nil {
t.Fatalf("re-apply up: %v", err)
}
if !schemaExists(ctx, t, db, "payments") {
t.Fatal("payments schema absent after re-apply")
}
}
// schemaExists reports whether a schema of the given name is present.
func schemaExists(ctx context.Context, t *testing.T, db *sql.DB, name string) bool {
t.Helper()
var exists bool
if err := db.QueryRowContext(ctx,
"SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE schema_name = $1)", name).Scan(&exists); err != nil {
t.Fatalf("check schema %s: %v", name, err)
}
return exists
}
@@ -0,0 +1,279 @@
//go:build integration
package inttest
import (
"context"
"database/sql"
"errors"
"testing"
"time"
"github.com/google/uuid"
"scrabble/backend/internal/payments"
)
// seedBalance writes a chip balance for an account+source directly (payments has no FK to
// accounts, so a bare uuid is a valid account id here).
func seedBalance(t *testing.T, id uuid.UUID, source string, chips int) {
t.Helper()
if _, err := testDB.ExecContext(context.Background(),
`INSERT INTO payments.balances (account_id, source, chips) VALUES ($1,$2,$3)
ON CONFLICT (account_id, source) DO UPDATE SET chips = EXCLUDED.chips`,
id, source, chips); err != nil {
t.Fatalf("seed balance: %v", err)
}
}
// readBalance reads an account's chip balance for a source (0 when the row is absent).
func readBalance(t *testing.T, id uuid.UUID, source string) int {
t.Helper()
var chips int
err := testDB.QueryRowContext(context.Background(),
`SELECT chips FROM payments.balances WHERE account_id=$1 AND source=$2`, id, source).Scan(&chips)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("read balance: %v", err)
}
return chips
}
// benefitUntil reads an account's no-ads term end for an origin (nil when none).
func benefitUntil(t *testing.T, id uuid.UUID, origin string) *time.Time {
t.Helper()
var until *time.Time
err := testDB.QueryRowContext(context.Background(),
`SELECT ads_paid_until FROM payments.benefits WHERE account_id=$1 AND origin=$2`, id, origin).Scan(&until)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("read benefit until: %v", err)
}
return until
}
// ledgerRows counts an account's ledger rows of a given kind.
func ledgerRows(t *testing.T, id uuid.UUID, kind string) int {
t.Helper()
var n int
if err := testDB.QueryRowContext(context.Background(),
`SELECT count(*) FROM payments.ledger WHERE account_id=$1 AND kind=$2`, id, kind).Scan(&n); err != nil {
t.Fatalf("ledger count: %v", err)
}
return n
}
// seedValueProduct creates an active chip-priced value: a product with a CHIP price (method
// NULL) and the given hint / no-ads-day atoms. It returns the product id.
func seedValueProduct(t *testing.T, priceChips, hints, noAdsDays int) uuid.UUID {
t.Helper()
ctx := context.Background()
prod := uuid.New()
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product (product_id, title, active) VALUES ($1,'test value',true)`, prod); err != nil {
t.Fatalf("seed product: %v", err)
}
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product_price (product_id, method, currency, amount) VALUES ($1, NULL, 'CHIP', $2)`,
prod, priceChips); err != nil {
t.Fatalf("seed price: %v", err)
}
if hints > 0 {
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product_item (product_id, atom_type, quantity) VALUES ($1,'hints',$2)`, prod, hints); err != nil {
t.Fatalf("seed hints item: %v", err)
}
}
if noAdsDays > 0 {
if _, err := testDB.ExecContext(ctx,
`INSERT INTO payments.product_item (product_id, atom_type, quantity) VALUES ($1,'noads_days',$2)`, prod, noAdsDays); err != nil {
t.Fatalf("seed noads item: %v", err)
}
}
return prod
}
// TestPaymentsSpendAppliesAtomically verifies a chip spend writes the ledger row, decrements the
// balance and applies the benefit together over Postgres.
func TestPaymentsSpendAppliesAtomically(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
seedBalance(t, acc, "direct", 100)
prod := seedValueProduct(t, 60, 3, 30)
if err := svc.Spend(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod); err != nil {
t.Fatalf("spend: %v", err)
}
if got := readBalance(t, acc, "direct"); got != 40 {
t.Errorf("balance after spend = %d, want 40", got)
}
if hints, _ := readBenefit(t, acc, "direct"); hints != 3 {
t.Errorf("hints after spend = %d, want 3", hints)
}
if benefitUntil(t, acc, "direct") == nil {
t.Error("no-ads term not applied by the spend")
}
if n := ledgerRows(t, acc, "spend"); n != 1 {
t.Errorf("spend ledger rows = %d, want 1", n)
}
}
// TestPaymentsSpendInsufficientNoWrite verifies an under-funded spend is refused and writes
// nothing (the balance, benefit and ledger are untouched).
func TestPaymentsSpendInsufficientNoWrite(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
seedBalance(t, acc, "direct", 10)
prod := seedValueProduct(t, 60, 3, 0)
if err := svc.Spend(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod); !errors.Is(err, payments.ErrInsufficientChips) {
t.Fatalf("spend = %v, want ErrInsufficientChips", err)
}
if got := readBalance(t, acc, "direct"); got != 10 {
t.Errorf("balance changed to %d, want 10 (no write)", got)
}
if h, _ := readBenefit(t, acc, "direct"); h != 0 {
t.Errorf("benefit applied on a refused spend: hints %d", h)
}
if ledgerRows(t, acc, "spend") != 0 {
t.Error("spend ledger row written on a refused spend")
}
}
// TestPaymentsSpendGuardRollsBack forces the in-transaction guard to bite: with a stale read
// cache the draw plan looks affordable, but the guarded decrement matches no row and the whole
// transaction rolls back — no ledger row, no benefit, balance unchanged.
func TestPaymentsSpendGuardRollsBack(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
seedBalance(t, acc, "direct", 100)
present := []payments.Source{payments.SourceDirect}
cxt := payments.NewContext("direct", "web")
if _, err := svc.Wallet(ctx, acc, cxt, present); err != nil { // warm the cache at 100
t.Fatalf("warm: %v", err)
}
// Drain the real balance behind the cache's back (no invalidation), so the plan over-commits.
if _, err := testDB.ExecContext(ctx, `UPDATE payments.balances SET chips = 10 WHERE account_id=$1 AND source='direct'`, acc); err != nil {
t.Fatalf("drain: %v", err)
}
prod := seedValueProduct(t, 60, 3, 0)
if err := svc.Spend(ctx, acc, cxt, present, prod); !errors.Is(err, payments.ErrInsufficientChips) {
t.Fatalf("spend = %v, want ErrInsufficientChips", err)
}
if got := readBalance(t, acc, "direct"); got != 10 {
t.Errorf("balance = %d, want 10 (rolled back)", got)
}
if ledgerRows(t, acc, "spend") != 0 {
t.Error("spend ledger row written despite the rollback")
}
if h, _ := readBenefit(t, acc, "direct"); h != 0 {
t.Error("benefit applied despite the rollback")
}
}
// TestPaymentsGrantCreditsValuesNotChips verifies admin_grant applies a benefit at price 0
// without ever crediting chips (D16).
func TestPaymentsGrantCreditsValuesNotChips(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
if err := svc.Grant(ctx, acc, payments.SourceDirect, 5, 0, true); err != nil {
t.Fatalf("grant: %v", err)
}
if hints, forever := readBenefit(t, acc, "direct"); hints != 5 || !forever {
t.Errorf("granted benefit = hints %d forever %v, want 5/true", hints, forever)
}
if readBalance(t, acc, "direct") != 0 {
t.Error("a grant must not credit chips")
}
if ledgerRows(t, acc, "admin_grant") != 1 {
t.Error("admin_grant ledger row missing")
}
if ledgerRows(t, acc, "spend") != 0 || ledgerRows(t, acc, "fund") != 0 {
t.Error("a grant wrote a non-grant ledger row")
}
}
// TestPaymentsSpendHintByContext verifies a hint is drawn from an applicable origin, and that a
// direct-origin hint is not usable inside a VK context (the compliance wall for hints).
func TestPaymentsSpendHintByContext(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
seedBenefit(t, acc, "direct", 2, false)
present := []payments.Source{payments.SourceDirect, payments.SourceVK}
if spent, err := svc.SpendHint(ctx, acc, payments.NewContext("direct", "web"), present); err != nil || !spent {
t.Fatalf("web spend hint = %v (err %v), want true", spent, err)
}
if h, _ := readBenefit(t, acc, "direct"); h != 1 {
t.Errorf("hints after spend = %d, want 1", h)
}
// Inside VK the applicable origins are {vk} only, so the direct-origin hint is untouched.
if spent, _ := svc.SpendHint(ctx, acc, payments.NewContext("vk", "android"), present); spent {
t.Error("direct-origin hint spent inside VK — compliance wall breached")
}
if h, _ := readBenefit(t, acc, "direct"); h != 1 {
t.Errorf("direct hints changed inside VK = %d, want 1 (untouched)", h)
}
}
// TestPaymentsComplianceGateOverPostgres is the named compliance regression at the integration
// layer: a direct-origin no-ads benefit applies on the web but never inside a store wrapper.
func TestPaymentsComplianceGateOverPostgres(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
acc := uuid.New()
if err := svc.Grant(ctx, acc, payments.SourceDirect, 0, 30, false); err != nil {
t.Fatalf("grant: %v", err)
}
present := []payments.Source{payments.SourceDirect, payments.SourceVK}
if adFree, _ := svc.AdFree(ctx, acc, payments.NewContext("direct", "web"), present); !adFree {
t.Error("direct no-ads should apply on web")
}
if adFree, _ := svc.AdFree(ctx, acc, payments.NewContext("vk", "android"), present); adFree {
t.Error("direct no-ads must NOT apply inside VK (compliance wall)")
}
if adFree, _ := svc.AdFree(ctx, acc, payments.NewContext("telegram", "web"), present); adFree {
t.Error("direct no-ads must NOT apply inside Telegram (compliance wall)")
}
}
// TestPaymentsMergeFoldsSegmentsAndBenefits verifies the merge folds chip segments (sum) and
// benefits (hints sum, forever OR) by origin, and clears the secondary's rows, over Postgres.
func TestPaymentsMergeFoldsSegmentsAndBenefits(t *testing.T) {
ctx := context.Background()
svc := newPaymentsService()
primary, secondary := uuid.New(), uuid.New()
seedBalance(t, primary, "vk", 10)
seedBalance(t, secondary, "vk", 25)
seedBenefit(t, primary, "vk", 1, false)
seedBenefit(t, secondary, "vk", 4, true)
tx, err := testDB.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("begin: %v", err)
}
if err := svc.MergeTx(ctx, tx, primary, secondary); err != nil {
_ = tx.Rollback()
t.Fatalf("merge: %v", err)
}
if err := tx.Commit(); err != nil {
t.Fatalf("commit: %v", err)
}
svc.Invalidate(primary, secondary)
if got := readBalance(t, primary, "vk"); got != 35 {
t.Errorf("merged chips = %d, want 35", got)
}
if h, forever := readBenefit(t, primary, "vk"); h != 5 || !forever {
t.Errorf("merged benefit = hints %d forever %v, want 5/true", h, forever)
}
if readBalance(t, secondary, "vk") != 0 {
t.Error("secondary balance not cleared after merge")
}
}
@@ -0,0 +1,178 @@
//go:build integration
package inttest
import (
"context"
"database/sql"
"testing"
"github.com/google/uuid"
"github.com/pressly/goose/v3"
testcontainers "github.com/testcontainers/testcontainers-go"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
"scrabble/backend/internal/account"
"scrabble/backend/internal/postgres"
"scrabble/backend/internal/postgres/migrations"
"scrabble/backend/internal/session"
)
// TestSessionPlatformCaptureAndUntrusted proves a session round-trips its captured
// platform through create and a cold-cache (DB-backed) resolve for each kind, and
// that an unattributed session records no platform — the untrusted, view-only case.
func TestSessionPlatformCaptureAndUntrusted(t *testing.T) {
ctx := context.Background()
accounts := account.NewStore(testDB)
store := session.NewStore(testDB)
svc := session.NewService(store, session.NewCache())
for _, tc := range []struct {
name string
platform session.Platform
}{
{"vk-ios", session.Platform{Kind: session.PlatformKindVK, Subtype: session.SubtypeIOS}},
{"telegram-android", session.Platform{Kind: session.PlatformKindTelegram, Subtype: session.SubtypeAndroid}},
{"direct-web", session.Platform{Kind: session.PlatformKindDirect, Subtype: session.SubtypeWeb}},
{"untrusted", session.Platform{}},
} {
t.Run(tc.name, func(t *testing.T) {
acc, err := accounts.ProvisionByIdentity(ctx, account.KindTelegram, "tg-"+uuid.NewString())
if err != nil {
t.Fatalf("provision: %v", err)
}
token, sess, err := svc.Create(ctx, acc.ID, tc.platform)
if err != nil {
t.Fatalf("create: %v", err)
}
if sess.Platform != tc.platform {
t.Errorf("created platform = %+v, want %+v", sess.Platform, tc.platform)
}
// Resolve through a cold cache so the value comes back via the DB columns.
cold := session.NewService(store, session.NewCache())
if err := cold.Warm(ctx); err != nil {
t.Fatalf("warm: %v", err)
}
got, err := cold.Resolve(ctx, token)
if err != nil {
t.Fatalf("resolve: %v", err)
}
if got.Platform != tc.platform {
t.Errorf("resolved platform = %+v, want %+v", got.Platform, tc.platform)
}
if got.Platform.Trusted() != tc.platform.Trusted() {
t.Errorf("resolved Trusted() = %v, want %v", got.Platform.Trusted(), tc.platform.Trusted())
}
})
}
}
// TestSessionPlatformCheckConstraints proves the CHECK constraints reject an
// out-of-range kind or subtype, so a corrupt value cannot be persisted.
func TestSessionPlatformCheckConstraints(t *testing.T) {
ctx := context.Background()
acc, err := account.NewStore(testDB).ProvisionByIdentity(ctx, account.KindTelegram, "tg-"+uuid.NewString())
if err != nil {
t.Fatalf("provision: %v", err)
}
const pgCheckViolation = "23514"
for _, tc := range []struct {
name string
kind string
subtype string
}{
{"bad-kind", "facebook", "web"},
{"bad-subtype", "vk", "windows"},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := testDB.ExecContext(ctx,
`INSERT INTO backend.sessions (session_id, account_id, token_hash, platform_kind, platform_subtype)
VALUES ($1, $2, $3, $4, $5)`,
uuid.New(), acc.ID, uuid.NewString(), tc.kind, tc.subtype)
if !isPgCode(err, pgCheckViolation) {
t.Errorf("insert %s: err = %v, want check_violation", tc.name, err)
}
})
}
}
// TestSessionPlatformMigrationReversible proves migration 00011 is expand-contract:
// it applies, rolls back (dropping the platform columns), and re-applies cleanly —
// so a backend image rollback stays DB-safe. It uses its own container so the Down
// does not disturb the shared suite database.
func TestSessionPlatformMigrationReversible(t *testing.T) {
ctx := context.Background()
container, err := tcpostgres.Run(ctx, pgImage,
tcpostgres.WithDatabase(pgDatabase),
tcpostgres.WithUsername(pgUser),
tcpostgres.WithPassword(pgPassword),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(containerStartup),
),
)
if err != nil {
t.Fatalf("start container: %v", err)
}
defer func() { _ = container.Terminate(context.Background()) }()
baseDSN, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatalf("connection string: %v", err)
}
dsn, err := withSearchPath(baseDSN, pgSchema)
if err != nil {
t.Fatalf("search path: %v", err)
}
cfg := postgres.DefaultConfig()
cfg.DSN = dsn
db, err := postgres.Open(ctx, cfg)
if err != nil {
t.Fatalf("open pool: %v", err)
}
defer func() { _ = db.Close() }()
if err := postgres.ApplyMigrations(ctx, db); err != nil {
t.Fatalf("apply up: %v", err)
}
if !sessionsPlatformColumnsExist(ctx, t, db) {
t.Fatal("platform columns absent after up")
}
goose.SetBaseFS(migrations.Migrations())
defer goose.SetBaseFS(nil)
if err := goose.SetDialect("postgres"); err != nil {
t.Fatalf("set dialect: %v", err)
}
// Down past 00011 (to 00010) and assert the columns are gone.
if err := goose.DownToContext(ctx, db, ".", 10); err != nil {
t.Fatalf("down to 10: %v", err)
}
if sessionsPlatformColumnsExist(ctx, t, db) {
t.Error("platform columns survived the down migration")
}
// Re-apply and assert they return.
if err := goose.UpContext(ctx, db, "."); err != nil {
t.Fatalf("re-apply up: %v", err)
}
if !sessionsPlatformColumnsExist(ctx, t, db) {
t.Fatal("platform columns absent after re-apply")
}
}
// sessionsPlatformColumnsExist reports whether both platform columns are present on
// backend.sessions.
func sessionsPlatformColumnsExist(ctx context.Context, t *testing.T, db *sql.DB) bool {
t.Helper()
var n int
if err := db.QueryRowContext(ctx,
`SELECT count(*) FROM information_schema.columns
WHERE table_schema = 'backend' AND table_name = 'sessions'
AND column_name IN ('platform_kind', 'platform_subtype')`).Scan(&n); err != nil {
t.Fatalf("count platform columns: %v", err)
}
return n == 2
}
+7 -3
View File
@@ -26,7 +26,8 @@ func TestSessionLifecycle(t *testing.T) {
store := session.NewStore(testDB)
svc := session.NewService(store, session.NewCache())
token, sess, err := svc.Create(ctx, acc.ID)
platform := session.Platform{Kind: session.PlatformKindVK, Subtype: session.SubtypeIOS}
token, sess, err := svc.Create(ctx, acc.ID, platform)
if err != nil {
t.Fatalf("create session: %v", err)
}
@@ -36,6 +37,9 @@ func TestSessionLifecycle(t *testing.T) {
if token == sess.TokenHash {
t.Error("plaintext token must not equal the stored hash")
}
if sess.Platform != platform {
t.Errorf("session platform = %+v, want %+v", sess.Platform, platform)
}
// Resolve via the warm write-through cache.
got, err := svc.Resolve(ctx, token)
@@ -63,8 +67,8 @@ func TestSessionLifecycle(t *testing.T) {
if _, ok := cold.Get(session.HashToken(token)); !ok {
t.Error("Warm must load the active session into the cache")
}
if got2, err := svc2.Resolve(ctx, token); err != nil || got2.ID != sess.ID {
t.Errorf("resolve after warm = (%s, %v), want %s", got2.ID, err, sess.ID)
if got2, err := svc2.Resolve(ctx, token); err != nil || got2.ID != sess.ID || got2.Platform != platform {
t.Errorf("resolve after warm = (%s, %+v, %v), want %s / %+v", got2.ID, got2.Platform, err, sess.ID, platform)
}
// Revoke, then the token no longer resolves; revoke again is a no-op.
+5 -1
View File
@@ -200,7 +200,11 @@ func (s *Service) merge(ctx context.Context, callerID, otherID uuid.UUID) (Merge
}
res := MergeResult{PrimaryID: primary}
if primary != callerID {
token, _, err := s.sessions.Create(ctx, primary)
// The switched-to session inherits the caller's current trusted platform
// (the context the merge was initiated from); absent when the caller's
// session itself is untrusted.
platform, _ := session.PlatformFromContext(ctx)
token, _, err := s.sessions.Create(ctx, primary, platform)
if err != nil {
return MergeResult{}, err
}
+4
View File
@@ -73,6 +73,10 @@ const (
// (e.g. an email was confirmed via the one-tap deeplink opened in another browser),
// so it re-fetches profile.get. It carries no payload. In-app only.
NotifyProfile = "profile"
// NotifyPayment tells the client that the viewer's wallet changed from a payment-intake event
// (a credit or a refund), so it re-fetches the wallet in place. It carries no payload. In-app
// only; the payment_events dispatcher emits it after the crediting transaction commits.
NotifyPayment = "payment"
// NotifyUserBlocked confirms to the blocker that a per-user block took effect,
// carrying the blocked account, so every one of the blocker's sessions updates the
// in-game block/add-friend controls and the struck name in place. It is delivered
@@ -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)
}
}
+72
View File
@@ -0,0 +1,72 @@
package payments
import (
"sync"
"time"
"github.com/google/uuid"
)
// benefitState is an account's benefit row for one origin: the no-ads term end (nil = none),
// the perpetual forever flag, and the hint count. It is the context-independent stored form;
// the read paths aggregate it over the origins applicable in a context.
type benefitState struct {
adsPaidUntil *time.Time
adsForever bool
hints int
}
// walletState is an account's full payments state: chip balances by source and benefits by
// origin. It is the raw, context-independent data every read path filters per execution
// context — the value the cache holds and the store recomputes from the materialized tables.
type walletState struct {
chips map[Source]int
benefits map[Source]benefitState
}
// chipsOf returns the chip balance for a source, zero when the segment has no row (an absent
// segment reads as zero, §2).
func (w walletState) chipsOf(s Source) int { return w.chips[s] }
// benefitOf returns the benefit for an origin, the zero benefit when the origin has no row.
func (w walletState) benefitOf(o Source) benefitState { return w.benefits[o] }
// walletCache is the payments read model: each account's chip/benefit state, keyed by account
// id, read on every ad-eligibility / hint / wallet / gate request and invalidated on every
// payments mutation (spend, grant, fund, refund, merge). It is a write-through cache in front
// of the materialized balances/benefits tables — the same pattern the account-suspension gate
// uses (backend/internal/account/suspension.go) — so the steady-state hot path issues no query
// to the payments schema. It is single-instance, matching the deployment (one shared Store); a
// multi-instance backend would need a shared cache.
type walletCache struct {
mu sync.RWMutex
m map[uuid.UUID]walletState
}
// newWalletCache constructs an empty cache.
func newWalletCache() *walletCache {
return &walletCache{m: make(map[uuid.UUID]walletState)}
}
// get returns the cached state for an account and whether it was present.
func (c *walletCache) get(id uuid.UUID) (walletState, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
s, ok := c.m[id]
return s, ok
}
// put stores an account's state.
func (c *walletCache) put(id uuid.UUID, s walletState) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[id] = s
}
// invalidate drops an account's entry so the next read reloads it from the materialized tables.
// Called after every mutation once its transaction has committed.
func (c *walletCache) invalidate(id uuid.UUID) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.m, id)
}
+82
View File
@@ -0,0 +1,82 @@
package payments
// AtomQty is one atom line of a catalog product in the read model: the base value type it grants
// (chips / hints / no-ads days / tournament) and how many of it the product carries.
type AtomQty struct {
AtomType string
Quantity int
}
// CatalogProduct is one storefront product projected for the execution context. A value is
// bought with chips, so it carries Chips (its uniform chip price) and no money price. A chip pack
// funds chips with money, so it carries MoneyAmount (minor units) and MoneyCurrency for the
// context's payment method and no chip price. Atoms lists what the product grants.
type CatalogProduct struct {
Kind string // "value" (bought with chips) or "pack" (funds chips with money)
ProductID string
Title string
Chips int // a value's uniform chip price; 0 for a pack
MoneyAmount int64 // a pack's price in the context currency's minor units; 0 for a value
MoneyCurrency string // a pack's currency for the context method; empty for a value
Atoms []AtomQty
}
// CatalogView is the storefront read model for one execution context: the products a player sees
// and can buy there — every chip-priced value plus the chip packs priced in the context's method.
type CatalogView struct {
Products []CatalogProduct
}
// atomChips is the atom type that marks a product as a chip pack (it funds chips) rather than a
// value (bought with chips). A value never carries it.
const atomChips = "chips"
// projectCatalog turns the raw active catalog into the storefront for the context. A value (no
// chips atom) is shown everywhere at its CHIP price. A chip pack is shown only when it carries a
// price for the context's payment method (cxt.Kind: vk / telegram / direct), priced in that
// method's currency. A value missing its CHIP price and a pack missing a price for the context
// method are omitted (misconfigured or unavailable there). An untrusted context (empty Kind) has
// no method, so only values show; buying is gated server-side regardless.
func projectCatalog(entries []catalogEntry, cxt Context) CatalogView {
var out CatalogView
for _, e := range entries {
isPack := false
atoms := make([]AtomQty, 0, len(e.atoms))
for _, a := range e.atoms {
atoms = append(atoms, AtomQty{AtomType: a.atomType, Quantity: a.quantity})
if a.atomType == atomChips {
isPack = true
}
}
p := CatalogProduct{ProductID: e.id.String(), Title: e.title, Atoms: atoms}
if isPack {
pr, ok := findPrice(e.prices, string(cxt.Kind))
if !ok {
continue // no price for this context's method — not purchasable here
}
p.Kind = "pack"
p.MoneyAmount = pr.amount
p.MoneyCurrency = string(pr.currency)
} else {
pr, ok := findPrice(e.prices, "")
if !ok {
continue // a value must carry a CHIP price
}
p.Kind = "value"
p.Chips = int(pr.amount)
}
out.Products = append(out.Products, p)
}
return out
}
// findPrice returns the price row for the given payment method — the empty string selects a
// value's CHIP price row (stored with a NULL method).
func findPrice(prices []priceRow, method string) (priceRow, bool) {
for _, pr := range prices {
if pr.method == method {
return pr, true
}
}
return priceRow{}, false
}
+136
View File
@@ -0,0 +1,136 @@
package payments
import (
"testing"
"github.com/google/uuid"
)
// catalog fixtures: a chip-priced value (hints), a multi-method chip pack, a VK-only chip pack, a
// value with no CHIP price (misconfigured), and a pack whose only method is telegram.
func fixtureCatalog() []catalogEntry {
value := catalogEntry{
id: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
title: "250 hints",
atoms: []atomQty{{atomType: "hints", quantity: 250}},
prices: []priceRow{
{method: "", currency: CurrencyChip, amount: 500},
},
}
pack := catalogEntry{
id: uuid.MustParse("00000000-0000-0000-0000-000000000002"),
title: "100 chips",
atoms: []atomQty{{atomType: "chips", quantity: 100}},
prices: []priceRow{
{method: "vk", currency: CurrencyVote, amount: 20},
{method: "telegram", currency: CurrencyStar, amount: 25},
{method: "direct", currency: CurrencyRUB, amount: 14900},
},
}
vkOnlyPack := catalogEntry{
id: uuid.MustParse("00000000-0000-0000-0000-000000000003"),
title: "VK-only chips",
atoms: []atomQty{{atomType: "chips", quantity: 50}},
prices: []priceRow{
{method: "vk", currency: CurrencyVote, amount: 10},
},
}
brokenValue := catalogEntry{
id: uuid.MustParse("00000000-0000-0000-0000-000000000004"),
title: "no chip price",
atoms: []atomQty{{atomType: "noads_days", quantity: 30}},
// no CHIP price row — misconfigured, must be omitted
}
return []catalogEntry{value, pack, vkOnlyPack, brokenValue}
}
// byID indexes a projected storefront by product id for assertions.
func byID(v CatalogView) map[string]CatalogProduct {
m := make(map[string]CatalogProduct, len(v.Products))
for _, p := range v.Products {
m[p.ProductID] = p
}
return m
}
func TestProjectCatalog_ContextMatrix(t *testing.T) {
const (
valueID = "00000000-0000-0000-0000-000000000001"
packID = "00000000-0000-0000-0000-000000000002"
vkPackID = "00000000-0000-0000-0000-000000000003"
brokenID = "00000000-0000-0000-0000-000000000004"
)
entries := fixtureCatalog()
tests := []struct {
name string
cxt Context
wantPackAmt int64
wantPackCur Currency
wantVKPack bool // the vk-only pack visible?
}{
{"vk", Context{Kind: SourceVK}, 20, CurrencyVote, true},
{"vk-ios frozen still lists vk price", Context{Kind: SourceVK, Subtype: SubtypeIOS}, 20, CurrencyVote, true},
{"telegram", Context{Kind: SourceTelegram}, 25, CurrencyStar, false},
{"direct", Context{Kind: SourceDirect}, 14900, CurrencyRUB, false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := byID(projectCatalog(entries, tc.cxt))
// The value shows everywhere at its uniform chip price, never a money price.
v, ok := got[valueID]
if !ok {
t.Fatalf("value missing from %s storefront", tc.name)
}
if v.Kind != "value" || v.Chips != 500 || v.MoneyCurrency != "" || v.MoneyAmount != 0 {
t.Errorf("value = %+v, want kind=value chips=500 no money", v)
}
if len(v.Atoms) != 1 || v.Atoms[0].AtomType != "hints" || v.Atoms[0].Quantity != 250 {
t.Errorf("value atoms = %+v, want [hints:250]", v.Atoms)
}
// The multi-method pack shows the context method's price, in that currency, no chips.
p, ok := got[packID]
if !ok {
t.Fatalf("pack missing from %s storefront", tc.name)
}
if p.Kind != "pack" || p.Chips != 0 || p.MoneyAmount != tc.wantPackAmt || p.MoneyCurrency != string(tc.wantPackCur) {
t.Errorf("pack = %+v, want kind=pack amount=%d currency=%s", p, tc.wantPackAmt, tc.wantPackCur)
}
// The vk-only pack shows only where a vk price exists.
if _, ok := got[vkPackID]; ok != tc.wantVKPack {
t.Errorf("vk-only pack present=%v, want %v (%s)", ok, tc.wantVKPack, tc.name)
}
// The misconfigured value (no CHIP price) is never shown.
if _, ok := got[brokenID]; ok {
t.Errorf("misconfigured value must be omitted (%s)", tc.name)
}
})
}
}
// An untrusted context (empty Kind) has no payment method, so it shows values only — no packs.
func TestProjectCatalog_UntrustedShowsValuesOnly(t *testing.T) {
got := byID(projectCatalog(fixtureCatalog(), Context{}))
if _, ok := got["00000000-0000-0000-0000-000000000001"]; !ok {
t.Error("untrusted context should still list the chip-priced value")
}
for _, id := range []string{
"00000000-0000-0000-0000-000000000002",
"00000000-0000-0000-0000-000000000003",
} {
if _, ok := got[id]; ok {
t.Errorf("untrusted context must not list pack %s", id)
}
}
}
// An empty catalog projects to an empty storefront (no products seeded yet — the Release-1 state).
func TestProjectCatalog_Empty(t *testing.T) {
if got := projectCatalog(nil, Context{Kind: SourceDirect}); len(got.Products) != 0 {
t.Errorf("empty catalog projected %d products, want 0", len(got.Products))
}
}
+202
View File
@@ -0,0 +1,202 @@
package payments
import (
"slices"
"time"
)
// Source is the platform axis a chip balance is segmented by (where it was funded) and a
// benefit is stamped with (where it was bought — its origin). The two roles share this value
// set but mean different things (see docs/PAYMENTS.md §3); Source names the axis for both.
type Source string
const (
// SourceVK is the VK platform: Votes purchases and VK rewarded ads fund here.
SourceVK Source = "vk"
// SourceTelegram is the Telegram platform: Stars purchases fund here.
SourceTelegram Source = "telegram"
// SourceDirect is the open web / native context: Robokassa purchases fund here.
SourceDirect Source = "direct"
)
// Valid reports whether s is one of the three known platform sources.
func (s Source) Valid() bool {
switch s {
case SourceVK, SourceTelegram, SourceDirect:
return true
default:
return false
}
}
// SubtypeIOS is the one device subtype the gate keys on: VK on iOS is frozen for spending
// (Apple forbids spending virtual currency on digital goods outside IAP). It is trusted only
// for VK, where it rides inside the signed launch parameters.
const SubtypeIOS = "ios"
// SourceForIdentityKind maps a backend identity kind to the payments source whose segment that
// identity makes available: a vk/telegram identity to its own source, a durable email identity
// to the direct source (the web/native recovery anchor). A robot identity — or any unknown
// kind — maps to no source (second return false). Callers use it to build the present set the
// payments interface takes, since payments cannot read the account schema.
func SourceForIdentityKind(kind string) (Source, bool) {
switch kind {
case "vk":
return SourceVK, true
case "telegram":
return SourceTelegram, true
case "email":
return SourceDirect, true
default:
return "", false
}
}
// PresentSources maps an account's identity kinds to the payments sources they make available
// (§6), de-duplicated: vk→vk, telegram→telegram, email→direct; a robot or unknown kind maps to
// nothing. Callers pass the kinds from account.Identities so the gate — which holds no
// cross-schema identity knowledge — can resolve which segments are awake.
func PresentSources(kinds []string) []Source {
var out []Source
for _, k := range kinds {
if s, ok := SourceForIdentityKind(k); ok && !has(out, s) {
out = append(out, s)
}
}
return out
}
// Context is the trusted execution context the store-compliance gate keys on: the platform
// Kind (the source the wrapper enforces) plus, for VK, the trusted Subtype (only the VK-iOS
// freeze depends on it). The zero Context (empty Kind) is an untrusted platform — the gate is
// fail-closed there: no spend, no purchase, no foreign-origin benefit, view only.
type Context struct {
Kind Source
Subtype string
}
// NewContext builds a Context from the session platform's kind and subtype strings (as carried
// on the trusted X-Platform signal). An unrecognised or empty kind yields an untrusted Context.
func NewContext(kind, subtype string) Context {
k := Source(kind)
if !k.Valid() {
return Context{}
}
return Context{Kind: k, Subtype: subtype}
}
// Trusted reports whether the platform is trusted (a known kind). An untrusted context denies
// every spend/purchase and the application of any foreign origin.
func (c Context) Trusted() bool { return c.Kind.Valid() }
// vkFrozen reports whether this is the VK-iOS spend freeze: VK context on the trusted iOS
// subtype. A previously bought benefit still applies there, but no spend or purchase is possible.
func (c Context) vkFrozen() bool { return c.Kind == SourceVK && c.Subtype == SubtypeIOS }
// spendPriority is the fixed draw order when several segments are spendable in one context
// (D7): the "home" direct segment first, the store-funded segments after.
var spendPriority = []Source{SourceDirect, SourceVK, SourceTelegram}
// has reports whether present contains s.
func has(present []Source, s Source) bool {
return slices.Contains(present, s)
}
// spendableSources returns the chip segments that may be SPENT in the context, in draw-priority
// order, restricted to the sources the account actually has (present). It is empty when the
// platform is untrusted (fail-closed) or VK-iOS (frozen): inside VK/TG only the same-named
// segment is spendable; on web/native all attached segments are, drained direct→vk→tg.
func spendableSources(c Context, present []Source) []Source {
if !c.Trusted() || c.vkFrozen() {
return nil
}
switch c.Kind {
case SourceVK, SourceTelegram:
if has(present, c.Kind) {
return []Source{c.Kind}
}
return nil
default: // direct (web/native)
var out []Source
for _, s := range spendPriority {
if has(present, s) {
out = append(out, s)
}
}
return out
}
}
// applicableOrigins returns the benefit origins that APPLY in the context, in draw-priority
// order, restricted to present sources. It differs from spendableSources in one way: VK-iOS is
// NOT excluded — a benefit bought earlier still applies while spending is frozen. Inside VK/TG
// only the same-named origin applies (a foreign, e.g. direct, origin never activates inside a
// store — the compliance wall); on web/native direct+vk+tg all apply, drained direct→vk→tg.
func applicableOrigins(c Context, present []Source) []Source {
if !c.Trusted() {
return nil
}
switch c.Kind {
case SourceVK, SourceTelegram:
if has(present, c.Kind) {
return []Source{c.Kind}
}
return nil
default: // direct (web/native)
var out []Source
for _, s := range spendPriority {
if has(present, s) {
out = append(out, s)
}
}
return out
}
}
// visibleSources returns the segments the wallet shows in the context, regardless of whether
// they are spendable: inside a store only the same-named segment (the others are invisible
// there); on web/native or an untrusted context all three (untrusted shows them view-only).
func visibleSources(c Context) []Source {
switch c.Kind {
case SourceVK, SourceTelegram:
return []Source{c.Kind}
default:
return spendPriority
}
}
// Segment is one chip balance the wallet shows: the source, its chip count, and whether it can
// be spent in the current context (false for a frozen VK-iOS balance or an untrusted platform).
type Segment struct {
Source Source
Chips int
Spendable bool
}
// BenefitView is the benefit state applicable in the current context: whether ads are off (and
// until when, or forever) and how many hints are available. It aggregates over the origins
// applicable in the context (§5).
type BenefitView struct {
AdsForever bool
AdsPaidUntil *time.Time
Hints int
}
// WalletView is the read model returned to the wallet: the visible segments plus the
// context-applicable benefits.
type WalletView struct {
Segments []Segment
Benefits BenefitView
}
// benefitDelta is the benefit change a spend or grant applies to one origin: hints added, a
// no-ads term in whole days (stacked from max(now, current end)), and the perpetual forever
// flag (which overrides terms).
type benefitDelta struct {
hintsAdd int
noAdsDays int
forever bool
}
// zero reports whether the delta changes nothing.
func (d benefitDelta) zero() bool { return d.hintsAdd == 0 && d.noAdsDays == 0 && !d.forever }
+132
View File
@@ -0,0 +1,132 @@
package payments
import (
"slices"
"testing"
)
// allPresent is an account attached to every source (the maximal present set).
var allPresent = []Source{SourceDirect, SourceVK, SourceTelegram}
func TestSpendableSources(t *testing.T) {
tests := []struct {
name string
ctx Context
present []Source
want []Source
}{
{"vk android, vk present", Context{Kind: SourceVK, Subtype: "android"}, allPresent, []Source{SourceVK}},
{"vk ios frozen", Context{Kind: SourceVK, Subtype: SubtypeIOS}, allPresent, nil},
{"vk android, vk absent", Context{Kind: SourceVK, Subtype: "android"}, []Source{SourceDirect}, nil},
{"telegram", Context{Kind: SourceTelegram, Subtype: "web"}, allPresent, []Source{SourceTelegram}},
{"telegram, tg absent", Context{Kind: SourceTelegram}, []Source{SourceVK}, nil},
{"direct all present, priority", Context{Kind: SourceDirect, Subtype: "web"}, allPresent, []Source{SourceDirect, SourceVK, SourceTelegram}},
{"direct, only vk+tg attached", Context{Kind: SourceDirect}, []Source{SourceTelegram, SourceVK}, []Source{SourceVK, SourceTelegram}},
{"direct, nothing attached", Context{Kind: SourceDirect}, nil, nil},
{"untrusted fail-closed", Context{}, allPresent, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := spendableSources(tc.ctx, tc.present); !slices.Equal(got, tc.want) {
t.Errorf("spendableSources(%+v, %v) = %v, want %v", tc.ctx, tc.present, got, tc.want)
}
})
}
}
func TestApplicableOrigins(t *testing.T) {
tests := []struct {
name string
ctx Context
present []Source
want []Source
}{
// A benefit still APPLIES on VK-iOS while spending is frozen.
{"vk ios still applies", Context{Kind: SourceVK, Subtype: SubtypeIOS}, allPresent, []Source{SourceVK}},
{"vk android", Context{Kind: SourceVK, Subtype: "android"}, allPresent, []Source{SourceVK}},
{"telegram", Context{Kind: SourceTelegram}, allPresent, []Source{SourceTelegram}},
{"direct all, priority", Context{Kind: SourceDirect}, allPresent, []Source{SourceDirect, SourceVK, SourceTelegram}},
{"untrusted fail-closed", Context{}, allPresent, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := applicableOrigins(tc.ctx, tc.present); !slices.Equal(got, tc.want) {
t.Errorf("applicableOrigins(%+v, %v) = %v, want %v", tc.ctx, tc.present, got, tc.want)
}
})
}
}
// TestComplianceWall is the named unit-level compliance regression: a direct origin (externally
// paid, outside any store cash desk) must NEVER be applicable inside a VK or TG wrapper, and no
// segment is ever spendable there beyond the same-named one. The dangerous direction stays shut.
func TestComplianceWall(t *testing.T) {
for _, kind := range []Source{SourceVK, SourceTelegram} {
for _, sub := range []string{"android", "ios", "web"} {
ctx := Context{Kind: kind, Subtype: sub}
if slices.Contains(applicableOrigins(ctx, allPresent), SourceDirect) {
t.Errorf("direct origin applies inside %s/%s — compliance wall breached", kind, sub)
}
for _, s := range spendableSources(ctx, allPresent) {
if s != kind {
t.Errorf("foreign segment %s spendable inside %s/%s", s, kind, sub)
}
}
// The opposite store's origin must not leak in either (vk⊥tg).
other := SourceVK
if kind == SourceVK {
other = SourceTelegram
}
if slices.Contains(applicableOrigins(ctx, allPresent), other) {
t.Errorf("%s origin applies inside %s — cross-store leak", other, kind)
}
}
}
}
func TestVisibleSources(t *testing.T) {
if got := visibleSources(Context{Kind: SourceVK, Subtype: SubtypeIOS}); !slices.Equal(got, []Source{SourceVK}) {
t.Errorf("VK visible = %v, want [vk] (direct/tg hidden in a store)", got)
}
if got := visibleSources(Context{Kind: SourceDirect}); !slices.Equal(got, allPresent) {
t.Errorf("direct visible = %v, want all three", got)
}
if got := visibleSources(Context{}); !slices.Equal(got, allPresent) {
t.Errorf("untrusted visible = %v, want all three (view-only)", got)
}
}
func TestSourceForIdentityKind(t *testing.T) {
tests := []struct {
kind string
want Source
ok bool
}{
{"vk", SourceVK, true},
{"telegram", SourceTelegram, true},
{"email", SourceDirect, true},
{"robot", "", false},
{"unknown", "", false},
}
for _, tc := range tests {
got, ok := SourceForIdentityKind(tc.kind)
if got != tc.want || ok != tc.ok {
t.Errorf("SourceForIdentityKind(%q) = %q,%v want %q,%v", tc.kind, got, ok, tc.want, tc.ok)
}
}
}
func TestNewContextTrusted(t *testing.T) {
if c := NewContext("vk", "ios"); !c.Trusted() || !c.vkFrozen() {
t.Errorf("vk/ios: trusted=%v frozen=%v, want true/true", c.Trusted(), c.vkFrozen())
}
if c := NewContext("bogus", "web"); c.Trusted() {
t.Errorf("bogus kind should be untrusted")
}
if c := NewContext("", ""); c.Trusted() {
t.Errorf("empty kind should be untrusted")
}
if c := NewContext("direct", "web"); c.vkFrozen() {
t.Errorf("direct is never frozen")
}
}
+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)
}
}
}
+177
View File
@@ -0,0 +1,177 @@
// 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
}
}
// Major renders the amount as a decimal string without the currency, with the currency's
// fractional digits and no floating point (e.g. "149.50", "250") — the form a provider's amount
// field (Robokassa OutSum) takes.
func (m Money) Major() string {
scale := m.currency.minorPerUnit()
if scale == 1 {
return fmt.Sprintf("%d", m.minor)
}
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", sign, abs/scale, width, abs%scale)
}
// String renders the amount as "<value> <currency>" (e.g. "149.50 RUB", "250 XTR").
func (m Money) String() string {
return m.Major() + " " + string(m.currency)
}
+246
View File
@@ -0,0 +1,246 @@
package payments
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
)
// Service is the payments domain's application layer — the narrow surface other domains depend
// on, keeping the schema reachable through one seam. Every read/gate method takes the trusted
// execution Context and the account's present identity sources (which segments are awake, §6);
// payments holds no cross-schema identity knowledge, so the caller supplies present. Reads are
// served from the store's in-process cache, so the steady-state hot path issues no query to the
// payments schema.
type Service struct {
store *Store
clock func() time.Time
}
// NewService constructs a Service over store with a wall-clock time source.
func NewService(store *Store) *Service {
return &Service{store: store, clock: func() time.Time { return time.Now().UTC() }}
}
// Ping reports whether the payments schema is reachable.
func (s *Service) Ping(ctx context.Context) error { return s.store.Ping(ctx) }
// Wallet returns the read model for the account in the execution context: the segments visible
// there (each with its chip count and whether it is spendable) plus the context-applicable
// benefits. In a store context only the same-named segment is shown; on web/native or an
// untrusted platform all attached segments are shown, spendable only when the gate allows.
func (s *Service) Wallet(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (WalletView, error) {
st, err := s.store.state(ctx, accountID)
if err != nil {
return WalletView{}, err
}
now := s.clock()
view := WalletView{Benefits: benefitView(st, cxt, present, now)}
spendable := spendableSources(cxt, present)
for _, src := range visibleSources(cxt) {
if !has(present, src) {
continue // only the account's own (attached) segments are shown
}
view.Segments = append(view.Segments, Segment{
Source: src,
Chips: st.chipsOf(src),
Spendable: has(spendable, src),
})
}
return view, nil
}
// Catalog returns the storefront for the execution context: every chip-priced value (shown in
// every context) plus the chip packs priced in the context's payment method. It is read straight
// from the catalog tables — small and rarely edited, so uncached. An untrusted context has no
// method and so shows values only; buying is gate-checked on Spend regardless (fail-closed).
func (s *Service) Catalog(ctx context.Context, cxt Context) (CatalogView, error) {
entries, err := s.store.loadCatalog(ctx)
if err != nil {
return CatalogView{}, err
}
return projectCatalog(entries, cxt), nil
}
// AdFree reports whether ads are suppressed for the account in the context: some origin
// applicable there has an active no-ads term or the forever flag. Fail-closed on an untrusted
// platform (no origin applies).
func (s *Service) AdFree(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (bool, error) {
st, err := s.store.state(ctx, accountID)
if err != nil {
return false, err
}
now := s.clock()
for _, o := range applicableOrigins(cxt, present) {
b := st.benefitOf(o)
if b.adsForever || (b.adsPaidUntil != nil && b.adsPaidUntil.After(now)) {
return true, nil
}
}
return false, nil
}
// HintsAvailable returns how many hints the account can use in the context — the sum over the
// applicable origins. Zero on an untrusted platform.
func (s *Service) HintsAvailable(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (int, error) {
st, err := s.store.state(ctx, accountID)
if err != nil {
return 0, err
}
total := 0
for _, o := range applicableOrigins(cxt, present) {
total += st.benefitOf(o).hints
}
return total, nil
}
// SpendHint consumes one hint from the first applicable origin that has one (priority
// direct→vk→tg), returning whether a hint was spent. It spends nothing when no origin is
// applicable (untrusted platform or no attached segment).
func (s *Service) SpendHint(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source) (bool, error) {
origins := applicableOrigins(cxt, present)
if len(origins) == 0 {
return false, nil
}
return s.store.consumeHint(ctx, accountID, origins, s.clock())
}
// Spend buys a chip-priced value: it gate-checks the context, draws the price across the
// spendable segments by priority direct→vk→tg, and applies the benefit — atomically. The
// benefit's origin is the purchase context. It fails closed on an untrusted or frozen platform
// (ErrUntrusted) and on insufficient chips (ErrInsufficientChips).
func (s *Service) Spend(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source, productID uuid.UUID) error {
spendable := spendableSources(cxt, present)
if len(spendable) == 0 {
return ErrUntrusted // untrusted, frozen, or no attached segment — no spend
}
prod, err := s.store.loadProduct(ctx, productID)
if err != nil {
return err
}
st, err := s.store.state(ctx, accountID)
if err != nil {
return err
}
draws, ok := planDraws(st, spendable, prod.priceChips)
if !ok {
return ErrInsufficientChips
}
snapshot, err := marshalSnapshot(prod)
if err != nil {
return err
}
return s.store.spend(ctx, accountID, draws, cxt.Kind, productID, prod.delta, snapshot, s.clock())
}
// Grant applies a benefit to an origin as a zero-price sale — an admin_grant ledger row and the
// benefit (hints, a no-ads term in whole days, or the forever flag). It never grants chips (no
// balance is touched — D16), so its signature has no chip amount. The origin is the admin's
// compliance choice.
func (s *Service) Grant(ctx context.Context, accountID uuid.UUID, origin Source, hints, noAdsDays int, forever bool) error {
if !origin.Valid() {
return fmt.Errorf("payments: invalid grant origin %q", origin)
}
d := benefitDelta{hintsAdd: hints, noAdsDays: noAdsDays, forever: forever}
if d.zero() {
return fmt.Errorf("payments: empty grant")
}
snapshot, err := marshalGrant(d)
if err != nil {
return err
}
return s.store.grant(ctx, accountID, origin, d, snapshot, s.clock())
}
// MergeTx merges the secondary account's segments and benefits into the primary inside the
// caller's transaction (the account-merge flow). The caller invalidates the affected caches
// after committing (Invalidate).
func (s *Service) MergeTx(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID) error {
return s.store.MergeTx(ctx, tx, primary, secondary, s.clock())
}
// Invalidate drops the cached state of the listed accounts (called after a merge commit).
func (s *Service) Invalidate(ids ...uuid.UUID) { s.store.Invalidate(ids...) }
// benefitView aggregates the benefits applicable in the context into the wallet view: ads-off
// forever if any applicable origin is perpetual, else the latest active term end, plus the total
// available hints.
func benefitView(st walletState, cxt Context, present []Source, now time.Time) BenefitView {
var v BenefitView
for _, o := range applicableOrigins(cxt, present) {
b := st.benefitOf(o)
if b.adsForever {
v.AdsForever = true
}
if b.adsPaidUntil != nil && b.adsPaidUntil.After(now) {
if v.AdsPaidUntil == nil || b.adsPaidUntil.After(*v.AdsPaidUntil) {
v.AdsPaidUntil = b.adsPaidUntil
}
}
v.Hints += b.hints
}
return v
}
// planDraws greedily allocates price across the spendable segments in priority order, draining
// each before moving on. It returns the per-segment draws and whether the segments together held
// enough.
func planDraws(st walletState, spendable []Source, price int) ([]sourceAmount, bool) {
remaining := price
var draws []sourceAmount
for _, src := range spendable {
if remaining <= 0 {
break
}
avail := st.chipsOf(src)
if avail <= 0 {
continue
}
take := min(avail, remaining)
draws = append(draws, sourceAmount{source: src, amount: take})
remaining -= take
}
if remaining > 0 {
return nil, false
}
return draws, true
}
// purchaseSnapshot is the catalog snapshot stored on a spend/grant ledger row, so history and
// receipts stay independent of later catalog edits (§7/D34).
type purchaseSnapshot struct {
ProductID string `json:"product_id,omitempty"`
Title string `json:"title,omitempty"`
Atoms map[string]int `json:"atoms,omitempty"`
PriceChips int `json:"price_chips"`
Forever bool `json:"forever,omitempty"`
}
// marshalSnapshot builds the snapshot for a chip spend.
func marshalSnapshot(p catalogProduct) ([]byte, error) {
b, err := json.Marshal(purchaseSnapshot{ProductID: p.id.String(), Title: p.title, Atoms: p.atoms, PriceChips: p.priceChips})
if err != nil {
return nil, fmt.Errorf("payments: marshal snapshot: %w", err)
}
return b, nil
}
// marshalGrant builds the snapshot for an admin grant (price 0).
func marshalGrant(d benefitDelta) ([]byte, error) {
atoms := map[string]int{}
if d.hintsAdd > 0 {
atoms["hints"] = d.hintsAdd
}
if d.noAdsDays > 0 {
atoms["noads_days"] = d.noAdsDays
}
b, err := json.Marshal(purchaseSnapshot{Atoms: atoms, PriceChips: 0, Forever: d.forever})
if err != nil {
return nil, fmt.Errorf("payments: marshal grant snapshot: %w", err)
}
return b, nil
}
+164
View File
@@ -0,0 +1,164 @@
package payments
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
)
// OrderResult is what CreateOrder returns to the transport: the created order id and the details a
// provider launch payload needs — the amount to charge and a human title for the payment.
type OrderResult struct {
OrderID uuid.UUID
Amount Money
Title string
}
// CreateOrder opens a pending order to fund a chip pack in the execution context's payment method,
// tagged with the provider that will settle it. It gate-checks the context (trusted, not the
// VK-iOS spend freeze) and that the method's funding segment is attached, prices the pack in the
// method's currency, then writes the order. The caller enforces any account-level precondition
// (e.g. the direct email anchor, D36) before calling — payments holds no cross-schema identity
// knowledge.
func (s *Service) CreateOrder(ctx context.Context, accountID uuid.UUID, cxt Context, present []Source, productID uuid.UUID, provider string) (OrderResult, error) {
if !cxt.Trusted() || cxt.vkFrozen() {
return OrderResult{}, ErrUntrusted
}
method := cxt.Kind
if !has(present, method) {
return OrderResult{}, ErrUntrusted // the funding segment is not attached to the account
}
pack, err := s.store.loadPackForOrder(ctx, productID, method)
if err != nil {
return OrderResult{}, err
}
orderID, err := uuid.NewV7()
if err != nil {
return OrderResult{}, fmt.Errorf("payments: order id: %w", err)
}
o := newOrder{
orderID: orderID,
accountID: accountID,
platform: string(method),
productID: productID,
amount: pack.price,
origin: method,
provider: provider,
}
if err := s.store.createOrder(ctx, o, s.clock()); err != nil {
return OrderResult{}, err
}
return OrderResult{OrderID: orderID, Amount: pack.price, Title: pack.title}, nil
}
// OrderItem returns a pending order's human title and the amount it charges, in the order's own
// currency — the details a provider's item-lookup phase needs (VK's get_item). It reads the order
// and the pack title, honouring the pack even if it was later deactivated (mirrors Fund).
func (s *Service) OrderItem(ctx context.Context, orderID uuid.UUID) (title string, amount Money, err error) {
ord, err := s.store.orderByID(ctx, orderID)
if err != nil {
return "", Money{}, err
}
_, title, err = s.store.packForCredit(ctx, ord.productID)
if err != nil {
return "", Money{}, err
}
amount, err = MoneyFromMinor(ord.expectedAmount, Currency(ord.currency))
if err != nil {
return "", Money{}, err
}
return title, amount, nil
}
// Fund credits a paid order into its funded segment exactly once, from a verified provider callback
// — the single writer for every rail. It matches the order, verifies the paid amount, appends the
// fund ledger row (idempotent on (provider, provider_payment_id)), credits the balance and marks
// the order paid. A duplicate callback returns AlreadyCredited without a second credit; a valid
// callback is honoured even on an expired order (§9/D23).
func (s *Service) Fund(ctx context.Context, orderID uuid.UUID, provider, providerPaymentID string, paid Money) (FundOutcome, error) {
return s.store.fund(ctx, orderID, provider, providerPaymentID, paid, s.clock())
}
// Refund reverses a paid order's credit best-effort, exactly once — for an external refund or an
// admin-initiated one (E7). It revokes the funded chips floored at 0 (never negative, D27), records
// any unrecoverable remainder as a per-account loss and abuse flag, and appends a refund ledger row
// idempotent on (provider, providerRefundID) — distinct from the fund's payment id. A duplicate
// refund returns AlreadyRefunded. The caller records the refunded payment event and performs any
// provider-side money-back (the rails have no unsolicited refund push: Robokassa via its refund API
// / cabinet, VK via support, Telegram via refundStarPayment — all admin-triggered).
func (s *Service) Refund(ctx context.Context, orderID uuid.UUID, provider, providerRefundID string, refunded Money) (RefundOutcome, error) {
return s.store.refund(ctx, orderID, provider, providerRefundID, refunded, s.clock())
}
// Pre-checkout decline reason codes. They are language-neutral: the transport layer localises them
// to the order account's preferred language before showing the payer (the reason is displayed in the
// Telegram payment sheet).
const (
// PreCheckoutGone means no order matches — an unknown or stale invoice payload.
PreCheckoutGone = "order_gone"
// PreCheckoutAlreadyPaid means the order is already paid (a reusable invoice link paid twice).
PreCheckoutAlreadyPaid = "already_paid"
// PreCheckoutPriceChanged means the amount or currency no longer matches the order.
PreCheckoutPriceChanged = "price_changed"
)
// PreCheckoutOutcome is the pre-charge validation of a Telegram Stars order. OK approves the charge;
// otherwise Reason is a decline reason code the transport localises. AccountID is the order's account
// (for localising the reason to its preferred language); it is the zero UUID when the order is unknown.
type PreCheckoutOutcome struct {
OK bool
Reason string
AccountID uuid.UUID
}
// ValidatePreCheckout answers whether a Stars pre_checkout_query for orderID paying amount may be
// approved, before any star is charged. It approves an order that exists, is not already paid (a
// reusable invoice link paid a second time is refused here) and whose expected amount and currency
// match the invoice. A pending or honoured-expired order is approved — a late credit is honoured
// (§9/D23). A missing order or a mismatch is a clean decline with a reason code, not an error.
func (s *Service) ValidatePreCheckout(ctx context.Context, orderID uuid.UUID, amount Money) (PreCheckoutOutcome, error) {
ord, err := s.store.orderByID(ctx, orderID)
if errors.Is(err, ErrOrderNotFound) {
return PreCheckoutOutcome{OK: false, Reason: PreCheckoutGone}, nil
}
if err != nil {
return PreCheckoutOutcome{}, err
}
if ord.status == "paid" {
return PreCheckoutOutcome{OK: false, Reason: PreCheckoutAlreadyPaid, AccountID: ord.accountID}, nil
}
if amount.Currency() != Currency(ord.currency) || amount.Minor() != ord.expectedAmount {
return PreCheckoutOutcome{OK: false, Reason: PreCheckoutPriceChanged, AccountID: ord.accountID}, nil
}
return PreCheckoutOutcome{OK: true, AccountID: ord.accountID}, nil
}
// ExpireOrders marks pending orders older than the configured lifetime as expired, returning how
// many were swept. It backs the periodic pending reaper; expiry is cosmetic (a late valid callback
// still credits — see Fund).
func (s *Service) ExpireOrders(ctx context.Context) (int, error) {
ttl, err := s.store.orderTTL(ctx)
if err != nil {
return 0, err
}
return s.store.expirePending(ctx, ttl, s.clock())
}
// RecordPaymentEvent appends a payment lifecycle event (succeeded/failed/refunded) for the
// dispatcher to deliver to the user (live stream, botlink or email).
func (s *Service) RecordPaymentEvent(ctx context.Context, accountID uuid.UUID, orderID *uuid.UUID, eventType string, payload []byte) error {
return s.store.insertPaymentEvent(ctx, accountID, orderID, eventType, payload, s.clock())
}
// UndispatchedEvents returns up to limit payment events awaiting delivery. The dispatcher drains
// them and marks each delivered via MarkEventDispatched.
func (s *Service) UndispatchedEvents(ctx context.Context, limit int) ([]PaymentEvent, error) {
return s.store.undispatchedEvents(ctx, limit)
}
// MarkEventDispatched stamps a payment event as delivered so it is not re-sent.
func (s *Service) MarkEventDispatched(ctx context.Context, eventID uuid.UUID) error {
return s.store.markEventDispatched(ctx, eventID, s.clock())
}
@@ -0,0 +1,42 @@
package payments
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
)
// gateOnlyService builds a Service with a fixed clock and no store, usable only for the CreateOrder
// gate rejections that return before any store access.
func gateOnlyService() *Service {
return &Service{clock: func() time.Time { return time.Unix(0, 0).UTC() }}
}
// TestCreateOrderGateRejections checks that CreateOrder fails closed — before touching the store —
// on an untrusted platform, the VK-iOS spend freeze, and a method whose funding segment the account
// does not hold.
func TestCreateOrderGateRejections(t *testing.T) {
ctx := context.Background()
acc, prod := uuid.New(), uuid.New()
present := []Source{SourceDirect, SourceVK}
cases := []struct {
name string
cxt Context
}{
{"untrusted context", Context{}},
{"vk-ios spend freeze", Context{Kind: SourceVK, Subtype: SubtypeIOS}},
{"method segment not attached", Context{Kind: SourceTelegram}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := gateOnlyService().CreateOrder(ctx, acc, tc.cxt, present, prod, "robokassa")
if !errors.Is(err, ErrUntrusted) {
t.Fatalf("CreateOrder(%s) = %v, want ErrUntrusted", tc.name, err)
}
})
}
}
+40
View File
@@ -0,0 +1,40 @@
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. It fronts the materialized balances/benefits tables with an
// in-process write-through cache (see cache.go) so hot reads issue no query on
// the steady-state path.
type Store struct {
db *sql.DB
cache *walletCache
}
// NewStore constructs a Store wrapping db, with an empty read cache.
func NewStore(db *sql.DB) *Store { return &Store{db: db, cache: newWalletCache()} }
// 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
}
@@ -0,0 +1,89 @@
package payments
import (
"context"
"fmt"
"github.com/go-jet/jet/v2/postgres"
"github.com/google/uuid"
"scrabble/backend/internal/postgres/jet/payments/model"
"scrabble/backend/internal/postgres/jet/payments/table"
)
// atomQty is one atom line of a product as loaded from the catalog: the atom type and quantity.
type atomQty struct {
atomType string
quantity int
}
// priceRow is one price of a product as loaded from the catalog: the payment method (empty for a
// value's CHIP price, stored with a NULL method) and the amount in that currency's minor units.
type priceRow struct {
method string
currency Currency
amount int64
}
// catalogEntry is a raw active product loaded for the storefront: its atom composition and every
// price row. [projectCatalog] turns it into the context-visible [CatalogProduct].
type catalogEntry struct {
id uuid.UUID
title string
atoms []atomQty
prices []priceRow
}
// loadCatalog reads every active product with its atoms and prices, ordered by creation, straight
// from the catalog tables. The catalog is small and rarely edited (admin console only), so it is
// read uncached — unlike the per-account balances/benefits the read cache fronts.
func (s *Store) loadCatalog(ctx context.Context) ([]catalogEntry, error) {
var prods []model.Product
if err := postgres.SELECT(table.Product.AllColumns).
FROM(table.Product).
WHERE(table.Product.Active.IS_TRUE()).
ORDER_BY(table.Product.CreatedAt.ASC()).
QueryContext(ctx, s.db, &prods); err != nil {
return nil, fmt.Errorf("payments: load catalog products: %w", err)
}
if len(prods) == 0 {
return nil, nil
}
entries := make([]catalogEntry, len(prods))
index := make(map[uuid.UUID]int, len(prods))
for i, p := range prods {
entries[i] = catalogEntry{id: p.ProductID, title: p.Title}
index[p.ProductID] = i
}
var items []model.ProductItem
if err := postgres.SELECT(table.ProductItem.AllColumns).
FROM(table.ProductItem).
QueryContext(ctx, s.db, &items); err != nil {
return nil, fmt.Errorf("payments: load catalog items: %w", err)
}
for _, it := range items {
if i, ok := index[it.ProductID]; ok {
entries[i].atoms = append(entries[i].atoms, atomQty{atomType: it.AtomType, quantity: int(it.Quantity)})
}
}
var prices []model.ProductPrice
if err := postgres.SELECT(table.ProductPrice.AllColumns).
FROM(table.ProductPrice).
QueryContext(ctx, s.db, &prices); err != nil {
return nil, fmt.Errorf("payments: load catalog prices: %w", err)
}
for _, pr := range prices {
i, ok := index[pr.ProductID]
if !ok {
continue // a price for a deactivated product — not in the storefront
}
method := ""
if pr.Method != nil {
method = *pr.Method
}
entries[i].prices = append(entries[i].prices, priceRow{method: method, currency: Currency(pr.Currency), amount: pr.Amount})
}
return entries, nil
}
+506
View File
@@ -0,0 +1,506 @@
package payments
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"scrabble/backend/internal/postgres/jet/payments/model"
"scrabble/backend/internal/postgres/jet/payments/table"
)
// Intake errors surfaced by the order-flow and external-credit (fund) path.
var (
// ErrNotAPack means the product is not a fundable chip pack in the requested method: it
// carries no chips atom, or no price for that payment method.
ErrNotAPack = errors.New("payments: product is not a chip pack for this method")
// ErrOrderNotFound means no order matches the id (an unknown or forged callback reference).
ErrOrderNotFound = errors.New("payments: order not found")
// ErrAmountMismatch means the callback's paid amount or currency does not match the order's
// expected amount — the credit is refused (§9: verify amount after matching by order id).
ErrAmountMismatch = errors.New("payments: paid amount does not match the order")
// ErrOrderNotPaid means a refund targets an order that was never funded — there is nothing to
// reverse (guards against a spurious loss/abuse record on an unpaid order).
ErrOrderNotPaid = errors.New("payments: order is not paid")
)
// errAlreadyCredited is the internal sentinel that unwinds the fund transaction when the ledger's
// (provider, provider_payment_id) unique index rejects a duplicate callback. It is not surfaced:
// a replayed callback is a success that credits nothing.
var errAlreadyCredited = errors.New("payments: already credited")
// errAlreadyRefunded unwinds the refund transaction when the ledger idempotency index rejects a
// duplicate refund (same provider refund id). It is not surfaced: a replayed refund reverses nothing.
var errAlreadyRefunded = errors.New("payments: already refunded")
// packInfo is a chip pack resolved for an order: the product, the chips it funds and its price in
// the requested payment method's currency.
type packInfo struct {
productID uuid.UUID
title string
chips int
price Money
}
// packChips returns the quantity of the chips atom a product carries, or 0 if it has none (which
// marks it as a value, not a fundable pack).
func (s *Store) packChips(ctx context.Context, productID uuid.UUID) (int, error) {
var item model.ProductItem
err := postgres.SELECT(table.ProductItem.AllColumns).
FROM(table.ProductItem).
WHERE(table.ProductItem.ProductID.EQ(postgres.UUID(productID)).
AND(table.ProductItem.AtomType.EQ(postgres.String(atomChips)))).
LIMIT(1).
QueryContext(ctx, s.db, &item)
if errors.Is(err, qrm.ErrNoRows) {
return 0, nil
}
if err != nil {
return 0, fmt.Errorf("payments: load pack chips %s: %w", productID, err)
}
return int(item.Quantity), nil
}
// loadPackForOrder resolves an active chip pack for a new order in the given payment method: an
// active product carrying a chips atom and a price row for the method (its currency and amount are
// the order's expected amount). It rejects a missing/deactivated product (ErrProductNotFound) and
// a product that is not a pack for the method (ErrNotAPack).
func (s *Store) loadPackForOrder(ctx context.Context, productID uuid.UUID, method Source) (packInfo, error) {
var p model.Product
err := postgres.SELECT(table.Product.AllColumns).
FROM(table.Product).
WHERE(table.Product.ProductID.EQ(postgres.UUID(productID))).
LIMIT(1).
QueryContext(ctx, s.db, &p)
if errors.Is(err, qrm.ErrNoRows) || (err == nil && !p.Active) {
return packInfo{}, ErrProductNotFound
}
if err != nil {
return packInfo{}, fmt.Errorf("payments: load product %s: %w", productID, err)
}
chips, err := s.packChips(ctx, productID)
if err != nil {
return packInfo{}, err
}
if chips <= 0 {
return packInfo{}, ErrNotAPack
}
var price model.ProductPrice
err = postgres.SELECT(table.ProductPrice.AllColumns).
FROM(table.ProductPrice).
WHERE(table.ProductPrice.ProductID.EQ(postgres.UUID(productID)).
AND(table.ProductPrice.Method.EQ(postgres.String(string(method))))).
LIMIT(1).
QueryContext(ctx, s.db, &price)
if errors.Is(err, qrm.ErrNoRows) {
return packInfo{}, ErrNotAPack
}
if err != nil {
return packInfo{}, fmt.Errorf("payments: load pack price %s: %w", productID, err)
}
money, err := MoneyFromMinor(price.Amount, Currency(price.Currency))
if err != nil {
return packInfo{}, err
}
return packInfo{productID: productID, title: p.Title, chips: chips, price: money}, nil
}
// packForCredit resolves the chips and title of an ordered pack at credit time, ignoring the
// product's active flag: the money is real, so an order is honoured even if the pack was
// deactivated after it was placed (§9/D23).
func (s *Store) packForCredit(ctx context.Context, productID uuid.UUID) (chips int, title string, err error) {
var p model.Product
e := postgres.SELECT(table.Product.Title).
FROM(table.Product).
WHERE(table.Product.ProductID.EQ(postgres.UUID(productID))).
LIMIT(1).
QueryContext(ctx, s.db, &p)
if errors.Is(e, qrm.ErrNoRows) {
return 0, "", ErrProductNotFound
}
if e != nil {
return 0, "", fmt.Errorf("payments: load product %s: %w", productID, e)
}
chips, err = s.packChips(ctx, productID)
if err != nil {
return 0, "", err
}
if chips <= 0 {
return 0, "", ErrNotAPack
}
return chips, p.Title, nil
}
// newOrder is the intent a CreateOrder writes: a pending order for a pack, priced in the method's
// currency, tagged with the provider that will settle it.
type newOrder struct {
orderID uuid.UUID
accountID uuid.UUID
platform string
productID uuid.UUID
amount Money
origin Source
provider string
}
// createOrder inserts a pending order.
func (s *Store) createOrder(ctx context.Context, o newOrder, now time.Time) error {
stmt := table.Orders.INSERT(
table.Orders.OrderID, table.Orders.AccountID, table.Orders.Platform,
table.Orders.ProductID, table.Orders.ExpectedAmount, table.Orders.Currency,
table.Orders.Origin, table.Orders.Status, table.Orders.Provider,
table.Orders.CreatedAt, table.Orders.UpdatedAt,
).VALUES(
o.orderID, o.accountID, o.platform,
o.productID, o.amount.Minor(), string(o.amount.Currency()),
string(o.origin), "pending", o.provider,
now, now,
)
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
return fmt.Errorf("payments: create order: %w", err)
}
return nil
}
// orderRow is a stored order read back for the intake path.
type orderRow struct {
orderID uuid.UUID
accountID uuid.UUID
productID uuid.UUID
expectedAmount int64
currency string
origin string
status string
}
// orderByID reads an order, or ErrOrderNotFound.
func (s *Store) orderByID(ctx context.Context, orderID uuid.UUID) (orderRow, error) {
var o model.Orders
err := postgres.SELECT(table.Orders.AllColumns).
FROM(table.Orders).
WHERE(table.Orders.OrderID.EQ(postgres.UUID(orderID))).
LIMIT(1).
QueryContext(ctx, s.db, &o)
if errors.Is(err, qrm.ErrNoRows) {
return orderRow{}, ErrOrderNotFound
}
if err != nil {
return orderRow{}, fmt.Errorf("payments: load order %s: %w", orderID, err)
}
return orderRow{
orderID: o.OrderID,
accountID: o.AccountID,
productID: o.ProductID,
expectedAmount: o.ExpectedAmount,
currency: o.Currency,
origin: o.Origin,
status: o.Status,
}, nil
}
// FundOutcome reports the result of an intake credit: whose balance, which segment and how many
// chips were credited, and whether the callback was a duplicate that credited nothing.
type FundOutcome struct {
AccountID uuid.UUID
Source Source
Chips int
AlreadyCredited bool
}
// fund credits a paid order exactly once: it matches the order, verifies the amount, then in one
// transaction appends a fund ledger row (idempotent on the (provider, provider_payment_id) unique
// index), credits the funded segment's balance and marks the order paid. A duplicate callback is
// rejected by the unique index and returns AlreadyCredited with no error and no second credit. A
// valid callback is honoured even on an expired order (§9/D23). The read cache is invalidated after
// the commit, since the credit runs outside any request the payments package owns.
func (s *Store) fund(ctx context.Context, orderID uuid.UUID, provider, providerPaymentID string, paid Money, now time.Time) (FundOutcome, error) {
ord, err := s.orderByID(ctx, orderID)
if err != nil {
return FundOutcome{}, err
}
if paid.Currency() != Currency(ord.currency) || paid.Minor() != ord.expectedAmount {
return FundOutcome{}, ErrAmountMismatch
}
chips, title, err := s.packForCredit(ctx, ord.productID)
if err != nil {
return FundOutcome{}, err
}
snapshot, err := marshalFundSnapshot(ord.productID, title, chips, paid)
if err != nil {
return FundOutcome{}, err
}
src := Source(ord.origin)
outcome := FundOutcome{AccountID: ord.accountID, Source: src, Chips: chips}
pv, pp := provider, providerPaymentID
productID := ord.productID
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
if e := insertLedgerTx(ctx, tx, ord.accountID, "fund", &src, &src, chips, &productID, &orderID, &pv, &pp, snapshot, now); e != nil {
if isUniqueViolation(e) {
outcome.AlreadyCredited = true
return errAlreadyCredited
}
return e
}
if _, e := tx.ExecContext(ctx,
`INSERT INTO payments.balances (account_id, source, chips, updated_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (account_id, source) DO UPDATE
SET chips = payments.balances.chips + EXCLUDED.chips, updated_at = now()`,
ord.accountID, string(src), chips); e != nil {
return fmt.Errorf("payments: credit balance %s: %w", src, e)
}
if _, e := tx.ExecContext(ctx,
`UPDATE payments.orders SET status = 'paid', provider = $2, provider_payment_id = $3, updated_at = now()
WHERE order_id = $1`,
orderID, provider, providerPaymentID); e != nil {
return fmt.Errorf("payments: mark order paid: %w", e)
}
return nil
})
if err != nil {
if errors.Is(err, errAlreadyCredited) {
return outcome, nil
}
return FundOutcome{}, err
}
s.cache.invalidate(ord.accountID)
return outcome, nil
}
// RefundOutcome reports a refund's result: whose funded segment was reversed, the chips actually
// clawed back (floored at 0), the unrecoverable remainder (a loss, when the chips were already
// spent), and whether the refund was a duplicate that reversed nothing.
type RefundOutcome struct {
AccountID uuid.UUID
Source Source
Revoked int
Loss int
AlreadyRefunded bool
}
// refund reverses a paid order's credit best-effort, exactly once. It matches the order (which must
// be paid), verifies the refunded amount, then in one transaction appends a refund ledger row
// (idempotent on the (provider, provider_payment_id) index — the refund id is distinct from the
// fund's payment id, so the two rows coexist), revokes the funded chips floored at 0 (never
// negative, D27/balances_chips_chk) and, when chips were already spent, records the unrecoverable
// remainder as a per-account loss and flips the abuse flag. A duplicate refund returns
// AlreadyRefunded with no second reversal. The ledger row's chipsDelta is what is actually
// reclaimed; the full reversal (money, original chips, loss) rides in its snapshot for the report.
func (s *Store) refund(ctx context.Context, orderID uuid.UUID, provider, providerRefundID string, refunded Money, now time.Time) (RefundOutcome, error) {
ord, err := s.orderByID(ctx, orderID)
if err != nil {
return RefundOutcome{}, err
}
if ord.status != "paid" {
return RefundOutcome{}, ErrOrderNotPaid
}
if refunded.Currency() != Currency(ord.currency) || refunded.Minor() != ord.expectedAmount {
return RefundOutcome{}, ErrAmountMismatch
}
chips, title, err := s.packForCredit(ctx, ord.productID)
if err != nil {
return RefundOutcome{}, err
}
src := Source(ord.origin)
outcome := RefundOutcome{AccountID: ord.accountID, Source: src}
pv, pr := provider, providerRefundID
productID := ord.productID
oid := orderID
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
// Lock the funded segment and read what is left; a spent balance floors the reversal at 0.
var avail int
e := tx.QueryRowContext(ctx,
`SELECT chips FROM payments.balances WHERE account_id = $1 AND source = $2 FOR UPDATE`,
ord.accountID, string(src)).Scan(&avail)
switch {
case errors.Is(e, sql.ErrNoRows):
avail = 0
case e != nil:
return fmt.Errorf("payments: read balance for refund: %w", e)
}
revoked := min(chips, avail)
loss := chips - revoked
outcome.Revoked, outcome.Loss = revoked, loss
snapshot, e := marshalRefundSnapshot(ord.productID, title, chips, revoked, loss, refunded, providerRefundID)
if e != nil {
return e
}
if e := insertLedgerTx(ctx, tx, ord.accountID, "refund", &src, &src, -revoked, &productID, &oid, &pv, &pr, snapshot, now); e != nil {
if isUniqueViolation(e) {
outcome.AlreadyRefunded = true
return errAlreadyRefunded
}
return e
}
if revoked > 0 {
if _, e := tx.ExecContext(ctx,
`UPDATE payments.balances SET chips = chips - $3, updated_at = now()
WHERE account_id = $1 AND source = $2`,
ord.accountID, string(src), revoked); e != nil {
return fmt.Errorf("payments: revoke chips %s: %w", src, e)
}
}
if loss > 0 {
if _, e := tx.ExecContext(ctx,
`INSERT INTO payments.account_risk (account_id, abuse, loss_chips, updated_at)
VALUES ($1, true, $2, now())
ON CONFLICT (account_id) DO UPDATE
SET abuse = true, loss_chips = payments.account_risk.loss_chips + EXCLUDED.loss_chips, updated_at = now()`,
ord.accountID, int64(loss)); e != nil {
return fmt.Errorf("payments: record refund loss: %w", e)
}
}
return nil
})
if err != nil {
if errors.Is(err, errAlreadyRefunded) {
return outcome, nil
}
return RefundOutcome{}, err
}
s.cache.invalidate(ord.accountID)
return outcome, nil
}
// insertPaymentEvent appends an undispatched lifecycle event (succeeded/failed/refunded) for the
// dispatcher to deliver. orderID and payload (a jsonb detail blob) are optional.
func (s *Store) insertPaymentEvent(ctx context.Context, accountID uuid.UUID, orderID *uuid.UUID, eventType string, payload []byte, now time.Time) error {
id, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("payments: event id: %w", err)
}
var pl any = postgres.NULL
if payload != nil {
pl = string(payload)
}
stmt := table.PaymentEvents.INSERT(
table.PaymentEvents.EventID, table.PaymentEvents.AccountID, table.PaymentEvents.OrderID,
table.PaymentEvents.Type, table.PaymentEvents.Payload, table.PaymentEvents.CreatedAt,
).VALUES(id, accountID, uuidOrNull(orderID), eventType, pl, now)
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
return fmt.Errorf("payments: insert %s event: %w", eventType, err)
}
return nil
}
// PaymentEvent is an undispatched lifecycle event the dispatcher delivers to an account.
type PaymentEvent struct {
EventID uuid.UUID
AccountID uuid.UUID
Type string
}
// undispatchedEvents reads up to limit payment events not yet delivered, oldest first.
func (s *Store) undispatchedEvents(ctx context.Context, limit int) ([]PaymentEvent, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT event_id, account_id, type FROM payments.payment_events
WHERE dispatched_at IS NULL ORDER BY created_at LIMIT $1`, limit)
if err != nil {
return nil, fmt.Errorf("payments: read undispatched events: %w", err)
}
defer rows.Close()
var out []PaymentEvent
for rows.Next() {
var e PaymentEvent
if err := rows.Scan(&e.EventID, &e.AccountID, &e.Type); err != nil {
return nil, fmt.Errorf("payments: scan event: %w", err)
}
out = append(out, e)
}
return out, rows.Err()
}
// markEventDispatched stamps an event as delivered so it is not re-sent.
func (s *Store) markEventDispatched(ctx context.Context, eventID uuid.UUID, now time.Time) error {
if _, err := s.db.ExecContext(ctx,
`UPDATE payments.payment_events SET dispatched_at = $2 WHERE event_id = $1`, eventID, now); err != nil {
return fmt.Errorf("payments: mark event dispatched: %w", err)
}
return nil
}
// orderTTL reads the configured pending-order lifetime in whole seconds.
func (s *Store) orderTTL(ctx context.Context) (int, error) {
var cfg model.Config
if err := postgres.SELECT(table.Config.OrderTTLSeconds).
FROM(table.Config).
LIMIT(1).
QueryContext(ctx, s.db, &cfg); err != nil {
return 0, fmt.Errorf("payments: read order ttl: %w", err)
}
return int(cfg.OrderTTLSeconds), nil
}
// expirePending marks every pending order older than ttlSeconds as expired, returning how many.
// Expiry is cosmetic DB hygiene: a later valid callback still credits an expired order (§9/D23).
func (s *Store) expirePending(ctx context.Context, ttlSeconds int, now time.Time) (int, error) {
cutoff := now.Add(-time.Duration(ttlSeconds) * time.Second)
res, err := table.Orders.
UPDATE(table.Orders.Status, table.Orders.UpdatedAt).
SET(postgres.String("expired"), postgres.TimestampzT(now)).
WHERE(table.Orders.Status.EQ(postgres.String("pending")).
AND(table.Orders.CreatedAt.LT(postgres.TimestampzT(cutoff)))).
ExecContext(ctx, s.db)
if err != nil {
return 0, fmt.Errorf("payments: expire pending orders: %w", err)
}
n, _ := res.RowsAffected()
return int(n), nil
}
// marshalFundSnapshot records what a fund credited (the pack, chips and paid amount) on the ledger
// row, so history stays independent of later catalog edits (§7/D34).
func marshalFundSnapshot(productID uuid.UUID, title string, chips int, paid Money) ([]byte, error) {
b, err := json.Marshal(struct {
ProductID string `json:"product_id"`
Title string `json:"title,omitempty"`
Chips int `json:"chips"`
Amount int64 `json:"amount_minor"`
Currency string `json:"currency"`
}{productID.String(), title, chips, paid.Minor(), string(paid.Currency())})
if err != nil {
return nil, fmt.Errorf("payments: marshal fund snapshot: %w", err)
}
return b, nil
}
// marshalRefundSnapshot records the full reversal on the refund ledger row: the pack, the original
// funded chips, how many were actually reclaimed, the unrecoverable loss (already spent), the money
// refunded and the provider refund id — so the ledger stays reconcilable against the balance
// (chipsDelta = revoked) while the report still sees the whole reversal (§7/D27/D34).
func marshalRefundSnapshot(productID uuid.UUID, title string, chips, revoked, loss int, refunded Money, refundID string) ([]byte, error) {
b, err := json.Marshal(struct {
ProductID string `json:"product_id"`
Title string `json:"title,omitempty"`
Chips int `json:"chips"`
Revoked int `json:"revoked"`
Loss int `json:"loss"`
Amount int64 `json:"amount_minor"`
Currency string `json:"currency"`
RefundID string `json:"refund_id"`
}{productID.String(), title, chips, revoked, loss, refunded.Minor(), string(refunded.Currency()), refundID})
if err != nil {
return nil, fmt.Errorf("payments: marshal refund snapshot: %w", err)
}
return b, nil
}
// isUniqueViolation reports whether err is a PostgreSQL unique-constraint violation (SQLSTATE
// 23505) — here, a duplicate provider callback hitting the ledger idempotency index.
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
+434
View File
@@ -0,0 +1,434 @@
package payments
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/google/uuid"
"scrabble/backend/internal/postgres/jet/payments/model"
"scrabble/backend/internal/postgres/jet/payments/table"
)
// Domain errors surfaced by the payments store and service.
var (
// ErrInsufficientChips means the spendable segments held fewer chips than the price.
ErrInsufficientChips = errors.New("payments: insufficient chips")
// ErrUntrusted means the platform context is untrusted, so the gate is fail-closed.
ErrUntrusted = errors.New("payments: untrusted platform")
// ErrProductNotFound means the product is absent or deactivated.
ErrProductNotFound = errors.New("payments: product not found")
// ErrNotAValue means the product has no chip price (it is a chip pack or unpriced), so it
// cannot be bought with chips.
ErrNotAValue = errors.New("payments: product is not a chip-priced value")
)
// withTx runs fn inside a transaction on db, rolling back on error or panic.
func withTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) (err error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("payments: begin tx: %w", err)
}
defer func() {
if p := recover(); p != nil {
_ = tx.Rollback()
panic(p)
}
}()
if err := fn(tx); err != nil {
_ = tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("payments: commit tx: %w", err)
}
return nil
}
// sourceAmount is one chip draw from a single segment during a spend.
type sourceAmount struct {
source Source
amount int
}
// catalogProduct is a product resolved for a chip spend: its chip price, the benefit its atoms
// fold into, and the raw atom composition for the purchase snapshot.
type catalogProduct struct {
id uuid.UUID
title string
priceChips int
delta benefitDelta
atoms map[string]int
}
// loadState reads an account's balances and benefits straight from the materialized tables.
func (s *Store) loadState(ctx context.Context, accountID uuid.UUID) (walletState, error) {
st := walletState{chips: map[Source]int{}, benefits: map[Source]benefitState{}}
var brows []model.Balances
if err := postgres.SELECT(table.Balances.AllColumns).
FROM(table.Balances).
WHERE(table.Balances.AccountID.EQ(postgres.UUID(accountID))).
QueryContext(ctx, s.db, &brows); err != nil {
return walletState{}, fmt.Errorf("payments: load balances %s: %w", accountID, err)
}
for _, r := range brows {
st.chips[Source(r.Source)] = int(r.Chips)
}
var frows []model.Benefits
if err := postgres.SELECT(table.Benefits.AllColumns).
FROM(table.Benefits).
WHERE(table.Benefits.AccountID.EQ(postgres.UUID(accountID))).
QueryContext(ctx, s.db, &frows); err != nil {
return walletState{}, fmt.Errorf("payments: load benefits %s: %w", accountID, err)
}
for _, r := range frows {
st.benefits[Source(r.Origin)] = benefitState{adsPaidUntil: r.AdsPaidUntil, adsForever: r.AdsForever, hints: int(r.Hints)}
}
return st, nil
}
// state returns an account's payments state, served from the read cache when warm, otherwise
// loaded from the materialized tables and cached. The returned maps are read-only.
func (s *Store) state(ctx context.Context, accountID uuid.UUID) (walletState, error) {
if st, ok := s.cache.get(accountID); ok {
return st, nil
}
st, err := s.loadState(ctx, accountID)
if err != nil {
return walletState{}, err
}
s.cache.put(accountID, st)
return st, nil
}
// Invalidate drops the cached state of every listed account so the next read reloads it. It is
// called after a committed mutation whose transaction the payments package does not own — the
// account-merge flow (after its own commit) and, later, external fund/refund intake.
func (s *Store) Invalidate(ids ...uuid.UUID) {
for _, id := range ids {
s.cache.invalidate(id)
}
}
// loadProduct resolves a chip-priced value: an active product with a CHIP price row
// (method NULL) whose atoms are benefits (hints / no-ads days). It rejects a missing or
// deactivated product (ErrProductNotFound), a product with no chip price (ErrNotAValue), and a
// product carrying the chips atom (a chip pack is funded, never bought with chips — ErrNotAValue).
func (s *Store) loadProduct(ctx context.Context, productID uuid.UUID) (catalogProduct, error) {
var p model.Product
err := postgres.SELECT(table.Product.AllColumns).
FROM(table.Product).
WHERE(table.Product.ProductID.EQ(postgres.UUID(productID))).
LIMIT(1).
QueryContext(ctx, s.db, &p)
if errors.Is(err, qrm.ErrNoRows) || (err == nil && !p.Active) {
return catalogProduct{}, ErrProductNotFound
}
if err != nil {
return catalogProduct{}, fmt.Errorf("payments: load product %s: %w", productID, err)
}
var price model.ProductPrice
err = postgres.SELECT(table.ProductPrice.AllColumns).
FROM(table.ProductPrice).
WHERE(table.ProductPrice.ProductID.EQ(postgres.UUID(productID)).
AND(table.ProductPrice.Method.IS_NULL()).
AND(table.ProductPrice.Currency.EQ(postgres.String(string(CurrencyChip))))).
LIMIT(1).
QueryContext(ctx, s.db, &price)
if errors.Is(err, qrm.ErrNoRows) {
return catalogProduct{}, ErrNotAValue
}
if err != nil {
return catalogProduct{}, fmt.Errorf("payments: load price %s: %w", productID, err)
}
var items []model.ProductItem
if err := postgres.SELECT(table.ProductItem.AllColumns).
FROM(table.ProductItem).
WHERE(table.ProductItem.ProductID.EQ(postgres.UUID(productID))).
QueryContext(ctx, s.db, &items); err != nil {
return catalogProduct{}, fmt.Errorf("payments: load items %s: %w", productID, err)
}
cp := catalogProduct{id: productID, title: p.Title, priceChips: int(price.Amount), atoms: map[string]int{}}
for _, it := range items {
cp.atoms[it.AtomType] = int(it.Quantity)
switch it.AtomType {
case "hints":
cp.delta.hintsAdd += int(it.Quantity)
case "noads_days":
cp.delta.noAdsDays += int(it.Quantity)
case "chips":
return catalogProduct{}, ErrNotAValue // a value never grants chips
}
}
return cp, nil
}
// stackNoAds returns the new no-ads term end after adding addDays whole days from
// max(now, current end) — terms add up, the remainder is never lost (§5/D33). A non-positive
// addDays leaves the term unchanged; a nil current means no term yet.
func stackNoAds(current *time.Time, addDays int, now time.Time) *time.Time {
if addDays <= 0 {
return current
}
base := now
if current != nil && current.After(now) {
base = *current
}
end := base.Add(time.Duration(addDays) * 24 * time.Hour)
return &end
}
// combineNoAds folds secondary's remaining no-ads term onto primary's during a merge: the
// remaining duration of each is preserved (§6/D15 "terms extend per origin").
func combineNoAds(primary, secondary *time.Time, now time.Time) *time.Time {
if secondary == nil || !secondary.After(now) {
return primary
}
base := now
if primary != nil && primary.After(now) {
base = *primary
}
end := base.Add(secondary.Sub(now))
return &end
}
// applyBenefitTx applies a benefit delta to one origin inside tx, stacking the no-ads term,
// OR-ing the forever flag and adding hints. It ensures the (account, origin) row exists, locks
// it, then writes the recomputed values — so concurrent applies serialise on the row lock.
func applyBenefitTx(ctx context.Context, tx *sql.Tx, accountID uuid.UUID, origin Source, d benefitDelta, now time.Time) error {
if d.zero() {
return nil
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO payments.benefits (account_id, origin) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
accountID, string(origin)); err != nil {
return fmt.Errorf("payments: ensure benefit row %s: %w", origin, err)
}
var untilCur *time.Time
var foreverCur bool
var hintsCur int32
if err := tx.QueryRowContext(ctx,
`SELECT ads_paid_until, ads_forever, hints FROM payments.benefits
WHERE account_id = $1 AND origin = $2 FOR UPDATE`, accountID, string(origin)).
Scan(&untilCur, &foreverCur, &hintsCur); err != nil {
return fmt.Errorf("payments: lock benefit %s: %w", origin, err)
}
if _, err := tx.ExecContext(ctx,
`UPDATE payments.benefits SET ads_paid_until = $3, ads_forever = $4, hints = $5, updated_at = now()
WHERE account_id = $1 AND origin = $2`,
accountID, string(origin), stackNoAds(untilCur, d.noAdsDays, now), foreverCur || d.forever, int(hintsCur)+d.hintsAdd); err != nil {
return fmt.Errorf("payments: apply benefit %s: %w", origin, err)
}
return nil
}
// insertLedgerTx appends one append-only ledger row inside tx. orderID, provider and
// providerPaymentID are set only on an intake credit (fund/refund) and are nil for a
// spend/admin_grant; a non-nil (provider, providerPaymentID) pair is guarded by the partial
// unique index, so a duplicate provider callback fails here (the idempotency key).
func insertLedgerTx(ctx context.Context, tx *sql.Tx, accountID uuid.UUID, kind string, source, origin *Source, chipsDelta int, productID, orderID *uuid.UUID, provider, providerPaymentID *string, snapshot []byte, now time.Time) error {
id, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("payments: ledger id: %w", err)
}
// The snapshot is a bare value, not a postgres.String literal: a jsonb column infers its
// type from an untyped parameter (the game-moves payload idiom), whereas a text-typed
// literal is rejected against jsonb.
var snap any = postgres.NULL
if snapshot != nil {
snap = string(snapshot)
}
stmt := table.Ledger.INSERT(
table.Ledger.LedgerID, table.Ledger.AccountID, table.Ledger.Kind,
table.Ledger.Source, table.Ledger.Origin, table.Ledger.ChipsDelta,
table.Ledger.ProductID, table.Ledger.OrderID, table.Ledger.Provider,
table.Ledger.ProviderPaymentID, table.Ledger.Snapshot, table.Ledger.CreatedAt,
).VALUES(
id, accountID, kind,
sourceOrNull(source), sourceOrNull(origin), int32(chipsDelta),
uuidOrNull(productID), uuidOrNull(orderID), stringOrNull(provider),
stringOrNull(providerPaymentID), snap, now,
)
if _, err := stmt.ExecContext(ctx, tx); err != nil {
return fmt.Errorf("payments: insert %s ledger: %w", kind, err)
}
return nil
}
// spend draws the chips across the given segments, appends a spend ledger row per draw (carrying
// the purchase snapshot), and applies the benefit — all in one transaction. It fails closed on
// an insufficient balance (a guarded decrement), rolling everything back.
func (s *Store) spend(ctx context.Context, accountID uuid.UUID, draws []sourceAmount, origin Source, productID uuid.UUID, d benefitDelta, snapshot []byte, now time.Time) error {
err := withTx(ctx, s.db, func(tx *sql.Tx) error {
for _, dr := range draws {
res, err := table.Balances.
UPDATE(table.Balances.Chips, table.Balances.UpdatedAt).
SET(table.Balances.Chips.SUB(postgres.Int(int64(dr.amount))), postgres.TimestampzT(now)).
WHERE(table.Balances.AccountID.EQ(postgres.UUID(accountID)).
AND(table.Balances.Source.EQ(postgres.String(string(dr.source)))).
AND(table.Balances.Chips.GT_EQ(postgres.Int(int64(dr.amount))))).
ExecContext(ctx, tx)
if err != nil {
return fmt.Errorf("payments: decrement %s: %w", dr.source, err)
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrInsufficientChips
}
src := dr.source
if err := insertLedgerTx(ctx, tx, accountID, "spend", &src, &origin, -dr.amount, &productID, nil, nil, nil, snapshot, now); err != nil {
return err
}
}
return applyBenefitTx(ctx, tx, accountID, origin, d, now)
})
if err != nil {
return err
}
s.cache.invalidate(accountID)
return nil
}
// grant records an admin_grant ledger row (price 0, no chips) and applies the granted benefit to
// the chosen origin, in one transaction — a zero-price sale of a value.
func (s *Store) grant(ctx context.Context, accountID uuid.UUID, origin Source, d benefitDelta, snapshot []byte, now time.Time) error {
err := withTx(ctx, s.db, func(tx *sql.Tx) error {
if err := insertLedgerTx(ctx, tx, accountID, "admin_grant", nil, &origin, 0, nil, nil, nil, nil, snapshot, now); err != nil {
return err
}
return applyBenefitTx(ctx, tx, accountID, origin, d, now)
})
if err != nil {
return err
}
s.cache.invalidate(accountID)
return nil
}
// consumeHint decrements one hint from the first applicable origin (in the given priority order)
// that has one, with a guarded update. It returns whether a hint was spent.
func (s *Store) consumeHint(ctx context.Context, accountID uuid.UUID, origins []Source, now time.Time) (bool, error) {
for _, o := range origins {
res, err := table.Benefits.
UPDATE(table.Benefits.Hints, table.Benefits.UpdatedAt).
SET(table.Benefits.Hints.SUB(postgres.Int(1)), postgres.TimestampzT(now)).
WHERE(table.Benefits.AccountID.EQ(postgres.UUID(accountID)).
AND(table.Benefits.Origin.EQ(postgres.String(string(o)))).
AND(table.Benefits.Hints.GT(postgres.Int(0)))).
ExecContext(ctx, s.db)
if err != nil {
return false, fmt.Errorf("payments: consume hint %s: %w", o, err)
}
if n, _ := res.RowsAffected(); n > 0 {
s.cache.invalidate(accountID)
return true, nil
}
}
return false, nil
}
// MergeTx folds the secondary account's segments and benefits into the primary, by source and by
// origin, inside the caller's transaction (the account-merge flow): chips sum, no-ads terms
// extend per origin, forever OR-s, hints add. The secondary's payments rows are removed. The
// caller invalidates the primary's cache after its own commit (Invalidate). It does not touch
// the account schema — the JET import boundary stays intact, only the shared connection is used.
func (s *Store) MergeTx(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
if _, err := tx.ExecContext(ctx,
`INSERT INTO payments.balances (account_id, source, chips, updated_at)
SELECT $1, source, chips, now() FROM payments.balances WHERE account_id = $2
ON CONFLICT (account_id, source) DO UPDATE
SET chips = payments.balances.chips + EXCLUDED.chips, updated_at = now()`,
primary, secondary); err != nil {
return fmt.Errorf("payments: merge balances: %w", err)
}
if _, err := tx.ExecContext(ctx, `DELETE FROM payments.balances WHERE account_id = $1`, secondary); err != nil {
return fmt.Errorf("payments: clear secondary balances: %w", err)
}
rows, err := tx.QueryContext(ctx,
`SELECT origin, ads_paid_until, ads_forever, hints FROM payments.benefits WHERE account_id = $1`, secondary)
if err != nil {
return fmt.Errorf("payments: read secondary benefits: %w", err)
}
type secBenefit struct {
origin Source
until *time.Time
forever bool
hints int
}
var secs []secBenefit
for rows.Next() {
var b secBenefit
var o string
var h int32
if err := rows.Scan(&o, &b.until, &b.forever, &h); err != nil {
rows.Close()
return fmt.Errorf("payments: scan secondary benefit: %w", err)
}
b.origin, b.hints = Source(o), int(h)
secs = append(secs, b)
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("payments: iterate secondary benefits: %w", err)
}
rows.Close()
for _, b := range secs {
if _, err := tx.ExecContext(ctx,
`INSERT INTO payments.benefits (account_id, origin) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
primary, string(b.origin)); err != nil {
return fmt.Errorf("payments: ensure primary benefit %s: %w", b.origin, err)
}
var untilCur *time.Time
var foreverCur bool
var hintsCur int32
if err := tx.QueryRowContext(ctx,
`SELECT ads_paid_until, ads_forever, hints FROM payments.benefits
WHERE account_id = $1 AND origin = $2 FOR UPDATE`, primary, string(b.origin)).
Scan(&untilCur, &foreverCur, &hintsCur); err != nil {
return fmt.Errorf("payments: lock primary benefit %s: %w", b.origin, err)
}
if _, err := tx.ExecContext(ctx,
`UPDATE payments.benefits SET ads_paid_until = $3, ads_forever = $4, hints = $5, updated_at = now()
WHERE account_id = $1 AND origin = $2`,
primary, string(b.origin), combineNoAds(untilCur, b.until, now), foreverCur || b.forever, int(hintsCur)+b.hints); err != nil {
return fmt.Errorf("payments: merge benefit %s: %w", b.origin, err)
}
}
if _, err := tx.ExecContext(ctx, `DELETE FROM payments.benefits WHERE account_id = $1`, secondary); err != nil {
return fmt.Errorf("payments: clear secondary benefits: %w", err)
}
return nil
}
// sourceOrNull renders an optional source as a SQL string or NULL.
func sourceOrNull(s *Source) postgres.Expression {
if s == nil {
return postgres.NULL
}
return postgres.String(string(*s))
}
// uuidOrNull renders an optional id as a SQL uuid or NULL.
func uuidOrNull(id *uuid.UUID) postgres.Expression {
if id == nil {
return postgres.NULL
}
return postgres.UUID(*id)
}
// stringOrNull renders an optional string as a SQL string or NULL.
func stringOrNull(s *string) postgres.Expression {
if s == nil {
return postgres.NULL
}
return postgres.String(*s)
}
+182
View File
@@ -0,0 +1,182 @@
package payments
import (
"context"
"testing"
"time"
"github.com/google/uuid"
)
// base is a fixed clock instant for the deterministic tests.
var base = time.Date(2026, 7, 8, 12, 0, 0, 0, time.UTC)
// seededService builds a Service whose read cache already holds st for id, so the read methods
// resolve without a database (the store's db is nil). The clock is pinned to base.
func seededService(id uuid.UUID, st walletState) *Service {
store := NewStore(nil)
store.cache.put(id, st)
return &Service{store: store, clock: func() time.Time { return base }}
}
func TestStackNoAds(t *testing.T) {
future := base.Add(48 * time.Hour)
past := base.Add(-time.Hour)
tests := []struct {
name string
current *time.Time
addDays int
want *time.Time
}{
{"fresh term", nil, 3, new(base.Add(72 * time.Hour))},
{"stack onto future", new(future), 2, new(future.Add(48 * time.Hour))},
{"lapsed term restarts from now", new(past), 1, new(base.Add(24 * time.Hour))},
{"zero days unchanged", new(future), 0, new(future)},
{"zero days, nil stays nil", nil, 0, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := stackNoAds(tc.current, tc.addDays, base)
if (got == nil) != (tc.want == nil) || (got != nil && !got.Equal(*tc.want)) {
t.Errorf("stackNoAds = %v, want %v", got, tc.want)
}
})
}
}
func TestCombineNoAds(t *testing.T) {
pFuture := base.Add(24 * time.Hour)
sFuture := base.Add(72 * time.Hour) // 3 days remaining
// primary future + secondary future: primary end + secondary's remaining (72h).
if got := combineNoAds(new(pFuture), new(sFuture), base); !got.Equal(pFuture.Add(72 * time.Hour)) {
t.Errorf("combine both future = %v, want %v", got, pFuture.Add(72*time.Hour))
}
// primary nil + secondary future: now + secondary's remaining.
if got := combineNoAds(nil, new(sFuture), base); !got.Equal(base.Add(72 * time.Hour)) {
t.Errorf("combine nil primary = %v, want %v", got, base.Add(72*time.Hour))
}
// secondary lapsed: primary unchanged.
if got := combineNoAds(new(pFuture), new(base.Add(-time.Hour)), base); !got.Equal(pFuture) {
t.Errorf("combine lapsed secondary = %v, want %v", got, pFuture)
}
// secondary nil: primary unchanged.
if got := combineNoAds(new(pFuture), nil, base); !got.Equal(pFuture) {
t.Errorf("combine nil secondary = %v, want %v", got, pFuture)
}
}
func TestPlanDraws(t *testing.T) {
st := walletState{chips: map[Source]int{SourceDirect: 30, SourceVK: 50, SourceTelegram: 5}}
// price met entirely by the first (direct) segment.
if draws, ok := planDraws(st, []Source{SourceDirect, SourceVK}, 20); !ok || len(draws) != 1 || draws[0] != (sourceAmount{SourceDirect, 20}) {
t.Errorf("single-segment draw = %v ok=%v", draws, ok)
}
// price spills from direct into vk by priority.
draws, ok := planDraws(st, []Source{SourceDirect, SourceVK, SourceTelegram}, 60)
want := []sourceAmount{{SourceDirect, 30}, {SourceVK, 30}}
if !ok || len(draws) != 2 || draws[0] != want[0] || draws[1] != want[1] {
t.Errorf("priority spill draw = %v ok=%v, want %v", draws, ok, want)
}
// insufficient total.
if _, ok := planDraws(st, []Source{SourceDirect, SourceVK, SourceTelegram}, 200); ok {
t.Error("expected insufficient")
}
}
func TestWalletSegments(t *testing.T) {
id := uuid.New()
st := walletState{chips: map[Source]int{SourceDirect: 100, SourceVK: 50}}
svc := seededService(id, st)
present := []Source{SourceDirect, SourceVK}
// Web/native: both attached segments shown, both spendable.
got, err := svc.Wallet(context.Background(), id, NewContext("direct", "web"), present)
if err != nil {
t.Fatal(err)
}
if len(got.Segments) != 2 || !got.Segments[0].Spendable || got.Segments[0].Source != SourceDirect {
t.Errorf("direct wallet segments = %+v", got.Segments)
}
// VK Android: only vk shown, spendable.
got, _ = svc.Wallet(context.Background(), id, NewContext("vk", "android"), present)
if len(got.Segments) != 1 || got.Segments[0].Source != SourceVK || !got.Segments[0].Spendable {
t.Errorf("vk-android wallet = %+v", got.Segments)
}
// VK iOS: only vk shown, frozen (not spendable) but the balance is visible.
got, _ = svc.Wallet(context.Background(), id, NewContext("vk", "ios"), present)
if len(got.Segments) != 1 || got.Segments[0].Chips != 50 || got.Segments[0].Spendable {
t.Errorf("vk-ios wallet = %+v (want vk 50 frozen)", got.Segments)
}
}
func TestAdFreeByContext(t *testing.T) {
id := uuid.New()
future := base.Add(48 * time.Hour)
ctx := context.Background()
// A vk-origin no-ads term applies inside VK and out on web, but a direct-origin term never
// applies inside VK (the compliance wall).
svc := seededService(id, walletState{benefits: map[Source]benefitState{
SourceVK: {adsPaidUntil: new(future)},
SourceDirect: {adsPaidUntil: new(future)},
}})
present := []Source{SourceDirect, SourceVK}
cases := []struct {
name string
cxt Context
want bool
}{
{"vk term inside vk", NewContext("vk", "android"), true},
{"vk term inside vk-ios (applies while frozen)", NewContext("vk", "ios"), true},
{"terms on web", NewContext("direct", "web"), true},
{"untrusted fail-closed", NewContext("", ""), false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := svc.AdFree(ctx, id, tc.cxt, present)
if err != nil || got != tc.want {
t.Errorf("AdFree = %v (err %v), want %v", got, err, tc.want)
}
})
}
// Compliance: ONLY a direct-origin term, checked inside VK, must not suppress ads.
svc2 := seededService(id, walletState{benefits: map[Source]benefitState{SourceDirect: {adsPaidUntil: new(future)}}})
if got, _ := svc2.AdFree(ctx, id, NewContext("vk", "android"), present); got {
t.Error("direct-origin no-ads must NOT apply inside VK (compliance wall)")
}
}
func TestHintsAvailableByContext(t *testing.T) {
id := uuid.New()
svc := seededService(id, walletState{benefits: map[Source]benefitState{
SourceDirect: {hints: 3},
SourceVK: {hints: 2},
}})
present := []Source{SourceDirect, SourceVK}
ctx := context.Background()
// Web: both applicable origins summed.
if n, _ := svc.HintsAvailable(ctx, id, NewContext("direct", "web"), present); n != 5 {
t.Errorf("web hints = %d, want 5", n)
}
// VK: only vk-origin hints.
if n, _ := svc.HintsAvailable(ctx, id, NewContext("vk", "android"), present); n != 2 {
t.Errorf("vk hints = %d, want 2", n)
}
// Untrusted: none.
if n, _ := svc.HintsAvailable(ctx, id, NewContext("", ""), present); n != 0 {
t.Errorf("untrusted hints = %d, want 0", n)
}
}
func TestSpendHintUntrustedNoOp(t *testing.T) {
id := uuid.New()
svc := seededService(id, walletState{benefits: map[Source]benefitState{SourceDirect: {hints: 3}}})
// Untrusted context: no applicable origin, so nothing is spent and the DB (nil) is never hit.
spent, err := svc.SpendHint(context.Background(), id, NewContext("", ""), []Source{SourceDirect})
if err != nil || spent {
t.Errorf("untrusted SpendHint = %v (err %v), want false", spent, err)
}
}
@@ -27,4 +27,6 @@ type FeedbackMessages struct {
ReplyReadAt *time.Time
CreatedAt time.Time
Lang *string
AppVersion *string
BrowserTz *string
}
@@ -0,0 +1,23 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type RobotBlocks struct {
ID uuid.UUID `sql:"primary_key"`
BlockerID uuid.UUID
GameID uuid.UUID
Seat int16
RobotID uuid.UUID
DisplayName string
CreatedAt time.Time
}
@@ -0,0 +1,23 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type RobotFriendRequests struct {
ID uuid.UUID `sql:"primary_key"`
RequesterID uuid.UUID
GameID uuid.UUID
Seat int16
RobotID uuid.UUID
DisplayName string
CreatedAt time.Time
}
@@ -13,11 +13,13 @@ import (
)
type Sessions struct {
SessionID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
TokenHash string
Status string
CreatedAt time.Time
LastSeenAt *time.Time
RevokedAt *time.Time
SessionID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
TokenHash string
Status string
CreatedAt time.Time
LastSeenAt *time.Time
RevokedAt *time.Time
PlatformKind *string
PlatformSubtype *string
}
@@ -31,6 +31,8 @@ type feedbackMessagesTable struct {
ReplyReadAt postgres.ColumnTimestampz
CreatedAt postgres.ColumnTimestampz
Lang postgres.ColumnString
AppVersion postgres.ColumnString
BrowserTz postgres.ColumnString
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
@@ -86,8 +88,10 @@ func newFeedbackMessagesTableImpl(schemaName, tableName, alias string) feedbackM
ReplyReadAtColumn = postgres.TimestampzColumn("reply_read_at")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
LangColumn = postgres.StringColumn("lang")
allColumns = postgres.ColumnList{MessageIDColumn, AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn, LangColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn, LangColumn}
AppVersionColumn = postgres.StringColumn("app_version")
BrowserTzColumn = postgres.StringColumn("browser_tz")
allColumns = postgres.ColumnList{MessageIDColumn, AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn, LangColumn, AppVersionColumn, BrowserTzColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn, LangColumn, AppVersionColumn, BrowserTzColumn}
defaultColumns = postgres.ColumnList{CreatedAtColumn}
)
@@ -109,6 +113,8 @@ func newFeedbackMessagesTableImpl(schemaName, tableName, alias string) feedbackM
ReplyReadAt: ReplyReadAtColumn,
CreatedAt: CreatedAtColumn,
Lang: LangColumn,
AppVersion: AppVersionColumn,
BrowserTz: BrowserTzColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
@@ -0,0 +1,96 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var RobotBlocks = newRobotBlocksTable("backend", "robot_blocks", "")
type robotBlocksTable struct {
postgres.Table
// Columns
ID postgres.ColumnString
BlockerID postgres.ColumnString
GameID postgres.ColumnString
Seat postgres.ColumnInteger
RobotID postgres.ColumnString
DisplayName postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type RobotBlocksTable struct {
robotBlocksTable
EXCLUDED robotBlocksTable
}
// AS creates new RobotBlocksTable with assigned alias
func (a RobotBlocksTable) AS(alias string) *RobotBlocksTable {
return newRobotBlocksTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new RobotBlocksTable with assigned schema name
func (a RobotBlocksTable) FromSchema(schemaName string) *RobotBlocksTable {
return newRobotBlocksTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new RobotBlocksTable with assigned table prefix
func (a RobotBlocksTable) WithPrefix(prefix string) *RobotBlocksTable {
return newRobotBlocksTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new RobotBlocksTable with assigned table suffix
func (a RobotBlocksTable) WithSuffix(suffix string) *RobotBlocksTable {
return newRobotBlocksTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newRobotBlocksTable(schemaName, tableName, alias string) *RobotBlocksTable {
return &RobotBlocksTable{
robotBlocksTable: newRobotBlocksTableImpl(schemaName, tableName, alias),
EXCLUDED: newRobotBlocksTableImpl("", "excluded", ""),
}
}
func newRobotBlocksTableImpl(schemaName, tableName, alias string) robotBlocksTable {
var (
IDColumn = postgres.StringColumn("id")
BlockerIDColumn = postgres.StringColumn("blocker_id")
GameIDColumn = postgres.StringColumn("game_id")
SeatColumn = postgres.IntegerColumn("seat")
RobotIDColumn = postgres.StringColumn("robot_id")
DisplayNameColumn = postgres.StringColumn("display_name")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
allColumns = postgres.ColumnList{IDColumn, BlockerIDColumn, GameIDColumn, SeatColumn, RobotIDColumn, DisplayNameColumn, CreatedAtColumn}
mutableColumns = postgres.ColumnList{BlockerIDColumn, GameIDColumn, SeatColumn, RobotIDColumn, DisplayNameColumn, CreatedAtColumn}
defaultColumns = postgres.ColumnList{CreatedAtColumn}
)
return robotBlocksTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
ID: IDColumn,
BlockerID: BlockerIDColumn,
GameID: GameIDColumn,
Seat: SeatColumn,
RobotID: RobotIDColumn,
DisplayName: DisplayNameColumn,
CreatedAt: CreatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,96 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var RobotFriendRequests = newRobotFriendRequestsTable("backend", "robot_friend_requests", "")
type robotFriendRequestsTable struct {
postgres.Table
// Columns
ID postgres.ColumnString
RequesterID postgres.ColumnString
GameID postgres.ColumnString
Seat postgres.ColumnInteger
RobotID postgres.ColumnString
DisplayName postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type RobotFriendRequestsTable struct {
robotFriendRequestsTable
EXCLUDED robotFriendRequestsTable
}
// AS creates new RobotFriendRequestsTable with assigned alias
func (a RobotFriendRequestsTable) AS(alias string) *RobotFriendRequestsTable {
return newRobotFriendRequestsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new RobotFriendRequestsTable with assigned schema name
func (a RobotFriendRequestsTable) FromSchema(schemaName string) *RobotFriendRequestsTable {
return newRobotFriendRequestsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new RobotFriendRequestsTable with assigned table prefix
func (a RobotFriendRequestsTable) WithPrefix(prefix string) *RobotFriendRequestsTable {
return newRobotFriendRequestsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new RobotFriendRequestsTable with assigned table suffix
func (a RobotFriendRequestsTable) WithSuffix(suffix string) *RobotFriendRequestsTable {
return newRobotFriendRequestsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newRobotFriendRequestsTable(schemaName, tableName, alias string) *RobotFriendRequestsTable {
return &RobotFriendRequestsTable{
robotFriendRequestsTable: newRobotFriendRequestsTableImpl(schemaName, tableName, alias),
EXCLUDED: newRobotFriendRequestsTableImpl("", "excluded", ""),
}
}
func newRobotFriendRequestsTableImpl(schemaName, tableName, alias string) robotFriendRequestsTable {
var (
IDColumn = postgres.StringColumn("id")
RequesterIDColumn = postgres.StringColumn("requester_id")
GameIDColumn = postgres.StringColumn("game_id")
SeatColumn = postgres.IntegerColumn("seat")
RobotIDColumn = postgres.StringColumn("robot_id")
DisplayNameColumn = postgres.StringColumn("display_name")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
allColumns = postgres.ColumnList{IDColumn, RequesterIDColumn, GameIDColumn, SeatColumn, RobotIDColumn, DisplayNameColumn, CreatedAtColumn}
mutableColumns = postgres.ColumnList{RequesterIDColumn, GameIDColumn, SeatColumn, RobotIDColumn, DisplayNameColumn, CreatedAtColumn}
defaultColumns = postgres.ColumnList{CreatedAtColumn}
)
return robotFriendRequestsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
ID: IDColumn,
RequesterID: RequesterIDColumn,
GameID: GameIDColumn,
Seat: SeatColumn,
RobotID: RobotIDColumn,
DisplayName: DisplayNameColumn,
CreatedAt: CreatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -17,13 +17,15 @@ type sessionsTable struct {
postgres.Table
// Columns
SessionID postgres.ColumnString
AccountID postgres.ColumnString
TokenHash postgres.ColumnString
Status postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
LastSeenAt postgres.ColumnTimestampz
RevokedAt postgres.ColumnTimestampz
SessionID postgres.ColumnString
AccountID postgres.ColumnString
TokenHash postgres.ColumnString
Status postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
LastSeenAt postgres.ColumnTimestampz
RevokedAt postgres.ColumnTimestampz
PlatformKind postgres.ColumnString
PlatformSubtype postgres.ColumnString
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
@@ -65,29 +67,33 @@ func newSessionsTable(schemaName, tableName, alias string) *SessionsTable {
func newSessionsTableImpl(schemaName, tableName, alias string) sessionsTable {
var (
SessionIDColumn = postgres.StringColumn("session_id")
AccountIDColumn = postgres.StringColumn("account_id")
TokenHashColumn = postgres.StringColumn("token_hash")
StatusColumn = postgres.StringColumn("status")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
LastSeenAtColumn = postgres.TimestampzColumn("last_seen_at")
RevokedAtColumn = postgres.TimestampzColumn("revoked_at")
allColumns = postgres.ColumnList{SessionIDColumn, AccountIDColumn, TokenHashColumn, StatusColumn, CreatedAtColumn, LastSeenAtColumn, RevokedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, TokenHashColumn, StatusColumn, CreatedAtColumn, LastSeenAtColumn, RevokedAtColumn}
defaultColumns = postgres.ColumnList{StatusColumn, CreatedAtColumn}
SessionIDColumn = postgres.StringColumn("session_id")
AccountIDColumn = postgres.StringColumn("account_id")
TokenHashColumn = postgres.StringColumn("token_hash")
StatusColumn = postgres.StringColumn("status")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
LastSeenAtColumn = postgres.TimestampzColumn("last_seen_at")
RevokedAtColumn = postgres.TimestampzColumn("revoked_at")
PlatformKindColumn = postgres.StringColumn("platform_kind")
PlatformSubtypeColumn = postgres.StringColumn("platform_subtype")
allColumns = postgres.ColumnList{SessionIDColumn, AccountIDColumn, TokenHashColumn, StatusColumn, CreatedAtColumn, LastSeenAtColumn, RevokedAtColumn, PlatformKindColumn, PlatformSubtypeColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, TokenHashColumn, StatusColumn, CreatedAtColumn, LastSeenAtColumn, RevokedAtColumn, PlatformKindColumn, PlatformSubtypeColumn}
defaultColumns = postgres.ColumnList{StatusColumn, CreatedAtColumn}
)
return sessionsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
SessionID: SessionIDColumn,
AccountID: AccountIDColumn,
TokenHash: TokenHashColumn,
Status: StatusColumn,
CreatedAt: CreatedAtColumn,
LastSeenAt: LastSeenAtColumn,
RevokedAt: RevokedAtColumn,
SessionID: SessionIDColumn,
AccountID: AccountIDColumn,
TokenHash: TokenHashColumn,
Status: StatusColumn,
CreatedAt: CreatedAtColumn,
LastSeenAt: LastSeenAtColumn,
RevokedAt: RevokedAtColumn,
PlatformKind: PlatformKindColumn,
PlatformSubtype: PlatformSubtypeColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
@@ -10,6 +10,7 @@ package table
// UseSchema sets a new schema name for all generated table SQL builder types. It is recommended to invoke
// this method only once at the beginning of the program.
func UseSchema(schema string) {
AccountBestMove = AccountBestMove.FromSchema(schema)
AccountRoles = AccountRoles.FromSchema(schema)
AccountStats = AccountStats.FromSchema(schema)
AccountSuspensions = AccountSuspensions.FromSchema(schema)
@@ -35,6 +36,8 @@ func UseSchema(schema string) {
Games = Games.FromSchema(schema)
Identities = Identities.FromSchema(schema)
RetainedIdentities = RetainedIdentities.FromSchema(schema)
RobotBlocks = RobotBlocks.FromSchema(schema)
RobotFriendRequests = RobotFriendRequests.FromSchema(schema)
Sessions = Sessions.FromSchema(schema)
SuspensionReasons = SuspensionReasons.FromSchema(schema)
}
@@ -0,0 +1,20 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type AccountRisk struct {
AccountID uuid.UUID `sql:"primary_key"`
Abuse bool
LossChips int64
UpdatedAt time.Time
}
@@ -0,0 +1,20 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Balances struct {
AccountID uuid.UUID `sql:"primary_key"`
Source string `sql:"primary_key"`
Chips int32
UpdatedAt time.Time
}
@@ -0,0 +1,22 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Benefits struct {
AccountID uuid.UUID `sql:"primary_key"`
Origin string `sql:"primary_key"`
AdsPaidUntil *time.Time
AdsForever bool
Hints int32
UpdatedAt time.Time
}
@@ -0,0 +1,12 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
type CatalogAtom struct {
AtomType string `sql:"primary_key"`
}
@@ -0,0 +1,17 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
type Config struct {
OnlyRow bool `sql:"primary_key"`
RewardedPayoutChips int32
CooldownGlobalSeconds int32
CooldownVsAiSeconds int32
CooldownHintSeconds int32
OrderTTLSeconds int32
}
@@ -0,0 +1,28 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Ledger struct {
LedgerID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
Kind string
Source *string
Origin *string
ChipsDelta int32
ProductID *uuid.UUID
OrderID *uuid.UUID
Provider *string
ProviderPaymentID *string
Snapshot *string
CreatedAt time.Time
}
@@ -0,0 +1,28 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Orders struct {
OrderID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
Platform string
ProductID uuid.UUID
ExpectedAmount int64
Currency string
Origin string
Status string
Provider *string
ProviderPaymentID *string
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -0,0 +1,23 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type PaymentEvents struct {
EventID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
OrderID *uuid.UUID
Type string
Payload *string
CreatedAt time.Time
DispatchedAt *time.Time
}
@@ -0,0 +1,21 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Product struct {
ProductID uuid.UUID `sql:"primary_key"`
Title string
Active bool
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -0,0 +1,18 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
)
type ProductItem struct {
ProductID uuid.UUID `sql:"primary_key"`
AtomType string `sql:"primary_key"`
Quantity int32
}
@@ -0,0 +1,19 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
)
type ProductPrice struct {
ProductID uuid.UUID
Method *string
Currency string
Amount int64
}
@@ -0,0 +1,87 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var AccountRisk = newAccountRiskTable("payments", "account_risk", "")
type accountRiskTable struct {
postgres.Table
// Columns
AccountID postgres.ColumnString
Abuse postgres.ColumnBool
LossChips postgres.ColumnInteger
UpdatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type AccountRiskTable struct {
accountRiskTable
EXCLUDED accountRiskTable
}
// AS creates new AccountRiskTable with assigned alias
func (a AccountRiskTable) AS(alias string) *AccountRiskTable {
return newAccountRiskTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new AccountRiskTable with assigned schema name
func (a AccountRiskTable) FromSchema(schemaName string) *AccountRiskTable {
return newAccountRiskTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new AccountRiskTable with assigned table prefix
func (a AccountRiskTable) WithPrefix(prefix string) *AccountRiskTable {
return newAccountRiskTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new AccountRiskTable with assigned table suffix
func (a AccountRiskTable) WithSuffix(suffix string) *AccountRiskTable {
return newAccountRiskTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newAccountRiskTable(schemaName, tableName, alias string) *AccountRiskTable {
return &AccountRiskTable{
accountRiskTable: newAccountRiskTableImpl(schemaName, tableName, alias),
EXCLUDED: newAccountRiskTableImpl("", "excluded", ""),
}
}
func newAccountRiskTableImpl(schemaName, tableName, alias string) accountRiskTable {
var (
AccountIDColumn = postgres.StringColumn("account_id")
AbuseColumn = postgres.BoolColumn("abuse")
LossChipsColumn = postgres.IntegerColumn("loss_chips")
UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
allColumns = postgres.ColumnList{AccountIDColumn, AbuseColumn, LossChipsColumn, UpdatedAtColumn}
mutableColumns = postgres.ColumnList{AbuseColumn, LossChipsColumn, UpdatedAtColumn}
defaultColumns = postgres.ColumnList{AbuseColumn, LossChipsColumn, UpdatedAtColumn}
)
return accountRiskTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
AccountID: AccountIDColumn,
Abuse: AbuseColumn,
LossChips: LossChipsColumn,
UpdatedAt: UpdatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,87 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Balances = newBalancesTable("payments", "balances", "")
type balancesTable struct {
postgres.Table
// Columns
AccountID postgres.ColumnString
Source postgres.ColumnString
Chips postgres.ColumnInteger
UpdatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type BalancesTable struct {
balancesTable
EXCLUDED balancesTable
}
// AS creates new BalancesTable with assigned alias
func (a BalancesTable) AS(alias string) *BalancesTable {
return newBalancesTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new BalancesTable with assigned schema name
func (a BalancesTable) FromSchema(schemaName string) *BalancesTable {
return newBalancesTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new BalancesTable with assigned table prefix
func (a BalancesTable) WithPrefix(prefix string) *BalancesTable {
return newBalancesTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new BalancesTable with assigned table suffix
func (a BalancesTable) WithSuffix(suffix string) *BalancesTable {
return newBalancesTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newBalancesTable(schemaName, tableName, alias string) *BalancesTable {
return &BalancesTable{
balancesTable: newBalancesTableImpl(schemaName, tableName, alias),
EXCLUDED: newBalancesTableImpl("", "excluded", ""),
}
}
func newBalancesTableImpl(schemaName, tableName, alias string) balancesTable {
var (
AccountIDColumn = postgres.StringColumn("account_id")
SourceColumn = postgres.StringColumn("source")
ChipsColumn = postgres.IntegerColumn("chips")
UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
allColumns = postgres.ColumnList{AccountIDColumn, SourceColumn, ChipsColumn, UpdatedAtColumn}
mutableColumns = postgres.ColumnList{ChipsColumn, UpdatedAtColumn}
defaultColumns = postgres.ColumnList{ChipsColumn, UpdatedAtColumn}
)
return balancesTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
AccountID: AccountIDColumn,
Source: SourceColumn,
Chips: ChipsColumn,
UpdatedAt: UpdatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,93 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Benefits = newBenefitsTable("payments", "benefits", "")
type benefitsTable struct {
postgres.Table
// Columns
AccountID postgres.ColumnString
Origin postgres.ColumnString
AdsPaidUntil postgres.ColumnTimestampz
AdsForever postgres.ColumnBool
Hints postgres.ColumnInteger
UpdatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type BenefitsTable struct {
benefitsTable
EXCLUDED benefitsTable
}
// AS creates new BenefitsTable with assigned alias
func (a BenefitsTable) AS(alias string) *BenefitsTable {
return newBenefitsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new BenefitsTable with assigned schema name
func (a BenefitsTable) FromSchema(schemaName string) *BenefitsTable {
return newBenefitsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new BenefitsTable with assigned table prefix
func (a BenefitsTable) WithPrefix(prefix string) *BenefitsTable {
return newBenefitsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new BenefitsTable with assigned table suffix
func (a BenefitsTable) WithSuffix(suffix string) *BenefitsTable {
return newBenefitsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newBenefitsTable(schemaName, tableName, alias string) *BenefitsTable {
return &BenefitsTable{
benefitsTable: newBenefitsTableImpl(schemaName, tableName, alias),
EXCLUDED: newBenefitsTableImpl("", "excluded", ""),
}
}
func newBenefitsTableImpl(schemaName, tableName, alias string) benefitsTable {
var (
AccountIDColumn = postgres.StringColumn("account_id")
OriginColumn = postgres.StringColumn("origin")
AdsPaidUntilColumn = postgres.TimestampzColumn("ads_paid_until")
AdsForeverColumn = postgres.BoolColumn("ads_forever")
HintsColumn = postgres.IntegerColumn("hints")
UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
allColumns = postgres.ColumnList{AccountIDColumn, OriginColumn, AdsPaidUntilColumn, AdsForeverColumn, HintsColumn, UpdatedAtColumn}
mutableColumns = postgres.ColumnList{AdsPaidUntilColumn, AdsForeverColumn, HintsColumn, UpdatedAtColumn}
defaultColumns = postgres.ColumnList{AdsForeverColumn, HintsColumn, UpdatedAtColumn}
)
return benefitsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
AccountID: AccountIDColumn,
Origin: OriginColumn,
AdsPaidUntil: AdsPaidUntilColumn,
AdsForever: AdsForeverColumn,
Hints: HintsColumn,
UpdatedAt: UpdatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,78 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var CatalogAtom = newCatalogAtomTable("payments", "catalog_atom", "")
type catalogAtomTable struct {
postgres.Table
// Columns
AtomType postgres.ColumnString
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type CatalogAtomTable struct {
catalogAtomTable
EXCLUDED catalogAtomTable
}
// AS creates new CatalogAtomTable with assigned alias
func (a CatalogAtomTable) AS(alias string) *CatalogAtomTable {
return newCatalogAtomTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new CatalogAtomTable with assigned schema name
func (a CatalogAtomTable) FromSchema(schemaName string) *CatalogAtomTable {
return newCatalogAtomTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new CatalogAtomTable with assigned table prefix
func (a CatalogAtomTable) WithPrefix(prefix string) *CatalogAtomTable {
return newCatalogAtomTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new CatalogAtomTable with assigned table suffix
func (a CatalogAtomTable) WithSuffix(suffix string) *CatalogAtomTable {
return newCatalogAtomTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newCatalogAtomTable(schemaName, tableName, alias string) *CatalogAtomTable {
return &CatalogAtomTable{
catalogAtomTable: newCatalogAtomTableImpl(schemaName, tableName, alias),
EXCLUDED: newCatalogAtomTableImpl("", "excluded", ""),
}
}
func newCatalogAtomTableImpl(schemaName, tableName, alias string) catalogAtomTable {
var (
AtomTypeColumn = postgres.StringColumn("atom_type")
allColumns = postgres.ColumnList{AtomTypeColumn}
mutableColumns = postgres.ColumnList{}
defaultColumns = postgres.ColumnList{}
)
return catalogAtomTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
AtomType: AtomTypeColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,93 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Config = newConfigTable("payments", "config", "")
type configTable struct {
postgres.Table
// Columns
OnlyRow postgres.ColumnBool
RewardedPayoutChips postgres.ColumnInteger
CooldownGlobalSeconds postgres.ColumnInteger
CooldownVsAiSeconds postgres.ColumnInteger
CooldownHintSeconds postgres.ColumnInteger
OrderTTLSeconds postgres.ColumnInteger
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type ConfigTable struct {
configTable
EXCLUDED configTable
}
// AS creates new ConfigTable with assigned alias
func (a ConfigTable) AS(alias string) *ConfigTable {
return newConfigTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new ConfigTable with assigned schema name
func (a ConfigTable) FromSchema(schemaName string) *ConfigTable {
return newConfigTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new ConfigTable with assigned table prefix
func (a ConfigTable) WithPrefix(prefix string) *ConfigTable {
return newConfigTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new ConfigTable with assigned table suffix
func (a ConfigTable) WithSuffix(suffix string) *ConfigTable {
return newConfigTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newConfigTable(schemaName, tableName, alias string) *ConfigTable {
return &ConfigTable{
configTable: newConfigTableImpl(schemaName, tableName, alias),
EXCLUDED: newConfigTableImpl("", "excluded", ""),
}
}
func newConfigTableImpl(schemaName, tableName, alias string) configTable {
var (
OnlyRowColumn = postgres.BoolColumn("only_row")
RewardedPayoutChipsColumn = postgres.IntegerColumn("rewarded_payout_chips")
CooldownGlobalSecondsColumn = postgres.IntegerColumn("cooldown_global_seconds")
CooldownVsAiSecondsColumn = postgres.IntegerColumn("cooldown_vs_ai_seconds")
CooldownHintSecondsColumn = postgres.IntegerColumn("cooldown_hint_seconds")
OrderTTLSecondsColumn = postgres.IntegerColumn("order_ttl_seconds")
allColumns = postgres.ColumnList{OnlyRowColumn, RewardedPayoutChipsColumn, CooldownGlobalSecondsColumn, CooldownVsAiSecondsColumn, CooldownHintSecondsColumn, OrderTTLSecondsColumn}
mutableColumns = postgres.ColumnList{RewardedPayoutChipsColumn, CooldownGlobalSecondsColumn, CooldownVsAiSecondsColumn, CooldownHintSecondsColumn, OrderTTLSecondsColumn}
defaultColumns = postgres.ColumnList{OnlyRowColumn, RewardedPayoutChipsColumn, CooldownGlobalSecondsColumn, CooldownVsAiSecondsColumn, CooldownHintSecondsColumn, OrderTTLSecondsColumn}
)
return configTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
OnlyRow: OnlyRowColumn,
RewardedPayoutChips: RewardedPayoutChipsColumn,
CooldownGlobalSeconds: CooldownGlobalSecondsColumn,
CooldownVsAiSeconds: CooldownVsAiSecondsColumn,
CooldownHintSeconds: CooldownHintSecondsColumn,
OrderTTLSeconds: OrderTTLSecondsColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,111 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Ledger = newLedgerTable("payments", "ledger", "")
type ledgerTable struct {
postgres.Table
// Columns
LedgerID postgres.ColumnString
AccountID postgres.ColumnString
Kind postgres.ColumnString
Source postgres.ColumnString
Origin postgres.ColumnString
ChipsDelta postgres.ColumnInteger
ProductID postgres.ColumnString
OrderID postgres.ColumnString
Provider postgres.ColumnString
ProviderPaymentID postgres.ColumnString
Snapshot postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type LedgerTable struct {
ledgerTable
EXCLUDED ledgerTable
}
// AS creates new LedgerTable with assigned alias
func (a LedgerTable) AS(alias string) *LedgerTable {
return newLedgerTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new LedgerTable with assigned schema name
func (a LedgerTable) FromSchema(schemaName string) *LedgerTable {
return newLedgerTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new LedgerTable with assigned table prefix
func (a LedgerTable) WithPrefix(prefix string) *LedgerTable {
return newLedgerTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new LedgerTable with assigned table suffix
func (a LedgerTable) WithSuffix(suffix string) *LedgerTable {
return newLedgerTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newLedgerTable(schemaName, tableName, alias string) *LedgerTable {
return &LedgerTable{
ledgerTable: newLedgerTableImpl(schemaName, tableName, alias),
EXCLUDED: newLedgerTableImpl("", "excluded", ""),
}
}
func newLedgerTableImpl(schemaName, tableName, alias string) ledgerTable {
var (
LedgerIDColumn = postgres.StringColumn("ledger_id")
AccountIDColumn = postgres.StringColumn("account_id")
KindColumn = postgres.StringColumn("kind")
SourceColumn = postgres.StringColumn("source")
OriginColumn = postgres.StringColumn("origin")
ChipsDeltaColumn = postgres.IntegerColumn("chips_delta")
ProductIDColumn = postgres.StringColumn("product_id")
OrderIDColumn = postgres.StringColumn("order_id")
ProviderColumn = postgres.StringColumn("provider")
ProviderPaymentIDColumn = postgres.StringColumn("provider_payment_id")
SnapshotColumn = postgres.StringColumn("snapshot")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
allColumns = postgres.ColumnList{LedgerIDColumn, AccountIDColumn, KindColumn, SourceColumn, OriginColumn, ChipsDeltaColumn, ProductIDColumn, OrderIDColumn, ProviderColumn, ProviderPaymentIDColumn, SnapshotColumn, CreatedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, KindColumn, SourceColumn, OriginColumn, ChipsDeltaColumn, ProductIDColumn, OrderIDColumn, ProviderColumn, ProviderPaymentIDColumn, SnapshotColumn, CreatedAtColumn}
defaultColumns = postgres.ColumnList{ChipsDeltaColumn, CreatedAtColumn}
)
return ledgerTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
LedgerID: LedgerIDColumn,
AccountID: AccountIDColumn,
Kind: KindColumn,
Source: SourceColumn,
Origin: OriginColumn,
ChipsDelta: ChipsDeltaColumn,
ProductID: ProductIDColumn,
OrderID: OrderIDColumn,
Provider: ProviderColumn,
ProviderPaymentID: ProviderPaymentIDColumn,
Snapshot: SnapshotColumn,
CreatedAt: CreatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,111 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Orders = newOrdersTable("payments", "orders", "")
type ordersTable struct {
postgres.Table
// Columns
OrderID postgres.ColumnString
AccountID postgres.ColumnString
Platform postgres.ColumnString
ProductID postgres.ColumnString
ExpectedAmount postgres.ColumnInteger
Currency postgres.ColumnString
Origin postgres.ColumnString
Status postgres.ColumnString
Provider postgres.ColumnString
ProviderPaymentID postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
UpdatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type OrdersTable struct {
ordersTable
EXCLUDED ordersTable
}
// AS creates new OrdersTable with assigned alias
func (a OrdersTable) AS(alias string) *OrdersTable {
return newOrdersTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new OrdersTable with assigned schema name
func (a OrdersTable) FromSchema(schemaName string) *OrdersTable {
return newOrdersTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new OrdersTable with assigned table prefix
func (a OrdersTable) WithPrefix(prefix string) *OrdersTable {
return newOrdersTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new OrdersTable with assigned table suffix
func (a OrdersTable) WithSuffix(suffix string) *OrdersTable {
return newOrdersTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newOrdersTable(schemaName, tableName, alias string) *OrdersTable {
return &OrdersTable{
ordersTable: newOrdersTableImpl(schemaName, tableName, alias),
EXCLUDED: newOrdersTableImpl("", "excluded", ""),
}
}
func newOrdersTableImpl(schemaName, tableName, alias string) ordersTable {
var (
OrderIDColumn = postgres.StringColumn("order_id")
AccountIDColumn = postgres.StringColumn("account_id")
PlatformColumn = postgres.StringColumn("platform")
ProductIDColumn = postgres.StringColumn("product_id")
ExpectedAmountColumn = postgres.IntegerColumn("expected_amount")
CurrencyColumn = postgres.StringColumn("currency")
OriginColumn = postgres.StringColumn("origin")
StatusColumn = postgres.StringColumn("status")
ProviderColumn = postgres.StringColumn("provider")
ProviderPaymentIDColumn = postgres.StringColumn("provider_payment_id")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
allColumns = postgres.ColumnList{OrderIDColumn, AccountIDColumn, PlatformColumn, ProductIDColumn, ExpectedAmountColumn, CurrencyColumn, OriginColumn, StatusColumn, ProviderColumn, ProviderPaymentIDColumn, CreatedAtColumn, UpdatedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, PlatformColumn, ProductIDColumn, ExpectedAmountColumn, CurrencyColumn, OriginColumn, StatusColumn, ProviderColumn, ProviderPaymentIDColumn, CreatedAtColumn, UpdatedAtColumn}
defaultColumns = postgres.ColumnList{StatusColumn, CreatedAtColumn, UpdatedAtColumn}
)
return ordersTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
OrderID: OrderIDColumn,
AccountID: AccountIDColumn,
Platform: PlatformColumn,
ProductID: ProductIDColumn,
ExpectedAmount: ExpectedAmountColumn,
Currency: CurrencyColumn,
Origin: OriginColumn,
Status: StatusColumn,
Provider: ProviderColumn,
ProviderPaymentID: ProviderPaymentIDColumn,
CreatedAt: CreatedAtColumn,
UpdatedAt: UpdatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,96 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var PaymentEvents = newPaymentEventsTable("payments", "payment_events", "")
type paymentEventsTable struct {
postgres.Table
// Columns
EventID postgres.ColumnString
AccountID postgres.ColumnString
OrderID postgres.ColumnString
Type postgres.ColumnString
Payload postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
DispatchedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type PaymentEventsTable struct {
paymentEventsTable
EXCLUDED paymentEventsTable
}
// AS creates new PaymentEventsTable with assigned alias
func (a PaymentEventsTable) AS(alias string) *PaymentEventsTable {
return newPaymentEventsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new PaymentEventsTable with assigned schema name
func (a PaymentEventsTable) FromSchema(schemaName string) *PaymentEventsTable {
return newPaymentEventsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new PaymentEventsTable with assigned table prefix
func (a PaymentEventsTable) WithPrefix(prefix string) *PaymentEventsTable {
return newPaymentEventsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new PaymentEventsTable with assigned table suffix
func (a PaymentEventsTable) WithSuffix(suffix string) *PaymentEventsTable {
return newPaymentEventsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newPaymentEventsTable(schemaName, tableName, alias string) *PaymentEventsTable {
return &PaymentEventsTable{
paymentEventsTable: newPaymentEventsTableImpl(schemaName, tableName, alias),
EXCLUDED: newPaymentEventsTableImpl("", "excluded", ""),
}
}
func newPaymentEventsTableImpl(schemaName, tableName, alias string) paymentEventsTable {
var (
EventIDColumn = postgres.StringColumn("event_id")
AccountIDColumn = postgres.StringColumn("account_id")
OrderIDColumn = postgres.StringColumn("order_id")
TypeColumn = postgres.StringColumn("type")
PayloadColumn = postgres.StringColumn("payload")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
DispatchedAtColumn = postgres.TimestampzColumn("dispatched_at")
allColumns = postgres.ColumnList{EventIDColumn, AccountIDColumn, OrderIDColumn, TypeColumn, PayloadColumn, CreatedAtColumn, DispatchedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, OrderIDColumn, TypeColumn, PayloadColumn, CreatedAtColumn, DispatchedAtColumn}
defaultColumns = postgres.ColumnList{CreatedAtColumn}
)
return paymentEventsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
EventID: EventIDColumn,
AccountID: AccountIDColumn,
OrderID: OrderIDColumn,
Type: TypeColumn,
Payload: PayloadColumn,
CreatedAt: CreatedAtColumn,
DispatchedAt: DispatchedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,90 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Product = newProductTable("payments", "product", "")
type productTable struct {
postgres.Table
// Columns
ProductID postgres.ColumnString
Title postgres.ColumnString
Active postgres.ColumnBool
CreatedAt postgres.ColumnTimestampz
UpdatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type ProductTable struct {
productTable
EXCLUDED productTable
}
// AS creates new ProductTable with assigned alias
func (a ProductTable) AS(alias string) *ProductTable {
return newProductTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new ProductTable with assigned schema name
func (a ProductTable) FromSchema(schemaName string) *ProductTable {
return newProductTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new ProductTable with assigned table prefix
func (a ProductTable) WithPrefix(prefix string) *ProductTable {
return newProductTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new ProductTable with assigned table suffix
func (a ProductTable) WithSuffix(suffix string) *ProductTable {
return newProductTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newProductTable(schemaName, tableName, alias string) *ProductTable {
return &ProductTable{
productTable: newProductTableImpl(schemaName, tableName, alias),
EXCLUDED: newProductTableImpl("", "excluded", ""),
}
}
func newProductTableImpl(schemaName, tableName, alias string) productTable {
var (
ProductIDColumn = postgres.StringColumn("product_id")
TitleColumn = postgres.StringColumn("title")
ActiveColumn = postgres.BoolColumn("active")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
allColumns = postgres.ColumnList{ProductIDColumn, TitleColumn, ActiveColumn, CreatedAtColumn, UpdatedAtColumn}
mutableColumns = postgres.ColumnList{TitleColumn, ActiveColumn, CreatedAtColumn, UpdatedAtColumn}
defaultColumns = postgres.ColumnList{TitleColumn, ActiveColumn, CreatedAtColumn, UpdatedAtColumn}
)
return productTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
ProductID: ProductIDColumn,
Title: TitleColumn,
Active: ActiveColumn,
CreatedAt: CreatedAtColumn,
UpdatedAt: UpdatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,84 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var ProductItem = newProductItemTable("payments", "product_item", "")
type productItemTable struct {
postgres.Table
// Columns
ProductID postgres.ColumnString
AtomType postgres.ColumnString
Quantity postgres.ColumnInteger
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type ProductItemTable struct {
productItemTable
EXCLUDED productItemTable
}
// AS creates new ProductItemTable with assigned alias
func (a ProductItemTable) AS(alias string) *ProductItemTable {
return newProductItemTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new ProductItemTable with assigned schema name
func (a ProductItemTable) FromSchema(schemaName string) *ProductItemTable {
return newProductItemTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new ProductItemTable with assigned table prefix
func (a ProductItemTable) WithPrefix(prefix string) *ProductItemTable {
return newProductItemTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new ProductItemTable with assigned table suffix
func (a ProductItemTable) WithSuffix(suffix string) *ProductItemTable {
return newProductItemTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newProductItemTable(schemaName, tableName, alias string) *ProductItemTable {
return &ProductItemTable{
productItemTable: newProductItemTableImpl(schemaName, tableName, alias),
EXCLUDED: newProductItemTableImpl("", "excluded", ""),
}
}
func newProductItemTableImpl(schemaName, tableName, alias string) productItemTable {
var (
ProductIDColumn = postgres.StringColumn("product_id")
AtomTypeColumn = postgres.StringColumn("atom_type")
QuantityColumn = postgres.IntegerColumn("quantity")
allColumns = postgres.ColumnList{ProductIDColumn, AtomTypeColumn, QuantityColumn}
mutableColumns = postgres.ColumnList{QuantityColumn}
defaultColumns = postgres.ColumnList{}
)
return productItemTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
ProductID: ProductIDColumn,
AtomType: AtomTypeColumn,
Quantity: QuantityColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,87 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var ProductPrice = newProductPriceTable("payments", "product_price", "")
type productPriceTable struct {
postgres.Table
// Columns
ProductID postgres.ColumnString
Method postgres.ColumnString
Currency postgres.ColumnString
Amount postgres.ColumnInteger
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type ProductPriceTable struct {
productPriceTable
EXCLUDED productPriceTable
}
// AS creates new ProductPriceTable with assigned alias
func (a ProductPriceTable) AS(alias string) *ProductPriceTable {
return newProductPriceTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new ProductPriceTable with assigned schema name
func (a ProductPriceTable) FromSchema(schemaName string) *ProductPriceTable {
return newProductPriceTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new ProductPriceTable with assigned table prefix
func (a ProductPriceTable) WithPrefix(prefix string) *ProductPriceTable {
return newProductPriceTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new ProductPriceTable with assigned table suffix
func (a ProductPriceTable) WithSuffix(suffix string) *ProductPriceTable {
return newProductPriceTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newProductPriceTable(schemaName, tableName, alias string) *ProductPriceTable {
return &ProductPriceTable{
productPriceTable: newProductPriceTableImpl(schemaName, tableName, alias),
EXCLUDED: newProductPriceTableImpl("", "excluded", ""),
}
}
func newProductPriceTableImpl(schemaName, tableName, alias string) productPriceTable {
var (
ProductIDColumn = postgres.StringColumn("product_id")
MethodColumn = postgres.StringColumn("method")
CurrencyColumn = postgres.StringColumn("currency")
AmountColumn = postgres.IntegerColumn("amount")
allColumns = postgres.ColumnList{ProductIDColumn, MethodColumn, CurrencyColumn, AmountColumn}
mutableColumns = postgres.ColumnList{ProductIDColumn, MethodColumn, CurrencyColumn, AmountColumn}
defaultColumns = postgres.ColumnList{}
)
return productPriceTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
ProductID: ProductIDColumn,
Method: MethodColumn,
Currency: CurrencyColumn,
Amount: AmountColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,24 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
// UseSchema sets a new schema name for all generated table SQL builder types. It is recommended to invoke
// this method only once at the beginning of the program.
func UseSchema(schema string) {
AccountRisk = AccountRisk.FromSchema(schema)
Balances = Balances.FromSchema(schema)
Benefits = Benefits.FromSchema(schema)
CatalogAtom = CatalogAtom.FromSchema(schema)
Config = Config.FromSchema(schema)
Ledger = Ledger.FromSchema(schema)
Orders = Orders.FromSchema(schema)
PaymentEvents = PaymentEvents.FromSchema(schema)
Product = Product.FromSchema(schema)
ProductItem = ProductItem.FromSchema(schema)
ProductPrice = ProductPrice.FromSchema(schema)
}
@@ -0,0 +1,266 @@
-- Payments data foundation: a self-contained `payments` schema for the in-game
-- currency, wallets, benefits, catalog, orders and the append-only operations
-- ledger. Nothing is wired to real money yet — this is the substrate the rest of
-- the payments domain builds on. Mechanics live in docs/PAYMENTS.md.
--
-- Isolation. The schema is confined to a dedicated NOLOGIN role that holds ALL
-- privileges on `payments.*` and none on `backend.*`; the backend application
-- keeps its single (superuser) pool, so the DB grants are a stepping-stone to a
-- future separate login/process rather than a runtime wall. The runtime wall is
-- code-level: only the payments package reaches these tables (an import-boundary
-- test guards it). There is deliberately NO cross-schema foreign key to
-- `backend.accounts`: `account_id` is a plain uuid, kept referentially honest in
-- code and joined to the tombstoned account / retained-identities dossier by the
-- stable account id — which keeps the domain extractable into its own database.
--
-- The ledger is append-only, enforced by a trigger (a superuser bypasses table
-- privileges, so a REVOKE would not bind the application). Money is stored as an
-- integer amount in the currency's minor units (RUB kopecks; Votes/Stars/chips
-- are whole units, scale 1), never a float — integer-currency integrality is
-- therefore structural.
--
-- Legacy note: backend.accounts.hint_balance and backend.accounts.paid_account
-- are superseded by the segmented model here and are DEPRECATED. They are NOT
-- dropped in this expand phase — reads still use them until the currency core
-- flips them, and the DROP is a later contract-phase migration (image rollback
-- must stay DB-safe). Neither was ever set in production.
--
-- Expand-contract: everything here is additive in its own schema, so a backend
-- image rollback stays DB-safe (older code simply ignores the new schema).
-- +goose Up
CREATE SCHEMA IF NOT EXISTS payments;
-- +goose StatementBegin
DO $$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'payments') THEN
CREATE ROLE payments NOLOGIN;
END IF;
END
$$;
-- +goose StatementEnd
GRANT USAGE ON SCHEMA payments TO payments;
-- Base value types (atoms) a product is composed of. A fixed, code-known set.
CREATE TABLE payments.catalog_atom (
atom_type text NOT NULL,
CONSTRAINT catalog_atom_pkey PRIMARY KEY (atom_type),
CONSTRAINT catalog_atom_type_chk
CHECK ((atom_type = ANY (ARRAY['chips'::text, 'hints'::text, 'noads_days'::text, 'tournament'::text])))
);
INSERT INTO payments.catalog_atom (atom_type) VALUES
('chips'), ('hints'), ('noads_days'), ('tournament');
-- A sellable product: a set of atoms at a price. Soft-deleted (deactivated),
-- never removed, so historical orders/ledger keep resolving it.
CREATE TABLE payments.product (
product_id uuid NOT NULL,
title text DEFAULT ''::text NOT NULL,
active boolean DEFAULT true NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT product_pkey PRIMARY KEY (product_id)
);
-- The atom composition of a product (e.g. 250 hints + 30 no-ads days).
CREATE TABLE payments.product_item (
product_id uuid NOT NULL,
atom_type text NOT NULL,
quantity integer NOT NULL,
CONSTRAINT product_item_pkey PRIMARY KEY (product_id, atom_type),
CONSTRAINT product_item_product_fkey FOREIGN KEY (product_id)
REFERENCES payments.product (product_id) ON DELETE CASCADE,
CONSTRAINT product_item_atom_fkey FOREIGN KEY (atom_type)
REFERENCES payments.catalog_atom (atom_type),
CONSTRAINT product_item_quantity_chk CHECK ((quantity > 0))
);
-- Price of a product. A chip pack carries a money price per method
-- (multi-currency Votes/Stars/RUB); a value carries a single chips price
-- (currency='CHIP', method NULL). `amount` is an integer in the currency's
-- minor units (RUB kopecks; Votes/Stars/chips whole, scale 1).
CREATE TABLE payments.product_price (
product_id uuid NOT NULL,
method text,
currency text NOT NULL,
amount bigint NOT NULL,
CONSTRAINT product_price_product_fkey FOREIGN KEY (product_id)
REFERENCES payments.product (product_id) ON DELETE CASCADE,
CONSTRAINT product_price_method_chk
CHECK ((method IS NULL) OR (method = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text]))),
CONSTRAINT product_price_currency_chk
CHECK ((currency = ANY (ARRAY['RUB'::text, 'VOTE'::text, 'XTR'::text, 'CHIP'::text]))),
CONSTRAINT product_price_amount_chk CHECK ((amount >= 0))
);
-- One price row per (product, method, currency); NULL method (a value's chip
-- price) collapses to one row via the COALESCE key.
CREATE UNIQUE INDEX product_price_unique_idx
ON payments.product_price (product_id, COALESCE(method, ''::text), currency);
-- A pre-created purchase intent. `expected_amount` is in `currency` minor units.
CREATE TABLE payments.orders (
order_id uuid NOT NULL,
account_id uuid NOT NULL,
platform text NOT NULL,
product_id uuid NOT NULL,
expected_amount bigint NOT NULL,
currency text NOT NULL,
origin text NOT NULL,
status text DEFAULT 'pending'::text NOT NULL,
provider text,
provider_payment_id text,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT orders_pkey PRIMARY KEY (order_id),
CONSTRAINT orders_product_fkey FOREIGN KEY (product_id)
REFERENCES payments.product (product_id),
CONSTRAINT orders_status_chk
CHECK ((status = ANY (ARRAY['pending'::text, 'paid'::text, 'expired'::text]))),
CONSTRAINT orders_origin_chk
CHECK ((origin = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text]))),
CONSTRAINT orders_currency_chk
CHECK ((currency = ANY (ARRAY['RUB'::text, 'VOTE'::text, 'XTR'::text, 'CHIP'::text]))),
CONSTRAINT orders_expected_amount_chk CHECK ((expected_amount >= 0))
);
-- The pending-expiry sweep scans (status, created_at).
CREATE INDEX orders_status_created_at_idx ON payments.orders (status, created_at);
-- The append-only operations ledger: every fund / spend / admin_grant / refund.
-- `chips_delta` is signed (0 for a grant, which credits values not chips);
-- `snapshot` records the sold atoms + price for a spend/grant. Never updated or
-- deleted (a trigger enforces it); a reversal is a new `refund` row.
CREATE TABLE payments.ledger (
ledger_id uuid NOT NULL,
account_id uuid NOT NULL,
kind text NOT NULL,
source text,
origin text,
chips_delta integer DEFAULT 0 NOT NULL,
product_id uuid,
order_id uuid,
provider text,
provider_payment_id text,
snapshot jsonb,
created_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT ledger_pkey PRIMARY KEY (ledger_id),
CONSTRAINT ledger_product_fkey FOREIGN KEY (product_id)
REFERENCES payments.product (product_id),
CONSTRAINT ledger_order_fkey FOREIGN KEY (order_id)
REFERENCES payments.orders (order_id),
CONSTRAINT ledger_kind_chk
CHECK ((kind = ANY (ARRAY['fund'::text, 'spend'::text, 'admin_grant'::text, 'refund'::text]))),
CONSTRAINT ledger_source_chk
CHECK ((source IS NULL) OR (source = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text]))),
CONSTRAINT ledger_origin_chk
CHECK ((origin IS NULL) OR (origin = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text])))
);
-- Idempotency key: a provider callback credits at most once. Partial so rows
-- without a provider payment id (spend/admin_grant) are unconstrained.
CREATE UNIQUE INDEX ledger_provider_payment_idx
ON payments.ledger (provider, provider_payment_id)
WHERE provider_payment_id IS NOT NULL;
-- +goose StatementBegin
CREATE FUNCTION payments.ledger_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'payments.ledger is append-only: % denied', TG_OP;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER ledger_no_mutation
BEFORE UPDATE OR DELETE ON payments.ledger
FOR EACH ROW EXECUTE FUNCTION payments.ledger_append_only();
-- Materialised chip balance, segmented by funding source. A fast cache of the
-- ledger, recomputable from it; created lazily on first fund (up to three rows
-- per account, absent = zero).
CREATE TABLE payments.balances (
account_id uuid NOT NULL,
source text NOT NULL,
chips integer DEFAULT 0 NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT balances_pkey PRIMARY KEY (account_id, source),
CONSTRAINT balances_source_chk
CHECK ((source = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text]))),
CONSTRAINT balances_chips_chk CHECK ((chips >= 0))
);
-- Materialised benefits, segmented by the purchase origin. no-ads is a duration
-- (ads_paid_until) plus a perpetual override (ads_forever); hints is a count.
-- Created lazily on first grant/spend.
CREATE TABLE payments.benefits (
account_id uuid NOT NULL,
origin text NOT NULL,
ads_paid_until timestamp with time zone,
ads_forever boolean DEFAULT false NOT NULL,
hints integer DEFAULT 0 NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT benefits_pkey PRIMARY KEY (account_id, origin),
CONSTRAINT benefits_origin_chk
CHECK ((origin = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text]))),
CONSTRAINT benefits_hints_chk CHECK ((hints >= 0))
);
-- The single-row tunable config (durations in whole seconds — go-jet stringifies
-- interval; payouts as counts). Edited in the admin console, no release needed.
CREATE TABLE payments.config (
only_row boolean DEFAULT true NOT NULL,
rewarded_payout_chips integer DEFAULT 0 NOT NULL,
cooldown_global_seconds integer DEFAULT 300 NOT NULL,
cooldown_vs_ai_seconds integer DEFAULT 1800 NOT NULL,
cooldown_hint_seconds integer DEFAULT 60 NOT NULL,
order_ttl_seconds integer DEFAULT 1800 NOT NULL,
CONSTRAINT config_pkey PRIMARY KEY (only_row),
CONSTRAINT config_single_row_chk CHECK (only_row)
);
INSERT INTO payments.config (only_row) VALUES (true);
-- Payment lifecycle events for the dispatcher (live stream / botlink / email).
CREATE TABLE payments.payment_events (
event_id uuid NOT NULL,
account_id uuid NOT NULL,
order_id uuid,
type text NOT NULL,
payload jsonb,
created_at timestamp with time zone DEFAULT now() NOT NULL,
dispatched_at timestamp with time zone,
CONSTRAINT payment_events_pkey PRIMARY KEY (event_id),
CONSTRAINT payment_events_order_fkey FOREIGN KEY (order_id)
REFERENCES payments.orders (order_id),
CONSTRAINT payment_events_type_chk
CHECK ((type = ANY (ARRAY['succeeded'::text, 'failed'::text, 'refunded'::text])))
);
CREATE INDEX payment_events_dispatch_idx
ON payments.payment_events (dispatched_at)
WHERE dispatched_at IS NULL;
-- Confine the payments role to this schema: ALL on its tables, nothing on
-- backend. New tables added later inherit the grant via default privileges.
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA payments TO payments;
ALTER DEFAULT PRIVILEGES IN SCHEMA payments GRANT ALL ON TABLES TO payments;
-- +goose Down
ALTER DEFAULT PRIVILEGES IN SCHEMA payments REVOKE ALL ON TABLES FROM payments;
DROP SCHEMA IF EXISTS payments CASCADE;
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT FROM pg_roles WHERE rolname = 'payments') THEN
EXECUTE 'DROP OWNED BY payments';
DROP ROLE payments;
END IF;
END
$$;
-- +goose StatementEnd
@@ -0,0 +1,23 @@
-- Record the trusted execution platform on a session: platform_kind (the wrapper the
-- session was established through — vk/telegram/direct) plus platform_subtype (the device
-- family — ios/android/web). Both are nullable: a session minted before this migration, or
-- one the gateway could not attribute, carries NULL and is treated as untrusted (view-only)
-- by the payments compliance gate. kind is derived server-side from the validated establish
-- path (never a client field); the subtype is trustworthy only for VK (vk_platform rides
-- inside the signed launch params) and best-effort for telegram/direct.
--
-- Expand-contract: the columns are additive and nullable, so a backend image rollback stays
-- DB-safe (older code neither writes nor reads them). The table shape changes, so the
-- generated go-jet model IS regenerated.
-- +goose Up
ALTER TABLE backend.sessions ADD COLUMN platform_kind text;
ALTER TABLE backend.sessions ADD COLUMN platform_subtype text;
ALTER TABLE backend.sessions ADD CONSTRAINT sessions_platform_kind_chk CHECK ((platform_kind IS NULL) OR (platform_kind = ANY (ARRAY['vk'::text, 'telegram'::text, 'direct'::text])));
ALTER TABLE backend.sessions ADD CONSTRAINT sessions_platform_subtype_chk CHECK ((platform_subtype IS NULL) OR (platform_subtype = ANY (ARRAY['ios'::text, 'android'::text, 'web'::text])));
-- +goose Down
ALTER TABLE backend.sessions DROP CONSTRAINT sessions_platform_subtype_chk;
ALTER TABLE backend.sessions DROP CONSTRAINT sessions_platform_kind_chk;
ALTER TABLE backend.sessions DROP COLUMN platform_subtype;
ALTER TABLE backend.sessions DROP COLUMN platform_kind;
@@ -0,0 +1,25 @@
-- Per-account payment risk: the loss and abuse signal an external/admin refund leaves
-- behind when the refunded chips were already spent. A refund revokes chips best-effort
-- and never drives a balance negative (D27, balances_chips_chk); the unrecoverable
-- remainder is a recorded loss and flips an abuse flag the /_gm financial report reads
-- (D40, E7). Mutable per-account state (upserted on each such refund), so — unlike the
-- ledger — it carries no append-only trigger. Additive: a new table only, so goose
-- applies it forward with no rewrite of existing data (the contour is not wiped). The
-- payments role inherits ALL on it via the schema default privileges set in 00010.
-- +goose Up
CREATE TABLE payments.account_risk (
account_id uuid NOT NULL,
-- abuse flips true the first time a refund cannot fully reclaim its chips (spent).
abuse boolean DEFAULT false NOT NULL,
-- loss_chips accumulates the unrecoverable chips across such refunds (bigint: an
-- accumulator, mapped to int64 by go-jet — not the numeric->float64 trap).
loss_chips bigint DEFAULT 0 NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT account_risk_pkey PRIMARY KEY (account_id),
CONSTRAINT account_risk_loss_chips_chk CHECK ((loss_chips >= 0))
);
-- +goose Down
DROP TABLE IF EXISTS payments.account_risk;
+104
View File
@@ -0,0 +1,104 @@
// Package robokassa builds and verifies Robokassa direct-rail (RUB) payments: it forms the signed
// hosted-payment URL a client is sent to, and verifies the Result-URL server callback that credits
// an order. It is pure provider glue — no database, no payments-domain coupling — so the payments
// domain stays provider-agnostic and this layer is unit-testable in isolation.
//
// The order is threaded through Robokassa's custom-parameter channel as Shp_order=<order id> (echoed
// back in the callback and bound into the signature), not the numeric InvId, because an order id is
// a uuid; InvId is sent as 0. Idempotency is therefore keyed on the order id at the credit site.
// Signatures use SHA-256 (configured to match the shop's technical settings); the shop's test mode
// is carried by IsTest.
package robokassa
import (
"crypto/sha256"
"encoding/hex"
"net/url"
"sort"
"strings"
"github.com/google/uuid"
)
// payEndpoint is Robokassa's hosted payment page; the signed query sends the client there.
const payEndpoint = "https://auth.robokassa.ru/Merchant/Index.aspx"
// Config is a Robokassa shop's credentials. Password1 signs the outgoing payment request;
// Password2 signs (and so verifies) the incoming Result callback. IsTest adds IsTest=1 so the shop's
// test mode simulates payments without money movement.
type Config struct {
MerchantLogin string
Password1 string
Password2 string
IsTest bool
}
// PaymentURL builds the signed hosted-payment URL for an order: amount is the OutSum decimal string
// (roubles, e.g. "149.00"), description is the human payment purpose. The order id rides as
// Shp_order and is bound into the SHA-256 signature; InvId is 0 (unused).
func (c Config) PaymentURL(orderID uuid.UUID, amount, description string) string {
q := url.Values{}
q.Set("Shp_order", orderID.String())
// Signature base: MerchantLogin:OutSum:InvId:Password1[:Shp_key=value...sorted].
base := c.MerchantLogin + ":" + amount + ":0:" + c.Password1 + shpSuffix(q)
q.Set("MerchantLogin", c.MerchantLogin)
q.Set("OutSum", amount)
q.Set("InvId", "0")
q.Set("Description", description)
q.Set("SignatureValue", sign(base))
if c.IsTest {
q.Set("IsTest", "1")
}
return payEndpoint + "?" + q.Encode()
}
// VerifyResult verifies a Result-URL callback and extracts the order it credits. It recomputes the
// SHA-256 signature OutSum:InvId:Password2[:Shp_...sorted] over the callback's own fields and
// compares it (case-insensitively) with SignatureValue. On success it returns the order id (from
// Shp_order) and the raw OutSum string the caller re-checks against the order amount; on any
// missing field, a signature mismatch or an unparseable order id it returns ok=false.
func (c Config) VerifyResult(v url.Values) (orderID uuid.UUID, outSum string, ok bool) {
outSum = v.Get("OutSum")
sig := v.Get("SignatureValue")
order := v.Get("Shp_order")
if outSum == "" || sig == "" || order == "" {
return uuid.Nil, "", false
}
// Robokassa signs with the InvId it returns in the callback; recompute with that same value.
base := outSum + ":" + v.Get("InvId") + ":" + c.Password2 + shpSuffix(v)
if !strings.EqualFold(sign(base), sig) {
return uuid.Nil, "", false
}
id, err := uuid.Parse(order)
if err != nil {
return uuid.Nil, "", false
}
return id, outSum, true
}
// shpSuffix renders the Shp_ custom parameters of v as Robokassa binds them into a signature:
// every Shp_-prefixed key, sorted alphabetically, appended as ":key=value".
func shpSuffix(v url.Values) string {
var keys []string
for k := range v {
if strings.HasPrefix(k, "Shp_") {
keys = append(keys, k)
}
}
sort.Strings(keys)
var b strings.Builder
for _, k := range keys {
b.WriteString(":")
b.WriteString(k)
b.WriteString("=")
b.WriteString(v.Get(k))
}
return b.String()
}
// sign returns the lowercase hex SHA-256 of s, the hash Robokassa compares against SignatureValue.
func sign(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
@@ -0,0 +1,85 @@
package robokassa
import (
"net/url"
"strings"
"testing"
"github.com/google/uuid"
)
func testCfg() Config {
return Config{MerchantLogin: "shop", Password1: "p1", Password2: "p2", IsTest: true}
}
// resultSig computes the Pass2 Result signature Robokassa would send for a callback carrying only
// Shp_order — the fixture the verifier must accept.
func resultSig(pass2, outSum, invID string, orderID uuid.UUID) string {
return sign(outSum + ":" + invID + ":" + pass2 + ":Shp_order=" + orderID.String())
}
func TestPaymentURL(t *testing.T) {
cfg := testCfg()
id := uuid.New()
u, err := url.Parse(cfg.PaymentURL(id, "149.00", "10 chips"))
if err != nil {
t.Fatalf("parse payment url: %v", err)
}
q := u.Query()
if got := q.Get("OutSum"); got != "149.00" {
t.Errorf("OutSum = %q, want 149.00", got)
}
if got := q.Get("InvId"); got != "0" {
t.Errorf("InvId = %q, want 0 (unused)", got)
}
if got := q.Get("Shp_order"); got != id.String() {
t.Errorf("Shp_order = %q, want the order id", got)
}
if got := q.Get("IsTest"); got != "1" {
t.Errorf("IsTest = %q, want 1 (test shop)", got)
}
want := sign("shop:149.00:0:p1:Shp_order=" + id.String())
if got := q.Get("SignatureValue"); got != want {
t.Errorf("SignatureValue = %q, want %q", got, want)
}
}
func TestVerifyResult(t *testing.T) {
cfg := testCfg()
id := uuid.New()
valid := func() url.Values {
v := url.Values{}
v.Set("OutSum", "149.00")
v.Set("InvId", "0")
v.Set("Shp_order", id.String())
// Robokassa sends the hash uppercase; the verifier must be case-insensitive.
v.Set("SignatureValue", strings.ToUpper(resultSig("p2", "149.00", "0", id)))
return v
}
gotID, gotSum, ok := cfg.VerifyResult(valid())
if !ok || gotID != id || gotSum != "149.00" {
t.Fatalf("VerifyResult(valid) = %v/%q/%v, want %v/149.00/true", gotID, gotSum, ok, id)
}
// A tampered amount breaks the signature.
tampered := valid()
tampered.Set("OutSum", "1.00")
if _, _, ok := cfg.VerifyResult(tampered); ok {
t.Error("VerifyResult accepted a tampered amount")
}
// The wrong Password2 (a forged callback) does not verify.
wrongPass := Config{MerchantLogin: "shop", Password1: "p1", Password2: "other"}
if _, _, ok := wrongPass.VerifyResult(valid()); ok {
t.Error("VerifyResult accepted a signature under the wrong password")
}
// A missing Shp_order is rejected (no order to credit).
noOrder := valid()
noOrder.Del("Shp_order")
if _, _, ok := cfg.VerifyResult(noOrder); ok {
t.Error("VerifyResult accepted a callback with no order")
}
}
+29 -6
View File
@@ -10,6 +10,7 @@ import (
"scrabble/backend/internal/ads"
"scrabble/backend/internal/engine"
"scrabble/backend/internal/notify"
"scrabble/backend/internal/payments"
)
// bannerDTO is the advertising-banner block attached to an eligible viewer's
@@ -55,7 +56,21 @@ type bannerTimingsDTO struct {
// a language switch).
func (s *Server) profileResponse(ctx context.Context, acc account.Account) profileResponse {
r := profileResponseFor(acc)
r.Banner = s.bannerFor(ctx, acc)
// Resolve the payments gate once (execution context + present sources) and feed it to both
// the hint count and the banner. The profile hint balance now comes from the payments benefit
// (context-aware), not the deprecated accounts.hint_balance column; on any failure the legacy
// value from profileResponseFor (zeroed in production) stands.
cxt, present, err := s.walletGate(ctx, acc.ID)
if err != nil {
s.log.Warn("profile: wallet gate failed", zap.String("account", acc.ID.String()), zap.Error(err))
} else if s.payments != nil {
if hints, herr := s.payments.HintsAvailable(ctx, acc.ID, cxt, present); herr == nil {
r.HintBalance = hints
} else {
s.log.Warn("profile: hint balance read failed", zap.String("account", acc.ID.String()), zap.Error(herr))
}
}
r.Banner = s.bannerFor(ctx, acc, cxt, present)
s.fillLinkedIdentities(ctx, &r, acc.ID)
r.DictVersions = s.currentDictVersions()
return r
@@ -115,7 +130,7 @@ func (s *Server) fillLinkedIdentities(ctx context.Context, r *profileResponse, a
// language, falling back to its interface language and then English. A failure
// reading roles or campaigns is logged and treated as "no banner" so the profile
// response still succeeds.
func (s *Server) bannerFor(ctx context.Context, acc account.Account) *bannerDTO {
func (s *Server) bannerFor(ctx context.Context, acc account.Account, cxt payments.Context, present []payments.Source) *bannerDTO {
if s.ads == nil {
return nil
}
@@ -124,16 +139,24 @@ func (s *Server) bannerFor(ctx context.Context, acc account.Account) *bannerDTO
s.log.Warn("banner: active set failed", zap.String("account", acc.ID.String()), zap.Error(err))
return nil
}
// An urgent campaign is shown to every viewer; otherwise the normal eligibility
// gate applies (a paid account, a non-empty hint wallet or the no_banner role
// hides the banner).
// An urgent campaign is shown to every viewer; otherwise the banner is suppressed by the
// no_banner role or by an active no-ads benefit applicable in the viewer's context (the
// payments gate — a hint balance no longer suppresses the banner). An untrusted platform is
// fail-closed by the gate, so it does not suppress the banner.
if !urgent {
hasNoBanner, err := s.accounts.HasRole(ctx, acc.ID, account.RoleNoBanner)
if err != nil {
s.log.Warn("banner: role check failed", zap.String("account", acc.ID.String()), zap.Error(err))
return nil
}
if !ads.Eligible(acc.PaidAccount, acc.HintBalance, hasNoBanner) {
adFree := false
if s.payments != nil {
if adFree, err = s.payments.AdFree(ctx, acc.ID, cxt, present); err != nil {
s.log.Warn("banner: ad-free check failed", zap.String("account", acc.ID.String()), zap.Error(err))
return nil
}
}
if hasNoBanner || adFree {
return nil
}
}
+7 -3
View File
@@ -28,10 +28,14 @@ type okResponse struct {
}
// resolveResponse maps a session token to its account. IsGuest lets the gateway
// gate guest-forbidden operations without an extra round-trip.
// gate guest-forbidden operations without an extra round-trip. PlatformKind and
// PlatformSubtype carry the session's trusted execution platform so the gateway can
// inject X-Platform; both are empty for an untrusted (pre-capture) session.
type resolveResponse struct {
UserID string `json:"user_id"`
IsGuest bool `json:"is_guest"`
UserID string `json:"user_id"`
IsGuest bool `json:"is_guest"`
PlatformKind string `json:"platform_kind"`
PlatformSubtype string `json:"platform_subtype"`
}
// profileResponse is the authenticated account's own profile. AwayStart and AwayEnd
+33
View File
@@ -15,6 +15,7 @@ import (
"scrabble/backend/internal/feedback"
"scrabble/backend/internal/game"
"scrabble/backend/internal/lobby"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/session"
"scrabble/backend/internal/social"
)
@@ -65,6 +66,28 @@ func (s *Server) registerRoutes() {
// client may still reach, to fetch the block's expiry and reason for the blocked screen.
u.GET("/block-status", s.handleBlockStatus)
}
if s.payments != nil {
// The wallet: the context-visible chip segments + benefits, the storefront catalog, and a
// chip spend on a value.
u.GET("/wallet", s.handleWallet)
u.GET("/wallet/catalog", s.handleWalletCatalog)
u.POST("/wallet/buy", s.handleWalletBuy)
}
if s.payments != nil {
// The money order endpoint dispatches by rail (direct → Robokassa, vk → VK); an
// unsupported or unconfigured rail returns 501 from the handler. The provider callbacks are
// gateway-only (the single writer): the VK payment callback (both phases handled here), and
// the Robokassa Result callback when a merchant is configured.
u.POST("/wallet/order", s.handleWalletOrder)
s.internal.POST("/payments/vk/callback", s.handleVKCallback)
// The Telegram Stars rail: the bot forwards a pre_checkout validation and a completed
// payment over the reverse bot-link; the gateway proxies both onto these gateway-only routes.
s.internal.POST("/payments/telegram/precheckout", s.handleTelegramPreCheckout)
s.internal.POST("/payments/telegram/payment", s.handleTelegramPayment)
if s.robokassa.MerchantLogin != "" {
s.internal.POST("/payments/robokassa/result", s.handleRobokassaResult)
}
}
if s.links != nil {
// Account linking & merge. The request step always mails a code;
// a required merge is revealed only after the code is verified, and the
@@ -250,6 +273,16 @@ func statusForError(err error) (int, string) {
return http.StatusConflict, "last_identity"
case errors.Is(err, accountmerge.ErrActiveGameConflict):
return http.StatusConflict, "merge_active_game_conflict"
case errors.Is(err, payments.ErrUntrusted):
return http.StatusForbidden, "payments_untrusted"
case errors.Is(err, payments.ErrInsufficientChips):
return http.StatusConflict, "insufficient_chips"
case errors.Is(err, payments.ErrProductNotFound):
return http.StatusNotFound, "product_not_found"
case errors.Is(err, payments.ErrNotAValue):
return http.StatusBadRequest, "not_a_value"
case errors.Is(err, payments.ErrNotAPack):
return http.StatusBadRequest, "not_a_pack"
case errors.Is(err, account.ErrInvalidEmail):
return http.StatusBadRequest, "invalid_email"
case errors.Is(err, account.ErrCodeMismatch), errors.Is(err, account.ErrCodeExpired),
+32 -14
View File
@@ -10,6 +10,7 @@ import (
"scrabble/backend/internal/account"
"scrabble/backend/internal/notify"
"scrabble/backend/internal/session"
)
// The /api/v1/internal/sessions/* endpoints are gateway-only: the gateway has
@@ -23,7 +24,9 @@ import (
// brand-new account's display name and language; BrowserTZ (the client's detected
// "±HH:MM" UTC offset) seeds its time zone; StartParam is the validated launch
// deep-link payload, which may seed the new account's variant preferences (first
// contact only).
// contact only). Subtype is the client-reported device family (ios/android/web);
// Telegram's initData does not sign it, so it is recorded best-effort and the
// payments gate never relies on it.
type telegramAuthRequest struct {
ExternalID string `json:"external_id"`
Username string `json:"username"`
@@ -31,6 +34,7 @@ type telegramAuthRequest struct {
LanguageCode string `json:"language_code"`
BrowserTZ string `json:"browser_tz"`
StartParam string `json:"start_param"`
Subtype string `json:"subtype"`
}
// handleTelegramAuth provisions (or finds) the account bound to a Telegram
@@ -63,19 +67,22 @@ func (s *Server) handleTelegramAuth(c *gin.Context) {
}
}
}
s.mintSession(c, acc)
s.mintSession(c, acc, session.Platform{Kind: session.PlatformKindTelegram, Subtype: session.NormalizeSubtype(req.Subtype)})
}
// vkAuthRequest carries the identity the gateway extracted from verified VK launch
// params. LanguageCode (vk_language) and DisplayName (read client-side via
// VKWebAppGetUserInfo, since VK omits the name from the signed params) seed a brand-new
// account's language and display name; BrowserTZ (the client's detected "±HH:MM" UTC
// offset) seeds its time zone. All seeds apply on first contact only.
// offset) seeds its time zone. All seeds apply on first contact only. Subtype is the
// device family the gateway derived from the signed vk_platform param — trusted,
// since it rides inside the verified launch signature.
type vkAuthRequest struct {
ExternalID string `json:"external_id"`
LanguageCode string `json:"language_code"`
DisplayName string `json:"display_name"`
BrowserTZ string `json:"browser_tz"`
Subtype string `json:"subtype"`
}
// handleVKAuth provisions (or finds) the account bound to a VK identity and mints a
@@ -94,7 +101,7 @@ func (s *Server) handleVKAuth(c *gin.Context) {
s.abortErr(c, err)
return
}
s.mintSession(c, acc)
s.mintSession(c, acc, session.Platform{Kind: session.PlatformKindVK, Subtype: session.NormalizeSubtype(req.Subtype)})
}
// pushTargetRequest asks for a user's out-of-app push routing data by account id.
@@ -150,6 +157,9 @@ func (s *Server) handlePushTarget(c *gin.Context) {
// time zone, so robot timing is anchored to the player's zone from the first game.
type guestAuthRequest struct {
BrowserTZ string `json:"browser_tz"`
// Subtype is the client-reported device family (ios/android/web) of this direct
// (web/native) session; there is no external signer, so it is recorded best-effort.
Subtype string `json:"subtype"`
}
// handleGuestAuth provisions a fresh ephemeral guest account and mints a session,
@@ -164,7 +174,7 @@ func (s *Server) handleGuestAuth(c *gin.Context) {
s.abortErr(c, err)
return
}
s.mintSession(c, acc)
s.mintSession(c, acc, session.Platform{Kind: session.PlatformKindDirect, Subtype: session.NormalizeSubtype(req.Subtype)})
}
// emailRequest is an email-login code request. BrowserTZ (the client's detected
@@ -196,10 +206,12 @@ func (s *Server) handleEmailRequest(c *gin.Context) {
c.JSON(http.StatusOK, okResponse{OK: true})
}
// emailLoginRequest verifies an email login code.
// emailLoginRequest verifies an email login code. Subtype is the client-reported
// device family (ios/android/web) of this direct session; recorded best-effort.
type emailLoginRequest struct {
Email string `json:"email"`
Code string `json:"code"`
Email string `json:"email"`
Code string `json:"code"`
Subtype string `json:"subtype"`
}
// handleEmailLogin verifies the code and mints a session for the owning account.
@@ -214,7 +226,7 @@ func (s *Server) handleEmailLogin(c *gin.Context) {
s.abortErr(c, err)
return
}
s.mintSession(c, acc)
s.mintSession(c, acc, session.Platform{Kind: session.PlatformKindDirect, Subtype: session.NormalizeSubtype(req.Subtype)})
}
// confirmLinkResponse is the outcome of a one-tap deeplink confirmation. For a login,
@@ -248,7 +260,8 @@ func (s *Server) handleEmailConfirmLink(c *gin.Context) {
s.abortErr(c, err)
return
}
token, _, err := s.sessions.Create(c.Request.Context(), acc.ID)
// A magic-link login always opens in a browser, so its session is direct/web.
token, _, err := s.sessions.Create(c.Request.Context(), acc.ID, session.Platform{Kind: session.PlatformKindDirect, Subtype: session.SubtypeWeb})
if err != nil {
s.abortErr(c, err)
return
@@ -288,7 +301,11 @@ func (s *Server) handleResolveSession(c *gin.Context) {
// is_guest is best-effort: a transient account read must not fail an otherwise
// valid resolve (the auth hot path), so a read error falls back to false; the
// per-operation backend gate remains the authoritative guest check.
resp := resolveResponse{UserID: sess.AccountID.String()}
resp := resolveResponse{
UserID: sess.AccountID.String(),
PlatformKind: sess.Platform.Kind,
PlatformSubtype: sess.Platform.Subtype,
}
if acc, err := s.accounts.GetByID(c.Request.Context(), sess.AccountID); err == nil {
resp.IsGuest = acc.IsGuest
}
@@ -309,9 +326,10 @@ func (s *Server) handleRevokeSession(c *gin.Context) {
c.JSON(http.StatusOK, okResponse{OK: true})
}
// mintSession creates a session for acc and writes the credential response.
func (s *Server) mintSession(c *gin.Context, acc account.Account) {
token, _, err := s.sessions.Create(c.Request.Context(), acc.ID)
// mintSession creates a session for acc carrying the captured platform and writes
// the credential response.
func (s *Server) mintSession(c *gin.Context, acc account.Account, platform session.Platform) {
token, _, err := s.sessions.Create(c.Request.Context(), acc.ID, platform)
if err != nil {
s.abortErr(c, err)
return
+399
View File
@@ -0,0 +1,399 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.uber.org/zap"
"scrabble/backend/internal/payments"
)
// Ledger/order provider tags per rail.
const (
providerRobokassa = "robokassa" // the direct (RUB) rail
providerVK = "vk" // the VK Votes rail
providerTelegram = "telegram" // the Telegram Stars (XTR) rail
)
// walletOrderRequest is the POST body of a chip-pack purchase: the pack to fund.
type walletOrderRequest struct {
ProductID string `json:"product_id"`
}
// walletOrderResponse returns the created order id and the rail's launch details. RedirectURL is
// the provider's hosted-payment URL for the direct rail (empty for VK/Telegram, which settle
// in-app). Rail names the settling rail so the gateway knows how to launch it; for the Telegram
// Stars rail the gateway mints the invoice link from InvoiceTitle and InvoiceAmount (whole stars)
// via the bot and returns it in RedirectURL.
type walletOrderResponse struct {
OrderID string `json:"order_id"`
RedirectURL string `json:"redirect_url"`
Rail string `json:"rail"`
InvoiceTitle string `json:"invoice_title,omitempty"`
InvoiceAmount int64 `json:"invoice_amount,omitempty"`
}
// handleWalletOrder opens a pending order to fund a chip pack and returns the rail's launch
// details for the client: the Robokassa hosted-payment URL (direct), the order id for
// VKWebAppShowOrderBox (VK), or the pack title and star amount the gateway mints into a Stars
// invoice link (Telegram). It enforces the wallet gate and, on the direct rail, D36 (a purchase
// requires a confirmed email anchor). No chips are credited here — only later, by the verified
// provider callback.
func (s *Server) handleWalletOrder(c *gin.Context) {
uid, ok := userID(c)
if !ok {
return
}
var req walletOrderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, errorResponse{Error: errorBody{Code: "invalid_request", Message: "invalid request body"}})
return
}
productID, err := uuid.Parse(req.ProductID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, errorResponse{Error: errorBody{Code: "invalid_request", Message: "invalid product id"}})
return
}
ctx := c.Request.Context()
cxt, present, err := s.walletGate(ctx, uid)
if err != nil {
s.abortErr(c, err)
return
}
switch cxt.Kind {
case payments.SourceDirect:
if s.robokassa.MerchantLogin == "" {
c.AbortWithStatusJSON(http.StatusNotImplemented, errorResponse{Error: errorBody{Code: "rail_unavailable", Message: "this payment method is not available"}})
return
}
// D36: a direct purchase requires a confirmed email anchor.
hasEmail, err := s.accounts.HasConfirmedEmail(ctx, uid)
if err != nil {
s.abortErr(c, err)
return
}
if !hasEmail {
c.AbortWithStatusJSON(http.StatusForbidden, errorResponse{Error: errorBody{Code: "email_required", Message: "confirm your email before making a purchase"}})
return
}
res, err := s.payments.CreateOrder(ctx, uid, cxt, present, productID, providerRobokassa)
if err != nil {
s.abortErr(c, err)
return
}
c.JSON(http.StatusOK, walletOrderResponse{
OrderID: res.OrderID.String(),
RedirectURL: s.robokassa.PaymentURL(res.OrderID, res.Amount.Major(), res.Title),
Rail: providerRobokassa,
})
case payments.SourceVK:
res, err := s.payments.CreateOrder(ctx, uid, cxt, present, productID, providerVK)
if err != nil {
s.abortErr(c, err)
return
}
// The client passes the order id to VKWebAppShowOrderBox as the item; there is no redirect.
c.JSON(http.StatusOK, walletOrderResponse{OrderID: res.OrderID.String(), Rail: providerVK})
case payments.SourceTelegram:
res, err := s.payments.CreateOrder(ctx, uid, cxt, present, productID, providerTelegram)
if err != nil {
s.abortErr(c, err)
return
}
// The gateway mints the Stars invoice link from the title and amount via the bot (only
// the bot reaches Telegram) and returns it to the client as RedirectURL; the amount is in
// whole stars (the XTR minor unit is the star). No chips are credited until the verified
// successful_payment is forwarded back through the bot.
c.JSON(http.StatusOK, walletOrderResponse{
OrderID: res.OrderID.String(),
Rail: providerTelegram,
InvoiceTitle: res.Title,
InvoiceAmount: res.Amount.Minor(),
})
default:
c.AbortWithStatusJSON(http.StatusNotImplemented, errorResponse{Error: errorBody{Code: "rail_unavailable", Message: "this payment method is not available yet"}})
}
}
// handleRobokassaResult is the verified Robokassa Result callback, reached only through the gateway
// (which forwards the provider's form parameters as a JSON object on the internal, gateway-only
// route). It verifies the Password2 signature, credits the matched order exactly once (idempotent,
// and honoured even if the order expired), records a succeeded event, and answers Robokassa's
// expected "OK<InvId>". A duplicate callback credits nothing but still answers OK.
func (s *Server) handleRobokassaResult(c *gin.Context) {
var params map[string]string
if err := c.ShouldBindJSON(&params); err != nil {
c.String(http.StatusBadRequest, "bad request")
return
}
v := url.Values{}
for k, val := range params {
v.Set(k, val)
}
orderID, outSum, ok := s.robokassa.VerifyResult(v)
if !ok {
s.log.Warn("robokassa result: bad signature")
c.String(http.StatusBadRequest, "bad sign")
return
}
paid, err := payments.ParseMoney(outSum, payments.CurrencyRUB)
if err != nil {
c.String(http.StatusBadRequest, "bad amount")
return
}
ctx := c.Request.Context()
outcome, err := s.payments.Fund(ctx, orderID, providerRobokassa, orderID.String(), paid)
if err != nil {
if errors.Is(err, payments.ErrOrderNotFound) || errors.Is(err, payments.ErrAmountMismatch) ||
errors.Is(err, payments.ErrNotAPack) || errors.Is(err, payments.ErrProductNotFound) {
s.log.Warn("robokassa result rejected", zap.String("order", orderID.String()), zap.Error(err))
c.String(http.StatusBadRequest, "rejected")
return
}
s.log.Error("robokassa fund failed", zap.String("order", orderID.String()), zap.Error(err))
c.String(http.StatusInternalServerError, "error")
return
}
if !outcome.AlreadyCredited {
payload, _ := json.Marshal(map[string]any{"chips": outcome.Chips, "source": string(outcome.Source)})
if err := s.payments.RecordPaymentEvent(ctx, outcome.AccountID, &orderID, "succeeded", payload); err != nil {
s.log.Error("record payment event failed", zap.String("order", orderID.String()), zap.Error(err))
}
}
// The gateway echoes response verbatim to Robokassa, which requires the body "OK<InvId>".
c.JSON(http.StatusOK, gin.H{"response": "OK" + v.Get("InvId")})
}
// vkErrorResponse builds VK's error envelope for a payment callback.
func vkErrorResponse(code int, msg string, critical bool) gin.H {
return gin.H{"error": gin.H{"error_code": code, "error_msg": msg, "critical": critical}}
}
// handleVKCallback is the VK Mini Apps payment callback, reached only through the gateway (which
// verifies the VK signature and forwards the provider's parameters as a JSON object on the internal
// route). It answers VK's two phases: get_item returns the ordered pack's title and vote price; a
// chargeable order_status_change credits the matched order exactly once (idempotent on VK's order
// id) and records a succeeded event. Both phases use VK's response envelope; the _test variants are
// the sandbox notifications and are handled identically.
func (s *Server) handleVKCallback(c *gin.Context) {
var params map[string]string
if err := c.ShouldBindJSON(&params); err != nil {
c.JSON(http.StatusOK, vkErrorResponse(1, "bad request", true))
return
}
ctx := c.Request.Context()
switch params["notification_type"] {
case "get_item", "get_item_test":
orderID, err := uuid.Parse(params["item"])
if err != nil {
c.JSON(http.StatusOK, vkErrorResponse(20, "item not available", true))
return
}
title, amount, err := s.payments.OrderItem(ctx, orderID)
if err != nil {
s.log.Warn("vk get_item lookup failed", zap.String("order", orderID.String()), zap.Error(err))
c.JSON(http.StatusOK, vkErrorResponse(20, "item not available", true))
return
}
c.JSON(http.StatusOK, gin.H{"response": gin.H{
"item_id": orderID.String(),
"title": title,
"price": amount.Minor(),
}})
case "order_status_change", "order_status_change_test":
if params["status"] != "chargeable" {
c.JSON(http.StatusOK, vkErrorResponse(100, "unsupported status", false))
return
}
orderID, err := uuid.Parse(params["item"])
if err != nil {
c.JSON(http.StatusOK, vkErrorResponse(20, "item not available", true))
return
}
price, err := strconv.ParseInt(params["item_price"], 10, 64)
if err != nil {
c.JSON(http.StatusOK, vkErrorResponse(100, "bad price", false))
return
}
paid, err := payments.MoneyFromMinor(price, payments.CurrencyVote)
if err != nil {
c.JSON(http.StatusOK, vkErrorResponse(100, "bad price", false))
return
}
vkOrderID := params["order_id"]
outcome, err := s.payments.Fund(ctx, orderID, providerVK, vkOrderID, paid)
if err != nil {
if errors.Is(err, payments.ErrOrderNotFound) || errors.Is(err, payments.ErrAmountMismatch) ||
errors.Is(err, payments.ErrNotAPack) || errors.Is(err, payments.ErrProductNotFound) {
s.log.Warn("vk order rejected", zap.String("order", orderID.String()), zap.Error(err))
c.JSON(http.StatusOK, vkErrorResponse(100, "cannot process the order", false))
return
}
s.log.Error("vk fund failed", zap.String("order", orderID.String()), zap.Error(err))
c.JSON(http.StatusOK, vkErrorResponse(100, "internal error", false))
return
}
if !outcome.AlreadyCredited {
payload, _ := json.Marshal(map[string]any{"chips": outcome.Chips, "source": string(outcome.Source)})
if err := s.payments.RecordPaymentEvent(ctx, outcome.AccountID, &orderID, "succeeded", payload); err != nil {
s.log.Error("record vk payment event failed", zap.String("order", orderID.String()), zap.Error(err))
}
}
// Echo VK's own order id; app_order_id is optional and our order id is a uuid, so omit it.
appOrderID, _ := strconv.ParseInt(vkOrderID, 10, 64)
c.JSON(http.StatusOK, gin.H{"response": gin.H{"order_id": appOrderID}})
default:
c.JSON(http.StatusOK, vkErrorResponse(100, "unknown notification", false))
}
}
// telegramPreCheckoutRequest is the bot's pre_checkout validation, forwarded through the gateway:
// the order in the invoice payload and the amount and currency Telegram is about to charge.
type telegramPreCheckoutRequest struct {
OrderID string `json:"order_id"`
Amount int64 `json:"amount"`
Currency string `json:"currency"`
}
// telegramPreCheckoutResponse tells the bot whether to approve the pre_checkout_query; Reason is a
// short message the bot surfaces to the payer on a decline.
type telegramPreCheckoutResponse struct {
OK bool `json:"ok"`
Reason string `json:"reason,omitempty"`
}
// handleTelegramPreCheckout validates a Telegram Stars pre_checkout_query before the charge,
// reached only through the gateway (the bot's ValidatePreCheckout, forwarded on the internal
// route). It approves an order that exists, is not already paid (a reusable invoice link paid twice
// is refused here, before any star moves) and whose amount and currency match. A malformed
// reference is a decline, not an error.
func (s *Server) handleTelegramPreCheckout(c *gin.Context) {
var req telegramPreCheckoutRequest
if err := c.ShouldBindJSON(&req); err != nil {
abortBadRequest(c, "invalid request body")
return
}
ctx := c.Request.Context()
orderID, err := uuid.Parse(req.OrderID)
if err != nil {
c.JSON(http.StatusOK, telegramPreCheckoutResponse{OK: false, Reason: telegramDeclineText(payments.PreCheckoutGone, "")})
return
}
amount, err := payments.MoneyFromMinor(req.Amount, payments.Currency(req.Currency))
if err != nil {
c.JSON(http.StatusOK, telegramPreCheckoutResponse{OK: false, Reason: telegramDeclineText(payments.PreCheckoutGone, "")})
return
}
out, err := s.payments.ValidatePreCheckout(ctx, orderID, amount)
if err != nil {
s.log.Error("telegram pre_checkout validate failed", zap.String("order", orderID.String()), zap.Error(err))
c.AbortWithStatusJSON(http.StatusInternalServerError, errorResponse{Error: errorBody{Code: "internal", Message: "internal error"}})
return
}
reason := ""
if !out.OK {
// Localise the decline to the order account's preferred language (the reason shows in the
// Telegram payment sheet). An unknown order has no account, so it falls back to English.
lang := ""
if s.accounts != nil && out.AccountID != (uuid.UUID{}) {
if acc, aerr := s.accounts.GetByID(ctx, out.AccountID); aerr == nil {
lang = acc.PreferredLanguage
}
}
reason = telegramDeclineText(out.Reason, lang)
}
c.JSON(http.StatusOK, telegramPreCheckoutResponse{OK: out.OK, Reason: reason})
}
// telegramDeclineText renders a pre-checkout decline reason code in the payer's language (ru or
// anything else falls back to English), for display in the Telegram payment sheet.
func telegramDeclineText(code, lang string) string {
ru := lang == "ru"
switch code {
case payments.PreCheckoutAlreadyPaid:
if ru {
return "Этот заказ уже оплачен."
}
return "This order has already been paid."
case payments.PreCheckoutPriceChanged:
if ru {
return "Цена изменилась — начните покупку заново."
}
return "The price has changed; please start the purchase again."
default:
if ru {
return "Этот заказ больше недоступен."
}
return "This order is no longer available."
}
}
// telegramPaymentRequest is a completed Stars payment forwarded from the bot's outbox through the
// gateway: the order, the Telegram charge id (the idempotency key), the stars paid, and the payer.
type telegramPaymentRequest struct {
OrderID string `json:"order_id"`
TelegramPaymentChargeID string `json:"telegram_payment_charge_id"`
Amount int64 `json:"amount"`
TelegramUserID int64 `json:"telegram_user_id"`
}
// telegramPaymentResponse reports the durable outcome to the bot: Credited is true once the order
// is credited (or already was). A false with a 200 means the payment was recorded but not creditable
// (the bot drops it); a 5xx means a transient failure the bot retries.
type telegramPaymentResponse struct {
Credited bool `json:"credited"`
}
// handleTelegramPayment credits a completed Telegram Stars payment, reached only through the gateway
// (the bot's ForwardPayment, forwarded on the internal route). It credits the matched order exactly
// once (idempotent on the Telegram charge id, honoured even if the order expired) and records a
// succeeded event. A permanent rejection (unknown order, amount mismatch) is answered 200 with
// Credited=false so the bot stops retrying a payment it cannot place; a transient failure is a 5xx
// the bot retries.
func (s *Server) handleTelegramPayment(c *gin.Context) {
var req telegramPaymentRequest
if err := c.ShouldBindJSON(&req); err != nil {
abortBadRequest(c, "invalid request body")
return
}
orderID, err := uuid.Parse(req.OrderID)
if err != nil {
s.log.Warn("telegram payment: bad order id", zap.String("charge", req.TelegramPaymentChargeID))
c.JSON(http.StatusOK, telegramPaymentResponse{Credited: false})
return
}
paid, err := payments.MoneyFromMinor(req.Amount, payments.CurrencyStar)
if err != nil {
c.JSON(http.StatusOK, telegramPaymentResponse{Credited: false})
return
}
ctx := c.Request.Context()
outcome, err := s.payments.Fund(ctx, orderID, providerTelegram, req.TelegramPaymentChargeID, paid)
if err != nil {
if errors.Is(err, payments.ErrOrderNotFound) || errors.Is(err, payments.ErrAmountMismatch) ||
errors.Is(err, payments.ErrNotAPack) || errors.Is(err, payments.ErrProductNotFound) {
// The star charge already happened but the order cannot be placed; record it loudly for
// an operator and tell the bot to stop retrying (an operator refunds or credits by hand).
s.log.Error("telegram payment rejected (charge taken, not credited)",
zap.String("order", orderID.String()), zap.String("charge", req.TelegramPaymentChargeID), zap.Error(err))
c.JSON(http.StatusOK, telegramPaymentResponse{Credited: false})
return
}
s.log.Error("telegram fund failed", zap.String("order", orderID.String()), zap.Error(err))
c.AbortWithStatusJSON(http.StatusInternalServerError, errorResponse{Error: errorBody{Code: "internal", Message: "internal error"}})
return
}
if !outcome.AlreadyCredited {
payload, _ := json.Marshal(map[string]any{"chips": outcome.Chips, "source": string(outcome.Source)})
if err := s.payments.RecordPaymentEvent(ctx, outcome.AccountID, &orderID, "succeeded", payload); err != nil {
s.log.Error("record telegram payment event failed", zap.String("order", orderID.String()), zap.Error(err))
}
}
c.JSON(http.StatusOK, telegramPaymentResponse{Credited: true})
}
+164
View File
@@ -0,0 +1,164 @@
package server
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"scrabble/backend/internal/payments"
)
// walletSegmentDTO is one chip balance in the wallet view: the funding source, the chip count,
// and whether it can be spent in the current execution context (false for a frozen VK-iOS
// balance or an untrusted platform).
type walletSegmentDTO struct {
Source string `json:"source"`
Chips int `json:"chips"`
Spendable bool `json:"spendable"`
}
// walletDTO is the user-facing wallet: the context-visible chip segments and the
// context-applicable benefits (the no-ads term or forever flag, and the available hints).
type walletDTO struct {
Segments []walletSegmentDTO `json:"segments"`
AdsForever bool `json:"ads_forever"`
AdsPaidUntil int64 `json:"ads_paid_until_ms"` // unix millis; 0 = no active term
Hints int `json:"hints"`
}
// walletBuyRequest is the POST body of a chip spend: the product to buy with chips.
type walletBuyRequest struct {
ProductID string `json:"product_id"`
}
// walletDTOFrom projects a payments wallet view into the wire DTO.
func walletDTOFrom(v payments.WalletView) walletDTO {
out := walletDTO{AdsForever: v.Benefits.AdsForever, Hints: v.Benefits.Hints}
if v.Benefits.AdsPaidUntil != nil {
out.AdsPaidUntil = v.Benefits.AdsPaidUntil.UnixMilli()
}
out.Segments = make([]walletSegmentDTO, 0, len(v.Segments))
for _, seg := range v.Segments {
out.Segments = append(out.Segments, walletSegmentDTO{Source: string(seg.Source), Chips: seg.Chips, Spendable: seg.Spendable})
}
return out
}
// catalogAtomDTO is one atom line of a storefront product: the base value type it grants and how
// many of it the product carries.
type catalogAtomDTO struct {
AtomType string `json:"atom_type"`
Quantity int `json:"quantity"`
}
// catalogProductDTO is one storefront product for the caller's context: a chip-priced value
// (chips set, no money price) or a chip pack priced in the context's payment method
// (money_amount minor units + money_currency, no chips), plus what it grants.
type catalogProductDTO struct {
Kind string `json:"kind"`
ProductID string `json:"product_id"`
Title string `json:"title"`
Chips int `json:"chips"`
MoneyAmount int64 `json:"money_amount"`
MoneyCurrency string `json:"money_currency"`
Atoms []catalogAtomDTO `json:"atoms"`
}
// catalogDTO is the storefront: the products visible and purchasable in the caller's context.
type catalogDTO struct {
Products []catalogProductDTO `json:"products"`
}
// catalogDTOFrom projects a payments catalog view into the wire DTO.
func catalogDTOFrom(v payments.CatalogView) catalogDTO {
out := catalogDTO{Products: make([]catalogProductDTO, 0, len(v.Products))}
for _, p := range v.Products {
atoms := make([]catalogAtomDTO, 0, len(p.Atoms))
for _, a := range p.Atoms {
atoms = append(atoms, catalogAtomDTO{AtomType: a.AtomType, Quantity: a.Quantity})
}
out.Products = append(out.Products, catalogProductDTO{
Kind: p.Kind, ProductID: p.ProductID, Title: p.Title,
Chips: p.Chips, MoneyAmount: p.MoneyAmount, MoneyCurrency: p.MoneyCurrency, Atoms: atoms,
})
}
return out
}
// handleWalletCatalog returns the storefront for the caller's trusted execution context: the
// chip-priced values and the chip packs priced in the context's payment method.
func (s *Server) handleWalletCatalog(c *gin.Context) {
uid, ok := userID(c)
if !ok {
return
}
ctx := c.Request.Context()
cxt, _, err := s.walletGate(ctx, uid)
if err != nil {
s.abortErr(c, err)
return
}
view, err := s.payments.Catalog(ctx, cxt)
if err != nil {
s.abortErr(c, err)
return
}
c.JSON(http.StatusOK, catalogDTOFrom(view))
}
// handleWallet returns the caller's wallet — the segments and benefits visible in the current
// trusted execution context.
func (s *Server) handleWallet(c *gin.Context) {
uid, ok := userID(c)
if !ok {
return
}
ctx := c.Request.Context()
cxt, present, err := s.walletGate(ctx, uid)
if err != nil {
s.abortErr(c, err)
return
}
view, err := s.payments.Wallet(ctx, uid, cxt, present)
if err != nil {
s.abortErr(c, err)
return
}
c.JSON(http.StatusOK, walletDTOFrom(view))
}
// handleWalletBuy spends chips on a chip-priced value and returns the updated wallet. It is
// fail-closed: an untrusted or frozen context, or an insufficient balance, is refused.
func (s *Server) handleWalletBuy(c *gin.Context) {
uid, ok := userID(c)
if !ok {
return
}
var req walletBuyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, errorResponse{Error: errorBody{Code: "invalid_request", Message: "invalid request body"}})
return
}
productID, err := uuid.Parse(req.ProductID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, errorResponse{Error: errorBody{Code: "invalid_request", Message: "invalid product id"}})
return
}
ctx := c.Request.Context()
cxt, present, err := s.walletGate(ctx, uid)
if err != nil {
s.abortErr(c, err)
return
}
if err := s.payments.Spend(ctx, uid, cxt, present, productID); err != nil {
s.abortErr(c, err)
return
}
view, err := s.payments.Wallet(ctx, uid, cxt, present)
if err != nil {
s.abortErr(c, err)
return
}
c.JSON(http.StatusOK, walletDTOFrom(view))
}
+43
View File
@@ -4,9 +4,12 @@ import (
"context"
"net/http"
"net/url"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"scrabble/backend/internal/session"
)
// headerUserID is the identity header the gateway injects after resolving a
@@ -41,6 +44,46 @@ func UserIDFromContext(ctx context.Context) (uuid.UUID, bool) {
return id, ok
}
// headerPlatform is the trusted execution-platform header the gateway injects after
// resolving a session's platform. Its value is "<kind>/<subtype>" (e.g. "vk/ios");
// it is omitted for an untrusted session, in which case platform(c) reports the
// zero Platform. Like X-User-ID, the value is the gateway's — never a client body.
const headerPlatform = "X-Platform"
// platformContext returns middleware that parses the gateway-injected X-Platform
// header into the request context, so handlers (and the link/merge session mint)
// read the caller's trusted platform. An absent or malformed header leaves the
// context without a platform (untrusted) and never rejects the request — X-Platform
// is a capability signal, not an identity gate.
func platformContext() gin.HandlerFunc {
return func(c *gin.Context) {
if p, ok := parsePlatformHeader(c.GetHeader(headerPlatform)); ok {
c.Request = c.Request.WithContext(session.WithPlatform(c.Request.Context(), p))
}
c.Next()
}
}
// parsePlatformHeader splits a "<kind>/<subtype>" X-Platform value into a Platform.
// A blank value or blank kind yields no platform (an untrusted session).
func parsePlatformHeader(h string) (session.Platform, bool) {
if h == "" {
return session.Platform{}, false
}
kind, subtype, _ := strings.Cut(h, "/")
if kind == "" {
return session.Platform{}, false
}
return session.Platform{Kind: kind, Subtype: subtype}, true
}
// platform returns the caller's trusted execution platform, or the zero Platform
// and false when the session was not attributed to one — an untrusted, view-only
// context for the payments gate.
func platform(c *gin.Context) (session.Platform, bool) {
return session.PlatformFromContext(c.Request.Context())
}
// requireSameOrigin guards the admin console's state-changing requests: it rejects
// a non-safe request whose Origin (or, failing that, Referer) host does not match
// the request Host. The gateway authenticates the operator with Basic-Auth in front
@@ -7,6 +7,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"scrabble/backend/internal/session"
)
// TestRequireUserID checks that the middleware accepts a valid X-User-ID,
@@ -58,3 +60,51 @@ func TestRequireUserID(t *testing.T) {
}
})
}
// TestPlatformContext checks that the middleware parses the gateway-injected
// X-Platform header into a trusted platform reachable via platform(c), treats an
// absent or blank-kind header as untrusted, and never rejects the request.
func TestPlatformContext(t *testing.T) {
gin.SetMode(gin.TestMode)
var seen session.Platform
var ok bool
r := gin.New()
r.Use(platformContext())
r.GET("/x", func(c *gin.Context) {
seen, ok = platform(c)
c.String(http.StatusOK, "ok")
})
for _, tc := range []struct {
name string
header string
setHeader bool
wantOK bool
want session.Platform
}{
{"vk-ios", "vk/ios", true, true, session.Platform{Kind: session.PlatformKindVK, Subtype: session.SubtypeIOS}},
{"telegram-no-subtype", "telegram", true, true, session.Platform{Kind: session.PlatformKindTelegram}},
{"direct-web", "direct/web", true, true, session.Platform{Kind: session.PlatformKindDirect, Subtype: session.SubtypeWeb}},
{"absent", "", false, false, session.Platform{}},
{"empty", "", true, false, session.Platform{}},
{"blank-kind", "/ios", true, false, session.Platform{}},
} {
t.Run(tc.name, func(t *testing.T) {
seen, ok = session.Platform{}, false
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if tc.setHeader {
req.Header.Set("X-Platform", tc.header)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (X-Platform never rejects)", rec.Code)
}
if ok != tc.wantOK || seen != tc.want {
t.Fatalf("platform = %+v (ok=%v), want %+v (ok=%v)", seen, ok, tc.want, tc.wantOK)
}
})
}
}
+31
View File
@@ -0,0 +1,31 @@
package server
import (
"context"
"github.com/google/uuid"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/session"
)
// walletGate resolves the payments gate inputs for an account on the current request: the
// trusted execution context (the session platform carried on ctx by the platformContext
// middleware; absent ⇒ untrusted, fail-closed) and the account's present identity sources
// (which chip/benefit segments are awake, §6). The payments domain holds no cross-schema
// identity knowledge, so the server supplies present from account.Identities.
func (s *Server) walletGate(ctx context.Context, accountID uuid.UUID) (payments.Context, []payments.Source, error) {
var cxt payments.Context
if p, ok := session.PlatformFromContext(ctx); ok {
cxt = payments.NewContext(p.Kind, p.Subtype)
}
ids, err := s.accounts.Identities(ctx, accountID)
if err != nil {
return payments.Context{}, nil, err
}
kinds := make([]string, len(ids))
for i, id := range ids {
kinds[i] = id.Kind
}
return cxt, payments.PresentSources(kinds), nil
}
+18
View File
@@ -28,8 +28,10 @@ import (
"scrabble/backend/internal/link"
"scrabble/backend/internal/lobby"
"scrabble/backend/internal/notify"
"scrabble/backend/internal/payments"
"scrabble/backend/internal/ratewatch"
"scrabble/backend/internal/render"
"scrabble/backend/internal/robokassa"
"scrabble/backend/internal/session"
"scrabble/backend/internal/social"
"scrabble/backend/internal/telemetry"
@@ -93,6 +95,11 @@ type Deps struct {
// profile.get banner block, plus the banner admin console section. A nil Ads
// omits the banner block and disables the banner console.
Ads *ads.Service
// Payments is the in-game currency domain service (wallet, benefits, catalog).
// The data-foundation layer exposes only a reachability check; its user and
// console routes are registered when the wallet surface lands. A nil Payments
// omits them.
Payments *payments.Service
// Notifier publishes live-event intents — here the banner-eligibility re-poll
// signal the banner/hint/role console actions emit. A nil Notifier discards
// them (notify.Nop).
@@ -103,6 +110,9 @@ type Deps struct {
// Renderer is the image-render sidecar client for the PNG export artifact. A
// nil Renderer makes the PNG download answer 404 (the GCG artifact still works).
Renderer *render.Client
// Robokassa configures the direct-rail (RUB) provider; an empty MerchantLogin leaves the
// order and Result-callback endpoints unregistered.
Robokassa robokassa.Config
}
// Server owns the gin engine, the underlying HTTP server and the readiness
@@ -129,6 +139,8 @@ type Server struct {
ratewatch *ratewatch.Watch
banview *banview.View
ads *ads.Service
payments *payments.Service
robokassa robokassa.Config
notifier notify.Publisher
console *adminconsole.Renderer
exportKey []byte
@@ -181,6 +193,8 @@ func New(addr string, deps Deps) *Server {
ratewatch: deps.RateWatch,
banview: deps.BanView,
ads: deps.Ads,
payments: deps.Payments,
robokassa: deps.Robokassa,
notifier: notifier,
renderer: deps.Renderer,
http: &http.Server{Addr: addr, Handler: engine},
@@ -230,6 +244,10 @@ func (s *Server) registerAPIGroups(engine *gin.Engine) {
s.public = v1.Group("/public")
s.user = v1.Group("/user")
s.user.Use(RequireUserID())
// Capture the gateway-injected trusted platform (X-Platform) into the request context,
// so the payments gate can read it via platform(c). Optional: an untrusted session simply
// carries no platform and is treated as view-only. Never rejects.
s.user.Use(platformContext())
// The suspension gate runs after identity is established: a blocked account is refused on
// every user route (except the block-status probe) so the UI can show the blocked screen.
s.user.Use(s.requireNotSuspended())
+65
View File
@@ -0,0 +1,65 @@
package session
import "context"
// Platform is the trusted execution context recorded on a session: the wrapper
// Kind the session was established through and the device Subtype. An empty Kind
// marks an untrusted session — one minted before platform capture, or one the
// gateway could not attribute — which the payments compliance gate treats as
// view-only.
//
// Kind is always trustworthy: it is derived server-side from the validated
// establish path, never from a client-supplied field. Subtype is trustworthy only
// for VK (vk_platform rides inside the signed launch params); for telegram and
// direct it is client-reported and best-effort, so the gate must never rely on it.
type Platform struct {
Kind string
Subtype string
}
// Platform kinds recorded in platform_kind.
const (
PlatformKindVK = "vk"
PlatformKindTelegram = "telegram"
PlatformKindDirect = "direct"
)
// Platform subtypes recorded in platform_subtype.
const (
SubtypeIOS = "ios"
SubtypeAndroid = "android"
SubtypeWeb = "web"
)
// Trusted reports whether the session was attributed to a platform (a non-empty
// Kind). The zero Platform is untrusted.
func (p Platform) Trusted() bool { return p.Kind != "" }
// NormalizeSubtype coerces subtype to one of the known device families, defaulting
// an empty or unrecognised value to web. A newly established session always carries
// at least a web subtype, so a trusted session is never left without one.
func NormalizeSubtype(subtype string) string {
switch subtype {
case SubtypeIOS, SubtypeAndroid, SubtypeWeb:
return subtype
default:
return SubtypeWeb
}
}
// platformCtxKey types the request-context slot the trusted platform rides in.
type platformCtxKey struct{}
// WithPlatform returns a copy of ctx carrying platform. The backend middleware
// calls it after parsing the gateway-injected X-Platform header, so downstream
// handlers and the link/merge session mint read the caller's platform from ctx.
func WithPlatform(ctx context.Context, platform Platform) context.Context {
return context.WithValue(ctx, platformCtxKey{}, platform)
}
// PlatformFromContext returns the platform stored by WithPlatform and whether one
// was present. A missing value yields the zero (untrusted) Platform.
func PlatformFromContext(ctx context.Context) (Platform, bool) {
p, ok := ctx.Value(platformCtxKey{}).(Platform)
return p, ok
}
+6 -4
View File
@@ -29,14 +29,16 @@ func (svc *Service) Ready() bool {
return svc.cache.Ready()
}
// Create mints a new active session for accountID and returns the plaintext
// token (shown to the caller once) together with the persisted session.
func (svc *Service) Create(ctx context.Context, accountID uuid.UUID) (string, Session, error) {
// Create mints a new active session for accountID carrying the captured platform
// and returns the plaintext token (shown to the caller once) together with the
// persisted session. Pass the zero Platform for a session that could not be
// attributed to a trusted platform.
func (svc *Service) Create(ctx context.Context, accountID uuid.UUID, platform Platform) (string, Session, error) {
token, tokenHash, err := GenerateToken()
if err != nil {
return "", Session{}, err
}
sess, err := svc.store.Insert(ctx, accountID, tokenHash)
sess, err := svc.store.Insert(ctx, accountID, tokenHash, platform)
if err != nil {
return "", Session{}, err
}
+25 -5
View File
@@ -25,7 +25,8 @@ const (
var ErrNotFound = errors.New("session: not found")
// Session mirrors a row in backend.sessions. TokenHash is the hex-encoded
// SHA-256 of the bearer token.
// SHA-256 of the bearer token. Platform is the trusted execution context captured
// at creation; its zero value marks an untrusted session (see Platform).
type Session struct {
ID uuid.UUID
AccountID uuid.UUID
@@ -34,6 +35,7 @@ type Session struct {
CreatedAt time.Time
LastSeenAt *time.Time
RevokedAt *time.Time
Platform Platform
}
// Store is the Postgres-backed query surface for backend.sessions.
@@ -46,9 +48,10 @@ func NewStore(db *sql.DB) *Store {
return &Store{db: db}
}
// Insert persists a new active session for accountID carrying tokenHash and
// returns the persisted row.
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, tokenHash string) (Session, error) {
// Insert persists a new active session for accountID carrying tokenHash and the
// captured platform, and returns the persisted row. An empty platform Kind/Subtype
// is written as SQL NULL, so an untrusted session records no platform.
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, tokenHash string, platform Platform) (Session, error) {
id, err := uuid.NewV7()
if err != nil {
return Session{}, fmt.Errorf("session: new id: %w", err)
@@ -57,7 +60,9 @@ func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, tokenHash strin
table.Sessions.SessionID,
table.Sessions.AccountID,
table.Sessions.TokenHash,
).VALUES(id, accountID, tokenHash).RETURNING(table.Sessions.AllColumns)
table.Sessions.PlatformKind,
table.Sessions.PlatformSubtype,
).VALUES(id, accountID, tokenHash, stringOrNull(platform.Kind), stringOrNull(platform.Subtype)).RETURNING(table.Sessions.AllColumns)
var row model.Sessions
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
@@ -173,5 +178,20 @@ func modelToSession(row model.Sessions) Session {
t := *row.RevokedAt
s.RevokedAt = &t
}
if row.PlatformKind != nil {
s.Platform.Kind = *row.PlatformKind
}
if row.PlatformSubtype != nil {
s.Platform.Subtype = *row.PlatformSubtype
}
return s
}
// stringOrNull maps an empty string to a SQL NULL literal and any other value to a
// string literal, so an untrusted session's absent platform is stored as NULL.
func stringOrNull(s string) postgres.Expression {
if s == "" {
return postgres.NULL
}
return postgres.String(s)
}
+16
View File
@@ -13,6 +13,22 @@ POSTGRES_DB=scrabble
POSTGRES_USER=scrabble
POSTGRES_PASSWORD=change-me # required
# --- Point-in-time recovery (pgBackRest -> S3; PROD main host only) ----------
# Continuous WAL archiving for PITR. PROD-ONLY: the test contour never archives (these
# stay unset there and archive_mode stays off). The artifact ships DISARMED —
# PGBACKREST_ARCHIVE_MODE defaults off; arm it only after setting up the S3 repository +
# secrets and creating the stanza, then flip it on (deploy/README.md, point-in-time
# recovery). Gitea: PROD_PGBACKREST_* — endpoint/bucket/region/archive-mode are variables,
# the two S3 keys + the cipher passphrase are secrets.
PGBACKREST_ARCHIVE_MODE=off # on = archiving active (arm only after the stanza exists)
PGBACKREST_S3_ENDPOINT= # S3 HOST ONLY — no https://, no port, no bucket (e.g. s3.ru-1.storage.selcloud.ru); path-style addressing
PGBACKREST_S3_PORT= # optional; default 443 — set only if the provider uses a non-standard S3 port
PGBACKREST_S3_BUCKET= # bucket name; lowercase, no dots/underscores
PGBACKREST_S3_REGION= # e.g. ru-1
PGBACKREST_S3_KEY= # secret: S3 access key id
PGBACKREST_S3_KEY_SECRET= # secret: S3 secret access key
PGBACKREST_CIPHER_PASS= # secret: repo encryption passphrase — KEEP SAFE, stored apart from the S3 keys (losing it makes the archive unrecoverable)
# --- Dictionary -------------------------------------------------------------
# scrabble-dictionary release tag baked into the image as the SEED dictionary for a
# FRESH volume (image build-arg; also labels the resident seed version). After first
+109 -8
View File
@@ -220,10 +220,108 @@ release tag, so any prior release is reachable.
**Migrations** must be **expand-contract** (backward-compatible; goose is forward-only):
the automatic rollback is image-only and never restores the DB. A deploy that changes
`backend/internal/postgres/migrations/` opens a maintenance window — the backend (sole
writer) is stopped for a consistent `pg_dump` into `/opt/scrabble/dumps` before the new
backend migrates. **Manual DB restore** (only if a migration was destructive):
`docker exec -i scrabble-postgres psql -U scrabble -d scrabble -c 'DROP SCHEMA backend CASCADE'`,
then pipe the dump into the same `psql`, and redeploy the matching old tag.
writer) is stopped for a consistent **whole-database** `pg_dump` into `/opt/scrabble/dumps`
(it covers `backend` **and** `payments`) before the new backend migrates. **Manual DB
restore** (only if a migration was destructive): drop the app schemas in the same instance
and pipe the dump back —
`docker exec -i scrabble-postgres psql -U scrabble -d scrabble -c 'DROP SCHEMA IF EXISTS backend CASCADE; DROP SCHEMA IF EXISTS payments CASCADE;'`,
then `docker exec -i scrabble-postgres psql -U scrabble -d scrabble < the-dump.sql`, and
redeploy the matching old tag. This dump is a belt-and-braces net for a bad migration;
**point-in-time recovery** (below) is the primary recovery path once armed, and the only one
that survives losing the host.
## Point-in-time recovery (PITR)
The main host archives Postgres continuously with **pgBackRest** to **Selectel S3**
(encrypted at rest, path-style addressing) so the database can be restored to any moment —
protecting the money ledger and the game state against corruption or host loss. It is the
primary recovery path; the migration-window `pg_dump` above is the secondary net.
**Live on the prod main host since v1.13.0** (armed + restore-drilled 2026-07-09).
**Shape.** A daily full **base backup** (a systemd timer on the main host, `04:00`) plus
**continuous WAL** archived by Postgres `archive_command` (a segment is forced at least every
5 minutes, so the recovery point is never more than a few minutes behind). Retention is **30
days** (`repo1-retention-full=30`); the repository is AES-256-CBC encrypted. This is main-host
only — the test contour never archives.
**Wiring.** pgBackRest ships inside the DB image (`deploy/postgres/Dockerfile`); the
repository + S3 credentials + cipher are the `PGBACKREST_*` environment on the postgres
service in `docker-compose.prod.yml`, rendered from the `PROD_` Gitea set by
`write-prod-env.sh`. Archiving is gated by **`PGBACKREST_ARCHIVE_MODE` (default `off`)**, so
shipping or redeploying this stack does **not** start archiving — the artifact is inert until
armed, which is why an un-armed prod deploy can never pile WAL onto the disk. The base-backup
timer is provisioned by the Ansible `main` role behind `pitr_enabled` (also default off). Two
Grafana alerts watch health: `WAL archiving failing` (`pg_stat_archiver_failed_count` rising)
and `WAL archiving stalled` (`pg_stat_archiver_last_archive_age` over 30 min) — both
absent/NaN-safe, so they stay quiet until archiving is armed.
**Assessment (owner-reviewed; the gate before the first real money).** Measured on prod
`pg_stat_wal`: WAL is generated at **~0.77 MB/day** and the database is **~9.6 MB**. At
30-day retention on Selectel S3 (~2 ₽/GB·month) the archive is **under ~0.3 GB → well under
1 ₽/month** (compression halves it again); request volume is trivial. Performance impact is
**negligible**: archive-push moves tiny compressed segments, and the daily full base backup is
small (the whole cluster is ~32 MB → ~3.7 MB compressed in the repo) and checkpoint-bound
(~1.5 min wall, minimal CPU/I-O) on the 2 vCPU host. Revisit if traffic grows ~100× (watch
`node_exporter` during a base backup).
**Arming (owner-coordinated, once, before real payments).** Ships disarmed; to turn it on:
1. **Owner (Selectel + Gitea):** create an S3 bucket (name **lowercase, no dots/underscores**)
and an S3 access key/secret; pick a repository **cipher passphrase** and store it **apart
from the S3 keys** (losing it makes the archive unrecoverable). Set the Gitea `PROD_` set —
variables `PROD_PGBACKREST_S3_ENDPOINT` (the S3 **host only** — no `https://`, no port, no
bucket) / `_S3_BUCKET` / `_S3_REGION`, an optional `_S3_PORT` (default 443, set only for a
non-standard provider port), and `PROD_PGBACKREST_ARCHIVE_MODE=on`; secrets
`PROD_PGBACKREST_S3_KEY` (the S3 **access key**) / `_S3_KEY_SECRET` (its paired **secret
key**, shown once at creation) / `_CIPHER_PASS` (a fresh repository passphrase, e.g.
`openssl rand -base64 48`).
2. Promote `development → master`, tag, and run **prod-deploy**. The roll recreates postgres
with `archive_mode=on` behind the maintenance page. (Archive pushes fail harmlessly for the
minute until step 3 creates the repository — the WAL is retained, not lost.)
3. On the main host, create the repository, verify archiving, take the first base backup. Run
pgBackRest **as the `postgres` OS user** (`-u postgres` — lock-dir/PGDATA consistency with
`archive-push`) and connect to the DB **as the superuser role** (`--pg1-user=scrabble`, the
`POSTGRES_USER`, not `postgres`); it inherits the container's `PGBACKREST_*` env:
```sh
docker exec -u postgres scrabble-postgres pgbackrest --stanza=scrabble --pg1-user=scrabble stanza-create
docker exec -u postgres scrabble-postgres pgbackrest --stanza=scrabble --pg1-user=scrabble check
docker exec -u postgres scrabble-postgres pgbackrest --stanza=scrabble --pg1-user=scrabble --type=full backup
docker exec -u postgres scrabble-postgres pgbackrest --stanza=scrabble info # (info takes no --pg1-user)
```
The few `archive-push` failures logged between `archive_mode=on` and `stanza-create` are the
expected transient (WAL retained, not lost); clear the counter afterwards with
`docker exec -u postgres scrabble-postgres psql -U scrabble -d scrabble -c "SELECT pg_stat_reset_shared('archiver');"`
so it does not trip the failing-archive alert.
4. Enable the daily timer: `ansible-playbook site.yml --limit main -e pitr_enabled=true`
(installs + starts `pgbackrest-backup.timer` on the main host).
5. Confirm in Grafana that the two archiving alerts are green (`last_archive_age` now tracks a
real number, `failed_count` flat).
**Restore drill (proves recoverability; re-run after arming and after any major change).** On
an **isolated, one-shot** target (a throwaway VM or a container with no ingress), pgBackRest,
the matching Postgres major, an empty `PGDATA`, and the same `PGBACKREST_*` environment:
```sh
# Throwaway container from the DB image (carries pgBackRest), the live PGBACKREST_* env, an
# empty PGDATA and no app network; restore, recover, verify, then wipe (-v drops the data).
IMG=$(docker inspect -f '{{.Config.Image}}' scrabble-postgres)
docker exec scrabble-postgres env | grep '^PGBACKREST_' > /tmp/drill.env; echo POSTGRES_PASSWORD=drill >> /tmp/drill.env
docker run -d --name pitr-drill --env-file /tmp/drill.env --entrypoint sleep "$IMG" infinity
docker exec pitr-drill sh -c 'rm -rf /var/lib/postgresql/data/*; chown -R postgres:postgres /var/lib/postgresql/data; chmod 700 /var/lib/postgresql/data'
# --type=immediate = to the base backup's consistency point; --type=time "--target=<ts>" for PITR
docker exec -u postgres pitr-drill pgbackrest --stanza=scrabble --pg1-path=/var/lib/postgresql/data --type=immediate restore
docker exec -u postgres pitr-drill pg_ctl -D /var/lib/postgresql/data -w start
docker exec -u postgres pitr-drill psql -U scrabble -d scrabble -c "SELECT count(*) FROM backend.accounts;" # verify data intact
docker rm -fv pitr-drill; rm -f /tmp/drill.env # wipe the restored real data
```
The target holds **real money + personal data** while it exists — keep it network-isolated and
**destroy it (wipe `PGDATA` + the instance) afterwards**. Record each drill (date, target
timestamp, outcome) here:
| Date | Target | Result |
| --- | --- | --- |
| 2026-07-09 | latest (`--type=immediate`) | PASS — v1.13.0 arming: 31.9 MB cluster restored from the encrypted S3 repo (3.7 MB compressed), recovered to consistency, `backend.accounts` intact; drill instance wiped. |
**bot-link cert rotation:** regenerate (`deploy/gen-certs.sh /tmp/c --force`), reset the
five `PROD_BOTLINK_*` secrets from `/tmp/c`, and re-run the workflow — both hosts redeploy
@@ -249,14 +347,17 @@ VITE_VK_APP_LINK, VITE_VK_APP_ID`. **Derived from `PUBLIC_BASE_URL` at deploy**
`PROD_{POSTGRES_PASSWORD, GM_BASICAUTH_HASH, GRAFANA_ADMIN_PASSWORD, TELEGRAM_BOT_TOKEN,
TELEGRAM_PROMO_BOT_TOKEN, EXPORT_SIGN_KEY, GATEWAY_HONEYTOKEN, REGISTRY_PASSWORD, SSH_KEY,
SSH_KNOWN_HOSTS, BOTLINK_CA, BOTLINK_GATEWAY_CERT, BOTLINK_GATEWAY_KEY, BOTLINK_BOT_CERT,
BOTLINK_BOT_KEY}`; variables:
BOTLINK_BOT_KEY, PGBACKREST_S3_KEY, PGBACKREST_S3_KEY_SECRET, PGBACKREST_CIPHER_PASS}`;
variables:
`PROD_{REGISTRY_USER, MAIN_HOST, TG_HOST, CADDY_SITE_ADDRESS, GM_BASICAUTH_USER, LOG_LEVEL,
TELEGRAM_GAME_CHANNEL_ID, TELEGRAM_CHAT_ID, TELEGRAM_SUPPORT_CHAT_ID, TELEGRAM_BOT_USERNAME,
VITE_TELEGRAM_BOT_ID, VITE_TELEGRAM_LINK, VITE_TELEGRAM_GAME_CHANNEL_NAME, SMTP_RELAY_FROM,
PUBLIC_BASE_URL, SMTP_RELAY_ADMIN_FROM, ADMIN_EMAIL, SMTP_RELAY_SERVICE_FROM, SERVICE_EMAIL,
GF_SMTP_ENABLED}`. The test contour uses the same names under `TEST_`, minus the prod-only
infra (`MAIN_HOST`/`TG_HOST`/`REGISTRY_*`/`SSH_*`/`BOTLINK_*`, which the test deploy generates
or runs locally) and plus `TEST_AWG_CONF` (the bot's VPN egress).
GF_SMTP_ENABLED, PGBACKREST_S3_ENDPOINT, PGBACKREST_S3_PORT, PGBACKREST_S3_BUCKET,
PGBACKREST_S3_REGION, PGBACKREST_ARCHIVE_MODE}`. The test contour uses the same names under `TEST_`, minus the
prod-only infra (`MAIN_HOST`/`TG_HOST`/`REGISTRY_*`/`SSH_*`/`BOTLINK_*` and the `PGBACKREST_*`
PITR set, which is prod-only — the test contour never archives) and plus `TEST_AWG_CONF` (the
bot's VPN egress).
## Host-side setup (outside this repo)
+3 -1
View File
@@ -45,5 +45,7 @@ safe (idempotent) and survives a host resize.
10m×3 log rotation), `deploy` user (docker group, no sudo), key-only sshd,
`ufw` default-deny incoming + allow SSH, fail2ban sshd jail, unattended
upgrades, chrony, `/opt/scrabble/{config,certs,dumps,images}`.
- **main**: `ufw` opens 80/443/9443; the external `edge` docker network.
- **main**: `ufw` opens 80/443/9443; the external `edge` docker network; the pgBackRest
daily base-backup systemd timer — installed only when `pitr_enabled=true` (off by default;
turned on as part of arming point-in-time recovery, see [`../README.md`](../README.md)).
- **tg**: verifies direct `api.telegram.org` egress (the no-VPN assumption).
+9
View File
@@ -27,3 +27,12 @@ docker_log_max_file: "3"
# path (a slow service beats a killed one). Set swap_size to "0" to skip provisioning.
swap_size: "1G"
swap_swappiness: 10
# Point-in-time recovery (pgBackRest). The base-backup systemd timer on the main host is
# gated by pitr_enabled so provisioning stays inert until archiving is armed — the timer
# would fail nightly if it ran before the S3 repository + stanza exist. Arm it as part of
# the PITR rollout (deploy/README.md): flip it on with `-e pitr_enabled=true` (or a main
# host_var) once the stanza is created. Only the `main` role reads these.
pitr_enabled: false
# systemd OnCalendar for the daily full base backup — a low-traffic hour on the main host.
pitr_backup_oncalendar: "*-*-* 04:00:00"
+27
View File
@@ -16,3 +16,30 @@
community.docker.docker_network:
name: edge
state: present
# --- pgBackRest base-backup schedule (point-in-time recovery) ------------------
# A daily full base backup via a systemd timer that runs pgBackRest inside the postgres
# container; archive_command handles the continuous WAL between backups. Gated by
# pitr_enabled so the schedule stays inert until archiving is armed (the S3 repository +
# stanza must exist first, or the run fails nightly). Arm per deploy/README.md.
- name: Install the pgBackRest base-backup service
ansible.builtin.template:
src: pgbackrest-backup.service.j2
dest: /etc/systemd/system/pgbackrest-backup.service
mode: "0644"
when: pitr_enabled | default(false) | bool
- name: Install the pgBackRest base-backup timer
ansible.builtin.template:
src: pgbackrest-backup.timer.j2
dest: /etc/systemd/system/pgbackrest-backup.timer
mode: "0644"
when: pitr_enabled | default(false) | bool
- name: Enable and start the pgBackRest base-backup timer
ansible.builtin.systemd:
name: pgbackrest-backup.timer
enabled: true
state: started
daemon_reload: true
when: pitr_enabled | default(false) | bool
@@ -0,0 +1,17 @@
# Managed by Ansible (deploy/ansible).
# Daily full pgBackRest base backup for the payments/game database. Runs pgBackRest
# inside the postgres container (where the repository configuration and PGDATA live);
# the continuous WAL between base backups is handled by the container's archive_command.
# Installed only when pitr_enabled is set (see deploy/ansible/group_vars/all.yml).
[Unit]
Description=pgBackRest full base backup (scrabble)
After=docker.service
Requires=docker.service
[Service]
Type=oneshot
# docker exec defaults to root, so run as the postgres OS user (-u postgres) for lock-dir and
# PGDATA consistency with archive-push, and connect to the database as the superuser role via
# --pg1-user: that role is the POSTGRES_USER (scrabble), not "postgres". It inherits the
# container's PGBACKREST_* environment (the S3 repository + cipher), so no host-side config.
ExecStart=/usr/bin/docker exec -u postgres scrabble-postgres pgbackrest --stanza=scrabble --pg1-user=scrabble --type=full backup
@@ -0,0 +1,12 @@
# Managed by Ansible (deploy/ansible).
# Fires the daily full base backup. Persistent=true catches up a run missed while the
# host was down. Installed only when pitr_enabled is set.
[Unit]
Description=Daily pgBackRest full base backup (scrabble)
[Timer]
OnCalendar={{ pitr_backup_oncalendar }}
Persistent=true
[Install]
WantedBy=timers.target
+1 -1
View File
@@ -86,7 +86,7 @@
# The game SPA and the Connect edge are served by the gateway. Strip any
# client-supplied X-Scrabble-Honeypot here so the gateway only ever honours the
# tag the honeypot block sets below (a client cannot self-tag a real request).
@gateway path /app /app/* /telegram /telegram/* /vk /vk/* /dict/* /dl/* /metrics/* /telemetry/* /scrabble.edge.v1.Gateway/*
@gateway path /app /app/* /telegram /telegram/* /vk /vk/* /dict/* /dl/* /pay/* /metrics/* /telemetry/* /scrabble.edge.v1.Gateway/*
handle @gateway {
reverse_proxy gateway:8081 {
header_up -X-Scrabble-Honeypot
+4
View File
@@ -28,6 +28,10 @@ services:
# the manage-topics and delete-messages rights.
TELEGRAM_SUPPORT_CHAT_ID: ${TELEGRAM_SUPPORT_CHAT_ID:-}
TELEGRAM_SUPPORT_STATE_DIR: /data
# The Telegram Stars payment outbox (shares the bot-state volume). A writable dir enables the
# Stars rail; empty disables it. The rail stays inert until a chip pack carries an XTR (Stars)
# price, so it is safe to leave on — seeding a Stars price in the admin is the real go-live.
TELEGRAM_STARS_OUTBOX_DIR: ${TELEGRAM_STARS_OUTBOX_DIR:-/data}
TELEGRAM_PROMO_BOT_TOKEN: ${TELEGRAM_PROMO_BOT_TOKEN:-}
TELEGRAM_BOT_USERNAME: ${TELEGRAM_BOT_USERNAME:-}
TELEGRAM_BOT_LINK: ${TELEGRAM_BOT_LINK:-}

Some files were not shown because too many files have changed in this diff Show More