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/CHANGELOG.md b/CHANGELOG.md index a873839c..ceabc525 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ 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.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 diff --git a/README.md b/README.md index d932d271..1bec32c1 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. diff --git a/package.json b/package.json index 2e34e6b8..c1a7fbf2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loopkit", - "version": "0.7.1", + "version": "0.8.0", "private": true, "packageManager": "pnpm@11.10.0", "engines": { 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/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/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/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 c93606aa..ad1676b3 100644 --- a/supabase/migrations/README.md +++ b/supabase/migrations/README.md @@ -86,3 +86,5 @@ exception. - `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 72cb35e7..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. 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;