From 6692dec9a24de902cf7f022481e428f095b2ee8d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 12:51:49 +0000 Subject: [PATCH 1/6] Harden resetDemoTenant to only ever target sandbox-slug companies demo_mode_enabled was ambiguously used both for purpose-built sandbox tenants (safe to fully wipe) and for seedDemoAction's additive opt-in on a real customer's own company. resetDemoTenant() did a full destructive wipe with no check against that ambiguity. Add SANDBOX_DEMO_SLUGS/isSandboxDemoCompany as the only valid resolution path for a destructive reset, verified both in the reset route and inside resetDemoTenant itself, and parameterize the seed script so a second sandbox tenant can be provisioned without technician auth identity collisions. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MR2GnZw5BX1L6QgTabt5JF --- scripts/seed-demo-tenant.mjs | 59 ++++++++++++++++++++-------- src/app/api/demo/reset/route.ts | 9 ++++- src/lib/__tests__/demo.test.ts | 39 +++++++++++++++++++ src/lib/demo.ts | 20 ++++++++++ src/lib/resetDemoTenant.ts | 68 +++++++++++++++++++++------------ 5 files changed, 152 insertions(+), 43 deletions(-) create mode 100644 src/lib/__tests__/demo.test.ts diff --git a/scripts/seed-demo-tenant.mjs b/scripts/seed-demo-tenant.mjs index d860834..d5f5bae 100644 --- a/scripts/seed-demo-tenant.mjs +++ b/scripts/seed-demo-tenant.mjs @@ -1,13 +1,33 @@ /** - * One-time setup for the public demo tenant. + * One-time setup for a sandbox demo tenant. * - * Creates the demo company, public login user (demo / demo), technicians, - * and quote template — then seeds the initial job set. + * Creates the demo company, login user, technicians, and quote template — + * then seeds the initial job set. * * Safe to re-run: all operations are idempotent. * * After initial setup, daily resets are handled automatically by the - * Vercel cron job calling POST /api/internal/reset-demo (05:00 UTC = 00:00 EST). + * Vercel cron job calling POST /api/internal/reset-demo (05:00 UTC = 00:00 EST) + * for every company whose slug is on SANDBOX_DEMO_SLUGS (src/lib/demo.ts) -- + * add the new slug there too, or the nightly reset will silently skip it. + * + * Defaults to the public demo tenant (swiftdispatch-demo, demo@swiftdispatch.app + * / demo) for back-compat with existing usage. Override via env vars to + * provision a second, separately-credentialed sandbox tenant -- e.g. a + * private one shared directly with trusted prospects rather than linked from + * the public site: + * + * DEMO_SLUG=swiftdispatch-preview \ + * DEMO_COMPANY_NAME="SwiftDispatch Preview" \ + * DEMO_USER_EMAIL=preview@swiftdispatch.app \ + * DEMO_USER_PASSWORD= \ + * DEMO_HANDLE_SUFFIX=preview \ + * node scripts/seed-demo-tenant.mjs + * + * DEMO_HANDLE_SUFFIX must be unique per tenant -- technician logins are + * shared Supabase Auth users keyed by handle@internal.swiftdispatch.app, so + * reusing a handle across tenants reassigns that technician's login to + * whichever company was seeded last instead of creating a separate one. * * Usage: * node scripts/seed-demo-tenant.mjs @@ -46,30 +66,34 @@ if (!supabaseUrl || !serviceRoleKey) { const supabase = createClient(supabaseUrl, serviceRoleKey); -const DEMO_COMPANY_SLUG = "swiftdispatch-demo"; +const DEMO_COMPANY_SLUG = process.env.DEMO_SLUG ?? "swiftdispatch-demo"; +const HANDLE_SUFFIX = process.env.DEMO_HANDLE_SUFFIX ?? ""; const COMPANY = { - name: "SwiftDispatch Demo", + name: process.env.DEMO_COMPANY_NAME ?? "SwiftDispatch Demo", slug: DEMO_COMPANY_SLUG, - email: "demo@swiftdispatch.app", + email: process.env.DEMO_COMPANY_EMAIL ?? "demo@swiftdispatch.app", phone: "555-0100", timezone: "America/New_York", - sms_sender_name: "SwiftDispatch", + sms_sender_name: process.env.DEMO_SMS_SENDER_NAME ?? "SwiftDispatch", payment_provider: "manual", demo_mode_enabled: true, }; -// Public demo credentials — safe to display on marketing pages +// Public demo credentials (defaults) — safe to display on marketing pages. +// A tenant seeded with DEMO_USER_EMAIL/DEMO_USER_PASSWORD overrides should +// NOT reuse a memorable password like "demo" -- these are meant to be +// shared privately with named people, not published. const DEMO_USER = { - email: "demo@swiftdispatch.app", - password: "demo", + email: process.env.DEMO_USER_EMAIL ?? "demo@swiftdispatch.app", + password: process.env.DEMO_USER_PASSWORD ?? "demo", role: "dispatcher", }; const TECHNICIANS = [ - { name: "Mia Torres", phone: "+15551234567", handle: "miatorres", pin: "1234", authPassword: "123456" }, - { name: "Leo Grant", phone: "+15557654321", handle: "leogrant", pin: "5678", authPassword: "567890" }, - { name: "Avery Brooks", phone: "+15553459876", handle: "averybrooks", pin: "9012", authPassword: "901234" }, + { name: "Mia Torres", phone: "+15551234567", handle: `miatorres${HANDLE_SUFFIX}`, pin: "1234", authPassword: "123456" }, + { name: "Leo Grant", phone: "+15557654321", handle: `leogrant${HANDLE_SUFFIX}`, pin: "5678", authPassword: "567890" }, + { name: "Avery Brooks", phone: "+15553459876", handle: `averybrooks${HANDLE_SUFFIX}`, pin: "9012", authPassword: "901234" }, ]; const TEMPLATE = { @@ -259,9 +283,9 @@ async function seedJobs(companyId, techIds) { // ─── Main ───────────────────────────────────────────────────────────────────── async function main() { - console.log("Setting up demo tenant…"); + console.log(`Setting up demo tenant (slug: ${DEMO_COMPANY_SLUG})…`); const companyId = await ensureCompany(); - console.log(` Company: ${companyId}`); + console.log(` Company: ${COMPANY.name} (${companyId})`); const demoAuthUser = await ensureAuthUser(DEMO_USER.email, DEMO_USER.password); await ensureUserProfile(demoAuthUser, companyId, DEMO_USER.role); @@ -280,9 +304,12 @@ async function main() { console.log(` Jobs seeded: ${seeded}`); console.log("\nDemo tenant ready."); + console.log(` Slug: ${DEMO_COMPANY_SLUG}`); console.log(` Login: ${DEMO_USER.email} / ${DEMO_USER.password}`); console.log(` Daily reset: POST /api/internal/reset-demo (05:00 UTC = 00:00 EST)`); console.log(` Vercel cron: set CRON_SECRET env var — already configured in vercel.json`); + console.log(` Make sure "${DEMO_COMPANY_SLUG}" is listed in SANDBOX_DEMO_SLUGS (src/lib/demo.ts),`); + console.log(` or the nightly reset will silently skip this tenant.`); } main().catch((err) => { console.error(err); process.exit(1); }); diff --git a/src/app/api/demo/reset/route.ts b/src/app/api/demo/reset/route.ts index 91f9aa4..d357cfe 100644 --- a/src/app/api/demo/reset/route.ts +++ b/src/app/api/demo/reset/route.ts @@ -2,7 +2,7 @@ import { NextResponse } from "next/server"; import { requireApiProfile } from "@/lib/auth"; import { resetDemoTenant } from "@/lib/resetDemoTenant"; import { createSupabaseServerClient } from "@/lib/supabase/server"; -import { isDemoCompany } from "@/lib/demo"; +import { isSandboxDemoCompany } from "@/lib/demo"; export async function POST() { const { profile, response } = await requireApiProfile(); @@ -18,7 +18,12 @@ export async function POST() { .eq("id", profile.company_id) .single(); - if (!isDemoCompany(company)) { + // resetDemoTenant() does a full destructive wipe (every job/quote/ + // status_event, not just is_demo=true rows) -- isSandboxDemoCompany() + // (purpose-built sandbox slugs only) is required here, not the looser + // isDemoCompany() flag check, since a real customer can also have + // demo_mode_enabled=true via the additive, non-destructive seedDemoAction. + if (!isSandboxDemoCompany(company)) { return NextResponse.json({ error: "Not a demo account" }, { status: 403 }); } diff --git a/src/lib/__tests__/demo.test.ts b/src/lib/__tests__/demo.test.ts new file mode 100644 index 0000000..f12a005 --- /dev/null +++ b/src/lib/__tests__/demo.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { DEMO_COMPANY_SLUG, SANDBOX_DEMO_SLUGS, isDemoCompany, isSandboxDemoCompany } from "@/lib/demo"; + +describe("isDemoCompany", () => { + it("is true when demo_mode_enabled is true, regardless of slug", () => { + expect(isDemoCompany({ slug: "acme-hvac", demo_mode_enabled: true })).toBe(true); + }); + + it("is true for the canonical public demo slug, regardless of the flag", () => { + expect(isDemoCompany({ slug: DEMO_COMPANY_SLUG, demo_mode_enabled: false })).toBe(true); + }); + + it("is false for a real company with the flag off", () => { + expect(isDemoCompany({ slug: "acme-hvac", demo_mode_enabled: false })).toBe(false); + }); + + it("is false for null/undefined", () => { + expect(isDemoCompany(null)).toBe(false); + expect(isDemoCompany(undefined)).toBe(false); + }); +}); + +describe("isSandboxDemoCompany", () => { + it("is true for every slug on SANDBOX_DEMO_SLUGS", () => { + for (const slug of SANDBOX_DEMO_SLUGS) { + expect(isSandboxDemoCompany({ slug })).toBe(true); + } + }); + + it("is false for a real company even with demo_mode_enabled true (issue: seedDemoAction lets a real customer set this flag on their own company)", () => { + expect(isSandboxDemoCompany({ slug: "acme-hvac", demo_mode_enabled: true })).toBe(false); + }); + + it("is false for null/undefined or a company with no slug", () => { + expect(isSandboxDemoCompany(null)).toBe(false); + expect(isSandboxDemoCompany(undefined)).toBe(false); + expect(isSandboxDemoCompany({ slug: null })).toBe(false); + }); +}); diff --git a/src/lib/demo.ts b/src/lib/demo.ts index d5939ee..9322d80 100644 --- a/src/lib/demo.ts +++ b/src/lib/demo.ts @@ -20,3 +20,23 @@ export function isDemoCompany(company: CompanyDemoShape | null | undefined): boo if (!company) return false; return company.demo_mode_enabled === true || company.slug === DEMO_COMPANY_SLUG; } + +/** + * Purpose-built sandbox tenants only -- entirely synthetic companies with no + * real operational data, safe to fully wipe and reseed. `demo_mode_enabled` + * alone is NOT sufficient for this: `seedDemoAction` (admin/actions.ts, gated + * behind ENABLE_SEED_DEMO) lets a *real* customer flip that same flag on + * their own company to additively try sample data, without ever wiping their + * real jobs. `resetDemoTenant()` does a full destructive wipe of every job/ + * quote/status_event for whatever company it targets -- it must only ever be + * pointed at a slug on this list, never resolved from the flag alone. + * + * Add a new slug here when provisioning another purpose-built sandbox + * tenant (e.g. a private one shared with trusted prospects). + */ +export const SANDBOX_DEMO_SLUGS = [DEMO_COMPANY_SLUG, "swiftdispatch-preview"] as const; + +export function isSandboxDemoCompany(company: CompanyDemoShape | null | undefined): boolean { + if (!company?.slug) return false; + return (SANDBOX_DEMO_SLUGS as readonly string[]).includes(company.slug); +} diff --git a/src/lib/resetDemoTenant.ts b/src/lib/resetDemoTenant.ts index a944abc..3ffd3b5 100644 --- a/src/lib/resetDemoTenant.ts +++ b/src/lib/resetDemoTenant.ts @@ -1,48 +1,66 @@ import { createSupabaseAdminClient } from '@/lib/supabase/admin' import { demoJobs, demoTechnicians } from '@/lib/demo-data' -import { DEMO_COMPANY_SLUG } from '@/lib/demo' +import { DEMO_COMPANY_SLUG, SANDBOX_DEMO_SLUGS, isSandboxDemoCompany } from '@/lib/demo' // Re-exported for back-compat with existing import sites. export { DEMO_COMPANY_SLUG } +type AdminClient = ReturnType + /** - * Reset the demo tenant's job data. + * Reset demo tenant job data. This is a FULL DESTRUCTIVE WIPE (every job, + * quote, and status_event for the target company, not just is_demo=true + * rows) -- it must only ever run against a purpose-built sandbox tenant on + * SANDBOX_DEMO_SLUGS, never a company resolved from the `demo_mode_enabled` + * flag alone. That flag is also used by the separate, additive-only + * `seedDemoAction` (admin/actions.ts) to let a *real* customer try sample + * data on their own company without wiping anything -- resolving this + * function's target from the flag would let a nightly cron or a stray + * "reset demo" click delete a real customer's job history. + * + * Pass `targetCompanyId` to reset one specific, already-authorized sandbox + * company -- this is what the in-app "Reset data" button does. The slug is + * re-verified here (not just by the caller) since a full wipe is too + * dangerous to trust a single call site to gate correctly. * - * Pass `targetCompanyId` to reset a specific (already-authorized) company — - * this is what the in-app "Reset data" button does, so a slug-less demo - * tenant resets ITS OWN board rather than some other flagged company. When - * omitted (e.g. the nightly cron), the canonical demo company is resolved by - * slug, falling back to the demo_mode_enabled flag. + * When omitted (the nightly cron), every company whose slug is on + * SANDBOX_DEMO_SLUGS is reset in turn and the seeded counts are summed. */ export async function resetDemoTenant(targetCompanyId?: string): Promise<{ jobsSeeded: number }> { const admin = createSupabaseAdminClient() - let companyId = targetCompanyId - - if (!companyId) { - let { data: company } = await admin + if (targetCompanyId) { + const { data: company } = await admin .from('companies') - .select('id') - .eq('slug', DEMO_COMPANY_SLUG) + .select('id, slug') + .eq('id', targetCompanyId) .maybeSingle() - if (!company) { - const { data: flagged } = await admin - .from('companies') - .select('id') - .eq('demo_mode_enabled', true) - .limit(1) - .maybeSingle() - company = flagged + if (!isSandboxDemoCompany(company)) { + throw new Error(`Refusing to reset non-sandbox company ${targetCompanyId}`) } - if (!company) { - throw new Error(`Demo company not found (slug: ${DEMO_COMPANY_SLUG} or demo_mode_enabled)`) - } + return resetOneCompany(admin, targetCompanyId) + } + + const { data: companies } = await admin + .from('companies') + .select('id') + .in('slug', SANDBOX_DEMO_SLUGS) - companyId = company.id + if (!companies || companies.length === 0) { + throw new Error(`No sandbox demo companies found (slugs: ${SANDBOX_DEMO_SLUGS.join(', ')})`) } + let jobsSeeded = 0 + for (const company of companies) { + const result = await resetOneCompany(admin, company.id) + jobsSeeded += result.jobsSeeded + } + return { jobsSeeded } +} + +async function resetOneCompany(admin: AdminClient, companyId: string): Promise<{ jobsSeeded: number }> { const { data: technicians } = await admin .from('technicians') .select('id, name') From 43f3ebbefae47fb3149d3520381b1383c620bac4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 12:54:58 +0000 Subject: [PATCH 2/6] Remove the seed-demo admin flow from prod A real customer's company could flip demo_mode_enabled via seedDemoAction (gated behind ENABLE_SEED_DEMO) to additively seed sample jobs on their own live company, and resetCompanyDataAction that paired with it was dead code with no caller. Since companies can already write their own test tickets to try any flow, this whole mechanism was unnecessary risk surface rather than a feature worth keeping. Removes /admin/seed-demo, seedDemoAction, resetCompanyDataAction, ENABLE_SEED_DEMO, and featureFlags.ts, and updates the comments/docs that referenced seedDemoAction as the reason demo_mode_enabled alone isn't a safe reset target. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MR2GnZw5BX1L6QgTabt5JF --- .env.example | 3 - docs/AUTHORIZATION.md | 14 +- src/app/(app)/admin/actions.ts | 201 +------------------------ src/app/(app)/admin/seed-demo/page.tsx | 50 ------ src/app/api/demo/reset/route.ts | 4 +- src/lib/__tests__/demo.test.ts | 2 +- src/lib/demo.ts | 12 +- src/lib/featureFlags.ts | 3 - src/lib/resetDemoTenant.ts | 9 +- 9 files changed, 23 insertions(+), 275 deletions(-) delete mode 100644 src/app/(app)/admin/seed-demo/page.tsx delete mode 100644 src/lib/featureFlags.ts diff --git a/.env.example b/.env.example index ef8b712..ef3b537 100644 --- a/.env.example +++ b/.env.example @@ -32,9 +32,6 @@ SENTRY_ORG= SENTRY_PROJECT= SENTRY_AUTH_TOKEN= -# Internal-only demo seeding. Leave unset in production. -ENABLE_SEED_DEMO= - # Payment providers (stubbed — fill in when ready) STRIPE_SECRET_KEY= STRIPE_PUBLISHABLE_KEY= diff --git a/docs/AUTHORIZATION.md b/docs/AUTHORIZATION.md index 36f1b58..d7218ca 100644 --- a/docs/AUTHORIZATION.md +++ b/docs/AUTHORIZATION.md @@ -72,11 +72,15 @@ Not role-gated by design (token/secret auth instead, unchanged by #49): **Reviewed, intentionally unchanged:** `POST /api/demo/reset` uses `requireApiProfile()` (any authenticated company member), not a role check. -It only ever mutates `is_demo=true` tenant data, isn't in #49's priority -list, and `ResetDemoButton` may be shown to any authenticated demo-tenant -member via `DemoBanner`. Restricting it wasn't required and there's no -evidence the current UX is wrong — flagged here rather than silently left -inconsistent with everything else. +It does a full destructive wipe of the caller's own company (every job, +quote, and status_event, not just `is_demo=true` rows), but the route +re-verifies `isSandboxDemoCompany()` before calling `resetDemoTenant()`, so +it can only ever target a purpose-built sandbox tenant on +`SANDBOX_DEMO_SLUGS` (see `src/lib/demo.ts`), never a real customer's data. +It isn't in #49's priority list, and `ResetDemoButton` may be shown to any +authenticated demo-tenant member via `DemoBanner`. Restricting it further +wasn't required and there's no evidence the current UX is wrong — flagged +here rather than silently left inconsistent with everything else. ## `POST /api/jobs` — technician tenant ownership diff --git a/src/app/(app)/admin/actions.ts b/src/app/(app)/admin/actions.ts index a9b7615..4794d47 100644 --- a/src/app/(app)/admin/actions.ts +++ b/src/app/(app)/admin/actions.ts @@ -1,12 +1,9 @@ "use server"; import { revalidatePath } from "next/cache"; -import { notFound, redirect } from "next/navigation"; +import { redirect } from "next/navigation"; import { requireAdminProfile, requireSuperAdminProfile } from "@/lib/auth"; -import { demoJobs, demoTechnicians } from "@/lib/demo-data"; -import { isSeedDemoEnabled } from "@/lib/featureFlags"; import { createSupabaseAdminClient } from "@/lib/supabase/admin"; -import type { JobStatus } from "@/types/db"; function stringValue(formData: FormData, key: string) { return String(formData.get(key) ?? "").trim(); @@ -104,199 +101,3 @@ export async function addTechniciansAction(formData: FormData) { revalidatePath("/admin"); } -export async function seedDemoAction(formData: FormData) { - if (!isSeedDemoEnabled()) notFound(); - - const profile = await requireAdminProfile(); - const supabase = createSupabaseAdminClient(); - const companyId = profile.company_id; - - if (!companyId) return; - - await supabase - .from("companies") - .update({ demo_mode_enabled: true, close_status: "demo_done" }) - .eq("id", companyId); - - // Ensure demo technicians exist - const { data: existingTechs } = await supabase - .from("technicians") - .select("id,name") - .eq("company_id", companyId); - - const missingTechs = demoTechnicians.filter( - (tech) => !existingTechs?.some((existing: { name: string }) => existing.name === tech.name), - ); - - if (missingTechs.length) { - await supabase.from("technicians").insert( - missingTechs.map((tech) => ({ ...tech, company_id: companyId })), - ); - } - - const { data: technicians } = await supabase - .from("technicians") - .select("id,name") - .eq("company_id", companyId) - .in("name", demoTechnicians.map((t) => t.name)); - - // Fetch existing demo jobs by their prefixed customer name to avoid duplication - const { data: existingJobs } = await supabase - .from("jobs") - .select("customer_name") - .eq("company_id", companyId) - .eq("is_demo", true); - - const now = Date.now(); - - for (const demoJob of demoJobs) { - const prefixedName = `DEMO - ${demoJob.customerName}`; - - if (existingJobs?.some((j: { customer_name: string }) => j.customer_name === prefixedName)) { - continue; - } - - const techList = technicians ?? []; - const technician = - demoJob.techIndex !== null ? (techList[demoJob.techIndex] ?? null) : null; - - const createdAt = new Date(now - demoJob.ageMinutes * 60_000); - const assignedAt = new Date(createdAt.getTime() + 8 * 60_000); - const enRouteAt = new Date(createdAt.getTime() + 18 * 60_000); - const arrivedAt = new Date(createdAt.getTime() + 40 * 60_000); - const quoteAt = new Date(createdAt.getTime() + 55 * 60_000); - const quoteSentAt = new Date(createdAt.getTime() + 58 * 60_000); - const completedAt = new Date(createdAt.getTime() + 90 * 60_000); - - const isAssigned = !["new", "cancelled"].includes(demoJob.status); - - const jobPayload: Record = { - customer_name: prefixedName, - phone: demoJob.phone, - address: demoJob.address, - issue: demoJob.issue, - problem_description: demoJob.problemDescription, - status: demoJob.status as JobStatus, - urgency: demoJob.urgency, - source: demoJob.source, - sms_consent_type: demoJob.source === "intake" ? "intake_form" : "verbal_logged", - technician_id: isAssigned ? (technician?.id ?? null) : null, - company_id: companyId, - created_at: createdAt.toISOString(), - is_demo: true, - }; - - if (isAssigned) jobPayload.assigned_at = assignedAt.toISOString(); - if (["en_route", "in_progress", "quote_pending", "completed", "no_access"].includes(demoJob.status)) { - jobPayload.en_route_at = enRouteAt.toISOString(); - } - if (["in_progress", "quote_pending", "completed", "no_access"].includes(demoJob.status)) { - jobPayload.arrived_at = arrivedAt.toISOString(); - } - if (demoJob.status === "completed") { - jobPayload.completed_at = completedAt.toISOString(); - } - if (demoJob.status === "cancelled") { - jobPayload.cancellation_reason = "Customer requested cancellation before dispatch."; - jobPayload.cancelled_at = new Date(createdAt.getTime() + 15 * 60_000).toISOString(); - } - - const { data: job, error: jobError } = await supabase - .from("jobs") - .insert(jobPayload) - .select("id") - .single(); - - if (jobError || !job) continue; - - // Seed status event history for each transition that has occurred - const events: Array<{ from: string | null; to: string; offsetMs: number; role: string }> = [ - { from: null, to: "new", offsetMs: 0, role: demoJob.source === "intake" ? "customer" : "dispatcher" }, - ]; - - if (isAssigned) { - events.push({ from: "new", to: "assigned", offsetMs: 8 * 60_000, role: "dispatcher" }); - } - if (["en_route", "in_progress", "quote_pending", "completed", "no_access"].includes(demoJob.status)) { - events.push({ from: "assigned", to: "en_route", offsetMs: 18 * 60_000, role: "technician" }); - } - if (["in_progress", "quote_pending", "completed", "no_access"].includes(demoJob.status)) { - events.push({ from: "en_route", to: "in_progress", offsetMs: 40 * 60_000, role: "technician" }); - } - if (["quote_pending", "completed"].includes(demoJob.status)) { - events.push({ from: "in_progress", to: "quote_pending", offsetMs: 60 * 60_000, role: "technician" }); - } - if (demoJob.status === "completed") { - events.push({ from: "quote_pending", to: "completed", offsetMs: 90 * 60_000, role: "customer" }); - } - if (demoJob.status === "no_access") { - events.push({ from: "in_progress", to: "no_access", offsetMs: 55 * 60_000, role: "technician" }); - } - if (demoJob.status === "cancelled") { - events.push({ from: "new", to: "cancelled", offsetMs: 15 * 60_000, role: "dispatcher" }); - } - - await supabase.from("status_events").insert( - events.map((e) => ({ - job_id: job.id, - from_status: e.from, - to_status: e.to, - actor_role: e.role, - created_at: new Date(createdAt.getTime() + e.offsetMs).toISOString(), - })), - ); - - // Seed quote and line items for relevant statuses - if (demoJob.quote && demoJob.quoteStatus) { - const total = demoJob.quote.reduce((sum, item) => sum + item.price * item.quantity, 0); - - const { data: quote } = await supabase - .from("quotes") - .insert({ - job_id: job.id, - total, - total_amount: total, - status: demoJob.quoteStatus, - created_at: quoteAt.toISOString(), - quote_sent_at: quoteSentAt.toISOString(), - accepted_at: - demoJob.quoteStatus === "accepted" - ? new Date(quoteSentAt.getTime() + 18 * 60_000).toISOString() - : null, - is_demo: true, - }) - .select("id") - .single(); - - if (quote) { - await supabase.from("quote_line_items").insert( - demoJob.quote.map((item) => ({ - quote_id: quote.id, - name: item.name, - price: item.price, - quantity: item.quantity, - })), - ); - } - } - } - - revalidatePath("/admin"); -} - -export async function resetCompanyDataAction(formData: FormData) { - const profile = await requireAdminProfile(); - const supabase = createSupabaseAdminClient(); - const companyId = profile.company_id; - - if (!companyId) return; - - // Only delete demo-flagged jobs so a reset cannot wipe live operational data. - await supabase.from("jobs").delete().eq("company_id", companyId).eq("is_demo", true); - await supabase - .from("companies") - .update({ demo_mode_enabled: false }) - .eq("id", companyId); - - revalidatePath("/admin"); -} diff --git a/src/app/(app)/admin/seed-demo/page.tsx b/src/app/(app)/admin/seed-demo/page.tsx deleted file mode 100644 index 2d51054..0000000 --- a/src/app/(app)/admin/seed-demo/page.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import Link from "next/link"; -import { notFound } from "next/navigation"; -import { seedDemoAction } from "../actions"; -import { requireAdminProfile } from "@/lib/auth"; -import { isSeedDemoEnabled } from "@/lib/featureFlags"; -import { createSupabaseAdminClient } from "@/lib/supabase/admin"; - -export default async function SeedDemoPage() { - if (!isSeedDemoEnabled()) notFound(); - - await requireAdminProfile(); - const supabase = createSupabaseAdminClient(); - const { data, error } = await supabase - .from("companies") - .select("id,name") - .order("name"); - - if (error) throw new Error(error.message); - - return ( -
- - Back to admin - -
-

