From 070dc5cba897d9aa87c765e4809cb8e9b69c3c21 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 21 Sep 2026 01:54:17 +0000 Subject: [PATCH 1/6] #75 Phase 2/3: analytics sandbox scoping, terminal technician release, reset error UX Three independent fixes from the Half-Shell Demo Tenant Audit (issue #75): - src/app/(app)/analytics/page.tsx never filtered is_demo at all, on any of its six jobs/quotes queries -- same bug class as PR #74 fixed elsewhere, just missed there. Applied the same isCompanySandboxDemo() scoping: an ordinary company's load-test rows (scripts/load-tech-actions.mjs etc.) now stay out of response-time/completion/acceptance-rate/revenue metrics, while a sandbox tenant's rows (which are the metrics) still count. - PATCH /api/jobs/[id] updated technician availability_status/ current_job_id on assignment, reassignment, and unassignment, but never on a status-only transition straight to a terminal status. Both the real technician "Complete" button and the dispatcher kanban board's drag-move (moveJobStatus) send {status} alone with no technician_id, so neither path ever released the technician -- they stayed on_job against a finished job indefinitely. Quote acceptance already got this right (/api/quotes/[id]/accept releases the technician on its completed transition); this applies the same release for completed/cancelled/ no_access reached through this route instead. Pre-existing production bug the demo tenant exposed, not demo-specific. - ResetDemoButton swallowed every failure (non-2xx or network error) silently -- the button just returned to normal with no feedback, so a failed destructive reset looked like nothing happened. Now shows the server's error message (or a fallback) for 6 seconds. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw --- src/app/(app)/analytics/page.tsx | 36 ++++++++++++++++---- src/app/api/jobs/[id]/route.test.ts | 53 +++++++++++++++++++++++++++++ src/app/api/jobs/[id]/route.ts | 21 ++++++++++++ src/components/ResetDemoButton.tsx | 41 ++++++++++++++++------ 4 files changed, 133 insertions(+), 18 deletions(-) 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..6188193 100644 --- a/src/app/api/jobs/[id]/route.test.ts +++ b/src/app/api/jobs/[id]/route.test.ts @@ -435,6 +435,59 @@ 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" }); + }); }); 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..4379821 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', @@ -177,6 +181,23 @@ export async function PATCH( .update({ availability_status: 'available', current_job_id: null }) .eq('id', currentJob.technician_id) } + } else if ( + currentJob.technician_id && + typeof patch.status === 'string' && + TERMINAL_STATUSES.includes(patch.status as JobStatus) + ) { + // 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, 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. + await supabase + .from('technicians') + .update({ availability_status: 'available', current_job_id: null }) + .eq('id', currentJob.technician_id) } if (Object.keys(patch).length === 0) { 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}} + ); } From 17b876ad445957e7ab9f2efa00ae9c550721efd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 21 Sep 2026 01:57:08 +0000 Subject: [PATCH 2/6] #75 P1/P2: gate TechPhoneModal's Complete button, add real link fidelity Donatello's P1 finding: TechPhoneModal's "Complete" button only checked the generic state-machine transition (canTransition(status, 'completed')), unlike the real technician UI (TechJobActionsClient), which additionally requires hasAcceptedQuote. That let a demo tech complete a job with no quote at all -- a state the real product cannot reach. Fixed by fetching the same accepted-quote check tech/page.tsx already does server-side and gating the button on it too. Michelangelo's P2 fidelity gaps, fixed: address now opens Google Maps and phone is a tel: link, both copied exactly from the real tech/job/[id] page's markup, instead of being styled as actionable text that did nothing. Left alone, flagging separately: the "Build Quote" button still directly PATCHes job status to quote_pending. Investigation found this is a deeper behavioral gap than a simple fix -- in the real product a technician's Build Quote link is read-only (it opens /tech/job/[jobId], which has no mutation UI at all); the in_progress -> quote_pending transition and the quote itself are built by the DISPATCHER via QuoteBuilder on the job detail page, not by the technician. Reusing the real component here would need either a technician-session impersonation adapter or a real quote-builder embedded in the phone mockup -- both larger, product-shape decisions the audit itself frames as open questions rather than a single correct fix, so this is called out to the user instead of decided unilaterally. "Sign out" is left inert for the same reason: it borrows the dispatcher's own session, so making it functional would sign the dispatcher out of their real account mid-demo. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw --- src/components/TechPhoneModal.tsx | 33 +++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/components/TechPhoneModal.tsx b/src/components/TechPhoneModal.tsx index d9d4dfa..90b1dc0 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}

@@ -250,8 +271,8 @@ export default function TechPhoneModal({ demoTechId, demoTechName, companyId }:
{/* Right: reset */}
- - Admin settings - + {profile.role === "admin" && ( + + Admin settings + + )}
diff --git a/src/components/TechPhoneModal.tsx b/src/components/TechPhoneModal.tsx index 90b1dc0..9969538 100644 --- a/src/components/TechPhoneModal.tsx +++ b/src/components/TechPhoneModal.tsx @@ -263,11 +263,11 @@ export default function TechPhoneModal({ demoTechId, demoTechName, companyId }: