+ 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: "",
},
],
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;
+ 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. +
+Your rewards
- {[...card.activeVouchers, ...freshVouchers].map((v) => ( + {[ + ...card.activeVouchers, + ...freshVouchers.map((v) => ({ ...v, codeIssued: false })), + ].map((v) => ({v.rewardText}
-+ Enter this code at qkit checkout. It works once. +
+
+ {code}
+
+
+