Seed Demo / Pilot Data

-
- - -
-
-
- ); -} diff --git a/src/app/api/demo/reset/route.ts b/src/app/api/demo/reset/route.ts index d357cfe..14381aa 100644 --- a/src/app/api/demo/reset/route.ts +++ b/src/app/api/demo/reset/route.ts @@ -21,8 +21,8 @@ export async function POST() { // resetDemoTenant() does a full destructive wipe (every job/quote/ // status_event, not just is_demo=true rows) -- isSandboxDemoCompany() // (purpose-built sandbox slugs only) is required here, not the looser - // isDemoCompany() flag check, since a real customer can also have - // demo_mode_enabled=true via the additive, non-destructive seedDemoAction. + // isDemoCompany() flag check, since a real customer's company could also + // carry demo_mode_enabled=true without ever being safe to wipe. if (!isSandboxDemoCompany(company)) { return NextResponse.json({ error: "Not a demo account" }, { status: 403 }); } diff --git a/src/lib/__tests__/demo.test.ts b/src/lib/__tests__/demo.test.ts index f12a005..7d2a32f 100644 --- a/src/lib/__tests__/demo.test.ts +++ b/src/lib/__tests__/demo.test.ts @@ -27,7 +27,7 @@ describe("isSandboxDemoCompany", () => { } }); - it("is false for a real company even with demo_mode_enabled true (issue: seedDemoAction lets a real customer set this flag on their own company)", () => { + it("is false for a real company even with demo_mode_enabled true (only a slug on SANDBOX_DEMO_SLUGS is safe to fully wipe)", () => { expect(isSandboxDemoCompany({ slug: "acme-hvac", demo_mode_enabled: true })).toBe(false); }); diff --git a/src/lib/demo.ts b/src/lib/demo.ts index 9322d80..24ebbeb 100644 --- a/src/lib/demo.ts +++ b/src/lib/demo.ts @@ -24,12 +24,12 @@ export function isDemoCompany(company: CompanyDemoShape | null | undefined): boo /** * Purpose-built sandbox tenants only -- entirely synthetic companies with no * real operational data, safe to fully wipe and reseed. `demo_mode_enabled` - * alone is NOT sufficient for this: `seedDemoAction` (admin/actions.ts, gated - * behind ENABLE_SEED_DEMO) lets a *real* customer flip that same flag on - * their own company to additively try sample data, without ever wiping their - * real jobs. `resetDemoTenant()` does a full destructive wipe of every job/ - * quote/status_event for whatever company it targets -- it must only ever be - * pointed at a slug on this list, never resolved from the flag alone. + * alone is NOT sufficient for this: a real customer's company can carry that + * same flag (set by hand, via support tooling, etc.) without ever being + * safe to wipe. `resetDemoTenant()` does a full destructive wipe of every + * job/quote/status_event for whatever company it targets -- it must only + * ever be pointed at a slug on this list, never resolved from the flag + * alone. * * Add a new slug here when provisioning another purpose-built sandbox * tenant (e.g. a private one shared with trusted prospects). diff --git a/src/lib/featureFlags.ts b/src/lib/featureFlags.ts deleted file mode 100644 index 911e463..0000000 --- a/src/lib/featureFlags.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function isSeedDemoEnabled() { - return process.env.ENABLE_SEED_DEMO === "true"; -} diff --git a/src/lib/resetDemoTenant.ts b/src/lib/resetDemoTenant.ts index 3ffd3b5..d429fab 100644 --- a/src/lib/resetDemoTenant.ts +++ b/src/lib/resetDemoTenant.ts @@ -12,11 +12,10 @@ type AdminClient = ReturnType * quote, and status_event for the target company, not just is_demo=true * rows) -- it must only ever run against a purpose-built sandbox tenant on * SANDBOX_DEMO_SLUGS, never a company resolved from the `demo_mode_enabled` - * flag alone. That flag is also used by the separate, additive-only - * `seedDemoAction` (admin/actions.ts) to let a *real* customer try sample - * data on their own company without wiping anything -- resolving this - * function's target from the flag would let a nightly cron or a stray - * "reset demo" click delete a real customer's job history. + * flag alone. A real customer's company could carry that same flag without + * ever being safe to wipe -- resolving this function's target from the flag + * would let a nightly cron or a stray "reset demo" click delete a real + * customer's job history. * * Pass `targetCompanyId` to reset one specific, already-authorized sandbox * company -- this is what the in-app "Reset data" button does. The slug is From 6399c659294aeaffe3c78045665ddd7f5086c912 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 13:02:40 +0000 Subject: [PATCH 3/6] Add a first-launch guided tutorial to the private preview demo Trusted prospects sharing the private preview tenant (any sandbox slug other than the public demo) get a spotlight-style walkthrough of the sidebar nav and the reset-data control on their first visit. It's gated to desktop widths (anchored tooltips don't translate well to the mobile nav), stores its dismissal in localStorage per company slug so it only shows once per browser, and offers a "Skip tutorial" control on every step in addition to running through to the end. Verified interaction logic (step navigation, skip, backdrop-click dismiss, localStorage persistence across reload, narrow-viewport suppression) with an isolated Playwright harness driving the actual component, since this environment has no live Supabase credentials to log into the real app with. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MR2GnZw5BX1L6QgTabt5JF --- src/components/AppSidebar.tsx | 9 +- src/components/DemoBanner.tsx | 8 +- src/components/DemoTutorial.tsx | 159 +++++++++++++++++++++++++++++ src/components/ResetDemoButton.tsx | 1 + src/lib/demo.ts | 10 ++ 5 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 src/components/DemoTutorial.tsx diff --git a/src/components/AppSidebar.tsx b/src/components/AppSidebar.tsx index f2a9ad5..ca2f4c6 100644 --- a/src/components/AppSidebar.tsx +++ b/src/components/AppSidebar.tsx @@ -11,6 +11,12 @@ type Section = "admin" | "superadmin" | "dispatch" | "dashboard"; type NavItem = { href: string; label: string }; type NavGroup = { label: string; items: NavItem[] }; +const NAV_TUTORIAL_TARGETS: Record = { + Dispatch: "nav-dispatch", + Analytics: "nav-analytics", + Overview: "nav-admin", +}; + function getNavGroups(section: Section, role: string): NavGroup[] { const dispatchHref = role === "super_admin" ? "/superadmin/dispatch" : "/dispatch"; @@ -88,6 +94,7 @@ export default function AppSidebar({ section, user }: Props) { key={item.href} href={item.href} onClick={() => setMobileOpen(false)} + data-tutorial={NAV_TUTORIAL_TARGETS[item.label]} className={`flex items-center rounded-md px-2 py-1.5 text-[13px] transition-colors ${ isActive ? "bg-[var(--c-paper-3)] font-medium text-[var(--c-text)]" @@ -125,7 +132,7 @@ export default function AppSidebar({ section, user }: Props) { className="no-print hidden w-[216px] shrink-0 flex-col border-r border-[var(--c-line)] bg-[var(--c-paper-2)] lg:flex" style={{ position: "sticky", top: 0, height: "100vh", overflowY: "auto" }} > -
+
{navContent} diff --git a/src/components/DemoBanner.tsx b/src/components/DemoBanner.tsx index bde0710..5012538 100644 --- a/src/components/DemoBanner.tsx +++ b/src/components/DemoBanner.tsx @@ -1,7 +1,8 @@ import Link from "next/link"; import { createSupabaseServerClient } from "@/lib/supabase/server"; -import { isDemoCompany } from "@/lib/demo"; +import { isDemoCompany, isPrivateSandboxDemoCompany } from "@/lib/demo"; import DemoTabNav from "@/components/DemoTabNav"; +import DemoTutorial from "@/components/DemoTutorial"; import ResetDemoButton from "@/components/ResetDemoButton"; export default async function DemoBanner() { @@ -23,7 +24,7 @@ export default async function DemoBanner() { .eq("id", profile.company_id) .single(); - if (!isDemoCompany(company)) return null; + if (!company || !isDemoCompany(company)) return null; return (
@@ -46,6 +47,9 @@ export default async function DemoBanner() {
+ {isPrivateSandboxDemoCompany(company) && ( + + )} ); } diff --git a/src/components/DemoTutorial.tsx b/src/components/DemoTutorial.tsx new file mode 100644 index 0000000..51a2d9e --- /dev/null +++ b/src/components/DemoTutorial.tsx @@ -0,0 +1,159 @@ +"use client"; + +import { useEffect, useState } from "react"; + +type Step = { + target: string; + title: string; + body: string; +}; + +const ALL_STEPS: Step[] = [ + { + target: "brand", + title: "Welcome to SwiftDispatch", + body: "This is a private preview — feel free to click around. Nothing here is a real customer, and it resets on its own.", + }, + { + target: "nav-dispatch", + title: "Dispatch board", + body: "Jobs move through new → assigned → en route → in progress → quote → completed. Click a job to see its full timeline.", + }, + { + target: "nav-analytics", + title: "Analytics", + body: "Response times, technician load, and job volume roll up here.", + }, + { + target: "nav-admin", + title: "Admin", + body: "Manage technicians, users, and SMS templates for the company.", + }, + { + target: "reset-demo", + title: "Reset anytime", + body: "This sandbox resets nightly on its own — or click here to wipe it back to sample data whenever you want a clean slate.", + }, +]; + +const DESKTOP_BREAKPOINT_PX = 1024; + +type Props = { + storageKey: string; + hasAdminNav: boolean; +}; + +export default function DemoTutorial({ storageKey, hasAdminNav }: Props) { + const dismissKey = `swiftdispatch_tutorial_dismissed_${storageKey}`; + const steps = hasAdminNav ? ALL_STEPS : ALL_STEPS.filter((s) => s.target !== "nav-admin"); + + const [visible, setVisible] = useState(false); + const [stepIndex, setStepIndex] = useState(0); + const [rect, setRect] = useState(null); + + useEffect(() => { + try { + if (localStorage.getItem(dismissKey)) return; + } catch { + return; + } + if (window.innerWidth < DESKTOP_BREAKPOINT_PX) return; + setVisible(true); + }, [dismissKey]); + + useEffect(() => { + if (!visible) return; + const step = steps[stepIndex]; + if (!step) return; + + const update = () => { + const el = document.querySelector(`[data-tutorial="${step.target}"]`); + setRect(el ? el.getBoundingClientRect() : null); + }; + update(); + window.addEventListener("resize", update); + return () => window.removeEventListener("resize", update); + }, [visible, stepIndex, steps]); + + function dismiss() { + setVisible(false); + try { + localStorage.setItem(dismissKey, "1"); + } catch { + // Private browsing / blocked storage: the tutorial just re-shows next launch. + } + } + + function next() { + if (stepIndex >= steps.length - 1) { + dismiss(); + return; + } + setStepIndex((i) => i + 1); + } + + if (!visible) return null; + const step = steps[stepIndex]; + if (!step) return null; + + const cardWidth = 300; + const cardTop = rect ? rect.bottom + 12 : window.innerHeight / 2 - 90; + const cardLeft = rect + ? Math.min(Math.max(rect.left, 16), window.innerWidth - cardWidth - 16) + : window.innerWidth / 2 - cardWidth / 2; + + return ( + <> +
+ {rect && ( +
+ )} +
+

+ Step {stepIndex + 1} of {steps.length} +

+

{step.title}

+

{step.body}

+
+ +
+ {stepIndex > 0 && ( + + )} + +
+
+
+ + ); +} diff --git a/src/components/ResetDemoButton.tsx b/src/components/ResetDemoButton.tsx index 753ceba..586379e 100644 --- a/src/components/ResetDemoButton.tsx +++ b/src/components/ResetDemoButton.tsx @@ -22,6 +22,7 @@ export default function ResetDemoButton() { type="button" onClick={handleReset} disabled={resetting} + data-tutorial="reset-demo" className="rounded-full border border-[var(--c-line)] px-3 py-1 font-mono text-[10px] text-[var(--c-text-4)] transition hover:border-[var(--c-line-2)] hover:text-[var(--c-text-3)] disabled:opacity-50" > {resetting ? "Resetting…" : "Reset data"} diff --git a/src/lib/demo.ts b/src/lib/demo.ts index 24ebbeb..b32c43a 100644 --- a/src/lib/demo.ts +++ b/src/lib/demo.ts @@ -40,3 +40,13 @@ export function isSandboxDemoCompany(company: CompanyDemoShape | null | undefine if (!company?.slug) return false; return (SANDBOX_DEMO_SLUGS as readonly string[]).includes(company.slug); } + +/** + * A purpose-built sandbox tenant that is NOT the public demo -- e.g. a + * private tenant shared with trusted prospects. Used to scope the + * first-launch guided tutorial to that private flow without also showing it + * on the public demo (which already has its own marketing-page framing). + */ +export function isPrivateSandboxDemoCompany(company: CompanyDemoShape | null | undefined): boolean { + return isSandboxDemoCompany(company) && company?.slug !== DEMO_COMPANY_SLUG; +} From 801c418e5dd24264b05d9b6a85ee8ccdd82d1252 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 13:06:24 +0000 Subject: [PATCH 4/6] Add regression tests for resetDemoTenant's sandbox-slug routing Covers the safety-critical logic added this branch: an explicit targetCompanyId on a non-sandbox company is refused with no wipe performed, a no-arg (cron) call resets every SANDBOX_DEMO_SLUGS company and aggregates jobsSeeded, and a real company that merely has demo_mode_enabled=true but isn't on the slug allowlist is never touched either way. Confirmed red-before-green by temporarily removing the non-sandbox guard: the regression test failed and showed the wipe actually proceeding (jobsSeeded: 14) before the guard was restored. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MR2GnZw5BX1L6QgTabt5JF --- src/lib/__tests__/resetDemoTenant.test.ts | 238 ++++++++++++++++++++++ 1 file changed, 238 insertions(+) create mode 100644 src/lib/__tests__/resetDemoTenant.test.ts diff --git a/src/lib/__tests__/resetDemoTenant.test.ts b/src/lib/__tests__/resetDemoTenant.test.ts new file mode 100644 index 0000000..6f9561c --- /dev/null +++ b/src/lib/__tests__/resetDemoTenant.test.ts @@ -0,0 +1,238 @@ +/** + * resetDemoTenant() does a FULL DESTRUCTIVE WIPE of every job/quote/ + * status_event for whatever company it targets. These tests exist to prove + * the safety-critical routing logic added around that wipe -- that it can + * only ever land on a company whose slug is on SANDBOX_DEMO_SLUGS, never a + * real customer resolved from the ambiguous `demo_mode_enabled` flag alone + * (see src/lib/demo.ts). They deliberately do NOT re-verify the seeding + * mechanics in exhaustive relational detail -- that's already exercised + * live by the nightly cron and the "Reset demo" button. + * + * Mocks @/lib/supabase/admin's createSupabaseAdminClient with a generic, + * permissive in-memory fake query builder (eq/in/not/order/limit/select/ + * insert/update/delete/single/maybeSingle, per-table row store), matching + * the pattern established by smsOutbox.test.ts. + */ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { demoJobs } from "@/lib/demo-data"; +import { resetDemoTenant } from "../resetDemoTenant"; + +type Row = Record; + +const { createSupabaseAdminClientMock } = vi.hoisted(() => ({ + createSupabaseAdminClientMock: vi.fn(), +})); + +vi.mock("@/lib/supabase/admin", () => ({ + createSupabaseAdminClient: () => createSupabaseAdminClientMock(), +})); + +type Filter = + | { type: "eq"; column: string; value: unknown } + | { type: "in"; column: string; values: unknown[] } + | { type: "not_in"; column: string; values: unknown[] }; + +function matchesFilters(row: Row, filters: Filter[]) { + return filters.every((f) => { + if (f.type === "eq") return row[f.column] === f.value; + if (f.type === "in") return f.values.includes(row[f.column]); + return !f.values.includes(row[f.column]); + }); +} + +function parseNotInList(raw: string): unknown[] { + return raw + .replace(/^\(|\)$/g, "") + .split(",") + .map((s) => s.replace(/^"|"$/g, "")); +} + +let idCounter = 0; + +class Builder { + private filters: Filter[] = []; + private orderColumn: string | null = null; + private orderAsc = true; + private limitN: number | null = null; + + constructor( + private table: string, + private store: Map, + private mode: "select" | "insert" | "update" | "delete", + private payload?: Row | Row[], + ) {} + + eq(column: string, value: unknown) { + this.filters.push({ type: "eq", column, value }); + return this; + } + in(column: string, values: unknown[]) { + this.filters.push({ type: "in", column, values }); + return this; + } + not(column: string, _op: string, raw: string) { + this.filters.push({ type: "not_in", column, values: parseNotInList(raw) }); + return this; + } + order(column: string, opts?: { ascending?: boolean }) { + this.orderColumn = column; + this.orderAsc = opts?.ascending ?? true; + return this; + } + limit(n: number) { + this.limitN = n; + return this; + } + select() { + return this; + } + + private rows() { + return this.store.get(this.table) ?? []; + } + private setRows(rows: Row[]) { + this.store.set(this.table, rows); + } + + private runSelect() { + let result = this.rows().filter((r) => matchesFilters(r, this.filters)); + if (this.orderColumn) { + const column = this.orderColumn; + result = [...result].sort((a, b) => { + const cmp = String(a[column]).localeCompare(String(b[column])); + return this.orderAsc ? cmp : -cmp; + }); + } + if (this.limitN !== null) result = result.slice(0, this.limitN); + return result; + } + + private runInsert() { + const items = Array.isArray(this.payload) ? this.payload : [this.payload!]; + const inserted = items.map((item) => ({ + id: `${this.table}-${(idCounter += 1)}`, + ...item, + })); + this.setRows([...this.rows(), ...inserted]); + return inserted; + } + + private runUpdate() { + const affected = this.rows().filter((r) => matchesFilters(r, this.filters)); + affected.forEach((r) => Object.assign(r, this.payload)); + return affected; + } + + private runDelete() { + const remaining = this.rows().filter((r) => !matchesFilters(r, this.filters)); + this.setRows(remaining); + } + + single() { + const rows = this.mode === "insert" ? this.runInsert() : this.runSelect(); + return Promise.resolve( + rows[0] ? { data: rows[0], error: null } : { data: null, error: { message: "not found" } }, + ); + } + + maybeSingle() { + const rows = this.mode === "insert" ? this.runInsert() : this.runSelect(); + return Promise.resolve({ data: rows[0] ?? null, error: null }); + } + + then(resolve: (value: { data: Row[] | null; error: null }) => void) { + let data: Row[] = []; + if (this.mode === "select") data = this.runSelect(); + else if (this.mode === "insert") data = this.runInsert(); + else if (this.mode === "update") data = this.runUpdate(); + else if (this.mode === "delete") this.runDelete(); + resolve({ data, error: null }); + } +} + +function createFakeSupabase(store: Map) { + return { + from(table: string) { + return { + select: () => new Builder(table, store, "select", undefined), + insert: (payload: Row | Row[]) => new Builder(table, store, "insert", payload), + update: (patch: Row) => new Builder(table, store, "update", patch), + delete: () => new Builder(table, store, "delete"), + }; + }, + }; +} + +const PUBLIC_DEMO_ID = "11111111-1111-4111-8111-111111111111"; +const PREVIEW_DEMO_ID = "22222222-2222-4222-8222-222222222222"; +const REAL_COMPANY_ID = "33333333-3333-4333-8333-333333333333"; + +function seedCompanies(store: Map) { + store.set("companies", [ + { id: PUBLIC_DEMO_ID, slug: "swiftdispatch-demo", demo_mode_enabled: true }, + { id: PREVIEW_DEMO_ID, slug: "swiftdispatch-preview", demo_mode_enabled: true }, + { id: REAL_COMPANY_ID, slug: "acme-hvac", demo_mode_enabled: true }, + ]); +} + +describe("resetDemoTenant", () => { + let store: Map; + + beforeEach(() => { + store = new Map(); + seedCompanies(store); + createSupabaseAdminClientMock.mockReset(); + createSupabaseAdminClientMock.mockImplementation(() => createFakeSupabase(store)); + }); + + it("resets an explicit targetCompanyId on a sandbox-slug company and reseeds its jobs", async () => { + const result = await resetDemoTenant(PREVIEW_DEMO_ID); + + expect(result.jobsSeeded).toBe(demoJobs.length); + const jobs = (store.get("jobs") ?? []).filter((j) => j.company_id === PREVIEW_DEMO_ID); + expect(jobs).toHaveLength(demoJobs.length); + }); + + it("refuses an explicit targetCompanyId on a non-sandbox company and performs no wipe", async () => { + store.set("jobs", [ + { id: "existing-job-1", company_id: REAL_COMPANY_ID, customer_name: "Real Customer" }, + ]); + + await expect(resetDemoTenant(REAL_COMPANY_ID)).rejects.toThrow( + /Refusing to reset non-sandbox company/, + ); + + // The real company's pre-existing job must be untouched -- no wipe, no reseed. + const jobs = store.get("jobs") ?? []; + expect(jobs).toHaveLength(1); + expect(jobs[0]).toMatchObject({ id: "existing-job-1", customer_name: "Real Customer" }); + }); + + it("with no targetCompanyId, resets every sandbox-slug company and aggregates jobsSeeded", async () => { + const result = await resetDemoTenant(); + + expect(result.jobsSeeded).toBe(demoJobs.length * 2); + const publicJobs = (store.get("jobs") ?? []).filter((j) => j.company_id === PUBLIC_DEMO_ID); + const previewJobs = (store.get("jobs") ?? []).filter((j) => j.company_id === PREVIEW_DEMO_ID); + expect(publicJobs).toHaveLength(demoJobs.length); + expect(previewJobs).toHaveLength(demoJobs.length); + }); + + it("with no targetCompanyId, never touches a real company even with demo_mode_enabled=true", async () => { + store.set("jobs", [ + { id: "existing-job-1", company_id: REAL_COMPANY_ID, customer_name: "Real Customer" }, + ]); + + await resetDemoTenant(); + + const realCompanyJobs = (store.get("jobs") ?? []).filter((j) => j.company_id === REAL_COMPANY_ID); + expect(realCompanyJobs).toHaveLength(1); + expect(realCompanyJobs[0]).toMatchObject({ id: "existing-job-1", customer_name: "Real Customer" }); + }); + + it("throws when no sandbox demo companies exist", async () => { + store.set("companies", [{ id: REAL_COMPANY_ID, slug: "acme-hvac", demo_mode_enabled: true }]); + + await expect(resetDemoTenant()).rejects.toThrow(/No sandbox demo companies found/); + }); +}); From a428853160db56c730760fe30bbd2931400da813 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 13:15:14 +0000 Subject: [PATCH 5/6] Fix Codex review findings: reserved-slug bypass and tutorial infinite loop P1: PATCH /api/admin/settings let any admin set their own company's slug to an unclaimed SANDBOX_DEMO_SLUGS value (only uniqueness was checked). Since resetDemoTenant() resolves its destructive-wipe target by slug alone, a real company that grabbed "swiftdispatch-preview" before it's provisioned would get its jobs wiped by the next nightly cron run. Reserve SANDBOX_DEMO_SLUGS from self-service slug edits. Confirmed red-before-green: reverting the guard let the reserved slug through with a 200, and the new regression test caught it. P1: DemoTutorial recomputed its filtered `steps` array with .filter() on every render whenever hasAdminNav was false (dispatcher role, the role a trusted-preview login would actually use). Since `steps` is an effect dependency and that effect calls setRect() with a new DOMRect each time, this was an infinite render loop -- reproduced with an isolated Playwright harness (hasAdminNav: false) showing 333 "Maximum update depth exceeded" errors before the fix, 0 after. Memoized with useMemo keyed on hasAdminNav. P2: also addressed while in the file -- suspend (not dismiss-and- remember) the tutorial if the viewport narrows below the desktop breakpoint while it's open, and give the card real dialog semantics (role="dialog", aria-modal, focus on open, Tab focus trap, Escape to dismiss, focus restored on close). Re-verified the full interaction surface (step-through, skip, resize-suspend, Escape, focus trap) with the same Playwright harness -- all passing, zero console errors. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MR2GnZw5BX1L6QgTabt5JF --- src/app/api/admin/settings/route.test.ts | 15 ++++++ src/app/api/admin/settings/route.ts | 11 ++++ src/components/DemoTutorial.tsx | 69 ++++++++++++++++++++++-- 3 files changed, 91 insertions(+), 4 deletions(-) diff --git a/src/app/api/admin/settings/route.test.ts b/src/app/api/admin/settings/route.test.ts index 8ee65a8..54eb0da 100644 --- a/src/app/api/admin/settings/route.test.ts +++ b/src/app/api/admin/settings/route.test.ts @@ -217,6 +217,21 @@ describe("PATCH /api/admin/settings", () => { expect(response.status).toBe(400); }); + it("rejects a reserved sandbox slug, even when it's currently unclaimed by any company", async () => { + requireApiRoleMock.mockResolvedValue({ + profile: adminProfile(), + response: null, + // No company holds "swiftdispatch-preview" yet -- proves this is + // blocked by the reserved-slug check itself, not the uniqueness + // conflict lookup (which would find no conflict and let it through). + supabase: supabaseWithCompanies(freshCompanies()), + }); + + const response = await patchSettings({ slug: "swiftdispatch-preview" }); + + expect(response.status).toBe(409); + }); + it("rejects a slug already taken by a real other-company row", async () => { requireApiRoleMock.mockResolvedValue({ profile: adminProfile(), diff --git a/src/app/api/admin/settings/route.ts b/src/app/api/admin/settings/route.ts index 5e61abc..74b7733 100644 --- a/src/app/api/admin/settings/route.ts +++ b/src/app/api/admin/settings/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from 'next/server' import { getPublicSquareConnection } from '@/lib/square' import { requireApiRole } from '@/lib/auth' +import { SANDBOX_DEMO_SLUGS } from '@/lib/demo' export async function GET() { const { profile, response, supabase } = await requireApiRole(['admin']) @@ -56,6 +57,16 @@ export async function PATCH(request: Request) { return NextResponse.json({ error: 'slug cannot be empty' }, { status: 400 }) } + // Reserved for purpose-built sandbox tenants (see SANDBOX_DEMO_SLUGS / + // resetDemoTenant()) -- resetDemoTenant() does a full destructive wipe of + // whatever company holds one of these slugs, resolved by slug alone with + // no ownership check. If self-service settings let any admin claim an + // unclaimed sandbox slug, a real company's data would be swept into the + // next nightly reset. + if ((SANDBOX_DEMO_SLUGS as readonly string[]).includes(slug)) { + return NextResponse.json({ error: 'That slug is reserved' }, { status: 409 }) + } + // Check slug uniqueness — maybeSingle() returns null (not an error) when no conflict found const { data: conflict } = await supabase .from('companies') diff --git a/src/components/DemoTutorial.tsx b/src/components/DemoTutorial.tsx index 51a2d9e..69ee408 100644 --- a/src/components/DemoTutorial.tsx +++ b/src/components/DemoTutorial.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; type Step = { target: string; @@ -45,12 +45,18 @@ type Props = { export default function DemoTutorial({ storageKey, hasAdminNav }: Props) { const dismissKey = `swiftdispatch_tutorial_dismissed_${storageKey}`; - const steps = hasAdminNav ? ALL_STEPS : ALL_STEPS.filter((s) => s.target !== "nav-admin"); + const steps = useMemo( + () => (hasAdminNav ? ALL_STEPS : ALL_STEPS.filter((s) => s.target !== "nav-admin")), + [hasAdminNav], + ); const [visible, setVisible] = useState(false); const [stepIndex, setStepIndex] = useState(0); const [rect, setRect] = useState(null); + const cardRef = useRef(null); + const previouslyFocusedRef = useRef(null); + useEffect(() => { try { if (localStorage.getItem(dismissKey)) return; @@ -75,6 +81,29 @@ export default function DemoTutorial({ storageKey, hasAdminNav }: Props) { return () => window.removeEventListener("resize", update); }, [visible, stepIndex, steps]); + // The anchored tour only makes sense at desktop widths (see the mount + // check above) -- if the viewport narrows while it's open (resize, device + // rotation), the sidebar it's pointing at can disappear entirely. Suspend + // rather than dismiss-and-remember, so it can still show next time they're + // back on desktop. + useEffect(() => { + if (!visible) return; + function onResize() { + if (window.innerWidth < DESKTOP_BREAKPOINT_PX) setVisible(false); + } + window.addEventListener("resize", onResize); + return () => window.removeEventListener("resize", onResize); + }, [visible]); + + useEffect(() => { + if (!visible) return; + previouslyFocusedRef.current = document.activeElement as HTMLElement | null; + cardRef.current?.focus(); + return () => { + previouslyFocusedRef.current?.focus?.(); + }; + }, [visible]); + function dismiss() { setVisible(false); try { @@ -84,6 +113,30 @@ export default function DemoTutorial({ storageKey, hasAdminNav }: Props) { } } + function onCardKeyDown(event: React.KeyboardEvent) { + if (event.key === "Escape") { + event.stopPropagation(); + dismiss(); + return; + } + if (event.key !== "Tab") return; + + const focusable = cardRef.current?.querySelectorAll( + 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', + ); + if (!focusable || focusable.length === 0) return; + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + } + function next() { if (stepIndex >= steps.length - 1) { dismiss(); @@ -118,13 +171,21 @@ export default function DemoTutorial({ storageKey, hasAdminNav }: Props) { /> )}

Step {stepIndex + 1} of {steps.length}

-

{step.title}

+

+ {step.title} +

{step.body}