Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ All notable changes to loopkit are documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [0.7.1] - 2026-12-02

### Fixed

- New push-provisioned vendors get a default stamp program named "Stamp card" instead of "Starter" (migration 0073), which read as the retired pricing tier. Existing programs keep their names.
- The Plan page links "Merqo account" to the Merqo dashboard, and the legacy "starter" entitlement tier is normalised to Pro instead of being rejected for loopkit.

## [0.7.0] - 2026-12-02

### Changed
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -556,3 +556,5 @@ Vendor-facing plan-limit copy states what the plan includes and never asks the v
Route loading skeletons come from `@merqo/ui` (`ListSkeleton`, `StatTileSkeleton`, `DataTableSkeleton`) under `components/loading-header.tsx`. The counter and setup edit-impact dialogs use the shared `ConfirmDialog`, and the counter empty state uses `EmptyState`. The login and reset-password forms stay local because their zod and React Hook Form validation, wordmark shell and reset-sent notice are not covered by the shared forms. Touch targets on setup chips and overview program links reach 44px on coarse pointers, and visit bars are tappable.

Customer-facing selects and buttons (`birthday-field.tsx`, `check-form.tsx`, dashboard `scan-button.tsx`) use the shared `@merqo/ui` Select and Button primitives with 44px touch targets. `/c` without a shop link shows a next-step message and a link home.

New vendors get a default program named "Stamp card" (migration 0073); the plan page links to the Merqo account and treats the legacy "starter" tier as Pro.
2 changes: 1 addition & 1 deletion docs/DEPLOY.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ Do the steps in order: **A (Supabase) → B (Vercel) → C (attach to merqo)**.
- apply `0032_loopkit_provision_default_program.sql` — adds
`provision_default_program(p_vendor_id)`, a service-role-only SECURITY
DEFINER function (never granted to `authenticated`) that seeds a default
"Starter" stamp program for a push-provisioned vendor, since
"Stamp card" stamp program for a push-provisioned vendor, since
`create_program` is keyed on the calling session's `auth.uid()` and can't
run on a vendor's behalf. Advisory-lock-guarded against a double-provision
race, idempotent on `loopkit.programs`. Backs
Expand Down
2 changes: 2 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ spec/plan development history.
## Parent

[loopkit](../README.md)

Deploy notes refer to the default program new vendors receive as "Stamp card".
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "loopkit",
"version": "0.7.0",
"version": "0.7.1",
"private": true,
"packageManager": "pnpm@11.10.0",
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/merqo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ qkit earn-config, and push-provisions a vendor onto loopkit.
- `vendor-activity/` — `GET` endpoint resolving one vendor's programs,
cards, and stamp/redeem activity by email, for merqo's cross-kit
`/admin/vendors/[email]` detail view.
- `vendor-provision/` — `POST` endpoint that creates a free-tier `vendors` row (and a default "Starter" stamp program) for a vendor id the Merqo hub is one-click-activating on loopkit.
- `vendor-provision/` — `POST` endpoint that creates a free-tier `vendors` row (and a default "Stamp card" stamp program) for a vendor id the Merqo hub is one-click-activating on loopkit.
- `vendor-status/`

## Connectivity
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/merqo/vendor-provision/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Purpose

Push-provisioning endpoint: Merqo hub calls this to activate loopkit for a vendor who hasn't signed up directly, keyed on their existing (shared) `auth.users.id`. Creates the vendor row AND a default "Starter" stamp program (loopkit's own `create_program` RPC can't be used here — see `provision_default_program`'s migration comment) so the vendor is genuinely active immediately, not left without a program.
Push-provisioning endpoint: Merqo hub calls this to activate loopkit for a vendor who hasn't signed up directly, keyed on their existing (shared) `auth.users.id`. Creates the vendor row AND a default "Stamp card" stamp program (loopkit's own `create_program` RPC can't be used here — see `provision_default_program`'s migration comment) so the vendor is genuinely active immediately, not left without a program.

## Contents

