diff --git a/.claude/README.md b/.claude/README.md index 33bf130e..a78a8903 100644 --- a/.claude/README.md +++ b/.claude/README.md @@ -15,7 +15,7 @@ against. - `comment-hygiene-patterns.txt` — the canonical change-narration/ticket-reference pattern list, read at runtime by `hooks/post-edit-comment-check.sh`, `.husky/lib/comment-hygiene.sh`, and `.github/workflows/ci.yml`'s `comment-hygiene` job instead of each hardcoding its own copy; first 10 lines are anchored keyword patterns (feed all three surfaces), last 3 (date/ticket/issue reference) are lower-precision and feed only the two warn-only surfaces, not the CI hard gate - `harness.json` — harness manifest (its `review_note` points at `docs/meta/templatecentral-adoption-log.md`, and the `AGENTS.md` `origin_hash` tracks the slimmed file; the hook-by-hook reference is `docs/meta/ai-harness-reference.md`): templateCentral version/stack/adaptation metadata, plus `seeded_files` — the enforcement-layer file list (path + sha256 `origin_hash`) that `verify-harness.sh` diffs against - `hooks/` -- `regen-harness.sh` — human-run-only: rewrites every `origin_hash` in `harness.json` to match current on-disk content, blessing an intentional harness edit; `protect-files.sh` requires human approval before an agent can even edit it (most recently re-run 2026-11-10 after the AGENTS.md skills-table edit) +- `regen-harness.sh` — human-run-only: rewrites every `origin_hash` in `harness.json` to match current on-disk content, blessing an intentional harness edit; `protect-files.sh` requires human approval before an agent can even edit it (most recently re-run 2026-12-02 after the `ci.yml` mutation-filter edit) - `settings.json` — wires each script in `hooks/` to a Claude Code lifecycle event (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, UserPromptSubmit) and sets tool `permissions` (allow/deny) and skill overrides - `skills/` - `verify-harness.sh` — harness integrity sensor: computes sha256 from committed HEAD blobs for every seeded file matched by a path guard (`hooks/`, `settings.json`, harness verifier/regen scripts, `.husky/`, `.gitleaks.toml`, `.github/workflows/`) and compares to `harness.json`'s `origin_hash` baseline; read-only, exits non-zero on drift; run by `.github/workflows/ci.yml` and husky's `pre-push` hook diff --git a/.claude/harness.json b/.claude/harness.json index d1e69444..74a415d2 100644 --- a/.claude/harness.json +++ b/.claude/harness.json @@ -8,7 +8,7 @@ "richReadme": true, "seeded_files": { "AGENTS.md": { - "origin_hash": "eb921107a858d512b9778f925bbd3a47c71a04bb569d807f10b38417037f955c", + "origin_hash": "0ff7c4173834e166903ea2434408c1660c22a8f9371604d0ba6f91c3eaf61b78", "path": "AGENTS.md" }, ".claude/settings.json": { @@ -100,7 +100,7 @@ "path": ".gitleaks.toml" }, ".github/workflows/ci.yml": { - "origin_hash": "c84a211fb37ec23cbe9d83c37c80971f722de3c1d7151b388838ca15537517ed", + "origin_hash": "bb626e231a4a872300a034bef0ac9524a35b4eedf190756385f74712a560225e", "path": ".github/workflows/ci.yml" }, ".claude/verify-harness.sh": { diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 55316156..81d5dfe1 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -7,7 +7,7 @@ security scanning. ## Contents -- `ci.yml` — main CI pipeline, four jobs plus three PR-only gates: harness integrity (`.claude/verify-harness.sh`), `pnpm check`/`pnpm exec vitest --run --coverage`/coverage with an 80% changed-line gate (`diff-cover`); a separate `next build` job with dummy Supabase env vars; a Playwright e2e smoke job; a CHANGELOG-required-for-`src/`-changes gate (`skip-changelog` label bypasses); a README-freshness gate requiring every changed folder's `README.md` also be in the diff (`skip-readme-check` label bypasses) — the CI-time counterpart to `.husky/lib/readme-coupling.sh`'s commit-time nudge; a comment-hygiene gate scanning only the PR's added lines (`git diff -U0`) for change-narration comments, using the first 10 (hard-precision) lines of `.claude/comment-hygiene-patterns.txt` (`skip-comment-check` label bypasses) — the CI-time hard gate counterpart to `.husky/lib/comment-hygiene.sh`'s commit-time warn-only nudge and `.claude/hooks/post-edit-comment-check.sh`'s live edit-time nudge, both of which scan the full 13-line pattern file. Also a `db` job (migrations + pgTAP RLS) and a PR-only, advisory `mutation` job that Stryker-mutates whichever `src/lib/*.ts` files the PR touched — its changed-file diff uses `--diff-filter=d` so a PR that only _deletes_ a `src/lib` file (nothing left to mutate) doesn't crash the job trying to mutate a file that no longer exists. +- `ci.yml` — main CI pipeline, four jobs plus three PR-only gates: harness integrity (`.claude/verify-harness.sh`), `pnpm check`/`pnpm exec vitest --run --coverage`/coverage with an 80% changed-line gate (`diff-cover`); a separate `next build` job with dummy Supabase env vars; a Playwright e2e smoke job; a CHANGELOG-required-for-`src/`-changes gate (`skip-changelog` label bypasses); a README-freshness gate requiring every changed folder's `README.md` also be in the diff (`skip-readme-check` label bypasses) — the CI-time counterpart to `.husky/lib/readme-coupling.sh`'s commit-time nudge; a comment-hygiene gate scanning only the PR's added lines (`git diff -U0`) for change-narration comments, using the first 10 (hard-precision) lines of `.claude/comment-hygiene-patterns.txt` (`skip-comment-check` label bypasses) — the CI-time hard gate counterpart to `.husky/lib/comment-hygiene.sh`'s commit-time warn-only nudge and `.claude/hooks/post-edit-comment-check.sh`'s live edit-time nudge, both of which scan the full 13-line pattern file. Also a `db` job (migrations + pgTAP RLS) and a PR-only, advisory `mutation` job that Stryker-mutates whichever `src/lib/*.ts` files the PR touched — its changed-file diff uses `--diff-filter=d` so a PR that only _deletes_ a `src/lib` file (nothing left to mutate) doesn't crash the job trying to mutate a file that no longer exists; type-only `src/lib/db-types/` files are filtered out too, since Stryker finds no tests for them, and a PR with nothing left to mutate exits 0. - `security.yml` — secret scan (gitleaks, full history) + the fail-closed `.claude/deps-gate.sh` dependency audit (`pnpm audit --prod`, high/critical severity); no CodeQL job, since code scanning requires GitHub Advanced Security which isn't available on this private repo's plan The gitleaks job installs the pinned release binary and checks its SHA-256, because gitleaks-action needs a paid license on organization-owned repos. It scans the PR commits, or the pushed range on `main`. - `staging-sync.yml`: on push to `main` (or a manual run), fast-forwards the diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16d83288..99a2dc7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -232,7 +232,7 @@ jobs: git fetch origin "$GITHUB_BASE_REF" --depth=1 CHANGED=$(git diff --name-only --diff-filter=d "origin/$GITHUB_BASE_REF...HEAD") FILES=$(printf '%s\n' "$CHANGED" | awk ' - /^src\/lib\/.*\.ts$/ && !/\.test\.ts$|\/types\.ts$|\/action-result\.ts$|^src\/lib\/supabase\// { + /^src\/lib\/.*\.ts$/ && !/\.test\.ts$|\/types\.ts$|\/action-result\.ts$|^src\/lib\/supabase\/|^src\/lib\/db-types\// { printf "%s%s", separator, $0 separator = "," }') diff --git a/.gitleaksignore b/.gitleaksignore new file mode 100644 index 00000000..aca5a7ff --- /dev/null +++ b/.gitleaksignore @@ -0,0 +1 @@ +3adfac34aa5faadc17b89edfc8e8e7b0be872da0:e2e/core-flow.spec.ts:generic-api-key:10 diff --git a/CHANGELOG.md b/CHANGELOG.md index a94151d5..a02a63c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ 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.8.1] - 2026-12-02 + +### 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). + +## [0.8.0] - 2026-12-02 + +### Added + +- A customer can spend an earned reward at qkit checkout. "Use at qkit checkout" on a reward marks it redeemed and shows a single-use `LK-` code from qkit, with a copy button, in one transaction (migration `0073`, `customer_use_voucher_at_qkit`; a retry returns the same code, and a spent reward stays on /c as "qkit code issued" with a "Show code" button). Vendors set what the code is worth (percent or dollars off) in Profile under "qkit reward code". Free for every vendor. The code expires when the reward does, and the value takes at most two decimals. The customer card list (`customer_join`) now also lists each card's active rewards, which /c never showed before. + +## [0.7.1] - 2026-12-02 + +### Fixed + +- New push-provisioned vendors get a default stamp program named "Stamp card" instead of "Starter" (migration 0073), which read as the retired pricing tier. Existing programs keep their names. +- The Plan page links "Merqo account" to the Merqo dashboard, and the legacy "starter" entitlement tier is normalised to Pro instead of being rejected for loopkit. + ## [0.7.0] - 2026-12-02 ### Changed diff --git a/README.md b/README.md index 11c7089a..32c8d151 100644 --- a/README.md +++ b/README.md @@ -304,7 +304,7 @@ src/lib/merqo-customer-notify.ts — notifyCustomerByPhone/notifyVendor: kit → src/lib/merqo-vendor-status.ts — reports status/metrics to merqo over HTTP src/lib/supabase/ — browser / server / service clients (schema: loopkit) src/components/ — wheel, scratch-card, flame-layers, cup, points-bar, stamp-dots, etc. -supabase/migrations/ — SQL schema + RLS +supabase/migrations/ — SQL schema + RLS (0074: qkit reward codes) ``` Touch devices (@media (pointer: coarse)) get 44px minimum buttons and fields; desktop density is unchanged. See src/app/globals.css. @@ -510,7 +510,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 @@ -556,3 +556,5 @@ Vendor-facing plan-limit copy states what the plan includes and never asks the v Route loading skeletons come from `@merqo/ui` (`ListSkeleton`, `StatTileSkeleton`, `DataTableSkeleton`) under `components/loading-header.tsx`. The counter and setup edit-impact dialogs use the shared `ConfirmDialog`, and the counter empty state uses `EmptyState`. The login and reset-password forms stay local because their zod and React Hook Form validation, wordmark shell and reset-sent notice are not covered by the shared forms. Touch targets on setup chips and overview program links reach 44px on coarse pointers, and visit bars are tappable. Customer-facing selects and buttons (`birthday-field.tsx`, `check-form.tsx`, dashboard `scan-button.tsx`) use the shared `@merqo/ui` Select and Button primitives with 44px touch targets. `/c` without a shop link shows a next-step message and a link home. + +New vendors get a default program named "Stamp card" (migration 0073); the plan page links to the Merqo account and treats the legacy "starter" tier as Pro. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index d9aee5c7..f0bbe918 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -205,7 +205,7 @@ Do the steps in order: **A (Supabase) → B (Vercel) → C (attach to merqo)**. - apply `0032_loopkit_provision_default_program.sql` — adds `provision_default_program(p_vendor_id)`, a service-role-only SECURITY DEFINER function (never granted to `authenticated`) that seeds a default - "Starter" stamp program for a push-provisioned vendor, since + "Stamp card" stamp program for a push-provisioned vendor, since `create_program` is keyed on the calling session's `auth.uid()` and can't run on a vendor's behalf. Advisory-lock-guarded against a double-provision race, idempotent on `loopkit.programs`. Backs diff --git a/docs/README.md b/docs/README.md index d7712a16..afb8d100 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,3 +17,5 @@ spec/plan development history. ## Parent [loopkit](../README.md) + +Deploy notes refer to the default program new vendors receive as "Stamp card". 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..861960f7 --- /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 = "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"; +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 d88acb0b..11e196ca 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loopkit", - "version": "0.7.0", + "version": "0.8.1", "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. diff --git a/src/app/api/merqo/README.md b/src/app/api/merqo/README.md index 1e7bc73f..fd18b214 100644 --- a/src/app/api/merqo/README.md +++ b/src/app/api/merqo/README.md @@ -13,7 +13,7 @@ qkit earn-config, and push-provisions a vendor onto loopkit. - `vendor-activity/` — `GET` endpoint resolving one vendor's programs, cards, and stamp/redeem activity by email, for merqo's cross-kit `/admin/vendors/[email]` detail view. -- `vendor-provision/` — `POST` endpoint that creates a free-tier `vendors` row (and a default "Starter" stamp program) for a vendor id the Merqo hub is one-click-activating on loopkit. +- `vendor-provision/` — `POST` endpoint that creates a free-tier `vendors` row (and a default "Stamp card" stamp program) for a vendor id the Merqo hub is one-click-activating on loopkit. - `vendor-status/` ## Connectivity diff --git a/src/app/api/merqo/vendor-provision/README.md b/src/app/api/merqo/vendor-provision/README.md index aebb0bde..98c97729 100644 --- a/src/app/api/merqo/vendor-provision/README.md +++ b/src/app/api/merqo/vendor-provision/README.md @@ -2,7 +2,7 @@ ## Purpose -Push-provisioning endpoint: Merqo hub calls this to activate loopkit for a vendor who hasn't signed up directly, keyed on their existing (shared) `auth.users.id`. Creates the vendor row AND a default "Starter" stamp program (loopkit's own `create_program` RPC can't be used here — see `provision_default_program`'s migration comment) so the vendor is genuinely active immediately, not left without a program. +Push-provisioning endpoint: Merqo hub calls this to activate loopkit for a vendor who hasn't signed up directly, keyed on their existing (shared) `auth.users.id`. Creates the vendor row AND a default "Stamp card" stamp program (loopkit's own `create_program` RPC can't be used here — see `provision_default_program`'s migration comment) so the vendor is genuinely active immediately, not left without a program. ## Contents diff --git a/src/app/dashboard/README.md b/src/app/dashboard/README.md index 25a48238..21ee703e 100644 --- a/src/app/dashboard/README.md +++ b/src/app/dashboard/README.md @@ -95,3 +95,7 @@ Dates and times on these pages render through `@merqo/ui`'s `formatDate`/`format The account menu shows the shared "Text size · 100%" submenu (a preset list under the Preferences label): `dashboard-nav.tsx` passes `textSizeKey="loopkit:scale:dashboard"` to `SharedDashboardNav` (`@merqo/ui` v0.68.0), so the scale applies to the dashboard only and persists per browser. `scan-button.tsx` renders its link and hero variants with the shared `Button` (44px minimum height) instead of native buttons. + +- `qkit-reward-code-action.test.ts` — unit tests for `saveQkitRewardCodeAction`: percent and dollar saves, two-decimal limit, range, clearing +- `qkit-reward-code-settings.dom.test.tsx` — jsdom tests for `QkitRewardCodeSettings`: saved value shown, empty when unset, entered value submitted +- `qkit-reward-code-settings.tsx` — client `QkitRewardCodeSettings` form (no Pro gate): code type (off, percent, dollars) and value, saved through `saveQkitRewardCodeAction` into `vendor_notify_settings` diff --git a/src/app/dashboard/plan/README.md b/src/app/dashboard/plan/README.md index ae62503d..b82b8a1f 100644 --- a/src/app/dashboard/plan/README.md +++ b/src/app/dashboard/plan/README.md @@ -19,3 +19,5 @@ Vendor billing/plan page at `/dashboard/plan`, shows Free vs. Pro feature compar Each page exports its own `metadata.title`, shown through the root `loopkit | %s` template. UI copy is plain: no emoji, no em dashes, no contractions in errors. - `page.tsx` renders its title row with `PageHeader`; `loading.tsx` uses `ListSkeleton`. + +The "Merqo account" line is a link built from `merqoBaseUrl()`, and the pricing ladder highlights the paid slug. diff --git a/src/app/dashboard/plan/page.tsx b/src/app/dashboard/plan/page.tsx index a0cf6530..af1d045c 100644 --- a/src/app/dashboard/plan/page.tsx +++ b/src/app/dashboard/plan/page.tsx @@ -13,7 +13,12 @@ import { Badge } from "@merqo/ui/primitives"; // merqo-ui's tierLabel lives in a client-only module and crashes when called // from a Server Component, so this page keeps its own copy of the labels. -const TIER_LABEL = { free: "Free", starter: "Starter", pro: "Pro" } as const; +const TIER_LABEL = { free: "Free", pro: "Pro" } as const; + +// The ladder only accepts "qkit" or "all_access" as a highlight and the +// catalog has no loopkit-only plan; the qkit plan includes full loopkit, so +// a Pro vendor sits on that entry. Loopkit's own wire tier is "paid". +const LADDER_HIGHLIGHT = "qkit"; export const metadata = { title: "Plan" }; @@ -77,13 +82,20 @@ export default async function PlanPage({ {pro ? "You're on Pro, unlimited loyalty programs are unlocked. " : "You're on Free, with one active loyalty program. "} - Change plan from your Merqo account. + Change plan from your{" "} + + Merqo account + + . {catalog ? ( diff --git a/src/app/dashboard/plan/plan-page.dom.test.tsx b/src/app/dashboard/plan/plan-page.dom.test.tsx index b4abbf33..8eea7ece 100644 --- a/src/app/dashboard/plan/plan-page.dom.test.tsx +++ b/src/app/dashboard/plan/plan-page.dom.test.tsx @@ -82,9 +82,8 @@ describe("PlanPage", () => { expect(card).toHaveTextContent("qkit"); expect(card).not.toHaveTextContent("All-Access"); expect(screen.queryByText(/event pass/i)).not.toBeInTheDocument(); - expect( - screen.getByText(/change plan from your merqo account/i), - ).toBeInTheDocument(); + const link = screen.getByRole("link", { name: /merqo account/i }); + expect(link).toHaveAttribute("href", expect.stringMatching(/\/dashboard$/)); }); it("sends the kit bearer to the plan catalog when the secret is set", async () => { diff --git a/src/app/dashboard/profile/README.md b/src/app/dashboard/profile/README.md index 7ed99855..98f93b5e 100644 --- a/src/app/dashboard/profile/README.md +++ b/src/app/dashboard/profile/README.md @@ -10,7 +10,7 @@ Shared controls and `cn` used by this folder's modules are imported from `@merqo - `actions.test.ts` — unit tests for `updateSocialLinksAction`: saves valid links while preserving the existing `stall_name`, rejects an invalid URL without calling `patchVendorProfile`, errors when not signed in, and errors (without revalidating) when the field-specific patch fails. - `actions.ts` — server actions `updateStallNameAction()` (thin wrapper around `saveStallName`, `src/lib/vendor.ts`, revalidates the dashboard layout), `updatePasswordAction()` (Zod-validates an 8-72 char password, updates it via the Supabase auth client), and `updateSocialLinksAction()` (Zod-validates each link as an optional URL, uses a field-specific shared-profile patch for `social_links`, preserving concurrent stall-name changes). -- `page.tsx` — `ProfilePage` server component (also hosts the former Settings page: an `#integrations` block with `QkitEarnSettings` and `CustomerNotifySettings`, loaded from `qkit_earn_config` / `vendor_notify_settings`; with no `qkit_earn_config` row the oldest active stamp program is passed as already on, mirroring `qkit_earn_resolve_program`); requires a vendor, loads the vendor profile (`getVendorProfile()`, `src/lib/vendor.ts`) and auth `user_metadata` display name, reads the shared `merqo.vendor_profile` row's `social_links` (degrading to `{}` on failure, same pattern as `/setup`'s page), and renders `@merqo/ui`'s `BackButton` ("Back to dashboard") above `ProfileForm`. Its root element is `
` — deliberately narrower than the `../layout.tsx` `
`'s shared `max-w-7xl` (this form genuinely reads better constrained), so it nests its own `mx-auto`/`max-w-*` wrapper inside that container rather than stretching full-width; the page no longer sets its own padding, which the layout's `
` now owns. +- `page.tsx` — `ProfilePage` server component (also hosts the former Settings page: an `#integrations` block with `QkitEarnSettings` and `CustomerNotifySettings`, loaded from `qkit_earn_config` / `vendor_notify_settings`, plus a free "qkit reward code" section (`QkitRewardCodeSettings`, reads `qkit_code_kind`/`qkit_code_value`); with no `qkit_earn_config` row the oldest active stamp program is passed as already on, mirroring `qkit_earn_resolve_program`); requires a vendor, loads the vendor profile (`getVendorProfile()`, `src/lib/vendor.ts`) and auth `user_metadata` display name, reads the shared `merqo.vendor_profile` row's `social_links` (degrading to `{}` on failure, same pattern as `/setup`'s page), and renders `@merqo/ui`'s `BackButton` ("Back to dashboard") above `ProfileForm`. Its root element is `
` — deliberately narrower than the `../layout.tsx` `
`'s shared `max-w-7xl` (this form genuinely reads better constrained), so it nests its own `mx-auto`/`max-w-*` wrapper inside that container rather than stretching full-width; the page no longer sets its own padding, which the layout's `
` now owns. - `profile-form.dom.test.tsx` — jsdom tests for `ProfileForm`: renders all 5 sections, prefills the social-links fields from `socialLinks` and saves them via `updateSocialLinksAction`, saves the stall name via `updateStallNameAction`. - `profile-form.tsx` — `ProfileForm` client component; `@merqo/ui`'s `TwoColumnSections` (column 1: stall name, profile icon, change password; column 2: display name, social links — the locked cross-kit order) of five independently-saving `Section` cards (stall name via server action, social/website links via `@merqo/ui`'s `SocialLinksFields` + server action, avatar via `@merqo/ui`'s `ImageUploader` + browser auth client, display name via browser auth client, password change with client-side confirm match). diff --git a/src/app/dashboard/profile/page.tsx b/src/app/dashboard/profile/page.tsx index b4433371..f14fc34a 100644 --- a/src/app/dashboard/profile/page.tsx +++ b/src/app/dashboard/profile/page.tsx @@ -6,6 +6,7 @@ import { getOrCreateVendorProfile } from "@/lib/merqo-vendor-profile"; import { ProfileForm } from "@/app/dashboard/profile/profile-form"; import { listPrograms } from "@/lib/program"; import { QkitEarnSettings } from "@/app/dashboard/qkit-earn-settings"; +import { QkitRewardCodeSettings } from "@/app/dashboard/qkit-reward-code-settings"; import { CustomerNotifySettings } from "@/app/dashboard/customer-notify-settings"; import type { SocialLinks } from "@/lib/types"; @@ -28,7 +29,9 @@ export default async function ProfilePage() { .maybeSingle(), supabase .from("vendor_notify_settings") - .select("customer_telegram_notify_enabled") + .select( + "customer_telegram_notify_enabled, qkit_code_kind, qkit_code_value", + ) .eq("vendor_id", user.id) .maybeSingle(), ]); @@ -100,6 +103,22 @@ export default async function ProfilePage() { current={qkitCurrent} />
+
+

+ qkit reward code +

+ +

Customer notifications diff --git a/src/app/dashboard/qkit-reward-code-action.test.ts b/src/app/dashboard/qkit-reward-code-action.test.ts new file mode 100644 index 00000000..fa2118b3 --- /dev/null +++ b/src/app/dashboard/qkit-reward-code-action.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const upsertMock = vi.fn(); + +vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })); +vi.mock("@/features/auth", () => ({ + requireVendor: vi.fn(async () => ({ user: { id: "vendor-1" } })), +})); +vi.mock("@/lib/program", () => ({ isPro: vi.fn() })); +vi.mock("@/lib/supabase/server", () => ({ + createServerClient: vi.fn(async () => ({ + from: () => ({ upsert: upsertMock }), + })), +})); + +import { saveQkitRewardCodeAction } from "./settings-actions"; + +function form(kind: string, value?: string) { + const fd = new FormData(); + fd.set("kind", kind); + if (value !== undefined) fd.set("value", value); + return fd; +} + +describe("saveQkitRewardCodeAction", () => { + beforeEach(() => { + vi.clearAllMocks(); + upsertMock.mockResolvedValue({ error: null }); + }); + + it("saves a percent code", async () => { + expect(await saveQkitRewardCodeAction(form("percent", "15"))).toEqual({ + success: true, + }); + expect(upsertMock).toHaveBeenCalledWith( + { vendor_id: "vendor-1", qkit_code_kind: "percent", qkit_code_value: 15 }, + { onConflict: "vendor_id" }, + ); + }); + + it("accepts a two-decimal dollar value", async () => { + const res = await saveQkitRewardCodeAction(form("fixed", "2.50")); + expect(res.success).toBe(true); + }); + + it("rejects more than two decimals", async () => { + const res = await saveQkitRewardCodeAction(form("fixed", "2.505")); + expect(res.success).toBe(false); + expect(upsertMock).not.toHaveBeenCalled(); + }); + + it("rejects a percent out of range", async () => { + const res = await saveQkitRewardCodeAction(form("percent", "101")); + expect(res.success).toBe(false); + }); + + it("clears both columns for none", async () => { + await saveQkitRewardCodeAction(form("none")); + expect(upsertMock).toHaveBeenCalledWith( + { vendor_id: "vendor-1", qkit_code_kind: null, qkit_code_value: null }, + { onConflict: "vendor_id" }, + ); + }); +}); diff --git a/src/app/dashboard/qkit-reward-code-settings.dom.test.tsx b/src/app/dashboard/qkit-reward-code-settings.dom.test.tsx new file mode 100644 index 00000000..9a7ecb69 --- /dev/null +++ b/src/app/dashboard/qkit-reward-code-settings.dom.test.tsx @@ -0,0 +1,33 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; + +const { saveMock } = vi.hoisted(() => ({ + saveMock: vi.fn().mockResolvedValue({ success: true }), +})); +vi.mock("./settings-actions", () => ({ saveQkitRewardCodeAction: saveMock })); + +import { QkitRewardCodeSettings } from "./qkit-reward-code-settings"; + +describe("QkitRewardCodeSettings", () => { + it("shows the saved value", () => { + render(); + expect(screen.getByLabelText("Value")).toHaveValue(15); + }); + + it("starts empty when nothing is saved", () => { + render(); + expect(screen.getByLabelText("Value")).toHaveValue(null); + }); + + it("submits the entered value", async () => { + const user = userEvent.setup(); + render(); + await user.clear(screen.getByLabelText("Value")); + await user.type(screen.getByLabelText("Value"), "3.5"); + await user.click(screen.getByRole("button", { name: "Save" })); + const fd = saveMock.mock.calls[0][0] as FormData; + expect(fd.get("value")).toBe("3.5"); + }); +}); diff --git a/src/app/dashboard/qkit-reward-code-settings.tsx b/src/app/dashboard/qkit-reward-code-settings.tsx new file mode 100644 index 00000000..a6f1bba3 --- /dev/null +++ b/src/app/dashboard/qkit-reward-code-settings.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { FormCard } from "@/components/form-card"; +import { useSaveSettings } from "@/hooks/use-save-settings"; +import { saveQkitRewardCodeAction } from "./settings-actions"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, + Input, + Label, + Button, +} from "@merqo/ui/primitives"; + +export function QkitRewardCodeSettings({ + current, +}: { + current: { kind: "percent" | "fixed"; value: number } | null; +}) { + const { pending, save } = useSaveSettings(saveQkitRewardCodeAction); + + return ( + +

+ When a customer spends a reward at qkit checkout, they get a one-time + code worth this much. Leave it off to stop offering codes. +

+
+
+ + +
+
+ + +
+
+ +
+ ); +} diff --git a/src/app/dashboard/settings-actions.ts b/src/app/dashboard/settings-actions.ts index 9537fcfc..6a5561bf 100644 --- a/src/app/dashboard/settings-actions.ts +++ b/src/app/dashboard/settings-actions.ts @@ -1,6 +1,7 @@ "use server"; import { revalidatePath } from "next/cache"; +import { z } from "zod"; import { requireVendor } from "@/features/auth"; import { createServerClient } from "@/lib/supabase/server"; import type { ActionResult } from "@merqo/ui/kit-api"; @@ -69,3 +70,46 @@ export async function saveCustomerNotifySettingsAction( revalidatePath("/dashboard/profile"); return { success: true, enabled }; } + +const qkitRewardCodeSchema = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("none") }), + z.object({ + kind: z.literal("percent"), + value: z.coerce.number().min(1).max(100).multipleOf(0.01), + }), + z.object({ + kind: z.literal("fixed"), + value: z.coerce.number().gt(0).max(100000).multipleOf(0.01), + }), +]); + +// Free for every vendor; "none" clears both columns, which the DB check ties together. +export async function saveQkitRewardCodeAction( + formData: FormData, +): Promise { + const { user } = await requireVendor(); + const parsed = qkitRewardCodeSchema.safeParse({ + kind: formData.get("kind"), + value: formData.get("value"), + }); + if (!parsed.success) { + return { success: false, error: "Enter a valid value for the code." }; + } + + const supabase = await createServerClient(); + const { error } = await supabase.from("vendor_notify_settings").upsert( + { + vendor_id: user.id, + qkit_code_kind: parsed.data.kind === "none" ? null : parsed.data.kind, + qkit_code_value: parsed.data.kind === "none" ? null : parsed.data.value, + }, + { onConflict: "vendor_id" }, + ); + if (error) { + console.error("saveQkitRewardCodeAction failed", error.message); + return { success: false, error: "Something went wrong." }; + } + + revalidatePath("/dashboard/profile"); + return { success: true }; +} diff --git a/src/features/card-check/README.md b/src/features/card-check/README.md index afd7ac0f..20a1e2d9 100644 --- a/src/features/card-check/README.md +++ b/src/features/card-check/README.md @@ -12,9 +12,9 @@ Lost capability recovery requires the owning shop, which rotates credentials whi - `components/` - `index.ts` — barrel re-exporting `CheckForm` - `types.ts` — shared `CardStatus`/`StatusState` types and the - `STATUS_IDLE` constant. `CardStatus.activeVouchers` (Points Club catalog - mode only, empty array for every other mechanic) lists each currently + `STATUS_IDLE` constant. `CardStatus.activeVouchers` (every program type; empty when none) lists each currently active voucher's own id/reward text/expiry/pre-rendered QR. + Each voucher also carries `codeIssued`, true once it was spent for a qkit code (shown as "qkit code issued" with a "Show code" button). `MarketingStatus` (`StatusState.marketing`) carries the current consent state, the shop name its wording is rendered from and whether a save failed diff --git a/src/features/card-check/api/README.md b/src/features/card-check/api/README.md index c85ea6fa..45cdc9fd 100644 --- a/src/features/card-check/api/README.md +++ b/src/features/card-check/api/README.md @@ -13,7 +13,7 @@ Responses are schema validated. Transport and malformed-response failures produc ## Contents - `check-status-action.ts` — `checkStatusAction`: validates the join form, rate limits, calls `customer_join`, saves the proof cookie, syncs marketing consent, credits a pending referral and builds the card view -- `card-actions.ts` — `regenerateCardAction`, `setCustomerBirthdayAction` and `selectPointsRewardAction`: proof-checked card mutations that each return a generic retry message on failure +- `card-actions.ts` — `regenerateCardAction`, `setCustomerBirthdayAction` and `selectPointsRewardAction` and `spendVoucherAtQkitAction` (spends a voucher for a qkit `LK-` code): proof-checked card mutations that each return a generic retry message on failure - `consent-actions.ts` — `setMarketingConsentAction` (the card-view switch) and `eraseMyDataAction` (self-service erase with one generic failure message) - `join-payload.ts` — `joinPayloadSchema` and `VendorJoinRow` for the `customer_join` response, plus the best-effort referral credit helpers - `card-status-builder.ts` — `buildCardStatus`: turns one joined row into a `CardStatus` with progress, QR, expiry and active-voucher QRs diff --git a/src/features/card-check/api/actions.test.ts b/src/features/card-check/api/actions.test.ts index 0e77f5cf..69c7e725 100644 --- a/src/features/card-check/api/actions.test.ts +++ b/src/features/card-check/api/actions.test.ts @@ -45,6 +45,7 @@ import { checkStatusAction } from "./check-status-action"; import { setCustomerBirthdayAction, selectPointsRewardAction, + spendVoucherAtQkitAction, regenerateCardAction, } from "./card-actions"; import { @@ -434,6 +435,36 @@ describe("setCustomerBirthdayAction", () => { describe("checkStatusAction surfaces active_vouchers", () => { beforeEach(() => vi.clearAllMocks()); + it("flags a voucher already spent for a qkit code", async () => { + rpcMock.mockResolvedValue({ + data: { + cards: [ + { + ...baseRow, + active_vouchers: [ + { + id: "00550000-0000-4000-8000-000000000002", + voucher_token: "c".repeat(32), + reward_text: "Free coffee", + expires_at: null, + qkit_code_issued: true, + }, + ], + }, + ], + }, + error: null, + }); + const result = await checkStatusAction( + STATUS_IDLE, + formData({ + phone: "91234567", + vendor: "00550000-0000-4000-8000-000000000001", + }), + ); + expect(result.cards?.[0].activeVouchers[0].codeIssued).toBe(true); + }); + it("renders each active voucher's own QR", async () => { rpcMock.mockResolvedValue({ data: { @@ -1103,3 +1134,58 @@ describe("eraseMyDataAction", () => { expect(rpcMock).not.toHaveBeenCalled(); }); }); + +describe("spendVoucherAtQkitAction", () => { + const vendor = "00550000-0000-4000-8000-000000000001"; + const voucher = "00550000-0000-4000-8000-000000000101"; + const fields = { vendor, voucher, phone: "91234567" }; + + beforeEach(() => rpcMock.mockReset()); + + it("returns the code from the RPC with the saved proof", async () => { + rpcMock.mockResolvedValue({ data: "LK-ABCD1234", error: null }); + const res = await spendVoucherAtQkitAction(formData(fields)); + expect(res).toEqual({ success: true, code: "LK-ABCD1234" }); + expect(rpcMock).toHaveBeenCalledWith("customer_use_voucher_at_qkit", { + p_vendor: vendor, + p_phone: "+6591234567", + p_token: "a".repeat(32), + p_voucher: voucher, + }); + }); + + it("asks for a saved card when there is no proof", async () => { + readProof.mockResolvedValueOnce(null); + const res = await spendVoucherAtQkitAction(formData(fields)); + expect(res.success).toBe(false); + expect(rpcMock).not.toHaveBeenCalled(); + }); + + it("rejects a malformed voucher id", async () => { + const res = await spendVoucherAtQkitAction( + formData({ ...fields, voucher: "nope" }), + ); + expect(res).toEqual({ success: false, error: "Missing reward." }); + }); + + it("maps an unconfigured shop to a clear message", async () => { + rpcMock.mockResolvedValue({ + data: null, + error: { message: "qkit_code_not_configured" }, + }); + const res = await spendVoucherAtQkitAction(formData(fields)); + expect(res).toEqual({ + success: false, + error: "This shop has not set up qkit reward codes.", + }); + }); + + it("hides unknown database errors", async () => { + rpcMock.mockResolvedValue({ data: null, error: { message: "boom" } }); + const res = await spendVoucherAtQkitAction(formData(fields)); + expect(res).toEqual({ + success: false, + error: "Something went wrong. Try again.", + }); + }); +}); diff --git a/src/features/card-check/api/card-actions.ts b/src/features/card-check/api/card-actions.ts index 73b4cf75..cf888518 100644 --- a/src/features/card-check/api/card-actions.ts +++ b/src/features/card-check/api/card-actions.ts @@ -93,6 +93,52 @@ async function setCustomerBirthdayActionImpl( return { success: true }; } +async function spendVoucherAtQkitActionImpl( + formData: FormData, +): Promise> { + const normalized = normalizePhone(String(formData.get("phone") ?? "")); + if (!normalized.ok) { + return { success: false, error: "Enter a valid Singapore phone number." }; + } + const voucherId = String(formData.get("voucher") ?? ""); + if (!z.uuid().safeParse(voucherId).success) { + return { success: false, error: "Missing reward." }; + } + const vendorId = String(formData.get("vendor") ?? ""); + if (!vendorIdSchema.safeParse(vendorId).success) + return { success: false, error: "Missing shop." }; + const proof = await readCustomerProof(vendorId); + if (!proof) + return { + success: false, + error: "Use your saved card code or ask the shop to recover your card.", + }; + + const supabase = await createServiceClient(); + const { data: code, error } = await supabase.rpc( + "customer_use_voucher_at_qkit", + { + p_vendor: vendorId, + p_phone: normalized.phone, + p_token: proof, + p_voucher: voucherId, + }, + ); + if (error || !code) { + const messages: Record = { + qkit_code_not_configured: "This shop has not set up qkit reward codes.", + already_redeemed: "This reward has already been used.", + expired: "This reward has expired.", + }; + return { + success: false, + error: + messages[error?.message ?? ""] ?? "Something went wrong. Try again.", + }; + } + return { success: true, code }; +} + async function selectPointsRewardActionImpl( formData: FormData, ): Promise< @@ -184,3 +230,13 @@ export async function selectPointsRewardAction( }; } } + +export async function spendVoucherAtQkitAction( + formData: FormData, +): Promise> { + try { + return await spendVoucherAtQkitActionImpl(formData); + } catch { + return { success: false, error: "Something went wrong. Try again." }; + } +} diff --git a/src/features/card-check/api/card-status-builder.ts b/src/features/card-check/api/card-status-builder.ts index f17a350e..d5efea52 100644 --- a/src/features/card-check/api/card-status-builder.ts +++ b/src/features/card-check/api/card-status-builder.ts @@ -9,6 +9,7 @@ type RawVoucher = { voucher_token: string; reward_text: string; expires_at: string | null; + qkit_code_issued?: boolean; }; async function buildActiveVouchers(row: VendorJoinRow) { @@ -20,6 +21,7 @@ async function buildActiveVouchers(row: VendorJoinRow) { id: v.id, rewardText: v.reward_text, expiresAt: v.expires_at, + codeIssued: v.qkit_code_issued === true, qr: await qrSvg(v.voucher_token), })), ); diff --git a/src/features/card-check/api/join-payload.ts b/src/features/card-check/api/join-payload.ts index fb456aa7..c53990d8 100644 --- a/src/features/card-check/api/join-payload.ts +++ b/src/features/card-check/api/join-payload.ts @@ -46,6 +46,7 @@ export const joinPayloadSchema = z.object({ voucher_token: customerTokenSchema, reward_text: z.string(), expires_at: z.string().nullable(), + qkit_code_issued: z.boolean().optional().default(false), }), ) .optional() diff --git a/src/features/card-check/components/README.md b/src/features/card-check/components/README.md index d00aeacf..270fcfaf 100644 --- a/src/features/card-check/components/README.md +++ b/src/features/card-check/components/README.md @@ -25,4 +25,6 @@ Customer-facing copy has no emoji or contractions. `birthday-field.tsx` uses the shared Select for month and day (44px triggers) and `check-form.tsx` renders "Change number" with the shared `Button`. +`use-at-qkit-button.tsx` is the "Use at qkit checkout" control on each voucher: it confirms, calls `spendVoucherAtQkitAction`, then shows the `LK-` code with a copy button; a voucher already spent for a code shows "Show code" instead, which re-calls the action and gets the same code; `use-at-qkit-button.dom.test.tsx` covers it. + `program-card-status.tsx` (retired-card notice) uses the shared `readStored`/`writeStored`/`useMediaQuery` helpers from `@merqo/ui` instead of local storage and media-query code, as do the visits trend, remember-program and serve-cta modules elsewhere in this slice. diff --git a/src/features/card-check/components/program-card-status.dom.test.tsx b/src/features/card-check/components/program-card-status.dom.test.tsx index 6e2ec770..00823ab7 100644 --- a/src/features/card-check/components/program-card-status.dom.test.tsx +++ b/src/features/card-check/components/program-card-status.dom.test.tsx @@ -312,6 +312,7 @@ describe("ProgramCardStatus points catalog mode", () => { id: "v1", rewardText: "Free drink", expiresAt: null, + codeIssued: false, qr: "mock", }, ], diff --git a/src/features/card-check/components/program-card-status.tsx b/src/features/card-check/components/program-card-status.tsx index 22757422..e26cee0d 100644 --- a/src/features/card-check/components/program-card-status.tsx +++ b/src/features/card-check/components/program-card-status.tsx @@ -7,6 +7,7 @@ import { regenerateCardAction } from "../api/card-actions"; import type { CardStatus } from "../types"; import { PointsCatalogPicker } from "./points-catalog-picker"; +import { UseAtQkitButton } from "./use-at-qkit-button"; import { CardShell } from "@/components/card-shell"; import { @@ -146,16 +147,31 @@ export function ProgramCardStatus({

Your rewards

- {[...card.activeVouchers, ...freshVouchers].map((v) => ( + {[ + ...card.activeVouchers, + ...freshVouchers.map((v) => ({ ...v, codeIssued: false })), + ].map((v) => (

{v.rewardText}

-
+ qkit code issued +

+ ) : ( +
+ )} +
))} diff --git a/src/features/card-check/components/use-at-qkit-button.dom.test.tsx b/src/features/card-check/components/use-at-qkit-button.dom.test.tsx new file mode 100644 index 00000000..977fac0e --- /dev/null +++ b/src/features/card-check/components/use-at-qkit-button.dom.test.tsx @@ -0,0 +1,74 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; + +const { spendMock, toastSuccess } = vi.hoisted(() => ({ + spendMock: vi.fn(), + toastSuccess: vi.fn(), +})); +vi.mock("../api/card-actions", () => ({ spendVoucherAtQkitAction: spendMock })); +vi.mock("sonner", () => ({ + toast: { success: toastSuccess, error: vi.fn() }, +})); + +import { UseAtQkitButton } from "./use-at-qkit-button"; + +function setup() { + render(); +} + +describe("UseAtQkitButton", () => { + beforeEach(() => { + spendMock.mockReset(); + toastSuccess.mockReset(); + }); + + it("shows the code after confirming and copies it", async () => { + spendMock.mockResolvedValue({ success: true, code: "LK-ABCD1234" }); + const writeText = vi.fn().mockResolvedValue(undefined); + const user = userEvent.setup(); + Object.defineProperty(navigator, "clipboard", { + value: { writeText }, + configurable: true, + }); + setup(); + await user.click( + screen.getByRole("button", { name: /use at qkit checkout/i }), + ); + await user.click(screen.getByRole("button", { name: "Get code" })); + expect(await screen.findByText("LK-ABCD1234")).toBeInTheDocument(); + const fd = spendMock.mock.calls[0][0] as FormData; + expect(fd.get("voucher")).toBe("r1"); + await user.click(screen.getByRole("button", { name: "Copy code" })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith("LK-ABCD1234")); + expect(toastSuccess).toHaveBeenCalledWith("Code copied."); + }); + + it("keeps the button when the action fails", async () => { + spendMock.mockResolvedValue({ success: false, error: "Not set up." }); + const user = userEvent.setup(); + setup(); + await user.click( + screen.getByRole("button", { name: /use at qkit checkout/i }), + ); + await user.click(screen.getByRole("button", { name: "Get code" })); + await waitFor(() => expect(spendMock).toHaveBeenCalled()); + expect(screen.queryByText(/^LK-/)).not.toBeInTheDocument(); + }); + + it("shows the code again for a voucher that already issued one, with no confirm step", async () => { + spendMock.mockResolvedValue({ success: true, code: "LK-SAME0001" }); + const user = userEvent.setup(); + render( + , + ); + await user.click(screen.getByRole("button", { name: "Show code" })); + expect(await screen.findByText("LK-SAME0001")).toBeInTheDocument(); + }); +}); diff --git a/src/features/card-check/components/use-at-qkit-button.tsx b/src/features/card-check/components/use-at-qkit-button.tsx new file mode 100644 index 00000000..34b050fb --- /dev/null +++ b/src/features/card-check/components/use-at-qkit-button.tsx @@ -0,0 +1,104 @@ +"use client"; + +import { useState } from "react"; +import { toast } from "sonner"; +import { spendVoucherAtQkitAction } from "../api/card-actions"; +import { Button } from "@merqo/ui/primitives"; +import { ConfirmDialog } from "@merqo/ui"; + +export function UseAtQkitButton({ + vendorId, + phone, + voucherId, + issued = false, +}: { + vendorId: string; + phone: string; + voucherId: string; + issued?: boolean; +}) { + const [code, setCode] = useState(null); + + async function confirm() { + const fd = new FormData(); + fd.set("vendor", vendorId); + fd.set("phone", phone); + fd.set("voucher", voucherId); + let res: Awaited>; + try { + res = await spendVoucherAtQkitAction(fd); + } catch { + throw new Error("Something went wrong. Try again."); + } + if (!res.success) throw new Error(res.error); + setCode(res.code); + } + + async function copy() { + if (!code) return; + try { + await navigator.clipboard.writeText(code); + toast.success("Code copied."); + } catch { + toast.error("Could not copy. Select the code instead."); + } + } + + if (code) { + return ( +
+

+ Enter this code at qkit checkout. It works once. +

+ + {code} + + +
+ ); + } + + if (issued) { + return ( + + ); + } + + return ( + + Use at qkit checkout + + } + /> + ); +} diff --git a/src/features/card-check/types.ts b/src/features/card-check/types.ts index c307971f..c7b4dd6d 100644 --- a/src/features/card-check/types.ts +++ b/src/features/card-check/types.ts @@ -24,6 +24,7 @@ export type CardStatus = { id: string; rewardText: string; expiresAt: string | null; + codeIssued: boolean; qr: string; }[]; }; diff --git a/src/lib/README.md b/src/lib/README.md index a6acd500..c46e5f49 100644 --- a/src/lib/README.md +++ b/src/lib/README.md @@ -156,3 +156,5 @@ card updates are not a transactional snapshot across separate HTTP reads. `merqo-vendor-activity.ts`'s `computeVendorActivity(isPro, { programs, cards, events }, nowMs)` and `program-config.ts`'s `buildChanceConfig(variant, segments, { pityCeiling, rewardText, scratchCoverStyle })` take grouped arguments. Colour values for the mechanic art live in `tokens/`. Empty activity cells use "-" and errors spell out "could not". + +`merqo-entitlement-contract.ts` normalises the legacy "starter" tier to paid (loopkit) or qkit so such a vendor is never treated as Free. diff --git a/src/lib/db-types/README.md b/src/lib/db-types/README.md index 8a0b2868..eb61da29 100644 --- a/src/lib/db-types/README.md +++ b/src/lib/db-types/README.md @@ -9,9 +9,9 @@ keep importing `Database`, `Json` and `SocialLinks` from `@/lib/types`. ## Contents - `common.ts` — `Json`, `SocialLinks` (shape of the shared `merqo.vendor_profile.social_links` JSONB column, not part of the `loopkit` schema), `MarketingConsentSource`, `EntitlementTier` and `EntitlementStatsWindow` -- `tables-core.ts` — `CoreTables`: Row/Insert/Update for `programs`, `cards`, `stamp_events`, `reward_vouchers`, `admins` and `admin_audit` -- `tables-vendor-customer.ts` — `VendorCustomerTables`: Row/Insert/Update for the vendor, qkit earn, customer, feedback, marketing consent, notify settings, referral and legal-check tables -- `functions.ts` — `DatabaseFunctions`: Args/Returns for every RPC in the `loopkit` schema +- `tables-core.ts` — `CoreTables`: Row/Insert/Update for `programs`, `cards`, `stamp_events`, `reward_vouchers` (incl. `qkit_code_issued_at`), `admins` and `admin_audit` +- `tables-vendor-customer.ts` — `VendorCustomerTables`: Row/Insert/Update for the vendor, qkit earn, customer, feedback, marketing consent, notify settings (incl. the qkit reward code kind and value), referral and legal-check tables +- `functions.ts` — `DatabaseFunctions`: Args/Returns for every RPC in the `loopkit` schema (incl. `customer_use_voucher_at_qkit`) - `database.ts` — `Database`: composes the table groups and `DatabaseFunctions` under the `loopkit` schema key (keep that key in sync with `db.schema` in `src/lib/supabase/`) ## Regenerating diff --git a/src/lib/db-types/functions.ts b/src/lib/db-types/functions.ts index 8b02ed3a..f95130cf 100644 --- a/src/lib/db-types/functions.ts +++ b/src/lib/db-types/functions.ts @@ -273,6 +273,15 @@ export type DatabaseFunctions = { }; Returns: Database["loopkit"]["Tables"]["reward_vouchers"]["Row"]; }; + customer_use_voucher_at_qkit: { + Args: { + p_vendor: string; + p_phone: string; + p_token: string; + p_voucher: string; + }; + Returns: string; + }; customer_erase: { Args: { p_vendor: string; p_phone: string; p_token: string }; Returns: boolean; diff --git a/src/lib/db-types/tables-core.ts b/src/lib/db-types/tables-core.ts index 5abbaa9b..7d7cea41 100644 --- a/src/lib/db-types/tables-core.ts +++ b/src/lib/db-types/tables-core.ts @@ -146,6 +146,7 @@ export type CoreTables = { status: string; updated_at: string; voucher_token: string | null; + qkit_code_issued_at: string | null; }; Insert: { id?: string; @@ -158,6 +159,7 @@ export type CoreTables = { status?: string; updated_at?: string; voucher_token?: string | null; + qkit_code_issued_at?: string | null; }; Update: { id?: string; @@ -170,6 +172,7 @@ export type CoreTables = { status?: string; updated_at?: string; voucher_token?: string | null; + qkit_code_issued_at?: string | null; }; Relationships: []; }; diff --git a/src/lib/db-types/tables-vendor-customer.ts b/src/lib/db-types/tables-vendor-customer.ts index 57c3b5f3..3f1c4541 100644 --- a/src/lib/db-types/tables-vendor-customer.ts +++ b/src/lib/db-types/tables-vendor-customer.ts @@ -200,16 +200,22 @@ export type VendorCustomerTables = { Row: { vendor_id: string; customer_telegram_notify_enabled: boolean; + qkit_code_kind: string | null; + qkit_code_value: number | null; updated_at: string; }; Insert: { vendor_id: string; customer_telegram_notify_enabled?: boolean; + qkit_code_kind?: string | null; + qkit_code_value?: number | null; updated_at?: string; }; Update: { vendor_id?: string; customer_telegram_notify_enabled?: boolean; + qkit_code_kind?: string | null; + qkit_code_value?: number | null; updated_at?: string; }; Relationships: []; diff --git a/src/lib/merqo-entitlement-contract.test.ts b/src/lib/merqo-entitlement-contract.test.ts new file mode 100644 index 00000000..41900994 --- /dev/null +++ b/src/lib/merqo-entitlement-contract.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { entitlementPayloadSchema } from "./merqo-entitlement-contract"; +import { isPaidEntitlement } from "./entitlement-cache"; + +const base = { + email: "v@example.com", + founder: false, + stats_window: "90d", + event_pass: null, + valid_until: null, + issued_at: "2026-12-01T00:00:00Z", +}; + +describe("entitlementPayloadSchema legacy starter tier", () => { + it("normalises starter to paid for loopkit so the vendor is Pro", () => { + const parsed = entitlementPayloadSchema.parse({ + ...base, + kit: "loopkit", + tier: "starter", + }); + expect(parsed.tier).toBe("paid"); + expect(isPaidEntitlement(parsed)).toBe(true); + }); + + it("normalises starter to qkit for the qkit kit", () => { + const parsed = entitlementPayloadSchema.parse({ + ...base, + kit: "qkit", + tier: "starter", + }); + expect(parsed.tier).toBe("qkit"); + }); + + it("still accepts free and rejects the qkit tier for loopkit", () => { + expect( + entitlementPayloadSchema.parse({ ...base, kit: "loopkit", tier: "free" }) + .tier, + ).toBe("free"); + expect( + entitlementPayloadSchema.safeParse({ + ...base, + kit: "loopkit", + tier: "qkit", + }).success, + ).toBe(false); + }); + + it("rejects starter for an unknown kit", () => { + expect( + entitlementPayloadSchema.safeParse({ + ...base, + kit: "paykit", + tier: "starter", + }).success, + ).toBe(false); + }); +}); diff --git a/src/lib/merqo-entitlement-contract.ts b/src/lib/merqo-entitlement-contract.ts index 57be3725..485b591d 100644 --- a/src/lib/merqo-entitlement-contract.ts +++ b/src/lib/merqo-entitlement-contract.ts @@ -5,7 +5,13 @@ const isoDate = z.string().datetime({ offset: true }); /** * Wire contract for merqo's entitlement push (POST /api/merqo/entitlement). * Copied verbatim from merqo's `src/lib/entitlements/contract.ts`; keep the - * two in step. + * two in step. The "starter" transform below is the one loopkit-local + * addition to that copy. + * + * "starter" is a retired tier still accepted on the wire so deploy order + * across repos does not matter; it is normalised to the Pro path (the same + * as qkit) before the per-kit check, so it never lands as Free. Any other kit keeps "starter" and fails the + * per-kit check. */ export const entitlementPayloadSchema = z .object({ @@ -18,6 +24,12 @@ export const entitlementPayloadSchema = z valid_until: isoDate.nullable(), issued_at: isoDate, }) + .transform((p) => { + if (p.tier !== "starter") return p; + if (p.kit === "loopkit") return { ...p, tier: "paid" as const }; + if (p.kit === "qkit") return { ...p, tier: "qkit" as const }; + return p; + }) .refine( (p) => p.kit === "qkit" diff --git a/supabase/migrations/0073_default_program_name.sql b/supabase/migrations/0073_default_program_name.sql new file mode 100644 index 00000000..dac78aca --- /dev/null +++ b/supabase/migrations/0073_default_program_name.sql @@ -0,0 +1,48 @@ +-- 0073: the default program seeded for push-provisioned vendors is renamed +-- from "Starter" to "Stamp card". "Starter" is the retired pricing tier and +-- read as a plan name on the vendor's dashboard. Only the inserted name +-- changes; signature, security definer, search_path, advisory lock, +-- idempotency and grants are identical to 0032. Existing programs keep +-- their names. +create or replace function loopkit.provision_default_program(p_vendor_id uuid) +returns uuid +language plpgsql security definer set search_path = '' as $$ +declare v_id uuid; +begin + -- Transaction-scoped advisory lock keyed on the vendor id: closes a TOCTOU + -- race where two concurrent calls for the same vendor (e.g. two browser + -- tabs double-clicking "Activate") both pass the `where not exists` check + -- below under READ COMMITTED and both insert, creating two active default + -- programs. Released automatically at transaction end (pg_advisory_xact_lock); + -- does not change this function's signature or return behavior. + perform pg_advisory_xact_lock(hashtextextended(p_vendor_id::text, 0)); + + -- config must duplicate stamps_required/reward_text (matching what + -- buildProgramFields in src/lib/program.ts produces for a stamp card): + -- resolveStampConfig (src/lib/engine/index.ts) reads programs.config as-is + -- whenever it has any keys at all, with no fallback to the table columns — + -- a config that sets only points_per_visit/variant would leave + -- stamps_required/reward_text undefined for every engine computation. + -- + -- Idempotent keyed on loopkit.programs, NOT on loopkit.vendors: the route + -- caller's own vendors-row insert can no-op (23505) for reasons unrelated + -- to program state (e.g. a vendor who signed up email/password-first, or + -- who already has a real, customized program from /setup's create_program + -- path) — a vendors-row conflict must never imply "already provisioned". + -- `where not exists` makes this call safe to run unconditionally on every + -- provision attempt; a null return means the vendor already had a program + -- and nothing was created, not an error. + insert into loopkit.programs + (vendor_id, type, name, stamps_required, reward_text, config, active) + select p_vendor_id, 'stamp', 'Stamp card', 10, '1 free item', + '{"stamps_required": 10, "reward_text": "1 free item", "points_per_visit": 1, "variant": "dots"}'::jsonb, + true + where not exists (select 1 from loopkit.programs where vendor_id = p_vendor_id) + returning id into v_id; + return v_id; +end; +$$; + +revoke all on function loopkit.provision_default_program(uuid) from public; +grant execute on function loopkit.provision_default_program(uuid) to service_role; +-- deliberately NOT granted to authenticated diff --git a/supabase/migrations/0074_qkit_reward_code.sql b/supabase/migrations/0074_qkit_reward_code.sql new file mode 100644 index 00000000..ab377d7e --- /dev/null +++ b/supabase/migrations/0074_qkit_reward_code.sql @@ -0,0 +1,120 @@ +-- A customer can spend an earned reward at qkit checkout: the voucher is +-- marked redeemed and a single-use LK- code is minted by qkit in one +-- transaction. The vendor sets what the code is worth. + +alter table loopkit.vendor_notify_settings + add column qkit_code_kind text check (qkit_code_kind in ('percent', 'fixed')), + add column qkit_code_value numeric(10, 2), + add constraint vendor_notify_settings_qkit_code_check check ( + (qkit_code_kind is null and qkit_code_value is null) + or (qkit_code_kind = 'percent' and qkit_code_value is not null and qkit_code_value between 1 and 100) + or (qkit_code_kind = 'fixed' and qkit_code_value is not null and qkit_code_value > 0) + ); + +-- Set once a code exists for the voucher so a retry can tell its own earlier +-- spend from a counter redemption by the vendor. +alter table loopkit.reward_vouchers add column qkit_code_issued_at timestamptz; + +create or replace function loopkit.customer_use_voucher_at_qkit( + p_vendor uuid, p_phone text, p_token text, p_voucher uuid +) +returns text +language plpgsql security definer set search_path = '' as $$ +declare + v_voucher loopkit.reward_vouchers; + v_kind text; + v_value numeric; +begin + perform loopkit._require_customer_capability(p_vendor, p_phone, p_token); + + select rv.* into v_voucher + from loopkit.reward_vouchers rv + join loopkit.cards c on c.id = rv.card_id + join loopkit.programs p on p.id = rv.program_id + where rv.id = p_voucher and c.phone = p_phone and p.vendor_id = p_vendor + for update of rv; + if v_voucher.id is null then + raise exception 'not authorized'; + end if; + + select s.qkit_code_kind, s.qkit_code_value into v_kind, v_value + from loopkit.vendor_notify_settings s where s.vendor_id = p_vendor; + if v_voucher.status = 'active' and (v_kind is null or v_value is null) then + raise exception 'qkit_code_not_configured'; + end if; + + if v_voucher.status = 'redeemed' and v_voucher.qkit_code_issued_at is null then + raise exception 'already_redeemed'; + end if; + if v_voucher.status = 'expired' + or (v_voucher.status = 'active' and v_voucher.expires_at is not null + and v_voucher.expires_at < now()) then + raise exception 'expired'; + end if; + + if v_voucher.status = 'active' then + update loopkit.reward_vouchers + set status = 'redeemed', redeemed_at = now(), + qkit_code_issued_at = now(), updated_at = now() + where id = v_voucher.id; + end if; + + -- On a repeat call the vendor setting may be cleared, so the coalesce placeholders only pass qkit's + -- argument checks; they are safe because qkit looks up source_ref before inserting and ignores them. + return qkit.issue_reward_code( + p_vendor, coalesce(v_kind, 'fixed'), coalesce(v_value, 1), v_voucher.expires_at, 'loopkit:' || v_voucher.id::text + ); +end; +$$; +revoke all on function loopkit.customer_use_voucher_at_qkit(uuid, text, text, uuid) + from public, anon, authenticated, service_role; +grant execute on function loopkit.customer_use_voucher_at_qkit(uuid, text, text, uuid) + to service_role; + +-- The customer card list never carried vouchers (vendor_join_cards has no +-- active_vouchers column), so no reward showed for any program type. Same body +-- as 0055 plus active_vouchers: active vouchers and ones already spent for a +-- qkit code, which stay listed so the customer can show the code again. +create or replace function loopkit.customer_join(p_vendor uuid,p_phone text,p_token text default null,p_referral_code text default null) +returns jsonb language plpgsql security definer set search_path='' as $$ +declare v_cards jsonb; v_credit jsonb; v_program uuid; v_token text; v_new_tokens text[] := array[]::text[]; v_new boolean := false; +begin + if p_vendor is null or p_phone is null or p_phone !~ '^\+65[3689][0-9]{7}$' then raise exception 'invalid customer'; end if; + perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended('customer-join-vendor:'||p_vendor::text,0)); + perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended('customer:'||p_vendor::text||':'||p_phone,0)); + if exists(select 1 from loopkit.cards c join loopkit.programs p on p.id=c.program_id where p.vendor_id=p_vendor and c.phone=p_phone) then + perform loopkit._require_customer_capability(p_vendor,p_phone,p_token); + elsif p_token is not null then + raise exception 'customer proof required'; + else + v_new := true; + for v_program in select id from loopkit.programs where vendor_id=p_vendor and active order by id for share loop + v_token := loopkit.enroll_card(v_program,p_phone); + if v_token is null then raise exception 'customer proof required'; end if; + v_new_tokens := array_append(v_new_tokens,v_token); + end loop; + end if; + if p_referral_code is not null then + if length(p_referral_code)>100 then raise exception 'invalid referral'; end if; + select r.referral_credit into v_credit from loopkit.vendor_join_referred(p_vendor,p_phone,p_referral_code) r limit 1; + end if; + if not v_new then perform loopkit.vendor_join_enroll(p_vendor,p_phone); end if; + if v_new and exists(select 1 from loopkit.cards c join loopkit.programs p on p.id=c.program_id + where p.vendor_id=p_vendor and c.phone=p_phone and not(c.card_token=any(v_new_tokens))) + then raise exception 'customer proof required'; end if; + select coalesce(jsonb_agg(to_jsonb(r) || jsonb_build_object('active_vouchers', ( + select coalesce(jsonb_agg(jsonb_build_object( + 'id', rv.id, 'voucher_token', rv.voucher_token, 'reward_text', rv.reward_text, + 'expires_at', rv.expires_at, 'qkit_code_issued', rv.status = 'redeemed' + ) order by rv.earned_at), '[]'::jsonb) + from loopkit.reward_vouchers rv join loopkit.cards c on c.id = rv.card_id + where c.program_id = r.program_id and c.phone = p_phone + and ((rv.status = 'active' and (rv.expires_at is null or rv.expires_at >= now())) + or (rv.status = 'redeemed' and rv.qkit_code_issued_at is not null)) + ))), '[]'::jsonb) into v_cards + from loopkit.vendor_join_cards(p_vendor,p_phone) r; + return jsonb_build_object('cards',v_cards,'referral_credit',v_credit); +end; +$$; +revoke all on function loopkit.customer_join(uuid,text,text,text) from public,anon,authenticated,service_role; +grant execute on function loopkit.customer_join(uuid,text,text,text) to service_role; diff --git a/supabase/migrations/README.md b/supabase/migrations/README.md index a73409c7..ad1676b3 100644 --- a/supabase/migrations/README.md +++ b/supabase/migrations/README.md @@ -83,5 +83,8 @@ exception. - `0070_drop_upgrade_requests.sql`: drops `loopkit.upgrade_requests`; the upgrade inbox is gone. - `0071_qkit_earn_default_stamp.sql`: `loopkit.qkit_earn_resolve_program(uuid)` picks the program a qkit order stamps: the `qkit_earn_config` program while enabled, active and a stamp program, or with no row, the vendor's oldest active stamp program. `qkit_earn_offer`, `qkit_earn_lookup` and `qkit_earn_commit` use it, so the stamp shows on every qkit order by default and `enabled = false` still turns it off. The offer adds `reward_label`, `stamps_goal` and `stamps_per_order` (always 1) and returns only `{enabled: false}` for vendors with no stamp program. - `0072_qkit_earn_free.sql`: qkit-order stamps are Free. `qkit_earn_resolve_program` drops the `loopkit.is_pro` check from 0071, so a vendor with no `qkit_earn_config` row defaults to its oldest active stamp program on any plan. +- `0073_default_program_name.sql`: `provision_default_program` now names the seeded program "Stamp card" instead of "Starter" (retired tier name); existing programs are not renamed. Prepared audit migrations require database validation and rollout review before deployment. + +- `0074_qkit_reward_code.sql`: adds `qkit_code_kind`/`qkit_code_value` to `vendor_notify_settings` (what a reward code is worth, free for every vendor) and `reward_vouchers.qkit_code_issued_at`. `loopkit.customer_use_voucher_at_qkit(vendor, phone, token, voucher)` (service role only, card-token proof) marks the voucher redeemed and calls `qkit.issue_reward_code` with `loopkit:` in one transaction; a retry (even after the vendor clears the setting) returns the same code. Also redefines `customer_join` so each card carries `active_vouchers` (active ones plus those spent for a qkit code, flagged `qkit_code_issued`). The code expires with the voucher. Deploy order: qkit `0129_discount_codes` (`qkit.issue_reward_code`) must be applied first; it already is on prod and staging. Raises `qkit_code_not_configured` until the vendor sets kind and value. diff --git a/supabase/tests/README.md b/supabase/tests/README.md index 64f951aa..0684d756 100644 --- a/supabase/tests/README.md +++ b/supabase/tests/README.md @@ -13,6 +13,7 @@ fixtures have not yet been executed in this checkout. provisioning, birthday bonuses, manual adjustments, legal-cache isolation and storage limits. Owner-level legacy reward fixtures do not prove anonymous authorization of the current customer endpoints. +- `qkit-reward-code.test.sql` covers `customer_use_voucher_at_qkit` (stubs `qkit.issue_reward_code`): happy path, idempotent retry, wrong customer or vendor, missing vendor config, anon denied. - `customer-capability.test.sql` and `earn-customer-capability.test.sql` exercise customer and earn proofs; `retired-rpc-permissions.test.sql` checks retired RPC grants. @@ -39,3 +40,5 @@ RLS or concurrent transaction behavior. Report database execution separately. ## Parent [supabase](../README.md) + +`rls.test.sql` asserts the provisioned default program is named "Stamp card". diff --git a/supabase/tests/qkit-reward-code.test.sql b/supabase/tests/qkit-reward-code.test.sql new file mode 100644 index 00000000..67fe34a7 --- /dev/null +++ b/supabase/tests/qkit-reward-code.test.sql @@ -0,0 +1,92 @@ +begin; +select no_plan(); + +-- CI has no qkit schema; stand in for qkit 0129's idempotent function only when the real one is absent. +create schema if not exists qkit; +create table if not exists qkit.test_codes (source_ref text primary key, code text not null, kind text, value numeric, expires_at timestamptz); +do $stub$ +begin + if to_regprocedure('qkit.issue_reward_code(uuid,text,numeric,timestamptz,text)') is null then + create function qkit.issue_reward_code( + p_vendor uuid, p_kind text, p_value numeric, p_expires_at timestamptz default null, p_source_ref text default null + ) returns text language plpgsql as $f$ + declare v_code text; + begin + select code into v_code from qkit.test_codes where source_ref = p_source_ref; + if v_code is not null then return v_code; end if; + if p_kind not in ('percent', 'fixed') then raise exception 'invalid kind'; end if; + if p_kind = 'percent' and (p_value < 1 or p_value > 100) then raise exception 'invalid percent'; end if; + if p_kind = 'fixed' and p_value <= 0 then raise exception 'invalid value'; end if; + v_code := 'LK-' || upper(substr(md5(random()::text), 1, 8)); + insert into qkit.test_codes values (p_source_ref, v_code, p_kind, p_value, p_expires_at); + return v_code; + end; + $f$; + end if; +end +$stub$; + +select ok(not has_function_privilege('anon','loopkit.customer_use_voucher_at_qkit(uuid,text,text,uuid)','execute'),'anon cannot spend a voucher at qkit'); +select ok(not has_function_privilege('authenticated','loopkit.customer_use_voucher_at_qkit(uuid,text,text,uuid)','execute'),'a vendor session cannot spend a voucher at qkit'); +select ok(has_function_privilege('service_role','loopkit.customer_use_voucher_at_qkit(uuid,text,text,uuid)','execute'),'the service proxy can spend a voucher at qkit'); + +insert into auth.users(id,instance_id,aud,role,email) values +('00720000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000000','authenticated','authenticated','qkit-code-a@test.local'), +('00720000-0000-0000-0000-000000000002','00000000-0000-0000-0000-000000000000','authenticated','authenticated','qkit-code-b@test.local'); +insert into loopkit.programs(id,vendor_id,type,name,stamps_required,reward_text,config,active) values +('00720000-0000-0000-0000-000000000010','00720000-0000-0000-0000-000000000001','stamp','Code A',10,'Coffee','{}',true), +('00720000-0000-0000-0000-000000000020','00720000-0000-0000-0000-000000000002','stamp','Code B',10,'Coffee','{}',true); +insert into loopkit.cards(id,program_id,phone,stamp_count,card_token) values +('00720000-0000-0000-0000-000000000011','00720000-0000-0000-0000-000000000010','+6591110072',0,repeat('a',32)), +('00720000-0000-0000-0000-000000000012','00720000-0000-0000-0000-000000000010','+6592220072',0,repeat('b',32)), +('00720000-0000-0000-0000-000000000021','00720000-0000-0000-0000-000000000020','+6591110072',0,repeat('c',32)); +insert into loopkit.reward_vouchers(id,card_id,program_id,reward_text) values +('00720000-0000-0000-0000-000000000101','00720000-0000-0000-0000-000000000011','00720000-0000-0000-0000-000000000010','Coffee'), +('00720000-0000-0000-0000-000000000102','00720000-0000-0000-0000-000000000011','00720000-0000-0000-0000-000000000010','Coffee'), +('00720000-0000-0000-0000-000000000103','00720000-0000-0000-0000-000000000011','00720000-0000-0000-0000-000000000010','Coffee'); + +set local role service_role; +select throws_ok($$select loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32),'00720000-0000-0000-0000-000000000101')$$,'P0001','qkit_code_not_configured','missing vendor config fails cleanly'); +reset role; +select is((select status from loopkit.reward_vouchers where id='00720000-0000-0000-0000-000000000101'),'active','a failed attempt leaves the voucher active'); + +insert into loopkit.vendor_notify_settings(vendor_id,qkit_code_kind,qkit_code_value) values +('00720000-0000-0000-0000-000000000001','percent',15); +select throws_ok($$insert into loopkit.vendor_notify_settings(vendor_id,qkit_code_kind,qkit_code_value) values ('00720000-0000-0000-0000-000000000002','percent',150)$$,'23514',null,'percent over 100 is rejected'); +select throws_ok($$insert into loopkit.vendor_notify_settings(vendor_id,qkit_code_kind) values ('00720000-0000-0000-0000-000000000002','fixed')$$,'23514',null,'a kind without a value is rejected'); + +update loopkit.reward_vouchers set expires_at='2099-01-01 00:00:00+00' where id='00720000-0000-0000-0000-000000000101'; +set local role service_role; +select throws_ok($$select loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('b',32),'00720000-0000-0000-0000-000000000101')$$,'P0001','customer proof required','wrong card token is denied'); +select throws_ok($$select loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6592220072',repeat('b',32),'00720000-0000-0000-0000-000000000101')$$,'P0001','not authorized','another customer cannot spend this voucher'); +select throws_ok($$select loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000002','+6591110072',repeat('c',32),'00720000-0000-0000-0000-000000000101')$$,'P0001','not authorized','another vendor cannot spend this voucher'); + +select set_config('test.code1',loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32),'00720000-0000-0000-0000-000000000101'),true); +select matches(current_setting('test.code1'),'^LK-[A-Z0-9]{8}$','happy path returns an LK- code'); +select is(loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32),'00720000-0000-0000-0000-000000000101'),current_setting('test.code1'),'retry returns the same code'); +select is( + (select (v->>'qkit_code_issued')::boolean from jsonb_array_elements(loopkit.customer_join('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32))->'cards') c, jsonb_array_elements(c->'active_vouchers') v where c->>'program_id'='00720000-0000-0000-0000-000000000010' and v->>'id'='00720000-0000-0000-0000-000000000101'), + true,'a spent voucher stays on the card list flagged as issued'); +select is( + (select jsonb_array_length(c->'active_vouchers') from jsonb_array_elements(loopkit.customer_join('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32))->'cards') c where c->>'program_id'='00720000-0000-0000-0000-000000000010'), + 3,'unspent vouchers of any program type are listed too'); +reset role; +update loopkit.vendor_notify_settings set qkit_code_kind=null,qkit_code_value=null where vendor_id='00720000-0000-0000-0000-000000000001'; +set local role service_role; +select is(loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32),'00720000-0000-0000-0000-000000000101'),current_setting('test.code1'),'showing the code again works after the vendor clears the setting'); +reset role; +update loopkit.vendor_notify_settings set qkit_code_kind='percent',qkit_code_value=15 where vendor_id='00720000-0000-0000-0000-000000000001'; +select is((select status from loopkit.reward_vouchers where id='00720000-0000-0000-0000-000000000101'),'redeemed','voucher is redeemed'); +select is((select count(*) from qkit.test_codes where source_ref='loopkit:00720000-0000-0000-0000-000000000101'),1::bigint,'retry did not mint a second code'); +select is((select value from qkit.test_codes where source_ref='loopkit:00720000-0000-0000-0000-000000000101'),15::numeric,'code carries the vendor value'); +select is((select expires_at from qkit.test_codes where source_ref='loopkit:00720000-0000-0000-0000-000000000101'),'2099-01-01 00:00:00+00'::timestamptz,'code expires with the voucher'); + +update loopkit.reward_vouchers set status='redeemed',redeemed_at=now() where id='00720000-0000-0000-0000-000000000102'; +update loopkit.reward_vouchers set expires_at=now()-interval '1 day' where id='00720000-0000-0000-0000-000000000103'; +set local role service_role; +select throws_ok($$select loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32),'00720000-0000-0000-0000-000000000102')$$,'P0001','already_redeemed','a voucher the vendor already redeemed cannot mint a code'); +select throws_ok($$select loopkit.customer_use_voucher_at_qkit('00720000-0000-0000-0000-000000000001','+6591110072',repeat('a',32),'00720000-0000-0000-0000-000000000103')$$,'P0001','expired','an expired voucher cannot mint a code'); +reset role; + +select * from finish(); +rollback; diff --git a/supabase/tests/rls.test.sql b/supabase/tests/rls.test.sql index 1e0ded1f..6e2cbc5f 100644 --- a/supabase/tests/rls.test.sql +++ b/supabase/tests/rls.test.sql @@ -12,7 +12,7 @@ -- Runs in ONE rolled-back transaction with inline fixtures (fixed UUIDs). begin; -select plan(87); +select plan(88); -- ── Fixtures (created under the default/superuser test role → RLS + grants -- are bypassed here, same as inserting via the table owner) ───────────────── @@ -200,7 +200,7 @@ select ok( -- provision_default_program idempotency (migration 0032 fix): keyed on -- loopkit.programs existence, not loopkit.vendors, so a vendor who already -- has ANY program (e.g. from /setup's create_program path, unrelated to --- this RPC) never gets a second "Starter" program silently added. +-- this RPC) never gets a second default program silently added. reset role; set local role service_role; @@ -219,6 +219,11 @@ select is( 1, 'vendor A now has exactly one program'); +select is( + (select name from loopkit.programs where vendor_id = '00000000-0000-0000-0000-00000000000a'), + 'Stamp card', + 'provisioned default program is named Stamp card'); + -- Vendor B: simulate an existing program created directly (NOT via this -- RPC — standing in for /setup's create_program path), then re-provision. insert into loopkit.programs (vendor_id, type, name, stamps_required, reward_text, config, active) @@ -233,7 +238,7 @@ select is( select is( (select count(*)::int from loopkit.programs where vendor_id = '00000000-0000-0000-0000-00000000000b'), 1, - 'vendor B still has exactly one program (no second Starter program added)'); + 'vendor B still has exactly one program (no second default program added)'); -- provision_default_program TOCTOU fix (migration 0032): a transaction-scoped -- advisory lock keyed on p_vendor_id closes the read-then-write race between diff --git a/vitest.config.ts b/vitest.config.ts index a6e9a352..7628da60 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -14,6 +14,10 @@ export default defineConfig({ test: { globals: true, maxWorkers: 2, + // jsdom form tests pass in under a second on a quiet machine but exceed the + // 5s default when the pre-push gate shares a loaded host. + testTimeout: 30000, + hookTimeout: 180000, environment: "node", // @merqo/ui entries import extensionless `next/server`, which Node's ESM // loader rejects; inlining lets Vite resolve it.