From b6c2598710cbc16776a1afa51e1825657307319d Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Fri, 10 Jul 2026 20:25:41 +0200 Subject: [PATCH] feat(offer): live catalog price list in the public offer, served by the render sidecar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Robokassa moderation requires the public offer to list every digital good with its price. Move /offer/ off the static landing container to the render sidecar: it splices the live catalog price list (§4.4) into the owner-edited ui/legal/offer_ru.md and renders it with the shared ui/src/lib/offer.ts — one renderer, no drift, always matching the current catalog with no redeploy. - backend: /api/v1/internal/offer/pricing (internal, off the edge allow-list) projects the active catalog into two markdown tables — chip packs priced per rail (roubles / VK votes / Telegram Stars) and chip-priced values — through payments.Money so no float reaches the page. Cached in memory: warmed at boot, marked stale on every catalog mutation, so a served render issues no query. - renderer: GET /offer/ fetches the tables and substitutes them at the <#pricing_template#> marker, then renders; offer_ru.md is baked into the image and marked is bundled from ui. GET /offer -> 301. Only /offer/ is edge-exposed. - caddy: route /offer/ to the sidecar; drop the now-dead landing /offer/ handlers and the vite emit-offer plugin. - offer: fill §4.3 (the chip-payment wording) and drop the in-page back link. - landing footer: a feedback link (the offer's Telegram contact) beside the offer link. - docs (ARCHITECTURE, FUNCTIONAL +_ru, renderer README), CI /offer/ probe, unit + integration + node tests. --- .gitea/workflows/ci.yaml | 19 ++- backend/cmd/backend/main.go | 7 + .../internal/inttest/payments_catalog_test.go | 42 ++++++ backend/internal/payments/catalog_admin.go | 24 +++- backend/internal/payments/offer.go | 125 ++++++++++++++++++ backend/internal/payments/offer_test.go | 69 ++++++++++ backend/internal/payments/service.go | 8 ++ backend/internal/server/handlers.go | 3 + backend/internal/server/handlers_wallet.go | 16 +++ deploy/caddy/Caddyfile | 9 ++ deploy/docker-compose.yml | 3 + deploy/landing/Caddyfile | 15 +-- docs/ARCHITECTURE.md | 18 ++- docs/FUNCTIONAL.md | 6 +- docs/FUNCTIONAL_ru.md | 7 +- renderer/Dockerfile | 5 +- renderer/README.md | 34 +++-- renderer/build.mjs | 4 + renderer/package.json | 1 + renderer/pnpm-lock.yaml | 10 ++ renderer/src/entry.ts | 11 +- renderer/src/offer.mjs | 17 +++ renderer/src/server.mjs | 51 +++++-- renderer/test/offer.test.mjs | 29 ++++ ui/e2e/landing.spec.ts | 11 +- ui/legal/offer_ru.md | 10 +- ui/src/Landing.svelte | 16 ++- ui/src/lib/i18n/en.ts | 1 + ui/src/lib/i18n/ru.ts | 1 + ui/src/lib/offer.test.ts | 4 +- ui/src/lib/offer.ts | 20 ++- ui/vite.config.ts | 18 --- 32 files changed, 524 insertions(+), 90 deletions(-) create mode 100644 backend/internal/payments/offer.go create mode 100644 backend/internal/payments/offer_test.go create mode 100644 renderer/src/offer.mjs create mode 100644 renderer/test/offer.test.mjs diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 72d5f62..32eda42 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -510,15 +510,20 @@ jobs: - name: Probe the /offer/ public offer page is served run: | set -u - # /offer/ is a static page baked into the landing image (rendered from - # ui/legal/offer_ru.md). If the landing Caddyfile stops routing it, the request - # silently falls through to the landing shell (also 200) — so assert offer-specific - # content, never just the status. + # /offer/ is rendered by the render sidecar: it splices the live catalog price list + # (fetched from the backend's internal endpoint) into the committed ui/legal/offer_ru.md. + # If the @offer caddy route is missing, the request falls to the landing shell (also 200), + # and if the backend fetch fails the sidecar returns 502 — so assert offer-specific content + # (the seller INN, §11) AND that the pricing marker was substituted (proves the fetch + + # splice ran), never just the status. Data-independent: an empty catalog still substitutes + # the marker with nothing, so "pricing_template" must be absent either way. out="$(docker run --rm --network edge alpine:3.20 wget -q -O - http://scrabble/offer/ 2>&1 || true)" - if echo "$out" | grep -q "290210610742"; then - echo "ok: /offer/ serves the public offer page" + if echo "$out" | grep -q "290210610742" && ! echo "$out" | grep -q "pricing_template"; then + echo "ok: /offer/ serves the rendered offer with the price list spliced in" else - echo "FAIL: /offer/ did not serve the offer page (fell through to the landing shell?)" + echo "FAIL: /offer/ did not serve the rendered offer (route fell through, or the price splice failed)" + docker logs --tail 50 scrabble-renderer || true + docker logs --tail 50 scrabble-backend || true docker logs --tail 50 scrabble-landing || true exit 1 fi diff --git a/backend/cmd/backend/main.go b/backend/cmd/backend/main.go index fa2ac40..1d6b3ee 100644 --- a/backend/cmd/backend/main.go +++ b/backend/cmd/backend/main.go @@ -283,6 +283,13 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error { } logger.Info("payments domain ready") + // Warm the public-offer price list cache so /offer/ serves the current catalog from the first + // request; it is reprojected lazily thereafter on any catalog edit. Non-fatal — a transient + // failure here only defers the projection to the first read. + if _, err := paymentsSvc.OfferPricing(ctx); err != nil { + logger.Warn("offer pricing warm failed; will project on first request", zap.Error(err)) + } + // Wire the payments surface into the domains that consume it: the online-game hint wallet // and the account-merge wallet fold. Done after the reachability check so a broken payments // schema fails boot before anything depends on it. diff --git a/backend/internal/inttest/payments_catalog_test.go b/backend/internal/inttest/payments_catalog_test.go index d50bc57..965fc23 100644 --- a/backend/internal/inttest/payments_catalog_test.go +++ b/backend/internal/inttest/payments_catalog_test.go @@ -4,6 +4,7 @@ package inttest import ( "context" + "strings" "testing" "github.com/google/uuid" @@ -111,3 +112,44 @@ func TestPaymentsCatalogExcludesDeactivated(t *testing.T) { t.Error("deactivated product must not appear in the storefront") } } + +// TestOfferPricingReflectsCatalogEdits verifies the public-offer price list (§4.4) is projected from +// the live catalog and its cache is invalidated on a catalog mutation: a newly created pack appears +// with its per-rail prices, and archiving it through the service drops it from the next read. +func TestOfferPricingReflectsCatalogEdits(t *testing.T) { + svc := newPaymentsService() + ctx := context.Background() + title := "OfferTest " + uuid.NewString() + id, err := svc.CreateProduct(ctx, payments.ProductInput{ + Title: title, + Atoms: []payments.AtomLine{{Atom: "chips", Quantity: 50}}, + Prices: []payments.PriceLine{ + {Method: "direct", Currency: payments.CurrencyRUB, Amount: 20000}, + {Method: "vk", Currency: payments.CurrencyVote, Amount: 30}, + {Method: "telegram", Currency: payments.CurrencyStar, Amount: 100}, + }, + }, true) + if err != nil { + t.Fatalf("create pack: %v", err) + } + + md, err := svc.OfferPricing(ctx) + if err != nil { + t.Fatalf("offer pricing: %v", err) + } + if row := "| " + title + " | 200.00 | 30 | 100 |"; !strings.Contains(md, row) { + t.Fatalf("offer pricing missing the new pack row %q\n%s", row, md) + } + + // Archiving through the service marks the cache stale; the next read must reproject without it. + if err := svc.SetProductActive(ctx, id, false); err != nil { + t.Fatalf("archive: %v", err) + } + md, err = svc.OfferPricing(ctx) + if err != nil { + t.Fatalf("offer pricing after archive: %v", err) + } + if strings.Contains(md, title) { + t.Errorf("archived pack must drop from the offer pricing:\n%s", md) + } +} diff --git a/backend/internal/payments/catalog_admin.go b/backend/internal/payments/catalog_admin.go index 999cbfb..401ec98 100644 --- a/backend/internal/payments/catalog_admin.go +++ b/backend/internal/payments/catalog_admin.go @@ -153,7 +153,11 @@ func (s *Service) CreateProduct(ctx context.Context, in ProductInput, active boo if err := validateProduct(in, active); err != nil { return uuid.Nil, err } - return s.store.createProduct(ctx, in, active, s.clock()) + id, err := s.store.createProduct(ctx, in, active, s.clock()) + if err == nil { + s.markOfferStale() + } + return id, err } // UpdateProduct validates and replaces a product's title, atoms and prices. An active product must @@ -166,7 +170,11 @@ func (s *Service) UpdateProduct(ctx context.Context, id uuid.UUID, in ProductInp if err := validateProduct(in, active); err != nil { return err } - return s.store.updateProduct(ctx, id, in, s.clock()) + if err := s.store.updateProduct(ctx, id, in, s.clock()); err != nil { + return err + } + s.markOfferStale() + return nil } // SetProductActive archives (active=false) or unarchives a product. Unarchiving revalidates the @@ -181,11 +189,19 @@ func (s *Service) SetProductActive(ctx context.Context, id uuid.UUID, active boo return err } } - return s.store.setProductActive(ctx, id, active, s.clock()) + if err := s.store.setProductActive(ctx, id, active, s.clock()); err != nil { + return err + } + s.markOfferStale() + return nil } // DeleteProduct hard-deletes a product only when it has never been transacted (no order or ledger // row references it); otherwise it returns ErrProductTransacted and the caller archives instead. func (s *Service) DeleteProduct(ctx context.Context, id uuid.UUID) error { - return s.store.deleteProduct(ctx, id) + if err := s.store.deleteProduct(ctx, id); err != nil { + return err + } + s.markOfferStale() + return nil } diff --git a/backend/internal/payments/offer.go b/backend/internal/payments/offer.go new file mode 100644 index 0000000..6fa7f32 --- /dev/null +++ b/backend/internal/payments/offer.go @@ -0,0 +1,125 @@ +package payments + +import ( + "context" + "fmt" + "strings" +) + +// pricingMarker is the token the owner-edited offer markdown (ui/legal/offer_ru.md, §4.4) carries +// where the price list belongs. The render sidecar replaces it with the markdown [Service.OfferPricing] +// returns before rendering the /offer/ page; the backend only produces the tables, never the marker. +const pricingMarker = "<#pricing_template#>" + +// OfferPricing returns the public-offer price list (§4.4) as two markdown tables projected from the +// active catalog: first the chip packs (funding chips with money, priced per rail — roubles / VK +// votes / Telegram Stars), then the chip-priced values (what a player exchanges chips for). The +// result is cached in memory and reprojected only after a catalog mutation (see [Service.markOfferStale]), +// so a steady-state read issues no query — only the first read after an edit reprojects. The render +// sidecar fetches it and splices it into the offer markdown at the pricing marker. +func (s *Service) OfferPricing(ctx context.Context) (string, error) { + s.offerMu.Lock() + defer s.offerMu.Unlock() + if s.offerFresh { + return s.offerMD, nil + } + md, err := s.buildOfferPricing(ctx) + if err != nil { + return "", err + } + s.offerMD = md + s.offerFresh = true + return md, nil +} + +// markOfferStale marks the cached offer price list for reprojection on the next [Service.OfferPricing] +// read. Every catalog mutation calls it; it takes no I/O, so it never fails the mutation that triggers it. +func (s *Service) markOfferStale() { + s.offerMu.Lock() + s.offerFresh = false + s.offerMu.Unlock() +} + +// buildOfferPricing loads the active catalog and projects it into the offer tables. +func (s *Service) buildOfferPricing(ctx context.Context) (string, error) { + entries, err := s.store.loadCatalog(ctx) + if err != nil { + return "", err + } + return projectOfferPricing(entries), nil +} + +// projectOfferPricing renders the active catalog into the two offer tables. A chip pack (it carries +// the chips atom) lists its per-rail money price; a value (no chips atom) lists its uniform chip +// price. Rows keep the catalog's creation order. An empty section is omitted. Amounts are rendered +// through [Money] so no floating point ever reaches the page (roubles show kopecks as "200.00", +// whole-unit rails as integers); a missing rail price shows an em dash. +func projectOfferPricing(entries []catalogEntry) string { + var packs, values []string + for _, e := range entries { + if isPackEntry(e) { + packs = append(packs, fmt.Sprintf("| %s | %s | %s | %s |", + offerCell(e.title), + offerPrice(e, string(SourceDirect), CurrencyRUB), + offerPrice(e, string(SourceVK), CurrencyVote), + offerPrice(e, string(SourceTelegram), CurrencyStar), + )) + } else { + values = append(values, fmt.Sprintf("| %s | %s |", + offerCell(e.title), offerPrice(e, "", CurrencyChip))) + } + } + + var b strings.Builder + if len(packs) > 0 { + b.WriteString("Приобретение внутриигровой валюты «Фишка»:\n\n") + b.WriteString("| Наименование | Рубли | Голоса в VK | Stars в Telegram |\n") + b.WriteString("| --- | --- | --- | --- |\n") + b.WriteString(strings.Join(packs, "\n")) + b.WriteString("\n") + } + if len(values) > 0 { + if len(packs) > 0 { + b.WriteString("\n") + } + b.WriteString("Использование внутриигровой валюты «Фишка»:\n\n") + b.WriteString("| Наименование | «Фишки» |\n") + b.WriteString("| --- | --- |\n") + b.WriteString(strings.Join(values, "\n")) + b.WriteString("\n") + } + return strings.TrimRight(b.String(), "\n") +} + +// isPackEntry reports whether the catalog entry is a chip pack — it carries the chips atom (funds +// chips with money) rather than being a chip-priced value. +func isPackEntry(e catalogEntry) bool { + for _, a := range e.atoms { + if a.atomType == atomChips { + return true + } + } + return false +} + +// offerPrice formats the entry's price for the given payment method and currency as a major-unit +// string, or an em dash when the entry carries no such price. +func offerPrice(e catalogEntry, method string, cur Currency) string { + for _, pr := range e.prices { + if pr.method == method && pr.currency == cur { + m, err := MoneyFromMinor(pr.amount, pr.currency) + if err != nil { + return "—" + } + return m.Major() + } + } + return "—" +} + +// offerCell escapes an owner-entered title for a markdown table cell: a literal pipe would break the +// column layout, and a newline would break the row. +func offerCell(s string) string { + s = strings.ReplaceAll(s, "\n", " ") + return strings.ReplaceAll(s, "|", "\\|") +} diff --git a/backend/internal/payments/offer_test.go b/backend/internal/payments/offer_test.go new file mode 100644 index 0000000..f387ae1 --- /dev/null +++ b/backend/internal/payments/offer_test.go @@ -0,0 +1,69 @@ +package payments + +import ( + "strings" + "testing" + + "github.com/google/uuid" +) + +// TestProjectOfferPricing checks the happy path: a chip pack priced on every rail and a chip-priced +// value render into the two tables, pack table first, money formatted through Money. +func TestProjectOfferPricing(t *testing.T) { + entries := []catalogEntry{ + { + id: uuid.New(), + title: "50 «Фишек»", + atoms: []atomQty{{atomType: atomChips, quantity: 50}}, + prices: []priceRow{ + {method: string(SourceDirect), currency: CurrencyRUB, amount: 20000}, + {method: string(SourceVK), currency: CurrencyVote, amount: 30}, + {method: string(SourceTelegram), currency: CurrencyStar, amount: 100}, + }, + }, + { + id: uuid.New(), + title: "200 подсказок", + atoms: []atomQty{{atomType: "hints", quantity: 200}}, + prices: []priceRow{{method: "", currency: CurrencyChip, amount: 50}}, + }, + } + md := projectOfferPricing(entries) + for _, want := range []string{ + "| Наименование | Рубли | Голоса в VK | Stars в Telegram |", + "| 50 «Фишек» | 200.00 | 30 | 100 |", + "| Наименование | «Фишки» |", + "| 200 подсказок | 50 |", + } { + if !strings.Contains(md, want) { + t.Errorf("projection missing %q\n---\n%s", want, md) + } + } + if strings.Index(md, "Приобретение") > strings.Index(md, "Использование") { + t.Errorf("the pack table must precede the values table:\n%s", md) + } +} + +// TestProjectOfferPricingMissingRailAndEscaping checks a pack missing a rail shows an em dash and a +// title carrying a pipe is escaped so the table layout survives. +func TestProjectOfferPricingMissingRailAndEscaping(t *testing.T) { + entries := []catalogEntry{{ + id: uuid.New(), + title: "Bonus | pack", + atoms: []atomQty{{atomType: atomChips, quantity: 10}}, + // A roubles price only — no VK, no Telegram. + prices: []priceRow{{method: string(SourceDirect), currency: CurrencyRUB, amount: 9900}}, + }} + md := projectOfferPricing(entries) + if want := `| Bonus \| pack | 99.00 | — | — |`; !strings.Contains(md, want) { + t.Errorf("want row %q in:\n%s", want, md) + } +} + +// TestProjectOfferPricingEmpty checks an empty catalog projects to the empty string (no stray table +// headers), so the offer's pricing marker is replaced with nothing. +func TestProjectOfferPricingEmpty(t *testing.T) { + if got := projectOfferPricing(nil); got != "" { + t.Errorf("empty catalog must project to empty string, got %q", got) + } +} diff --git a/backend/internal/payments/service.go b/backend/internal/payments/service.go index a0c55ee..cfab16f 100644 --- a/backend/internal/payments/service.go +++ b/backend/internal/payments/service.go @@ -5,6 +5,7 @@ import ( "database/sql" "encoding/json" "fmt" + "sync" "time" "github.com/google/uuid" @@ -19,6 +20,13 @@ import ( type Service struct { store *Store clock func() time.Time + + // offerMu guards the cached public-offer price list (§4.4). offerMD holds the projected + // markdown tables and offerFresh whether they are current; a catalog mutation clears offerFresh + // (markOfferStale) and the next OfferPricing read reprojects, so a served render issues no query. + offerMu sync.Mutex + offerMD string + offerFresh bool } // NewService constructs a Service over store with a wall-clock time source. diff --git a/backend/internal/server/handlers.go b/backend/internal/server/handlers.go index 197e764..2e3f114 100644 --- a/backend/internal/server/handlers.go +++ b/backend/internal/server/handlers.go @@ -74,6 +74,9 @@ func (s *Server) registerRoutes() { u.POST("/wallet/buy", s.handleWalletBuy) // A rewarded-video credit (VK ads): client-attested + a config daily cap. u.POST("/wallet/reward", s.handleWalletReward) + // The public-offer price list (§4.4) as markdown, for the render sidecar that serves the + // /offer/ page. Internal (off the edge allow-list); called by the renderer, not the gateway. + s.internal.GET("/offer/pricing", s.handleOfferPricing) } if s.payments != nil { // The money order endpoint dispatches by rail (direct → Robokassa, vk → VK); an diff --git a/backend/internal/server/handlers_wallet.go b/backend/internal/server/handlers_wallet.go index 89f68e7..0424086 100644 --- a/backend/internal/server/handlers_wallet.go +++ b/backend/internal/server/handlers_wallet.go @@ -112,6 +112,22 @@ func (s *Server) handleWalletCatalog(c *gin.Context) { c.JSON(http.StatusOK, catalogDTOFrom(view)) } +// handleOfferPricing serves the public-offer price list (§4.4) as markdown — the two catalog tables +// projected from the active products. The render sidecar fetches it and splices it into the offer +// markdown before rendering the /offer/ page. Internal, non-public: the /api/v1/internal group is +// off the edge allow-list, and the value is served from the payments cache (no per-request query in +// the steady state). Called by the renderer, not the gateway. +func (s *Server) handleOfferPricing(c *gin.Context) { + md, err := s.payments.OfferPricing(c.Request.Context()) + if err != nil { + s.log.Error("offer pricing projection failed", zap.Error(err)) + c.String(http.StatusInternalServerError, "offer pricing unavailable") + return + } + c.Header("Content-Type", "text/markdown; charset=utf-8") + c.String(http.StatusOK, md) +} + // handleWallet returns the caller's wallet — the segments and benefits visible in the current // trusted execution context, plus the rewarded-video payout available here (0 outside VK or when // unconfigured), which gates the client's "watch for chips" button. diff --git a/deploy/caddy/Caddyfile b/deploy/caddy/Caddyfile index 1b19493..8a9ab64 100644 --- a/deploy/caddy/Caddyfile +++ b/deploy/caddy/Caddyfile @@ -107,6 +107,15 @@ } } + # The public offer page is rendered by the render sidecar: it splices the live catalog price + # list (backend, internal) into the committed ui/legal/offer_ru.md and returns the HTML. Only + # /offer/ is exposed here — the sidecar's /render stays off this allow-list, internal-only. Kept + # disjoint from the landing/app paths so the catch-all below never shadows it. + @offer path /offer /offer/* + handle @offer { + reverse_proxy renderer:8090 + } + # Everything else — the public landing at / and any stray path — is static. handle { reverse_proxy landing:80 diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index fe508ba..cb61d2b 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -84,6 +84,9 @@ services: logging: *default-logging environment: RENDERER_PORT: "8090" + # The offer page (GET /offer/) fetches the live catalog price list from the backend's internal + # endpoint and splices it into the committed offer markdown. Backend down ⇒ /offer/ returns 502. + RENDERER_BACKEND_URL: http://backend:8080 healthcheck: test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8090/healthz').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] interval: 10s diff --git a/deploy/landing/Caddyfile b/deploy/landing/Caddyfile index d8747b7..4a3d66a 100644 --- a/deploy/landing/Caddyfile +++ b/deploy/landing/Caddyfile @@ -18,18 +18,9 @@ @shell not path /assets/* header @shell Cache-Control "no-cache" - # The static public offer page, rendered from ui/legal/offer_ru.md at build - # time into dist/offer/index.html (vite emit-offer plugin). Served with its own - # index so /offer/ resolves to /srv/offer/index.html rather than falling to the - # landing shell below (whose index is landing.html). A bare /offer redirects in. - handle /offer { - redir * /offer/ permanent - } - handle /offer/* { - file_server { - index index.html - } - } + # The public offer page (/offer/) is no longer served here: the contour caddy routes it to the + # render sidecar, which splices the live catalog price list into ui/legal/offer_ru.md. This + # container never sees /offer/, so it carries no offer assets (the vite emit-offer plugin is gone). # An unknown path falls back to the landing shell (the gateway's old "/" # behaviour); "/" itself resolves through the index below. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 540f210..948df6a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -909,6 +909,17 @@ finished journal on each GET. The only degraded platform is a legacy Telegram cl predating `downloadFile`, where the GCG falls back to the old clipboard copy and the image option is not offered. +The same sidecar also serves the **public offer page** at `/offer/` — the one edge-exposed +route on it (caddy routes `/offer/` here; its `/render` stays internal). It reuses the shared +`ui/src/lib/offer.ts` renderer (again one renderer, no drift) over the owner-edited +`ui/legal/offer_ru.md`, baked into the image, splicing in the **live price list** (§4.4): it +fetches the two catalog tables as markdown from the backend's internal +`/api/v1/internal/offer/pricing` at the `<#pricing_template#>` marker, then renders the page. The +backend projects the tables from the active catalog through `payments.Money` (no float reaches the +page) and caches them in memory — built at boot, reprojected on any catalog edit — so a served +render issues no query in the steady state and the page always reflects the current catalog without +a redeploy. A backend outage degrades `/offer/` to a 502 rather than a stale price list. + The alphabet-on-the-wire transport does **not** touch this invariant: the live edge exchanges alphabet indices, but the persisted journal (and everything derived from it — replay, history, GCG) keeps the decoded concrete letters described above, so an archived @@ -1349,9 +1360,10 @@ in-process (the distroless image has no `/etc/mime.types`). Hash-named `/assets/ in-compose **caddy** is the contour's edge: it owns a single `/_gm` Basic-Auth and routes `/_gm/grafana/*` to **Grafana** (anonymous-admin, so the one shared login gates it with no per-user Grafana accounts) and the rest of `/_gm/*` to the backend-rendered -**admin console**; `/app/`, `/telegram/`, `/vk/` and the Connect path go to the gateway; the -catch-all — notably the landing at `/`, plus the static public offer at `/offer/` -(rendered from `ui/legal/offer_ru.md` at build time) — goes to the landing container. The +**admin console**; `/app/`, `/telegram/`, `/vk/` and the Connect path go to the gateway; `/offer/` +(the public offer, rendered by the `renderer` sidecar with the live catalog price list spliced in) +goes to the render sidecar; and the catch-all — notably the landing at `/` — goes to the landing +container. The **Telegram validator** runs as a separate container with **no public ingress**, answering only internal gRPC (HMAC, no Telegram egress). The **Telegram bot** holds no inbound port either: it dials the gateway's **bot-link** (mTLS) and egresses to diff --git a/docs/FUNCTIONAL.md b/docs/FUNCTIONAL.md index d93dc5e..5da59fe 100644 --- a/docs/FUNCTIONAL.md +++ b/docs/FUNCTIONAL.md @@ -30,7 +30,11 @@ render with arbitrary languages, so detection would make the indexed content nondeterministic); a saved 🌐 choice still wins. The page carries a static Russian SEO head (title/description, the Open Graph card Telegram/VK link previews use, a canonical link pinned to the production origin, JSON-LD, the favicon set and `robots.txt`), while the SPA -shell is `noindex` — the landing is the only indexable page. +shell is `noindex` — the landing is the only indexable page. The footer links to the **public +offer** (`/offer/`) and, beside it, **feedback** — the Telegram bot the offer names as the seller's +contact. The offer page (the legal document a purchase accepts) is rendered on demand from +`ui/legal/offer_ru.md` with its **price list** (§4.4) generated from the live product catalog, so +the published prices always match what is currently on sale — no redeploy to update them. On the plain web the client is an **installable PWA**: a logged-out player sees an install call-to-action under the login form (and at the bottom of Settings) that installs the app to the diff --git a/docs/FUNCTIONAL_ru.md b/docs/FUNCTIONAL_ru.md index 7e27cf5..c39dd0c 100644 --- a/docs/FUNCTIONAL_ru.md +++ b/docs/FUNCTIONAL_ru.md @@ -32,7 +32,12 @@ top-1 подсказку, безлимитную проверку слова с главнее. Страница несёт статическую русскую SEO-«шапку» (title/description, карточка Open Graph, которую используют превью ссылок в Telegram/VK, канонический адрес продакшен-домена, JSON-LD, набор favicon и `robots.txt`), а оболочка SPA помечена -`noindex` — индексируется только посадочная страница. +`noindex` — индексируется только посадочная страница. В подвале — ссылки на **публичную +оферту** (`/offer/`) и рядом на **обратную связь** (тот самый Telegram-бот, который оферта +указывает как контакт Продавца). Страница оферты (юридический документ, который принимается при +покупке) рендерится по запросу из `ui/legal/offer_ru.md`, а её **перечень стоимости** (§4.4) +формируется из живого каталога товаров, поэтому опубликованные цены всегда совпадают с тем, что +сейчас в продаже — без передеплоя. В обычном вебе клиент — **устанавливаемое PWA**: незалогиненный игрок видит призыв к установке под формой входа (и внизу «Настроек»), который в один тап ставит приложение на рабочий стол diff --git a/renderer/Dockerfile b/renderer/Dockerfile index d083897..65905a7 100644 --- a/renderer/Dockerfile +++ b/renderer/Dockerfile @@ -23,7 +23,10 @@ ENV APP_VERSION=${VERSION} WORKDIR /app COPY --from=build /src/renderer/node_modules ./node_modules COPY --from=build /src/renderer/dist ./dist -COPY renderer/src/server.mjs renderer/src/render.mjs ./src/ +COPY renderer/src/server.mjs renderer/src/render.mjs renderer/src/offer.mjs ./src/ +# The public-offer prose (GET /offer/): the owner-edited markdown, read once at boot. The dynamic +# price list is fetched from the backend at request time and spliced in. +COPY ui/legal/offer_ru.md ./legal/offer_ru.md USER node EXPOSE 8090 CMD ["node", "src/server.mjs"] diff --git a/renderer/README.md b/renderer/README.md index 79a25e4..a219e1a 100644 --- a/renderer/README.md +++ b/renderer/README.md @@ -1,10 +1,10 @@ -# renderer — the finished-game image-render sidecar +# renderer — the render sidecar (finished-game image + public offer page) -An internal-only Node service that rasterizes the finished-game export PNG. It runs the -**same** `ui/src/lib/gameimage.ts` the web project unit-tests — bundled verbatim at image -build time (`src/entry.ts` → esbuild → `dist/gameimage.mjs`) — on -[skia-canvas](https://github.com/samizdatco/skia-canvas), so the server render is -pixel-identical to the design the owner signed off in the browser. +An internal Node service that runs shared `ui/src/lib` renderers server-side — bundled verbatim at +image build time (`src/entry.ts` → esbuild → `dist/gameimage.mjs`) so there is one renderer and no +drift from the browser. It serves two surfaces: the finished-game export **PNG** (on +[skia-canvas](https://github.com/samizdatco/skia-canvas), pixel-identical to the design the owner +signed off) and the public **offer page**. ## Interface @@ -12,20 +12,30 @@ pixel-identical to the design the owner signed off in the browser. `image/png`. `game`/`moves` are the ui-model shapes (`GameView` / `MoveRecord[]`); `alphabet` is the per-variant `(index, letter, value)` table tile values are drawn from; `labels` localizes the non-play moves (pass/exchange/resign/timeout); - `hostname` + `dateLocale` feed the footer. + `hostname` + `dateLocale` feed the footer. Internal-only. +- `GET /offer/` — the public offer page as `text/html`: the owner-edited `ui/legal/offer_ru.md` + (baked into the image, read at boot) with the live catalog **price list** (§4.4) fetched as + markdown from the backend's internal `/api/v1/internal/offer/pricing` (`RENDERER_BACKEND_URL`) + and spliced in at the `<#pricing_template#>` marker, then rendered by the shared + `ui/src/lib/offer.ts`. `GET /offer` → 301 `/offer/`. **The only edge-exposed route** — caddy + routes `/offer/` here; a backend outage yields a 502, never a stale price list. - `GET /healthz` — liveness (the compose healthcheck the backend's `depends_on` gates on). -The service draws and nothing else: authentication, the participant check and the signed -public download URL all live in the backend (`backend/internal/server/export.go`); the -network path is client → gateway `/dl/*` → backend → this sidecar. +The service renders and nothing else: for the PNG, authentication, the participant check and the +signed public download URL all live in the backend (`backend/internal/server/export.go`), the path +being client → gateway `/dl/*` → backend → this sidecar; for the offer, the catalog projection and +its cache live in the backend (`backend/internal/payments/offer.go`) and no user input reaches the +page. ## Development ```sh pnpm install # skia-canvas + esbuild MUST stay approved in pnpm-workspace.yaml # (allowBuilds) or the native binary is silently never fetched -pnpm test # bundles, then node --test against testdata/request.json -node src/server.mjs # local run on :8090 (RENDERER_PORT overrides) +pnpm test # bundles, then node --test (PNG smoke + offer splice) +# local run on :8090 (RENDERER_PORT overrides). For /offer/, point at the offer source and a +# reachable backend (else the boot read / the price fetch fail): +RENDERER_OFFER_MD=../ui/legal/offer_ru.md RENDERER_BACKEND_URL=http://localhost:8080 node src/server.mjs ``` The runtime image (`renderer/Dockerfile`, `node:22-slim`) bakes in Liberation Sans (the diff --git a/renderer/build.mjs b/renderer/build.mjs index 23423c6..775e6ef 100644 --- a/renderer/build.mjs +++ b/renderer/build.mjs @@ -9,5 +9,9 @@ await build({ format: 'esm', platform: 'node', outfile: 'dist/gameimage.mjs', + // The shared ui/src/lib modules are copied without their node_modules, so a bare npm import they + // make (offer.ts → 'marked', the offer renderer's markdown parser) is not resolvable from the ui + // tree. NODE_PATH-style fallback to the renderer's own node_modules, where marked is a dependency. + nodePaths: ['node_modules'], logLevel: 'info', }); diff --git a/renderer/package.json b/renderer/package.json index c791dfd..428754f 100644 --- a/renderer/package.json +++ b/renderer/package.json @@ -9,6 +9,7 @@ "test": "pnpm run bundle && node --test test/*.test.mjs" }, "dependencies": { + "marked": "^18.0.5", "skia-canvas": "^3.0.6" }, "devDependencies": { diff --git a/renderer/pnpm-lock.yaml b/renderer/pnpm-lock.yaml index 32027d3..0425c84 100644 --- a/renderer/pnpm-lock.yaml +++ b/renderer/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + marked: + specifier: ^18.0.5 + version: 18.0.6 skia-canvas: specifier: ^3.0.6 version: 3.0.8 @@ -209,6 +212,11 @@ packages: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} + marked@18.0.6: + resolution: {integrity: sha512-MrV5puXBfuiy6wl6DLaq3BtIJQAJToAd5zt/ZKhRfGRAuFPALE7/4Y7jnxRQoEgK/pBgurGqLyAuRgZ2xOjr6w==} + engines: {node: '>= 20'} + hasBin: true + ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -347,6 +355,8 @@ snapshots: transitivePeerDependencies: - supports-color + marked@18.0.6: {} + ms@2.1.3: {} parenthesis@3.1.8: {} diff --git a/renderer/src/entry.ts b/renderer/src/entry.ts index 2b1a954..2e6c8e0 100644 --- a/renderer/src/entry.ts +++ b/renderer/src/entry.ts @@ -1,6 +1,9 @@ -// The esbuild bundle entry: re-exports the SHARED game-image renderer from ui/src/lib — -// the exact module the browser build unit-tests — plus the alphabet cache seeder the -// server fills from the backend-supplied per-variant table. Bundled by `pnpm run bundle` -// into dist/gameimage.mjs (type erasure only; the ui project type-checks the source). +// The esbuild bundle entry: re-exports the SHARED ui/src/lib modules — the exact modules the +// browser build unit-tests — so the sidecar runs them on the server. Bundled by `pnpm run bundle` +// into dist/gameimage.mjs (type erasure only; the ui project type-checks the source): +// - drawGameImage + setAlphabet: the finished-game PNG export (POST /render). +// - renderOfferHtml: the public-offer page (GET /offer/) — the same renderer the landing build +// used to invoke, now server-side so the live catalog price list can be spliced in. export { drawGameImage, type RenderOptions } from '../../ui/src/lib/gameimage'; export { setAlphabet } from '../../ui/src/lib/alphabet'; +export { renderOfferHtml } from '../../ui/src/lib/offer'; diff --git a/renderer/src/offer.mjs b/renderer/src/offer.mjs new file mode 100644 index 0000000..f464d6f --- /dev/null +++ b/renderer/src/offer.mjs @@ -0,0 +1,17 @@ +// The public-offer page renderer: splices the live catalog price list into the owner-edited offer +// markdown and renders it with the SAME renderOfferHtml the landing build used to invoke (bundled +// from ui/src/lib/offer). Kept out of server.mjs so the substitution is unit-testable without HTTP. +import { renderOfferHtml } from '../dist/gameimage.mjs'; + +// pricingMarker is the token ui/legal/offer_ru.md carries at §4.4 where the price list belongs. It +// mirrors the backend marker (backend/internal/payments/offer.go) and is replaced with the fetched +// tables before rendering. +export const pricingMarker = '<#pricing_template#>'; + +// renderOffer returns the standalone /offer/ HTML: the offer markdown with the pricing marker +// replaced by pricingTables (the two markdown tables the backend projects from the active catalog), +// rendered to a self-contained document. The replacement is literal (a function replacer) so a "$" +// in a product title is never read as a replacement pattern; a missing marker leaves the text as is. +export function renderOffer(offerMarkdown, pricingTables) { + return renderOfferHtml(offerMarkdown.replace(pricingMarker, () => pricingTables)); +} diff --git a/renderer/src/server.mjs b/renderer/src/server.mjs index 84ea98c..bd0edac 100644 --- a/renderer/src/server.mjs +++ b/renderer/src/server.mjs @@ -1,20 +1,43 @@ -// The render sidecar: a minimal internal HTTP service the backend calls to rasterize the -// finished-game export image. It runs the same drawGameImage the browser build ships -// (bundled from ui/src/lib at image build time) on skia-canvas, with system fonts from -// the image (Liberation Sans + Noto Color Emoji via fontconfig). +// The render sidecar: a minimal internal HTTP service on skia-canvas and the shared ui/src/lib +// renderers (bundled from ui/src/lib at image build time). It serves two surfaces: // // POST /render {game, moves, alphabet, labels, dateLocale, hostname, scale?} → image/png +// GET /offer/ → text/html (the public offer page: ui/legal/offer_ru.md with the live catalog +// price list spliced in — the only edge-exposed route; caddy routes /offer/ here) +// GET /offer → 301 /offer/ // GET /healthz → 200 // -// The service is internal-only (docker network `internal`); authentication, participant -// checks and the signed public URL all live in the backend — this process only draws. +// /render is internal-only (the backend calls it; authentication, participant checks and the signed +// public URL live in the backend). /offer/ is reachable from the edge but read-only and unprivileged +// — it fetches the price list from the backend's internal endpoint and renders the committed offer +// markdown; no user input reaches it. import { createServer } from 'node:http'; +import { readFileSync } from 'node:fs'; import { renderRequest } from './render.mjs'; +import { renderOffer } from './offer.mjs'; const PORT = Number(process.env.RENDERER_PORT || 8090); // A render request is a finished game's journal — generously capped. const MAX_BODY = 2 * 1024 * 1024; +// The offer prose is baked into the image (renderer/Dockerfile) and read once at boot; only the +// price list is dynamic (fetched per request). The backend endpoint is internal (off the edge +// allow-list) and serves the tables from its in-memory cache. RENDERER_OFFER_MD overrides the baked +// path for a local run (point it at ../ui/legal/offer_ru.md). +const OFFER_MD = readFileSync(process.env.RENDERER_OFFER_MD || new URL('../legal/offer_ru.md', import.meta.url), 'utf8'); +const OFFER_PRICING_URL = + (process.env.RENDERER_BACKEND_URL || 'http://backend:8080') + '/api/v1/internal/offer/pricing'; + +// fetchOfferPricing returns the two catalog price tables as markdown from the backend, or throws a +// 502 (upstream error) / 504 (timeout) so the offer never renders with a broken price list. +async function fetchOfferPricing() { + const resp = await fetch(OFFER_PRICING_URL, { signal: AbortSignal.timeout(5000) }); + if (!resp.ok) { + throw Object.assign(new Error(`offer pricing upstream ${resp.status}`), { status: 502 }); + } + return resp.text(); +} + function readBody(req) { return new Promise((resolve, reject) => { const chunks = []; @@ -35,11 +58,23 @@ function readBody(req) { const server = createServer(async (req, res) => { try { - if (req.method === 'GET' && req.url === '/healthz') { + const path = (req.url || '').split('?')[0]; + if (req.method === 'GET' && path === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain' }).end('ok'); return; } - if (req.method === 'POST' && req.url === '/render') { + if (req.method === 'GET' && path === '/offer') { + res.writeHead(301, { location: '/offer/' }).end(); + return; + } + if (req.method === 'GET' && path === '/offer/') { + const html = renderOffer(OFFER_MD, await fetchOfferPricing()); + res + .writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' }) + .end(html); + return; + } + if (req.method === 'POST' && path === '/render') { const png = await renderRequest(JSON.parse(await readBody(req))); res.writeHead(200, { 'content-type': 'image/png', 'content-length': png.length }).end(png); return; diff --git a/renderer/test/offer.test.mjs b/renderer/test/offer.test.mjs new file mode 100644 index 0000000..a82cf5b --- /dev/null +++ b/renderer/test/offer.test.mjs @@ -0,0 +1,29 @@ +// Unit test for the public-offer page assembly: renderOffer splices the backend's price-list +// markdown into the offer at the pricing marker and renders it with the shared renderOfferHtml +// (bundled from ui/src/lib/offer). The prose rendering itself is unit-tested in ui/ (offer.test.ts); +// here we assert the substitution and that the tables reach the rendered HTML. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { renderOffer, pricingMarker } from '../src/offer.mjs'; + +const tables = + '| Наименование | Рубли | Голоса в VK | Stars в Telegram |\n' + + '| --- | --- | --- | --- |\n' + + '| 50 «Фишек» | 200.00 | 30 | 100 |'; + +test('splices the price list into the offer and renders the tables to HTML', () => { + const md = `# Публичная оферта\n\n**4.4.** Стоимость Товаров:\n\n${pricingMarker}\n`; + const html = renderOffer(md, tables); + // The marker is gone and the projected table reached the document as a real HTML table. + assert.ok(!html.includes(pricingMarker), 'pricing marker must be substituted'); + assert.ok(html.includes(''), 'the price list must render as an HTML table'); + assert.ok(html.includes(''), 'a rouble price cell must be present'); + assert.ok(html.includes('50 «Фишек»'), 'the product title must be present'); + // The offer chrome from the shared renderer is intact. + assert.ok(html.includes('')); +}); + +test('a "$" in a title is substituted literally, not as a replacement pattern', () => { + const html = renderOffer(`x ${pricingMarker} y`, '| $5 pack | 1 |'); + assert.ok(html.includes('$5 pack'), 'a "$" in the tables must survive substitution'); +}); diff --git a/ui/e2e/landing.spec.ts b/ui/e2e/landing.spec.ts index 4ce19bf..4918bfb 100644 --- a/ui/e2e/landing.spec.ts +++ b/ui/e2e/landing.spec.ts @@ -59,13 +59,18 @@ test('the landing shows a web-version entry linking /app/, with a caption', asyn await expect(page.getByText('Веб-версия')).toBeVisible(); }); -// The footer carries a public-offer link to the static /offer/ page (rendered from -// ui/legal/offer_ru.md at build; the legal document a purchase accepts). -test('the landing footer links to the public offer at /offer/', async ({ page }) => { +// The footer carries the public-offer link (/offer/ — the legal document a purchase accepts, +// rendered by the render sidecar) and, beside it, the feedback link to the Telegram bot the offer +// lists as the seller's contact. +test('the landing footer links to the public offer and the feedback bot', async ({ page }) => { await page.goto('/landing.html'); await expect(page.getByText(/Играй в «Эрудита»/)).toBeVisible(); // Russian by default const offer = page.getByRole('link', { name: 'Публичная оферта' }); await expect(offer).toBeVisible(); expect(await offer.getAttribute('href')).toBe('/offer/'); + + const feedback = page.getByRole('link', { name: 'Обратная связь' }); + await expect(feedback).toBeVisible(); + expect(await feedback.getAttribute('href')).toBe('https://t.me/Erudit_GameBot'); }); diff --git a/ui/legal/offer_ru.md b/ui/legal/offer_ru.md index 39af269..2e2b866 100644 --- a/ui/legal/offer_ru.md +++ b/ui/legal/offer_ru.md @@ -80,6 +80,12 @@ **4.2.** Все расчеты по Договору производятся в безналичном порядке. +**4.3.** Порядок расчётов. Приобретаемым Товаром является внутриигровая валюта «Фишка» — условная учётная единица, используемая исключительно в пределах Сайта Продавца. «Фишки» предоставляют Покупателю возможность получения внутриигровых благ и дополнительных функций, включая, но не ограничиваясь: отказ от показа рекламы, приобретение подсказок в игре и иные внутриигровые возможности. «Фишка» не является электронным средством платежа либо денежным средством, не подлежит обмену на денежные средства и не может быть использована за пределами Сайта Продавца. «Фишки» зачисляются на внутриигровой счёт Покупателя единовременно после поступления оплаты; дальнейшее их использование для получения внутриигровых благ осуществляется Покупателем самостоятельно в интерфейсе игры. + +**4.4.** Стоимость Товаров: + +<#pricing_template#> + ## 5. Обмен и возврат Товара **5.1.** Покупатель вправе осуществить возврат (обмен) Продавцу Товара, приобретенный дистанционным способом, за исключением перечня товаров, не подлежащих обмену и возврату согласно действующему законодательству Российской Федерации. Условия, сроки и порядок возврата Товара надлежащего и ненадлежащего качества установлены в соответствии с Гражданским кодексом РФ, Закона РФ от 07.02.1992 N 2300-1 «О защите прав потребителей», Правил, утвержденных Постановлением Правительства РФ от 31.12.2020 N 2463. @@ -120,7 +126,7 @@ **9.3.** Договор вступает в силу с момента Акцепта условий настоящей Оферты Покупателем и действует до полного исполнения Сторонами обязательств по Договору. -**9.4.** Изменения, внесенные Продавцом в Договор и опубликованные на сайте в форме актуализированной Оферты, считаются принятыми Покупателем в полном объеме. +**9.4.** Изменения, внесенные Продавцом в Договор и опубликованные на сайте в форме актуализированной Оферты, считаются принятыми Покупателем в полном объеме при оплате Товаров. ## 10. Дополнительные условия @@ -143,3 +149,5 @@ ## 11. Реквизиты Продавца Денисов Илья Аркадьевич, ИНН 290210610742. + +Обратная связь в Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot). diff --git a/ui/src/Landing.svelte b/ui/src/Landing.svelte index 4fa71a0..0795ba3 100644 --- a/ui/src/Landing.svelte +++ b/ui/src/Landing.svelte @@ -125,7 +125,13 @@ @@ -287,6 +293,14 @@ color: var(--text-muted); font-size: 0.8rem; } + .ft .legal { + display: flex; + align-items: center; + gap: 8px; + } + .ft .sep { + color: var(--text-muted); + } .ft .offer { color: inherit; } diff --git a/ui/src/lib/i18n/en.ts b/ui/src/lib/i18n/en.ts index 1e6334e..d3a50de 100644 --- a/ui/src/lib/i18n/en.ts +++ b/ui/src/lib/i18n/en.ts @@ -285,6 +285,7 @@ export const en = { 'landing.captionVK': 'VK', 'landing.captionWeb': 'Web', 'landing.offer': 'Public offer', + 'landing.feedback': 'Feedback', 'install.title': 'Install the app', 'install.subtitle': 'Put the app icon on your desktop (home screen) to open the game in one tap.', diff --git a/ui/src/lib/i18n/ru.ts b/ui/src/lib/i18n/ru.ts index a9df0cd..b177751 100644 --- a/ui/src/lib/i18n/ru.ts +++ b/ui/src/lib/i18n/ru.ts @@ -285,6 +285,7 @@ export const ru: Record = { 'landing.captionVK': 'VK', 'landing.captionWeb': 'Веб-версия', 'landing.offer': 'Публичная оферта', + 'landing.feedback': 'Обратная связь', 'install.title': 'Установить приложение', 'install.subtitle': 'Поместите иконку приложения на рабочий стол (домашний экран), чтобы открывать игру одним нажатием.', diff --git a/ui/src/lib/offer.test.ts b/ui/src/lib/offer.test.ts index a9da8c3..e46cf3b 100644 --- a/ui/src/lib/offer.test.ts +++ b/ui/src/lib/offer.test.ts @@ -10,8 +10,8 @@ describe('renderOfferHtml', () => { // The markdown heading is rendered, not left as literal source. expect(html).toContain('