Expand Down
2 changes: 2 additions & 0 deletions src/app/dashboard/plan/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ Vendor billing/plan page at `/dashboard/plan`, shows Free vs. Pro feature compar
Each page exports its own `metadata.title`, shown through the root `loopkit | %s` template. UI copy is plain: no emoji, no em dashes, no contractions in errors.

- `page.tsx` renders its title row with `PageHeader`; `loading.tsx` uses `ListSkeleton`.

The "Merqo account" line is a link built from `merqoBaseUrl()`, and the pricing ladder highlights the paid slug.
18 changes: 15 additions & 3 deletions src/app/dashboard/plan/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ import { Badge } from "@merqo/ui/primitives";

// merqo-ui's tierLabel lives in a client-only module and crashes when called
// from a Server Component, so this page keeps its own copy of the labels.
const TIER_LABEL = { free: "Free", starter: "Starter", pro: "Pro" } as const;
const TIER_LABEL = { free: "Free", pro: "Pro" } as const;

// The ladder only accepts "qkit" or "all_access" as a highlight and the
// catalog has no loopkit-only plan; the qkit plan includes full loopkit, so
// a Pro vendor sits on that entry. Loopkit's own wire tier is "paid".
const LADDER_HIGHLIGHT = "qkit";

export const metadata = { title: "Plan" };

