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/scripts/lib/seedDemoGuard.mjs b/scripts/lib/seedDemoGuard.mjs new file mode 100644 index 0000000..0195f5c --- /dev/null +++ b/scripts/lib/seedDemoGuard.mjs @@ -0,0 +1,63 @@ +/** + * Preflight guard for scripts/seed-demo-tenant.mjs. Pulled out into its own + * module so it can run before ANY Supabase write and be unit-tested without + * a live database. + * + * seed-demo-tenant.mjs does a full destructive wipe of whatever company its + * slug resolves to, and can silently reassign existing Supabase Auth users + * (the demo login, the three technician logins) to a different company if + * their email/handle collide. The public demo's defaults are safe BECAUSE + * they're only ever applied to the public demo's own company -- any other + * slug must come with its own non-default credentials and technician handle + * suffix, or this refuses to run. + * + * Mirrors SANDBOX_DEMO_SLUGS in src/lib/demo.ts -- this script is a plain + * .mjs with no bundler, so it can't import that TypeScript module directly. + * Keep both lists in sync. + */ +export const SANDBOX_DEMO_SLUGS = ["swiftdispatch-demo", "swiftdispatch-preview"]; + +export const PUBLIC_DEMO_SLUG = "swiftdispatch-demo"; +export const PUBLIC_DEMO_EMAIL = "demo@swiftdispatch.app"; +export const PUBLIC_DEMO_PASSWORD = "demo"; + +/** + * @param {{ slug: string, userEmail: string, userPassword: string, handleSuffix: string }} config + * @throws {Error} if the config would let this script hijack the public + * demo's auth users or wipe a company outside the sandbox allowlist. + */ +export function validateSeedConfig({ slug, userEmail, userPassword, handleSuffix }) { + if (!SANDBOX_DEMO_SLUGS.includes(slug)) { + throw new Error( + `Refusing to seed "${slug}" -- it is not on SANDBOX_DEMO_SLUGS. This script does a full ` + + `destructive wipe of whatever company the slug resolves to. Add the slug to ` + + `SANDBOX_DEMO_SLUGS in both src/lib/demo.ts and scripts/lib/seedDemoGuard.mjs first if this ` + + `is a new purpose-built sandbox tenant.`, + ); + } + + if (slug === PUBLIC_DEMO_SLUG) return; + + if (userEmail === PUBLIC_DEMO_EMAIL) { + throw new Error( + `Refusing to seed "${slug}" with the public demo's login email (${PUBLIC_DEMO_EMAIL}). ` + + `Set DEMO_USER_EMAIL to a distinct address, or this reassigns the public demo's login to ` + + `this company.`, + ); + } + + if (userPassword === PUBLIC_DEMO_PASSWORD) { + throw new Error( + `Refusing to seed "${slug}" with the public demo's default password. Set DEMO_USER_PASSWORD ` + + `to a real generated password -- this tenant's credentials are meant to be shared privately.`, + ); + } + + if (!handleSuffix) { + throw new Error( + `Refusing to seed "${slug}" without DEMO_HANDLE_SUFFIX. Reusing the public demo's technician ` + + `handles (miatorres, leogrant, averybrooks) would hijack their Supabase Auth logins into ` + + `this company.`, + ); + } +} diff --git a/scripts/lib/seedDemoGuard.test.mjs b/scripts/lib/seedDemoGuard.test.mjs new file mode 100644 index 0000000..b277765 --- /dev/null +++ b/scripts/lib/seedDemoGuard.test.mjs @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { validateSeedConfig } from "./seedDemoGuard.mjs"; + +const PUBLIC_DEFAULTS = { + slug: "swiftdispatch-demo", + userEmail: "demo@swiftdispatch.app", + userPassword: "demo", + handleSuffix: "", +}; + +const PREVIEW_TENANT = { + slug: "swiftdispatch-preview", + userEmail: "preview@swiftdispatch.app", + userPassword: "a-real-generated-password", + handleSuffix: "preview", +}; + +describe("validateSeedConfig", () => { + it("allows the canonical public demo defaults", () => { + expect(() => validateSeedConfig(PUBLIC_DEFAULTS)).not.toThrow(); + }); + + it("allows a fully-specified preview tenant", () => { + expect(() => validateSeedConfig(PREVIEW_TENANT)).not.toThrow(); + }); + + it("refuses a custom slug with the public demo's default email", () => { + expect(() => + validateSeedConfig({ ...PREVIEW_TENANT, userEmail: "demo@swiftdispatch.app" }), + ).toThrow(/public demo's login email/); + }); + + it("refuses a custom slug with the public demo's default password", () => { + expect(() => validateSeedConfig({ ...PREVIEW_TENANT, userPassword: "demo" })).toThrow( + /public demo's default password/, + ); + }); + + it("refuses a custom slug with an empty technician handle suffix", () => { + expect(() => validateSeedConfig({ ...PREVIEW_TENANT, handleSuffix: "" })).toThrow( + /DEMO_HANDLE_SUFFIX/, + ); + }); + + it("refuses a slug that isn't on SANDBOX_DEMO_SLUGS, before any other check", () => { + expect(() => + validateSeedConfig({ + slug: "acme-hvac", + userEmail: "demo@swiftdispatch.app", + userPassword: "demo", + handleSuffix: "", + }), + ).toThrow(/not on SANDBOX_DEMO_SLUGS/); + }); +}); diff --git a/scripts/seed-demo-tenant.mjs b/scripts/seed-demo-tenant.mjs index d860834..5ab9eb6 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 @@ -17,6 +37,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { createClient } from "@supabase/supabase-js"; +import { validateSeedConfig } from "./lib/seedDemoGuard.mjs"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -46,32 +67,46 @@ 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" }, ]; +// Runs before any Supabase call below -- refuses to start rather than +// silently hijacking the public demo's auth users or wiping the wrong +// company. See scripts/lib/seedDemoGuard.mjs for what it checks and why. +validateSeedConfig({ + slug: DEMO_COMPANY_SLUG, + userEmail: DEMO_USER.email, + userPassword: DEMO_USER.password, + handleSuffix: HANDLE_SUFFIX, +}); + const TEMPLATE = { name: "Standard Diagnostic + Repair", estimated_duration_minutes: 90, @@ -259,9 +294,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 +315,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/(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/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/app/api/demo/reset/route.ts b/src/app/api/demo/reset/route.ts index 91f9aa4..14381aa 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'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/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..69ee408 --- /dev/null +++ b/src/components/DemoTutorial.tsx @@ -0,0 +1,220 @@ +"use client"; + +import { useEffect, useMemo, useRef, 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 = 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; + } 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]); + + // 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 { + localStorage.setItem(dismissKey, "1"); + } catch { + // Private browsing / blocked storage: the tutorial just re-shows next launch. + } + } + + 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(); + 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/__tests__/demo.test.ts b/src/lib/__tests__/demo.test.ts new file mode 100644 index 0000000..7d2a32f --- /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 (only a slug on SANDBOX_DEMO_SLUGS is safe to fully wipe)", () => { + 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/__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/); + }); +}); diff --git a/src/lib/demo.ts b/src/lib/demo.ts index d5939ee..b32c43a 100644 --- a/src/lib/demo.ts +++ b/src/lib/demo.ts @@ -20,3 +20,33 @@ 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: 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). + */ +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); +} + +/** + * 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; +} 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 a944abc..d429fab 100644 --- a/src/lib/resetDemoTenant.ts +++ b/src/lib/resetDemoTenant.ts @@ -1,48 +1,65 @@ 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. 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 + * 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')