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
340 changes: 195 additions & 145 deletions docs/demo-experience-design.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/app/api/jobs/[id]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ describe("PATCH /api/jobs/[id] - dispatcher assignment", () => {
status: "en_route",
technician_id: TECH_ID,
created_at: "2024-01-01T00:00:00.000Z",
is_demo: false,
});
db.technicians[0].availability_status = "on_job";
db.technicians[0].current_job_id = JOB_ID;
Expand Down
36 changes: 6 additions & 30 deletions src/app/api/jobs/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { requireApiRole } from '@/lib/auth'
import { createSupabaseAdminClient } from '@/lib/supabase/admin'
import { assertValidTransition, type JobStatus } from '@/lib/stateMachine'
import { queueCustomerStatusSms, queueTechnicianAssignmentSms } from '@/lib/jobNotifications'
import { reconcileTechnicianAfterTerminalJob, TERMINAL_STATUSES } from '@/lib/technicianReconciliation'
import type { SmsConsentType } from '@/lib/smsGate'

const PatchJobSchema = z.object({
Expand All @@ -13,10 +14,6 @@ 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 @@ -261,32 +258,11 @@ export async function PATCH(
}

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)
await reconcileTechnicianAfterTerminalJob(supabase, {
technicianId: currentJob.technician_id as string,
companyId: profile.company_id,
completedJobId: id,
})
}

// Write status event if status changed. status_events has no INSERT RLS
Expand Down
79 changes: 73 additions & 6 deletions src/app/api/quotes/[id]/accept/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,61 @@ vi.mock("@/lib/jobNotifications", () => ({
queueCustomerInvoiceSms: queueCustomerInvoiceSmsMock,
}));

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[]) {
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: row, error: null } : { data: null, error: { message: "Row not found" } };
},
maybeSingle: async () => {
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] ?? null, error: null };
},
then(resolve: (value: { data: Row[]; error: null }) => void) {
resolve({ data: getRows().filter((r) => matchesFilters(r, filters)), error: null });
},
Expand All @@ -60,7 +100,7 @@ function makeSelectBuilder(getRows: () => Row[]) {
}

function makeUpdateBuilder(getRows: () => 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 @@ -69,7 +109,7 @@ function makeUpdateBuilder(getRows: () => Row[], patch: Row) {
}
const builder = {
eq(column: string, value: unknown) {
filters.push([column, value]);
filters.push({ type: "eq", column, value });
return builder;
},
then(resolve: (value: { data: null; error: null }) => void) {
Expand All @@ -85,6 +125,7 @@ type Db = {
jobs: Row[];
quote_line_items: Row[];
technicians: Row[];
companies: Row[];
};

function createFakeSupabase(db: Db) {
Expand Down Expand Up @@ -117,6 +158,11 @@ function createFakeSupabase(db: Db) {
insert: async () => ({ error: null }),
};
}
if (table === "companies") {
return {
select: () => makeSelectBuilder(() => db.companies),
};
}
throw new Error(`Unexpected table in test double: ${table}`);
},
};
Expand Down Expand Up @@ -148,6 +194,7 @@ function freshDb(): Db {
],
quote_line_items: [{ quote_id: QUOTE_ID, price: 250, quantity: 2 }],
technicians: [{ id: TECH_ID, company_id: COMPANY_ID, availability_status: "on_job", current_job_id: JOB_ID }],
companies: [{ id: COMPANY_ID, slug: "acme-hvac" }],
};
}

Expand Down Expand Up @@ -202,6 +249,26 @@ describe("PATCH /api/quotes/[id]/accept", () => {
expect(requireApiRoleMock).not.toHaveBeenCalled();
});

it("promotes another active job instead of releasing the technician, if one remains (issue #75)", async () => {
const OTHER_JOB_ID = "77777777-7777-4777-8777-777777777777";
db.jobs.push({
id: OTHER_JOB_ID,
status: "en_route",
company_id: COMPANY_ID,
technician_id: TECH_ID,
created_at: "2024-01-01T00:00:00.000Z",
customer_name: "Carmichael Home",
is_demo: false,
});

const token = generateQuoteApprovalToken(QUOTE_ID);
const response = await acceptQuote({ token });

expect(response.status).toBe(200);
expect(db.jobs[0].status).toBe("completed");
expect(db.technicians[0]).toMatchObject({ availability_status: "on_job", current_job_id: OTHER_JOB_ID });
});

it("accepts via an authenticated dispatcher (no token)", async () => {
const response = await acceptQuote({});

Expand Down
10 changes: 6 additions & 4 deletions src/app/api/quotes/[id]/accept/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { verifyQuoteApprovalToken } from '@/lib/quoteTokens'
import { resolveEffectiveTotal, sumLineItems } from '@/lib/quotePricing'
import { requireApiRole } from '@/lib/auth'
import { queueCustomerInvoiceSms, queueCustomerStatusSms } from '@/lib/jobNotifications'
import { reconcileTechnicianAfterTerminalJob } from '@/lib/technicianReconciliation'
import type { SmsConsentType } from '@/lib/smsGate'

// Accepts PATCH (authenticated dispatcher) or token-gated customer accept
Expand Down Expand Up @@ -91,10 +92,11 @@ export async function PATCH(
})

if (job.technician_id) {
await supabase
.from('technicians')
.update({ availability_status: 'available', current_job_id: null })
.eq('id', job.technician_id)
await reconcileTechnicianAfterTerminalJob(supabase, {
technicianId: job.technician_id,
companyId: job.company_id,
completedJobId: job.id,
})
}

const companyData = Array.isArray(job.companies) ? job.companies[0] : job.companies
Expand Down
Loading
Loading