From 3adfac34aa5faadc17b89edfc8e8e7b0be872da0 Mon Sep 17 00:00:00 2001 From: Clarence Date: Tue, 1 Dec 2026 21:54:02 +0800 Subject: [PATCH 1/3] test(e2e): cover the core stamp card flow end to end Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 8 +- README.md | 2 +- e2e/README.md | 3 +- e2e/core-flow.spec.ts | 279 ++++++++++++++++++++++++++++++++++++++++++ e2e/mock-supabase.ts | 70 +++++++++-- package.json | 2 +- playwright.config.ts | 9 +- 7 files changed, 357 insertions(+), 16 deletions(-) create mode 100644 e2e/core-flow.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d5af21ee..65b3c156 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,13 @@ All notable changes to loopkit are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## [0.6.1] - 2026-12-01 +## [0.6.2] - 2026-12-01 + +### Added + +- Playwright core-flow e2e: a vendor creates a stamp card program, a customer joins from the shop link with a phone number and a birthday, and the vendor stamps that card at the counter and sees the count update. The Supabase stand-in now keeps state across requests (table functions, RPC handlers). + +- 2026-12-01 ### Changed diff --git a/README.md b/README.md index 45da6235..bb2a5489 100644 --- a/README.md +++ b/README.md @@ -505,7 +505,7 @@ See `AGENTS.md` for engineering rules and skills. `AGENTS.md` is kept under 200 - `.github/` — CI workflows - `.husky/` — git hook scripts (pre-commit/commit-msg/pre-push) - `docs/` — deploy runbook, superpowers specs/plans, CONSTITUTION -- `e2e/` — Playwright end-to-end smoke + signed-out route-protection tests (both run without Supabase provisioning) +- `e2e/` — Playwright end-to-end smoke, signed-out route-protection and core vendor/customer flow tests (all run without Supabase provisioning) - `src/` — application source (App Router pages, lib, components) - `supabase/` — SQL migrations and seed data - `test/` — Vitest unit/integration tests diff --git a/e2e/README.md b/e2e/README.md index 8b98c851..07f8f9c4 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -10,7 +10,8 @@ Playwright end-to-end smoke tests — runnable with only `pnpm dev` + - `route-protection.spec.ts` — signed-out route protection: `/dashboard`, `/dashboard/customers`, and `/setup` redirect to `/login`; `/admin` 404s rather than revealing the route exists; `/c` without `?v=` and `/earn` without `?order=` (copy: "This link is incomplete. Ask the shop for a new one.") render their no-DB-call fallback copy instead of attempting a lookup. Like `smoke.spec.ts`, runnable without Supabase provisioning — middleware's `getUser()` resolves `user: null` locally with no session cookie, so these gates fire without a live DB. - `smoke.spec.ts` — public smoke: the landing page renders its hero heading and "Join the waitlist" link; `/login` renders its "Continue with Google" button. The hero heading locator (here and in `csp.spec.ts`) accepts either hyphen in "one-time", because the hero uses a non-breaking hyphen (U+2011) - `signed-in-smoke.spec.ts`: signed in as an admin vendor with MFA cleared (`aal2`), `renderSmoke` over every dashboard (including the Customers referrals route and the old referrals/settings redirects), setup (`/setup` and `/setup/new`) and admin page, failing on a 5xx, error boundary, page error, CSP violation or 404; a password-only (`aal1`) admin session is sent to `/mfa`. It starts the stand-in below itself and runs in its own Playwright project after the others. It sees empty data, not seeded rows. -- `mock-supabase.ts`: not a spec; a small `http` server standing in for GoTrue and PostgREST, plus `signedInCookie()`, which builds the Supabase auth cookie for a signed-in session. +- `core-flow.spec.ts`: the core path end to end against a stateful stand-in: the vendor creates a stamp card at `/setup/new`, a customer in a separate browser context opens `/c?v=`, enters a phone number and picks a birthday with the shared Select, then the vendor looks the number up at `/dashboard/counter` and adds a stamp; asserts the stored program, card, birthday and the on-screen `0 / 5` to `1 / 5` stamp count. It runs in its own `core-flow` Playwright project after `signed-in`, because it binds the same stand-in port. Camera scanning is not driven; the counter's phone lookup stands in for it. +- `mock-supabase.ts`: not a spec; a small `http` server standing in for GoTrue and PostgREST, honouring `offset`/`limit` and the app's keyset cursors so paged reads end, plus `signedInCookie()`, which builds the Supabase auth cookie for a signed-in session. ## Parent diff --git a/e2e/core-flow.spec.ts b/e2e/core-flow.spec.ts new file mode 100644 index 00000000..6626fadf --- /dev/null +++ b/e2e/core-flow.spec.ts @@ -0,0 +1,279 @@ +import type { Server } from "node:http"; +import { test, expect } from "@playwright/test"; +import { signedInCookie, startSupabaseMock } from "./mock-supabase"; + +const SUPABASE_URL = + process.env.NEXT_PUBLIC_SUPABASE_URL ?? "http://127.0.0.1:54321"; +const USER_ID = "6df824a1-9da2-4608-ad13-2400a9114ec0"; +const PROGRAM_ID = "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; +const CARD_ID = "1c2d3e4f-5061-4b7c-9d8e-0f1a2b3c4d5e"; +const CARD_TOKEN = "a1b2c3d4e5f60718293a4b5c6d7e8f90"; +// Singapore mobile: normalizePhone stores it as +65 followed by the 8 digits. +const PHONE_INPUT = "9123 4567"; +const PHONE_E164 = "+6591234567"; +const STAMPS_REQUIRED = 5; +const PROGRAM_NAME = "Coffee card"; +const REWARD_TEXT = "Free coffee"; + +type ProgramRow = { + id: string; + name: string; + stamps_required: number; + reward_text: string; + type: string; + config: unknown; + active: boolean; + expiry_days: number | null; + reward_expiry_days: number | null; + reward_cost_cents: number | null; + head_start: boolean; + head_start_percent: number; + replaced_by: string | null; + carry_over_stamps: boolean; + birthday_bonus_enabled: boolean; +}; + +type CardRow = { + id: string; + phone: string; + program_id: string; + stamp_count: number; + reward_count: number; + state: unknown; + cycle_started_at: string; + updated_at: string; +}; + +// The vendor creates a stamp card, a customer joins from the shop link and the +// vendor stamps that card, against a stateful stand-in for Supabase: the +// stand-in's RPCs keep programs and cards in memory so each step reads what the +// previous one wrote. +test.describe("core vendor and customer flow", () => { + // Each step compiles routes on first hit under `next dev`. + test.describe.configure({ mode: "serial", timeout: 120_000 }); + + let server: Server; + let listening = false; + let programs: ProgramRow[] = []; + let cards: CardRow[] = []; + let birthday: { month: unknown; day: unknown } | null = null; + + const programSummary = (program: ProgramRow, card: CardRow) => ({ + program_id: program.id, + name: program.name, + type: program.type, + config: program.config, + state: card.state, + stamp_count: card.stamp_count, + card_token: CARD_TOKEN, + reward_text: program.reward_text, + stamps_required: program.stamps_required, + expiry_days: program.expiry_days, + cycle_started_at: card.cycle_started_at, + active: program.active, + replaced_by_name: null, + replaced_by_stamp_count: null, + vendor_avatar_url: null, + active_vouchers: [], + }); + + test.beforeAll(async () => { + programs = []; + cards = []; + birthday = null; + const url = new URL(SUPABASE_URL); + server = startSupabaseMock({ + tables: { + programs: () => programs, + cards: () => cards, + legal_check_state: () => [ + { + email: "e2e-vendor@merqo.test", + checked_at: new Date().toISOString(), + is_current: true, + }, + ], + }, + rpc: { + check_rate_limit: () => true, + create_program: (args: Record) => { + programs.push({ + id: PROGRAM_ID, + name: String(args.p_name), + stamps_required: Number(args.p_stamps_required), + reward_text: String(args.p_reward_text), + type: String(args.p_type), + config: args.p_config, + active: true, + expiry_days: null, + reward_expiry_days: null, + reward_cost_cents: null, + head_start: false, + head_start_percent: 0, + replaced_by: null, + carry_over_stamps: false, + birthday_bonus_enabled: false, + }); + return PROGRAM_ID; + }, + vendor_active_programs: () => + programs.map((p) => ({ + id: p.id, + name: p.name, + type: p.type, + reward_text: p.reward_text, + })), + customer_join: (args: Record) => { + const program = programs[0]; + if (!program) return { cards: [] }; + let card = cards.find((c) => c.phone === args.p_phone); + if (!card) { + card = { + id: CARD_ID, + phone: String(args.p_phone), + program_id: program.id, + stamp_count: 0, + reward_count: 0, + state: {}, + cycle_started_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }; + cards.push(card); + } + return { cards: [programSummary(program, card)] }; + }, + customer_set_birthday: (args: Record) => { + birthday = { month: args.p_month, day: args.p_day }; + return null; + }, + add_stamp: (args: Record) => { + let card = cards.find((c) => c.phone === args.p_phone); + if (!card) { + card = { + id: CARD_ID, + phone: String(args.p_phone), + program_id: String(args.p_program), + stamp_count: 0, + reward_count: 0, + state: {}, + cycle_started_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }; + cards.push(card); + } + card.stamp_count += 1; + card.updated_at = new Date().toISOString(); + return { + id: card.id, + phone: card.phone, + stamp_count: card.stamp_count, + }; + }, + }, + }); + listening = await new Promise((resolve) => { + server.once("error", () => resolve(false)); + server.listen(Number(url.port), url.hostname, () => resolve(true)); + }); + }); + + test.afterAll(async () => { + if (listening) + await new Promise((done) => server.close(() => done())); + }); + + test.beforeEach(() => { + // Intentional, conditional skip: a real stack already owns the port. + test.skip(!listening, "the Supabase stand-in could not bind its port"); + }); + + test("vendor creates a stamp card program", async ({ + context, + page, + baseURL, + }) => { + const { name, value } = signedInCookie(SUPABASE_URL); + await context.addCookies([ + { name, value, url: baseURL ?? "http://localhost:3000" }, + ]); + + await page.goto("/setup/new"); + await page.getByRole("button", { name: "Next: Basics" }).click(); + await page.locator("#name").fill(PROGRAM_NAME); + await page.locator("#reward_text").fill(REWARD_TEXT); + await page.locator("#stamps_required").fill(String(STAMPS_REQUIRED)); + await page.getByRole("button", { name: "Next: Rules" }).click(); + await page.getByRole("button", { name: "Create card" }).click(); + + await expect(page).toHaveURL(new RegExp(`/dashboard\\?p=${PROGRAM_ID}`), { + timeout: 60_000, + }); + expect(programs).toHaveLength(1); + expect(programs[0]).toMatchObject({ + name: PROGRAM_NAME, + type: "stamp", + stamps_required: STAMPS_REQUIRED, + reward_text: REWARD_TEXT, + }); + }); + + test("customer joins from the shop link and saves a birthday", async ({ + browser, + baseURL, + }) => { + // A separate context: the customer has no vendor session. + const customer = await browser.newContext({ baseURL }); + const page = await customer.newPage(); + + await page.goto(`/c?v=${USER_ID}`); + await expect(page.getByText(`Join: ${PROGRAM_NAME}`)).toBeVisible(); + + await page.locator("#phone").fill(PHONE_INPUT); + await page.getByRole("button", { name: "Check my card" }).click(); + + await expect(page.getByText(REWARD_TEXT).first()).toBeVisible(); + expect(cards).toHaveLength(1); + expect(cards[0]).toMatchObject({ phone: PHONE_E164, stamp_count: 0 }); + + // The shared Select is Radix: open the trigger, then pick the option. + await page.getByRole("combobox", { name: "Birth month" }).click(); + await page.getByRole("option", { name: "March" }).click(); + await page.getByRole("combobox", { name: "Birth day" }).click(); + await page.getByRole("option", { name: "14", exact: true }).click(); + await page.getByRole("button", { name: "Save", exact: true }).click(); + + await expect(page.getByText("Birthday saved.")).toBeVisible(); + expect(birthday).toEqual({ month: 3, day: 14 }); + + await customer.close(); + }); + + test("vendor stamps the enrolled card and the count updates", async ({ + context, + page, + baseURL, + }) => { + const { name, value } = signedInCookie(SUPABASE_URL); + await context.addCookies([ + { name, value, url: baseURL ?? "http://localhost:3000" }, + ]); + + await page.goto(`/dashboard/counter?p=${PROGRAM_ID}`, { + waitUntil: "domcontentloaded", + }); + await expect( + page.getByRole("button", { name: /Serve a customer/ }), + ).toBeVisible(); + + await page + .getByText(/Existing customer who can.t scan\? Enter their number/) + .click(); + await page.locator("#phone").fill(PHONE_INPUT); + await page.getByRole("button", { name: "Look up" }).click(); + await expect(page.getByText(`0 / ${STAMPS_REQUIRED} stamps`)).toBeVisible(); + + await page.getByRole("button", { name: "Add stamp" }).click(); + await expect(page.getByText(`1 / ${STAMPS_REQUIRED} stamps`)).toBeVisible(); + expect(cards[0]?.stamp_count).toBe(1); + }); +}); diff --git a/e2e/mock-supabase.ts b/e2e/mock-supabase.ts index 660192e9..18e5c13f 100644 --- a/e2e/mock-supabase.ts +++ b/e2e/mock-supabase.ts @@ -8,12 +8,20 @@ const USER_EMAIL = "e2e-vendor@merqo.test"; const OBJECT_ACCEPT = "application/vnd.pgrst.object+json"; export type MockFixtures = { - /** Rows PostgREST returns per table; a table not listed is empty. */ - tables?: Record; - /** JSON an RPC returns; an RPC not listed returns null. */ + /** + * Rows PostgREST returns per table; a table not listed is empty. A function + * is read on every request, so a spec can serve rows its RPCs have changed. + */ + tables?: Record unknown[])>; + /** + * JSON an RPC returns; an RPC not listed returns null. A function receives + * the RPC's JSON arguments and may keep state between calls. + */ rpc?: Record; }; +type RpcHandler = (args: Record) => unknown; + function base64url(value: unknown): string { return Buffer.from(JSON.stringify(value)).toString("base64url"); } @@ -83,26 +91,66 @@ function readRows( : send(406, { code: "PGRST116", message: "no single row" }); } -function handleRest( +async function readJson( + req: IncomingMessage, +): Promise> { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk as Buffer); + try { + return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"); + } catch { + return {}; + } +} + +// The app pages through tables until an empty page, by offset or by a keyset +// cursor (`id.gt.X`, or `updated_at`/`id` descending via an `or` filter), so +// honour all three or a non-empty table would be re-served forever. +function selectRows(all: unknown[], url: URL): unknown[] { + const { searchParams } = url; + const idAfter = searchParams.get("id")?.match(/^gt\.(.+)$/)?.[1]; + const before = searchParams + .get("or") + ?.match( + /^\(updated_at\.lt\.([^,]+),and\(updated_at\.eq\.[^,]+,id\.lt\.([^)]+)\)\)$/, + ); + const keyed = all.filter((row) => { + const { id, updated_at } = row as { id?: unknown; updated_at?: unknown }; + if (idAfter !== undefined && String(id) <= idAfter) return false; + if (!before) return true; + const stamp = String(updated_at); + return stamp < before[1] || (stamp === before[1] && String(id) < before[2]); + }); + const offset = Number(searchParams.get("offset") ?? 0); + const limit = searchParams.get("limit"); + return keyed.slice( + offset, + limit === null ? undefined : offset + Number(limit), + ); +} + +async function handleRest( req: IncomingMessage, pathname: string, fixtures: MockFixtures, send: Send, ) { const rpc = /^\/rest\/v1\/rpc\/(.+)$/.exec(pathname); - if (rpc) return send(200, fixtures.rpc?.[rpc[1]] ?? null); + if (rpc) { + const result = fixtures.rpc?.[rpc[1]]; + if (typeof result !== "function") return send(200, result ?? null); + return send(200, (result as RpcHandler)(await readJson(req)) ?? null); + } const table = /^\/rest\/v1\/([^/]+)$/.exec(pathname)?.[1]; if (!table) return send(404, { message: "not mocked" }); if (req.method !== "GET" && req.method !== "HEAD") { return send(204, undefined); } - return readRows( - req.method, - req.headers.accept, - fixtures.tables?.[table] ?? [], - send, - ); + const source = fixtures.tables?.[table] ?? []; + const all = typeof source === "function" ? source() : source; + const rows = selectRows(all, new URL(req.url ?? "/", "https://mock.invalid")); + return readRows(req.method, req.headers.accept, rows, send); } export function startSupabaseMock(fixtures: MockFixtures = {}): Server { diff --git a/package.json b/package.json index 97f55778..d45e5efa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loopkit", - "version": "0.6.1", + "version": "0.6.2", "private": true, "packageManager": "pnpm@11.10.0", "engines": { diff --git a/playwright.config.ts b/playwright.config.ts index e11d5d5b..b082a20f 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -19,7 +19,7 @@ export default defineConfig({ projects: [ { name: "chromium", - testIgnore: /signed-in-smoke/, + testIgnore: /signed-in-smoke|core-flow.spec/, use: { ...devices["Desktop Chrome"] }, }, { @@ -28,6 +28,13 @@ export default defineConfig({ dependencies: ["chromium"], use: { ...devices["Desktop Chrome"] }, }, + { + // Binds the same stand-in port, so it waits for the signed-in smoke. + name: "core-flow", + testMatch: /core-flow.spec/, + dependencies: ["signed-in"], + use: { ...devices["Desktop Chrome"] }, + }, ], webServer: { // CI tests the production build, where the nonce CSP is active. From 6b759b9837955c2cb44bfac993ec3533cccb619d Mon Sep 17 00:00:00 2001 From: Clarence Date: Wed, 2 Dec 2026 08:42:00 +0800 Subject: [PATCH 2/3] test(e2e): use a low-entropy card token fixture so gitleaks stays quiet Co-Authored-By: Claude Sonnet 5.5 --- e2e/core-flow.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/core-flow.spec.ts b/e2e/core-flow.spec.ts index 6626fadf..fefa6d4f 100644 --- a/e2e/core-flow.spec.ts +++ b/e2e/core-flow.spec.ts @@ -7,7 +7,7 @@ const SUPABASE_URL = const USER_ID = "6df824a1-9da2-4608-ad13-2400a9114ec0"; const PROGRAM_ID = "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; const CARD_ID = "1c2d3e4f-5061-4b7c-9d8e-0f1a2b3c4d5e"; -const CARD_TOKEN = "a1b2c3d4e5f60718293a4b5c6d7e8f90"; +const CARD_TOKEN = "e2e-fixture-card-token"; // Singapore mobile: normalizePhone stores it as +65 followed by the 8 digits. const PHONE_INPUT = "9123 4567"; const PHONE_E164 = "+6591234567"; From 5308e9b8e9e7ab0a6ba856f1fa204c9dfed9df33 Mon Sep 17 00:00:00 2001 From: Clarence Date: Wed, 2 Dec 2026 09:07:10 +0800 Subject: [PATCH 3/3] test(e2e): keep the card token fixture 32 hex chars The app validates card tokens as 32 lowercase hex characters, so the previous low-entropy placeholder broke the customer join. Co-Authored-By: Claude Sonnet 5.5 --- e2e/core-flow.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/core-flow.spec.ts b/e2e/core-flow.spec.ts index fefa6d4f..861960f7 100644 --- a/e2e/core-flow.spec.ts +++ b/e2e/core-flow.spec.ts @@ -7,7 +7,7 @@ const SUPABASE_URL = const USER_ID = "6df824a1-9da2-4608-ad13-2400a9114ec0"; const PROGRAM_ID = "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d"; const CARD_ID = "1c2d3e4f-5061-4b7c-9d8e-0f1a2b3c4d5e"; -const CARD_TOKEN = "e2e-fixture-card-token"; +const CARD_TOKEN = "0".repeat(31) + "1"; // Singapore mobile: normalizePhone stores it as +65 followed by the 8 digits. const PHONE_INPUT = "9123 4567"; const PHONE_E164 = "+6591234567";