diff --git a/src/app/(app)/analytics/page.tsx b/src/app/(app)/analytics/page.tsx index 5e9dd90..d35a752 100644 --- a/src/app/(app)/analytics/page.tsx +++ b/src/app/(app)/analytics/page.tsx @@ -1,13 +1,22 @@ +import { redirect } from "next/navigation"; import { getCurrentProfile } from "@/lib/auth"; +import { isCompanySandboxDemo } from "@/lib/demo"; import { createSupabaseServerClient } from "@/lib/supabase/server"; export default async function AnalyticsPage() { const profile = await getCurrentProfile(); + if (!profile.company_id) redirect("/login"); const supabase = await createSupabaseServerClient(); const companyId = profile.company_id; const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(); + // A sandbox tenant's rows are all is_demo=true (that data IS the demo); an + // ordinary company's is_demo=true rows are load-test/live-QA traffic (see + // scripts/load-tech-actions.mjs) that must stay out of these metrics. + const isSandbox = await isCompanySandboxDemo(supabase, companyId); - const { data: responseTimes } = await supabase.from("jobs").select("created_at, en_route_at").eq("company_id", companyId).not("en_route_at", "is", null).gte("created_at", thirtyDaysAgo); + let responseTimesQuery = supabase.from("jobs").select("created_at, en_route_at").eq("company_id", companyId).not("en_route_at", "is", null).gte("created_at", thirtyDaysAgo); + if (!isSandbox) responseTimesQuery = responseTimesQuery.eq("is_demo", false); + const { data: responseTimes } = await responseTimesQuery; const avgResponseMinutes = (() => { const valid = (responseTimes ?? []).filter((j) => j.en_route_at); if (!valid.length) return null; @@ -15,15 +24,22 @@ export default async function AnalyticsPage() { return Math.round(sum / valid.length); })(); - const { count: completedCount } = await supabase.from("jobs").select("*", { count: "exact", head: true }).eq("company_id", companyId).eq("status", "completed").gte("completed_at", thirtyDaysAgo); - const { data: quotesForRate } = await supabase.from("quotes").select("status, jobs!inner(company_id)").eq("jobs.company_id", companyId).gte("created_at", thirtyDaysAgo); + let completedCountQuery = supabase.from("jobs").select("*", { count: "exact", head: true }).eq("company_id", companyId).eq("status", "completed").gte("completed_at", thirtyDaysAgo); + if (!isSandbox) completedCountQuery = completedCountQuery.eq("is_demo", false); + const { count: completedCount } = await completedCountQuery; + + let quotesForRateQuery = supabase.from("quotes").select("status, jobs!inner(company_id)").eq("jobs.company_id", companyId).gte("created_at", thirtyDaysAgo); + if (!isSandbox) quotesForRateQuery = quotesForRateQuery.eq("is_demo", false); + const { data: quotesForRate } = await quotesForRateQuery; const acceptanceRate = (() => { const all = (quotesForRate ?? []).filter((q) => q.status !== "draft"); if (!all.length) return null; return Math.round((all.filter((q) => q.status === "accepted").length / all.length) * 100); })(); - const { data: durations } = await supabase.from("jobs").select("arrived_at, completed_at").eq("company_id", companyId).not("arrived_at", "is", null).not("completed_at", "is", null).gte("completed_at", thirtyDaysAgo); + let durationsQuery = supabase.from("jobs").select("arrived_at, completed_at").eq("company_id", companyId).not("arrived_at", "is", null).not("completed_at", "is", null).gte("completed_at", thirtyDaysAgo); + if (!isSandbox) durationsQuery = durationsQuery.eq("is_demo", false); + const { data: durations } = await durationsQuery; const avgDurationMinutes = (() => { const valid = (durations ?? []).filter((j) => j.arrived_at && j.completed_at); if (!valid.length) return null; @@ -31,7 +47,9 @@ export default async function AnalyticsPage() { return Math.round(sum / valid.length); })(); - const { data: revenueData } = await supabase.from("jobs").select("technician_id, quotes!inner(total_amount, total, status), technicians(name)").eq("company_id", companyId).gte("completed_at", thirtyDaysAgo); + let revenueDataQuery = supabase.from("jobs").select("technician_id, quotes!inner(total_amount, total, status), technicians(name)").eq("company_id", companyId).gte("completed_at", thirtyDaysAgo); + if (!isSandbox) revenueDataQuery = revenueDataQuery.eq("is_demo", false); + const { data: revenueData } = await revenueDataQuery; const revenueByTech: Record = {}; (revenueData ?? []).forEach((job) => { if (!job.technician_id) return; @@ -44,8 +62,12 @@ export default async function AnalyticsPage() { }); const topTechs = Object.values(revenueByTech).sort((a, b) => b.revenue - a.revenue).slice(0, 5); - const { count: totalJobs } = await supabase.from("jobs").select("*", { count: "exact", head: true }).eq("company_id", companyId).gte("created_at", thirtyDaysAgo); - const { count: noAccessCount } = await supabase.from("jobs").select("*", { count: "exact", head: true }).eq("company_id", companyId).eq("status", "no_access").gte("created_at", thirtyDaysAgo); + let totalJobsQuery = supabase.from("jobs").select("*", { count: "exact", head: true }).eq("company_id", companyId).gte("created_at", thirtyDaysAgo); + if (!isSandbox) totalJobsQuery = totalJobsQuery.eq("is_demo", false); + const { count: totalJobs } = await totalJobsQuery; + let noAccessCountQuery = supabase.from("jobs").select("*", { count: "exact", head: true }).eq("company_id", companyId).eq("status", "no_access").gte("created_at", thirtyDaysAgo); + if (!isSandbox) noAccessCountQuery = noAccessCountQuery.eq("is_demo", false); + const { count: noAccessCount } = await noAccessCountQuery; const noAccessRate = totalJobs ? Math.round(((noAccessCount ?? 0) / totalJobs) * 100) : null; const fmt = (v: number | null | undefined, suffix = "") => (v != null ? `${v}${suffix}` : "—"); diff --git a/src/app/api/jobs/[id]/route.test.ts b/src/app/api/jobs/[id]/route.test.ts index e5b50a7..4598fcd 100644 --- a/src/app/api/jobs/[id]/route.test.ts +++ b/src/app/api/jobs/[id]/route.test.ts @@ -43,15 +43,49 @@ const DISPATCHER_ID = "44444444-4444-4444-8444-444444444444"; const TECH_AUTH_USER_ID = "66666666-6666-4666-8666-666666666666"; const OTHER_TECH_AUTH_USER_ID = "77777777-7777-4777-8777-777777777777"; -function matchesFilters(row: Row, filters: [string, unknown][]) { - return filters.every(([column, value]) => row[column] === value); +type Filter = + | { type: "eq"; column: string; value: unknown } + | { type: "neq"; column: string; value: unknown } + | { type: "not_in"; column: string; values: unknown[] }; + +function parseNotInList(raw: string): unknown[] { + return raw + .replace(/^\(|\)$/g, "") + .split(",") + .map((s) => s.replace(/^"|"$/g, "")); +} + +function matchesFilters(row: Row, filters: Filter[]) { + return filters.every((f) => { + if (f.type === "eq") return row[f.column] === f.value; + if (f.type === "neq") return row[f.column] !== f.value; + return !f.values.includes(row[f.column]); + }); } function makeSelectBuilder(getRows: () => Row[], project: (row: Row) => Row) { - const filters: [string, unknown][] = []; + const filters: Filter[] = []; + let orderColumn: string | null = null; + let limitN: number | null = null; const builder = { eq(column: string, value: unknown) { - filters.push([column, value]); + filters.push({ type: "eq", column, value }); + return builder; + }, + neq(column: string, value: unknown) { + filters.push({ type: "neq", column, value }); + return builder; + }, + not(column: string, _op: string, raw: string) { + filters.push({ type: "not_in", column, values: parseNotInList(raw) }); + return builder; + }, + order(column: string) { + orderColumn = column; + return builder; + }, + limit(n: number) { + limitN = n; return builder; }, single: async () => { @@ -59,15 +93,20 @@ function makeSelectBuilder(getRows: () => Row[], project: (row: Row) => Row) { return row ? { data: project(row), error: null } : { data: null, error: { message: "Row not found" } }; }, maybeSingle: async () => { - const row = getRows().find((r) => matchesFilters(r, filters)); - return { data: row ? project(row) : null, error: null }; + let rows = getRows().filter((r) => matchesFilters(r, filters)); + if (orderColumn) { + const column = orderColumn; + rows = [...rows].sort((a, b) => String(a[column]).localeCompare(String(b[column]))); + } + if (limitN !== null) rows = rows.slice(0, limitN); + return { data: rows[0] ? project(rows[0]) : null, error: null }; }, }; return builder; } function makeUpdateBuilder(getRows: () => Row[], project: (row: Row) => Row, patch: Row) { - const filters: [string, unknown][] = []; + const filters: Filter[] = []; function applyAndFind() { const row = getRows().find((r) => matchesFilters(r, filters)); if (!row) return null; @@ -76,7 +115,7 @@ function makeUpdateBuilder(getRows: () => Row[], project: (row: Row) => Row, pat } const builder = { eq(column: string, value: unknown) { - filters.push([column, value]); + filters.push({ type: "eq", column, value }); return builder; }, select() { @@ -435,6 +474,155 @@ describe("PATCH /api/jobs/[id] - dispatcher assignment", () => { const repeatBody = (await repeat.json()) as { job: Row; error?: string }; expect(repeatBody.error).toBeUndefined(); }); + + it("releases the technician back to available when a status-only transition completes their job (issue #75)", async () => { + // The real technician "Complete" button sends {status: 'completed'} + // alone -- same shape as TECHNICIAN_ALLOWED_STATUSES enforces -- so + // the technician_id branch never runs. Before this fix, the tech + // stayed on_job against a now-finished job indefinitely. + // quote_pending -> completed is the only valid transition into + // 'completed' per VALID_TRANSITIONS. + db.jobs[0].status = "quote_pending"; + db.technicians[0].availability_status = "on_job"; + db.technicians[0].current_job_id = JOB_ID; + asTechnician(TECH_AUTH_USER_ID); + + const response = await patchJob({ status: "completed" }); + + expect(response.status).toBe(200); + expect(db.jobs[0].status).toBe("completed"); + expect(db.technicians[0].availability_status).toBe("available"); + expect(db.technicians[0].current_job_id).toBeNull(); + }); + }); + + describe("technician release on terminal status (issue #75)", () => { + it("releases the technician when a dispatcher status-only move (e.g. kanban drag) cancels the job", async () => { + // KanbanBoard's moveJobStatus sends {status} alone, same as the + // technician path above -- covers the dispatcher-driven route to the + // same bug. + db.jobs[0].technician_id = TECH_ID; + db.jobs[0].status = "assigned"; + db.technicians[0].availability_status = "on_job"; + db.technicians[0].current_job_id = JOB_ID; + + const response = await patchJob({ status: "cancelled" }); + + expect(response.status).toBe(200); + expect(db.jobs[0].status).toBe("cancelled"); + expect(db.technicians[0].availability_status).toBe("available"); + expect(db.technicians[0].current_job_id).toBeNull(); + }); + + it("does not touch a different technician's availability", async () => { + db.jobs[0].technician_id = TECH_ID; + db.jobs[0].status = "en_route"; + db.technicians[0].availability_status = "on_job"; + db.technicians[0].current_job_id = JOB_ID; + db.technicians[1].availability_status = "on_job"; + db.technicians[1].current_job_id = "some-other-job"; + + const response = await patchJob({ status: "no_access" }); + + expect(response.status).toBe(200); + expect(db.technicians[1]).toMatchObject({ availability_status: "on_job", current_job_id: "some-other-job" }); + }); + + it("promotes another active assignment instead of releasing, when the terminated job was the current pointer (Half-Shell review, PR #76)", async () => { + // Tech holds two active jobs simultaneously; current_job_id points at + // JOB_ID specifically. Terminating JOB_ID must not report the tech + // available while OTHER_JOB_ID is still open work assigned to them -- + // it should repoint current_job_id at that remaining active job. + const OTHER_JOB_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + db.jobs[0].technician_id = TECH_ID; + db.jobs[0].status = "assigned"; + db.jobs[0].created_at = "2024-01-02T00:00:00.000Z"; + db.jobs.push({ + id: OTHER_JOB_ID, + company_id: COMPANY_ID, + status: "en_route", + technician_id: TECH_ID, + created_at: "2024-01-01T00:00:00.000Z", + }); + db.technicians[0].availability_status = "on_job"; + db.technicians[0].current_job_id = JOB_ID; + + const response = await patchJob({ status: "cancelled" }); + + expect(response.status).toBe(200); + expect(db.jobs[0].status).toBe("cancelled"); + expect(db.technicians[0]).toMatchObject({ + availability_status: "on_job", + current_job_id: OTHER_JOB_ID, + }); + }); + + it("does not release a technician whose current_job_id points to a different active assignment (Codex review, PR #76)", async () => { + // The demo seed (and the real assignment API) let one technician hold + // multiple simultaneous nonterminal jobs. current_job_id tracks only + // ONE of them -- cancelling a job that isn't the one it currently + // points to must not clear that other, still-active assignment. + db.jobs[0].technician_id = TECH_ID; + db.jobs[0].status = "assigned"; + db.technicians[0].availability_status = "on_job"; + db.technicians[0].current_job_id = "some-other-active-job"; + + const response = await patchJob({ status: "cancelled" }); + + expect(response.status).toBe(200); + expect(db.jobs[0].status).toBe("cancelled"); + expect(db.technicians[0]).toMatchObject({ + availability_status: "on_job", + current_job_id: "some-other-active-job", + }); + }); + + it("does not release the technician if the job write itself is rejected (Codex review, PR #76)", async () => { + // TOCTOU: a technician's ownership changed between this route's read + // and its write (simulated the same way the existing TOCTOU test + // above does, by mutating technician_id as a side effect of the + // ownership-check read). The job update then matches zero rows and + // 403s -- the technician must not have already been released before + // that write was known to fail. + db.jobs[0].technician_id = TECH_ID; + db.jobs[0].status = "quote_pending"; + db.technicians[0].availability_status = "on_job"; + db.technicians[0].current_job_id = JOB_ID; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const racySupabase: any = createFakeSupabase(db); + const originalFrom = racySupabase.from.bind(racySupabase); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + racySupabase.from = (table: string): any => { + const real = originalFrom(table); + if (table !== "technicians") return real; + return { + ...real, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + select: (...args: unknown[]): any => { + const builder = real.select(...args); + const originalMaybeSingle = builder.maybeSingle.bind(builder); + builder.maybeSingle = async () => { + const result = await originalMaybeSingle(); + db.jobs[0].technician_id = OTHER_TECH_ID; + return result; + }; + return builder; + }, + }; + }; + + requireApiRoleMock.mockResolvedValue({ + profile: { id: TECH_AUTH_USER_ID, email: "tech@example.com", company_id: COMPANY_ID, role: "technician" }, + response: null, + supabase: racySupabase, + }); + + const response = await patchJob({ status: "completed" }); + + expect(response.status).toBe(403); + expect(db.technicians[0]).toMatchObject({ availability_status: "on_job", current_job_id: JOB_ID }); + }); }); describe("cross-tenant isolation (issue #49)", () => { diff --git a/src/app/api/jobs/[id]/route.ts b/src/app/api/jobs/[id]/route.ts index c1917a7..c5baf53 100644 --- a/src/app/api/jobs/[id]/route.ts +++ b/src/app/api/jobs/[id]/route.ts @@ -13,6 +13,10 @@ const PatchJobSchema = z.object({ cancellation_reason: z.string().optional(), }) +// Mirrors dispatch/page.tsx's own TERMINAL_STATUSES -- a job in one of these +// is no longer active work for whichever technician was on it. +const TERMINAL_STATUSES: JobStatus[] = ['completed', 'cancelled', 'no_access'] + const TIMESTAMP_COLUMNS: Partial> = { assigned: 'assigned_at', en_route: 'en_route_at', @@ -179,6 +183,30 @@ export async function PATCH( } } + // A status-only transition to a terminal status (e.g. the real technician + // "Complete" button, which sends {status: 'completed'} alone -- see + // TECHNICIAN_ALLOWED_STATUSES above) never touches the technician_id + // branch above, so without this the technician stayed on_job against a + // job that had already finished. Quote acceptance (/api/quotes/[id]/ + // accept) already releases the technician on its own completed + // transition; this mirrors that for every other path a job reaches a + // terminal status through this route. + // + // Deferred and scoped per Codex review on PR #76: + // - deferred until after the job write below succeeds, so a failed or + // ownership-rejected update (technicianOwnerId mismatch) never leaves + // the technician released against a job that's still actually theirs. + // - scoped to current_job_id = id at write time (not just at technician_id) + // because the demo seed (and the real assignment API) allow a + // technician to hold multiple simultaneous nonterminal jobs; releasing + // them unconditionally could clear a *different*, still-active + // assignment their current_job_id had since moved to. + const shouldReleaseTerminalTechnician = + !('technician_id' in parsed.data) && + !!currentJob.technician_id && + typeof patch.status === 'string' && + TERMINAL_STATUSES.includes(patch.status as JobStatus) + if (Object.keys(patch).length === 0) { // A requested status that already matches persisted state is a legitimate // no-op (e.g. a stale board re-confirming a move that already landed via @@ -232,6 +260,35 @@ export async function PATCH( : NextResponse.json({ error: 'Job not found' }, { status: 404 }) } + if (shouldReleaseTerminalTechnician) { + // The technician can hold multiple simultaneous nonterminal jobs (the + // demo seed/reset logic assumes this too). If another one is still + // active, promote it -- oldest first, the same deterministic + // convention seed-demo-tenant.mjs/resetDemoTenant.ts use -- rather + // than reporting the technician available while real work remains + // assigned to them (Half-Shell review, PR #76). + const { data: nextActiveJob } = await supabase + .from('jobs') + .select('id') + .eq('technician_id', currentJob.technician_id as string) + .eq('company_id', profile.company_id) + .not('status', 'in', '("completed","cancelled","no_access")') + .neq('id', id) + .order('created_at', { ascending: true }) + .limit(1) + .maybeSingle() + + await supabase + .from('technicians') + .update( + nextActiveJob + ? { availability_status: 'on_job', current_job_id: nextActiveJob.id } + : { availability_status: 'available', current_job_id: null }, + ) + .eq('id', currentJob.technician_id as string) + .eq('current_job_id', id) + } + // Write status event if status changed. status_events has no INSERT RLS // policy for the authenticated role (only SELECT) -- confirmed against // the live project for issue #66, so this must go through the admin diff --git a/src/components/DemoBanner.tsx b/src/components/DemoBanner.tsx index 5012538..64b847b 100644 --- a/src/components/DemoBanner.tsx +++ b/src/components/DemoBanner.tsx @@ -38,12 +38,14 @@ export default async function DemoBanner() { {/* Right: reset */}
- - Admin settings - + {profile.role === "admin" && ( + + Admin settings + + )}
diff --git a/src/components/ResetDemoButton.tsx b/src/components/ResetDemoButton.tsx index 586379e..058f715 100644 --- a/src/components/ResetDemoButton.tsx +++ b/src/components/ResetDemoButton.tsx @@ -1,31 +1,50 @@ "use client"; +import { useRef, useState } from "react"; import { useRouter } from "next/navigation"; -import { useState } from "react"; export default function ResetDemoButton() { const router = useRouter(); const [resetting, setResetting] = useState(false); + const [error, setError] = useState(""); + const errorTimer = useRef | null>(null); + + function showError(message: string) { + setError(message); + if (errorTimer.current) clearTimeout(errorTimer.current); + errorTimer.current = setTimeout(() => setError(""), 6000); + } async function handleReset() { setResetting(true); + setError(""); try { const res = await fetch("/api/demo/reset", { method: "POST" }); - if (res.ok) router.refresh(); + if (res.ok) { + router.refresh(); + } else { + const body = await res.json().catch(() => null); + showError(body?.error ?? "Reset failed. Try again."); + } + } catch { + showError("Reset failed. Check your connection and try again."); } finally { setResetting(false); } } return ( - + + + {error && {error}} + ); } diff --git a/src/components/TechPhoneModal.tsx b/src/components/TechPhoneModal.tsx index d9d4dfa..9969538 100644 --- a/src/components/TechPhoneModal.tsx +++ b/src/components/TechPhoneModal.tsx @@ -42,6 +42,7 @@ function canTransition(current: string, target: JobStatus) { export default function TechPhoneModal({ demoTechId, demoTechName, companyId }: Props) { const [open, setOpen] = useState(false); const [job, setJob] = useState(null); + const [hasAcceptedQuote, setHasAcceptedQuote] = useState(false); const [loading, setLoading] = useState(false); const [actionLoading, setActionLoading] = useState(null); const [error, setError] = useState(""); @@ -57,6 +58,21 @@ export default function TechPhoneModal({ demoTechId, demoTechName, companyId }: .limit(1) .maybeSingle(); setJob(data as ActiveJob | null); + + // Mirrors tech/page.tsx's hasAcceptedQuote check -- the real technician + // UI only allows "Mark Complete" once a quote has actually been + // accepted, not just because the state machine permits the transition. + if (data) { + const { data: quotes } = await supabase + .from("quotes") + .select("id") + .eq("job_id", (data as ActiveJob).id) + .eq("status", "accepted") + .limit(1); + setHasAcceptedQuote((quotes?.length ?? 0) > 0); + } else { + setHasAcceptedQuote(false); + } }, [demoTechId]); useEffect(() => { @@ -201,20 +217,25 @@ export default function TechPhoneModal({ demoTechId, demoTechName, companyId }:
- - +

Issue

{job.issue}

@@ -242,16 +263,16 @@ export default function TechPhoneModal({ demoTechId, demoTechName, companyId }: