Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 18785efc8c | |||
| 850884d077 | |||
| a58f2ce0e4 | |||
| e922f5f3b9 | |||
| 04976a64e8 | |||
| 4aa6174968 | |||
| 41f4fd3497 | |||
| 1c06d1d0d1 | |||
| 780ff68ec2 | |||
| 57ff2d03f8 | |||
| a9d0986e74 | |||
| 45957bdcd6 | |||
| 829e29a726 | |||
| 399508f2f0 | |||
| 3a18e683ca | |||
| 93d086a8a3 | |||
| 8fe1bdba6b | |||
| 7923b3cc09 | |||
| 4891216749 | |||
| f1b8769c89 | |||
| b6f28a2423 | |||
| e32ee9ce68 | |||
| dc946a1faf | |||
| 384bd143d0 | |||
| c5d22fceca | |||
| deaa7a29c5 | |||
| 24017bcb7f | |||
| 2c4f4b10dc |
@@ -77,7 +77,7 @@ jobs:
|
|||||||
# The main-stack images via compose (reuses the build args, incl. VERSION);
|
# The main-stack images via compose (reuses the build args, incl. VERSION);
|
||||||
# the bot separately, since it is profiled out of the prod compose.
|
# 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 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 build -f ../platform/telegram/Dockerfile --target bot --build-arg VERSION="$TAG" -t "$REGISTRY/scrabble-telegram-bot:$TAG" ..
|
||||||
docker push "$REGISTRY/scrabble-telegram-bot:$TAG"
|
docker push "$REGISTRY/scrabble-telegram-bot:$TAG"
|
||||||
|
|
||||||
@@ -135,6 +135,18 @@ jobs:
|
|||||||
DICT_VERSION: ${{ vars.DICT_VERSION }}
|
DICT_VERSION: ${{ vars.DICT_VERSION }}
|
||||||
POSTGRES_DB: ${{ vars.PROD_POSTGRES_DB }}
|
POSTGRES_DB: ${{ vars.PROD_POSTGRES_DB }}
|
||||||
POSTGRES_USER: ${{ vars.PROD_POSTGRES_USER }}
|
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
|
# TELEGRAM_MINIAPP_URL and GRAFANA_ROOT_URL are derived from PUBLIC_BASE_URL in
|
||||||
# deploy/write-prod-env.sh, not stored variables.
|
# deploy/write-prod-env.sh, not stored variables.
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -77,6 +77,16 @@ jobs:
|
|||||||
SERVICE_EMAIL: ${{ vars.PROD_SERVICE_EMAIL }}
|
SERVICE_EMAIL: ${{ vars.PROD_SERVICE_EMAIL }}
|
||||||
GRAFANA_SMTP_PORT: ${{ vars.GRAFANA_SMTP_PORT }}
|
GRAFANA_SMTP_PORT: ${{ vars.GRAFANA_SMTP_PORT }}
|
||||||
GF_SMTP_ENABLED: ${{ vars.PROD_GF_SMTP_ENABLED }}
|
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 }}
|
INPUT_TARGET: ${{ inputs.target_version }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|||||||
@@ -2,9 +2,12 @@
|
|||||||
|
|
||||||
Technical, step-by-step implementation of the monetization domain. Business mechanics and
|
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
|
the rationale for every rule live in [`docs/PAYMENTS.md`](docs/PAYMENTS.md) (RU mirror
|
||||||
[`docs/PAYMENTS_ru.md`](docs/PAYMENTS_ru.md)); this file is the *how*. Each stage is written
|
[`docs/PAYMENTS_ru.md`](docs/PAYMENTS_ru.md)); the frozen owner agreements they both derive
|
||||||
to be self-sufficient: returning to it gives full context — goal, exact touch-points,
|
from (the `D1`–`D41` decisions log) live in
|
||||||
tests, done-criteria, and current status — without re-deriving decisions.
|
[`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
|
## How to use this file
|
||||||
|
|
||||||
@@ -28,9 +31,9 @@ tests, done-criteria, and current status — without re-deriving decisions.
|
|||||||
|-------|-------|---------|--------|
|
|-------|-------|---------|--------|
|
||||||
| E0 | Payments data foundation | 1 | DONE |
|
| E0 | Payments data foundation | 1 | DONE |
|
||||||
| E1 | Trusted platform signal | 1 | DONE |
|
| E1 | Trusted platform signal | 1 | DONE |
|
||||||
| E2 | Currency + benefit core | 1 | TODO |
|
| E2 | Currency + benefit core | 1 | DONE |
|
||||||
| E3 | Wallet UI | 1 | TODO |
|
| E3 | Wallet UI | 1 | DONE |
|
||||||
| E4 | Durability (PITR) | 2 | TODO |
|
| E4 | Durability (PITR) | 2 | WIP |
|
||||||
| E5 | Payment intake | 2 | TODO |
|
| E5 | Payment intake | 2 | TODO |
|
||||||
| E6 | Ads | 2 | TODO |
|
| E6 | Ads | 2 | TODO |
|
||||||
| E7 | Admin & reports | 2 | TODO |
|
| E7 | Admin & reports | 2 | TODO |
|
||||||
@@ -82,9 +85,21 @@ Read once; individual stages assume it.
|
|||||||
`registerRoutes` gated `if s.payments != nil`, admin section in `registerConsole` gated
|
`registerRoutes` gated `if s.payments != nil`, admin section in `registerConsole` gated
|
||||||
`if s.payments != nil`.
|
`if s.payments != nil`.
|
||||||
- Game/other domains depend on payments only through a **narrow interface** (e.g.
|
- Game/other domains depend on payments only through a **narrow interface** (e.g.
|
||||||
`AdFree(ctx, account, platform) bool`, `SpendHint(ctx, account, platform) error`,
|
`AdFree(ctx, account, platform, present) bool`, `SpendHint(ctx, account, platform, present)
|
||||||
`Balances(ctx, account, platform) …`). Keep the surface small; this is the seam that lets
|
error`, `Balances(ctx, account, platform, present) …`), where `present` is the set of
|
||||||
payments become a separate process later without touching callers.
|
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 & codegen
|
||||||
|
|
||||||
@@ -283,33 +298,40 @@ Release 2). TG/direct subtype is not cryptographically trusted — E2 must keep
|
|||||||
|
|
||||||
## E2 — Currency + benefit core
|
## E2 — Currency + benefit core
|
||||||
|
|
||||||
**Status:** TODO · **Release 1** · depends on: E0, E1 · mechanics: PAYMENTS §2–§6, §11.
|
**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**
|
**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,
|
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
|
benefit application (no-ads stacking, hints per-origin), the legacy migration, and the
|
||||||
`SpendHint` rewrite. This is the heart.
|
`SpendHint` rewrite. This is the heart.
|
||||||
|
|
||||||
**Payments service (Go).**
|
**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)` → the segments spendable in the platform's context
|
- `Balances(ctx, account, platform, present)` → per-segment `{source, chips, spendable}` for
|
||||||
(VK→vk; TG→tg; direct→direct+vk+tg; VK-iOS→frozen/view; untrusted→none).
|
the context (VK→vk spendable, direct/tg hidden; TG→tg; direct→direct+vk+tg by priority;
|
||||||
- `Spend(ctx, account, platform, productID)` → gate-checked purchase of a value with chips:
|
VK-iOS→vk shown as a **frozen** number, none spendable; untrusted→view-only, none spendable).
|
||||||
resolve spendable segments by context, draw by priority (direct→vk→tg on web), write a
|
- `Spend(ctx, account, platform, present, productID)` → gate-checked purchase of a **value**
|
||||||
`spend` ledger row + decrement balance + apply benefit (extend `ads_paid_until[origin]`
|
(CHIP price, `method=NULL`; never a chip pack) with chips: resolve spendable segments by
|
||||||
from `max(now,end)` / set `ads_forever` / add hints) **in one tx**, stamping `origin` =
|
context, draw by priority direct→vk→tg, write a `spend` ledger row (+ a catalog **snapshot**
|
||||||
platform context. Refuse if untrusted (fail-closed) or funds insufficient.
|
of atoms+price) + decrement balance + apply benefit (extend `ads_paid_until[origin]` from
|
||||||
- `Grant(ctx, account, origin, atoms)` → `admin_grant` ledger row (price 0, concrete values
|
`max(now,end)` / set `ads_forever` / add hints) **in one tx**, stamping `origin` = platform
|
||||||
only, never chips), same benefit application; origin chosen by the admin (E7 UI; here the
|
context. Refuse if untrusted (fail-closed) or funds insufficient.
|
||||||
service method + an internal/admin entrypoint).
|
- `Grant(ctx, account, origin, atoms)` → a **0-price sale of a value**: an `admin_grant`
|
||||||
- `AdFree(ctx, account, platform)` / `HintsAvailable(ctx, account, platform)` /
|
ledger row (`chips_delta=0`, + snapshot), same benefit application; concrete values only,
|
||||||
`SpendHint(ctx, account, platform)` → apply the one-directional origin rule: in context P,
|
never chips (no chips move — it neither requires nor touches a balance). Origin chosen by
|
||||||
usable origins = {P} plus, when P is web/native, {vk,tg} (relaxation outward); in VK only
|
the admin. In E2 this is the Go service method only, exercised by tests; the admin grant UI
|
||||||
vk; in TG only tg.
|
+ catalog editor are E7.
|
||||||
- `Merge` / `Unlink` hooks: extend `accountmerge` to merge segments+benefits by origin
|
- `AdFree(ctx, account, platform, present)` / `HintsAvailable(…)` / `SpendHint(…)` → apply
|
||||||
(same-origin add, different coexist), and make segment availability follow identity
|
the one-directional origin rule: in context P, usable origins = {P} plus, when P is
|
||||||
presence (unlink → sleep, re-link → wake). Warn-before-unlink is a UI concern (surface the
|
web/native, {vk,tg} (relaxation outward); in VK only vk; in TG only tg. Hint consumption
|
||||||
balance via the interface).
|
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.**
|
**Backend wiring & migration.**
|
||||||
|
|
||||||
@@ -328,18 +350,22 @@ methods, Connect methods + transcode + FBS. Admin grant is internal/admin (E7 UI
|
|||||||
|
|
||||||
**Tests.**
|
**Tests.**
|
||||||
|
|
||||||
- unit (Go): gate-by-context matrix (every row of PAYMENTS §4); priority draw; no-ads
|
- unit (Go): gate-by-context matrix (every row of PAYMENTS §4, incl. VK-iOS frozen +
|
||||||
stacking (`+=` from max(now,end)) + forever override; per-origin hint applicability;
|
untrusted); priority draw; no-ads stacking (`+=` from max(now,end)) + forever override;
|
||||||
merge/unlink segment math.
|
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);
|
- 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/
|
admin_grant credits values not chips; legacy migration zeroes and flips reads; merge/
|
||||||
unlink over Postgres.
|
unlink over Postgres.
|
||||||
- UI: none new (E3 builds the screen); wallet DTO covered by codec unit tests.
|
- UI: none new (E3 builds the screen); wallet DTO covered by codec unit tests.
|
||||||
|
|
||||||
**Done-criteria.** With chips seeded via `admin_grant`, a user can buy no-ads/hints; the gate
|
**Done-criteria.** `admin_grant` applies no-ads/hints directly (a 0-price sale of a value —
|
||||||
blocks cross-context spend and cross-origin application; ads gate reads the new benefit;
|
no chips involved); the player chip-spend path (`Spend`) is proven by unit/integration tests
|
||||||
`SpendHint` uses segments; all layers green; **compliance regression** (a `direct` benefit
|
(balance seeded in-test, since a legitimate chip source arrives only with Release 2); the gate
|
||||||
never activates inside VK/TG) is a named test.
|
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
|
**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
|
`SpendHint`/`ads.Eligible`). Minimize surface, keep the interface narrow, no mixed-in
|
||||||
@@ -349,82 +375,128 @@ refactors. The legacy flip is expand-contract: reads move first, DROP much later
|
|||||||
|
|
||||||
## E3 — Wallet UI
|
## E3 — Wallet UI
|
||||||
|
|
||||||
**Status:** TODO · **Release 1** · depends on: E2 · mechanics: PAYMENTS §1, §7, §6, §13, §4.
|
**Status:** DONE · **Release 1** · depends on: E2 · mechanics: PAYMENTS §1, §7, §6, §13, §4.
|
||||||
|
|
||||||
**Goal.** The user-facing "Кошелёк" (Wallet) section: balances + active benefits + the
|
**Goal.** The user-facing "Кошелёк" (Wallet) section: balances + active benefits + the
|
||||||
catalog storefront, honouring guest-hidden, GP-stub, and the web-spend warning.
|
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/`).**
|
**UI (`ui/`).**
|
||||||
|
|
||||||
- New `'wallet'` tab in `ui/src/screens/SettingsHub.svelte` — `SettingsTab` union, tab
|
- New `'wallet'` tab in `ui/src/screens/SettingsHub.svelte` — `SettingsTab` union, tab button
|
||||||
button **between Friends (:65) and About (:66)**, body branch in the `:42-51` switch,
|
**between Friends and About** (guest-hidden like Friends, offline-disabled like Profile/Friends),
|
||||||
`'wallet'` route in `ui/src/lib/routeparse.ts` + `ui/src/App.svelte`. Reuse the hub's
|
body branch, `'wallet'` route in `ui/src/lib/routeparse.ts` + `ui/src/App.svelte`.
|
||||||
guest/offline gating.
|
- `Wallet.svelte` screen: context-available chip balances + active benefits (no-ads until date /
|
||||||
- `Wallet.svelte` screen: **minimal** — context-available chip balances + active benefits
|
forever, hints count). **No history feed** (PAYMENTS §11 — noise). Storefront: values priced in
|
||||||
(no-ads until date, hints count). **No history feed** (PAYMENTS §11 — noise). Storefront:
|
chips (buyable with `wallet.buy`), chip packs priced per method.
|
||||||
products from the configurable catalog, prices in chips (values) / per-method (chip packs).
|
|
||||||
- **Guest:** section hidden entirely (durable-only).
|
- **Guest:** section hidden entirely (durable-only).
|
||||||
- **GP build:** purchase CTA replaced by a stub ("install the RuStore build to make
|
- **GP build:** the chip-pack purchases are hidden behind a RuStore stub; spending earned chips on
|
||||||
purchases"); rewarded + spending earned chips still work. Detect the GP native build.
|
values still works (PAYMENTS §13). Detected by a build-time flag `VITE_GP_BUILD`
|
||||||
- **Web-spend warning:** before spending vk/tg chips in a web/native (direct) context, show
|
(`ui/src/lib/distribution.ts`), forcible under the mock e2e with `?gp`.
|
||||||
an own `Modal` (not `showPopup` — that eats the user-activation gesture) warning the value
|
- **Web-spend warning:** before a value spend that would draw vk/tg chips in a direct context, an
|
||||||
will be web/native-only.
|
own `Modal` (not `showPopup`) warns the benefit will be web/native-only. The context is inferred
|
||||||
- Extract all logic into `ui/src/lib/*` (unit-testable); keep `.svelte` thin.
|
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.**
|
**Tests.**
|
||||||
|
|
||||||
- unit (vitest): storefront/price formatting, context-available-segment selection, warning
|
- unit (Go): `projectCatalog` context matrix (value everywhere; pack per context method; misconfig
|
||||||
trigger condition.
|
omitted). unit (vitest): money/price formatting, spendable-segment selection, warning trigger,
|
||||||
- UI (Playwright mock, Chromium+WebKit): Wallet renders between Friends/About; guest hides
|
the GP flag; `decodeCatalog` codec round-trip (mock e2e bypasses the codec).
|
||||||
it; GP stub; warning modal on web vk/tg spend. Mock overlay must stay instant under
|
- integration (`inttest`): `/wallet/catalog` returns active products with the context-correct price
|
||||||
`MODE==='mock'` (or it intercepts taps).
|
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.** Owner can review the Wallet on the deployed test contour (visual sign-off
|
**Done-criteria (met).** Balances/benefits/storefront render per context; guest/GP/warning paths
|
||||||
is on the contour, not local); balances/benefits/storefront correct per context; guest/GP/
|
verified by unit + integration + mock e2e on both engines. **A *populated* contour review depends
|
||||||
warning paths verified. Release 1 is now demonstrable end-to-end via `admin_grant`.
|
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/` — style per-component with scoped CSS +
|
**Notes/risks.** No global `.btn`/`.ghost` in `ui/` — styled per-component with scoped CSS + tokens
|
||||||
tokens (mirror NewGame `.invite` for a CTA). Svelte whitespace/`$state` naming gotchas
|
(mirror NewGame `.invite`). Product titles are single-language catalog data (E0 `product.title`),
|
||||||
apply. iOS WebView download/gesture caveats are irrelevant here (no file delivery).
|
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)
|
## E4 — Durability (PITR)
|
||||||
|
|
||||||
**Status:** TODO · **Release 2** · depends on: E0 (schema exists) · mechanics: PAYMENTS §14.
|
**Status:** WIP — repo artifacts landed; **prod arming pending** (owner-coordinated, before
|
||||||
|
E5). · **Release 2** · depends on: E0 (schema exists) · mechanics: PAYMENTS §14 (D4).
|
||||||
|
|
||||||
**Goal.** Continuous WAL archiving with point-in-time recovery, armed **before the first
|
**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.
|
real money** is accepted (E5 prod). Protects both money and game data.
|
||||||
|
|
||||||
**Work.**
|
**Locked decisions (this stage).**
|
||||||
|
|
||||||
- Add WAL archiving to the prod Postgres (pgBackRest or WAL-G): base backups + continuous
|
- **Tool: pgBackRest.** **Destination: Selectel S3** object storage (encrypted AES-256-CBC,
|
||||||
WAL to a second host or object storage. Wire into `deploy/` (compose/prod overlay +
|
path-style addressing), **prod main host only** — the test contour never archives. (D4 left
|
||||||
ansible `deploy/ansible/`), config + secrets under the `PROD_` prefix.
|
the tool + destination open; resolved here. Warm replica stays deferred, per D4.)
|
||||||
- Restore runbook in `deploy/README.md`: base + WAL replay to a timestamp; test the restore
|
- **Retention 30 days**, **daily full base backup** (a systemd timer) + continuous WAL
|
||||||
on a scratch target.
|
(`archive_command`, a 5-minute forced switch bounds the recovery point). Assessment
|
||||||
- Keep the existing migration-time `pg_dump` (`deploy/prod-deploy.sh`) as belt-and-braces.
|
(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.
|
||||||
|
|
||||||
**Mandatory pre-prod assessment (owner-required, gates the Release 2 prod rollout).**
|
**Work (landed in the artifacts PR into `development`).**
|
||||||
Before the first money goes live, produce and record here:
|
|
||||||
|
|
||||||
1. **Disk-storage cost estimate** for the WAL archive + base backups (retention window ×
|
- pgBackRest in the DB image (`deploy/postgres/Dockerfile`); postgres becomes a built + pushed
|
||||||
WAL volume; account for both hosts / object-storage pricing). This can change hosting
|
image (prod overlay `image:` + `prod-deploy.yaml` build/push list).
|
||||||
sizing.
|
- Repository config + `archive_mode` via `PGBACKREST_*` env on the prod-overlay postgres
|
||||||
2. **PG performance-degradation assessment** from continuous archiving (write amplification,
|
service; secrets/vars rendered by `deploy/write-prod-env.sh` from the `PROD_PGBACKREST_*`
|
||||||
archive_command latency, backup I/O contention) on the prod-sized instance.
|
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`.
|
||||||
|
|
||||||
Neither blocks building the plan, but both **must** be completed and reviewed before the
|
**Prod arming (SEPARATE — owner-coordinated, before E5; NOT the artifacts PR).** Owner creates
|
||||||
prod release — surface the numbers to the owner (they may change host settings).
|
the Selectel S3 bucket + the `PROD_PGBACKREST_*` secrets/variables (incl. `ARCHIVE_MODE=on`);
|
||||||
|
then promote `development → master` → `prod-deploy` (archive_mode on behind the maintenance
|
||||||
|
window), `pgbackrest stanza-create` + first base backup + `check`, re-run Ansible with
|
||||||
|
`-e pitr_enabled=true`, and run the restore drill on an isolated one-shot target. Exact steps:
|
||||||
|
`deploy/README.md` (point-in-time recovery — arming).
|
||||||
|
|
||||||
**Tests.** Restore drill on a scratch instance (base + WAL → target timestamp) documented
|
**Tests.** Restore drill on an isolated one-shot instance (base + WAL → target timestamp),
|
||||||
and passing. No app-level tests.
|
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.** WAL archiving live on prod PG; a timed restore verified; cost + perf
|
**Done-criteria.** Artifacts merged with archiving inert. **Fully done** at arming: WAL
|
||||||
assessment recorded and owner-reviewed; runbook in `deploy/README.md`.
|
archiving live on prod PG; a timed restore verified; cost + perf assessment reviewed; runbook
|
||||||
|
current in `deploy/README.md`.
|
||||||
|
|
||||||
**Notes/risks.** The tg host is weak (1 vCPU) — if the archive lands there, watch
|
**Notes/risks.** The repository **cipher passphrase is unrecoverable if lost** — stored apart
|
||||||
contention. Migrations stay expand-contract so image rollback remains DB-safe alongside PITR.
|
from the S3 keys. Enabling `archive_mode` restarts postgres (rides the prod-deploy maintenance
|
||||||
|
window). Migrations stay expand-contract so image rollback remains DB-safe alongside PITR.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -440,7 +512,9 @@ receipts, and refunds.
|
|||||||
|
|
||||||
- `POST /api/v1/user/wallet/order` → create `order(pending)` (account/platform/product/
|
- `POST /api/v1/user/wallet/order` → create `order(pending)` (account/platform/product/
|
||||||
expected amount/origin), return the provider-specific launch payload with `order_id`
|
expected amount/origin), return the provider-specific launch payload with `order_id`
|
||||||
threaded in (Robokassa `InvId` / TG `invoice_payload` / VK `item`).
|
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`
|
- 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,
|
`@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
|
proxied into a payments intake handler. Match by `order_id`, verify amount, credit
|
||||||
|
|||||||
+4
-1
@@ -100,7 +100,10 @@ state, lobby enqueue, chat). The social/account/history operations under
|
|||||||
`/api/v1/user`: `friends/*` (request/respond/cancel/unfriend,
|
`/api/v1/user`: `friends/*` (request/respond/cancel/unfriend,
|
||||||
list/incoming, the one-time `code` issue/redeem), `blocks/*`, `invitations/*`
|
list/incoming, the one-time `code` issue/redeem), `blocks/*`, `invitations/*`
|
||||||
(create/accept/decline/cancel/list), `PUT profile`, `email/{request,confirm}`,
|
(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
|
second listener — `internal/pushgrpc`, a gRPC server (`BACKEND_GRPC_ADDR`) streaming
|
||||||
live events (your-turn, opponent-moved, chat, nudge, match-found, notify) to the
|
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
|
gateway. The gateway-only `POST /api/v1/internal/push-target` (a user's
|
||||||
|
|||||||
@@ -195,7 +195,8 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
emails.SetSendLimiter(account.NewSendLimiter(time.Minute, 5))
|
emails.SetSendLimiter(account.NewSendLimiter(time.Minute, 5))
|
||||||
// Account linking & merge: the orchestrator over the account, merge and
|
// Account linking & merge: the orchestrator over the account, merge and
|
||||||
// session layers. Wired to the /api/v1/user/link REST surface below.
|
// 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 := social.NewService(social.NewStore(db), accounts, games)
|
||||||
socialSvc.SetNotifier(hub)
|
socialSvc.SetNotifier(hub)
|
||||||
socialSvc.SetMetrics(tel.MeterProvider().Meter("scrabble/backend/social"))
|
socialSvc.SetMetrics(tel.MeterProvider().Meter("scrabble/backend/social"))
|
||||||
@@ -270,6 +271,12 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
}
|
}
|
||||||
logger.Info("payments domain ready")
|
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
|
// The image-render sidecar client for the PNG export artifact; nil (PNG
|
||||||
// download answers 404) when BACKEND_RENDERER_URL is unset.
|
// download answers 404) when BACKEND_RENDERER_URL is unset.
|
||||||
var renderer *render.Client
|
var renderer *render.Client
|
||||||
|
|||||||
@@ -51,8 +51,24 @@ var ErrSameAccount = errors.New("accountmerge: primary and secondary are the sam
|
|||||||
type Merger struct {
|
type Merger struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
now func() time.Time
|
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.
|
// NewMerger constructs a Merger over db.
|
||||||
func NewMerger(db *sql.DB) *Merger {
|
func NewMerger(db *sql.DB) *Merger {
|
||||||
return &Merger{db: db, now: func() time.Time { return time.Now().UTC() }}
|
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
|
return ErrSameAccount
|
||||||
}
|
}
|
||||||
now := m.now()
|
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 {
|
if err := guardActiveSharedGame(ctx, tx, primary, secondary); err != nil {
|
||||||
return err
|
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 {
|
if err := deleteEphemerals(ctx, tx, secondary); err != nil {
|
||||||
return err
|
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)
|
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
|
// 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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// mergeAccountFields adds secondary's hint wallet to primary and ORs the paid flag;
|
// mergeAccountFields bumps the primary account's updated_at to reflect the merge. The former
|
||||||
// all other profile fields stay the primary's.
|
// hint-wallet and paid-flag merge moved to the payments domain, where segments and benefits
|
||||||
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
// merge by origin (see the payments MergeTx step and docs/PAYMENTS.md §6); the legacy
|
||||||
var sec model.Accounts
|
// accounts.hint_balance / paid_account columns are deprecated and no longer read or written.
|
||||||
if err := postgres.SELECT(table.Accounts.AllColumns).
|
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, _ uuid.UUID, now time.Time) error {
|
||||||
FROM(table.Accounts).
|
upd := table.Accounts.UPDATE(table.Accounts.UpdatedAt).
|
||||||
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(secondary))).
|
SET(postgres.TimestampzT(now)).
|
||||||
QueryContext(ctx, tx, &sec); err != nil {
|
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(primary)))
|
||||||
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)))
|
|
||||||
if _, err := upd.ExecContext(ctx, tx); err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,14 +100,6 @@ type ActiveCampaign struct {
|
|||||||
OverrideDark *ColorSet
|
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
|
// 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.
|
// 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
|
// Campaigns outside their validity window, and campaigns with no messages, are
|
||||||
|
|||||||
@@ -6,30 +6,6 @@ import (
|
|||||||
"time"
|
"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) {
|
func TestComputeActiveSet(t *testing.T) {
|
||||||
now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.UTC)
|
now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.UTC)
|
||||||
past := now.Add(-24 * time.Hour)
|
past := now.Add(-24 * time.Hour)
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import (
|
|||||||
"scrabble/backend/internal/account"
|
"scrabble/backend/internal/account"
|
||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
"scrabble/backend/internal/notify"
|
"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
|
// 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
|
// 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.
|
// these games). Kept as a func so the game package never imports the robot package.
|
||||||
aiTrigger func(gameID uuid.UUID)
|
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
|
// 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
|
// 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.
|
// 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
|
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
|
// 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)
|
// 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.
|
// 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
|
return HintResult{Move: move}, nil
|
||||||
}
|
}
|
||||||
acc, err := svc.accounts.GetByID(ctx, accountID)
|
cxt, present, err := svc.walletContext(ctx, accountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return HintResult{}, err
|
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
|
used := pre.Seats[seat].HintsUsed
|
||||||
fromAllowance := used < pre.HintsPerPlayer
|
fromAllowance := used < pre.HintsPerPlayer
|
||||||
if !fromAllowance && acc.HintBalance <= 0 {
|
if !fromAllowance && wallet <= 0 {
|
||||||
return HintResult{}, ErrNoHintsLeft
|
return HintResult{}, ErrNoHintsLeft
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1142,9 +1189,9 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
|
|||||||
return HintResult{}, ErrNoHintAvailable
|
return HintResult{}, ErrNoHintAvailable
|
||||||
}
|
}
|
||||||
|
|
||||||
walletAfter := acc.HintBalance
|
walletAfter := wallet
|
||||||
if !fromAllowance {
|
if !fromAllowance {
|
||||||
spent, err := svc.accounts.SpendHint(ctx, accountID)
|
spent, err := svc.hintWallet.SpendHint(ctx, accountID, cxt, present)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return HintResult{}, err
|
return HintResult{}, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,13 +15,15 @@ import (
|
|||||||
|
|
||||||
"scrabble/backend/internal/account"
|
"scrabble/backend/internal/account"
|
||||||
"scrabble/backend/internal/ads"
|
"scrabble/backend/internal/ads"
|
||||||
|
"scrabble/backend/internal/payments"
|
||||||
"scrabble/backend/internal/server"
|
"scrabble/backend/internal/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
// bannerServer assembles a console-capable server with the ads domain wired.
|
// 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()
|
t.Helper()
|
||||||
adsSvc := ads.NewService(ads.NewStore(testDB))
|
adsSvc := ads.NewService(ads.NewStore(testDB))
|
||||||
|
paySvc := newPaymentsService()
|
||||||
srv := server.New(":0", server.Deps{
|
srv := server.New(":0", server.Deps{
|
||||||
Logger: zap.NewNop(),
|
Logger: zap.NewNop(),
|
||||||
Accounts: account.NewStore(testDB),
|
Accounts: account.NewStore(testDB),
|
||||||
@@ -29,8 +31,9 @@ func bannerServer(t *testing.T) (*server.Server, *ads.Service) {
|
|||||||
Registry: testRegistry,
|
Registry: testRegistry,
|
||||||
DictDir: dictDir(),
|
DictDir: dictDir(),
|
||||||
Ads: adsSvc,
|
Ads: adsSvc,
|
||||||
|
Payments: paySvc,
|
||||||
})
|
})
|
||||||
return srv, adsSvc
|
return srv, adsSvc, paySvc
|
||||||
}
|
}
|
||||||
|
|
||||||
// findCampaign returns the id of the campaign with the given name, or fails.
|
// 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.
|
// reorder/delete.
|
||||||
func TestBannerConsoleCRUD(t *testing.T) {
|
func TestBannerConsoleCRUD(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
srv, adsSvc := bannerServer(t)
|
srv, adsSvc, _ := bannerServer(t)
|
||||||
h := srv.Handler()
|
h := srv.Handler()
|
||||||
base := "http://admin.test/_gm"
|
base := "http://admin.test/_gm"
|
||||||
const origin = "http://admin.test"
|
const origin = "http://admin.test"
|
||||||
@@ -151,7 +154,7 @@ func TestBannerConsoleCRUD(t *testing.T) {
|
|||||||
// unrelated campaign's URL must be refused.
|
// unrelated campaign's URL must be refused.
|
||||||
func TestBannerMessageOwnership(t *testing.T) {
|
func TestBannerMessageOwnership(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
srv, adsSvc := bannerServer(t)
|
srv, adsSvc, _ := bannerServer(t)
|
||||||
h := srv.Handler()
|
h := srv.Handler()
|
||||||
base := "http://admin.test/_gm"
|
base := "http://admin.test/_gm"
|
||||||
const origin = "http://admin.test"
|
const origin = "http://admin.test"
|
||||||
@@ -207,10 +210,11 @@ type profileBanner struct {
|
|||||||
// wallet each suppress it.
|
// wallet each suppress it.
|
||||||
func TestBannerProfileEligibility(t *testing.T) {
|
func TestBannerProfileEligibility(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
srv, _ := bannerServer(t)
|
srv, _, pay := bannerServer(t)
|
||||||
accounts := account.NewStore(testDB)
|
accounts := account.NewStore(testDB)
|
||||||
id := provisionAccount(t)
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
// getBanner fetches the profile banner with no platform header (an untrusted context).
|
||||||
getBanner := func() profileBanner {
|
getBanner := func() profileBanner {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
rec := userGet(t, srv, "/api/v1/user/profile", id)
|
rec := userGet(t, srv, "/api/v1/user/profile", id)
|
||||||
@@ -223,10 +227,27 @@ func TestBannerProfileEligibility(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return p
|
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.
|
// A free account with no role and no benefit is eligible.
|
||||||
p := getBanner()
|
if p := getBanner(); p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
|
||||||
if p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
|
|
||||||
t.Fatalf("eligible account: banner=%v", p.Banner)
|
t.Fatalf("eligible account: banner=%v", p.Banner)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,19 +262,31 @@ func TestBannerProfileEligibility(t *testing.T) {
|
|||||||
t.Fatalf("revoke role: %v", err)
|
t.Fatalf("revoke role: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// A non-empty hint wallet suppresses it.
|
// A hint wallet no longer suppresses the banner — hints and no-ads are distinct benefits now.
|
||||||
if _, err := accounts.GrantHints(ctx, id, 5); err != nil {
|
if err := pay.Grant(ctx, id, payments.SourceTelegram, 5, 0, false); err != nil {
|
||||||
t.Fatalf("grant hints: %v", err)
|
t.Fatalf("grant hints: %v", err)
|
||||||
}
|
}
|
||||||
if p := getBanner(); p.Banner != nil {
|
if p := getBannerTG(); p.Banner == nil {
|
||||||
t.Fatal("a non-empty hint wallet still shows the banner")
|
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
|
// 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.
|
// banner block too, so the client's profile keeps the banner instead of losing it until reload.
|
||||||
func TestBannerSurvivesProfileUpdate(t *testing.T) {
|
func TestBannerSurvivesProfileUpdate(t *testing.T) {
|
||||||
srv, _ := bannerServer(t)
|
srv, _, _ := bannerServer(t)
|
||||||
id := provisionAccount(t)
|
id := provisionAccount(t)
|
||||||
|
|
||||||
body := `{"display_name":"Tester","preferred_language":"ru","time_zone":"UTC","away_start":"00:00",` +
|
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).
|
// default campaign stays plain (colours + urgent are ignored for it).
|
||||||
func TestBannerConsoleColorsAndUrgent(t *testing.T) {
|
func TestBannerConsoleColorsAndUrgent(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
srv, adsSvc := bannerServer(t)
|
srv, adsSvc, _ := bannerServer(t)
|
||||||
h := srv.Handler()
|
h := srv.Handler()
|
||||||
base := "http://admin.test/_gm"
|
base := "http://admin.test/_gm"
|
||||||
const origin = "http://admin.test"
|
const origin = "http://admin.test"
|
||||||
@@ -351,7 +384,7 @@ func TestBannerConsoleColorsAndUrgent(t *testing.T) {
|
|||||||
// otherwise suppress the banner.
|
// otherwise suppress the banner.
|
||||||
func TestBannerUrgentBypassesEligibility(t *testing.T) {
|
func TestBannerUrgentBypassesEligibility(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
srv, adsSvc := bannerServer(t)
|
srv, adsSvc, _ := bannerServer(t)
|
||||||
accounts := account.NewStore(testDB)
|
accounts := account.NewStore(testDB)
|
||||||
id := provisionAccount(t)
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import (
|
|||||||
"scrabble/backend/internal/account"
|
"scrabble/backend/internal/account"
|
||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
"scrabble/backend/internal/game"
|
"scrabble/backend/internal/game"
|
||||||
|
"scrabble/backend/internal/payments"
|
||||||
|
"scrabble/backend/internal/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestListForAccount checks the lobby "my games" query: it returns exactly the
|
// 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
|
// TestHintPolicy exercises the per-game allowance, the profile wallet and the
|
||||||
// disabled switch.
|
// disabled switch.
|
||||||
func TestHintPolicy(t *testing.T) {
|
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()
|
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)}
|
seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)}
|
||||||
seed := openingSeed(t)
|
seed := openingSeed(t)
|
||||||
g, err := svc.Create(ctx, game.CreateParams{
|
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) {
|
if _, err := svc.Hint(ctx, g.ID, seats[0]); !errors.Is(err, game.ErrNoHintsLeft) {
|
||||||
t.Fatalf("second hint = %v, want ErrNoHintsLeft", err)
|
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
|
res, err := svc.Hint(ctx, g.ID, seats[0]) // spends the wallet
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("wallet hint: %v", err)
|
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 {
|
func equalStrings(a, b []string) bool {
|
||||||
if len(a) != len(b) {
|
if len(a) != len(b) {
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import (
|
|||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
"scrabble/backend/internal/game"
|
"scrabble/backend/internal/game"
|
||||||
"scrabble/backend/internal/lobby"
|
"scrabble/backend/internal/lobby"
|
||||||
|
"scrabble/backend/internal/payments"
|
||||||
"scrabble/backend/internal/robot"
|
"scrabble/backend/internal/robot"
|
||||||
"scrabble/backend/internal/social"
|
"scrabble/backend/internal/social"
|
||||||
)
|
)
|
||||||
@@ -42,9 +43,42 @@ func newGameService() *game.Service {
|
|||||||
zap.NewNop(),
|
zap.NewNop(),
|
||||||
)
|
)
|
||||||
svc.SetFirstMoveEntropy(seatZeroFirstMove)
|
svc.SetFirstMoveEntropy(seatZeroFirstMove)
|
||||||
|
svc.SetHintWallet(newPaymentsService())
|
||||||
return svc
|
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
|
// 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
|
// 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
|
// despite the real draw's randomness: the first contender draws a blank — the best
|
||||||
|
|||||||
@@ -58,14 +58,6 @@ func bestMoveCount(t *testing.T, id uuid.UUID) int {
|
|||||||
return n
|
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) {
|
func bindEmailIdentity(t *testing.T, acc uuid.UUID, email string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
if _, err := testDB.ExecContext(context.Background(),
|
if _, err := testDB.ExecContext(context.Background(),
|
||||||
@@ -131,6 +123,7 @@ func TestAccountMergeCore(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
store := account.NewStore(testDB)
|
store := account.NewStore(testDB)
|
||||||
merger := accountmerge.NewMerger(testDB)
|
merger := accountmerge.NewMerger(testDB)
|
||||||
|
merger.SetPayments(newPaymentsService())
|
||||||
|
|
||||||
primary := provisionAccount(t)
|
primary := provisionAccount(t)
|
||||||
secondary := provisionAccount(t)
|
secondary := provisionAccount(t)
|
||||||
@@ -140,8 +133,8 @@ func TestAccountMergeCore(t *testing.T) {
|
|||||||
setStats(t, secondary, 3, 1, 2, 400, 80)
|
setStats(t, secondary, 3, 1, 2, 400, 80)
|
||||||
setStatsCounts(t, primary, 100, 5)
|
setStatsCounts(t, primary, 100, 5)
|
||||||
setStatsCounts(t, secondary, 50, 8)
|
setStatsCounts(t, secondary, 50, 8)
|
||||||
setWallet(t, primary, 2, false)
|
seedBenefit(t, primary, "telegram", 2, false)
|
||||||
setWallet(t, secondary, 5, true)
|
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
|
// 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.
|
// scrabble_ru (30) is new to primary and carried over.
|
||||||
setBestMove(t, primary, "scrabble_en", 50)
|
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")
|
t.Error("secondary stats row should be deleted after merge")
|
||||||
}
|
}
|
||||||
|
|
||||||
acc, err := store.GetByID(ctx, primary)
|
// The payments wallet merged by origin: hints sum (2+5) and the forever flag OR-s; the
|
||||||
if err != nil {
|
// deprecated accounts.hint_balance / paid_account columns are no longer touched by a merge.
|
||||||
t.Fatalf("get primary: %v", err)
|
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 {
|
if hints, _ := readBenefit(t, secondary, "telegram"); hints != 0 {
|
||||||
t.Errorf("hint balance = %d, want 7", acc.HintBalance)
|
t.Errorf("secondary benefit should be cleared after merge, got hints %d", hints)
|
||||||
}
|
|
||||||
if !acc.PaidAccount {
|
|
||||||
t.Error("paid_account should be true (ORed from secondary)")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if owner, ok, _ := store.AccountIDByIdentity(ctx, account.KindEmail, email); !ok || owner != primary {
|
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,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,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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,246 @@
|
|||||||
package payments
|
package payments
|
||||||
|
|
||||||
import "context"
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
// Service is the payments domain's application layer — the narrow surface other
|
"github.com/google/uuid"
|
||||||
// domains depend on, keeping the schema reachable through one seam. The
|
)
|
||||||
// data-foundation layer exposes only a health check; the wallet, benefit and
|
|
||||||
// store-compliance operations arrive with the currency mechanics.
|
// 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 {
|
type Service struct {
|
||||||
store *Store
|
store *Store
|
||||||
|
clock func() time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewService constructs a Service over store.
|
// NewService constructs a Service over store with a wall-clock time source.
|
||||||
func NewService(store *Store) *Service { return &Service{store: store} }
|
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.
|
// Ping reports whether the payments schema is reachable.
|
||||||
func (s *Service) Ping(ctx context.Context) error { return s.store.Ping(ctx) }
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,13 +14,16 @@ import (
|
|||||||
// Store is the Postgres-backed query surface for the payments schema. It is the
|
// 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
|
// only place in the backend that issues SQL against payments.* (an
|
||||||
// import-boundary test enforces it), so the domain stays extractable into its
|
// import-boundary test enforces it), so the domain stays extractable into its
|
||||||
// own database.
|
// 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 {
|
type Store struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
|
cache *walletCache
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewStore constructs a Store wrapping db.
|
// NewStore constructs a Store wrapping db, with an empty read cache.
|
||||||
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
|
func NewStore(db *sql.DB) *Store { return &Store{db: db, cache: newWalletCache()} }
|
||||||
|
|
||||||
// Ping verifies the payments schema is reachable by reading the singleton config
|
// 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
|
// row. It is the data-foundation health check; the wallet query surface arrives
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
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.
|
||||||
|
func insertLedgerTx(ctx context.Context, tx *sql.Tx, accountID uuid.UUID, kind string, source, origin *Source, chipsDelta int, productID *uuid.UUID, 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.Snapshot, table.Ledger.CreatedAt,
|
||||||
|
).VALUES(
|
||||||
|
id, accountID, kind,
|
||||||
|
sourceOrNull(source), sourceOrNull(origin), int32(chipsDelta),
|
||||||
|
uuidOrNull(productID), 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, 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, 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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"scrabble/backend/internal/ads"
|
"scrabble/backend/internal/ads"
|
||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
"scrabble/backend/internal/notify"
|
"scrabble/backend/internal/notify"
|
||||||
|
"scrabble/backend/internal/payments"
|
||||||
)
|
)
|
||||||
|
|
||||||
// bannerDTO is the advertising-banner block attached to an eligible viewer's
|
// bannerDTO is the advertising-banner block attached to an eligible viewer's
|
||||||
@@ -55,7 +56,21 @@ type bannerTimingsDTO struct {
|
|||||||
// a language switch).
|
// a language switch).
|
||||||
func (s *Server) profileResponse(ctx context.Context, acc account.Account) profileResponse {
|
func (s *Server) profileResponse(ctx context.Context, acc account.Account) profileResponse {
|
||||||
r := profileResponseFor(acc)
|
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)
|
s.fillLinkedIdentities(ctx, &r, acc.ID)
|
||||||
r.DictVersions = s.currentDictVersions()
|
r.DictVersions = s.currentDictVersions()
|
||||||
return r
|
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
|
// 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
|
// reading roles or campaigns is logged and treated as "no banner" so the profile
|
||||||
// response still succeeds.
|
// 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 {
|
if s.ads == nil {
|
||||||
return 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))
|
s.log.Warn("banner: active set failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// An urgent campaign is shown to every viewer; otherwise the normal eligibility
|
// An urgent campaign is shown to every viewer; otherwise the banner is suppressed by the
|
||||||
// gate applies (a paid account, a non-empty hint wallet or the no_banner role
|
// no_banner role or by an active no-ads benefit applicable in the viewer's context (the
|
||||||
// hides the banner).
|
// 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 {
|
if !urgent {
|
||||||
hasNoBanner, err := s.accounts.HasRole(ctx, acc.ID, account.RoleNoBanner)
|
hasNoBanner, err := s.accounts.HasRole(ctx, acc.ID, account.RoleNoBanner)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Warn("banner: role check failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
s.log.Warn("banner: role check failed", zap.String("account", acc.ID.String()), zap.Error(err))
|
||||||
return nil
|
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
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"scrabble/backend/internal/feedback"
|
"scrabble/backend/internal/feedback"
|
||||||
"scrabble/backend/internal/game"
|
"scrabble/backend/internal/game"
|
||||||
"scrabble/backend/internal/lobby"
|
"scrabble/backend/internal/lobby"
|
||||||
|
"scrabble/backend/internal/payments"
|
||||||
"scrabble/backend/internal/session"
|
"scrabble/backend/internal/session"
|
||||||
"scrabble/backend/internal/social"
|
"scrabble/backend/internal/social"
|
||||||
)
|
)
|
||||||
@@ -65,6 +66,13 @@ func (s *Server) registerRoutes() {
|
|||||||
// client may still reach, to fetch the block's expiry and reason for the blocked screen.
|
// client may still reach, to fetch the block's expiry and reason for the blocked screen.
|
||||||
u.GET("/block-status", s.handleBlockStatus)
|
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.links != nil {
|
if s.links != nil {
|
||||||
// Account linking & merge. The request step always mails a code;
|
// Account linking & merge. The request step always mails a code;
|
||||||
// a required merge is revealed only after the code is verified, and the
|
// a required merge is revealed only after the code is verified, and the
|
||||||
@@ -250,6 +258,14 @@ func statusForError(err error) (int, string) {
|
|||||||
return http.StatusConflict, "last_identity"
|
return http.StatusConflict, "last_identity"
|
||||||
case errors.Is(err, accountmerge.ErrActiveGameConflict):
|
case errors.Is(err, accountmerge.ErrActiveGameConflict):
|
||||||
return http.StatusConflict, "merge_active_game_conflict"
|
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, account.ErrInvalidEmail):
|
case errors.Is(err, account.ErrInvalidEmail):
|
||||||
return http.StatusBadRequest, "invalid_email"
|
return http.StatusBadRequest, "invalid_email"
|
||||||
case errors.Is(err, account.ErrCodeMismatch), errors.Is(err, account.ErrCodeExpired),
|
case errors.Is(err, account.ErrCodeMismatch), errors.Is(err, account.ErrCodeExpired),
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -13,6 +13,22 @@ POSTGRES_DB=scrabble
|
|||||||
POSTGRES_USER=scrabble
|
POSTGRES_USER=scrabble
|
||||||
POSTGRES_PASSWORD=change-me # required
|
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 -------------------------------------------------------------
|
# --- Dictionary -------------------------------------------------------------
|
||||||
# scrabble-dictionary release tag baked into the image as the SEED dictionary for a
|
# 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
|
# FRESH volume (image build-arg; also labels the resident seed version). After first
|
||||||
|
|||||||
+90
-8
@@ -220,10 +220,89 @@ release tag, so any prior release is reachable.
|
|||||||
**Migrations** must be **expand-contract** (backward-compatible; goose is forward-only):
|
**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
|
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
|
`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
|
writer) is stopped for a consistent **whole-database** `pg_dump` into `/opt/scrabble/dumps`
|
||||||
backend migrates. **Manual DB restore** (only if a migration was destructive):
|
(it covers `backend` **and** `payments`) before the new backend migrates. **Manual DB
|
||||||
`docker exec -i scrabble-postgres psql -U scrabble -d scrabble -c 'DROP SCHEMA backend CASCADE'`,
|
restore** (only if a migration was destructive): drop the app schemas in the same instance
|
||||||
then pipe the dump into the same `psql`, and redeploy the matching old tag.
|
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.
|
||||||
|
|
||||||
|
**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 a ~10 MB, sub-second job on the 2 vCPU host. Revisit both 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, take the first base backup, and verify:
|
||||||
|
```sh
|
||||||
|
docker exec scrabble-postgres pgbackrest --stanza=scrabble stanza-create
|
||||||
|
docker exec scrabble-postgres pgbackrest --stanza=scrabble --type=full backup
|
||||||
|
docker exec scrabble-postgres pgbackrest --stanza=scrabble check
|
||||||
|
```
|
||||||
|
4. Enable the daily timer: `ansible-playbook site.yml -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
|
||||||
|
pgbackrest --stanza=scrabble --type=time "--target=YYYY-MM-DD HH:MM:SS+00" --delta restore
|
||||||
|
# start Postgres; it replays WAL to the target; then verify a known row / the ledger tail
|
||||||
|
```
|
||||||
|
|
||||||
|
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 timestamp | Result |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| _pending first arming_ | — | — |
|
||||||
|
|
||||||
**bot-link cert rotation:** regenerate (`deploy/gen-certs.sh /tmp/c --force`), reset the
|
**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
|
five `PROD_BOTLINK_*` secrets from `/tmp/c`, and re-run the workflow — both hosts redeploy
|
||||||
@@ -249,14 +328,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,
|
`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,
|
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,
|
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,
|
`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,
|
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,
|
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,
|
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
|
GF_SMTP_ENABLED, PGBACKREST_S3_ENDPOINT, PGBACKREST_S3_PORT, PGBACKREST_S3_BUCKET,
|
||||||
infra (`MAIN_HOST`/`TG_HOST`/`REGISTRY_*`/`SSH_*`/`BOTLINK_*`, which the test deploy generates
|
PGBACKREST_S3_REGION, PGBACKREST_ARCHIVE_MODE}`. The test contour uses the same names under `TEST_`, minus the
|
||||||
or runs locally) and plus `TEST_AWG_CONF` (the bot's VPN egress).
|
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)
|
## Host-side setup (outside this repo)
|
||||||
|
|
||||||
|
|||||||
@@ -45,5 +45,7 @@ safe (idempotent) and survives a host resize.
|
|||||||
10m×3 log rotation), `deploy` user (docker group, no sudo), key-only sshd,
|
10m×3 log rotation), `deploy` user (docker group, no sudo), key-only sshd,
|
||||||
`ufw` default-deny incoming + allow SSH, fail2ban sshd jail, unattended
|
`ufw` default-deny incoming + allow SSH, fail2ban sshd jail, unattended
|
||||||
upgrades, chrony, `/opt/scrabble/{config,certs,dumps,images}`.
|
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).
|
- **tg**: verifies direct `api.telegram.org` egress (the no-VPN assumption).
|
||||||
|
|||||||
@@ -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.
|
# path (a slow service beats a killed one). Set swap_size to "0" to skip provisioning.
|
||||||
swap_size: "1G"
|
swap_size: "1G"
|
||||||
swap_swappiness: 10
|
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"
|
||||||
|
|||||||
@@ -16,3 +16,30 @@
|
|||||||
community.docker.docker_network:
|
community.docker.docker_network:
|
||||||
name: edge
|
name: edge
|
||||||
state: present
|
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,15 @@
|
|||||||
|
# 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 runs as the image's postgres user and inherits the container's PGBACKREST_*
|
||||||
|
# environment (the S3 repository + cipher), so no repository config is needed on the host.
|
||||||
|
ExecStart=/usr/bin/docker exec scrabble-postgres pgbackrest --stanza=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
|
||||||
@@ -45,6 +45,43 @@ services:
|
|||||||
memory: 384M
|
memory: 384M
|
||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
|
image: ${REGISTRY:?set REGISTRY}/scrabble-postgres:${TAG:?set TAG}
|
||||||
|
# Continuous WAL archiving to S3 via pgBackRest (point-in-time recovery), on the prod
|
||||||
|
# main host only. archive_mode is gated by PGBACKREST_ARCHIVE_MODE (default "off"), so
|
||||||
|
# merging/redeploying this stack does NOT start archiving until the operator arms it:
|
||||||
|
# archiving stays inert — and cannot pile WAL onto the disk — until the S3 repository is
|
||||||
|
# set up, the stanza is created and the switch is flipped on. See deploy/README.md
|
||||||
|
# (point-in-time recovery — arming). Non-secret settings are inline; the endpoint,
|
||||||
|
# bucket, region, S3 keys and repository cipher passphrase come from the prod env.sh
|
||||||
|
# (deploy/write-prod-env.sh, PROD_ secrets/variables).
|
||||||
|
environment:
|
||||||
|
PGBACKREST_STANZA: scrabble
|
||||||
|
PGBACKREST_PG1_PATH: /var/lib/postgresql/data
|
||||||
|
PGBACKREST_REPO1_TYPE: s3
|
||||||
|
PGBACKREST_REPO1_PATH: /pgbackrest
|
||||||
|
PGBACKREST_REPO1_S3_URI_STYLE: path
|
||||||
|
PGBACKREST_REPO1_S3_ENDPOINT: ${PGBACKREST_S3_ENDPOINT:-}
|
||||||
|
PGBACKREST_REPO1_S3_PORT: ${PGBACKREST_S3_PORT:-443}
|
||||||
|
PGBACKREST_REPO1_S3_BUCKET: ${PGBACKREST_S3_BUCKET:-}
|
||||||
|
PGBACKREST_REPO1_S3_REGION: ${PGBACKREST_S3_REGION:-}
|
||||||
|
PGBACKREST_REPO1_S3_KEY: ${PGBACKREST_S3_KEY:-}
|
||||||
|
PGBACKREST_REPO1_S3_KEY_SECRET: ${PGBACKREST_S3_KEY_SECRET:-}
|
||||||
|
PGBACKREST_REPO1_CIPHER_TYPE: aes-256-cbc
|
||||||
|
PGBACKREST_REPO1_CIPHER_PASS: ${PGBACKREST_CIPHER_PASS:-}
|
||||||
|
PGBACKREST_REPO1_RETENTION_FULL: "30"
|
||||||
|
PGBACKREST_COMPRESS_TYPE: zst
|
||||||
|
PGBACKREST_LOG_LEVEL_CONSOLE: info
|
||||||
|
PGBACKREST_LOG_LEVEL_FILE: "off"
|
||||||
|
# archive_command is inert while archive_mode is off, so it is always present and only
|
||||||
|
# the mode switches. A forced 5-minute segment switch bounds the recovery point.
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- archive_mode=${PGBACKREST_ARCHIVE_MODE:-off}
|
||||||
|
- -c
|
||||||
|
- "archive_command=pgbackrest --stanza=scrabble archive-push %p"
|
||||||
|
- -c
|
||||||
|
- archive_timeout=300
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
limits:
|
limits:
|
||||||
|
|||||||
@@ -38,7 +38,13 @@ x-logging: &default-logging
|
|||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
container_name: scrabble-postgres
|
container_name: scrabble-postgres
|
||||||
image: postgres:17-alpine
|
# Built from postgres:17-alpine + pgBackRest (deploy/postgres/Dockerfile) so the prod
|
||||||
|
# main host can archive WAL for point-in-time recovery. Archiving is switched on only by
|
||||||
|
# the prod overlay (docker-compose.prod.yml); on this contour the extra binary is present
|
||||||
|
# but idle and this is a plain postgres. See deploy/README.md (point-in-time recovery).
|
||||||
|
image: scrabble-postgres:latest
|
||||||
|
build:
|
||||||
|
context: postgres
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@@ -212,3 +212,62 @@ groups:
|
|||||||
- evaluator: { type: gt, params: [0.8] }
|
- evaluator: { type: gt, params: [0.8] }
|
||||||
labels: { severity: warning }
|
labels: { severity: warning }
|
||||||
annotations: { summary: 'Postgres using over 80% of max_connections.' }
|
annotations: { summary: 'Postgres using over 80% of max_connections.' }
|
||||||
|
|
||||||
|
# Continuous WAL archiving health (pgBackRest -> S3, point-in-time recovery). Both rules
|
||||||
|
# read the postgres_exporter's built-in pg_stat_archiver metrics and are absent/NaN-safe:
|
||||||
|
# on the test contour (and any host before archiving is armed) archive_mode is off, so
|
||||||
|
# failed_count stays 0 and last_archive_age is NaN — neither threshold trips.
|
||||||
|
- orgId: 1
|
||||||
|
name: scrabble-backup
|
||||||
|
folder: Alerts
|
||||||
|
interval: 1m
|
||||||
|
rules:
|
||||||
|
- uid: pg_archive_failing
|
||||||
|
title: WAL archiving failing
|
||||||
|
condition: C
|
||||||
|
for: 15m
|
||||||
|
noDataState: OK
|
||||||
|
execErrState: OK
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange: { from: 900, to: 0 }
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
refId: A
|
||||||
|
expr: increase(pg_stat_archiver_failed_count[15m])
|
||||||
|
instant: true
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
expression: A
|
||||||
|
conditions:
|
||||||
|
- evaluator: { type: gt, params: [0] }
|
||||||
|
labels: { severity: critical }
|
||||||
|
annotations: { summary: 'pgBackRest archive_command is failing — PITR is degrading and pg_wal can fill the disk. Run `docker exec scrabble-postgres pgbackrest --stanza=scrabble check`.' }
|
||||||
|
|
||||||
|
- uid: pg_archive_stalled
|
||||||
|
title: WAL archiving stalled
|
||||||
|
condition: C
|
||||||
|
for: 15m
|
||||||
|
noDataState: OK
|
||||||
|
execErrState: OK
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange: { from: 300, to: 0 }
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
refId: A
|
||||||
|
expr: pg_stat_archiver_last_archive_age
|
||||||
|
instant: true
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
expression: A
|
||||||
|
conditions:
|
||||||
|
- evaluator: { type: gt, params: [1800] }
|
||||||
|
labels: { severity: critical }
|
||||||
|
annotations: { summary: 'No WAL segment archived for over 30 minutes (archive_timeout is 5m) — archiving is stalled; the PITR recovery point is frozen and pg_wal may grow.' }
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Postgres for the Scrabble contour, extended with pgBackRest for continuous WAL
|
||||||
|
# archiving and point-in-time recovery. pgBackRest must live in the database container
|
||||||
|
# because Postgres runs archive_command in-process; the scheduled base backups and the
|
||||||
|
# manual restore drills invoke the same binary through `docker exec`, inheriting the
|
||||||
|
# repository configuration from the container environment.
|
||||||
|
#
|
||||||
|
# Archiving is enabled only on the production main host, where the prod overlay
|
||||||
|
# (docker-compose.prod.yml) sets archive_mode and supplies the S3 repository. On the test
|
||||||
|
# contour this image behaves exactly as a plain postgres:17-alpine. See deploy/README.md
|
||||||
|
# (point-in-time recovery).
|
||||||
|
FROM postgres:17-alpine
|
||||||
|
RUN apk add --no-cache pgbackrest
|
||||||
@@ -140,7 +140,10 @@ if [ "$MIGRATION" = 1 ]; then
|
|||||||
echo "migration deploy: opening maintenance window (stopping the backend = the only writer)"
|
echo "migration deploy: opening maintenance window (stopping the backend = the only writer)"
|
||||||
dc stop backend
|
dc stop backend
|
||||||
dump="$DUMP_DIR/pre-$TAG-$(date +%Y%m%d-%H%M%S).sql"
|
dump="$DUMP_DIR/pre-$TAG-$(date +%Y%m%d-%H%M%S).sql"
|
||||||
if ! docker exec scrabble-postgres pg_dump -U "$PG_USER" -d "$PG_DB" -n backend > "$dump"; then
|
# Dump the WHOLE database (no -n): the payments schema — and any schema added later —
|
||||||
|
# must be in the belt-and-braces snapshot, not just backend. Restored manually into the
|
||||||
|
# same instance only if a migration turned out destructive (see deploy/README.md).
|
||||||
|
if ! docker exec scrabble-postgres pg_dump -U "$PG_USER" -d "$PG_DB" > "$dump"; then
|
||||||
echo "pg_dump failed; restarting the old backend and aborting"
|
echo "pg_dump failed; restarting the old backend and aborting"
|
||||||
dc start backend
|
dc start backend
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
@@ -73,4 +73,16 @@ export GF_SMTP_ENABLED='$GF_SMTP_ENABLED'
|
|||||||
export PUBLIC_BASE_URL='$PUBLIC_BASE_URL'
|
export PUBLIC_BASE_URL='$PUBLIC_BASE_URL'
|
||||||
export GATEWAY_HONEYTOKEN='$GATEWAY_HONEYTOKEN'
|
export GATEWAY_HONEYTOKEN='$GATEWAY_HONEYTOKEN'
|
||||||
export GATEWAY_ABUSE_BAN_ENABLED='true'
|
export GATEWAY_ABUSE_BAN_ENABLED='true'
|
||||||
|
# Continuous WAL archiving (pgBackRest -> S3) for point-in-time recovery. The artifact
|
||||||
|
# ships disarmed: PGBACKREST_ARCHIVE_MODE defaults off, so archiving stays inert until the
|
||||||
|
# operator sets the S3 repository values + secrets, creates the stanza and flips the switch
|
||||||
|
# on (deploy/README.md). Empty repository values are harmless while the mode is off.
|
||||||
|
export PGBACKREST_ARCHIVE_MODE='${PGBACKREST_ARCHIVE_MODE:-off}'
|
||||||
|
export PGBACKREST_S3_ENDPOINT='$PGBACKREST_S3_ENDPOINT'
|
||||||
|
export PGBACKREST_S3_PORT='${PGBACKREST_S3_PORT:-443}'
|
||||||
|
export PGBACKREST_S3_BUCKET='$PGBACKREST_S3_BUCKET'
|
||||||
|
export PGBACKREST_S3_REGION='$PGBACKREST_S3_REGION'
|
||||||
|
export PGBACKREST_S3_KEY='$PGBACKREST_S3_KEY'
|
||||||
|
export PGBACKREST_S3_KEY_SECRET='$PGBACKREST_S3_KEY_SECRET'
|
||||||
|
export PGBACKREST_CIPHER_PASS='$PGBACKREST_CIPHER_PASS'
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -522,6 +522,25 @@ stops only feedback submission). Roles are listed and granted/revoked on the use
|
|||||||
message does not mark it read — only the explicit actions do; message bodies and attachments are
|
message does not mark it read — only the explicit actions do; message bodies and attachments are
|
||||||
shown defensively (text escaped, attachments downloaded rather than rendered).
|
shown defensively (text escaped, attachments downloaded rather than rendered).
|
||||||
|
|
||||||
|
### Wallet
|
||||||
|
|
||||||
|
Durable players have a **Wallet** — a tab in the Settings hub, between Friends and About; guests have
|
||||||
|
none. It shows their **chips** (the in-game currency, split by where they were funded — VK, Telegram
|
||||||
|
or the web), their **active benefits** (ads off until a date or forever, and the available hint
|
||||||
|
count), and a **store**. What is visible and spendable depends on **where the app runs**, by the
|
||||||
|
store-compliance rules in [`PAYMENTS.md`](PAYMENTS.md): inside a store only that store's chips are
|
||||||
|
usable; on the open web all attached chips are, drawn web → VK → Telegram; on VK-iOS the balance is
|
||||||
|
shown but frozen for spending.
|
||||||
|
|
||||||
|
The **store** lists **values** bought with chips (extra hints, days without ads) at a fixed chip
|
||||||
|
price shown in every context, and **chip packs** bought with real money, priced in the running
|
||||||
|
context's currency (VK Votes, Telegram Stars, or roubles on the web). Buying a value applies its
|
||||||
|
benefit at once. Before a web purchase that would draw VK/Telegram chips, the app **warns** that the
|
||||||
|
benefit will then work only on the web and in the app — a store rule — and asks the player to confirm.
|
||||||
|
On the **Google Play** build the money purchases are hidden behind a note pointing to the RuStore
|
||||||
|
build (Google's in-app-currency rule); spending already-earned chips still works. The wallet keeps
|
||||||
|
**no purchase history** — only the current balances, benefits and store.
|
||||||
|
|
||||||
### Advertising banner
|
### Advertising banner
|
||||||
|
|
||||||
A one-line banner under the nav shows short promotional or operational messages to **free
|
A one-line banner under the nav shows short promotional or operational messages to **free
|
||||||
|
|||||||
@@ -535,6 +535,25 @@ high-rate флага. С карточки пользователя операт
|
|||||||
сообщения и вложения показываются защищённо (текст экранируется, вложения отдаются на скачивание, а не
|
сообщения и вложения показываются защищённо (текст экранируется, вложения отдаются на скачивание, а не
|
||||||
рендерятся).
|
рендерятся).
|
||||||
|
|
||||||
|
### Кошелёк
|
||||||
|
|
||||||
|
У постоянных (не гостевых) игроков есть **Кошелёк** — вкладка в разделе настроек, между «Друзьями» и
|
||||||
|
«О программе»; у гостей его нет. Он показывает **фишки** (внутриигровую валюту, разделённую по тому,
|
||||||
|
где она была пополнена — VK, Telegram или веб), **активные блага** (реклама выключена до даты или
|
||||||
|
навсегда, и число доступных подсказок) и **магазин**. Что видно и что можно потратить, зависит от
|
||||||
|
того, **где запущено приложение**, по правилам соответствия магазинам из [`PAYMENTS.md`](PAYMENTS.md):
|
||||||
|
внутри магазина доступны только его фишки; в открытом вебе — все привязанные, списываются в порядке
|
||||||
|
веб → VK → Telegram; на VK-iOS баланс показан, но трата заморожена.
|
||||||
|
|
||||||
|
**Магазин** перечисляет **ценности**, покупаемые за фишки (дополнительные подсказки, дни без рекламы),
|
||||||
|
по фиксированной цене в фишках, одинаковой во всех контекстах, и **наборы фишек**, покупаемые за
|
||||||
|
настоящие деньги, в валюте текущего контекста (голоса VK, звёзды Telegram или рубли в вебе). Покупка
|
||||||
|
ценности сразу применяет её благо. Перед покупкой в вебе, которая списала бы фишки VK/Telegram,
|
||||||
|
приложение **предупреждает**, что благо будет работать только в вебе и в приложении — это правило
|
||||||
|
магазинов — и просит подтверждения. В сборке для **Google Play** покупки за деньги скрыты за подсказкой
|
||||||
|
установить сборку из RuStore (правило Google о внутриигровой валюте); трата уже заработанных фишек
|
||||||
|
по-прежнему работает. Кошелёк **не хранит историю покупок** — только текущие балансы, блага и магазин.
|
||||||
|
|
||||||
### Рекламный баннер
|
### Рекламный баннер
|
||||||
|
|
||||||
Однострочный баннер под навбаром показывает короткие рекламные или служебные сообщения **бесплатным
|
Однострочный баннер под навбаром показывает короткие рекламные или служебные сообщения **бесплатным
|
||||||
|
|||||||
@@ -273,6 +273,16 @@ the **origin benefit applicable in the current context** rather than one global
|
|||||||
`(account, origin)` are a fast **materialized** cache, updated **in the same transaction** as
|
`(account, origin)` are a fast **materialized** cache, updated **in the same transaction** as
|
||||||
the ledger write, and recomputable from the ledger for reconciliation.
|
the ledger write, and recomputable from the ledger for reconciliation.
|
||||||
|
|
||||||
|
**In-process read cache.** On top of the materialized tables, the payments package keeps an
|
||||||
|
in-process, account-keyed, write-through cache of each account's segments and benefits, so the
|
||||||
|
hot read paths — the ad-eligibility check, hint availability, the wallet view, the spend gate
|
||||||
|
— issue **no** query to the `payments` schema on the steady-state path. It is invalidated on
|
||||||
|
every payments mutation (spend / grant / fund / refund / merge) and re-read from the
|
||||||
|
materialized tables on a miss (the same write-through pattern the account-suspension gate
|
||||||
|
uses). Single-instance, matching the deployment; a multi-instance backend would need a shared
|
||||||
|
cache. Identity-presence (which segments are awake, §6) is supplied by the caller, not cached
|
||||||
|
here, so unlink/re-link takes effect immediately.
|
||||||
|
|
||||||
**Admin rewards.** An admin grants **concrete values only** (no-ads / hints) — **never
|
**Admin rewards.** An admin grants **concrete values only** (no-ads / hints) — **never
|
||||||
chips** (a gifted currency balance = a store cash-desk bypass). The admin **picks the
|
chips** (a gifted currency balance = a store cash-desk bypass). The admin **picks the
|
||||||
origin** at grant time (compliance is on them: `origin=vk` point-wise/low-volume = low risk,
|
origin** at grant time (compliance is on them: `origin=vk` point-wise/low-volume = low risk,
|
||||||
|
|||||||
@@ -0,0 +1,293 @@
|
|||||||
|
# Монетизация scrabble-game — проектирование и внедрение
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Игра в проде (`erudit-game.ru`), мультиплатформенная (VK / Telegram Mini App /
|
||||||
|
web+PWA / native Android+iOS через Capacitor). Владелец (самозанятый, НПД) хочет
|
||||||
|
ввести монетизацию: игровая валюта «Фишка», раздельные кошельки по платформам,
|
||||||
|
покупка бенефитов (без рекламы, подсказки, будущий турнирный взнос), rewarded-реклама
|
||||||
|
как канал пополнения, строгий транзакционный лог и админ-отчёты.
|
||||||
|
|
||||||
|
Отправная точка — `monetization-prerequisites.md` (пожелания владельца). Цель этого
|
||||||
|
процесса: (1) через интервью выстроить чёткую модель, (2) оформить и поддерживать
|
||||||
|
`PAYMENTS.md` (механики + договорённости), (3) составить `PLAN.md` (поэтапное
|
||||||
|
внедрение от основ к интеграциям).
|
||||||
|
|
||||||
|
### Что уже есть в коде (переиспользуем)
|
||||||
|
|
||||||
|
- `accounts.hint_balance int` (`CHECK >= 0`) + атомарный `SpendHint` / `GrantHints`
|
||||||
|
(`backend/internal/account/account.go:551-595`) — существующий «кошелёк подсказок»,
|
||||||
|
но пополняется только админом, покупки нет.
|
||||||
|
- `accounts.paid_account bool` — пожизненный флаг «без рекламы», уже читается в
|
||||||
|
`ads.Eligible(...)` (`backend/internal/ads/ads.go:107`); «no purchase flow yet».
|
||||||
|
- Реклама сейчас = внутренний server-driven **текст-баннер** (`ads` домен + UI
|
||||||
|
`AdBanner.svelte`), гасится `paid_account` / `hint_balance>0` / роль `no_banner`.
|
||||||
|
Rewarded-видео нет нигде.
|
||||||
|
- Подсказки — фича готова end-to-end (кнопка, 30-мин gate, vs_ai безлимит).
|
||||||
|
- Settings — таб-хаб (`ui/src/screens/SettingsHub.svelte`), вставка «Кошелёк» между
|
||||||
|
«Друзья» и «Инфо» чистая.
|
||||||
|
- Админка `/_gm` — per-user карточка уже показывает `PaidAccount`+`HintBalance`;
|
||||||
|
прецедент денежного действия — `POST /_gm/users/:id/grant-hints`.
|
||||||
|
- Один аккаунт держит VK+TG+email identity **разом** (kind∈telegram/vk/email/robot);
|
||||||
|
мерж сейчас **складывает** `hint_balance` и OR-ит `paid_account`.
|
||||||
|
- Прецедент изолированного сервиса: connector (gRPC), renderer (HTTP-sidecar),
|
||||||
|
platform/telegram. Прецедент public HMAC-подписанного роута (экспорт партии) —
|
||||||
|
образец для приёмника вебхуков.
|
||||||
|
|
||||||
|
### Greenfield
|
||||||
|
|
||||||
|
Валюта «Фишка», реальные рельсы (Stars / Голоса / Robokassa), rewarded-видео,
|
||||||
|
раздельные кошельки, транзакционный леджер, PITR/репликация, серверное знание
|
||||||
|
платформы.
|
||||||
|
|
||||||
|
## Зафиксированные решения (Decisions Log)
|
||||||
|
|
||||||
|
- **D1. Модель валюты — двухуровневая.** Деньги (Голоса/Stars/руб) и rewarded-реклама
|
||||||
|
пополняют баланс «Фишек»; за Фишки покупаются ценности (без рекламы, подсказки,
|
||||||
|
турнир). Витрина ценностей — в Фишках.
|
||||||
|
- **D2. Фишка единая (1 = 1 везде).** Разница по методам оплаты сидит **в курсе
|
||||||
|
покупки Фишек** (пакет стоит X Голосов / Y Stars / Z руб, курс учитывает комиссии
|
||||||
|
сторов). Цена ценностей — фиксирована в Фишках, одинакова для всех методов.
|
||||||
|
- **D3. Изоляция — схема `payments` в общем инстансе Postgres** + доменная граница
|
||||||
|
(свой store/service/интерфейс) + отдельный DB-роль (права только на `payments`).
|
||||||
|
Атомарность «Фишки↔бенефит» с `backend.accounts` сохраняется (cross-schema tx в
|
||||||
|
одном инстансе). Отдельный процесс/БД отвергнуты: ломают атомарность выдачи бенефита
|
||||||
|
(бенефиты живут на `accounts`), цена распределённых транзакций не окупается. Вынос в
|
||||||
|
отдельный сервис оставлен как возможность на потом (граница уже чистая).
|
||||||
|
- **D4. Сохранность — PITR** (непрерывный WAL-архив, pgBackRest/WAL-G на 2-й хост или
|
||||||
|
объектное хранилище). Тёплая реплика — опция на потом. Durability решается этим, а не
|
||||||
|
топологией БД.
|
||||||
|
- **D5. Сегмент кошелька — по source (vk / telegram / direct) на аккаунте.** Баланс =
|
||||||
|
(account_id, source), ровно 3 сегмента. Не per-identity.
|
||||||
|
- **D6. Комплаенс-гейт — логический, аккаунт единый.** email/direct физически привязан
|
||||||
|
(мерж, единый профиль/друзья/статистика), но в VK/TG-контексте сервер активирует
|
||||||
|
только одноимённый сегмент; чужое (в первую очередь direct) внутри VK/TG невидимо и
|
||||||
|
не тратится. Гейт держится на **доверенном сигнале платформы** (проставляет гейтвей
|
||||||
|
из подписанного контекста, не тело запроса — клиенту не верим).
|
||||||
|
- **D7. Три операции разведены:** (1) пополнение Фишек по контексту; (2) трата Фишек =
|
||||||
|
покупка бенефита, по контексту с гейтом (в VK только vk; в вебе direct+vk+tg по
|
||||||
|
приоритету direct→vk→tg); (3) применение бенефита во времени.
|
||||||
|
- **D8. origin бенефита = контекст ПОКУПКИ** (не «чем оплачено»). Правило послабления:
|
||||||
|
origin∈{vk,tg} → действует **везде** (в сторе и наружу в web/native);
|
||||||
|
origin=direct → **только** web/native (внутрь VK/TG нельзя = бан). Срок «без рекламы»
|
||||||
|
хранится **per-origin** (`paid_until` на origin, покупки одного origin складываются/
|
||||||
|
сдвигают дату); «реклама выключена в контексте P» = есть применимый в P origin с
|
||||||
|
`paid_until > now` (в вебе берём максимум direct/vk/tg, в VK — только vk, в TG — tg).
|
||||||
|
- **D9. «Без рекламы» гасит** верхний баннер + fullscreen-ролик после хода. Добровольный
|
||||||
|
**rewarded** (за Фишки) не трогаем.
|
||||||
|
- **D10. UX-требование:** при трате tg/vk-Фишек **в вебе** — предупредить юзера ДО
|
||||||
|
покупки, что купленная механика будет доступна только здесь (web/native), т.к.
|
||||||
|
ограничения VK/TG.
|
||||||
|
- **D11. Три сущности разведены:** Фишки (валюта, сегмент по **source** = где
|
||||||
|
пополнено), Подсказки (расходник, сегмент по **origin** = где куплено), «Без рекламы»
|
||||||
|
(срок, сегмент по **origin**). source и origin — одна ось значений {vk,tg,direct},
|
||||||
|
но разная семантика; в вебе source и origin расходятся (vk-Фишки → direct-покупка).
|
||||||
|
- **D12. Подсказки — по origin с обратным послаблением** (vk/tg→везде, direct→только
|
||||||
|
web/native), как «без рекламы». Списание в онлайн-игре = из origin, применимого в
|
||||||
|
контексте; переписать `SpendHint` (`game/service.go:1147`) на контекст-аварное
|
||||||
|
списание. vs_ai подсказки остаются бесплатными/безлимитными (не в счёт).
|
||||||
|
- **D13. `accounts.hint_balance` выводим** expand-contract (сначала игнор, потом DROP);
|
||||||
|
legacy-баланс **обнуляем** (в проде даров не было).
|
||||||
|
- **D14. Unlink vk/tg — разрешён, сегмент усыпляется.** Сегмент доступен ⟺ на аккаунте
|
||||||
|
есть identity этого source (direct ⟺ есть устойчивый identity/email). Отвязка не
|
||||||
|
сжигает баланс/бенефит — усыпляет; re-link будит. Перед отвязкой — предупреждение
|
||||||
|
«N Фишек станут недоступны до повторной привязки». Последнюю identity отвязать нельзя
|
||||||
|
(существующий `ErrLastIdentity`).
|
||||||
|
- **D15. Мерж — слияние по origin:** одноимённые сегменты складываются (Фишки sum,
|
||||||
|
сроки бенефита продлеваются per-origin), разные сосуществуют. Прямое расширение
|
||||||
|
текущего `hint_balance +=` / `paid_account OR=`; origin сохраняется, ничего не
|
||||||
|
протекает между платформами.
|
||||||
|
- **D16. Админ-награждение:** админ начисляет **только конкретные ценности** (без
|
||||||
|
рекламы / подсказки), **никогда не Фишки** (подаренный баланс валюты = обход кассы
|
||||||
|
стора). Админ **выбирает origin** при выдаче (ответственность за комплаенс на нём:
|
||||||
|
origin=vk точечно/малый объём = низкий риск, origin=direct = безопасно). Грант =
|
||||||
|
транзакция типа `admin_grant` в едином леджере, цена 0 Фишек — полный аудит наград.
|
||||||
|
- **D17. Доверенная платформа = свойство сессии,** переподтверждается свежей подписью
|
||||||
|
(VK sign / TG `initData`) при **каждом холодном старте** (не однократно при входе —
|
||||||
|
обёртка всё равно шлёт подпись каждое открытие). `direct` фиксируется фактом создания
|
||||||
|
веб/native-сессии (внешней подписи нет и не нужно — доступ к vk/tg-сегментам в direct
|
||||||
|
всё равно требует реальной привязки, D14). Backend получает `platform` при резолве
|
||||||
|
сессии. Платформа несёт **kind** (vk/tg/direct) **+ подтип** (ios/android/web) —
|
||||||
|
подтип обязателен (VK iOS заморожен). TG `initData`-валидатор уже есть
|
||||||
|
(`platform/telegram/internal/initdata`).
|
||||||
|
- **D18. Fail-closed:** недоверенная/неподтверждённая платформа (VK/TG-сессия без
|
||||||
|
валидной подписи на старте; старая сессия без записанной платформы) → запрет
|
||||||
|
трат/покупок/применения чужого origin, только просмотр.
|
||||||
|
- **D19. Дистрибуция native Android:** RuStore (Robokassa разрешён, чистый direct) +
|
||||||
|
Google Play (**direct-покупки скрыты** — на «Кошельке» заглушка «установите версию из
|
||||||
|
RuStore для покупок»; rewarded-реклама и трата уже накопленных Фишек работают). Перед
|
||||||
|
GP-релизом свериться с актуальными правилами Google по внутренней валюте.
|
||||||
|
- **D20. Приём оплаты — только серверный колбэк провайдера.** Фишки начисляются лишь по
|
||||||
|
проверенному (подпись/HMAC) серверному уведомлению: Robokassa webhook / TG
|
||||||
|
`successful_payment` / VK callback. Клиентское «я оплатил» игнорируется.
|
||||||
|
- **D21. Единый payments-домен — единственный писатель леджера.** Публичные вебхуки
|
||||||
|
(Robokassa/VK) терминируются на edge (Caddy/gateway) и проксируются в payments;
|
||||||
|
TG `successful_payment` → бот → payments. Один источник начисления/идемпотентности.
|
||||||
|
- **D22. Order-flow с предзаказом.** Сервер создаёт `order(pending)` с account/
|
||||||
|
платформой/пакетом/ожидаемой суммой/origin; `order_id` прокидывается провайдеру
|
||||||
|
(Robokassa `InvId` / TG `invoice_payload` / VK `item` — точную форму VK уточнить при
|
||||||
|
интеграции). Колбэк матчится по `order_id` (не по сумме → коллизия сумм невозможна),
|
||||||
|
сверяет сумму, начисляет, помечает `paid`. **Идемпотентность** — дедуп по (провайдер,
|
||||||
|
`provider_payment_id`).
|
||||||
|
- **D23. Pending невидим юзеру;** авто-expiry по таймауту (~30 мин — гигиена БД). Но
|
||||||
|
**валидный колбэк исполняется ВСЕГДА**, даже на истёкшем order (`expired` ≠ отмена —
|
||||||
|
деньги реальны, обязаны выдать). Юзер видит только успешные покупки.
|
||||||
|
- **D24. Экран «Кошелёк» — минимальный:** балансы Фишек (доступные в контексте) +
|
||||||
|
активные бенефиты (без рекламы до даты, счётчик подсказок). **Без ленты истории**
|
||||||
|
(шумит, отвлекает от игры). Полная история — только в админке.
|
||||||
|
- **D25. TG-бот outbox — SQLite на диске бота.** Store-and-forward: получил
|
||||||
|
`successful_payment` → сохранил в SQLite → подтвердил апдейт Telegram → форвардит в
|
||||||
|
payments (идемпотентно, дедуп по `telegram_payment_charge_id`) → ack → `forwarded`.
|
||||||
|
Ретраи с backoff, дореталивание при рестарте. At-least-once доставка + идемпотентный
|
||||||
|
приём = начисление ровно один раз.
|
||||||
|
- **D26. Событийный слой `payment_events`** (succeeded/failed/refunded) + диспетчер по
|
||||||
|
каналам: live gRPC-стрим (если юзер в аппе), иначе `botlink`/email-relay
|
||||||
|
(существующие). «Оплата не прошла» = **активный отказ провайдера** (не брошенный
|
||||||
|
pending) — доводится до юзера. «Оплата прошла» — хук (письмо/сообщение в бота).
|
||||||
|
- **D27. Возвраты.** ToS «невозвратно» — юзеру возврат не предлагаем. **Админ может
|
||||||
|
сделать ручной возврат** (исключение: юзер требует вскоре после оплаты / закрывает
|
||||||
|
аккаунт — связать с `accountdelete`, где уже правило «сообщения не трогаем»).
|
||||||
|
**Внешние возвраты** (чарджбек / решение стора / TG / VK) — система принимает событие
|
||||||
|
`refunded`, **по возможности** отзывает бенефит (в минус НЕ уходим; если Фишки
|
||||||
|
потрачены — фиксируем убыток + флаг защиты от злоупотреблений), пишет в журнал.
|
||||||
|
Журнал операций **проектируем экспортопригодным** (будущая налоговая отчётность +
|
||||||
|
авто-сверка с Robokassa) — реализацию сверки пока не делаем, схему закладываем
|
||||||
|
совместимой.
|
||||||
|
- **D28. Стартовый охват видео-рекламы — только VK** (рублёвый доход, ОРД автоматом,
|
||||||
|
API готов). web/native/TG — существующий текст-баннер. Рекламный провайдер
|
||||||
|
закладываем **абстракцией** (будущая крутилка для других платформ встроится без
|
||||||
|
переделки). Крипто-провайдеры (AdsGram/AdMob) отвергнуты — нет легального рублёвого
|
||||||
|
дохода самозанятому (санкции + НПД не учитывает крипту).
|
||||||
|
- **D29. Rewarded (добровольный ролик за Фишки)** начисляет Фишки через payments по
|
||||||
|
**серверному verify-колбэку** рекламной сети (клиенту не верим, как платёж). Не
|
||||||
|
гасится «без рекламы». Сколько Фишек за просмотр — в блоке экономики.
|
||||||
|
- **D30. Частота навязанного interstitial** (конфигурируемые серверные значения):
|
||||||
|
глобальный кулдаун **на юзера сквозь все партии**, дефолт **5 мин**; **vs_ai — 30 мин**
|
||||||
|
(соосно кулдауну подсказок). Применение **подсказки** триггерит ролик после хода
|
||||||
|
**независимо** от основного кулдауна, со своим кулдауном **1 мин**. Оффлайн — только
|
||||||
|
баннер. Уважать собственные лимиты частоты VK.
|
||||||
|
- **D31. `paid_account` тоже deprecated** → удаление из схемы (как `hint_balance`), в
|
||||||
|
пользу per-origin бенефитов «без рекламы». Существующий `ads.Eligible`
|
||||||
|
(`backend/internal/ads/ads.go:107`) расширяется: баннер гасится по origin-бенефиту,
|
||||||
|
**применимому в текущем контексте**, а не по одному глобальному флагу. Legacy
|
||||||
|
`paid_account`/`hint_balance` в проде никем не выставлены (потока покупки не было) →
|
||||||
|
обнуляем/игнорируем, после релиза платежей дропаем.
|
||||||
|
- **D32. Каталог — конфигурируемый (БД + админка).** Базовые ценности (атомы
|
||||||
|
начисления): Фишки, подсказки, дни-без-рекламы, участие-в-турнире. **Продукт = набор
|
||||||
|
атомов + цена** (по одной ценности или комбо). «Пакет Фишек» — цена **per-метод**
|
||||||
|
(мультивалютная: Голоса/Stars/руб — один продукт, D2). «Ценность за Фишки» — цена в
|
||||||
|
Фишках (единая). Курсы покупки Фишек и Фишки за rewarded — тоже в каталоге.
|
||||||
|
- **D33. Стекинг «без рекламы»:** `paid_until[origin] += срок` от `max(now, текущий
|
||||||
|
конец)` (остаток не теряется, «плюсуются» как в документе). «Навсегда» — отдельный
|
||||||
|
вечный флаг (перекрывает сроки). Бонусы «(+50)» — маркетинговая пометка владельца;
|
||||||
|
юзеру показываем финальную цифру, в модели просто количество.
|
||||||
|
- **D34. Деактивация, не удаление.** Продукты soft-delete (деактивация). Покупка хранит
|
||||||
|
**снимок проданного** (состав атомов + цена на момент) → архив. Для истории, чеков,
|
||||||
|
налоговой — покупка не зависит от дальнейших правок/деактивации каталога.
|
||||||
|
- **D35. Антифрод rewarded — только серверный verify провайдера** на старте (без своего
|
||||||
|
дневного потолка). Провайдер-абстракция позволит добавить лимиты позже.
|
||||||
|
- **D36. Email/direct.** У гостей раздел «Кошелёк» **скрыт полностью**; баланс и
|
||||||
|
покупки — **только у durable-аккаунтов**. В direct email обязателен **перед первой
|
||||||
|
покупкой** (якорь восстановления доступа; в VK/TG якорь — сама vk/tg-привязка). Флоу
|
||||||
|
email уже есть (запрос кода → подтверждение → `ClearGuest` → durable).
|
||||||
|
- **D37. Reaper — гостей чистит свободно:** у гостя баланса нет by design (Кошелёк
|
||||||
|
скрыт, покупок нет, direct-rewarded нет). Спец-защита не нужна.
|
||||||
|
- **D38. Гостевые ограничения — ОТДЕЛЬНЫЙ этап монетизации** (воронка к регистрации).
|
||||||
|
Набор: макс **1 активная игра со случайным + 1 vs_ai**; **серверный** guest-гейт на
|
||||||
|
friend-request / redeem-code / invitation-create. Находка: сейчас гейт **только в UI**
|
||||||
|
— `social/friends.go:50` (`SendFriendRequest`), `robotfriends.go:41` (`RequestInGame`),
|
||||||
|
`friendcodes.go:67` (`RedeemFriendCode`), `lobby/invitations.go:208`
|
||||||
|
(`CreateInvitation`) **не проверяют `is_guest`**. Это изменение поведения игры → свой
|
||||||
|
этап со своими тестами.
|
||||||
|
- **D39. Хранение — неизменяемый журнал + материализованный баланс.** Журнал операций
|
||||||
|
**append-only** (только INSERT, никогда UPDATE/DELETE — полный аудит, №3). Баланс
|
||||||
|
сегмента `(account, source)` и бенефиты `(account, origin)` — быстрый материализованный
|
||||||
|
кэш, обновляется **в той же транзакции**, что и запись журнала; пересчитывается из
|
||||||
|
журнала для сверки.
|
||||||
|
- **D40. Финансовый отчёт per-user в `/_gm`** — балансы сегментов, платежи, траты,
|
||||||
|
гранты, возвраты, полная история — расширение существующей карточки
|
||||||
|
(`UserDetailView`, `handlers_admin_console.go:343`). Плюс экспорт журнала (D27).
|
||||||
|
- **D41. Налоги/чеки — авто через провайдера.** **Robokassa** (direct) — авточек НПД
|
||||||
|
(режим самозанятого). **VK** — сам процессит Голоса через налоговую (владельцу делать
|
||||||
|
нечего). **TG Stars** — налоговой стороны нет (для РФ-самозанятого невыводимы легально
|
||||||
|
= не доход по НПД; принимаем, чек не формируем). ОРД по VK-рекламе — на стороне VK.
|
||||||
|
*(Не юридическая консультация — точную схему НПД владелец сверяет с налоговой стороной.)*
|
||||||
|
|
||||||
|
## Заметки к оформлению документов
|
||||||
|
|
||||||
|
- **Язык документов (решено).** `PAYMENTS.md` — **на английском**, терминами как в коде
|
||||||
|
и общепринятыми (`ledger`, `refund`, `idempotency`, `order`, …). Рядом
|
||||||
|
`PAYMENTS_ru.md` — перевод на простой русский владельца. Паттерн `FUNCTIONAL.md` +
|
||||||
|
`FUNCTIONAL_ru.md`, уже принятый в репозитории; мирроринг правок — в том же PR.
|
||||||
|
- **Язык диалога** с владельцем — по-русски, без калек-англицизмов
|
||||||
|
(«леджер»→«журнал операций»). Сохранить как feedback-память после выхода из plan mode.
|
||||||
|
- **Формат интервью (владелец флагнул дважды).** ВСЕ вопросы владельцу — только через
|
||||||
|
интерактивное интервью (AskUserQuestion). НИКОГДА не выносить вопросы в текст ответа,
|
||||||
|
даже «мелкие» или «да/нет»: смешение текстовых и интерактивных вопросов раздражает и
|
||||||
|
ведёт к пропускам. Текст — только для фиксации решённого и пояснений. Усилить
|
||||||
|
feedback-память `prefer-interview-mode` после plan mode.
|
||||||
|
|
||||||
|
## Все развилки закрыты (D1-D41)
|
||||||
|
|
||||||
|
Интервью завершено. Дальше — оформление документов и реализация по релизам.
|
||||||
|
|
||||||
|
## План внедрения (черновик PLAN.md — «слоями»)
|
||||||
|
|
||||||
|
Владелец выбрал слоёную стратегию: сначала вся механика без реальных денег (обкатка
|
||||||
|
через `admin_grant`), затем монетизация (все рельсы + реклама вместе).
|
||||||
|
|
||||||
|
### Релиз 1 — механика без денег (обкатка через `admin_grant`)
|
||||||
|
|
||||||
|
- **E0. Фундамент данных `payments`.** Схема + DB-роль + jetgen-таргет + миграции.
|
||||||
|
Таблицы: журнал операций (append-only, D39), балансы сегментов `(account, source)`,
|
||||||
|
бенефиты `(account, origin)` (paid_until/forever + подсказки count), каталог продуктов
|
||||||
|
(D32, soft-delete D34), заказы `orders` (D22), `payment_events` (D26). Доменный пакет с
|
||||||
|
жёсткой границей (D3). Старт deprecate `hint_balance`/`paid_account` (expand).
|
||||||
|
- **E1. Доверенный сигнал платформы.** Platform в сессии (kind+подтип), переподтверждение
|
||||||
|
на холодном старте (VK sign / TG `initData`), fail-closed (D17-D18); gateway прокидывает
|
||||||
|
`platform` в backend.
|
||||||
|
- **E2. Ядро валюты + бенефитов.** Баланс Фишек; трата Фишек → бенефит атомарно (D7);
|
||||||
|
гейт по контексту (D6-D8); применение per-origin (без рекламы стекинг D33, подсказки
|
||||||
|
D12); переписать `SpendHint` на контекст-аварное списание; миграция/обнуление legacy
|
||||||
|
(D13, D31). Обкатка начислений через `admin_grant` (D16).
|
||||||
|
- **E3. Кошелёк UI.** Раздел в `SettingsHub` (между Друзья/Инфо), балансы + бенефиты
|
||||||
|
(минимальный, D24), витрина каталога, скрыт у гостей (D36), GP-заглушка (D19),
|
||||||
|
предупреждение при трате vk/tg в вебе (D10).
|
||||||
|
|
||||||
|
### Релиз 2 — монетизация (рельсы + реклама вместе)
|
||||||
|
|
||||||
|
- **E4. Durability (PITR).** WAL-архив (pgBackRest/WAL-G, D4) — ДО первого реального
|
||||||
|
приёма денег.
|
||||||
|
- **E5. Приём платежей.** Order-flow (D22); единый payments-домен принимает колбэки
|
||||||
|
(D21); Robokassa + VK + TG (бот-outbox на SQLite, D25); идемпотентность; `payment_events`
|
||||||
|
+ диспетчер уведомлений (D26); чеки НПД (D41); внешние + ручные возвраты (D27).
|
||||||
|
- **E6. Реклама.** VK interstitial (частота-конфиг D30) + VK rewarded (verify→Фишки D29,
|
||||||
|
D35); `ads.Eligible` расширение per-origin (D31). Провайдер-абстракция (D28).
|
||||||
|
- **E7. Админка / отчёты.** Финансовый отчёт per-user в `/_gm` (D40); UI ручного
|
||||||
|
возврата; экспорт журнала (D27).
|
||||||
|
|
||||||
|
### Отдельный этап (изменение поведения игры)
|
||||||
|
|
||||||
|
- **E8. Гостевые ограничения.** Серверный guest-гейт друзей/приглашений + лимиты игр
|
||||||
|
(1 случайная + 1 vs_ai, D38). Свои тесты; можно вести параллельно.
|
||||||
|
|
||||||
|
### Будущее
|
||||||
|
|
||||||
|
- **E9. Турнирный взнос.** Тип-ценность заложен в E0; механика позже.
|
||||||
|
|
||||||
|
## Финальные артефакты
|
||||||
|
|
||||||
|
1. `PAYMENTS.md` (англ) + `PAYMENTS_ru.md` (рус) — **первыми**, из Decisions Log D1-D41;
|
||||||
|
поддерживать далее (мирроринг в том же PR, как FUNCTIONAL).
|
||||||
|
2. `PLAN.md` — из раздела «План внедрения» выше, с критериями готовности на этап.
|
||||||
|
3. Реализация по релизам, начиная с E0.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Каждый этап — своим слоем (`docs/TESTING.md`): **unit** (гейт по контексту, стекинг
|
||||||
|
сроков, курсы, идемпотентность-ключи); **integration** (Postgres-backed атомарные
|
||||||
|
транзакции «Фишки↔бенефит», идемпотентность колбэков, бот-outbox доставка); **UI**
|
||||||
|
(Кошелёк, предупреждения, гость-скрыт, GP-заглушка); контурный прогон на `development`
|
||||||
|
перед промоушеном. Локальная полная проверка перед пушем (интеграция + UI + codegen).
|
||||||
|
Прод: expand-contract миграции (rollback-safe), PITR армирован до первого приёма денег.
|
||||||
|
Комплаенс-гейт — обязательная регрессия (direct-бенефит не активируется в VK/TG).
|
||||||
@@ -275,6 +275,16 @@ INSERT** (никогда UPDATE/DELETE — полный аудит). Балан
|
|||||||
бенефиты `(account, origin)` — быстрый **материализованный** кэш, обновляется **в той же
|
бенефиты `(account, origin)` — быстрый **материализованный** кэш, обновляется **в той же
|
||||||
транзакции**, что и запись журнала, и пересчитывается из журнала для сверки.
|
транзакции**, что и запись журнала, и пересчитывается из журнала для сверки.
|
||||||
|
|
||||||
|
**In-process кэш чтения.** Поверх материализованных таблиц пакет payments держит
|
||||||
|
in-process кэш сегментов и бенефитов по ключу-аккаунту (write-through), чтобы горячие пути
|
||||||
|
чтения — проверка показа рекламы, доступность подсказок, экран кошелька, гейт траты — на
|
||||||
|
устоявшемся пути **не** делали ни одного запроса к схеме `payments`. Кэш инвалидируется на
|
||||||
|
каждой изменяющей операции payments (трата / грант / пополнение / возврат / мерж) и
|
||||||
|
перечитывается из материализованных таблиц при промахе (тот же write-through-паттерн, что и у
|
||||||
|
гейта блокировок аккаунта). Один инстанс — под текущий деплой; многоинстансный backend
|
||||||
|
потребовал бы общего кэша. Присутствие identity (какие сегменты «не спят», §6) передаёт
|
||||||
|
вызывающий, здесь не кэшируется, поэтому отвязка/повторная привязка действует сразу.
|
||||||
|
|
||||||
**Награждение админом.** Админ начисляет **только конкретные ценности** (без рекламы /
|
**Награждение админом.** Админ начисляет **только конкретные ценности** (без рекламы /
|
||||||
подсказки) — **никогда не Фишки** (подаренный баланс валюты = обход кассы стора). Админ
|
подсказки) — **никогда не Фишки** (подаренный баланс валюты = обход кассы стора). Админ
|
||||||
**выбирает origin** при выдаче (ответственность за комплаенс на нём: `origin=vk`
|
**выбирает origin** при выдаче (ответственность за комплаенс на нём: `origin=vk`
|
||||||
|
|||||||
@@ -360,6 +360,72 @@ func (c *Client) Profile(ctx context.Context, userID string) (ProfileResp, error
|
|||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WalletSegmentResp is one chip balance in the wallet: the funding source, the chip count, and
|
||||||
|
// whether it is spendable in the caller's current context.
|
||||||
|
type WalletSegmentResp struct {
|
||||||
|
Source string `json:"source"`
|
||||||
|
Chips int `json:"chips"`
|
||||||
|
Spendable bool `json:"spendable"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WalletResp is the caller's wallet: the context-visible chip segments and the context-applicable
|
||||||
|
// benefits (no-ads term end as unix millis / forever flag, and the available hints).
|
||||||
|
type WalletResp struct {
|
||||||
|
Segments []WalletSegmentResp `json:"segments"`
|
||||||
|
AdsForever bool `json:"ads_forever"`
|
||||||
|
AdsPaidUntil int64 `json:"ads_paid_until_ms"`
|
||||||
|
Hints int `json:"hints"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// walletBuyBody is the chip-spend request body.
|
||||||
|
type walletBuyBody struct {
|
||||||
|
ProductID string `json:"product_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wallet fetches the caller's wallet in their current execution context.
|
||||||
|
func (c *Client) Wallet(ctx context.Context, userID string) (WalletResp, error) {
|
||||||
|
var out WalletResp
|
||||||
|
err := c.do(ctx, http.MethodGet, "/api/v1/user/wallet", userID, "", nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// WalletBuy spends chips on a chip-priced value and returns the updated wallet.
|
||||||
|
func (c *Client) WalletBuy(ctx context.Context, userID, productID string) (WalletResp, error) {
|
||||||
|
var out WalletResp
|
||||||
|
err := c.do(ctx, http.MethodPost, "/api/v1/user/wallet/buy", userID, "", walletBuyBody{ProductID: productID}, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CatalogAtomResp is one atom line of a storefront product: the value type it grants and quantity.
|
||||||
|
type CatalogAtomResp struct {
|
||||||
|
AtomType string `json:"atom_type"`
|
||||||
|
Quantity int `json:"quantity"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CatalogProductResp is one storefront product for the caller's context: a chip-priced value
|
||||||
|
// (chips set) or a chip pack priced in the context method (money_amount + money_currency).
|
||||||
|
type CatalogProductResp 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 []CatalogAtomResp `json:"atoms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CatalogResp is the storefront: the products visible and purchasable in the caller's context.
|
||||||
|
type CatalogResp struct {
|
||||||
|
Products []CatalogProductResp `json:"products"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Catalog fetches the storefront in the caller's current execution context.
|
||||||
|
func (c *Client) Catalog(ctx context.Context, userID string) (CatalogResp, error) {
|
||||||
|
var out CatalogResp
|
||||||
|
err := c.do(ctx, http.MethodGet, "/api/v1/user/wallet/catalog", userID, "", nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
// BlockStatusResp is the caller's current manual-block state. Until is an RFC3339 UTC instant for
|
// BlockStatusResp is the caller's current manual-block state. Until is an RFC3339 UTC instant for
|
||||||
// a temporary block, empty for a permanent one or when not blocked; Reason is resolved to the
|
// a temporary block, empty for a permanent one or when not blocked; Reason is resolved to the
|
||||||
// account's language, empty when none was cited.
|
// account's language, empty when none was cited.
|
||||||
|
|||||||
@@ -79,6 +79,80 @@ func encodeConfirmLinkResult(r backendclient.ConfirmLinkResp) []byte {
|
|||||||
|
|
||||||
// encodeProfile builds a Profile payload, including the advertising-banner block
|
// encodeProfile builds a Profile payload, including the advertising-banner block
|
||||||
// when the backend marked the viewer eligible.
|
// when the backend marked the viewer eligible.
|
||||||
|
// encodeWallet builds the Wallet payload: the visible chip segments and the context-applicable
|
||||||
|
// benefits. Each WalletSegment table (and its source string) is built before the segments vector
|
||||||
|
// is opened, per FlatBuffers' rule against a nested table while another is under construction.
|
||||||
|
func encodeWallet(w backendclient.WalletResp) []byte {
|
||||||
|
b := flatbuffers.NewBuilder(128)
|
||||||
|
segs := make([]flatbuffers.UOffsetT, len(w.Segments))
|
||||||
|
for i, seg := range w.Segments {
|
||||||
|
src := b.CreateString(seg.Source)
|
||||||
|
fb.WalletSegmentStart(b)
|
||||||
|
fb.WalletSegmentAddSource(b, src)
|
||||||
|
fb.WalletSegmentAddChips(b, int32(seg.Chips))
|
||||||
|
fb.WalletSegmentAddSpendable(b, seg.Spendable)
|
||||||
|
segs[i] = fb.WalletSegmentEnd(b)
|
||||||
|
}
|
||||||
|
fb.WalletStartSegmentsVector(b, len(segs))
|
||||||
|
for i := len(segs) - 1; i >= 0; i-- {
|
||||||
|
b.PrependUOffsetT(segs[i])
|
||||||
|
}
|
||||||
|
segVec := b.EndVector(len(segs))
|
||||||
|
fb.WalletStart(b)
|
||||||
|
fb.WalletAddSegments(b, segVec)
|
||||||
|
fb.WalletAddAdsForever(b, w.AdsForever)
|
||||||
|
fb.WalletAddAdsPaidUntilMs(b, w.AdsPaidUntil)
|
||||||
|
fb.WalletAddHints(b, int32(w.Hints))
|
||||||
|
b.Finish(fb.WalletEnd(b))
|
||||||
|
return b.FinishedBytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodeCatalog builds a Catalog payload: the storefront products for the caller's context, each
|
||||||
|
// with its atom composition (built bottom-up — every product's atoms vector is finished before
|
||||||
|
// its product table, and every product before the products vector).
|
||||||
|
func encodeCatalog(cat backendclient.CatalogResp) []byte {
|
||||||
|
b := flatbuffers.NewBuilder(256)
|
||||||
|
prods := make([]flatbuffers.UOffsetT, len(cat.Products))
|
||||||
|
for i, p := range cat.Products {
|
||||||
|
atoms := make([]flatbuffers.UOffsetT, len(p.Atoms))
|
||||||
|
for j, a := range p.Atoms {
|
||||||
|
at := b.CreateString(a.AtomType)
|
||||||
|
fb.CatalogAtomStart(b)
|
||||||
|
fb.CatalogAtomAddAtomType(b, at)
|
||||||
|
fb.CatalogAtomAddQuantity(b, int32(a.Quantity))
|
||||||
|
atoms[j] = fb.CatalogAtomEnd(b)
|
||||||
|
}
|
||||||
|
fb.CatalogProductStartAtomsVector(b, len(atoms))
|
||||||
|
for j := len(atoms) - 1; j >= 0; j-- {
|
||||||
|
b.PrependUOffsetT(atoms[j])
|
||||||
|
}
|
||||||
|
atomsVec := b.EndVector(len(atoms))
|
||||||
|
|
||||||
|
kind := b.CreateString(p.Kind)
|
||||||
|
pid := b.CreateString(p.ProductID)
|
||||||
|
title := b.CreateString(p.Title)
|
||||||
|
cur := b.CreateString(p.MoneyCurrency)
|
||||||
|
fb.CatalogProductStart(b)
|
||||||
|
fb.CatalogProductAddKind(b, kind)
|
||||||
|
fb.CatalogProductAddProductId(b, pid)
|
||||||
|
fb.CatalogProductAddTitle(b, title)
|
||||||
|
fb.CatalogProductAddChips(b, int32(p.Chips))
|
||||||
|
fb.CatalogProductAddMoneyAmount(b, p.MoneyAmount)
|
||||||
|
fb.CatalogProductAddMoneyCurrency(b, cur)
|
||||||
|
fb.CatalogProductAddAtoms(b, atomsVec)
|
||||||
|
prods[i] = fb.CatalogProductEnd(b)
|
||||||
|
}
|
||||||
|
fb.CatalogStartProductsVector(b, len(prods))
|
||||||
|
for i := len(prods) - 1; i >= 0; i-- {
|
||||||
|
b.PrependUOffsetT(prods[i])
|
||||||
|
}
|
||||||
|
prodVec := b.EndVector(len(prods))
|
||||||
|
fb.CatalogStart(b)
|
||||||
|
fb.CatalogAddProducts(b, prodVec)
|
||||||
|
b.Finish(fb.CatalogEnd(b))
|
||||||
|
return b.FinishedBytes()
|
||||||
|
}
|
||||||
|
|
||||||
func encodeProfile(p backendclient.ProfileResp) []byte {
|
func encodeProfile(p backendclient.ProfileResp) []byte {
|
||||||
b := flatbuffers.NewBuilder(192)
|
b := flatbuffers.NewBuilder(192)
|
||||||
uid := b.CreateString(p.UserID)
|
uid := b.CreateString(p.UserID)
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ const (
|
|||||||
MsgFeedbackSubmit = "feedback.submit"
|
MsgFeedbackSubmit = "feedback.submit"
|
||||||
MsgFeedbackGet = "feedback.get"
|
MsgFeedbackGet = "feedback.get"
|
||||||
MsgFeedbackUnread = "feedback.unread"
|
MsgFeedbackUnread = "feedback.unread"
|
||||||
|
MsgWalletGet = "wallet.get"
|
||||||
|
MsgWalletCatalog = "wallet.catalog"
|
||||||
|
MsgWalletBuy = "wallet.buy"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request is one decoded Execute call.
|
// Request is one decoded Execute call.
|
||||||
@@ -105,6 +108,9 @@ func NewRegistry(backend *backendclient.Client, tg TelegramValidator, opts ...Op
|
|||||||
r.ops[MsgAuthEmailLogin] = Op{Handler: authEmailLoginHandler(backend), Email: true}
|
r.ops[MsgAuthEmailLogin] = Op{Handler: authEmailLoginHandler(backend), Email: true}
|
||||||
r.ops[MsgAuthEmailConfirmLink] = Op{Handler: authEmailConfirmLinkHandler(backend)}
|
r.ops[MsgAuthEmailConfirmLink] = Op{Handler: authEmailConfirmLinkHandler(backend)}
|
||||||
r.ops[MsgProfileGet] = Op{Handler: profileHandler(backend), Auth: true}
|
r.ops[MsgProfileGet] = Op{Handler: profileHandler(backend), Auth: true}
|
||||||
|
r.ops[MsgWalletGet] = Op{Handler: walletHandler(backend), Auth: true}
|
||||||
|
r.ops[MsgWalletCatalog] = Op{Handler: walletCatalogHandler(backend), Auth: true}
|
||||||
|
r.ops[MsgWalletBuy] = Op{Handler: walletBuyHandler(backend), Auth: true}
|
||||||
r.ops[MsgBlockStatus] = Op{Handler: blockStatusHandler(backend), Auth: true}
|
r.ops[MsgBlockStatus] = Op{Handler: blockStatusHandler(backend), Auth: true}
|
||||||
r.ops[MsgGameSubmitPlay] = Op{Handler: submitPlayHandler(backend), Auth: true}
|
r.ops[MsgGameSubmitPlay] = Op{Handler: submitPlayHandler(backend), Auth: true}
|
||||||
r.ops[MsgGameState] = Op{Handler: gameStateHandler(backend), Auth: true}
|
r.ops[MsgGameState] = Op{Handler: gameStateHandler(backend), Auth: true}
|
||||||
@@ -294,6 +300,37 @@ func profileHandler(backend *backendclient.Client) Handler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func walletHandler(backend *backendclient.Client) Handler {
|
||||||
|
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||||
|
w, err := backend.Wallet(ctx, req.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return encodeWallet(w), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func walletCatalogHandler(backend *backendclient.Client) Handler {
|
||||||
|
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||||
|
cat, err := backend.Catalog(ctx, req.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return encodeCatalog(cat), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func walletBuyHandler(backend *backendclient.Client) Handler {
|
||||||
|
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||||
|
in := fb.GetRootAsWalletBuyRequest(req.Payload, 0)
|
||||||
|
w, err := backend.WalletBuy(ctx, req.UserID, string(in.ProductId()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return encodeWallet(w), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func blockStatusHandler(backend *backendclient.Client) Handler {
|
func blockStatusHandler(backend *backendclient.Client) Handler {
|
||||||
return func(ctx context.Context, req Request) ([]byte, error) {
|
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||||
bs, err := backend.BlockStatus(ctx, req.UserID)
|
bs, err := backend.BlockStatus(ctx, req.UserID)
|
||||||
|
|||||||
@@ -86,6 +86,52 @@ func TestGameStateRoundTripForwardsUserID(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWalletCatalogRoundTrip(t *testing.T) {
|
||||||
|
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if got := r.Header.Get("X-User-ID"); got != "u-9" {
|
||||||
|
t.Errorf("X-User-ID = %q, want u-9", got)
|
||||||
|
}
|
||||||
|
if r.URL.Path != "/api/v1/user/wallet/catalog" {
|
||||||
|
t.Errorf("unexpected path %q", r.URL.Path)
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte(`{"products":[` +
|
||||||
|
`{"kind":"value","product_id":"val-1","title":"50 hints","chips":100,"money_amount":0,"money_currency":"","atoms":[{"atom_type":"hints","quantity":50}]},` +
|
||||||
|
`{"kind":"pack","product_id":"pack-1","title":"100 chips","chips":0,"money_amount":14900,"money_currency":"RUB","atoms":[{"atom_type":"chips","quantity":100}]}` +
|
||||||
|
`]}`))
|
||||||
|
})
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
reg := transcode.NewRegistry(backend, nil)
|
||||||
|
op, ok := reg.Lookup(transcode.MsgWalletCatalog)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("wallet.catalog not registered")
|
||||||
|
}
|
||||||
|
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-9"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("handler: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cat := fb.GetRootAsCatalog(payload, 0)
|
||||||
|
if cat.ProductsLength() != 2 {
|
||||||
|
t.Fatalf("products = %d, want 2", cat.ProductsLength())
|
||||||
|
}
|
||||||
|
var value fb.CatalogProduct
|
||||||
|
cat.Products(&value, 0)
|
||||||
|
if string(value.Kind()) != "value" || string(value.ProductId()) != "val-1" || value.Chips() != 100 || value.AtomsLength() != 1 {
|
||||||
|
t.Fatalf("value decoded wrong: kind=%q id=%q chips=%d atoms=%d", value.Kind(), value.ProductId(), value.Chips(), value.AtomsLength())
|
||||||
|
}
|
||||||
|
var atom fb.CatalogAtom
|
||||||
|
value.Atoms(&atom, 0)
|
||||||
|
if string(atom.AtomType()) != "hints" || atom.Quantity() != 50 {
|
||||||
|
t.Fatalf("atom decoded wrong: type=%q qty=%d", atom.AtomType(), atom.Quantity())
|
||||||
|
}
|
||||||
|
var pack fb.CatalogProduct
|
||||||
|
cat.Products(&pack, 1)
|
||||||
|
if string(pack.Kind()) != "pack" || pack.Chips() != 0 || pack.MoneyAmount() != 14900 || string(pack.MoneyCurrency()) != "RUB" {
|
||||||
|
t.Fatalf("pack decoded wrong: kind=%q chips=%d money=%d cur=%q", pack.Kind(), pack.Chips(), pack.MoneyAmount(), pack.MoneyCurrency())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestEnqueueRoundTripEncodesMatch(t *testing.T) {
|
func TestEnqueueRoundTripEncodesMatch(t *testing.T) {
|
||||||
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
|
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
_, _ = w.Write([]byte(`{"matched":true,"game":{"id":"g-9","variant":"scrabble_en","status":"active","players":2,"to_move":0,"seats":[]}}`))
|
_, _ = w.Write([]byte(`{"matched":true,"game":{"id":"g-9","variant":"scrabble_en","status":"active","players":2,"to_move":0,"seats":[]}}`))
|
||||||
|
|||||||
@@ -848,3 +848,54 @@ table NotificationEvent {
|
|||||||
invitation:Invitation;
|
invitation:Invitation;
|
||||||
state:StateView;
|
state:StateView;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WalletSegment is one chip balance in the wallet view: the funding source
|
||||||
|
// ("vk"/"telegram"/"direct"), the chip count, and whether it is spendable in the current
|
||||||
|
// execution context (false for a frozen VK-iOS balance or an untrusted platform).
|
||||||
|
table WalletSegment {
|
||||||
|
source:string;
|
||||||
|
chips:int;
|
||||||
|
spendable:bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wallet is the user-facing wallet: the context-visible chip segments and the context-applicable
|
||||||
|
// benefits — the no-ads term end as unix milliseconds (0 = no active term) or the perpetual
|
||||||
|
// forever flag, and the available hint count.
|
||||||
|
table Wallet {
|
||||||
|
segments:[WalletSegment];
|
||||||
|
ads_forever:bool;
|
||||||
|
ads_paid_until_ms:long;
|
||||||
|
hints:int;
|
||||||
|
}
|
||||||
|
|
||||||
|
// WalletBuyRequest buys a chip-priced value with chips: the product to buy.
|
||||||
|
table WalletBuyRequest {
|
||||||
|
product_id:string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CatalogAtom is one atom line of a storefront product: the base value type it grants
|
||||||
|
// ("chips"/"hints"/"noads_days"/"tournament") and how many of it the product carries.
|
||||||
|
table CatalogAtom {
|
||||||
|
atom_type:string;
|
||||||
|
quantity:int;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CatalogProduct is one storefront product projected for the caller's context. A "value" is
|
||||||
|
// bought with chips (chips is its uniform price, money fields zero); a "pack" funds chips with
|
||||||
|
// money (money_amount is its price in the context currency's minor units under money_currency,
|
||||||
|
// chips zero). atoms lists what the product grants.
|
||||||
|
table CatalogProduct {
|
||||||
|
kind:string;
|
||||||
|
product_id:string;
|
||||||
|
title:string;
|
||||||
|
chips:int;
|
||||||
|
money_amount:long;
|
||||||
|
money_currency:string;
|
||||||
|
atoms:[CatalogAtom];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Catalog is the storefront: the products visible and purchasable in the caller's context — the
|
||||||
|
// chip-priced values and the chip packs priced in the context's payment method.
|
||||||
|
table Catalog {
|
||||||
|
products:[CatalogProduct];
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||||
|
|
||||||
|
package scrabblefb
|
||||||
|
|
||||||
|
import (
|
||||||
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Catalog struct {
|
||||||
|
_tab flatbuffers.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRootAsCatalog(buf []byte, offset flatbuffers.UOffsetT) *Catalog {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||||
|
x := &Catalog{}
|
||||||
|
x.Init(buf, n+offset)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishCatalogBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.Finish(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSizePrefixedRootAsCatalog(buf []byte, offset flatbuffers.UOffsetT) *Catalog {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||||
|
x := &Catalog{}
|
||||||
|
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishSizePrefixedCatalogBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.FinishSizePrefixed(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Catalog) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||||
|
rcv._tab.Bytes = buf
|
||||||
|
rcv._tab.Pos = i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Catalog) Table() flatbuffers.Table {
|
||||||
|
return rcv._tab
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Catalog) Products(obj *CatalogProduct, j int) bool {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
x := rcv._tab.Vector(o)
|
||||||
|
x += flatbuffers.UOffsetT(j) * 4
|
||||||
|
x = rcv._tab.Indirect(x)
|
||||||
|
obj.Init(rcv._tab.Bytes, x)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Catalog) ProductsLength() int {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.VectorLen(o)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func CatalogStart(builder *flatbuffers.Builder) {
|
||||||
|
builder.StartObject(1)
|
||||||
|
}
|
||||||
|
func CatalogAddProducts(builder *flatbuffers.Builder, products flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(products), 0)
|
||||||
|
}
|
||||||
|
func CatalogStartProductsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
|
||||||
|
return builder.StartVector(4, numElems, 4)
|
||||||
|
}
|
||||||
|
func CatalogEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||||
|
return builder.EndObject()
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||||
|
|
||||||
|
package scrabblefb
|
||||||
|
|
||||||
|
import (
|
||||||
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CatalogAtom struct {
|
||||||
|
_tab flatbuffers.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRootAsCatalogAtom(buf []byte, offset flatbuffers.UOffsetT) *CatalogAtom {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||||
|
x := &CatalogAtom{}
|
||||||
|
x.Init(buf, n+offset)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishCatalogAtomBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.Finish(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSizePrefixedRootAsCatalogAtom(buf []byte, offset flatbuffers.UOffsetT) *CatalogAtom {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||||
|
x := &CatalogAtom{}
|
||||||
|
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishSizePrefixedCatalogAtomBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.FinishSizePrefixed(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogAtom) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||||
|
rcv._tab.Bytes = buf
|
||||||
|
rcv._tab.Pos = i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogAtom) Table() flatbuffers.Table {
|
||||||
|
return rcv._tab
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogAtom) AtomType() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogAtom) Quantity() int32 {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetInt32(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogAtom) MutateQuantity(n int32) bool {
|
||||||
|
return rcv._tab.MutateInt32Slot(6, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CatalogAtomStart(builder *flatbuffers.Builder) {
|
||||||
|
builder.StartObject(2)
|
||||||
|
}
|
||||||
|
func CatalogAtomAddAtomType(builder *flatbuffers.Builder, atomType flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(atomType), 0)
|
||||||
|
}
|
||||||
|
func CatalogAtomAddQuantity(builder *flatbuffers.Builder, quantity int32) {
|
||||||
|
builder.PrependInt32Slot(1, quantity, 0)
|
||||||
|
}
|
||||||
|
func CatalogAtomEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||||
|
return builder.EndObject()
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||||
|
|
||||||
|
package scrabblefb
|
||||||
|
|
||||||
|
import (
|
||||||
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CatalogProduct struct {
|
||||||
|
_tab flatbuffers.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRootAsCatalogProduct(buf []byte, offset flatbuffers.UOffsetT) *CatalogProduct {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||||
|
x := &CatalogProduct{}
|
||||||
|
x.Init(buf, n+offset)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishCatalogProductBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.Finish(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSizePrefixedRootAsCatalogProduct(buf []byte, offset flatbuffers.UOffsetT) *CatalogProduct {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||||
|
x := &CatalogProduct{}
|
||||||
|
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishSizePrefixedCatalogProductBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.FinishSizePrefixed(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||||
|
rcv._tab.Bytes = buf
|
||||||
|
rcv._tab.Pos = i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) Table() flatbuffers.Table {
|
||||||
|
return rcv._tab
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) Kind() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) ProductId() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) Title() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) Chips() int32 {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetInt32(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) MutateChips(n int32) bool {
|
||||||
|
return rcv._tab.MutateInt32Slot(10, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) MoneyAmount() int64 {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetInt64(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) MutateMoneyAmount(n int64) bool {
|
||||||
|
return rcv._tab.MutateInt64Slot(12, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) MoneyCurrency() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) Atoms(obj *CatalogAtom, j int) bool {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(16))
|
||||||
|
if o != 0 {
|
||||||
|
x := rcv._tab.Vector(o)
|
||||||
|
x += flatbuffers.UOffsetT(j) * 4
|
||||||
|
x = rcv._tab.Indirect(x)
|
||||||
|
obj.Init(rcv._tab.Bytes, x)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *CatalogProduct) AtomsLength() int {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(16))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.VectorLen(o)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func CatalogProductStart(builder *flatbuffers.Builder) {
|
||||||
|
builder.StartObject(7)
|
||||||
|
}
|
||||||
|
func CatalogProductAddKind(builder *flatbuffers.Builder, kind flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(kind), 0)
|
||||||
|
}
|
||||||
|
func CatalogProductAddProductId(builder *flatbuffers.Builder, productId flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(productId), 0)
|
||||||
|
}
|
||||||
|
func CatalogProductAddTitle(builder *flatbuffers.Builder, title flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(title), 0)
|
||||||
|
}
|
||||||
|
func CatalogProductAddChips(builder *flatbuffers.Builder, chips int32) {
|
||||||
|
builder.PrependInt32Slot(3, chips, 0)
|
||||||
|
}
|
||||||
|
func CatalogProductAddMoneyAmount(builder *flatbuffers.Builder, moneyAmount int64) {
|
||||||
|
builder.PrependInt64Slot(4, moneyAmount, 0)
|
||||||
|
}
|
||||||
|
func CatalogProductAddMoneyCurrency(builder *flatbuffers.Builder, moneyCurrency flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(moneyCurrency), 0)
|
||||||
|
}
|
||||||
|
func CatalogProductAddAtoms(builder *flatbuffers.Builder, atoms flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(6, flatbuffers.UOffsetT(atoms), 0)
|
||||||
|
}
|
||||||
|
func CatalogProductStartAtomsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
|
||||||
|
return builder.StartVector(4, numElems, 4)
|
||||||
|
}
|
||||||
|
func CatalogProductEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||||
|
return builder.EndObject()
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||||
|
|
||||||
|
package scrabblefb
|
||||||
|
|
||||||
|
import (
|
||||||
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Wallet struct {
|
||||||
|
_tab flatbuffers.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRootAsWallet(buf []byte, offset flatbuffers.UOffsetT) *Wallet {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||||
|
x := &Wallet{}
|
||||||
|
x.Init(buf, n+offset)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishWalletBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.Finish(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSizePrefixedRootAsWallet(buf []byte, offset flatbuffers.UOffsetT) *Wallet {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||||
|
x := &Wallet{}
|
||||||
|
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishSizePrefixedWalletBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.FinishSizePrefixed(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||||
|
rcv._tab.Bytes = buf
|
||||||
|
rcv._tab.Pos = i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) Table() flatbuffers.Table {
|
||||||
|
return rcv._tab
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) Segments(obj *WalletSegment, j int) bool {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
x := rcv._tab.Vector(o)
|
||||||
|
x += flatbuffers.UOffsetT(j) * 4
|
||||||
|
x = rcv._tab.Indirect(x)
|
||||||
|
obj.Init(rcv._tab.Bytes, x)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) SegmentsLength() int {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.VectorLen(o)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) AdsForever() bool {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetBool(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) MutateAdsForever(n bool) bool {
|
||||||
|
return rcv._tab.MutateBoolSlot(6, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) AdsPaidUntilMs() int64 {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetInt64(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) MutateAdsPaidUntilMs(n int64) bool {
|
||||||
|
return rcv._tab.MutateInt64Slot(8, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) Hints() int32 {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetInt32(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *Wallet) MutateHints(n int32) bool {
|
||||||
|
return rcv._tab.MutateInt32Slot(10, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WalletStart(builder *flatbuffers.Builder) {
|
||||||
|
builder.StartObject(4)
|
||||||
|
}
|
||||||
|
func WalletAddSegments(builder *flatbuffers.Builder, segments flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(segments), 0)
|
||||||
|
}
|
||||||
|
func WalletStartSegmentsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
|
||||||
|
return builder.StartVector(4, numElems, 4)
|
||||||
|
}
|
||||||
|
func WalletAddAdsForever(builder *flatbuffers.Builder, adsForever bool) {
|
||||||
|
builder.PrependBoolSlot(1, adsForever, false)
|
||||||
|
}
|
||||||
|
func WalletAddAdsPaidUntilMs(builder *flatbuffers.Builder, adsPaidUntilMs int64) {
|
||||||
|
builder.PrependInt64Slot(2, adsPaidUntilMs, 0)
|
||||||
|
}
|
||||||
|
func WalletAddHints(builder *flatbuffers.Builder, hints int32) {
|
||||||
|
builder.PrependInt32Slot(3, hints, 0)
|
||||||
|
}
|
||||||
|
func WalletEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||||
|
return builder.EndObject()
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||||
|
|
||||||
|
package scrabblefb
|
||||||
|
|
||||||
|
import (
|
||||||
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WalletBuyRequest struct {
|
||||||
|
_tab flatbuffers.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRootAsWalletBuyRequest(buf []byte, offset flatbuffers.UOffsetT) *WalletBuyRequest {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||||
|
x := &WalletBuyRequest{}
|
||||||
|
x.Init(buf, n+offset)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishWalletBuyRequestBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.Finish(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSizePrefixedRootAsWalletBuyRequest(buf []byte, offset flatbuffers.UOffsetT) *WalletBuyRequest {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||||
|
x := &WalletBuyRequest{}
|
||||||
|
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishSizePrefixedWalletBuyRequestBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.FinishSizePrefixed(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletBuyRequest) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||||
|
rcv._tab.Bytes = buf
|
||||||
|
rcv._tab.Pos = i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletBuyRequest) Table() flatbuffers.Table {
|
||||||
|
return rcv._tab
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletBuyRequest) ProductId() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func WalletBuyRequestStart(builder *flatbuffers.Builder) {
|
||||||
|
builder.StartObject(1)
|
||||||
|
}
|
||||||
|
func WalletBuyRequestAddProductId(builder *flatbuffers.Builder, productId flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(productId), 0)
|
||||||
|
}
|
||||||
|
func WalletBuyRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||||
|
return builder.EndObject()
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||||
|
|
||||||
|
package scrabblefb
|
||||||
|
|
||||||
|
import (
|
||||||
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WalletSegment struct {
|
||||||
|
_tab flatbuffers.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRootAsWalletSegment(buf []byte, offset flatbuffers.UOffsetT) *WalletSegment {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||||
|
x := &WalletSegment{}
|
||||||
|
x.Init(buf, n+offset)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishWalletSegmentBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.Finish(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSizePrefixedRootAsWalletSegment(buf []byte, offset flatbuffers.UOffsetT) *WalletSegment {
|
||||||
|
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||||
|
x := &WalletSegment{}
|
||||||
|
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishSizePrefixedWalletSegmentBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||||
|
builder.FinishSizePrefixed(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||||
|
rcv._tab.Bytes = buf
|
||||||
|
rcv._tab.Pos = i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) Table() flatbuffers.Table {
|
||||||
|
return rcv._tab
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) Source() []byte {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) Chips() int32 {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetInt32(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) MutateChips(n int32) bool {
|
||||||
|
return rcv._tab.MutateInt32Slot(6, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) Spendable() bool {
|
||||||
|
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
|
||||||
|
if o != 0 {
|
||||||
|
return rcv._tab.GetBool(o + rcv._tab.Pos)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rcv *WalletSegment) MutateSpendable(n bool) bool {
|
||||||
|
return rcv._tab.MutateBoolSlot(8, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WalletSegmentStart(builder *flatbuffers.Builder) {
|
||||||
|
builder.StartObject(3)
|
||||||
|
}
|
||||||
|
func WalletSegmentAddSource(builder *flatbuffers.Builder, source flatbuffers.UOffsetT) {
|
||||||
|
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(source), 0)
|
||||||
|
}
|
||||||
|
func WalletSegmentAddChips(builder *flatbuffers.Builder, chips int32) {
|
||||||
|
builder.PrependInt32Slot(1, chips, 0)
|
||||||
|
}
|
||||||
|
func WalletSegmentAddSpendable(builder *flatbuffers.Builder, spendable bool) {
|
||||||
|
builder.PrependBoolSlot(2, spendable, false)
|
||||||
|
}
|
||||||
|
func WalletSegmentEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||||
|
return builder.EndObject()
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { expect, test, type Page } from './fixtures';
|
||||||
|
|
||||||
|
// The Wallet section against the mock transport (no backend). The mock seeds a web/native (direct)
|
||||||
|
// account holding a direct + vk chip segment and a small catalog (two chip-priced values and one
|
||||||
|
// rouble-priced chip pack — see lib/mock/client.ts), so the storefront, the store-compliance
|
||||||
|
// warning and the Google Play stub are all exercisable without a backend.
|
||||||
|
|
||||||
|
async function loginLobby(page: Page): Promise<void> {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.getByRole('button', { name: /guest/i }).click();
|
||||||
|
await expect(page.getByText('Your turn')).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSettings(page: Page): Promise<void> {
|
||||||
|
await page.getByRole('button', { name: /Settings/ }).click(); // lobby ⚙️ tab
|
||||||
|
await expect(page.locator('.pane')).toHaveCount(1); // let the slide settle
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openWallet(page: Page): Promise<void> {
|
||||||
|
await openSettings(page);
|
||||||
|
await page.getByRole('button', { name: 'Wallet', exact: true }).click();
|
||||||
|
await expect(page.getByTestId('wallet')).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
test('wallet: balances, benefits and the storefront render for a durable account', async ({ page }) => {
|
||||||
|
await loginLobby(page);
|
||||||
|
await openWallet(page);
|
||||||
|
|
||||||
|
// Balances: the seeded direct ("Web") and vk segments.
|
||||||
|
await expect(page.getByRole('heading', { name: 'Balance' })).toBeVisible();
|
||||||
|
await expect(page.getByText('Web', { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByText('VK', { exact: true })).toBeVisible();
|
||||||
|
|
||||||
|
// Benefits + the storefront: two values priced in chips, one pack priced in roubles.
|
||||||
|
await expect(page.getByRole('heading', { name: 'Benefits' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Store' })).toBeVisible();
|
||||||
|
await expect(page.getByTestId('product')).toHaveCount(3);
|
||||||
|
const pack = page.locator('[data-kind="pack"]');
|
||||||
|
await expect(pack).toContainText('₽');
|
||||||
|
// The pack purchase (money intake) is not wired yet, so its action is the disabled 'Soon'.
|
||||||
|
await expect(pack.getByRole('button', { name: 'Soon' })).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wallet: the tab sits between Friends and About', async ({ page }) => {
|
||||||
|
await loginLobby(page);
|
||||||
|
await openSettings(page);
|
||||||
|
const labels = await page.locator('.tab .lbl').allInnerTexts();
|
||||||
|
const iFriends = labels.indexOf('Friends');
|
||||||
|
const iWallet = labels.indexOf('Wallet');
|
||||||
|
const iAbout = labels.indexOf('Info');
|
||||||
|
expect(iFriends).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(iWallet).toBe(iFriends + 1);
|
||||||
|
expect(iAbout).toBe(iWallet + 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wallet: a guest has no wallet (nor friends) tab', async ({ page }) => {
|
||||||
|
await page.goto('/?guest');
|
||||||
|
await page.getByRole('button', { name: /guest/i }).click();
|
||||||
|
await expect(page.getByText('Your turn')).toBeVisible();
|
||||||
|
await openSettings(page);
|
||||||
|
await expect(page.getByRole('button', { name: 'Wallet', exact: true })).toBeHidden();
|
||||||
|
await expect(page.getByRole('button', { name: 'Friends', exact: true })).toBeHidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wallet: the Google Play build hides the money purchases behind the RuStore stub', async ({ page }) => {
|
||||||
|
await page.goto('/?gp');
|
||||||
|
await page.getByRole('button', { name: /guest/i }).click();
|
||||||
|
await expect(page.getByText('Your turn')).toBeVisible();
|
||||||
|
await openWallet(page);
|
||||||
|
|
||||||
|
// The chip pack is gone; the stub points at the RuStore build. Spending earned chips still works.
|
||||||
|
await expect(page.getByTestId('gp-stub')).toBeVisible();
|
||||||
|
await expect(page.locator('[data-kind="pack"]')).toHaveCount(0);
|
||||||
|
await expect(page.locator('[data-kind="value"]').first().getByTestId('buy')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wallet: a web spend that would draw store chips warns first, then completes', async ({ page }) => {
|
||||||
|
await loginLobby(page);
|
||||||
|
await openWallet(page);
|
||||||
|
|
||||||
|
// The 300-chip value drains direct (120) then reaches into vk (180) → a store segment → warn.
|
||||||
|
await page.locator('[data-pid="val-noads-30"]').getByTestId('buy').click();
|
||||||
|
await expect(page.getByTestId('warn')).toBeVisible();
|
||||||
|
await page.getByTestId('warn-confirm').click();
|
||||||
|
await expect(page.getByTestId('warn')).toBeHidden();
|
||||||
|
// The spend applied: the no-ads benefit now shows an end date.
|
||||||
|
await expect(page.getByTestId('wallet')).toContainText('No ads until');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wallet: a spend the direct segment covers alone does not warn', async ({ page }) => {
|
||||||
|
await loginLobby(page);
|
||||||
|
await openWallet(page);
|
||||||
|
|
||||||
|
// The 100-chip value is covered by the direct segment (120) alone → no store draw, no warning.
|
||||||
|
await page.locator('[data-pid="val-hints-50"]').getByTestId('buy').click();
|
||||||
|
await expect(page.getByTestId('warn')).toBeHidden();
|
||||||
|
// The hints benefit rose from 5 to 55.
|
||||||
|
await expect(page.getByTestId('wallet')).toContainText('Hints 55');
|
||||||
|
});
|
||||||
@@ -26,10 +26,11 @@ const DIST = 'dist';
|
|||||||
// countdown toast live in the always-loaded game screen (Game.svelte) — and to 120 for the offline
|
// countdown toast live in the always-loaded game screen (Game.svelte) — and to 120 for the offline
|
||||||
// pass-and-play (hotseat) mode: the on-screen PIN pad, the creation roster and the in-game host menu
|
// pass-and-play (hotseat) mode: the on-screen PIN pad, the creation roster and the in-game host menu
|
||||||
// live in the always-loaded New Game / Game / Lobby screens (the offline engine and the tiny PIN
|
// live in the always-loaded New Game / Game / Lobby screens (the offline engine and the tiny PIN
|
||||||
// hashing stay in lazy chunks / are negligible). The heavy parts — the dict loader, the move
|
// hashing stay in lazy chunks / are negligible), then to 123 for the Wallet section — its screen,
|
||||||
// generator and the preload orchestration — still stay in lazy chunks. Scoped CSS lands in the CSS
|
// storefront logic and the catalog codec load with the always-mounted settings hub (its i18n lands
|
||||||
// chunk, not this JS budget.
|
// in the shared chunk). The heavy parts — the dict loader, the move generator and the preload
|
||||||
const BUDGET = { app: 120, shared: 30, landing: 5 };
|
// orchestration — still stay in lazy chunks. Scoped CSS lands in the CSS chunk, not this JS budget.
|
||||||
|
const BUDGET = { app: 123, shared: 30, landing: 5 };
|
||||||
|
|
||||||
// gzipped returns the gzipped byte size of a built asset, or 0 when the reference is not a
|
// gzipped returns the gzipped byte size of a built asset, or 0 when the reference is not a
|
||||||
// local file (e.g. the Telegram SDK loaded from a CDN) or is missing.
|
// local file (e.g. the Telegram SDK loaded from a CDN) or is missing.
|
||||||
|
|||||||
@@ -116,6 +116,8 @@
|
|||||||
<SettingsHub initialTab="about" />
|
<SettingsHub initialTab="about" />
|
||||||
{:else if router.route.name === 'friends'}
|
{:else if router.route.name === 'friends'}
|
||||||
<SettingsHub initialTab="friends" />
|
<SettingsHub initialTab="friends" />
|
||||||
|
{:else if router.route.name === 'wallet'}
|
||||||
|
<SettingsHub initialTab="wallet" />
|
||||||
{:else if router.route.name === 'feedback'}
|
{:else if router.route.name === 'feedback'}
|
||||||
<Feedback />
|
<Feedback />
|
||||||
{:else if router.route.name === 'stats'}
|
{:else if router.route.name === 'stats'}
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ export { BestMoveTile } from './scrabblefb/best-move-tile.js';
|
|||||||
export { BestMoveView } from './scrabblefb/best-move-view.js';
|
export { BestMoveView } from './scrabblefb/best-move-view.js';
|
||||||
export { BlockList } from './scrabblefb/block-list.js';
|
export { BlockList } from './scrabblefb/block-list.js';
|
||||||
export { BlockStatus } from './scrabblefb/block-status.js';
|
export { BlockStatus } from './scrabblefb/block-status.js';
|
||||||
|
export { Catalog } from './scrabblefb/catalog.js';
|
||||||
|
export { CatalogAtom } from './scrabblefb/catalog-atom.js';
|
||||||
|
export { CatalogProduct } from './scrabblefb/catalog-product.js';
|
||||||
export { ChatList } from './scrabblefb/chat-list.js';
|
export { ChatList } from './scrabblefb/chat-list.js';
|
||||||
export { ChatMessage } from './scrabblefb/chat-message.js';
|
export { ChatMessage } from './scrabblefb/chat-message.js';
|
||||||
export { ChatPostRequest } from './scrabblefb/chat-post-request.js';
|
export { ChatPostRequest } from './scrabblefb/chat-post-request.js';
|
||||||
@@ -81,5 +84,8 @@ export { TelegramLoginRequest } from './scrabblefb/telegram-login-request.js';
|
|||||||
export { TileRecord } from './scrabblefb/tile-record.js';
|
export { TileRecord } from './scrabblefb/tile-record.js';
|
||||||
export { UpdateProfileRequest } from './scrabblefb/update-profile-request.js';
|
export { UpdateProfileRequest } from './scrabblefb/update-profile-request.js';
|
||||||
export { VKLoginRequest } from './scrabblefb/vklogin-request.js';
|
export { VKLoginRequest } from './scrabblefb/vklogin-request.js';
|
||||||
|
export { Wallet } from './scrabblefb/wallet.js';
|
||||||
|
export { WalletBuyRequest } from './scrabblefb/wallet-buy-request.js';
|
||||||
|
export { WalletSegment } from './scrabblefb/wallet-segment.js';
|
||||||
export { WordCheckResult } from './scrabblefb/word-check-result.js';
|
export { WordCheckResult } from './scrabblefb/word-check-result.js';
|
||||||
export { YourTurnEvent } from './scrabblefb/your-turn-event.js';
|
export { YourTurnEvent } from './scrabblefb/your-turn-event.js';
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
import * as flatbuffers from 'flatbuffers';
|
||||||
|
|
||||||
|
export class CatalogAtom {
|
||||||
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
|
bb_pos = 0;
|
||||||
|
__init(i:number, bb:flatbuffers.ByteBuffer):CatalogAtom {
|
||||||
|
this.bb_pos = i;
|
||||||
|
this.bb = bb;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getRootAsCatalogAtom(bb:flatbuffers.ByteBuffer, obj?:CatalogAtom):CatalogAtom {
|
||||||
|
return (obj || new CatalogAtom()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static getSizePrefixedRootAsCatalogAtom(bb:flatbuffers.ByteBuffer, obj?:CatalogAtom):CatalogAtom {
|
||||||
|
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
|
||||||
|
return (obj || new CatalogAtom()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
atomType():string|null
|
||||||
|
atomType(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
atomType(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
quantity():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||||
|
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static startCatalogAtom(builder:flatbuffers.Builder) {
|
||||||
|
builder.startObject(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addAtomType(builder:flatbuffers.Builder, atomTypeOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(0, atomTypeOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addQuantity(builder:flatbuffers.Builder, quantity:number) {
|
||||||
|
builder.addFieldInt32(1, quantity, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static endCatalogAtom(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||||
|
const offset = builder.endObject();
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
static createCatalogAtom(builder:flatbuffers.Builder, atomTypeOffset:flatbuffers.Offset, quantity:number):flatbuffers.Offset {
|
||||||
|
CatalogAtom.startCatalogAtom(builder);
|
||||||
|
CatalogAtom.addAtomType(builder, atomTypeOffset);
|
||||||
|
CatalogAtom.addQuantity(builder, quantity);
|
||||||
|
return CatalogAtom.endCatalogAtom(builder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
import * as flatbuffers from 'flatbuffers';
|
||||||
|
|
||||||
|
import { CatalogAtom } from '../scrabblefb/catalog-atom.js';
|
||||||
|
|
||||||
|
|
||||||
|
export class CatalogProduct {
|
||||||
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
|
bb_pos = 0;
|
||||||
|
__init(i:number, bb:flatbuffers.ByteBuffer):CatalogProduct {
|
||||||
|
this.bb_pos = i;
|
||||||
|
this.bb = bb;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getRootAsCatalogProduct(bb:flatbuffers.ByteBuffer, obj?:CatalogProduct):CatalogProduct {
|
||||||
|
return (obj || new CatalogProduct()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static getSizePrefixedRootAsCatalogProduct(bb:flatbuffers.ByteBuffer, obj?:CatalogProduct):CatalogProduct {
|
||||||
|
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
|
||||||
|
return (obj || new CatalogProduct()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
kind():string|null
|
||||||
|
kind(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
kind(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
productId():string|null
|
||||||
|
productId(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
productId(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
title():string|null
|
||||||
|
title(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
title(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 8);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
chips():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 10);
|
||||||
|
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
moneyAmount():bigint {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 12);
|
||||||
|
return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
|
||||||
|
}
|
||||||
|
|
||||||
|
moneyCurrency():string|null
|
||||||
|
moneyCurrency(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
moneyCurrency(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 14);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
atoms(index: number, obj?:CatalogAtom):CatalogAtom|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 16);
|
||||||
|
return offset ? (obj || new CatalogAtom()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
atomsLength():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 16);
|
||||||
|
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static startCatalogProduct(builder:flatbuffers.Builder) {
|
||||||
|
builder.startObject(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addKind(builder:flatbuffers.Builder, kindOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(0, kindOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addProductId(builder:flatbuffers.Builder, productIdOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(1, productIdOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addTitle(builder:flatbuffers.Builder, titleOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(2, titleOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addChips(builder:flatbuffers.Builder, chips:number) {
|
||||||
|
builder.addFieldInt32(3, chips, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addMoneyAmount(builder:flatbuffers.Builder, moneyAmount:bigint) {
|
||||||
|
builder.addFieldInt64(4, moneyAmount, BigInt('0'));
|
||||||
|
}
|
||||||
|
|
||||||
|
static addMoneyCurrency(builder:flatbuffers.Builder, moneyCurrencyOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(5, moneyCurrencyOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addAtoms(builder:flatbuffers.Builder, atomsOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(6, atomsOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static createAtomsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
|
||||||
|
builder.startVector(4, data.length, 4);
|
||||||
|
for (let i = data.length - 1; i >= 0; i--) {
|
||||||
|
builder.addOffset(data[i]!);
|
||||||
|
}
|
||||||
|
return builder.endVector();
|
||||||
|
}
|
||||||
|
|
||||||
|
static startAtomsVector(builder:flatbuffers.Builder, numElems:number) {
|
||||||
|
builder.startVector(4, numElems, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
static endCatalogProduct(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||||
|
const offset = builder.endObject();
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
static createCatalogProduct(builder:flatbuffers.Builder, kindOffset:flatbuffers.Offset, productIdOffset:flatbuffers.Offset, titleOffset:flatbuffers.Offset, chips:number, moneyAmount:bigint, moneyCurrencyOffset:flatbuffers.Offset, atomsOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||||
|
CatalogProduct.startCatalogProduct(builder);
|
||||||
|
CatalogProduct.addKind(builder, kindOffset);
|
||||||
|
CatalogProduct.addProductId(builder, productIdOffset);
|
||||||
|
CatalogProduct.addTitle(builder, titleOffset);
|
||||||
|
CatalogProduct.addChips(builder, chips);
|
||||||
|
CatalogProduct.addMoneyAmount(builder, moneyAmount);
|
||||||
|
CatalogProduct.addMoneyCurrency(builder, moneyCurrencyOffset);
|
||||||
|
CatalogProduct.addAtoms(builder, atomsOffset);
|
||||||
|
return CatalogProduct.endCatalogProduct(builder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
import * as flatbuffers from 'flatbuffers';
|
||||||
|
|
||||||
|
import { CatalogProduct } from '../scrabblefb/catalog-product.js';
|
||||||
|
|
||||||
|
|
||||||
|
export class Catalog {
|
||||||
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
|
bb_pos = 0;
|
||||||
|
__init(i:number, bb:flatbuffers.ByteBuffer):Catalog {
|
||||||
|
this.bb_pos = i;
|
||||||
|
this.bb = bb;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getRootAsCatalog(bb:flatbuffers.ByteBuffer, obj?:Catalog):Catalog {
|
||||||
|
return (obj || new Catalog()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static getSizePrefixedRootAsCatalog(bb:flatbuffers.ByteBuffer, obj?:Catalog):Catalog {
|
||||||
|
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
|
||||||
|
return (obj || new Catalog()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
products(index: number, obj?:CatalogProduct):CatalogProduct|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? (obj || new CatalogProduct()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
productsLength():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static startCatalog(builder:flatbuffers.Builder) {
|
||||||
|
builder.startObject(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addProducts(builder:flatbuffers.Builder, productsOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(0, productsOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static createProductsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
|
||||||
|
builder.startVector(4, data.length, 4);
|
||||||
|
for (let i = data.length - 1; i >= 0; i--) {
|
||||||
|
builder.addOffset(data[i]!);
|
||||||
|
}
|
||||||
|
return builder.endVector();
|
||||||
|
}
|
||||||
|
|
||||||
|
static startProductsVector(builder:flatbuffers.Builder, numElems:number) {
|
||||||
|
builder.startVector(4, numElems, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
static endCatalog(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||||
|
const offset = builder.endObject();
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
static createCatalog(builder:flatbuffers.Builder, productsOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||||
|
Catalog.startCatalog(builder);
|
||||||
|
Catalog.addProducts(builder, productsOffset);
|
||||||
|
return Catalog.endCatalog(builder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
import * as flatbuffers from 'flatbuffers';
|
||||||
|
|
||||||
|
export class WalletBuyRequest {
|
||||||
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
|
bb_pos = 0;
|
||||||
|
__init(i:number, bb:flatbuffers.ByteBuffer):WalletBuyRequest {
|
||||||
|
this.bb_pos = i;
|
||||||
|
this.bb = bb;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getRootAsWalletBuyRequest(bb:flatbuffers.ByteBuffer, obj?:WalletBuyRequest):WalletBuyRequest {
|
||||||
|
return (obj || new WalletBuyRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static getSizePrefixedRootAsWalletBuyRequest(bb:flatbuffers.ByteBuffer, obj?:WalletBuyRequest):WalletBuyRequest {
|
||||||
|
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
|
||||||
|
return (obj || new WalletBuyRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
productId():string|null
|
||||||
|
productId(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
productId(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static startWalletBuyRequest(builder:flatbuffers.Builder) {
|
||||||
|
builder.startObject(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addProductId(builder:flatbuffers.Builder, productIdOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(0, productIdOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static endWalletBuyRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||||
|
const offset = builder.endObject();
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
static createWalletBuyRequest(builder:flatbuffers.Builder, productIdOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||||
|
WalletBuyRequest.startWalletBuyRequest(builder);
|
||||||
|
WalletBuyRequest.addProductId(builder, productIdOffset);
|
||||||
|
return WalletBuyRequest.endWalletBuyRequest(builder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
import * as flatbuffers from 'flatbuffers';
|
||||||
|
|
||||||
|
export class WalletSegment {
|
||||||
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
|
bb_pos = 0;
|
||||||
|
__init(i:number, bb:flatbuffers.ByteBuffer):WalletSegment {
|
||||||
|
this.bb_pos = i;
|
||||||
|
this.bb = bb;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getRootAsWalletSegment(bb:flatbuffers.ByteBuffer, obj?:WalletSegment):WalletSegment {
|
||||||
|
return (obj || new WalletSegment()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static getSizePrefixedRootAsWalletSegment(bb:flatbuffers.ByteBuffer, obj?:WalletSegment):WalletSegment {
|
||||||
|
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
|
||||||
|
return (obj || new WalletSegment()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
source():string|null
|
||||||
|
source(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||||
|
source(optionalEncoding?:any):string|Uint8Array|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
chips():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||||
|
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
spendable():boolean {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 8);
|
||||||
|
return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static startWalletSegment(builder:flatbuffers.Builder) {
|
||||||
|
builder.startObject(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addSource(builder:flatbuffers.Builder, sourceOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(0, sourceOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addChips(builder:flatbuffers.Builder, chips:number) {
|
||||||
|
builder.addFieldInt32(1, chips, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addSpendable(builder:flatbuffers.Builder, spendable:boolean) {
|
||||||
|
builder.addFieldInt8(2, +spendable, +false);
|
||||||
|
}
|
||||||
|
|
||||||
|
static endWalletSegment(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||||
|
const offset = builder.endObject();
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
static createWalletSegment(builder:flatbuffers.Builder, sourceOffset:flatbuffers.Offset, chips:number, spendable:boolean):flatbuffers.Offset {
|
||||||
|
WalletSegment.startWalletSegment(builder);
|
||||||
|
WalletSegment.addSource(builder, sourceOffset);
|
||||||
|
WalletSegment.addChips(builder, chips);
|
||||||
|
WalletSegment.addSpendable(builder, spendable);
|
||||||
|
return WalletSegment.endWalletSegment(builder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
import * as flatbuffers from 'flatbuffers';
|
||||||
|
|
||||||
|
import { WalletSegment } from '../scrabblefb/wallet-segment.js';
|
||||||
|
|
||||||
|
|
||||||
|
export class Wallet {
|
||||||
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
|
bb_pos = 0;
|
||||||
|
__init(i:number, bb:flatbuffers.ByteBuffer):Wallet {
|
||||||
|
this.bb_pos = i;
|
||||||
|
this.bb = bb;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getRootAsWallet(bb:flatbuffers.ByteBuffer, obj?:Wallet):Wallet {
|
||||||
|
return (obj || new Wallet()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static getSizePrefixedRootAsWallet(bb:flatbuffers.ByteBuffer, obj?:Wallet):Wallet {
|
||||||
|
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
|
||||||
|
return (obj || new Wallet()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
segments(index: number, obj?:WalletSegment):WalletSegment|null {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? (obj || new WalletSegment()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
segmentsLength():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 4);
|
||||||
|
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
adsForever():boolean {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||||
|
return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
adsPaidUntilMs():bigint {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 8);
|
||||||
|
return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
|
||||||
|
}
|
||||||
|
|
||||||
|
hints():number {
|
||||||
|
const offset = this.bb!.__offset(this.bb_pos, 10);
|
||||||
|
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static startWallet(builder:flatbuffers.Builder) {
|
||||||
|
builder.startObject(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addSegments(builder:flatbuffers.Builder, segmentsOffset:flatbuffers.Offset) {
|
||||||
|
builder.addFieldOffset(0, segmentsOffset, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static createSegmentsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
|
||||||
|
builder.startVector(4, data.length, 4);
|
||||||
|
for (let i = data.length - 1; i >= 0; i--) {
|
||||||
|
builder.addOffset(data[i]!);
|
||||||
|
}
|
||||||
|
return builder.endVector();
|
||||||
|
}
|
||||||
|
|
||||||
|
static startSegmentsVector(builder:flatbuffers.Builder, numElems:number) {
|
||||||
|
builder.startVector(4, numElems, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addAdsForever(builder:flatbuffers.Builder, adsForever:boolean) {
|
||||||
|
builder.addFieldInt8(1, +adsForever, +false);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addAdsPaidUntilMs(builder:flatbuffers.Builder, adsPaidUntilMs:bigint) {
|
||||||
|
builder.addFieldInt64(2, adsPaidUntilMs, BigInt('0'));
|
||||||
|
}
|
||||||
|
|
||||||
|
static addHints(builder:flatbuffers.Builder, hints:number) {
|
||||||
|
builder.addFieldInt32(3, hints, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static endWallet(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||||
|
const offset = builder.endObject();
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
static createWallet(builder:flatbuffers.Builder, segmentsOffset:flatbuffers.Offset, adsForever:boolean, adsPaidUntilMs:bigint, hints:number):flatbuffers.Offset {
|
||||||
|
Wallet.startWallet(builder);
|
||||||
|
Wallet.addSegments(builder, segmentsOffset);
|
||||||
|
Wallet.addAdsForever(builder, adsForever);
|
||||||
|
Wallet.addAdsPaidUntilMs(builder, adsPaidUntilMs);
|
||||||
|
Wallet.addHints(builder, hints);
|
||||||
|
return Wallet.endWallet(builder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,8 @@ import type {
|
|||||||
Tile,
|
Tile,
|
||||||
Variant,
|
Variant,
|
||||||
WordCheckResult,
|
WordCheckResult,
|
||||||
|
Wallet,
|
||||||
|
Catalog,
|
||||||
} from './model';
|
} from './model';
|
||||||
|
|
||||||
/** GatewayError carries a stable code (the gateway result_code, or an edge code). */
|
/** GatewayError carries a stable code (the gateway result_code, or an edge code). */
|
||||||
@@ -135,6 +137,17 @@ export interface GatewayClient {
|
|||||||
/** feedbackUnread reports whether an operator reply awaits delivery (the badge). */
|
/** feedbackUnread reports whether an operator reply awaits delivery (the badge). */
|
||||||
feedbackUnread(): Promise<boolean>;
|
feedbackUnread(): Promise<boolean>;
|
||||||
|
|
||||||
|
// --- wallet ---
|
||||||
|
/** wallet returns the caller's chip segments and active benefits, visible in their current
|
||||||
|
* trusted execution context (view-only when the platform is untrusted or VK-iOS frozen). */
|
||||||
|
wallet(): Promise<Wallet>;
|
||||||
|
/** catalog returns the storefront for the caller's context: chip-priced values and the chip
|
||||||
|
* packs priced in the context's payment method. */
|
||||||
|
catalog(): Promise<Catalog>;
|
||||||
|
/** walletBuy spends chips on a chip-priced value and returns the updated wallet. Gate-checked
|
||||||
|
* server-side: an untrusted/frozen context or an insufficient balance is refused. */
|
||||||
|
walletBuy(productId: string): Promise<Wallet>;
|
||||||
|
|
||||||
// --- friends ---
|
// --- friends ---
|
||||||
friendsList(): Promise<AccountRef[]>;
|
friendsList(): Promise<AccountRef[]>;
|
||||||
friendsIncoming(): Promise<AccountRef[]>;
|
friendsIncoming(): Promise<AccountRef[]>;
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ import {
|
|||||||
decodeMatchResult,
|
decodeMatchResult,
|
||||||
decodeOutgoingList,
|
decodeOutgoingList,
|
||||||
decodeProfile,
|
decodeProfile,
|
||||||
|
decodeWallet,
|
||||||
|
decodeCatalog,
|
||||||
|
encodeWalletBuy,
|
||||||
decodeSession,
|
decodeSession,
|
||||||
decodeFeedbackState,
|
decodeFeedbackState,
|
||||||
decodeFeedbackUnread,
|
decodeFeedbackUnread,
|
||||||
@@ -41,6 +44,83 @@ import {
|
|||||||
} from './codec';
|
} from './codec';
|
||||||
|
|
||||||
describe('codec', () => {
|
describe('codec', () => {
|
||||||
|
it('round-trips the wallet buy request and the wallet view', () => {
|
||||||
|
// buy request: product id survives the wire
|
||||||
|
const req = fb.WalletBuyRequest.getRootAsWalletBuyRequest(new ByteBuffer(encodeWalletBuy('prod-42')));
|
||||||
|
expect(req.productId()).toBe('prod-42');
|
||||||
|
|
||||||
|
// wallet response: build a Wallet payload and decode it, checking the segment vector,
|
||||||
|
// the spendable flag and the benefit fields (the long ms field decodes to a number).
|
||||||
|
const b = new Builder(128);
|
||||||
|
const src = b.createString('direct');
|
||||||
|
fb.WalletSegment.startWalletSegment(b);
|
||||||
|
fb.WalletSegment.addSource(b, src);
|
||||||
|
fb.WalletSegment.addChips(b, 120);
|
||||||
|
fb.WalletSegment.addSpendable(b, true);
|
||||||
|
const seg = fb.WalletSegment.endWalletSegment(b);
|
||||||
|
const segs = fb.Wallet.createSegmentsVector(b, [seg]);
|
||||||
|
fb.Wallet.startWallet(b);
|
||||||
|
fb.Wallet.addSegments(b, segs);
|
||||||
|
fb.Wallet.addAdsForever(b, false);
|
||||||
|
fb.Wallet.addAdsPaidUntilMs(b, BigInt(1_700_000_000_000));
|
||||||
|
fb.Wallet.addHints(b, 5);
|
||||||
|
b.finish(fb.Wallet.endWallet(b));
|
||||||
|
|
||||||
|
const w = decodeWallet(b.asUint8Array());
|
||||||
|
expect(w.segments).toEqual([{ source: 'direct', chips: 120, spendable: true }]);
|
||||||
|
expect(w.adsForever).toBe(false);
|
||||||
|
expect(w.adsPaidUntilMs).toBe(1_700_000_000_000);
|
||||||
|
expect(w.hints).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('round-trips the catalog view (value + pack)', () => {
|
||||||
|
const b = new Builder(256);
|
||||||
|
|
||||||
|
// a chip-priced value with one atom
|
||||||
|
const vKind = b.createString('value');
|
||||||
|
const vId = b.createString('val-1');
|
||||||
|
const vTitle = b.createString('50 hints');
|
||||||
|
const aType = b.createString('hints');
|
||||||
|
fb.CatalogAtom.startCatalogAtom(b);
|
||||||
|
fb.CatalogAtom.addAtomType(b, aType);
|
||||||
|
fb.CatalogAtom.addQuantity(b, 50);
|
||||||
|
const atom = fb.CatalogAtom.endCatalogAtom(b);
|
||||||
|
const vAtoms = fb.CatalogProduct.createAtomsVector(b, [atom]);
|
||||||
|
fb.CatalogProduct.startCatalogProduct(b);
|
||||||
|
fb.CatalogProduct.addKind(b, vKind);
|
||||||
|
fb.CatalogProduct.addProductId(b, vId);
|
||||||
|
fb.CatalogProduct.addTitle(b, vTitle);
|
||||||
|
fb.CatalogProduct.addChips(b, 100);
|
||||||
|
fb.CatalogProduct.addMoneyAmount(b, BigInt(0));
|
||||||
|
fb.CatalogProduct.addAtoms(b, vAtoms);
|
||||||
|
const value = fb.CatalogProduct.endCatalogProduct(b);
|
||||||
|
|
||||||
|
// a RUB-priced chip pack (no atoms exercised)
|
||||||
|
const pKind = b.createString('pack');
|
||||||
|
const pId = b.createString('pack-1');
|
||||||
|
const pTitle = b.createString('100 chips');
|
||||||
|
const pCur = b.createString('RUB');
|
||||||
|
fb.CatalogProduct.startCatalogProduct(b);
|
||||||
|
fb.CatalogProduct.addKind(b, pKind);
|
||||||
|
fb.CatalogProduct.addProductId(b, pId);
|
||||||
|
fb.CatalogProduct.addTitle(b, pTitle);
|
||||||
|
fb.CatalogProduct.addChips(b, 0);
|
||||||
|
fb.CatalogProduct.addMoneyAmount(b, BigInt(14900));
|
||||||
|
fb.CatalogProduct.addMoneyCurrency(b, pCur);
|
||||||
|
const pack = fb.CatalogProduct.endCatalogProduct(b);
|
||||||
|
|
||||||
|
const prods = fb.Catalog.createProductsVector(b, [value, pack]);
|
||||||
|
fb.Catalog.startCatalog(b);
|
||||||
|
fb.Catalog.addProducts(b, prods);
|
||||||
|
b.finish(fb.Catalog.endCatalog(b));
|
||||||
|
|
||||||
|
const c = decodeCatalog(b.asUint8Array());
|
||||||
|
expect(c.products).toEqual([
|
||||||
|
{ kind: 'value', productId: 'val-1', title: '50 hints', chips: 100, moneyAmount: 0, moneyCurrency: '', atoms: [{ atomType: 'hints', quantity: 50 }] },
|
||||||
|
{ kind: 'pack', productId: 'pack-1', title: '100 chips', chips: 0, moneyAmount: 14900, moneyCurrency: 'RUB', atoms: [] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it('round-trips the export-url request and response', () => {
|
it('round-trips the export-url request and response', () => {
|
||||||
const req = fb.ExportUrlRequest.getRootAsExportUrlRequest(
|
const req = fb.ExportUrlRequest.getRootAsExportUrlRequest(
|
||||||
new ByteBuffer(
|
new ByteBuffer(
|
||||||
|
|||||||
@@ -38,6 +38,11 @@ import type {
|
|||||||
MoveRecord,
|
MoveRecord,
|
||||||
MoveResult,
|
MoveResult,
|
||||||
Profile,
|
Profile,
|
||||||
|
Wallet,
|
||||||
|
WalletSegment,
|
||||||
|
Catalog,
|
||||||
|
CatalogProduct,
|
||||||
|
CatalogAtom,
|
||||||
ProfileUpdate,
|
ProfileUpdate,
|
||||||
PushEvent,
|
PushEvent,
|
||||||
Seat,
|
Seat,
|
||||||
@@ -359,6 +364,60 @@ export function decodeSession(buf: Uint8Array): Session {
|
|||||||
return sessionFromTable(fb.Session.getRootAsSession(new ByteBuffer(buf)));
|
return sessionFromTable(fb.Session.getRootAsSession(new ByteBuffer(buf)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// encodeWalletBuy wraps the product id for a chip spend (POST /user/wallet/buy).
|
||||||
|
export function encodeWalletBuy(productId: string): Uint8Array {
|
||||||
|
const b = new Builder(64);
|
||||||
|
const pid = b.createString(productId);
|
||||||
|
fb.WalletBuyRequest.startWalletBuyRequest(b);
|
||||||
|
fb.WalletBuyRequest.addProductId(b, pid);
|
||||||
|
return finish(b, fb.WalletBuyRequest.endWalletBuyRequest(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeWallet reads the wallet payload: the context-visible chip segments and the
|
||||||
|
// context-applicable benefits.
|
||||||
|
export function decodeWallet(buf: Uint8Array): Wallet {
|
||||||
|
const w = fb.Wallet.getRootAsWallet(new ByteBuffer(buf));
|
||||||
|
const segments: WalletSegment[] = [];
|
||||||
|
for (let i = 0; i < w.segmentsLength(); i++) {
|
||||||
|
const seg = w.segments(i);
|
||||||
|
if (!seg) continue;
|
||||||
|
segments.push({ source: s(seg.source()), chips: seg.chips(), spendable: seg.spendable() });
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
segments,
|
||||||
|
adsForever: w.adsForever(),
|
||||||
|
adsPaidUntilMs: Number(w.adsPaidUntilMs()),
|
||||||
|
hints: w.hints(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeCatalog reads the storefront payload: the context-visible products, each a chip-priced
|
||||||
|
// value or a chip pack priced in the context's payment method, with its atom composition.
|
||||||
|
export function decodeCatalog(buf: Uint8Array): Catalog {
|
||||||
|
const c = fb.Catalog.getRootAsCatalog(new ByteBuffer(buf));
|
||||||
|
const products: CatalogProduct[] = [];
|
||||||
|
for (let i = 0; i < c.productsLength(); i++) {
|
||||||
|
const p = c.products(i);
|
||||||
|
if (!p) continue;
|
||||||
|
const atoms: CatalogAtom[] = [];
|
||||||
|
for (let j = 0; j < p.atomsLength(); j++) {
|
||||||
|
const a = p.atoms(j);
|
||||||
|
if (!a) continue;
|
||||||
|
atoms.push({ atomType: s(a.atomType()), quantity: a.quantity() });
|
||||||
|
}
|
||||||
|
products.push({
|
||||||
|
kind: s(p.kind()) === 'pack' ? 'pack' : 'value',
|
||||||
|
productId: s(p.productId()),
|
||||||
|
title: s(p.title()),
|
||||||
|
chips: p.chips(),
|
||||||
|
moneyAmount: Number(p.moneyAmount()),
|
||||||
|
moneyCurrency: s(p.moneyCurrency()),
|
||||||
|
atoms,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { products };
|
||||||
|
}
|
||||||
|
|
||||||
export function decodeProfile(buf: Uint8Array): Profile {
|
export function decodeProfile(buf: Uint8Array): Profile {
|
||||||
const p = fb.Profile.getRootAsProfile(new ByteBuffer(buf));
|
const p = fb.Profile.getRootAsProfile(new ByteBuffer(buf));
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { isGooglePlayBuild } from './distribution';
|
||||||
|
|
||||||
|
describe('isGooglePlayBuild', () => {
|
||||||
|
it('is false by default (no VITE_GP_BUILD flag, not the mock ?gp force)', () => {
|
||||||
|
// The unit env is neither the Google Play build nor the mock ?gp force, so the normal purchase
|
||||||
|
// actions show. The Google Play stub and the mock force are covered by the Playwright e2e.
|
||||||
|
expect(isGooglePlayBuild()).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// Distribution channel of the native build. Google Play forbids selling in-app currency through
|
||||||
|
// an external gate, so the Google Play build hides the purchase actions and shows a stub pointing
|
||||||
|
// the user to the RuStore build; every other build (web, VK, Telegram, RuStore native) sells
|
||||||
|
// normally. The channel is a build-time flag the Google Play build sets, not a runtime guess.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* isGooglePlayBuild reports whether this is the Google Play native build, where in-app-currency
|
||||||
|
* purchases are hidden. It reads the build-time flag VITE_GP_BUILD (set to "1" only by the Google
|
||||||
|
* Play build); every other build reads false. Under the mock e2e it can be forced on with a `?gp`
|
||||||
|
* query parameter so the stub path is exercisable without a separate build.
|
||||||
|
*/
|
||||||
|
export function isGooglePlayBuild(): boolean {
|
||||||
|
if (
|
||||||
|
import.meta.env.MODE === 'mock' &&
|
||||||
|
typeof window !== 'undefined' &&
|
||||||
|
new URLSearchParams(window.location.search).has('gp')
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return (import.meta.env as Record<string, string | undefined>).VITE_GP_BUILD === '1';
|
||||||
|
}
|
||||||
@@ -225,6 +225,33 @@ export const en = {
|
|||||||
'offline.promptYes': 'Enable',
|
'offline.promptYes': 'Enable',
|
||||||
'offline.promptNo': 'Keep trying',
|
'offline.promptNo': 'Keep trying',
|
||||||
|
|
||||||
|
// --- wallet ---
|
||||||
|
'wallet.title': 'Wallet',
|
||||||
|
'wallet.tab': 'Wallet',
|
||||||
|
'wallet.balance': 'Balance',
|
||||||
|
'wallet.noChips': 'No chips yet',
|
||||||
|
'wallet.source.vk': 'VK',
|
||||||
|
'wallet.source.telegram': 'Telegram',
|
||||||
|
'wallet.source.direct': 'Web',
|
||||||
|
'wallet.viewOnly': 'view only',
|
||||||
|
'wallet.benefits': 'Benefits',
|
||||||
|
'wallet.noAdsUntil': 'No ads until {date}',
|
||||||
|
'wallet.noAdsForever': 'No ads forever',
|
||||||
|
'wallet.adsOn': 'Ads are on',
|
||||||
|
'wallet.hints': 'Hints {n}',
|
||||||
|
'wallet.store': 'Store',
|
||||||
|
'wallet.empty': 'The store is empty for now',
|
||||||
|
'wallet.buy': 'Buy',
|
||||||
|
'wallet.soon': 'Soon',
|
||||||
|
'wallet.gpStub': 'To buy chips, install the RuStore build.',
|
||||||
|
'wallet.cur.RUB': '₽',
|
||||||
|
'wallet.cur.VOTE': 'votes',
|
||||||
|
'wallet.cur.XTR': '⭐',
|
||||||
|
'wallet.warnTitle': 'Web-only purchase',
|
||||||
|
'wallet.warnBody':
|
||||||
|
'This spends your VK/Telegram chips, and the benefit will work on the web and in the app only — because of store rules.',
|
||||||
|
'wallet.warnConfirm': 'Continue',
|
||||||
|
'wallet.warnCancel': 'Cancel',
|
||||||
'about.title': 'About',
|
'about.title': 'About',
|
||||||
'about.tab': 'Info',
|
'about.tab': 'Info',
|
||||||
'about.description': 'A multiplatform Scrabble game.',
|
'about.description': 'A multiplatform Scrabble game.',
|
||||||
|
|||||||
@@ -225,6 +225,33 @@ export const ru: Record<MessageKey, string> = {
|
|||||||
'offline.promptYes': 'Включить',
|
'offline.promptYes': 'Включить',
|
||||||
'offline.promptNo': 'Ждать сеть',
|
'offline.promptNo': 'Ждать сеть',
|
||||||
|
|
||||||
|
// --- wallet ---
|
||||||
|
'wallet.title': 'Кошелёк',
|
||||||
|
'wallet.tab': 'Кошелёк',
|
||||||
|
'wallet.balance': 'Баланс',
|
||||||
|
'wallet.noChips': 'Пока нет фишек',
|
||||||
|
'wallet.source.vk': 'VK',
|
||||||
|
'wallet.source.telegram': 'Telegram',
|
||||||
|
'wallet.source.direct': 'Веб',
|
||||||
|
'wallet.viewOnly': 'просмотр',
|
||||||
|
'wallet.benefits': 'Блага',
|
||||||
|
'wallet.noAdsUntil': 'Без рекламы до {date}',
|
||||||
|
'wallet.noAdsForever': 'Без рекламы навсегда',
|
||||||
|
'wallet.adsOn': 'Реклама включена',
|
||||||
|
'wallet.hints': 'Подсказки {n}',
|
||||||
|
'wallet.store': 'Магазин',
|
||||||
|
'wallet.empty': 'Магазин пока пуст',
|
||||||
|
'wallet.buy': 'Купить',
|
||||||
|
'wallet.soon': 'Скоро',
|
||||||
|
'wallet.gpStub': 'Чтобы покупать фишки, установите версию из RuStore.',
|
||||||
|
'wallet.cur.RUB': '₽',
|
||||||
|
'wallet.cur.VOTE': 'голосов',
|
||||||
|
'wallet.cur.XTR': '⭐',
|
||||||
|
'wallet.warnTitle': 'Покупка только для веба',
|
||||||
|
'wallet.warnBody':
|
||||||
|
'Оплата спишет фишки VK/Telegram, и благо будет работать только в вебе и приложении — из-за правил магазинов.',
|
||||||
|
'wallet.warnConfirm': 'Продолжить',
|
||||||
|
'wallet.warnCancel': 'Отмена',
|
||||||
'about.title': 'О программе',
|
'about.title': 'О программе',
|
||||||
'about.tab': 'Инфо',
|
'about.tab': 'Инфо',
|
||||||
'about.description': 'Мультиплатформенная игра в «Эрудит».',
|
'about.description': 'Мультиплатформенная игра в «Эрудит».',
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ import type {
|
|||||||
Stats,
|
Stats,
|
||||||
Variant,
|
Variant,
|
||||||
WordCheckResult,
|
WordCheckResult,
|
||||||
|
Wallet,
|
||||||
|
Catalog,
|
||||||
} from '../model';
|
} from '../model';
|
||||||
import { valueForLetter } from '../alphabet';
|
import { valueForLetter } from '../alphabet';
|
||||||
import { seedMockAlphabets } from './alphabet';
|
import { seedMockAlphabets } from './alphabet';
|
||||||
@@ -112,10 +114,37 @@ export class MockGateway implements GatewayClient {
|
|||||||
private readonly stats: Stats = { ...MOCK_STATS };
|
private readonly stats: Stats = { ...MOCK_STATS };
|
||||||
private readonly drafts = new Map<string, string>();
|
private readonly drafts = new Map<string, string>();
|
||||||
|
|
||||||
|
// The mock chip wallet: a web/native (direct) context holding a direct and a vk segment, so the
|
||||||
|
// storefront, the priority draw (direct→vk→tg) and the web-spend warning (a value whose price
|
||||||
|
// reaches into the vk segment) are all exercisable without a backend.
|
||||||
|
private readonly mockWallet: Wallet = {
|
||||||
|
segments: [
|
||||||
|
{ source: 'direct', chips: 120, spendable: true },
|
||||||
|
{ source: 'vk', chips: 400, spendable: true },
|
||||||
|
],
|
||||||
|
adsForever: false,
|
||||||
|
adsPaidUntilMs: 0,
|
||||||
|
hints: 5,
|
||||||
|
};
|
||||||
|
// The mock storefront: two chip-priced values (one cheap enough to draw direct only, one that
|
||||||
|
// reaches into vk → the warning) and one RUB-priced chip pack (the direct-context method).
|
||||||
|
private readonly mockCatalog: Catalog = {
|
||||||
|
products: [
|
||||||
|
{ kind: 'value', productId: 'val-hints-50', title: '50 подсказок', chips: 100, moneyAmount: 0, moneyCurrency: '', atoms: [{ atomType: 'hints', quantity: 50 }] },
|
||||||
|
{ kind: 'value', productId: 'val-noads-30', title: 'Без рекламы: 30 дней', chips: 300, moneyAmount: 0, moneyCurrency: '', atoms: [{ atomType: 'noads_days', quantity: 30 }] },
|
||||||
|
{ kind: 'pack', productId: 'pack-chips-100', title: '100 фишек', chips: 0, moneyAmount: 14900, moneyCurrency: 'RUB', atoms: [{ atomType: 'chips', quantity: 100 }] },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
// Seed the per-variant alphabet cache the rack, blank chooser and scoring read, so the
|
// Seed the per-variant alphabet cache the rack, blank chooser and scoring read, so the
|
||||||
// mock-driven UI is alphabet-agnostic without a backend.
|
// mock-driven UI is alphabet-agnostic without a backend.
|
||||||
seedMockAlphabets();
|
seedMockAlphabets();
|
||||||
|
// e2e seam: `?guest` seeds a guest profile so the durable-only surfaces (Friends, Wallet) can
|
||||||
|
// be asserted hidden. The mock profile is otherwise a durable account.
|
||||||
|
if (typeof window !== 'undefined' && new URLSearchParams(window.location.search).has('guest')) {
|
||||||
|
this.profile.isGuest = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setToken(_token: string | null): void {
|
setToken(_token: string | null): void {
|
||||||
@@ -166,6 +195,44 @@ export class MockGateway implements GatewayClient {
|
|||||||
// The mock never blocks; the blocked screen is driven directly via the mock-mode __block seam.
|
// The mock never blocks; the blocked screen is driven directly via the mock-mode __block seam.
|
||||||
return { blocked: false, permanent: false, until: '', reason: '' };
|
return { blocked: false, permanent: false, until: '', reason: '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- wallet ---
|
||||||
|
async wallet(): Promise<Wallet> {
|
||||||
|
return this.cloneWallet();
|
||||||
|
}
|
||||||
|
async catalog(): Promise<Catalog> {
|
||||||
|
return { products: this.mockCatalog.products.map((p) => ({ ...p, atoms: p.atoms.map((a) => ({ ...a })) })) };
|
||||||
|
}
|
||||||
|
async walletBuy(productId: string): Promise<Wallet> {
|
||||||
|
const p = this.mockCatalog.products.find((x) => x.productId === productId);
|
||||||
|
if (!p || p.kind !== 'value') throw new GatewayError('product_not_found');
|
||||||
|
// Draw the chip price across the segments by priority direct→vk→tg, mirroring the backend.
|
||||||
|
let remaining = p.chips;
|
||||||
|
for (const src of ['direct', 'vk', 'telegram'] as const) {
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
const seg = this.mockWallet.segments.find((s) => s.source === src);
|
||||||
|
if (!seg) continue;
|
||||||
|
const take = Math.min(seg.chips, remaining);
|
||||||
|
seg.chips -= take;
|
||||||
|
remaining -= take;
|
||||||
|
}
|
||||||
|
if (remaining > 0) throw new GatewayError('insufficient_chips');
|
||||||
|
for (const a of p.atoms) {
|
||||||
|
if (a.atomType === 'hints') this.mockWallet.hints += a.quantity;
|
||||||
|
if (a.atomType === 'noads_days') {
|
||||||
|
this.mockWallet.adsPaidUntilMs = Math.max(Date.now(), this.mockWallet.adsPaidUntilMs) + a.quantity * 86_400_000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.cloneWallet();
|
||||||
|
}
|
||||||
|
private cloneWallet(): Wallet {
|
||||||
|
return {
|
||||||
|
segments: this.mockWallet.segments.map((s) => ({ ...s })),
|
||||||
|
adsForever: this.mockWallet.adsForever,
|
||||||
|
adsPaidUntilMs: this.mockWallet.adsPaidUntilMs,
|
||||||
|
hints: this.mockWallet.hints,
|
||||||
|
};
|
||||||
|
}
|
||||||
async fetchDict(variant: Variant, _version: string, opts?: { signal?: AbortSignal; reload?: boolean }): Promise<ArrayBuffer> {
|
async fetchDict(variant: Variant, _version: string, opts?: { signal?: AbortSignal; reload?: boolean }): Promise<ArrayBuffer> {
|
||||||
// The offline e2e serves the real per-variant dawgs from the preview build's /e2edict/ (copied
|
// The offline e2e serves the real per-variant dawgs from the preview build's /e2edict/ (copied
|
||||||
// in by scripts/e2e-dict.mjs from the scrabble-dictionary release, never committed), so a local
|
// in by scripts/e2e-dict.mjs from the scrabble-dictionary release, never committed), so a local
|
||||||
|
|||||||
@@ -152,6 +152,50 @@ export interface FeedbackState {
|
|||||||
reply: FeedbackReply | null;
|
reply: FeedbackReply | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One chip balance in the wallet: the funding source, the chip count, and whether it is
|
||||||
|
* spendable in the current execution context (false for a frozen VK-iOS balance or untrusted). */
|
||||||
|
export interface WalletSegment {
|
||||||
|
source: string;
|
||||||
|
chips: number;
|
||||||
|
spendable: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The user-facing wallet: the context-visible chip segments and the context-applicable
|
||||||
|
* benefits (the no-ads term end as unix millis / forever flag, and the available hints). */
|
||||||
|
export interface Wallet {
|
||||||
|
segments: WalletSegment[];
|
||||||
|
adsForever: boolean;
|
||||||
|
/** No-ads term end as unix milliseconds; 0 = no active term. */
|
||||||
|
adsPaidUntilMs: number;
|
||||||
|
hints: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One atom line of a storefront product: the base value type it grants ("chips"/"hints"/
|
||||||
|
* "noads_days"/"tournament") and how many of it the product carries. */
|
||||||
|
export interface CatalogAtom {
|
||||||
|
atomType: string;
|
||||||
|
quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One storefront product for the caller's context. A "value" is bought with chips (chips is its
|
||||||
|
* uniform price, money fields zero); a "pack" funds chips with money (moneyAmount is its price in
|
||||||
|
* the context currency's minor units under moneyCurrency, chips zero). atoms lists what it grants. */
|
||||||
|
export interface CatalogProduct {
|
||||||
|
kind: 'value' | 'pack';
|
||||||
|
productId: string;
|
||||||
|
title: string;
|
||||||
|
chips: number;
|
||||||
|
moneyAmount: number;
|
||||||
|
moneyCurrency: string;
|
||||||
|
atoms: CatalogAtom[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The storefront: the products visible and purchasable in the caller's context — the chip-priced
|
||||||
|
* values and the chip packs priced in the context's payment method. */
|
||||||
|
export interface Catalog {
|
||||||
|
products: CatalogProduct[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface Profile {
|
export interface Profile {
|
||||||
userId: string;
|
userId: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export type RouteName =
|
|||||||
| 'settings'
|
| 'settings'
|
||||||
| 'about'
|
| 'about'
|
||||||
| 'friends'
|
| 'friends'
|
||||||
|
| 'wallet'
|
||||||
| 'feedback'
|
| 'feedback'
|
||||||
| 'stats'
|
| 'stats'
|
||||||
| 'confirm'
|
| 'confirm'
|
||||||
@@ -55,6 +56,8 @@ export function parse(hash: string): Route {
|
|||||||
return { name: 'about', params: {} };
|
return { name: 'about', params: {} };
|
||||||
case 'friends':
|
case 'friends':
|
||||||
return { name: 'friends', params: {} };
|
return { name: 'friends', params: {} };
|
||||||
|
case 'wallet':
|
||||||
|
return { name: 'wallet', params: {} };
|
||||||
case 'feedback':
|
case 'feedback':
|
||||||
return { name: 'feedback', params: {} };
|
return { name: 'feedback', params: {} };
|
||||||
case 'stats':
|
case 'stats':
|
||||||
|
|||||||
@@ -228,6 +228,16 @@ export function createTransport(baseUrl: string): GatewayClient {
|
|||||||
return codec.decodeFeedbackUnread(await exec('feedback.unread', codec.empty()));
|
return codec.decodeFeedbackUnread(await exec('feedback.unread', codec.empty()));
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async wallet() {
|
||||||
|
return codec.decodeWallet(await exec('wallet.get', codec.empty()));
|
||||||
|
},
|
||||||
|
async catalog() {
|
||||||
|
return codec.decodeCatalog(await exec('wallet.catalog', codec.empty()));
|
||||||
|
},
|
||||||
|
async walletBuy(productId: string) {
|
||||||
|
return codec.decodeWallet(await exec('wallet.buy', codec.encodeWalletBuy(productId)));
|
||||||
|
},
|
||||||
|
|
||||||
async friendsList() {
|
async friendsList() {
|
||||||
return codec.decodeFriendList(await exec('friends.list', codec.empty()));
|
return codec.decodeFriendList(await exec('friends.list', codec.empty()));
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import type { Wallet, WalletSegment } from './model';
|
||||||
|
import { majorAmount, formatAmount, spendableChips, needsWebSpendWarning } from './wallet';
|
||||||
|
|
||||||
|
function seg(source: string, chips: number, spendable = true): WalletSegment {
|
||||||
|
return { source, chips, spendable };
|
||||||
|
}
|
||||||
|
|
||||||
|
function wallet(segments: WalletSegment[]): Wallet {
|
||||||
|
return { segments, adsForever: false, adsPaidUntilMs: 0, hints: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('money formatting', () => {
|
||||||
|
it('scales roubles by 100 and leaves whole-unit currencies as-is', () => {
|
||||||
|
expect(majorAmount(14900, 'RUB')).toBe(149);
|
||||||
|
expect(majorAmount(20, 'VOTE')).toBe(20);
|
||||||
|
expect(majorAmount(25, 'XTR')).toBe(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats roubles with two decimals and whole-unit currencies as integers', () => {
|
||||||
|
expect(formatAmount(14900, 'RUB')).toBe('149.00');
|
||||||
|
expect(formatAmount(15050, 'RUB')).toBe('150.50');
|
||||||
|
expect(formatAmount(20, 'VOTE')).toBe('20');
|
||||||
|
expect(formatAmount(25, 'XTR')).toBe('25');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('spendableChips', () => {
|
||||||
|
it('sums only the spendable segments', () => {
|
||||||
|
expect(spendableChips(wallet([seg('direct', 100), seg('vk', 50)]))).toBe(150);
|
||||||
|
expect(spendableChips(wallet([seg('direct', 100, false), seg('vk', 50, false)]))).toBe(0);
|
||||||
|
expect(spendableChips(wallet([seg('direct', 100), seg('vk', 50, false)]))).toBe(100);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('needsWebSpendWarning', () => {
|
||||||
|
it('does not warn when the direct segment alone covers the price', () => {
|
||||||
|
expect(needsWebSpendWarning('direct', [seg('direct', 200), seg('vk', 400)], 150)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('warns when the priority draw reaches into a store (vk/tg) segment', () => {
|
||||||
|
// direct 120 + vk covers the rest of a 300 price → touches vk
|
||||||
|
expect(needsWebSpendWarning('direct', [seg('direct', 120), seg('vk', 400)], 300)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('warns when only a store segment is spendable and it covers the price', () => {
|
||||||
|
expect(needsWebSpendWarning('direct', [seg('vk', 400)], 100)).toBe(true);
|
||||||
|
expect(needsWebSpendWarning('direct', [seg('telegram', 400)], 100)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not warn when the price exceeds all spendable chips (buy is disabled anyway)', () => {
|
||||||
|
expect(needsWebSpendWarning('direct', [seg('direct', 120), seg('vk', 100)], 500)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never warns inside a VK or Telegram context (spend stays in the same store segment)', () => {
|
||||||
|
expect(needsWebSpendWarning('vk', [seg('vk', 400)], 100)).toBe(false);
|
||||||
|
expect(needsWebSpendWarning('telegram', [seg('telegram', 400)], 100)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores non-spendable segments (a frozen or untrusted wallet never warns)', () => {
|
||||||
|
expect(needsWebSpendWarning('direct', [seg('vk', 400, false)], 100)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// Wallet storefront logic, kept pure and out of the .svelte screen so it unit-tests in the node
|
||||||
|
// environment: money/price formatting, the spendable-segment selection, and the web-spend warning
|
||||||
|
// trigger. The server owns the real store-compliance gate; these helpers drive display only.
|
||||||
|
|
||||||
|
import type { Wallet, WalletSegment } from './model';
|
||||||
|
import { insideVK } from './vk';
|
||||||
|
import { insideTelegram } from './telegram';
|
||||||
|
|
||||||
|
/** The client's execution context for the wallet UI, mirroring the server's platform kind. */
|
||||||
|
export type SpendContext = 'vk' | 'telegram' | 'direct';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* executionContext reports the client's best-effort context: a VK Mini App, a Telegram Mini App,
|
||||||
|
* else a web/native (direct) session. It only drives the display-only web-spend warning; the
|
||||||
|
* server enforces the real gate on every spend (fail-closed), never trusting this.
|
||||||
|
*/
|
||||||
|
export function executionContext(): SpendContext {
|
||||||
|
if (insideVK()) return 'vk';
|
||||||
|
if (insideTelegram()) return 'telegram';
|
||||||
|
return 'direct';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* majorAmount converts a money amount in a currency's minor units to its major unit — the rouble
|
||||||
|
* has 100 kopecks; Votes and Stars are whole units (scale 1).
|
||||||
|
*/
|
||||||
|
export function majorAmount(minor: number, currency: string): number {
|
||||||
|
return minor / (currency === 'RUB' ? 100 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* formatAmount renders a money price in major units: two fractional digits for the rouble, a whole
|
||||||
|
* number for the whole-unit currencies (Votes / Stars). The currency label is added by the caller
|
||||||
|
* (it is localized), so this stays a pure number formatter.
|
||||||
|
*/
|
||||||
|
export function formatAmount(minor: number, currency: string): string {
|
||||||
|
return currency === 'RUB' ? (minor / 100).toFixed(2) : String(minor);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* spendableChips totals the chips the player can actually spend in the current context — the sum of
|
||||||
|
* the segments the server marked spendable (zero for a VK-iOS-frozen or untrusted wallet, where no
|
||||||
|
* segment is spendable).
|
||||||
|
*/
|
||||||
|
export function spendableChips(w: Wallet): number {
|
||||||
|
return w.segments.reduce((sum, s) => sum + (s.spendable ? s.chips : 0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawPriority is the segment draw order on the web, mirroring the backend spend: the home direct
|
||||||
|
// segment first, then the store-funded segments.
|
||||||
|
const drawPriority: readonly string[] = ['direct', 'vk', 'telegram'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* needsWebSpendWarning reports whether buying a chip-priced value in the current context would draw
|
||||||
|
* store-funded (vk / telegram) chips — the case the UI must warn about, because the benefit it buys
|
||||||
|
* (origin=direct) is then usable on the web/native only, by the store-compliance rule. It fires only
|
||||||
|
* in a direct context and only when the priority draw (direct→vk→tg) actually reaches a store
|
||||||
|
* segment to cover the price; a spend that the direct segment covers alone, or a spend in a VK/
|
||||||
|
* Telegram context (which stays within the same store segment), never warns.
|
||||||
|
*/
|
||||||
|
export function needsWebSpendWarning(
|
||||||
|
context: SpendContext,
|
||||||
|
segments: WalletSegment[],
|
||||||
|
chipPrice: number,
|
||||||
|
): boolean {
|
||||||
|
if (context !== 'direct') return false;
|
||||||
|
let remaining = chipPrice;
|
||||||
|
let reachesStore = false;
|
||||||
|
for (const src of drawPriority) {
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
const seg = segments.find((s) => s.source === src && s.spendable);
|
||||||
|
if (!seg || seg.chips <= 0) continue;
|
||||||
|
const take = Math.min(seg.chips, remaining);
|
||||||
|
if (src !== 'direct' && take > 0) reachesStore = true;
|
||||||
|
remaining -= take;
|
||||||
|
}
|
||||||
|
return remaining <= 0 && reachesStore;
|
||||||
|
}
|
||||||
@@ -4,15 +4,17 @@
|
|||||||
import Settings from './Settings.svelte';
|
import Settings from './Settings.svelte';
|
||||||
import Profile from './Profile.svelte';
|
import Profile from './Profile.svelte';
|
||||||
import Friends from './Friends.svelte';
|
import Friends from './Friends.svelte';
|
||||||
|
import Wallet from './Wallet.svelte';
|
||||||
import About from './About.svelte';
|
import About from './About.svelte';
|
||||||
import { app } from '../lib/app.svelte';
|
import { app } from '../lib/app.svelte';
|
||||||
import { offlineMode } from '../lib/offline.svelte';
|
import { offlineMode } from '../lib/offline.svelte';
|
||||||
import { t, type MessageKey } from '../lib/i18n/index.svelte';
|
import { t, type MessageKey } from '../lib/i18n/index.svelte';
|
||||||
|
|
||||||
// The Settings hub: a single nav bar + bottom tab bar hosting the Settings / Profile /
|
// The Settings hub: a single nav bar + bottom tab bar hosting the Settings / Profile /
|
||||||
// Friends / About bodies. Tabs switch in place (no navigation), so the back control
|
// Friends / Wallet / About bodies. Tabs switch in place (no navigation), so the back control
|
||||||
// always returns to the lobby. Guests have no social surface, so the Friends tab hides.
|
// always returns to the lobby. Guests have no social surface and no wallet, so the Friends and
|
||||||
type SettingsTab = 'settings' | 'profile' | 'friends' | 'about';
|
// Wallet tabs hide for them.
|
||||||
|
type SettingsTab = 'settings' | 'profile' | 'friends' | 'wallet' | 'about';
|
||||||
let { initialTab = 'settings' }: { initialTab?: SettingsTab } = $props();
|
let { initialTab = 'settings' }: { initialTab?: SettingsTab } = $props();
|
||||||
|
|
||||||
const guest = $derived(app.profile?.isGuest ?? true);
|
const guest = $derived(app.profile?.isGuest ?? true);
|
||||||
@@ -20,21 +22,22 @@
|
|||||||
// the hub is keyed by route in App.svelte, so initialTab is constant for its lifetime.
|
// the hub is keyed by route in App.svelte, so initialTab is constant for its lifetime.
|
||||||
// svelte-ignore state_referenced_locally
|
// svelte-ignore state_referenced_locally
|
||||||
let tab = $state<SettingsTab>(initialTab);
|
let tab = $state<SettingsTab>(initialTab);
|
||||||
// A guest who deep-links to the Friends tab falls back to Settings.
|
// A guest who deep-links to the Friends or Wallet tab (durable-only surfaces) falls back to Settings.
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (guest && tab === 'friends') tab = 'settings';
|
if (guest && (tab === 'friends' || tab === 'wallet')) tab = 'settings';
|
||||||
});
|
});
|
||||||
// Offline mode has no network, so the Profile and Friends surfaces (which read/save over the
|
// Offline mode has no network, so the Profile and Friends surfaces (which read/save over the
|
||||||
// network) are disabled — fall back to Settings if the hub is on one (a deep-link or a live flip).
|
// network) are disabled — fall back to Settings if the hub is on one (a deep-link or a live flip).
|
||||||
// Settings stays reachable: it holds the online/offline toggle.
|
// Settings stays reachable: it holds the online/offline toggle.
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (offlineMode.active && (tab === 'profile' || tab === 'friends')) tab = 'settings';
|
if (offlineMode.active && (tab === 'profile' || tab === 'friends' || tab === 'wallet')) tab = 'settings';
|
||||||
});
|
});
|
||||||
|
|
||||||
const titleKey: Record<SettingsTab, MessageKey> = {
|
const titleKey: Record<SettingsTab, MessageKey> = {
|
||||||
settings: 'settings.title',
|
settings: 'settings.title',
|
||||||
profile: 'profile.title',
|
profile: 'profile.title',
|
||||||
friends: 'friends.title',
|
friends: 'friends.title',
|
||||||
|
wallet: 'wallet.title',
|
||||||
about: 'about.title',
|
about: 'about.title',
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
@@ -46,6 +49,8 @@
|
|||||||
<Profile />
|
<Profile />
|
||||||
{:else if tab === 'friends'}
|
{:else if tab === 'friends'}
|
||||||
<Friends />
|
<Friends />
|
||||||
|
{:else if tab === 'wallet'}
|
||||||
|
<Wallet />
|
||||||
{:else}
|
{:else}
|
||||||
<About />
|
<About />
|
||||||
{/if}
|
{/if}
|
||||||
@@ -63,6 +68,11 @@
|
|||||||
<span class="face"><span class="sq" aria-hidden="true">🤝{#if app.notifications > 0}<span class="badge">{app.notifications}</span>{/if}</span><span class="lbl">{t('friends.title')}</span></span>
|
<span class="face"><span class="sq" aria-hidden="true">🤝{#if app.notifications > 0}<span class="badge">{app.notifications}</span>{/if}</span><span class="lbl">{t('friends.title')}</span></span>
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if !guest}
|
||||||
|
<button class="tab" class:active={tab === 'wallet'} disabled={offlineMode.active} onclick={() => (tab = 'wallet')}>
|
||||||
|
<span class="face"><span class="sq" aria-hidden="true">👛</span><span class="lbl">{t('wallet.tab')}</span></span>
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
<button class="tab" class:active={tab === 'about'} onclick={() => (tab = 'about')}>
|
<button class="tab" class:active={tab === 'about'} onclick={() => (tab = 'about')}>
|
||||||
<span class="face"><span class="sq" aria-hidden="true">ℹ️{#if app.feedbackReplyUnread}<span class="badge">1</span>{/if}</span><span class="lbl">{t('about.tab')}</span></span>
|
<span class="face"><span class="sq" aria-hidden="true">ℹ️{#if app.feedbackReplyUnread}<span class="badge">1</span>{/if}</span><span class="lbl">{t('about.tab')}</span></span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import Modal from '../components/Modal.svelte';
|
||||||
|
import { handleError } from '../lib/app.svelte';
|
||||||
|
import { gateway } from '../lib/gateway';
|
||||||
|
import { t, i18n, type MessageKey } from '../lib/i18n/index.svelte';
|
||||||
|
import { executionContext, formatAmount, needsWebSpendWarning, type SpendContext } from '../lib/wallet';
|
||||||
|
import { isGooglePlayBuild } from '../lib/distribution';
|
||||||
|
import type { Wallet, Catalog, CatalogProduct } from '../lib/model';
|
||||||
|
|
||||||
|
// The Wallet section: the context-visible chip balances, the active benefits, and the storefront.
|
||||||
|
// Values are bought with chips (they work once the player has any); chip packs are bought with
|
||||||
|
// money (the purchase itself arrives with payment intake — here they are shown priced only). On
|
||||||
|
// the Google Play build the money purchases are hidden behind a RuStore stub (store policy), while
|
||||||
|
// spending already-earned chips still works.
|
||||||
|
|
||||||
|
let wallet = $state<Wallet | null>(null);
|
||||||
|
let catalog = $state<Catalog | null>(null);
|
||||||
|
let loading = $state(true);
|
||||||
|
let busy = $state(false);
|
||||||
|
// The value awaiting a web-spend warning confirmation (a spend that would draw vk/tg chips).
|
||||||
|
let warnProduct = $state<CatalogProduct | null>(null);
|
||||||
|
|
||||||
|
const context: SpendContext = executionContext();
|
||||||
|
const gpBuild = isGooglePlayBuild();
|
||||||
|
|
||||||
|
const values = $derived(catalog?.products.filter((p) => p.kind === 'value') ?? []);
|
||||||
|
const packs = $derived(catalog?.products.filter((p) => p.kind === 'pack') ?? []);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
const [w, c] = await Promise.all([gateway.wallet(), gateway.catalog()]);
|
||||||
|
wallet = w;
|
||||||
|
catalog = c;
|
||||||
|
} catch (e) {
|
||||||
|
handleError(e);
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onMount(load);
|
||||||
|
|
||||||
|
function sourceLabel(source: string): string {
|
||||||
|
return t(`wallet.source.${source}` as MessageKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
function currencyLabel(currency: string): string {
|
||||||
|
return t(`wallet.cur.${currency}` as MessageKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
function adsLine(): string {
|
||||||
|
if (!wallet) return '';
|
||||||
|
if (wallet.adsForever) return t('wallet.noAdsForever');
|
||||||
|
if (wallet.adsPaidUntilMs > Date.now()) {
|
||||||
|
const date = new Date(wallet.adsPaidUntilMs).toLocaleDateString(i18n.locale === 'ru' ? 'ru-RU' : 'en-US');
|
||||||
|
return t('wallet.noAdsUntil', { date });
|
||||||
|
}
|
||||||
|
return t('wallet.adsOn');
|
||||||
|
}
|
||||||
|
|
||||||
|
function onBuy(p: CatalogProduct) {
|
||||||
|
if (needsWebSpendWarning(context, wallet?.segments ?? [], p.chips)) {
|
||||||
|
warnProduct = p;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void doBuy(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doBuy(p: CatalogProduct) {
|
||||||
|
warnProduct = null;
|
||||||
|
if (busy) return;
|
||||||
|
busy = true;
|
||||||
|
try {
|
||||||
|
wallet = await gateway.walletBuy(p.productId);
|
||||||
|
} catch (e) {
|
||||||
|
handleError(e);
|
||||||
|
} finally {
|
||||||
|
busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="wallet" data-testid="wallet">
|
||||||
|
<section>
|
||||||
|
<h3>{t('wallet.balance')}</h3>
|
||||||
|
{#if wallet && wallet.segments.length > 0}
|
||||||
|
{#each wallet.segments as s (s.source)}
|
||||||
|
<div class="row">
|
||||||
|
<span class="name">{sourceLabel(s.source)}</span>
|
||||||
|
<span class="value"
|
||||||
|
>🪙 {s.chips}{#if !s.spendable} <span class="muted">({t('wallet.viewOnly')})</span>{/if}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{:else if !loading}
|
||||||
|
<p class="empty">{t('wallet.noChips')}</p>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h3>{t('wallet.benefits')}</h3>
|
||||||
|
<div class="row"><span class="name">{adsLine()}</span></div>
|
||||||
|
<div class="row"><span class="name">{t('wallet.hints', { n: wallet?.hints ?? 0 })}</span></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h3>{t('wallet.store')}</h3>
|
||||||
|
{#each values as p (p.productId)}
|
||||||
|
<div class="row product" data-testid="product" data-kind="value" data-pid={p.productId}>
|
||||||
|
<span class="name">{p.title}</span>
|
||||||
|
<span class="price">🪙 {p.chips}</span>
|
||||||
|
<button class="buy" data-testid="buy" disabled={busy} onclick={() => onBuy(p)}>{t('wallet.buy')}</button>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
|
||||||
|
{#if gpBuild}
|
||||||
|
<p class="stub" data-testid="gp-stub">{t('wallet.gpStub')}</p>
|
||||||
|
{:else}
|
||||||
|
{#each packs as p (p.productId)}
|
||||||
|
<div class="row product" data-testid="product" data-kind="pack" data-pid={p.productId}>
|
||||||
|
<span class="name">{p.title}</span>
|
||||||
|
<span class="price">{formatAmount(p.moneyAmount, p.moneyCurrency)} {currencyLabel(p.moneyCurrency)}</span>
|
||||||
|
<button class="buy" disabled>{t('wallet.soon')}</button>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if !loading && values.length === 0 && (gpBuild || packs.length === 0)}
|
||||||
|
<p class="empty">{t('wallet.empty')}</p>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if warnProduct}
|
||||||
|
<Modal title={t('wallet.warnTitle')} onclose={() => (warnProduct = null)}>
|
||||||
|
<p class="warn-body" data-testid="warn">{t('wallet.warnBody')}</p>
|
||||||
|
<div class="warn-actions">
|
||||||
|
<button class="cancel" onclick={() => (warnProduct = null)}>{t('wallet.warnCancel')}</button>
|
||||||
|
<button class="buy" data-testid="warn-confirm" onclick={() => warnProduct && doBuy(warnProduct)}
|
||||||
|
>{t('wallet.warnConfirm')}</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.wallet {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 18px;
|
||||||
|
padding: var(--pad);
|
||||||
|
}
|
||||||
|
section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.name {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.value,
|
||||||
|
.price {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.muted {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
.buy {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 8px 14px;
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-text);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.buy:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.empty,
|
||||||
|
.stub {
|
||||||
|
margin: 0;
|
||||||
|
padding: 10px 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
.stub {
|
||||||
|
border: 1px dashed var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
}
|
||||||
|
.warn-body {
|
||||||
|
margin: 0 0 14px;
|
||||||
|
}
|
||||||
|
.warn-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.cancel {
|
||||||
|
padding: 8px 14px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in New Issue
Block a user