diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c502a69 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + checks: + name: Checks (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + env: + DATABASE_URL: file:${{ github.workspace }}/storage/database/ci.sqlite3 + strategy: + fail-fast: false + matrix: + node: ['22', '24'] + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node }} + cache: npm + + - run: npm ci + - run: npx prisma generate + - run: npx prisma migrate deploy + + # The real file is written by `theme:sync --apply` and never committed. + - name: Use the example channel config + run: cp config/channel.generated.example.ts config/channel.generated.ts + + - run: npm run typecheck + - run: npm run lint + - run: npm test + - run: npm run build + - run: npm run build:assets + + # Exits 2 on error; run bare so the step fails on it. + - run: node dist/src/console/main.js config:validate diff --git a/README.md b/README.md index f14d1d2..d2f816d 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ never sent to the AsterMD platform and never written to this application's datab ```bash npm install cp .env.example .env # then edit it, see Configuration below +cp config/channel.generated.example.ts config/channel.generated.ts # until theme:sync --apply writes it npx prisma migrate deploy # creates the SQLite file and applies migrations npm run build:assets # compiles the Tailwind theme npm run start:dev # dev server with watch, http://localhost:8080 @@ -203,7 +204,6 @@ docs/ architecture, operations, middleware, journey notes | | | |---|---| | [`docs/STACK.md`](docs/STACK.md) | the stack, request lifecycle, container and the reasoning behind each choice | -| [`STATUS.md`](STATUS.md) | development log: build phases, what is real vs. Null-backed, known gaps | | [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | how the funnel, journey store, catalog and gateways fit together | | [`docs/MIDDLEWARE.md`](docs/MIDDLEWARE.md) | the nine-slot middleware pipeline, slot by slot | | [`docs/JOURNEY.md`](docs/JOURNEY.md) | one customer journey traced end to end | diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index 9be975d..0000000 --- a/STATUS.md +++ /dev/null @@ -1,1254 +0,0 @@ -# Build status - -Development log for the storefront: what each build phase delivered, what is real vs. Null-backed, -known gaps, and the real bugs found along the way. [`docs/STACK.md`](docs/STACK.md) describes the -stack; this file records how it got there. Entries are dated notes kept as written at the time, so -some describe intermediate states the code has since moved past. - -Last updated: 2026-09-24. - ---- - -## Phase status - -| Phase | Scope | Status | -| --- | --- | --- | -| 0 | Project init & toolchain | ✅ Done | -| 1 | Skeleton, bootstrap, CoreModule, tokens, error boundaries | ✅ Done | -| 2 | 9-slot middleware pipeline | ✅ Done | -| 3 | Persistence (Prisma + SQLite) | ✅ Done | -| 4 | Domain: Cart, CartRules, FunnelRouter, StepPreconditions | ✅ Done | -| 5 | Catalog + home/product/treatments/cart routes + templates | ✅ Done | -| — | **Real EMR integration** (Session/Cart/Verification/Teleform/Intake/Lead/Identity) | ✅ Done — not in the original 11-phase plan | -| 6 | Forms/intake engine + verify step | ✅ Done | -| 7 | Checkout (order-of-operations, idempotency, payment) | ✅ Done | -| 8 | Upsell + completion + receipt + teardown | ✅ Done | -| 9 | SEO + legal pages + error-page X-Robots-Tag correctness | ✅ **Done**, including the asset pipeline (deferred earlier in this session, now built — see note below) | -| 10 | Remaining console commands + observability | ✅ **Done** — see note below | -| — | **Real Vrio + CheckoutChamp payment adapters** | ✅ Done — not in the original 11-phase plan, user-directed reversal of the Null-payment-only decision | -| 11 | Test suite consolidation | 🟡 In progress — see note below | - -All of Phases 0–10 are covered by automated tests and were also manually smoke-tested (curl -click-through, or — for the intake templates, which the real EMR channel can't currently exercise -end-to-end — a dedicated render test driving every field type through the real view-model code; for -Phase 10, every console command run once for real via `node dist/src/console/main.js `). - ---- - -## Stack, as actually built (departs from the first stack draft) - -- **Prisma**, not Kysely — on **`7.10.0`** (the real latest *stable* release; npm's `latest` - dist-tag resolves to an unstable `8.0.0-rc.15` — see `CLAUDE.local.md` for the standing rule - this taught). Prisma 7 removed `schema.prisma`'s inline `datasource.url` entirely: the CLI reads - its connection string from `prisma.config.ts` now, and the app's own `PrismaClient` takes a - driver adapter (`@prisma/adapter-better-sqlite3`) instead of reading `DATABASE_URL` on its own — - see `prisma.config.ts` and `src/database/connection-factory.ts`'s doc comments. Re-verified with - a real runtime boot + DB write, not just `npm test`. Prisma 7+ also ships an AI-agent safety - guard on destructive CLI commands (`db push --accept-data-loss`) — see `CLAUDE.local.md`. -- **eslint/typescript-eslint/prettier bumped to latest stable** (`eslint@10.11.0`, - `typescript-eslint@8.70.1`, `prettier@3.9.8`) — no config breakage, `npm run lint` stayed clean. -- **EJS**, not Nunjucks — no template inheritance; every page includes its own head/foot partials. -- **class-validator DTOs** on every mutating route with a *static* body shape — additive to the - domain-layer validators. The intake save/submit/capture endpoints deliberately skip a DTO - class: their body shape is the teleform's own field set, which is data, not code, so no fixed - DTO can describe it — they take `@Body() body: Record` directly (Nest's - `ValidationPipe` only validates class-typed bodies, so this is a real bypass, not an oversight). -- **Node `>=22`** (not 24 — an earlier `>=24` pin in `package.json`/`.nvmrc` was a mistake, fixed). - -## Real EMR integration — what's actually live - -Reverses the original plan's "every EMR-family port stays Null-bound for the whole effort" -decision, after the real, official `@astermd-hq/sdk` npm package was found and real dev-sandbox -credentials were made available (`storefront-lamp/.env`). - -**Real, backed by `@astermd-hq/sdk`, config-gated against Null** (all on -`config.app.session.analytics`, except where noted): -- `SESSION_GATEWAY` → `EmrSessionGateway` (mints/looks up analytics sessions) -- `CART_GATEWAY` → `EmrCartGateway` (mirrors cart contents) -- `EMR_VERIFICATION_GATEWAY` → `EmrVerificationGateway` (email/address checks, each gated on its own - `config.app.features.emrVerifyEmail`/`emrVerifyAddress`; `EMR_VERIFICATION` still sets both) -- `ADDRESS_AUTOFILL` → `EmrAddressAutofill` (checkout address suggestions from the EMR when there is no - Google key; Null only under `NODE_ENV=test`) -- `INTAKE_UPLOADS` → `EmrIntakeUploads` (file-upload answers, whole or multipart; on `session.analytics`) -- `TELEFORM_GATEWAY` → `EmrTeleformGateway` (teleform metadata + definition fetch) -- `INTAKE_GATEWAY` → `EmrIntakeGateway`, wrapped in `RecordingIntakeGateway` (always writes a - local `events` audit row regardless of which gateway is inside) -- `LEAD_GATEWAY` → `EmrLeadGateway` (opportunity create/update) -- `IDENTITY_GATEWAY` → `EmrIdentityGateway` (KYC checks, gated on `config.verification.enabled` - — separately from the other six, which all key off `session.analytics`) - -`NODE_ENV=test` forces every one of these flags false, so the test suite never reaches the -network — re-verified after every addition, not assumed. - -**Still Null-only**: `PAYMENT_ADAPTER` (wired for real via `AdapterRegistry` in Phase 7, but zero -adapters are ever registered by design — see docs/STACK.md) and `CHECKOUT_EVENT_REPORTER` (Phase 7 built -its port + Null implementation only, since it's structurally unreachable while no real payment -adapter exists to place an order). - -**Proven end-to-end against the real dev-sandbox EMR** (`health.api.dev.besimplified.net`), twice: -1. A bare `curl` (no cookie) minted a real analytics session, confirmed on record via a direct - SDK call (`visit_page` event, geo-resolved IP). -2. A full cart-add → funnel-routing → intake-controller → `EmrTeleformGateway` round-trip: adding - an Rx product with a real variant selected correctly routed to `/intake/medical/`, correctly - called the real EMR for the teleform (which 404s, since this example catalog's teleform ids - don't exist in the real channel), and correctly rendered the `form-unavailable` degrade page — - the exact designed failure path, observed for real. - -**Token caching**: `@astermd-hq/sdk`'s own `FileTokenStore`, at `storage/cache/emr-token.json` — -the same path and package storefront-lamp's PHP side already uses. - ---- - -## Phase 6 — Forms/intake engine + verify step (done) - -The whole Forms domain, unit-tested (34 new tests across `Bmi`/`DateAnswer`/`RuleEvaluator`, plus -a full template-render test): `Definition`/`Field`/`Page`, `AnswerSet`/`AnswerEncoder`/ -`AnswerValidator`, `RuleEvaluator` (ported with extra care as the single highest-risk file — -inverted condition defaults, per-join combinator indexing, phone normalization, membership -semantics; every test passed on the first run), `Disqualification`/`DisqualificationOutcome`/ -`TerminationRule`, `TeleformSource`/`DefinitionCache`, the `TeleformGateway`/`IntakeGateway`/ -`LeadGateway`/`IdentityGateway` families (`Emr*`/`Null*` pairs, config-gated), `RecordMapper`, -`LeadWriter`, `IntakeSession` (the orchestrator, exact persist-before-validate ordering intact), -`VerificationStep` (identity assembly via `Prefill` read backwards through the teleform's -`db_fields` map), `IntakeController`/`NotEligibleController`/`VerifyController`, all wired into -`AppModule`. - -**Templates — all 18 field-type EJS partials built** (`field-text/boolean/choice-single/ -choice-multi/date/number/dropdown/bmi/hidden/heading/form-header/paragraph/divider/alert/image/ -form-progress/button/unsupported`) plus the `field.ejs` dispatcher, `partials/stepper.ejs`, and -both questionnaire pages (`pages/intake/form.ejs` for the server-rendered mode, `form-js-engine.ejs` -for the hosted-engine mode). Verified by a dedicated render test -(`test/forms/intake-templates.spec.ts`) that builds one definition covering every field type, -runs it through the real `FieldViewModel`/`RuleEvaluator` code (not hand-typed template locals), -and renders both page templates against the result — since this example catalog's teleform ids -don't exist in the real EMR channel, the live route can never reach a populated form to prove this -any other way. - -**Client-side multi-page stepping, wired up post-Phase 10.** `public/js/intake.js` (copied verbatim -from storefront-lamp during the asset pipeline work) expects a specific `data-intake-*` attribute -contract that the storefront's `field.ejs`/`form.ejs`/`stepper.ejs` didn't actually emit — different -attribute names entirely (`data-field-name` vs. the script's `data-intake-field`), an inverted -`cols` → `sm:col-span-*` mapping, a flex-column page layout instead of the `grid-cols-1 -sm:grid-cols-2` the script's markup expects, and a stepper using different CSS classes than the -ones `intake.js`'s own `updateStepper()` re-applies as the visitor advances. Fixed by porting -`field.twig`/`form.twig`/`stepper.twig`'s exact attribute contract from storefront-lamp field-for- -field: `field.ejs` now emits `data-intake-field`/`data-intake-type`/`data-intake-required`/ -`data-intake-hidden`/`data-intake-conditions` with the correct `cols` logic; a new shared -`field-error.ejs` partial (`data-intake-error`, always rendered so the script has a stable node to -write into) replaces the inline error markup duplicated across 7 field-type partials; -`field-bmi.ejs` gained `data-intake-bmi`/`-target`/`-result`/`-score`; `form.ejs` gained -`data-intake-form`/`data-save-url`/`data-submit-url`/`data-capture-url`/`data-intake-rules`/ -`data-intake-blocked`, the correct 2-column page grid, the eligibility interstitial, and one shared -Back/Continue nav (matching the script's own page-count-based submit-vs-advance logic, replacing -the previous per-page "Submit on the last page" markup that the script never actually drove); -`stepper.ejs` gained `data-funnel-stepper`/`data-stepper-*` and the exact done/active/upcoming class -strings `intake.js`'s `updateStepper()` hardcodes. **Verified with a real interactive test**, not -just visual inspection: a rendered two-page fixture, driven through a real browser via Playwright, -correctly advances from page 1 to page 2 on a genuine click — `data-intake-page-input`'s value -changes from `0` to `1`, the stepper re-styles step 1 as done (checkmark connector) and step 2 as -active, and the second page's own fields render. `test/forms/intake-templates.spec.ts` updated to -pass `definition` (present in the real controller's payload, missing from the test's hand-built -locals) and to match the ported copy's exact wording. - ---- - -## Known gaps - -None currently flagged. - -## Bugs found and fixed this session - -- **`cookie-parser` was never installed.** `SessionResolver`'s "cookie-present → trust it" branch - reads `request.cookies`, which no middleware populated. Completely invisible under - `NullSessionGateway` (no gateway ever returned a real UUID, so no cookie was ever set to fail to - recognize) — the instant `EmrSessionGateway` went live, **every request re-minted a brand-new - EMR session**, discovered via a real multi-request `curl` session. Fixed: installed - `cookie-parser`, registered as the first entry in `AppModule`'s pinned-middleware chain. -- **`config/app.ts`'s `session.analytics` default was wrong** (defaulted `false` via an invented - env knob; PHP has none and defaults `true` outside `APP_ENV=test`). Fixed to match exactly. -- **`AttributionMiddleware` had no route-exists guard.** The PHP original skips minting a session - for a request that doesn't match any real route (a bot scan, a stray asset request), via an - injected closure. The storefront never had an equivalent — invisible under Null-only, a real cost - once `EmrSessionGateway` went live (a GET to any unmatched path minted a real, billable EMR - session before `NotFoundController` got a say). Fixed via a new `RouteExistsChecker` - (`src/support/route-exists-checker.ts`) that introspects Express 5's own router - (`app.router.stack`, `layer.matchers`) to test-match a path against every *real* registered - route, excluding the catch-all fallback. Fails open on any structural surprise. Verified live: a - bot-scan-shaped path no longer sets `amd_session`, while static and dynamic real routes still do. -- **Prisma 6→7**: `latest` npm dist-tag is an unstable `8.0.0-rc.15`; the real latest stable is - `7.10.0`, itself a breaking major bump (inline `datasource.url` removed — see above). Migrated - cleanly; all tests + a real runtime boot re-verified afterward. - ---- - -## Phase 7 — Checkout (done) - -Full order-of-operations port of `core/Checkout/CheckoutService.php`, built from literal verbatim -source (BuyerValidator, CheckoutService, CheckoutController, the 3 repositories, Consents, -IdempotencyKey, CheckoutAttempt, PostChargeGuard, SettlementPolicy, OrderBumps, CheckoutResult/ -CheckoutViewModel, ConsentDefinition/ConsentRecord — 17 files read directly rather than from a -research-agent summary, per this project's "grep before building on a summary" rule). - -- **Domain/value objects** (`src/checkout/`): `totals`, `promotion`, `buyer-details`, `card-number`, - `consent-definition`, `consent-record`, `consents`, `idempotency-key`, `checkout-attempt`, - `post-charge-guard`, `settlement-policy`, `order-bump(s)`, `checkout-result`, - `checkout-view-model`, `buyer-validator`, `prefill`, `checkout-event-reporter` + - `null-checkout-event-reporter`, `order-recorder` + `null-order-recorder` + - `database-order-recorder`. -- **`checkout.service.ts`** — the full `submit()`/`view()`/`toggleBump()`/`applyPromotion()`/ - `removePromotion()`/`choosePlan()` orchestrator, in the spec's exact order: rate-limit before - anything costs money → re-price a stored promotion → validate buyer+consents together → - re-run the geo gate → store the buyer *before* the provider call → claim the idempotency key → - assemble one `OrderEnvelope` → mark the attempt sent → call the adapter → run - `PostChargeGuard`-wrapped writes only after that. Every constant/copy string ported verbatim. -- **Repositories** (Prisma-backed): `checkout-attempt-repository.ts` (claim/renewClaim/markSent/ - recordOutcome/release — the exact conditional-update ownership-token semantics that prevent the - PHP original's documented double-charge bug), `rate-limit-repository.ts` (fixed-window hit()), - `order-repository.ts` (transactional insert of orders/order_lines/order_consents + - findByReference). `prisma/schema.prisma`'s `Order` model gained `settlement`/`userAgent` columns - (migration `20260923093528_checkout_settlement_user_agent`). -- **`src/support/`**: `request-context.ts` (CDN IP header precedence), `database-rate-limiter.ts` - (fail-open fixed-window limiter over `RateLimitRepository`). -- **`src/upsell/`**: `upsell.ts` + `upsells.ts` — `queueFor()` (what `CheckoutService.placed()` - needs at checkout success) is fully ported; `resolve()` exists for Phase 8's page but is unused - until then. `config/upsells.ts` ships empty, matching the PHP original. -- **`PAYMENT_ADAPTER` wired for real**: `CoreModule` now binds it through `AdapterRegistry.for(config.payment.adapter)` — zero adapters ever registered, so every resolve falls through to - `NullPaymentAdapter`, exactly per plan. `ORDER_RECORDER` binds to `DatabaseOrderRecorder` - (real, DB-backed — orders must be recorded for receipt/reconciliation data to exist); - `CHECKOUT_EVENT_REPORTER` stays Null-only (structurally unreachable while `PaymentAdapter` never - places a real order — becomes real alongside a real payment adapter, not before one). -- **Routes**: `CheckoutController`/`CheckoutModule` (`GET`/`POST /checkout/`, - `POST /checkout/bump|promo|promo/remove|plan`), all 4 sub-action DTOs plus `SubmitCheckoutDto`. -- **`views/pages/checkout.ejs`** — styled per `docs/mockup/mockup/intake/checkout.html` (two-column - contact/delivery/payment form beside a sticky order summary); the mockup's shipping-method/ - express-checkout/PayPal/Afterpay/upsell-add-on sections are omitted as presentational content - with no backing service in the storefront (declared gaps), not wired to nothing. -- **`JourneyState` grew 7 fields**: `promotion`, `promotionQuotedAgainst`, `acceptedBumps`, - `consents`, `reusableCredential`, `upsellQueue`, `upsellCursor`, `upsellOutcomes` + methods - `storeBuyer()`/`storeReusableCredential()`/`wipePaymentCredential()`. - -**Bug found and fixed this session**: every `@Injectable()` class with an optional trailing -constructor parameter with no type Nest can resolve (`DatabaseRateLimiter`'s and -`CheckoutService`'s injected `clock?: () => string` test seam, `Consents`'s injected clock) failed -`AppModule` bootstrap with "Nest can't resolve dependencies… argument Function" — Nest tries to -resolve *every* constructor parameter, optional or not, unless marked `@Optional()`. Fixed by adding -`@Optional()` to all three. **A second bug, found via a real curl submit**: the checkout DTOs' -buyer-contact-detail fields (`first_name`, `email`, ...) had no `class-validator` decorators at -all — the global `ValidationPipe`'s `whitelist: true` silently deletes any property with zero -validation decorators before the controller ever sees it, which emptied every field on a real -submit. Fixed by decorating every field `@IsOptional() @IsString()` (a new shared -`BuyerContactFieldsDto` base class for the 3 sub-action DTOs that repeat the same 8 fields). - -**Proven against a real running server, not just unit-tested**: a real multi-request `curl` session -— add an OTC product to cart, submit checkout with full buyer details, a test card, and consent — -correctly failed buyer validation when fields were empty (caught the `whitelist` bug), and once -fixed, correctly reached the priced-line-unmapped decline (`[13.19]`): the port's example catalog -has no product with a real provider `offer_id`/`product_id` mapping (a documented Phase 5/6 gap), -so every priced line is honestly declined with "One of the items in your order is not available for -purchase right now" *before* ever reaching `NullPaymentAdapter` — and a resubmit of the identical -form got the same fresh decline rather than an in-flight/duplicate answer, proving -`releaseQuietly()` correctly gives the idempotency key back on this decline path. - ---- - -## Phase 8 — Upsell + completion + receipt + teardown (done) - -Full port of `core/Upsell/*` and `core/Completion/*`, built from literal verbatim source -(`Upsell`, `UpsellQueue`, `UpsellResult`, `UpsellService`, `UpsellViewModel`, `Completion`, -`Receipt`, `ReceiptViewModel`, `UpsellController`, `ReceiptController` — 10 files read directly). - -- **`JourneyState` grew 4 more fields** (`upsellQuotes`, `receipt`, `completedAt`) plus 5 - `UPSELL_*` outcome constants, and `upsellOutcomes` changed shape from Phase 7's placeholder - array to the real `Record` map the PHP original always used. The Phase 7 - `reusableCredential` field was renamed to `reusableCredentialData` with a new - `reusableCredential()` *method* added alongside it, reconstructing the real `PaymentCredential` - via `fromStorable()` — Phase 7 only ever needed to *write* the stored handle; Phase 8's - `UpsellService.accept()` is the first thing that needs to *read* it back as a real, chargeable - credential. New methods: `isComplete()`, `wipeForCompletion()`. -- **`src/upsell/`**: `upsell-queue.ts` (skip/advance/position over the durable queue — an entry - the catalog can no longer resolve is skipped and logged the moment it's read, never left for a - later render to trip over again), `upsell-result.ts`, `upsell-view-model.ts`, `upsell-service.ts` - (the full `view()`/`accept()`/`decline()` orchestrator — reuses the *checkout's own* - `checkout_attempts` idempotency guard rather than a second one, and `CheckoutAttempt.releasesKey()` - rather than re-deriving it). `[16.11]`'s central rule — a declined/skipped/unresolvable upsell - never traps the buyer, every path ends in a redirect further forward — is structural: `UpsellResult.redirectTo` is non-nullable, unlike `CheckoutResult`'s. -- **`src/completion/`**: `receipt.ts` (built from real Prisma order rows — `OrderRowForReceipt` - types `OrderRepository.findByReference()`'s actual camelCase return shape directly, no - snake_case translation layer needed), `receipt-view-model.ts`, `completion.ts` (the fire-once - orchestrator — `wipeForCompletion()` runs last, after every action that still needs the - attribution/buyer contact has already used them). -- **`CheckoutEventReporter` interface grew 5 methods** (`upsellOffered`/`upsellAccepted`/ - `upsellDeclined`/`journeyCompleted`/`treatmentsSynced`) — all no-ops on - `NullCheckoutEventReporter`, for the same structural reason Phase 7 gave: unreachable while - `PAYMENT_ADAPTER` never places a real order. -- **Routes**: `UpsellController`/`UpsellModule` (`GET /upsell/`, `POST /upsell/accept|decline`), - `ReceiptController`/`ReceiptModule` (`GET /thank-you/`) — both thin, deciding nothing themselves. -- **`views/pages/upsell.ejs`, `thank-you.ejs`** — styled per `docs/mockup/mockup/intake/ - {upsell,thankyou}.html`. Deliberately omitted, since nothing in the storefront backs them: a case id - (`ReceiptViewModel` carries none on purpose — the EMR's treatment record has a null - `provider_case_id` at creation time), the delivery map, a separate billing address (`[13.2]`: - billing = shipping), a shipping method/cost line (`config/app.ts`'s declared `shippingSelector: - false` gap), and upsell.ejs's footnote is only ever the *configured* one — never a hardcoded - "Cancel anytime", which `Upsell.php`'s own doc comment explains can only be written truthfully - per deployment/per offer. - -**Proven end-to-end against a real, fully-migrated test database** (not the suite's default -unmigrated in-memory one — this test pushes the real schema to a throwaway temp SQLite file, same -as `test/database.spec.ts`), with a stub `PaymentAdapter` that actually places (`AdapterCapabilities` -otherwise stays Null-shaped) and a `FakeSessionGateway`/`FakeCatalogProvider` swapped in for the -example catalog's real gap (no product in it carries a provider mapping — see Phase 7's own -section): a full `supertest` click-through — add to cart, submit checkout, land on `/upsell/`, -fall straight through to `/thank-you/` since no upsells are configured, see the real order and -reference on the receipt, reload the receipt and get the identical frozen snapshot (fire-once), and -then discover that `/checkout/`'s `cart_not_empty` precondition now fails (cart cleared on -placement) — which is also what triggers `[4.18]`'s delayed session-cookie teardown, confirmed by -checking order matters: visiting the receipt a second time has to happen *before* visiting any other -page, or the teardown already fired and the second receipt visit lands on a fresh, order-less -session instead. This also strengthens Phase 7's own coverage, which previously only exercised the -*decline* path (the example catalog's unmapped-line gap) — this is the first automated test of a -checkout that actually reaches `placed()`. - -Two test-only fixtures were added along the way and are reusable by later phases: -`test/support/fake-session-gateway.ts` (mints a real, stable session uuid — `NullSessionGateway` -never does, so no journey persists across requests without this) and -`test/support/fake-catalog-provider.ts` (overriding `PRODUCT_CATALOG` alone is not enough for any -test touching `/products/:slug/` — `ProductDetailController` injects the concrete `CatalogProvider` -class directly rather than through the token; this fixture overrides `CatalogProvider` itself, which -`PRODUCT_CATALOG`'s `useExisting` binding also resolves through). - ---- - -## Phase 9 — SEO + legal pages + error-page X-Robots-Tag correctness (done) - -Ported from literal verbatim source: `RobotsPolicy.php`, `MetaResolver.php`, `PageMeta.php`, -`StructuredData.php` + its 4 emitters (`Organisation`, `WebSite`, `BreadcrumbList`, `Product`), -`RobotsController.php`, `SitemapController.php`, `SeoMiddleware.php`, the 3 `pages/legal/*.twig` -placeholder templates, and `structured-data.twig`. - -- **`src/seo/`**: `robots-policy.ts` grew from Phase 1's bare `REFUSED` constant into the full - per-path directive resolver (`directiveFor`/`refusesIndexing`/`isIndexable`/ - `indexingDiscouraged`, exact-beats-prefix / longer-prefix-beats-shorter specificity ranking with - the doubled-score tie-break so object key order can never decide a match), `meta-resolver.ts` - (title/description/canonical/social resolution chain — every product this EMR syncs carries an - empty description, so a blank candidate falls *through* rather than satisfying the chain), - `page-meta.ts` (the single-writer resolved-once value object). -- **`src/seo/structured-data/`**: `emitter.ts` (the one-emitter-per-type interface), - `organisation.ts`, `web-site.ts` (conditional `SearchAction`, conditional `publisher` reference — - never a dangling `@id`), `breadcrumb-list.ts` (a 1-crumb trail emits nothing), `product.ts` - (`[24.9]`: the offer prices from the *resolved variant*, never the product-level figure, and - availability is derived from whether that variant actually carries a provider mapping; `[24.10]`: - an `rx` product publishes nothing unless the deployment explicitly permits it, and its breadcrumb - trail is withheld too, since the last crumb would restate exactly what the product omission - withheld), `structured-data.ts` (the graph assembler — every emitter independently switchable in - `config/app.ts`'s `seo.structuredData`, defaulting **off** per key). -- **`CatalogProvider` grew a `channel()` getter** — Phase 5 discarded `CatalogMerger.merge()`'s - `channel` field entirely; `StructuredData`'s offer needs the synced channel's currency (`[24.9]`: - no currency configured means no offer is published, never a guessed one). -- **`SeoMiddleware` rewritten off Phase 2's always-`noindex` stub** onto real resolution: publishes - a `res.locals.seo` object (`canonical`, the real per-path `robots` directive, `page` — a - `PageMeta` a page can `.with(title, description, type)`) and sets `X-Robots-Tag` from the same - directive on every response. -- **`partials/head.ejs` gained a canonical ``, a structured-data include, and one behavioural - change to the `` tag — additive, not a rewrite of the other ~30 templates - that already call it.** Every page that passes its own explicit `noindex` (funnel steps, error - pages) is completely unaffected. A page that passes **no opinion at all** (most of the marketing - surface, and both legal pages as of this phase) now falls through to `seo.robots` instead of - defaulting to indexable — closing a real disagreement `[24.2]` forbids: before this fallback, such - a page's `X-Robots-Tag` header said `noindex` under `discourageIndexing` (every non-production - environment) while its meta tag said nothing at all. Proven directly: `test/routes/ - legal.e2e-spec.ts` asserts the home page and all 3 legal pages agree, header vs. meta tag, under - `NODE_ENV=test`. -- **Routes**: `RobotsController`/`SitemapController`/`SeoModule` (`GET /robots.txt`, - `GET /sitemap.xml` — the sitemap's exclusions are `RobotsPolicy.isIndexable()` calls, never a - second hand-kept list, so a funnel step added later needs one robots rule, not two files kept in - sync), `LegalController`/`LegalModule` (`GET /terms|privacy|telehealth-consent/` — three thin - methods rather than porting Slim's generic template-argument `PageController`, since Nest has no - equivalent route-argument style and Nest routing wants a real method per path). -- **`views/pages/legal/{terms,privacy,telehealth-consent}.ejs`** — the placeholder copy ported - verbatim (still not real legal text; every deployment is responsible for its own, exactly as the - PHP original states). -- **Structured data wired into the 3 pages PHP's own `StructuredData::pathsToInspect()` covers**: - `HomeController`, `ProductListController` (`/treatments/`), `ProductDetailController` - (`/products/:slug/`) — each now passes `structured_data: this.structuredData.json(req.path)`. -- **Error pages needed no changes.** They already passed `noindex: true` explicitly and - `ErrorPresenter` already set `X-Robots-Tag: noindex, nofollow` unconditionally (Phase 1) — header - and meta tag already agreed; the "lands in Phase 9" note on those views was about moving them into - a shared funnel layout, which the storefront's EJS-has-no-inheritance decision (see docs/STACK.md's Templates - section) already ruled out as a real layout file — every page includes its own head/foot partials - by design, so there was no separate layout work to do here. -- **The Tailwind v4 asset-build pipeline and client JS, initially deferred, were built later this - session** (after Phase 10) — see the "Asset pipeline + design pass" section below for the full - account. - -**Proven against a real running server**: `robots.txt` correctly emits a blanket `Disallow: /` plus -a `Sitemap:` line under `discourageIndexing` (dev/test), `sitemap.xml` serves a well-formed but -empty `` so the two documents never contradict each other, all 3 legal pages render with -matching header/meta-tag `noindex`, and the home page's `