Публичная оферта

'); expect(html).not.toContain('# Публичная оферта'); - // A back link to the landing root is always present. - expect(html).toContain('href="/"'); + // No in-page navigation: the standalone offer carries no "back" link. + expect(html).not.toContain('class="back"'); }); it('renders headings, bold clause numbers and lists', () => { diff --git a/ui/src/lib/offer.ts b/ui/src/lib/offer.ts index f6cecd9..4d0d969 100644 --- a/ui/src/lib/offer.ts +++ b/ui/src/lib/offer.ts @@ -2,13 +2,15 @@ import { marked } from 'marked'; /** * renderOfferHtml renders the public-offer markdown source into a standalone, - * self-contained HTML document served statically at `/offer/`. The build emits - * the result as `dist/offer/index.html` (see the `emit-offer` plugin in - * `vite.config.ts`), which the landing container serves. + * self-contained HTML document served at `/offer/`. It runs server-side in the + * render sidecar (`renderer/src/offer.mjs`), which reads the owner-edited + * `ui/legal/offer_ru.md`, splices the live catalog price list into it and calls + * this function — one renderer shared with the browser build, kept unit-tested + * here (`offer.test.ts`). * - * The input `markdown` is trusted repository content (the owner-edited - * `ui/legal/offer_ru.md`), not user input, so the rendered HTML is deliberately - * not sanitised. The page carries its own minimal light/dark styling so it needs + * The input `markdown` is trusted repository content plus the backend's own + * catalog projection, not user input, so the rendered HTML is deliberately not + * sanitised. The page carries its own minimal light/dark styling so it needs * neither the app bundle nor `app.css`. */ export function renderOfferHtml(markdown: string): string { @@ -55,11 +57,6 @@ export function renderOfferHtml(markdown: string): string { a { color: var(--accent); } - .back { - display: inline-block; - margin-bottom: 20px; - text-decoration: none; - } h1 { font-size: 1.6rem; text-align: center; @@ -84,7 +81,6 @@ export function renderOfferHtml(markdown: string): string {
- ← На главную ${body}
diff --git a/ui/vite.config.ts b/ui/vite.config.ts index 62a6217..5a36909 100644 --- a/ui/vite.config.ts +++ b/ui/vite.config.ts @@ -3,7 +3,6 @@ import { resolve } from 'node:path'; import { defineConfig, type Plugin } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import { VitePWA } from 'vite-plugin-pwa'; -import { renderOfferHtml } from './src/lib/offer'; /** * injectBootVersion stamps the app version into index.html's boot-capability guard, replacing its @@ -39,22 +38,6 @@ function emitPolyfills(): Plugin { }; } -/** - * emitOffer renders the public offer markdown (legal/offer_ru.md) to a standalone - * static page and emits it as dist/offer/index.html, which the landing container - * serves at /offer/ (deploy/landing/Caddyfile). The markdown is the owner-editable - * source of truth, so the page is regenerated from it on every build. - */ -function emitOffer(): Plugin { - return { - name: 'emit-offer', - generateBundle() { - const md = readFileSync(resolve(import.meta.dirname, 'legal/offer_ru.md'), 'utf8'); - this.emitFile({ type: 'asset', fileName: 'offer/index.html', source: renderOfferHtml(md) }); - }, - }; -} - // The edge Connect service is scrabble.edge.v1.Gateway; the gateway serves it over // h2c on :8081 by default. In dev we proxy the RPC path so the browser (which can // not speak h2c directly) talks to the dev server on the same origin. In `mock` @@ -77,7 +60,6 @@ export default defineConfig(({ mode }) => ({ plugins: [ svelte(), emitPolyfills(), - emitOffer(), injectBootVersion(), // App-shell precache for the offline mode: a custom (injectManifest) service worker precaches // index.html + the hashed assets so the installed web PWA cold-launches with no network. It
200.00