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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions scripts/seed-demo-tenant.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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" });
Expand All @@ -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;
}

Expand Down
6 changes: 4 additions & 2 deletions src/app/(app)/admin/page.tsx
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -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"),
]);
Expand All @@ -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;
Expand Down
14 changes: 11 additions & 3 deletions src/app/(app)/dispatch/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -116,7 +124,7 @@ export default async function DispatchPage({ searchParams }: { searchParams: Pro
</div>

<div className="grid gap-4 xl:grid-cols-[1fr_260px]">
<KanbanBoard companyId={companyId} initialJobs={allJobs} readOnly={impersonating} smsFailedJobIds={smsFailedJobIds} technicians={techList} />
<KanbanBoard companyId={companyId} initialJobs={allJobs} readOnly={impersonating} smsFailedJobIds={smsFailedJobIds} technicians={techList} isSandboxDemo={isSandboxDemo} />
{!impersonating && <TechRail companyId={companyId} initialTechnicians={techList} />}
</div>

Expand Down
10 changes: 6 additions & 4 deletions src/app/(app)/quote/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions src/app/api/jobs/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});
8 changes: 5 additions & 3 deletions src/app/api/jobs/route.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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")')
Comment on lines 30 to 31

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the demo filter for non-sandbox tenants

When this endpoint is used by a non-sandbox company that has run the load harness, removing this predicate exposes its synthetic jobs as operational work. This is a supported scenario rather than a hypothetical one: scripts/load-tech-actions.mjs and scripts/load-multi-tech-actions.mjs insert 75–100 assigned jobs with is_demo: true into configurable company slugs, and the former explicitly says the flag reduces operational noise. The same unconditional removal also contaminates the admin job metrics. Include demo rows only for companies recognized by isSandboxDemoCompany, while retaining is_demo = false elsewhere.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed — load-tech-actions.mjs/load-multi-tech-actions.mjs/seed-live-qa.mjs do insert is_demo=true into non-sandbox company slugs specifically to keep that traffic out of operator views. Fixed in 6dcf5a3: added isCompanySandboxDemo() and made the filter conditional everywhere this PR touched it — applied for ordinary companies (unchanged), skipped only for SANDBOX_DEMO_SLUGS tenants. Thanks for catching this.


Generated by Claude Code


Generated by Claude Code

.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 })
Expand Down
56 changes: 55 additions & 1 deletion src/app/api/quotes/[id]/line-items/[itemId]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
},
Expand Down Expand Up @@ -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 {
Expand All @@ -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}`);
},
};
Expand All @@ -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" }],
};
}

Expand Down Expand Up @@ -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);
});
});
10 changes: 6 additions & 4 deletions src/app/api/quotes/[id]/line-items/[itemId]/route.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { NextResponse } from "next/server";
import { requireApiRole } from "@/lib/auth";
import { isCompanySandboxDemo } from "@/lib/demo";
import { sumLineItems } from "@/lib/quotePricing";

async function assertQuoteOwnership(
supabase: Awaited<ReturnType<typeof requireApiRole>>["supabase"],
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(
Expand Down
58 changes: 57 additions & 1 deletion src/app/api/quotes/[id]/line-items/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
},
Expand Down Expand Up @@ -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 {
Expand All @@ -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}`);
},
};
Expand All @@ -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" }],
};
}

Expand Down Expand Up @@ -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);
});
});
Loading
Loading