Expand Down Expand Up @@ -77,13 +82,20 @@ export default async function PlanPage({
{pro
? "You're on Pro, unlimited loyalty programs are unlocked. "
: "You're on Free, with one active loyalty program. "}
Change plan from your Merqo account.
Change plan from your{" "}
<a
href={`${merqoBaseUrl()}/dashboard`}
className="underline underline-offset-4"
>
Merqo account
</a>
.
</ElevatedCard>

{catalog ? (
<PricingLadder
catalog={catalog}
highlight="qkit"
highlight={LADDER_HIGHLIGHT}
notice="Charging starts 1 January 2027."
showEventPass={false}
/>
Expand Down
5 changes: 2 additions & 3 deletions src/app/dashboard/plan/plan-page.dom.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,8 @@ describe("PlanPage", () => {
expect(card).toHaveTextContent("qkit");
expect(card).not.toHaveTextContent("All-Access");
expect(screen.queryByText(/event pass/i)).not.toBeInTheDocument();
expect(
screen.getByText(/change plan from your merqo account/i),
).toBeInTheDocument();
const link = screen.getByRole("link", { name: /merqo account/i });
expect(link).toHaveAttribute("href", expect.stringMatching(/\/dashboard$/));
});

it("sends the kit bearer to the plan catalog when the secret is set", async () => {
Expand Down
2 changes: 2 additions & 0 deletions src/lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,5 @@ card updates are not a transactional snapshot across separate HTTP reads.
`merqo-vendor-activity.ts`'s `computeVendorActivity(isPro, { programs, cards, events }, nowMs)` and `program-config.ts`'s `buildChanceConfig(variant, segments, { pityCeiling, rewardText, scratchCoverStyle })` take grouped arguments. Colour values for the mechanic art live in `tokens/`.

Empty activity cells use "-" and errors spell out "could not".

`merqo-entitlement-contract.ts` normalises the legacy "starter" tier to paid (loopkit) or qkit so such a vendor is never treated as Free.
57 changes: 57 additions & 0 deletions src/lib/merqo-entitlement-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { entitlementPayloadSchema } from "./merqo-entitlement-contract";
import { isPaidEntitlement } from "./entitlement-cache";

const base = {
email: "v@example.com",
founder: false,
stats_window: "90d",
event_pass: null,
valid_until: null,
issued_at: "2026-12-01T00:00:00Z",
};

describe("entitlementPayloadSchema legacy starter tier", () => {
it("normalises starter to paid for loopkit so the vendor is Pro", () => {
const parsed = entitlementPayloadSchema.parse({
...base,
kit: "loopkit",
tier: "starter",
});
expect(parsed.tier).toBe("paid");
expect(isPaidEntitlement(parsed)).toBe(true);
});

it("normalises starter to qkit for the qkit kit", () => {
const parsed = entitlementPayloadSchema.parse({
...base,
kit: "qkit",
tier: "starter",
});
expect(parsed.tier).toBe("qkit");
});

it("still accepts free and rejects the qkit tier for loopkit", () => {
expect(
entitlementPayloadSchema.parse({ ...base, kit: "loopkit", tier: "free" })
.tier,
).toBe("free");
expect(
entitlementPayloadSchema.safeParse({
...base,
kit: "loopkit",
tier: "qkit",
}).success,
).toBe(false);
});

it("rejects starter for an unknown kit", () => {
expect(
entitlementPayloadSchema.safeParse({
...base,
kit: "paykit",
tier: "starter",
}).success,
).toBe(false);
});
});
14 changes: 13 additions & 1 deletion src/lib/merqo-entitlement-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ const isoDate = z.string().datetime({ offset: true });
/**
* Wire contract for merqo's entitlement push (POST /api/merqo/entitlement).
* Copied verbatim from merqo's `src/lib/entitlements/contract.ts`; keep the
* two in step.
* two in step. The "starter" transform below is the one loopkit-local
* addition to that copy.
*
* "starter" is a retired tier still accepted on the wire so deploy order
* across repos does not matter; it is normalised to the Pro path (the same
* as qkit) before the per-kit check, so it never lands as Free. Any other kit keeps "starter" and fails the
* per-kit check.
*/
export const entitlementPayloadSchema = z
.object({
Expand All @@ -18,6 +24,12 @@ export const entitlementPayloadSchema = z
valid_until: isoDate.nullable(),
issued_at: isoDate,
})
.transform((p) => {
if (p.tier !== "starter") return p;
if (p.kit === "loopkit") return { ...p, tier: "paid" as const };
if (p.kit === "qkit") return { ...p, tier: "qkit" as const };
return p;
})
.refine(
(p) =>
p.kit === "qkit"
Expand Down
48 changes: 48 additions & 0 deletions supabase/migrations/0073_default_program_name.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
-- 0073: the default program seeded for push-provisioned vendors is renamed
-- from "Starter" to "Stamp card". "Starter" is the retired pricing tier and
-- read as a plan name on the vendor's dashboard. Only the inserted name
-- changes; signature, security definer, search_path, advisory lock,
-- idempotency and grants are identical to 0032. Existing programs keep
-- their names.
create or replace function loopkit.provision_default_program(p_vendor_id uuid)
returns uuid
language plpgsql security definer set search_path = '' as $$
declare v_id uuid;
begin
-- Transaction-scoped advisory lock keyed on the vendor id: closes a TOCTOU
-- race where two concurrent calls for the same vendor (e.g. two browser
-- tabs double-clicking "Activate") both pass the `where not exists` check
-- below under READ COMMITTED and both insert, creating two active default
-- programs. Released automatically at transaction end (pg_advisory_xact_lock);
-- does not change this function's signature or return behavior.
perform pg_advisory_xact_lock(hashtextextended(p_vendor_id::text, 0));

-- config must duplicate stamps_required/reward_text (matching what
-- buildProgramFields in src/lib/program.ts produces for a stamp card):
-- resolveStampConfig (src/lib/engine/index.ts) reads programs.config as-is
-- whenever it has any keys at all, with no fallback to the table columns —
-- a config that sets only points_per_visit/variant would leave
-- stamps_required/reward_text undefined for every engine computation.
--
-- Idempotent keyed on loopkit.programs, NOT on loopkit.vendors: the route
-- caller's own vendors-row insert can no-op (23505) for reasons unrelated
-- to program state (e.g. a vendor who signed up email/password-first, or
-- who already has a real, customized program from /setup's create_program
-- path) — a vendors-row conflict must never imply "already provisioned".
-- `where not exists` makes this call safe to run unconditionally on every
-- provision attempt; a null return means the vendor already had a program
-- and nothing was created, not an error.
insert into loopkit.programs
(vendor_id, type, name, stamps_required, reward_text, config, active)
select p_vendor_id, 'stamp', 'Stamp card', 10, '1 free item',
'{"stamps_required": 10, "reward_text": "1 free item", "points_per_visit": 1, "variant": "dots"}'::jsonb,
true
where not exists (select 1 from loopkit.programs where vendor_id = p_vendor_id)
returning id into v_id;
return v_id;
end;
$$;

revoke all on function loopkit.provision_default_program(uuid) from public;
grant execute on function loopkit.provision_default_program(uuid) to service_role;
-- deliberately NOT granted to authenticated
1 change: 1 addition & 0 deletions supabase/migrations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,6 @@ exception.
- `0070_drop_upgrade_requests.sql`: drops `loopkit.upgrade_requests`; the upgrade inbox is gone.
- `0071_qkit_earn_default_stamp.sql`: `loopkit.qkit_earn_resolve_program(uuid)` picks the program a qkit order stamps: the `qkit_earn_config` program while enabled, active and a stamp program, or with no row, the vendor's oldest active stamp program. `qkit_earn_offer`, `qkit_earn_lookup` and `qkit_earn_commit` use it, so the stamp shows on every qkit order by default and `enabled = false` still turns it off. The offer adds `reward_label`, `stamps_goal` and `stamps_per_order` (always 1) and returns only `{enabled: false}` for vendors with no stamp program.
- `0072_qkit_earn_free.sql`: qkit-order stamps are Free. `qkit_earn_resolve_program` drops the `loopkit.is_pro` check from 0071, so a vendor with no `qkit_earn_config` row defaults to its oldest active stamp program on any plan.
- `0073_default_program_name.sql`: `provision_default_program` now names the seeded program "Stamp card" instead of "Starter" (retired tier name); existing programs are not renamed.

Prepared audit migrations require database validation and rollout review before deployment.
2 changes: 2 additions & 0 deletions supabase/tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,5 @@ RLS or concurrent transaction behavior. Report database execution separately.
## Parent

[supabase](../README.md)

`rls.test.sql` asserts the provisioned default program is named "Stamp card".
11 changes: 8 additions & 3 deletions supabase/tests/rls.test.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
-- Runs in ONE rolled-back transaction with inline fixtures (fixed UUIDs).

begin;
select plan(87);
select plan(88);

-- ── Fixtures (created under the default/superuser test role → RLS + grants
-- are bypassed here, same as inserting via the table owner) ─────────────────
Expand Down Expand Up @@ -200,7 +200,7 @@ select ok(
-- provision_default_program idempotency (migration 0032 fix): keyed on
-- loopkit.programs existence, not loopkit.vendors, so a vendor who already
-- has ANY program (e.g. from /setup's create_program path, unrelated to
-- this RPC) never gets a second "Starter" program silently added.
-- this RPC) never gets a second default program silently added.
reset role;
set local role service_role;

Expand All @@ -219,6 +219,11 @@ select is(
1,
'vendor A now has exactly one program');

select is(
(select name from loopkit.programs where vendor_id = '00000000-0000-0000-0000-00000000000a'),
'Stamp card',
'provisioned default program is named Stamp card');

-- Vendor B: simulate an existing program created directly (NOT via this
-- RPC — standing in for /setup's create_program path), then re-provision.
insert into loopkit.programs (vendor_id, type, name, stamps_required, reward_text, config, active)
Expand All @@ -233,7 +238,7 @@ select is(
select is(
(select count(*)::int from loopkit.programs where vendor_id = '00000000-0000-0000-0000-00000000000b'),
1,
'vendor B still has exactly one program (no second Starter program added)');
'vendor B still has exactly one program (no second default program added)');

-- provision_default_program TOCTOU fix (migration 0032): a transaction-scoped
-- advisory lock keyed on p_vendor_id closes the read-then-write race between
Expand Down
4 changes: 4 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export default defineConfig({
test: {
globals: true,
maxWorkers: 2,
// jsdom form tests pass in under a second on a quiet machine but exceed the
// 5s default when the pre-push gate shares a loaded host.
testTimeout: 30000,
hookTimeout: 180000,
environment: "node",
// @merqo/ui entries import extensionless `next/server`, which Node's ESM
// loader rejects; inlining lets Vite resolve it.
Expand Down
Loading