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
36 changes: 29 additions & 7 deletions src/app/(app)/analytics/page.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,55 @@
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;
const sum = valid.reduce((s, j) => s + (new Date(j.en_route_at!).getTime() - new Date(j.created_at).getTime()) / 60000, 0);
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;
const sum = valid.reduce((s, j) => s + (new Date(j.completed_at!).getTime() - new Date(j.arrived_at!).getTime()) / 60000, 0);
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<string, { name: string; revenue: number }> = {};
(revenueData ?? []).forEach((job) => {
if (!job.technician_id) return;
Expand All @@ -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}` : "—");

Expand Down
204 changes: 196 additions & 8 deletions src/app/api/jobs/[id]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,31 +43,70 @@ 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 () => {
const row = getRows().find((r) => matchesFilters(r, filters));
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;
Expand All @@ -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() {
Expand Down Expand Up @@ -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)", () => {
Expand Down
57 changes: 57 additions & 0 deletions src/app/api/jobs/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<JobStatus, string>> = {
assigned: 'assigned_at',
en_route: 'en_route_at',
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading