diff --git a/PLAN.md b/PLAN.md index d1534e9..f345161 100644 --- a/PLAN.md +++ b/PLAN.md @@ -32,7 +32,7 @@ status — without re-deriving decisions. | E0 | Payments data foundation | 1 | DONE | | E1 | Trusted platform signal | 1 | DONE | | E2 | Currency + benefit core | 1 | DONE | -| E3 | Wallet UI | 1 | TODO | +| E3 | Wallet UI | 1 | DONE | | E4 | Durability (PITR) | 2 | TODO | | E5 | Payment intake | 2 | TODO | | E6 | Ads | 2 | TODO | @@ -375,43 +375,72 @@ refactors. The legacy flip is expand-contract: reads move first, DROP much later ## 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 catalog storefront, honouring guest-hidden, GP-stub, and the web-spend warning. +**Backend + wire (catalog read — new).** E2 shipped `wallet.get` / `wallet.buy` (segments + +benefits + a chip spend) but no way to *list* the catalog; the storefront needs one, so E3 adds a +read path following the E2 shape: + +- `payments.Service.Catalog(ctx, cxt)` + `store.loadCatalog` (`internal/payments/{catalog, + store_catalog}.go`) read every **active** product with atoms and prices and project them to the + context (`projectCatalog`, pure + unit-tested): a **value** (no `chips` atom) carries its CHIP + price and shows everywhere; a **chip pack** (`chips` atom) carries the money price for the + context method (`cxt.Kind`: vk→VOTE, telegram→XTR, direct→RUB) and shows only where that method + is priced. Read **uncached** (the catalog is small and rarely edited — unlike the per-account + balances/benefits the read cache fronts). +- REST `GET /api/v1/user/wallet/catalog` (`handleWalletCatalog`, gated by `walletGate`) → + `catalogDTO`; gateway op `wallet.catalog` (`transcode.go` + `encodeCatalog`), `backendclient. + Catalog`; FBS `Catalog`/`CatalogProduct`/`CatalogAtom` (`pkg/fbs/scrabble.fbs`), client + `decodeCatalog`. + **UI (`ui/`).** -- New `'wallet'` tab in `ui/src/screens/SettingsHub.svelte` — `SettingsTab` union, tab - button **between Friends (:65) and About (:66)**, body branch in the `:42-51` switch, - `'wallet'` route in `ui/src/lib/routeparse.ts` + `ui/src/App.svelte`. Reuse the hub's - guest/offline gating. -- `Wallet.svelte` screen: **minimal** — context-available chip balances + active benefits - (no-ads until date, hints count). **No history feed** (PAYMENTS §11 — noise). Storefront: - products from the configurable catalog, prices in chips (values) / per-method (chip packs). +- New `'wallet'` tab in `ui/src/screens/SettingsHub.svelte` — `SettingsTab` union, tab button + **between Friends and About** (guest-hidden like Friends, offline-disabled like Profile/Friends), + body branch, `'wallet'` route in `ui/src/lib/routeparse.ts` + `ui/src/App.svelte`. +- `Wallet.svelte` screen: context-available chip balances + active benefits (no-ads until date / + forever, hints count). **No history feed** (PAYMENTS §11 — noise). Storefront: values priced in + chips (buyable with `wallet.buy`), chip packs priced per method. - **Guest:** section hidden entirely (durable-only). -- **GP build:** purchase CTA replaced by a stub ("install the RuStore build to make - purchases"); rewarded + spending earned chips still work. Detect the GP native build. -- **Web-spend warning:** before spending vk/tg chips in a web/native (direct) context, show - an own `Modal` (not `showPopup` — that eats the user-activation gesture) warning the value - will be web/native-only. -- Extract all logic into `ui/src/lib/*` (unit-testable); keep `.svelte` thin. +- **GP build:** the chip-pack purchases are hidden behind a RuStore stub; spending earned chips on + values still works (PAYMENTS §13). Detected by a build-time flag `VITE_GP_BUILD` + (`ui/src/lib/distribution.ts`), forcible under the mock e2e with `?gp`. +- **Web-spend warning:** before a value spend that would draw vk/tg chips in a direct context, an + own `Modal` (not `showPopup`) warns the benefit will be web/native-only. The context is inferred + client-side (`executionContext` — VK/Telegram/direct); the server enforces the real gate on + `wallet.buy` (fail-closed), so no wallet-DTO change was needed. +- Logic extracted to `ui/src/lib/{wallet,distribution}.ts` (unit-testable); `.svelte` stays thin. + +**Pack purchase is display-only in E3.** Buying a chip pack needs the money order flow, which is +**E5**; here a pack card shows its price with a disabled **"Soon"** action. E5 replaces that with the +launch/order CTA. Value spends are wired now (E2 `wallet.buy`), though a Release-1 durable account +has 0 chips until funding exists (E5/E6), so a real value spend returns insufficient-funds until then. **Tests.** -- unit (vitest): storefront/price formatting, context-available-segment selection, warning - trigger condition. -- UI (Playwright mock, Chromium+WebKit): Wallet renders between Friends/About; guest hides - it; GP stub; warning modal on web vk/tg spend. Mock overlay must stay instant under - `MODE==='mock'` (or it intercepts taps). +- unit (Go): `projectCatalog` context matrix (value everywhere; pack per context method; misconfig + omitted). unit (vitest): money/price formatting, spendable-segment selection, warning trigger, + the GP flag; `decodeCatalog` codec round-trip (mock e2e bypasses the codec). +- integration (`inttest`): `/wallet/catalog` returns active products with the context-correct price + over Postgres; soft-deleted excluded. +- UI (Playwright mock, Chromium+WebKit): Wallet renders between Friends/About; guest hides it + (`?guest` seam); GP stub (`?gp`); warning modal on a vk-drawing web spend, no warning on a + direct-covered spend. Mock overlay stays instant under `MODE==='mock'` (or it intercepts taps). -**Done-criteria.** Owner can review the Wallet on the deployed test contour (visual sign-off -is on the contour, not local); balances/benefits/storefront correct per context; guest/GP/ -warning paths verified. Release 1 is now demonstrable end-to-end via `admin_grant`. +**Done-criteria (met).** Balances/benefits/storefront render per context; guest/GP/warning paths +verified by unit + integration + mock e2e on both engines. **A *populated* contour review depends +on later stages** (no products until the E7 catalog editor, no chip funding until E5/E6, no grant +UI until E7): on the contour E3 shows the correct **empty** wallet/storefront states; the populated +UI is proven by the mock e2e. (This replaces the earlier "demonstrable end-to-end via `admin_grant`" +line — the grant UI is E7.) -**Notes/risks.** No global `.btn`/`.ghost` in `ui/` — style per-component with scoped CSS + -tokens (mirror NewGame `.invite` for a CTA). Svelte whitespace/`$state` naming gotchas -apply. iOS WebView download/gesture caveats are irrelevant here (no file delivery). +**Notes/risks.** No global `.btn`/`.ghost` in `ui/` — styled per-component with scoped CSS + tokens +(mirror NewGame `.invite`). Product titles are single-language catalog data (E0 `product.title`), +shown verbatim; currency/chip words are i18n, counts follow the app's label+number convention (no +noun agreement). Svelte whitespace/`$state` naming gotchas apply. --- @@ -466,7 +495,9 @@ receipts, and refunds. - `POST /api/v1/user/wallet/order` → create `order(pending)` (account/platform/product/ expected amount/origin), return the provider-specific launch payload with `order_id` - threaded in (Robokassa `InvId` / TG `invoice_payload` / VK `item`). + threaded in (Robokassa `InvId` / TG `invoice_payload` / VK `item`). The storefront's chip-pack + card wires its purchase CTA to this here, **replacing the disabled "Soon" placeholder E3 left** + (`ui/src/screens/Wallet.svelte`). - Robokassa + VK **public webhooks**: new edge routes (add to `deploy/caddy/Caddyfile` `@gateway` matcher — or they fall to the landing catch-all), signature/HMAC verified, proxied into a payments intake handler. Match by `order_id`, verify amount, credit diff --git a/backend/README.md b/backend/README.md index 3755184..8b6fc3a 100644 --- a/backend/README.md +++ b/backend/README.md @@ -100,7 +100,10 @@ state, lobby enqueue, chat). The social/account/history operations under `/api/v1/user`: `friends/*` (request/respond/cancel/unfriend, list/incoming, the one-time `code` issue/redeem), `blocks/*`, `invitations/*` (create/accept/decline/cancel/list), `PUT profile`, `email/{request,confirm}`, -`stats`, and `games/:id/gcg` (finished-only). The `internal/notify` hub feeds a +`stats`, `games/:id/gcg` (finished-only), and the payments `wallet` / +`wallet/catalog` (`GET` — the context-visible chip segments + benefits, and the +storefront catalog) / `wallet/buy` (`POST` — a chip spend on a value), served by +`internal/payments` behind the store-compliance gate. The `internal/notify` hub feeds a second listener — `internal/pushgrpc`, a gRPC server (`BACKEND_GRPC_ADDR`) streaming live events (your-turn, opponent-moved, chat, nudge, match-found, notify) to the gateway. The gateway-only `POST /api/v1/internal/push-target` (a user's diff --git a/backend/internal/inttest/payments_catalog_test.go b/backend/internal/inttest/payments_catalog_test.go new file mode 100644 index 0000000..d50bc57 --- /dev/null +++ b/backend/internal/inttest/payments_catalog_test.go @@ -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") + } +} diff --git a/backend/internal/payments/catalog.go b/backend/internal/payments/catalog.go new file mode 100644 index 0000000..abebfff --- /dev/null +++ b/backend/internal/payments/catalog.go @@ -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 +} diff --git a/backend/internal/payments/catalog_test.go b/backend/internal/payments/catalog_test.go new file mode 100644 index 0000000..a243a98 --- /dev/null +++ b/backend/internal/payments/catalog_test.go @@ -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)) + } +} diff --git a/backend/internal/payments/service.go b/backend/internal/payments/service.go index 643b5c0..5a8b177 100644 --- a/backend/internal/payments/service.go +++ b/backend/internal/payments/service.go @@ -54,6 +54,18 @@ func (s *Service) Wallet(ctx context.Context, accountID uuid.UUID, cxt Context, 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). diff --git a/backend/internal/payments/store_catalog.go b/backend/internal/payments/store_catalog.go new file mode 100644 index 0000000..9e0cdc9 --- /dev/null +++ b/backend/internal/payments/store_catalog.go @@ -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 +} diff --git a/backend/internal/server/handlers.go b/backend/internal/server/handlers.go index 7b398be..c704f00 100644 --- a/backend/internal/server/handlers.go +++ b/backend/internal/server/handlers.go @@ -67,8 +67,10 @@ func (s *Server) registerRoutes() { u.GET("/block-status", s.handleBlockStatus) } if s.payments != nil { - // The wallet: the context-visible chip segments + benefits, and a chip spend on a value. + // 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 { diff --git a/backend/internal/server/handlers_wallet.go b/backend/internal/server/handlers_wallet.go index 5d83fef..518e18b 100644 --- a/backend/internal/server/handlers_wallet.go +++ b/backend/internal/server/handlers_wallet.go @@ -45,6 +45,68 @@ func walletDTOFrom(v payments.WalletView) walletDTO { 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) { diff --git a/docs/FUNCTIONAL.md b/docs/FUNCTIONAL.md index bda5ac7..ff7a7ab 100644 --- a/docs/FUNCTIONAL.md +++ b/docs/FUNCTIONAL.md @@ -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 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 A one-line banner under the nav shows short promotional or operational messages to **free diff --git a/docs/FUNCTIONAL_ru.md b/docs/FUNCTIONAL_ru.md index a2ca461..00dc508 100644 --- a/docs/FUNCTIONAL_ru.md +++ b/docs/FUNCTIONAL_ru.md @@ -535,6 +535,25 @@ high-rate флага. С карточки пользователя операт сообщения и вложения показываются защищённо (текст экранируется, вложения отдаются на скачивание, а не рендерятся). +### Кошелёк + +У постоянных (не гостевых) игроков есть **Кошелёк** — вкладка в разделе настроек, между «Друзьями» и +«О программе»; у гостей его нет. Он показывает **фишки** (внутриигровую валюту, разделённую по тому, +где она была пополнена — VK, Telegram или веб), **активные блага** (реклама выключена до даты или +навсегда, и число доступных подсказок) и **магазин**. Что видно и что можно потратить, зависит от +того, **где запущено приложение**, по правилам соответствия магазинам из [`PAYMENTS.md`](PAYMENTS.md): +внутри магазина доступны только его фишки; в открытом вебе — все привязанные, списываются в порядке +веб → VK → Telegram; на VK-iOS баланс показан, но трата заморожена. + +**Магазин** перечисляет **ценности**, покупаемые за фишки (дополнительные подсказки, дни без рекламы), +по фиксированной цене в фишках, одинаковой во всех контекстах, и **наборы фишек**, покупаемые за +настоящие деньги, в валюте текущего контекста (голоса VK, звёзды Telegram или рубли в вебе). Покупка +ценности сразу применяет её благо. Перед покупкой в вебе, которая списала бы фишки VK/Telegram, +приложение **предупреждает**, что благо будет работать только в вебе и в приложении — это правило +магазинов — и просит подтверждения. В сборке для **Google Play** покупки за деньги скрыты за подсказкой +установить сборку из RuStore (правило Google о внутриигровой валюте); трата уже заработанных фишек +по-прежнему работает. Кошелёк **не хранит историю покупок** — только текущие балансы, блага и магазин. + ### Рекламный баннер Однострочный баннер под навбаром показывает короткие рекламные или служебные сообщения **бесплатным diff --git a/gateway/internal/backendclient/api.go b/gateway/internal/backendclient/api.go index b84af7b..1607b67 100644 --- a/gateway/internal/backendclient/api.go +++ b/gateway/internal/backendclient/api.go @@ -396,6 +396,36 @@ func (c *Client) WalletBuy(ctx context.Context, userID, productID string) (Walle 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 // 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. diff --git a/gateway/internal/transcode/encode.go b/gateway/internal/transcode/encode.go index 511d135..b99c973 100644 --- a/gateway/internal/transcode/encode.go +++ b/gateway/internal/transcode/encode.go @@ -107,6 +107,52 @@ func encodeWallet(w backendclient.WalletResp) []byte { 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 { b := flatbuffers.NewBuilder(192) uid := b.CreateString(p.UserID) diff --git a/gateway/internal/transcode/transcode.go b/gateway/internal/transcode/transcode.go index 82c5c74..3b5c76f 100644 --- a/gateway/internal/transcode/transcode.go +++ b/gateway/internal/transcode/transcode.go @@ -53,6 +53,7 @@ const ( MsgFeedbackGet = "feedback.get" MsgFeedbackUnread = "feedback.unread" MsgWalletGet = "wallet.get" + MsgWalletCatalog = "wallet.catalog" MsgWalletBuy = "wallet.buy" ) @@ -108,6 +109,7 @@ func NewRegistry(backend *backendclient.Client, tg TelegramValidator, opts ...Op r.ops[MsgAuthEmailConfirmLink] = Op{Handler: authEmailConfirmLinkHandler(backend)} 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[MsgGameSubmitPlay] = Op{Handler: submitPlayHandler(backend), Auth: true} @@ -308,6 +310,16 @@ func walletHandler(backend *backendclient.Client) Handler { } } +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) diff --git a/gateway/internal/transcode/transcode_test.go b/gateway/internal/transcode/transcode_test.go index 9429423..32a2ca2 100644 --- a/gateway/internal/transcode/transcode_test.go +++ b/gateway/internal/transcode/transcode_test.go @@ -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) { 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":[]}}`)) diff --git a/pkg/fbs/scrabble.fbs b/pkg/fbs/scrabble.fbs index eee3ef8..89e13f5 100644 --- a/pkg/fbs/scrabble.fbs +++ b/pkg/fbs/scrabble.fbs @@ -872,3 +872,30 @@ table Wallet { 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]; +} diff --git a/pkg/fbs/scrabblefb/Catalog.go b/pkg/fbs/scrabblefb/Catalog.go new file mode 100644 index 0000000..b172b59 --- /dev/null +++ b/pkg/fbs/scrabblefb/Catalog.go @@ -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() +} diff --git a/pkg/fbs/scrabblefb/CatalogAtom.go b/pkg/fbs/scrabblefb/CatalogAtom.go new file mode 100644 index 0000000..90364d3 --- /dev/null +++ b/pkg/fbs/scrabblefb/CatalogAtom.go @@ -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() +} diff --git a/pkg/fbs/scrabblefb/CatalogProduct.go b/pkg/fbs/scrabblefb/CatalogProduct.go new file mode 100644 index 0000000..e140660 --- /dev/null +++ b/pkg/fbs/scrabblefb/CatalogProduct.go @@ -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() +} diff --git a/ui/e2e/wallet.spec.ts b/ui/e2e/wallet.spec.ts new file mode 100644 index 0000000..df85476 --- /dev/null +++ b/ui/e2e/wallet.spec.ts @@ -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 { + await page.goto('/'); + await page.getByRole('button', { name: /guest/i }).click(); + await expect(page.getByText('Your turn')).toBeVisible(); +} + +async function openSettings(page: Page): Promise { + 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 { + 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'); +}); diff --git a/ui/scripts/bundle-size.mjs b/ui/scripts/bundle-size.mjs index ab27cb6..9ac7e97 100644 --- a/ui/scripts/bundle-size.mjs +++ b/ui/scripts/bundle-size.mjs @@ -26,10 +26,11 @@ const DIST = 'dist'; // 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 // 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 -// generator and the preload orchestration — still stay in lazy chunks. Scoped CSS lands in the CSS -// chunk, not this JS budget. -const BUDGET = { app: 120, shared: 30, landing: 5 }; +// hashing stay in lazy chunks / are negligible), then to 123 for the Wallet section — its screen, +// storefront logic and the catalog codec load with the always-mounted settings hub (its i18n lands +// in the shared chunk). The heavy parts — the dict loader, the move generator and the preload +// 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 // local file (e.g. the Telegram SDK loaded from a CDN) or is missing. diff --git a/ui/src/App.svelte b/ui/src/App.svelte index 734fd81..c4cbeb6 100644 --- a/ui/src/App.svelte +++ b/ui/src/App.svelte @@ -116,6 +116,8 @@ {:else if router.route.name === 'friends'} + {:else if router.route.name === 'wallet'} + {:else if router.route.name === 'feedback'} {:else if router.route.name === 'stats'} diff --git a/ui/src/gen/fbs/scrabblefb.ts b/ui/src/gen/fbs/scrabblefb.ts index dde13db..df83fb6 100644 --- a/ui/src/gen/fbs/scrabblefb.ts +++ b/ui/src/gen/fbs/scrabblefb.ts @@ -11,6 +11,9 @@ export { BestMoveTile } from './scrabblefb/best-move-tile.js'; export { BestMoveView } from './scrabblefb/best-move-view.js'; export { BlockList } from './scrabblefb/block-list.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 { ChatMessage } from './scrabblefb/chat-message.js'; export { ChatPostRequest } from './scrabblefb/chat-post-request.js'; diff --git a/ui/src/gen/fbs/scrabblefb/catalog-atom.ts b/ui/src/gen/fbs/scrabblefb/catalog-atom.ts new file mode 100644 index 0000000..ca99a53 --- /dev/null +++ b/ui/src/gen/fbs/scrabblefb/catalog-atom.ts @@ -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); +} +} diff --git a/ui/src/gen/fbs/scrabblefb/catalog-product.ts b/ui/src/gen/fbs/scrabblefb/catalog-product.ts new file mode 100644 index 0000000..f0353b4 --- /dev/null +++ b/ui/src/gen/fbs/scrabblefb/catalog-product.ts @@ -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); +} +} diff --git a/ui/src/gen/fbs/scrabblefb/catalog.ts b/ui/src/gen/fbs/scrabblefb/catalog.ts new file mode 100644 index 0000000..b519042 --- /dev/null +++ b/ui/src/gen/fbs/scrabblefb/catalog.ts @@ -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); +} +} diff --git a/ui/src/lib/client.ts b/ui/src/lib/client.ts index a647da3..738466c 100644 --- a/ui/src/lib/client.ts +++ b/ui/src/lib/client.ts @@ -34,6 +34,8 @@ import type { Tile, Variant, WordCheckResult, + Wallet, + Catalog, } from './model'; /** 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(): Promise; + // --- 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; + /** 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; + /** 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; + // --- friends --- friendsList(): Promise; friendsIncoming(): Promise; diff --git a/ui/src/lib/codec.test.ts b/ui/src/lib/codec.test.ts index e6e1561..3ef1a78 100644 --- a/ui/src/lib/codec.test.ts +++ b/ui/src/lib/codec.test.ts @@ -15,6 +15,7 @@ import { decodeOutgoingList, decodeProfile, decodeWallet, + decodeCatalog, encodeWalletBuy, decodeSession, decodeFeedbackState, @@ -72,6 +73,54 @@ describe('codec', () => { 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', () => { const req = fb.ExportUrlRequest.getRootAsExportUrlRequest( new ByteBuffer( diff --git a/ui/src/lib/codec.ts b/ui/src/lib/codec.ts index a197423..38a03c0 100644 --- a/ui/src/lib/codec.ts +++ b/ui/src/lib/codec.ts @@ -40,6 +40,9 @@ import type { Profile, Wallet, WalletSegment, + Catalog, + CatalogProduct, + CatalogAtom, ProfileUpdate, PushEvent, Seat, @@ -388,6 +391,33 @@ export function decodeWallet(buf: Uint8Array): Wallet { }; } +// 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 { const p = fb.Profile.getRootAsProfile(new ByteBuffer(buf)); return { diff --git a/ui/src/lib/distribution.test.ts b/ui/src/lib/distribution.test.ts new file mode 100644 index 0000000..a429e35 --- /dev/null +++ b/ui/src/lib/distribution.test.ts @@ -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); + }); +}); diff --git a/ui/src/lib/distribution.ts b/ui/src/lib/distribution.ts new file mode 100644 index 0000000..e7b10a0 --- /dev/null +++ b/ui/src/lib/distribution.ts @@ -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).VITE_GP_BUILD === '1'; +} diff --git a/ui/src/lib/i18n/en.ts b/ui/src/lib/i18n/en.ts index d665346..8f5f431 100644 --- a/ui/src/lib/i18n/en.ts +++ b/ui/src/lib/i18n/en.ts @@ -225,6 +225,33 @@ export const en = { 'offline.promptYes': 'Enable', '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.tab': 'Info', 'about.description': 'A multiplatform Scrabble game.', diff --git a/ui/src/lib/i18n/ru.ts b/ui/src/lib/i18n/ru.ts index 05ecef9..ed1004c 100644 --- a/ui/src/lib/i18n/ru.ts +++ b/ui/src/lib/i18n/ru.ts @@ -225,6 +225,33 @@ export const ru: Record = { 'offline.promptYes': 'Включить', '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.tab': 'Инфо', 'about.description': 'Мультиплатформенная игра в «Эрудит».', diff --git a/ui/src/lib/mock/client.ts b/ui/src/lib/mock/client.ts index 6f6ebe9..84b5764 100644 --- a/ui/src/lib/mock/client.ts +++ b/ui/src/lib/mock/client.ts @@ -40,6 +40,8 @@ import type { Stats, Variant, WordCheckResult, + Wallet, + Catalog, } from '../model'; import { valueForLetter } from '../alphabet'; import { seedMockAlphabets } from './alphabet'; @@ -112,10 +114,37 @@ export class MockGateway implements GatewayClient { private readonly stats: Stats = { ...MOCK_STATS }; private readonly drafts = new Map(); + // 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() { // Seed the per-variant alphabet cache the rack, blank chooser and scoring read, so the // mock-driven UI is alphabet-agnostic without a backend. 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 { @@ -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. return { blocked: false, permanent: false, until: '', reason: '' }; } + + // --- wallet --- + async wallet(): Promise { + return this.cloneWallet(); + } + async catalog(): Promise { + return { products: this.mockCatalog.products.map((p) => ({ ...p, atoms: p.atoms.map((a) => ({ ...a })) })) }; + } + async walletBuy(productId: string): Promise { + 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 { // 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 diff --git a/ui/src/lib/model.ts b/ui/src/lib/model.ts index 5182f8f..e376f58 100644 --- a/ui/src/lib/model.ts +++ b/ui/src/lib/model.ts @@ -170,6 +170,32 @@ export interface Wallet { 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 { userId: string; displayName: string; diff --git a/ui/src/lib/routeparse.ts b/ui/src/lib/routeparse.ts index b91191d..cb19fc6 100644 --- a/ui/src/lib/routeparse.ts +++ b/ui/src/lib/routeparse.ts @@ -13,6 +13,7 @@ export type RouteName = | 'settings' | 'about' | 'friends' + | 'wallet' | 'feedback' | 'stats' | 'confirm' @@ -55,6 +56,8 @@ export function parse(hash: string): Route { return { name: 'about', params: {} }; case 'friends': return { name: 'friends', params: {} }; + case 'wallet': + return { name: 'wallet', params: {} }; case 'feedback': return { name: 'feedback', params: {} }; case 'stats': diff --git a/ui/src/lib/transport.ts b/ui/src/lib/transport.ts index 0737337..8794deb 100644 --- a/ui/src/lib/transport.ts +++ b/ui/src/lib/transport.ts @@ -228,6 +228,16 @@ export function createTransport(baseUrl: string): GatewayClient { 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() { return codec.decodeFriendList(await exec('friends.list', codec.empty())); }, diff --git a/ui/src/lib/wallet.test.ts b/ui/src/lib/wallet.test.ts new file mode 100644 index 0000000..5c4e0a6 --- /dev/null +++ b/ui/src/lib/wallet.test.ts @@ -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); + }); +}); diff --git a/ui/src/lib/wallet.ts b/ui/src/lib/wallet.ts new file mode 100644 index 0000000..8b079bf --- /dev/null +++ b/ui/src/lib/wallet.ts @@ -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; +} diff --git a/ui/src/screens/SettingsHub.svelte b/ui/src/screens/SettingsHub.svelte index a2934dc..447060a 100644 --- a/ui/src/screens/SettingsHub.svelte +++ b/ui/src/screens/SettingsHub.svelte @@ -4,15 +4,17 @@ import Settings from './Settings.svelte'; import Profile from './Profile.svelte'; import Friends from './Friends.svelte'; + import Wallet from './Wallet.svelte'; import About from './About.svelte'; import { app } from '../lib/app.svelte'; import { offlineMode } from '../lib/offline.svelte'; import { t, type MessageKey } from '../lib/i18n/index.svelte'; // 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 - // always returns to the lobby. Guests have no social surface, so the Friends tab hides. - type SettingsTab = 'settings' | 'profile' | 'friends' | 'about'; + // Friends / Wallet / About bodies. Tabs switch in place (no navigation), so the back control + // always returns to the lobby. Guests have no social surface and no wallet, so the Friends and + // Wallet tabs hide for them. + type SettingsTab = 'settings' | 'profile' | 'friends' | 'wallet' | 'about'; let { initialTab = 'settings' }: { initialTab?: SettingsTab } = $props(); 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. // svelte-ignore state_referenced_locally let tab = $state(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(() => { - 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 // 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. $effect(() => { - if (offlineMode.active && (tab === 'profile' || tab === 'friends')) tab = 'settings'; + if (offlineMode.active && (tab === 'profile' || tab === 'friends' || tab === 'wallet')) tab = 'settings'; }); const titleKey: Record = { settings: 'settings.title', profile: 'profile.title', friends: 'friends.title', + wallet: 'wallet.title', about: 'about.title', }; @@ -46,6 +49,8 @@ {:else if tab === 'friends'} + {:else if tab === 'wallet'} + {:else} {/if} @@ -63,6 +68,11 @@ {t('friends.title')} {/if} + {#if !guest} + + {/if} diff --git a/ui/src/screens/Wallet.svelte b/ui/src/screens/Wallet.svelte new file mode 100644 index 0000000..7ade3db --- /dev/null +++ b/ui/src/screens/Wallet.svelte @@ -0,0 +1,226 @@ + + +
+
+

{t('wallet.balance')}

+ {#if wallet && wallet.segments.length > 0} + {#each wallet.segments as s (s.source)} +
+ {sourceLabel(s.source)} + 🪙 {s.chips}{#if !s.spendable} ({t('wallet.viewOnly')}){/if} +
+ {/each} + {:else if !loading} +

{t('wallet.noChips')}

+ {/if} +
+ +
+

{t('wallet.benefits')}

+
{adsLine()}
+
{t('wallet.hints', { n: wallet?.hints ?? 0 })}
+
+ +
+

{t('wallet.store')}

+ {#each values as p (p.productId)} +
+ {p.title} + 🪙 {p.chips} + +
+ {/each} + + {#if gpBuild} +

{t('wallet.gpStub')}

+ {:else} + {#each packs as p (p.productId)} +
+ {p.title} + {formatAmount(p.moneyAmount, p.moneyCurrency)} {currencyLabel(p.moneyCurrency)} + +
+ {/each} + {/if} + + {#if !loading && values.length === 0 && (gpBuild || packs.length === 0)} +

{t('wallet.empty')}

+ {/if} +
+
+ +{#if warnProduct} + (warnProduct = null)}> +

{t('wallet.warnBody')}

+
+ + +
+
+{/if} + +