diff --git a/scripts/seed-demo-tenant.mjs b/scripts/seed-demo-tenant.mjs index 5ab9eb6..7afda80 100644 --- a/scripts/seed-demo-tenant.mjs +++ b/scripts/seed-demo-tenant.mjs @@ -232,6 +232,11 @@ async function seedJobs(companyId, techIds) { const now = Date.now(); let seeded = 0; + const TERMINAL_STATUSES = ["completed", "cancelled", "no_access"]; + // Oldest active job per technician wins -- matches the (technician_id, status) + // semantics PATCH /api/jobs/[id] uses for real assignments, so the tech rail's + // "on job" state agrees with what the kanban cards show for this tech. + const techActiveJobs = new Map(); for (const demoJob of DEMO_JOBS) { const createdAt = new Date(now - demoJob.ageMinutes * 60_000); @@ -268,6 +273,13 @@ async function seedJobs(companyId, techIds) { const { data: job, error: jobError } = await supabase.from("jobs").insert(jobPayload).select("id").single(); if (jobError || !job) { console.error(`Failed to insert ${demoJob.customerName}:`, jobError?.message); continue; } + if (isAssigned && techId && !TERMINAL_STATUSES.includes(demoJob.status)) { + const existing = techActiveJobs.get(techId); + if (!existing || createdAt.getTime() < existing.createdAt) { + techActiveJobs.set(techId, { jobId: job.id, createdAt: createdAt.getTime() }); + } + } + const events = [{ 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"].includes(demoJob.status)) events.push({ from: "assigned", to: "en_route", offsetMs: 18 * 60_000, role: "technician" }); @@ -288,6 +300,12 @@ async function seedJobs(companyId, techIds) { seeded++; } + // Reflect each technician's active job in their availability, so the tech + // rail (available/on job) agrees with what the kanban cards show them doing. + for (const [techId, { jobId }] of techActiveJobs) { + await supabase.from("technicians").update({ availability_status: "on_job", current_job_id: jobId }).eq("id", techId); + } + return seeded; } diff --git a/src/app/(app)/admin/page.tsx b/src/app/(app)/admin/page.tsx index 866f9ce..1e9369c 100644 --- a/src/app/(app)/admin/page.tsx +++ b/src/app/(app)/admin/page.tsx @@ -1,6 +1,7 @@ import Link from "next/link"; import { addTechniciansAction, createDispatcherAction } from "./actions"; import { requireAdminProfile } from "@/lib/auth"; +import { isSandboxDemoCompany } from "@/lib/demo"; import { createSupabaseServerClient } from "@/lib/supabase/server"; type CompanyRow = { @@ -32,7 +33,7 @@ export default async function AdminPage() { const supabase = await createSupabaseServerClient(); const [companyResult, jobsResult, techsResult, usersResult] = await Promise.all([ supabase.from("companies").select("id,name,email,phone,slug,timezone,sms_sender_name,payment_provider").eq("id", profile.company_id).single(), - supabase.from("jobs").select("id,status").eq("company_id", profile.company_id).eq("is_demo", false).order("created_at", { ascending: false }), + supabase.from("jobs").select("id,status,is_demo").eq("company_id", profile.company_id).order("created_at", { ascending: false }), supabase.from("technicians").select("id,name,availability_status").eq("company_id", profile.company_id).order("name"), supabase.from("users").select("id,email,role").eq("company_id", profile.company_id).order("email"), ]); @@ -43,7 +44,8 @@ export default async function AdminPage() { if (usersResult.error) throw new Error(usersResult.error.message); const company = companyResult.data as CompanyRow; - const jobs = jobsResult.data ?? []; + const isSandbox = isSandboxDemoCompany(company); + const jobs = (jobsResult.data ?? []).filter((job) => isSandbox || !job.is_demo); const techs = techsResult.data ?? []; const users = (usersResult.data ?? []) as UserRow[]; const activeJobs = jobs.filter((job) => !["completed", "cancelled"].includes(job.status)).length; diff --git a/src/app/(app)/dispatch/page.tsx b/src/app/(app)/dispatch/page.tsx index 35e58bd..7b7e458 100644 --- a/src/app/(app)/dispatch/page.tsx +++ b/src/app/(app)/dispatch/page.tsx @@ -5,7 +5,7 @@ import TechPhoneModal from "@/components/TechPhoneModal"; import { createSupabaseAdminClient } from "@/lib/supabase/admin"; import { getCurrentProfile } from "@/lib/auth"; import { createSupabaseServerClient } from "@/lib/supabase/server"; -import { isDemoCompany } from "@/lib/demo"; +import { isDemoCompany, isSandboxDemoCompany } from "@/lib/demo"; import { demoTechnicians } from "@/lib/demo-data"; import type { JobWithTechnician, Technician } from "@/types/db"; @@ -67,11 +67,19 @@ export default async function DispatchPage({ searchParams }: { searchParams: Pro supabase.from("sms_outbox").select("job_id").eq("company_id", companyId).eq("status", "failed"), ]); - const allJobs = (jobs ?? []) as JobWithTechnician[]; const techList = (technicians ?? []) as Technician[]; const companyData = (companyRes as { data: { name: string; slug: string | null; demo_mode_enabled: boolean } | null }).data; const companyName = companyData?.name ?? companyId; + // Independent of `impersonating` -- this reflects whether the COMPANY's own + // rows are all synthetic, not who's currently viewing them. A load-tested + // ordinary company must hide its is_demo=true rows here the same way its + // own dispatcher's board (and KanbanBoard's realtime refetch) does; a + // sandbox tenant must show them even when a super_admin is impersonating + // it, or platform support would see an empty board for it. + const companyIsSandbox = isSandboxDemoCompany(companyData); + const allJobs = ((jobs ?? []) as JobWithTechnician[]).filter((j) => companyIsSandbox || !j.is_demo); const isDemo = !impersonating && isDemoCompany(companyData); + const isSandboxDemo = !impersonating && companyIsSandbox; const smsFailedJobIds = (failedSms ?? []).map((r: { job_id: string | null }) => r.job_id).filter(Boolean) as string[]; const activeCount = allJobs.filter((j) => !["completed", "cancelled"].includes(j.status)).length; @@ -116,7 +124,7 @@ export default async function DispatchPage({ searchParams }: { searchParams: Pro
- + {!impersonating && }
diff --git a/src/app/(app)/quote/[id]/page.tsx b/src/app/(app)/quote/[id]/page.tsx index 2ef8d1d..0185b07 100644 --- a/src/app/(app)/quote/[id]/page.tsx +++ b/src/app/(app)/quote/[id]/page.tsx @@ -3,6 +3,7 @@ import AcceptQuoteButton from "@/components/AcceptQuoteButton"; import { StatusDot } from "@/components/DesignSystem"; import { money } from "@/lib/format"; import { requireProfileWithRole } from "@/lib/auth"; +import { isCompanySandboxDemo } from "@/lib/demo"; import { createSupabaseServerClient } from "@/lib/supabase/server"; import type { QuoteWithItems } from "@/types/db"; @@ -17,14 +18,15 @@ export default async function PublicQuotePage({ params }: { params: Promise<{ id const { id } = await params; const profile = await requireProfileWithRole(["admin", "dispatcher"]); const supabase = await createSupabaseServerClient(); + const isSandbox = await isCompanySandboxDemo(supabase, profile.company_id); - const { data, error } = await supabase + let quoteQuery = supabase .from("quotes") .select("*, quote_line_items(id,quote_id,name,price,quantity), jobs!inner(id,customer_name,phone,address,issue,company_id)") .eq("id", id) - .eq("is_demo", false) - .eq("jobs.company_id", profile.company_id) - .single(); + .eq("jobs.company_id", profile.company_id); + if (!isSandbox) quoteQuery = quoteQuery.eq("is_demo", false); + const { data, error } = await quoteQuery.single(); if (error || !data) notFound(); const quote = data as QuoteWithItems; diff --git a/src/app/api/jobs/route.test.ts b/src/app/api/jobs/route.test.ts index 44a35b5..22ca192 100644 --- a/src/app/api/jobs/route.test.ts +++ b/src/app/api/jobs/route.test.ts @@ -372,4 +372,15 @@ describe("GET /api/jobs", () => { expect(ids).toEqual(["job-existing-active"]); expect(ids).not.toContain("job-other-company"); }); + + it("includes demo jobs for a sandbox tenant (whose jobs are all is_demo=true)", async () => { + db.companies[0].slug = "swiftdispatch-preview"; + const response = await listJobs(); + + expect(response.status).toBe(200); + const body = (await response.json()) as { jobs: Row[] }; + const ids = body.jobs.map((j) => j.id).sort(); + expect(ids).toEqual(["job-existing-active", "job-existing-demo"]); + expect(ids).not.toContain("job-other-company"); + }); }); diff --git a/src/app/api/jobs/route.ts b/src/app/api/jobs/route.ts index 7851d32..d5cfada 100644 --- a/src/app/api/jobs/route.ts +++ b/src/app/api/jobs/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from 'next/server' import { z } from 'zod' import { requireApiRole } from '@/lib/auth' +import { isCompanySandboxDemo } from '@/lib/demo' import { createSupabaseAdminClient } from '@/lib/supabase/admin' import { queueCustomerStatusSms, queueTechnicianAssignmentSms } from '@/lib/jobNotifications' import type { SmsConsentType } from '@/lib/smsGate' @@ -22,13 +23,14 @@ export async function GET() { const { profile, response, supabase } = await requireApiRole(['dispatcher', 'admin']) if (response || !profile) return response - const { data, error } = await supabase + const isSandbox = await isCompanySandboxDemo(supabase, profile.company_id) + let query = supabase .from('jobs') .select('*, technicians!jobs_technician_id_fkey(id,name,phone)') .eq('company_id', profile.company_id) - .eq('is_demo', false) .not('status', 'in', '("completed","cancelled")') - .order('created_at', { ascending: false }) + if (!isSandbox) query = query.eq('is_demo', false) + const { data, error } = await query.order('created_at', { ascending: false }) if (error) { return NextResponse.json({ error: error.message }, { status: 400 }) diff --git a/src/app/api/quotes/[id]/line-items/[itemId]/route.test.ts b/src/app/api/quotes/[id]/line-items/[itemId]/route.test.ts index 5f483f7..65bbd82 100644 --- a/src/app/api/quotes/[id]/line-items/[itemId]/route.test.ts +++ b/src/app/api/quotes/[id]/line-items/[itemId]/route.test.ts @@ -35,6 +35,10 @@ function makeSelectBuilder(getRows: () => Row[]) { const row = getRows().find((r) => matchesFilters(r, filters)); return row ? { data: row, error: null } : { data: null, error: { message: "Row not found" } }; }, + maybeSingle: async () => { + const row = getRows().find((r) => matchesFilters(r, filters)); + return { data: row ?? null, error: null }; + }, then(resolve: (value: { data: Row[]; error: null }) => void) { resolve({ data: getRows().filter((r) => matchesFilters(r, filters)), error: null }); }, @@ -83,7 +87,7 @@ function makeDeleteBuilder(db: Db) { return builder; } -type Db = { quotes: Row[]; quote_line_items: Row[] }; +type Db = { quotes: Row[]; quote_line_items: Row[]; companies: Row[] }; function createFakeSupabase(db: Db) { return { @@ -101,6 +105,9 @@ function createFakeSupabase(db: Db) { delete: () => makeDeleteBuilder(db), }; } + if (table === "companies") { + return { select: () => makeSelectBuilder(() => db.companies) }; + } throw new Error(`Unexpected table in test double: ${table}`); }, }; @@ -120,6 +127,7 @@ function freshDb(): Db { { id: ITEM_ID, quote_id: QUOTE_ID, name: "Compressor", price: 200, quantity: 1 }, { id: OTHER_ITEM_ID, quote_id: QUOTE_ID, name: "Filter", price: 50, quantity: 1 }, ], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], }; } @@ -207,3 +215,49 @@ describe("DELETE /api/quotes/[id]/line-items/[itemId]", () => { expect(db.quote_line_items).toHaveLength(2); }); }); + +// Half-Shell review on this PR (echoing the Codex finding on GET /api/jobs): +// a sandbox tenant's is_demo=true quotes must stay editable here, while an +// ordinary company's is_demo=true rows (load-test/live-QA traffic -- see +// scripts/load-tech-actions.mjs) must stay hidden/unfindable. +describe("is_demo visibility", () => { + const SANDBOX_COMPANY_ID = "99999999-9999-4999-8999-999999999999"; + + beforeEach(() => { + requireApiRoleMock.mockReset(); + }); + + function requireApiRoleWith(companyId: string, testDb: Db) { + requireApiRoleMock.mockResolvedValue({ + profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: companyId, role: "dispatcher" }, + response: null, + supabase: createFakeSupabase(testDb), + }); + } + + it("sandbox tenant: can edit a line item on an is_demo=true quote", async () => { + db = { + quotes: [{ id: QUOTE_ID, is_demo: true, jobs: { company_id: SANDBOX_COMPANY_ID } }], + quote_line_items: [{ id: ITEM_ID, quote_id: QUOTE_ID, name: "Compressor", price: 200, quantity: 1 }], + companies: [{ id: SANDBOX_COMPANY_ID, slug: "swiftdispatch-preview" }], + }; + requireApiRoleWith(SANDBOX_COMPANY_ID, db); + + const response = await patchLineItem(ITEM_ID, { price: 300 }); + + expect(response.status).toBe(200); + }); + + it("ordinary tenant: an is_demo=true quote (load-test traffic) is not found for editing", async () => { + db = { + quotes: [{ id: QUOTE_ID, is_demo: true, jobs: { company_id: COMPANY_ID } }], + quote_line_items: [{ id: ITEM_ID, quote_id: QUOTE_ID, name: "Compressor", price: 200, quantity: 1 }], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], + }; + requireApiRoleWith(COMPANY_ID, db); + + const response = await patchLineItem(ITEM_ID, { price: 300 }); + + expect(response.status).toBe(404); + }); +}); diff --git a/src/app/api/quotes/[id]/line-items/[itemId]/route.ts b/src/app/api/quotes/[id]/line-items/[itemId]/route.ts index 1be85ac..beedf7e 100644 --- a/src/app/api/quotes/[id]/line-items/[itemId]/route.ts +++ b/src/app/api/quotes/[id]/line-items/[itemId]/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import { requireApiRole } from "@/lib/auth"; +import { isCompanySandboxDemo } from "@/lib/demo"; import { sumLineItems } from "@/lib/quotePricing"; async function assertQuoteOwnership( @@ -7,13 +8,14 @@ async function assertQuoteOwnership( quoteId: string, companyId: string, ) { - return supabase + const isSandbox = await isCompanySandboxDemo(supabase, companyId); + let query = supabase .from("quotes") .select("id,jobs!inner(company_id)") .eq("id", quoteId) - .eq("is_demo", false) - .eq("jobs.company_id", companyId) - .single(); + .eq("jobs.company_id", companyId); + if (!isSandbox) query = query.eq("is_demo", false); + return query.single(); } async function recomputeQuoteTotal( diff --git a/src/app/api/quotes/[id]/line-items/route.test.ts b/src/app/api/quotes/[id]/line-items/route.test.ts index 8156078..8383c5a 100644 --- a/src/app/api/quotes/[id]/line-items/route.test.ts +++ b/src/app/api/quotes/[id]/line-items/route.test.ts @@ -35,6 +35,10 @@ function makeSelectBuilder(getRows: () => Row[]) { const row = getRows().find((r) => matchesFilters(r, filters)); return row ? { data: row, error: null } : { data: null, error: { message: "Row not found" } }; }, + maybeSingle: async () => { + const row = getRows().find((r) => matchesFilters(r, filters)); + return { data: row ?? null, error: null }; + }, then(resolve: (value: { data: Row[]; error: null }) => void) { resolve({ data: getRows().filter((r) => matchesFilters(r, filters)), error: null }); }, @@ -72,7 +76,7 @@ function makeUpdateBuilder(getRows: () => Row[], patch: Row) { return builder; } -type Db = { quotes: Row[]; quote_line_items: Row[] }; +type Db = { quotes: Row[]; quote_line_items: Row[]; companies: Row[] }; function createFakeSupabase(db: Db) { return { @@ -89,6 +93,9 @@ function createFakeSupabase(db: Db) { insert: (row: Row) => makeInsertBuilder(() => db.quote_line_items, row), }; } + if (table === "companies") { + return { select: () => makeSelectBuilder(() => db.companies) }; + } throw new Error(`Unexpected table in test double: ${table}`); }, }; @@ -103,6 +110,7 @@ function freshDb(): Db { return { quotes: [{ id: QUOTE_ID, is_demo: false, jobs: { company_id: COMPANY_ID } }], quote_line_items: [{ id: "item-existing", quote_id: QUOTE_ID, name: "Filter", price: 50, quantity: 1 }], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], }; } @@ -169,3 +177,51 @@ describe("POST /api/quotes/[id]/line-items", () => { expect(requireApiRoleMock).toHaveBeenCalledWith(["dispatcher", "admin"]); }); }); + +// Half-Shell review on this PR (echoing the Codex finding on GET /api/jobs): +// a sandbox tenant's is_demo=true quotes must stay mutable here, while an +// ordinary company's is_demo=true rows (load-test/live-QA traffic -- see +// scripts/load-tech-actions.mjs) must stay hidden/unfindable. +describe("POST /api/quotes/[id]/line-items - is_demo visibility", () => { + const SANDBOX_COMPANY_ID = "88888888-8888-4888-8888-888888888888"; + + beforeEach(() => { + requireApiRoleMock.mockReset(); + }); + + it("sandbox tenant: can add a line item to an is_demo=true quote", async () => { + const db: Db = { + quotes: [{ id: QUOTE_ID, is_demo: true, jobs: { company_id: SANDBOX_COMPANY_ID } }], + quote_line_items: [], + companies: [{ id: SANDBOX_COMPANY_ID, slug: "swiftdispatch-preview" }], + }; + requireApiRoleMock.mockResolvedValue({ + profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: SANDBOX_COMPANY_ID, role: "dispatcher" }, + response: null, + supabase: createFakeSupabase(db), + }); + + const response = await addLineItem({ name: "Diagnostic", price: 89, quantity: 1 }); + + expect(response.status).toBe(200); + expect(db.quote_line_items).toHaveLength(1); + }); + + it("ordinary tenant: an is_demo=true quote (load-test traffic) is not found", async () => { + const db: Db = { + quotes: [{ id: QUOTE_ID, is_demo: true, jobs: { company_id: COMPANY_ID } }], + quote_line_items: [], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], + }; + requireApiRoleMock.mockResolvedValue({ + profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: COMPANY_ID, role: "dispatcher" }, + response: null, + supabase: createFakeSupabase(db), + }); + + const response = await addLineItem({ name: "Diagnostic", price: 89, quantity: 1 }); + + expect(response.status).toBe(404); + expect(db.quote_line_items).toHaveLength(0); + }); +}); diff --git a/src/app/api/quotes/[id]/line-items/route.ts b/src/app/api/quotes/[id]/line-items/route.ts index e0f9964..73ab223 100644 --- a/src/app/api/quotes/[id]/line-items/route.ts +++ b/src/app/api/quotes/[id]/line-items/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import { requireApiRole } from "@/lib/auth"; +import { isCompanySandboxDemo } from "@/lib/demo"; import { sumLineItems } from "@/lib/quotePricing"; async function recomputeQuoteTotal( @@ -32,13 +33,14 @@ export async function POST( if (response || !profile) return response; const body = await request.json().catch(() => ({})); - const { data: quote, error: quoteError } = await supabase + const isSandbox = await isCompanySandboxDemo(supabase, profile.company_id); + let quoteQuery = supabase .from("quotes") .select("id,jobs!inner(company_id)") .eq("id", id) - .eq("is_demo", false) - .eq("jobs.company_id", profile.company_id) - .single(); + .eq("jobs.company_id", profile.company_id); + if (!isSandbox) quoteQuery = quoteQuery.eq("is_demo", false); + const { data: quote, error: quoteError } = await quoteQuery.single(); if (quoteError || !quote) { return NextResponse.json({ error: "Quote not found" }, { status: 404 }); diff --git a/src/app/api/quotes/route.test.ts b/src/app/api/quotes/route.test.ts index 55dc4dd..62edbed 100644 --- a/src/app/api/quotes/route.test.ts +++ b/src/app/api/quotes/route.test.ts @@ -4,9 +4,17 @@ * (401/403/200 semantics) is unit-tested in src/lib/__tests__/auth.test.ts; * this proves the route actually calls it with the right allowed-role set * and respects a denial before touching the database. + * + * Also covers both sides of the is_demo visibility contract (Half-Shell + * review on this PR, echoing the Codex finding on GET /api/jobs): a sandbox + * tenant's is_demo=true quotes must be found (not shadowed by a duplicate + * insert), while an ordinary company's is_demo=true rows (load-test/live-QA + * traffic -- see scripts/load-tech-actions.mjs) must stay invisible here. */ import { beforeEach, describe, expect, it, vi } from "vitest"; +type Row = Record; + const requireApiRoleMock = vi.fn(); vi.mock("@/lib/auth", () => ({ @@ -14,38 +22,77 @@ vi.mock("@/lib/auth", () => ({ })); const COMPANY_ID = "11111111-1111-4111-8111-111111111111"; +const SANDBOX_COMPANY_ID = "33333333-3333-4333-8333-333333333333"; const JOB_ID = "22222222-2222-4222-8222-222222222222"; +const EXISTING_QUOTE_ID = "77777777-7777-4777-8777-777777777777"; const DISPATCHER_ID = "44444444-4444-4444-8444-444444444444"; function forbiddenResponse() { return new Response(JSON.stringify({ error: "Forbidden" }), { status: 403 }); } -function allowedDispatcherContext() { +function matchesFilters(row: Row, filters: [string, unknown][]) { + return filters.every(([column, value]) => row[column] === value); +} + +function makeQuotesSelectBuilder(getRows: () => Row[]) { + const filters: [string, unknown][] = []; + const builder = { + eq(column: string, value: unknown) { + filters.push([column, value]); + return builder; + }, + order() { + return builder; + }, + limit() { + return builder; + }, + maybeSingle: async () => { + const row = getRows().find((r) => matchesFilters(r, filters)); + return { data: row ?? null, error: null }; + }, + }; + return builder; +} + +type Db = { quotes: Row[]; companies: Row[] }; + +function createFakeSupabase(db: Db) { return { - profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: COMPANY_ID, role: "dispatcher" }, - response: null, - supabase: { - from: (table: string) => { - if (table === "jobs") { - return { select: () => ({ eq: () => ({ eq: () => ({ single: async () => ({ data: { id: JOB_ID }, error: null }) }) }) }) }; - } - if (table === "quotes") { - return { - select: () => ({ - eq: () => ({ - eq: () => ({ order: () => ({ limit: () => ({ maybeSingle: async () => ({ data: null, error: null }) }) }) }), - }), + from(table: string) { + if (table === "jobs") { + return { select: () => ({ eq: () => ({ eq: () => ({ single: async () => ({ data: { id: JOB_ID }, error: null }) }) }) }) }; + } + if (table === "companies") { + return { + select: () => ({ + eq: (column: string, value: unknown) => ({ + maybeSingle: async () => ({ data: db.companies.find((c) => c[column] === value) ?? null, error: null }), }), - insert: () => ({ select: () => ({ single: async () => ({ data: { id: "quote-1" }, error: null }) }) }), - }; - } - throw new Error(`Unexpected table in test double: ${table}`); - }, + }), + }; + } + if (table === "quotes") { + return { + select: () => makeQuotesSelectBuilder(() => db.quotes), + insert: () => ({ select: () => ({ single: async () => ({ data: { id: "quote-new" }, error: null }) }) }), + update: () => ({ eq: () => ({ select: () => ({ single: async () => ({ data: { id: EXISTING_QUOTE_ID }, error: null }) }) }) }), + }; + } + throw new Error(`Unexpected table in test double: ${table}`); }, }; } +function requireApiRoleAs(companyId: string, db: Db) { + requireApiRoleMock.mockResolvedValue({ + profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: companyId, role: "dispatcher" }, + response: null, + supabase: createFakeSupabase(db), + }); +} + async function postQuote(body: Record) { const { POST } = await import("./route"); return POST( @@ -71,7 +118,10 @@ describe("POST /api/quotes - authorization", () => { }); it("allows a dispatcher to build a quote", async () => { - requireApiRoleMock.mockResolvedValue(allowedDispatcherContext()); + requireApiRoleAs(COMPANY_ID, { + quotes: [], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], + }); const response = await postQuote({ job_id: JOB_ID }); @@ -79,3 +129,35 @@ describe("POST /api/quotes - authorization", () => { expect(requireApiRoleMock).toHaveBeenCalledWith(["dispatcher", "admin"]); }); }); + +describe("POST /api/quotes - is_demo visibility", () => { + beforeEach(() => { + requireApiRoleMock.mockReset(); + }); + + it("sandbox tenant: finds an existing is_demo=true quote instead of creating a duplicate", async () => { + requireApiRoleAs(SANDBOX_COMPANY_ID, { + quotes: [{ id: EXISTING_QUOTE_ID, job_id: JOB_ID, is_demo: true, total: 959 }], + companies: [{ id: SANDBOX_COMPANY_ID, slug: "swiftdispatch-preview" }], + }); + + const response = await postQuote({ job_id: JOB_ID }); + const body = (await response.json()) as { quote_id: string }; + + expect(response.status).toBe(200); + expect(body.quote_id).toBe(EXISTING_QUOTE_ID); + }); + + it("ordinary tenant: an is_demo=true row (load-test traffic) stays hidden, so a fresh quote is created instead", async () => { + requireApiRoleAs(COMPANY_ID, { + quotes: [{ id: EXISTING_QUOTE_ID, job_id: JOB_ID, is_demo: true, total: 959 }], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], + }); + + const response = await postQuote({ job_id: JOB_ID }); + const body = (await response.json()) as { quote_id: string }; + + expect(response.status).toBe(200); + expect(body.quote_id).not.toBe(EXISTING_QUOTE_ID); + }); +}); diff --git a/src/app/api/quotes/route.ts b/src/app/api/quotes/route.ts index da0cc1d..26fa975 100644 --- a/src/app/api/quotes/route.ts +++ b/src/app/api/quotes/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import { requireApiRole } from "@/lib/auth"; +import { isCompanySandboxDemo } from "@/lib/demo"; type LineItemInput = { name: string; @@ -23,11 +24,13 @@ export async function POST(request: Request) { return NextResponse.json({ error: "Job not found" }, { status: 404 }); } - const { data: existingQuote } = await supabase + const isSandbox = await isCompanySandboxDemo(supabase, profile.company_id); + let existingQuoteQuery = supabase .from("quotes") .select("id,total,status,created_at,quote_sent_at,accepted_at,rejected_at,quote_line_items(id,quote_id,name,price,quantity)") - .eq("job_id", body.job_id) - .eq("is_demo", false) + .eq("job_id", body.job_id); + if (!isSandbox) existingQuoteQuery = existingQuoteQuery.eq("is_demo", false); + const { data: existingQuote } = await existingQuoteQuery .order("created_at", { ascending: false }) .limit(1) .maybeSingle(); diff --git a/src/app/api/send-sms/route.test.ts b/src/app/api/send-sms/route.test.ts index ce9d669..5e89341 100644 --- a/src/app/api/send-sms/route.test.ts +++ b/src/app/api/send-sms/route.test.ts @@ -45,6 +45,10 @@ function makeSelectBuilder(getRows: () => Row[]) { const row = getRows().find((r) => matchesFilters(r, filters)); return row ? { data: row, error: null } : { data: null, error: { message: "Row not found" } }; }, + maybeSingle: async () => { + const row = getRows().find((r) => matchesFilters(r, filters)); + return { data: row ?? null, error: null }; + }, }; return builder; } @@ -65,7 +69,7 @@ function makeUpdateBuilder(getRows: () => Row[], patch: Row) { return builder; } -type Db = { quotes: Row[] }; +type Db = { quotes: Row[]; companies: Row[] }; function createFakeSupabase(db: Db) { return { @@ -76,6 +80,9 @@ function createFakeSupabase(db: Db) { update: (patch: Row) => makeUpdateBuilder(() => db.quotes, patch), }; } + if (table === "companies") { + return { select: () => makeSelectBuilder(() => db.companies) }; + } throw new Error(`Unexpected table in test double: ${table}`); }, }; @@ -97,6 +104,7 @@ function freshDb(): Db { jobs: { id: JOB_ID, phone: "+15550000002", company_id: COMPANY_ID, sms_consent_type: "intake_form" }, }, ], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], }; } @@ -170,3 +178,57 @@ describe("POST /api/send-sms", () => { expect(db.quotes[0].status).toBe("sent"); }); }); + +// Half-Shell review on this PR (echoing the Codex finding on GET /api/jobs): +// a sandbox tenant's is_demo=true quotes must stay sendable here, while an +// ordinary company's is_demo=true rows (load-test/live-QA traffic -- see +// scripts/load-tech-actions.mjs) must stay hidden/unfindable. +describe("POST /api/send-sms - is_demo visibility", () => { + const SANDBOX_COMPANY_ID = "22222222-2222-4222-8222-222222222222"; + + beforeEach(() => { + requireApiRoleMock.mockReset(); + enqueueSmsMock.mockReset(); + enqueueSmsMock.mockResolvedValue(undefined); + }); + + it("sandbox tenant: can send an is_demo=true quote", async () => { + const db: Db = { + quotes: [ + { + id: QUOTE_ID, + is_demo: true, + status: "draft", + jobs: { id: JOB_ID, phone: "+15550000002", company_id: SANDBOX_COMPANY_ID, sms_consent_type: "intake_form" }, + }, + ], + companies: [{ id: SANDBOX_COMPANY_ID, slug: "swiftdispatch-preview" }], + }; + requireApiRoleAs(db, SANDBOX_COMPANY_ID); + + const response = await sendSms({ quote_id: QUOTE_ID }); + + expect(response.status).toBe(200); + expect(db.quotes[0].status).toBe("sent"); + }); + + it("ordinary tenant: an is_demo=true quote (load-test traffic) is not found for sending", async () => { + const db: Db = { + quotes: [ + { + id: QUOTE_ID, + is_demo: true, + status: "draft", + jobs: { id: JOB_ID, phone: "+15550000002", company_id: COMPANY_ID, sms_consent_type: "intake_form" }, + }, + ], + companies: [{ id: COMPANY_ID, slug: "acme-hvac" }], + }; + requireApiRoleAs(db, COMPANY_ID); + + const response = await sendSms({ quote_id: QUOTE_ID }); + + expect(response.status).toBe(404); + expect(enqueueSmsMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/api/send-sms/route.ts b/src/app/api/send-sms/route.ts index bb28502..63ea358 100644 --- a/src/app/api/send-sms/route.ts +++ b/src/app/api/send-sms/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import { requireApiRole } from "@/lib/auth"; +import { isCompanySandboxDemo } from "@/lib/demo"; import { generateQuoteApprovalToken } from "@/lib/quoteTokens"; import { assertSmsConsent } from "@/lib/smsGate"; import { firstSms } from "@/lib/twilio"; @@ -21,13 +22,14 @@ export async function POST(request: Request) { return NextResponse.json({ error: 'quote_id is required' }, { status: 400 }); } - const { data, error } = await supabase + const isSandbox = await isCompanySandboxDemo(supabase, profile.company_id); + let quoteQuery = supabase .from("quotes") .select("id, jobs!inner(id,phone,company_id,sms_consent_type)") .eq("id", quote_id) - .eq("is_demo", false) - .eq("jobs.company_id", profile.company_id) - .single(); + .eq("jobs.company_id", profile.company_id); + if (!isSandbox) quoteQuery = quoteQuery.eq("is_demo", false); + const { data, error } = await quoteQuery.single(); if (error || !data || !data.jobs) { return NextResponse.json({ error: "Quote not found" }, { status: 404 }); diff --git a/src/components/KanbanBoard.tsx b/src/components/KanbanBoard.tsx index 83671b5..c4b97b1 100644 --- a/src/components/KanbanBoard.tsx +++ b/src/components/KanbanBoard.tsx @@ -45,9 +45,10 @@ type Props = { readOnly?: boolean; smsFailedJobIds?: string[]; technicians: Technician[]; + isSandboxDemo?: boolean; }; -export default function KanbanBoard({ companyId, initialJobs, readOnly = false, smsFailedJobIds = [], technicians }: Props) { +export default function KanbanBoard({ companyId, initialJobs, readOnly = false, smsFailedJobIds = [], technicians, isSandboxDemo = false }: Props) { const [jobs, setJobs] = useState( initialJobs.map((job) => ({ ...job, status: normalizeStatus(job.status) })), ); @@ -83,12 +84,12 @@ export default function KanbanBoard({ companyId, initialJobs, readOnly = false, const supabase = createSupabaseBrowserClient(); async function refetchAll() { - const { data } = await supabase + let query = supabase .from("jobs") .select("*, technicians!jobs_technician_id_fkey(id,name,phone)") - .eq("company_id", companyId) - .eq("is_demo", false) - .order("created_at", { ascending: false }); + .eq("company_id", companyId); + if (!isSandboxDemo) query = query.eq("is_demo", false); + const { data } = await query.order("created_at", { ascending: false }); if (data) { startTransition(() => { setJobs((data as JobWithTechnician[]).map((job) => ({ ...job, status: normalizeStatus(job.status) }))); @@ -146,7 +147,7 @@ export default function KanbanBoard({ companyId, initialJobs, readOnly = false, void supabase.removeChannel(channel); if (moveErrorTimer.current) clearTimeout(moveErrorTimer.current); }; - }, [companyId, readOnly]); + }, [companyId, readOnly, isSandboxDemo]); const activeJobs = useMemo( () => jobs.filter((job) => statuses.includes(normalizeStatus(job.status))), diff --git a/src/lib/demo.ts b/src/lib/demo.ts index b32c43a..be081cf 100644 --- a/src/lib/demo.ts +++ b/src/lib/demo.ts @@ -50,3 +50,22 @@ export function isSandboxDemoCompany(company: CompanyDemoShape | null | undefine export function isPrivateSandboxDemoCompany(company: CompanyDemoShape | null | undefined): boolean { return isSandboxDemoCompany(company) && company?.slug !== DEMO_COMPANY_SLUG; } + +/** + * Server-side helper for read paths that otherwise filter out `is_demo` + * rows (quote preview/build, admin stats, the jobs list). A sandbox tenant's + * jobs/quotes are ALL is_demo=true, so that filter must be skipped there or + * every read comes back empty -- but load-testing/live-QA scripts also seed + * is_demo=true rows into ordinary (non-sandbox) companies specifically to + * keep them out of real operator views, so the filter must stay everywhere + * else. One extra `companies` lookup per request; callers that already have + * the company row on hand should call isSandboxDemoCompany() directly + * instead of paying for a second query. + */ +export async function isCompanySandboxDemo( + supabase: Awaited>, + companyId: string, +): Promise { + const { data } = await supabase.from("companies").select("slug").eq("id", companyId).maybeSingle(); + return isSandboxDemoCompany(data); +} diff --git a/src/lib/resetDemoTenant.ts b/src/lib/resetDemoTenant.ts index d429fab..cc9e33c 100644 --- a/src/lib/resetDemoTenant.ts +++ b/src/lib/resetDemoTenant.ts @@ -105,6 +105,11 @@ async function resetOneCompany(admin: AdminClient, companyId: string): Promise<{ // Re-seed fresh jobs const now = Date.now() let seeded = 0 + const TERMINAL_STATUSES = ['completed', 'cancelled', 'no_access'] + // Oldest active job per technician wins -- matches the (technician_id, status) + // semantics PATCH /api/jobs/[id] uses for real assignments, so the tech rail's + // "on job" state agrees with what the kanban cards show for this tech. + const techActiveJobs = new Map() for (const demoJob of demoJobs) { const createdAt = new Date(now - demoJob.ageMinutes * 60_000) @@ -151,6 +156,13 @@ async function resetOneCompany(admin: AdminClient, companyId: string): Promise<{ const { data: job } = await admin.from('jobs').insert(jobPayload).select('id').single() if (!job) continue + if (isAssigned && techId && !TERMINAL_STATUSES.includes(demoJob.status)) { + const existing = techActiveJobs.get(techId) + if (!existing || createdAt.getTime() < existing.createdAt) { + techActiveJobs.set(techId, { jobId: job.id, createdAt: createdAt.getTime() }) + } + } + // Status event history const events: Array<{ from: string | null; to: string; offsetMs: number; role: string }> = [ { from: null, to: 'new', offsetMs: 0, role: demoJob.source === 'intake' ? 'customer' : 'dispatcher' }, @@ -215,22 +227,10 @@ async function resetOneCompany(admin: AdminClient, companyId: string): Promise<{ seeded++ } - // Set current_job_id on Mia Torres (demo tech 0) to her most active job - const miaId = techIds[0] - if (miaId) { - const { data: miaJob } = await admin - .from('jobs') - .select('id') - .eq('company_id', companyId) - .eq('technician_id', miaId) - .not('status', 'in', '("completed","cancelled","no_access")') - .order('created_at', { ascending: true }) - .limit(1) - .maybeSingle() - - if (miaJob) { - await admin.from('technicians').update({ current_job_id: miaJob.id }).eq('id', miaId) - } + // Reflect each technician's active job in their availability, so the tech + // rail (available/on job) agrees with what the kanban cards show them doing. + for (const [techId, { jobId }] of techActiveJobs) { + await admin.from('technicians').update({ availability_status: 'on_job', current_job_id: jobId }).eq('id', techId) } return { jobsSeeded: seeded }