diff --git a/docs/demo-experience-design.md b/docs/demo-experience-design.md index 7f01684..f758409 100644 --- a/docs/demo-experience-design.md +++ b/docs/demo-experience-design.md @@ -1,145 +1,195 @@ -# Live Demo Experience — Design Plan - -## Problem - -The current live demo (`demo@swiftdispatch.app / demo`) only drops prospects into the dispatcher view. The tech portal (`/tech`) runs a completely separate auth flow (`/tech/login`) with its own session, so there is no way to switch between personas without logging out and logging in again with different credentials. Prospects never see the admin or analytics pages unless they find the nav links. The demo experience therefore only demonstrates one-third of the product. - -## Goal - -A prospect who lands on the live sandbox should be able to experience all three personas — dispatcher, technician, and admin — in one continuous session without re-authentication, friction, or any "please log in as a different user" interruptions. - ---- - -## Personas & pages - -| Persona | Real URL | Auth requirement | -|---|---|---| -| Dispatcher | `/dispatch` | Supabase session, role `admin` or `dispatcher` | -| Admin | `/admin`, `/analytics`, `/admin/technicians`, `/admin/templates` | Supabase session, role `admin` | -| Technician | `/tech` | Separate Supabase session, role `technician` | - -The tech portal is the hard case: it uses an independent auth guard (`redirect('/tech/login')`) and renders a mobile-optimised layout. Solving it without a second login is the core design problem. - ---- - -## Proposed solution: Demo persona switcher + tech preview route - -### 1. Demo detection - -Identify the demo session by checking `company.slug === 'demo'` (or a dedicated `is_demo` boolean on the company row). All demo-specific UI gates behind this check so it has zero effect on real tenants. - -### 2. Persistent demo banner - -A fixed bar pinned to the top of every `(app)` layout page when the session is detected as demo. It sits above the existing nav. - -``` -┌────────────────────────────────────────────────────────────────────┐ -│ DEMO SANDBOX · Viewing as Dispatcher [Tech view →] │ -│ [Analytics] [Admin] │ -└────────────────────────────────────────────────────────────────────┘ -``` - -- Eyebrow label shows which persona is active -- One-click links to `/dispatch`, `/demo/tech`, `/analytics`, `/admin` -- Resets demo data button (calls existing `resetDemoTenant` logic) -- Small, unobtrusive — maybe 32px tall, navy background, mono font - -### 3. New route: `/demo/tech` - -A new page inside the `(app)` route group that: -- Requires a normal dispatcher/admin session (no tech re-auth) -- Reads one of the demo technicians' current job from the database (e.g., whichever tech has `current_job_id` set) -- Renders the **exact same JSX** as `/tech/page.tsx` but without the `redirect('/tech/login')` guard -- Wraps the content in an iPhone-style viewport frame on desktop (so it's obvious this is a mobile-first view) — the same frame idea as the `DemoPreview` marketing mockup, but real and interactive - -The page header should say: **"Tech view — Jason K."** with a note that this is the mobile experience dispatchers' field techs see on their phones. - -Because it uses the same real data (live jobs, real status transitions), the prospect can: -- See Jason K.'s current active job -- Tap "Mark Arrived" and watch the dispatch board update in real time (Supabase realtime) -- See the status change reflected in the `/dispatch` kanban if they open it in another tab - -This is the demo's killer moment: show the realtime feedback loop between dispatcher and tech. - -### 4. Admin & analytics - -These already work for the demo account (role is `admin`). The banner just makes them discoverable. Add a brief "Demo company" callout on the admin page when in demo mode so prospects understand this is their company's data. - ---- - -## Tech view page spec - -**Route:** `/app/(app)/demo/tech/page.tsx` - -**Auth:** `getCurrentProfile()` (dispatcher session). If not demo company, redirect to `/dispatch`. - -**Data fetch:** -```ts -// Pick the first demo tech with an active job, fallback to any tech -const tech = await supabase - .from('technicians') - .select('id, name, current_job_id') - .eq('company_id', profile.company_id) - .not('current_job_id', 'is', null) - .limit(1) - .maybeSingle() -``` - -**Rendering:** -- Desktop: center a `max-w-[390px]` container inside a phone-chrome frame (same rounded-[2.5rem] border-8 border-slate-800 style from the marketing mockup). Add a label above: "Field technician view · Jason K. · iPhone" -- Mobile: render without the phone frame (the actual screen IS a phone) -- Reuse the existing tech page JSX (extract to a shared `TechJobView` server component that both `/tech/page.tsx` and `/demo/tech/page.tsx` consume) - -**Interactivity:** The `TechJobActionsClient` buttons work as-is — they POST to `/api/jobs/[id]` which only checks `company_id`, not tech auth. So status transitions work live in the demo. - ---- - -## Demo banner component spec - -**File:** `src/components/DemoBanner.tsx` (server component, reads profile) - -**Placement:** Top of `src/app/(app)/layout.tsx` (the shared app shell), conditionally rendered: - -```tsx -{profile.company?.slug === 'demo' && } -``` - -**Links:** -- Dispatcher → `/dispatch` -- Tech view → `/demo/tech` -- Analytics → `/analytics` -- Admin → `/admin` -- Reset data → server action calling `resetDemoTenant()` - -**Active state:** Highlights the current persona based on route prefix. - ---- - -## Data state for the demo - -For the demo to work across all three views, the seed data needs to be structured so: - -1. At least one technician (`Jason K.`) has `current_job_id` pointing to an active job (status `assigned` or `en_route`) -2. Quote data exists so analytics page shows real numbers (not all dashes) -3. `status_events` rows exist so the timeline on job detail pages is populated -4. The nightly reset (already in place) returns to this baseline state - -The seed script (`scripts/seed-demo-tenant.mjs`) already creates jobs; it needs a small addition to set `current_job_id` on one technician after seeding. - ---- - -## Implementation order - -1. **Extract `TechJobView`** — pull the rendering logic out of `/tech/page.tsx` into a shared server component so both routes can use it without duplication -2. **Add `/demo/tech` route** — demo-gated, dispatcher-authed, renders `TechJobView` in phone frame -3. **Add `DemoBanner`** — server component, conditionally shown in `(app)` layout -4. **Seed fix** — ensure `current_job_id` is set on a technician after seeding -5. **Analytics data** — ensure seed creates enough accepted quotes and status events for the analytics page to show real numbers - ---- - -## Open questions - -- **Should the tech view demo buttons (En Route, Arrived, etc.) be live or blocked?** Live is more impressive but means the demo state drifts. Since the nightly reset restores it, live is probably the right call. -- **Should we show a second demo persona credential** (`tech@swiftdispatch.app / demo`) on the marketing page as a fallback for prospects who want a real mobile test on their phone? Low engineering cost, worth considering alongside the `/demo/tech` route. -- **Should the demo banner show a countdown to next reset?** ("Resets in 6h 22m") — adds trust, shows the sandbox is managed. +# Demo & Sandbox Tenant Architecture + +> Supersedes the original "Live Demo Experience — Design Plan" that used to +> live in this file. That plan (a `/demo/tech` route reusing `/tech/page.tsx` +> JSX, `company.slug === 'demo'` detection, an admin-role demo login) was +> never built. What actually shipped (PRs #72, #74, #75/#76) took a +> different shape, described below. If you're looking for the old proposal, +> it's in git history; treat it as superseded, not as a roadmap. + +## Two sandbox tenants, one mechanism + +There are two purpose-built, fully-synthetic company tenants: + +| Tenant | Slug | Audience | Login role | +|---|---|---|---| +| Public demo | `swiftdispatch-demo` | Anyone (linked from marketing pages) | dispatcher | +| Private preview | `swiftdispatch-preview` | Trusted prospects (credentials shared directly) | dispatcher | + +Both are provisioned by `scripts/seed-demo-tenant.mjs` (one-time, env-var +driven — see the file's own header comment for usage) and reset nightly (and +on-demand via the in-app button) by `resetDemoTenant()` +(`src/lib/resetDemoTenant.ts`). Adding a third sandbox tenant means adding +its slug to `SANDBOX_DEMO_SLUGS` in **both** `src/lib/demo.ts` and +`scripts/lib/seedDemoGuard.mjs` (they can't share an import — the seed +script is a bundler-less `.mjs` — so they're kept in sync by hand; tracked +separately as issue #73). + +## Demo detection: two different questions, two different functions + +`src/lib/demo.ts` exports three predicates, each answering a distinct +question. Using the wrong one for a given purpose has caused real bugs +(PRs #72 and #74/#76 both had to fix exactly this): + +- **`isDemoCompany(company)`** — "should demo-only *UI chrome* show?" True + if `demo_mode_enabled` is set OR the slug is the public demo's. Loose on + purpose: a real customer's company could carry `demo_mode_enabled` by + accident (support tooling, a stray flag flip) without that making it safe + to wipe. Used to gate `DemoBanner` itself. +- **`isSandboxDemoCompany(company)`** — "is every row this company owns + synthetic, safe to fully wipe, and safe to show regardless of the + `is_demo` flag on individual rows?" A strict allowlist check against + `SANDBOX_DEMO_SLUGS`. This is the one that must gate anything destructive + (`resetDemoTenant()`) or anything that decides whether `is_demo=true` rows + should be visible. +- **`isPrivateSandboxDemoCompany(company)`** — "is this the *private* + preview tenant specifically (not the public demo)?" Scopes the + first-launch tutorial to the private flow, which already has its own + framing (a direct prospect handoff) that would be redundant with the + public demo's marketing-page framing. + +`isCompanySandboxDemo(supabase, companyId)` (also in `demo.ts`) is the +async, one-query-away version of `isSandboxDemoCompany` for routes/pages +that only have a `companyId`, not an already-loaded company row. + +## Why `is_demo` visibility needed per-route scoping + +A sandbox tenant's jobs/quotes are **all** `is_demo=true` — that data *is* +the product being demoed. But `scripts/load-tech-actions.mjs` and its +siblings also seed `is_demo=true` rows into ordinary, non-sandbox company +slugs, specifically to keep synthetic load-test traffic out of real +operators' views (grep those scripts for "reduce operational noise"). + +So no single blanket rule works: a sandbox tenant needs `is_demo` rows +**visible**, an ordinary tenant needs them **hidden**. Every read/write path +that used to filter `.eq("is_demo", false)` unconditionally now does it +conditionally, keyed off `isCompanySandboxDemo`/`isSandboxDemoCompany`: +quote build/preview/line-items/send-sms, the admin stats page, the +analytics page, `GET /api/jobs`, `KanbanBoard`'s realtime refetch, and +`DispatchPage`'s initial SSR load (SSR and realtime must agree — that +mismatch was its own bug, fixed in PR #76). RLS itself has no `is_demo` +predicate anywhere; this is purely an app-layer concern, not a security +boundary. + +## The demo banner and its pieces + +`DemoBanner` (`src/components/DemoBanner.tsx`) renders when `isDemoCompany` +is true, across every `(app)` page via the shared layout. It contains: + +- **`DemoTabNav`** — quick links to `/dispatch` and `/analytics`. +- **An "Admin settings" link** — only for an `admin`-role profile. The + private preview's login is `dispatcher` (see below), so it doesn't see + this. +- **`ResetDemoButton`** — POSTs `/api/demo/reset`, which re-verifies + `isSandboxDemoCompany` server-side before calling `resetDemoTenant()` + (never trusts the button's own gating alone). Surfaces the server's error + message on failure instead of failing silently. +- **`DemoTutorial`** — only for `isPrivateSandboxDemoCompany`. A four-step + anchored walkthrough (brand → dispatch → analytics → reset), desktop-only, + dismissal remembered in `localStorage`. + +## Why the demo login is `dispatcher`, not `admin` + +Considered and decided against making the private preview's login `admin` +(which would unlock `/admin`, `/admin/technicians`, `/admin/templates`, +`/admin/users`, `/admin/settings` in the same session). Staying +`dispatcher` and hiding the admin CTA was the smaller, lower-risk change, +and keeps the reset baseline's scope small — an admin-capable demo login +would put company settings, technician identities, and templates within a +prospect's reach, all of which `resetDemoTenant()` deliberately does not +restore (see below). If this decision changes, revisit that reset scope +too. + +## Tech preview: a floating widget, not a separate route + +There is no `/demo/tech` route. Instead, `TechPhoneModal` +(`src/components/TechPhoneModal.tsx`) is a floating "Tech view" button on +`/dispatch` itself, opening an iPhone-chrome mockup. Important +architectural fact: **it runs under the viewer's own dispatcher/admin +session**, not a real technician session — there's no auth-impersonation +layer. That has real consequences: + +- Its actions call the same `PATCH /api/jobs/[id]` a dispatcher would use, + so it's bound by `requireApiRole`'s dispatcher/admin rules, not the + narrower `TECHNICIAN_ALLOWED_STATUSES` a real technician session is + restricted to. +- "Complete" is gated on an accepted quote existing (`hasAcceptedQuote`, + fetched the same way `tech/page.tsx` computes it server-side), matching + the real technician UI's rule — it used to only check the generic + state-machine transition, which let a demo tech complete a job with no + quote at all. +- "Build Quote" is disabled (non-mutating) once a job reaches `in_progress`, + with an explanatory `title`. It used to PATCH the job straight to + `quote_pending`, which no real technician session can do either — in the + real product that transition is dispatcher-driven, via `QuoteBuilder` on + the job detail page; a real technician's own "Build Quote" link is + read-only (`/tech/job/[id]` has no mutation UI at all). +- Address/phone are real `https://maps.google.com/?q=...` and `tel:` links, + copied from `/tech/job/[id]`'s markup, not decorative text. +- "Sign out" is inert on purpose: there is no separate technician session + to sign out of. Making it functional would sign the *dispatcher* out of + their own account mid-demo. + +Reusing the real technician UI wholesale (a shared `TechJobView` component, +or a technician-session impersonation adapter) was considered and +explicitly deferred — it's a larger, security-relevant architectural +decision (issue #75), not a bug fix. + +## External side effects: SMS is suppressed centrally, payment is a non-issue + +Every SMS this app sends — intake, tech-action, quote-approval, invoice, +status updates — funnels through one worker, `processSmsOutboxBatch()` +(`src/lib/smsOutbox.ts`). That's the single place sandbox suppression is +decided: a sandbox tenant's queued messages are marked sent with a +`demo-simulated-*` id instead of ever calling Twilio. This is deliberately +**not** decided per-route via `is_demo` filters — that conflates a +data-visibility concern with an external-side-effect concern, which is +exactly the mistake PR #74 made and had to walk back. + +Payment needed no equivalent suppression: sandbox companies are seeded with +`payment_provider: "manual"`, and `ManualPaymentProvider` +(`src/lib/payments/manual.ts`) never makes an external call — it only +writes to this app's own `invoices` table. + +## What "Reset data" actually restores + +`resetDemoTenant()` does a full destructive wipe and reseed of job-centric +state: jobs, quotes, quote line items, status events, the SMS outbox, and +technician `availability_status`/`current_job_id`. It also restores two +things beyond job state to a canonical baseline: + +- **Technician name/phone**, matched *positionally* (ordered by + `created_at`, mirroring the original seed script's insertion order) — + not by name, which broke silently the moment a technician was renamed. + `handle`/`pin`/`auth_user_id` are never touched; those are the + technician's actual Supabase Auth login identity. +- **The canonical quote template** (`demoTemplate` in + `src/lib/demo-data.ts`), created if missing or restored if drifted. + +Deliberately **not** restored: company-level settings (name, email, phone, +timezone, `sms_sender_name`, `payment_provider`) and user roles. There's no +canonical source of truth for a given tenant's company settings without new +config infrastructure (the private preview's name/email were one-time CLI +args to the seed script, never persisted anywhere reset can read back), and +blanket-resetting user roles risks undoing a legitimate internal admin +account someone set up on purpose. If the demo login ever becomes +`admin`-capable, this gap becomes more load-bearing and should be +revisited. + +## Open follow-ups (tracked under issue #75) + +- Whether to eventually give `TechPhoneModal` a real shared-component or + impersonation-based connection to the production technician UI/rules, + instead of its current parallel (now rule-matched, but still separate) + implementation. This is a larger refactor than the audit's other fixes + and is left as a product/architecture decision rather than done + unprompted; `src/lib/__tests__/demoTenantQuoteLifecycle.test.ts` and the + per-route regression tests already guard the rule-matching in the + meantime. +- Automated coverage for the two things this repo has no test harness + for: rendering `/quote/[id]` and `/intake/quote/[token]` themselves + (vs. the data they'd render, which the E2E suite does cover), and any + component-level check of `KanbanBoard`, `DemoBanner`, or + `TechPhoneModal`'s actual DOM output. Both would need a React + Testing Library / jsdom render harness that doesn't exist anywhere in + this codebase yet. diff --git a/src/app/api/jobs/[id]/route.test.ts b/src/app/api/jobs/[id]/route.test.ts index 4598fcd..bc34222 100644 --- a/src/app/api/jobs/[id]/route.test.ts +++ b/src/app/api/jobs/[id]/route.test.ts @@ -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; diff --git a/src/app/api/jobs/[id]/route.ts b/src/app/api/jobs/[id]/route.ts index c5baf53..db0a582 100644 --- a/src/app/api/jobs/[id]/route.ts +++ b/src/app/api/jobs/[id]/route.ts @@ -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({ @@ -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> = { assigned: 'assigned_at', en_route: 'en_route_at', @@ -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 diff --git a/src/app/api/quotes/[id]/accept/route.test.ts b/src/app/api/quotes/[id]/accept/route.test.ts index 3ab69dd..9180c9d 100644 --- a/src/app/api/quotes/[id]/accept/route.test.ts +++ b/src/app/api/quotes/[id]/accept/route.test.ts @@ -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 }); }, @@ -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; @@ -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) { @@ -85,6 +125,7 @@ type Db = { jobs: Row[]; quote_line_items: Row[]; technicians: Row[]; + companies: Row[]; }; function createFakeSupabase(db: Db) { @@ -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}`); }, }; @@ -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" }], }; } @@ -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({}); diff --git a/src/app/api/quotes/[id]/accept/route.ts b/src/app/api/quotes/[id]/accept/route.ts index 5fac7e7..47c2180 100644 --- a/src/app/api/quotes/[id]/accept/route.ts +++ b/src/app/api/quotes/[id]/accept/route.ts @@ -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 @@ -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 diff --git a/src/lib/__tests__/demoTenantQuoteLifecycle.test.ts b/src/lib/__tests__/demoTenantQuoteLifecycle.test.ts new file mode 100644 index 0000000..badcd54 --- /dev/null +++ b/src/lib/__tests__/demoTenantQuoteLifecycle.test.ts @@ -0,0 +1,400 @@ +/** + * End-to-end sandbox-tenant quote lifecycle (issue #75, Phase 1/4): drives + * the real route handlers in sequence -- POST /api/quotes -> POST .../line- + * items -> POST /api/send-sms -> PATCH .../accept (or POST .../decline) -- + * against one shared in-memory fake Supabase. Per-route unit coverage for + * the sandbox-vs-ordinary is_demo visibility contract already exists (see + * src/app/api/quotes/route.test.ts and its siblings); this file's job is + * proving the *sequence* works end to end and that technician state comes + * out correct at the finish line, not re-litigating that contract. + * + * Deliberately NOT covered: rendering /quote/[id] or /intake/quote/[token] + * themselves. This repo has no page-component test infrastructure (no + * React Testing Library / jsdom render harness is set up anywhere), so a + * regression that breaks either preview page while the underlying data is + * correct would not be caught here -- only by manual or e2e-browser testing. + * Building that harness is out of scope for this file. + * + * Same "call the exported handler directly" pattern used throughout this + * repo (src/app/api/jobs/[id]/route.test.ts, resetDemoTenant.test.ts) -- + * no live server, no network. + */ +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +type Row = Record; + +const requireApiRoleMock = vi.fn(); +const enqueueSmsMock = vi.fn(); +const queueCustomerInvoiceSmsMock = vi.fn(); +const queueCustomerStatusSmsMock = vi.fn(); +const queueTechnicianAssignmentSmsMock = vi.fn(); + +vi.mock("@/lib/auth", () => ({ + requireApiRole: requireApiRoleMock, +})); + +vi.mock("@/lib/smsOutbox", () => ({ + enqueueSms: enqueueSmsMock, +})); + +vi.mock("@/lib/jobNotifications", () => ({ + queueCustomerInvoiceSms: queueCustomerInvoiceSmsMock, + queueCustomerStatusSms: queueCustomerStatusSmsMock, + queueTechnicianAssignmentSms: queueTechnicianAssignmentSmsMock, +})); + +// Invoicing is a real subsystem with its own tests; stubbed here so this +// file stays focused on quote/job/technician state, not invoice numbering. +vi.mock("@/lib/payments", () => ({ + getPaymentProvider: () => ({ + createInvoice: async () => ({ invoiceId: "stub-invoice", invoiceUrl: "/invoice/stub", totalAmount: 0 }), + getPaymentStatus: async () => ({ status: "pending" as const }), + }), +})); + +let adminStore: Map; +vi.mock("@/lib/supabase/admin", () => ({ + createSupabaseAdminClient: () => createFakeSupabase(adminStore), +})); + +// ── Generic in-memory multi-table fake, shared across every route call in +// a test so writes from one route are visible to the next. Filters support +// dot-paths (getPath) so a fake "join" -- e.g. quotes.jobs.company_id -- +// works by embedding a live object reference on the row at setup time +// (see attachJobRef below), not by actually joining tables. ────────────── + +type Filter = + | { type: "eq"; path: string; value: unknown } + | { type: "neq"; path: string; value: unknown } + | { type: "not_in"; path: string; values: unknown[] }; + +function getPath(row: Row, path: string): unknown { + return path.split(".").reduce((v, k) => (v && typeof v === "object" ? (v as Row)[k] : undefined), row); +} + +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) => { + const v = getPath(row, f.path); + if (f.type === "eq") return v === f.value; + if (f.type === "neq") return v !== f.value; + return !f.values.includes(v); + }); +} + +let idCounter = 0; + +class Builder { + private filters: Filter[] = []; + private orderPath: string | null = null; + private orderAsc = true; + private limitN: number | null = null; + + constructor( + private table: string, + private store: Map, + private mode: "select" | "insert" | "update" | "delete", + private payload?: Row | Row[], + ) {} + + eq(path: string, value: unknown) { + this.filters.push({ type: "eq", path, value }); + return this; + } + neq(path: string, value: unknown) { + this.filters.push({ type: "neq", path, value }); + return this; + } + not(path: string, _op: string, raw: string) { + this.filters.push({ type: "not_in", path, values: parseNotInList(raw) }); + return this; + } + order(path: string, opts?: { ascending?: boolean }) { + this.orderPath = path; + this.orderAsc = opts?.ascending ?? true; + return this; + } + limit(n: number) { + this.limitN = n; + return this; + } + select() { + return this; + } + + private rows() { + return this.store.get(this.table) ?? []; + } + private setRows(rows: Row[]) { + this.store.set(this.table, rows); + } + + private runSelect() { + let result = this.rows().filter((r) => matchesFilters(r, this.filters)); + if (this.orderPath) { + const p = this.orderPath; + result = [...result].sort((a, b) => { + const cmp = String(getPath(a, p)).localeCompare(String(getPath(b, p))); + return this.orderAsc ? cmp : -cmp; + }); + } + if (this.limitN !== null) result = result.slice(0, this.limitN); + return result; + } + + private runInsert() { + const items = Array.isArray(this.payload) ? this.payload : [this.payload!]; + const inserted = items.map((item) => ({ + id: `${this.table}-${(idCounter += 1)}`, + created_at: new Date(Date.now() + idCounter).toISOString(), + ...item, + })); + this.setRows([...this.rows(), ...inserted]); + return inserted; + } + + private runUpdate() { + const affected = this.rows().filter((r) => matchesFilters(r, this.filters)); + affected.forEach((r) => Object.assign(r, this.payload)); + return affected; + } + + private runDelete() { + this.setRows(this.rows().filter((r) => !matchesFilters(r, this.filters))); + } + + single() { + const rows = this.mode === "insert" ? this.runInsert() : this.runSelect(); + return Promise.resolve(rows[0] ? { data: rows[0], error: null } : { data: null, error: { message: "not found" } }); + } + maybeSingle() { + const rows = this.mode === "insert" ? this.runInsert() : this.runSelect(); + return Promise.resolve({ data: rows[0] ?? null, error: null }); + } + then(resolve: (value: { data: Row[] | null; error: null }) => void) { + let data: Row[] = []; + if (this.mode === "select") data = this.runSelect(); + else if (this.mode === "insert") data = this.runInsert(); + else if (this.mode === "update") data = this.runUpdate(); + else if (this.mode === "delete") this.runDelete(); + resolve({ data, error: null }); + } +} + +function createFakeSupabase(store: Map) { + return { + from(table: string) { + return { + select: () => new Builder(table, store, "select"), + insert: (payload: Row | Row[]) => new Builder(table, store, "insert", payload), + update: (patch: Row) => new Builder(table, store, "update", patch), + delete: () => new Builder(table, store, "delete"), + }; + }, + }; +} + +// ── Fixtures ───────────────────────────────────────────────────────────── + +const SANDBOX_COMPANY_ID = "11111111-1111-4111-8111-111111111111"; +const JOB_ID = "22222222-2222-4222-8222-222222222222"; +const TECH_ID = "33333333-3333-4333-8333-333333333333"; +const DISPATCHER_ID = "44444444-4444-4444-8444-444444444444"; + +function asDispatcher(store: Map) { + requireApiRoleMock.mockResolvedValue({ + profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: SANDBOX_COMPANY_ID, role: "dispatcher" }, + response: null, + supabase: createFakeSupabase(store), + }); +} + +function seed(store: Map) { + const company = { id: SANDBOX_COMPANY_ID, slug: "swiftdispatch-preview", name: "SwiftDispatch Preview", sms_sender_name: "SwiftDispatch", payment_provider: "manual" }; + const technician = { id: TECH_ID, company_id: SANDBOX_COMPANY_ID, name: "Mia Torres", phone: "+15551234567", availability_status: "on_job", current_job_id: JOB_ID }; + const job: Row = { + id: JOB_ID, + company_id: SANDBOX_COMPANY_ID, + status: "in_progress", + technician_id: TECH_ID, + customer_name: "Riverside Dental", + phone: "+15550010001", + address: "240 Riverside Blvd", + issue: "AC not cooling", + sms_consent_type: "intake_form", + is_demo: true, + }; + // Fake "joins": live object references, not copies, so a later + // Object.assign(job, patch) elsewhere is visible through every row that + // embeds this same reference -- the same trick used for `companies`/ + // `technicians` below. + job.companies = company; + job.technicians = technician; + + store.set("companies", [company]); + store.set("technicians", [technician]); + store.set("jobs", [job]); + store.set("quotes", []); + store.set("quote_line_items", []); + store.set("status_events", []); + + return { company, technician, job }; +} + +async function createQuote(body: Record) { + const { POST } = await import("../../app/api/quotes/route"); + return POST(new Request("http://localhost/api/quotes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })); +} + +async function addLineItem(quoteId: string, body: Record) { + const { POST } = await import("../../app/api/quotes/[id]/line-items/route"); + return POST( + new Request(`http://localhost/api/quotes/${quoteId}/line-items`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }), + { params: Promise.resolve({ id: quoteId }) }, + ); +} + +async function sendQuote(body: Record) { + const { POST } = await import("../../app/api/send-sms/route"); + return POST(new Request("http://localhost/api/send-sms", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })); +} + +async function acceptQuote(quoteId: string, body: Record) { + const { PATCH } = await import("../../app/api/quotes/[id]/accept/route"); + return PATCH( + new Request(`http://localhost/api/quotes/${quoteId}/accept`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }), + { params: Promise.resolve({ id: quoteId }) }, + ); +} + +async function declineQuote(quoteId: string, body: Record) { + const { POST } = await import("../../app/api/quotes/[id]/decline/route"); + return POST( + new Request(`http://localhost/api/quotes/${quoteId}/decline`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }), + { params: Promise.resolve({ id: quoteId }) }, + ); +} + +describe("sandbox tenant: full quote lifecycle", () => { + let store: Map; + let fixtures: ReturnType; + + beforeAll(() => { + process.env.QUOTE_TOKEN_SECRET = "test-secret-for-vitest-only"; + }); + + beforeEach(() => { + store = new Map(); + adminStore = store; + fixtures = seed(store); + requireApiRoleMock.mockReset(); + enqueueSmsMock.mockReset(); + enqueueSmsMock.mockResolvedValue(undefined); + queueCustomerInvoiceSmsMock.mockReset(); + queueCustomerStatusSmsMock.mockReset(); + queueTechnicianAssignmentSmsMock.mockReset(); + asDispatcher(store); + }); + + it("create -> add line item -> send -> accept ends with a completed job and a released technician", async () => { + const createRes = await createQuote({ job_id: JOB_ID, line_items: [{ name: "Diagnostic visit", price: 89, quantity: 1 }] }); + expect(createRes.status).toBe(200); + const { quote_id: quoteId } = (await createRes.json()) as { quote_id: string }; + expect(quoteId).toBeTruthy(); + + // The route's own insert has no real FK join -- attach the same live + // job reference so the line-items/send-sms routes' `jobs!inner(...)` + // selects resolve, matching how a real Postgres join would. + const quoteRow = store.get("quotes")!.find((q) => q.id === quoteId)!; + quoteRow.jobs = fixtures.job; + + const lineItemRes = await addLineItem(quoteId, { name: "Standard repair labor", price: 110, quantity: 1 }); + expect(lineItemRes.status).toBe(200); + const { total: lineItemTotal } = (await lineItemRes.json()) as { total: number }; + expect(lineItemTotal).toBe(199); // 89 + 110 + + // Real flow: the dispatcher moves the job to quote_pending once the + // quote is ready to send (a separate kanban/status action, not + // simulated here) -- quote_pending -> completed is the only valid + // transition accept's assertValidTransition allows. + fixtures.job.status = "quote_pending"; + + const sendRes = await sendQuote({ quote_id: quoteId }); + expect(sendRes.status).toBe(200); + expect(enqueueSmsMock).toHaveBeenCalledTimes(1); + expect(quoteRow.status).toBe("sent"); + + const token = (await import("@/lib/quoteTokens")).generateQuoteApprovalToken(quoteId); + const acceptRes = await acceptQuote(quoteId, { token }); + expect(acceptRes.status).toBe(200); + + expect(quoteRow.status).toBe("accepted"); + expect(fixtures.job.status).toBe("completed"); + expect(fixtures.technician.availability_status).toBe("available"); + expect(fixtures.technician.current_job_id).toBeNull(); + + const events = store.get("status_events")!; + expect(events.some((e) => e.to_status === "completed")).toBe(true); + }); + + it("create -> add line item -> send -> decline puts the job back to in_progress without releasing the technician", async () => { + const createRes = await createQuote({ job_id: JOB_ID, line_items: [{ name: "Diagnostic visit", price: 89, quantity: 1 }] }); + const { quote_id: quoteId } = (await createRes.json()) as { quote_id: string }; + const quoteRow = store.get("quotes")!.find((q) => q.id === quoteId)!; + quoteRow.jobs = fixtures.job; + + // Job must be quote_pending for decline's assertValidTransition(status, 'in_progress') to accept it. + fixtures.job.status = "quote_pending"; + + const sendRes = await sendQuote({ quote_id: quoteId }); + expect(sendRes.status).toBe(200); + + const token = (await import("@/lib/quoteTokens")).generateQuoteApprovalToken(quoteId); + const declineRes = await declineQuote(quoteId, { token, reason: "Too expensive" }); + expect(declineRes.status).toBe(200); + + expect(quoteRow.status).toBe("declined"); + expect(fixtures.job.status).toBe("in_progress"); + // Decline never touches technician state -- they're still working the job. + expect(fixtures.technician.availability_status).toBe("on_job"); + expect(fixtures.technician.current_job_id).toBe(JOB_ID); + + const events = store.get("status_events")!; + expect(events.some((e) => e.to_status === "in_progress" && e.actor_role === "customer")).toBe(true); + }); + + it("promotes another active job instead of releasing the technician if one remains after acceptance", async () => { + const OTHER_JOB_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + store.get("jobs")!.push({ + id: OTHER_JOB_ID, + company_id: SANDBOX_COMPANY_ID, + status: "en_route", + technician_id: TECH_ID, + created_at: "2024-01-01T00:00:00.000Z", + customer_name: "Carmichael Home", + phone: "+15550020002", + }); + + const createRes = await createQuote({ job_id: JOB_ID, line_items: [{ name: "Diagnostic visit", price: 89, quantity: 1 }] }); + const { quote_id: quoteId } = (await createRes.json()) as { quote_id: string }; + const quoteRow = store.get("quotes")!.find((q) => q.id === quoteId)!; + quoteRow.jobs = fixtures.job; + + fixtures.job.status = "quote_pending"; + await sendQuote({ quote_id: quoteId }); + const token = (await import("@/lib/quoteTokens")).generateQuoteApprovalToken(quoteId); + const acceptRes = await acceptQuote(quoteId, { token }); + + expect(acceptRes.status).toBe(200); + expect(fixtures.job.status).toBe("completed"); + // /api/quotes/[id]/accept completes jobs independently of PATCH + // /api/jobs/[id], but shares the same reconcileTechnicianAfterTerminalJob + // helper (src/lib/technicianReconciliation.ts), so it must not report + // the technician available while OTHER_JOB_ID is still open work. + expect(fixtures.technician.availability_status).toBe("on_job"); + expect(fixtures.technician.current_job_id).toBe(OTHER_JOB_ID); + }); +}); diff --git a/src/lib/__tests__/resetDemoTenant.test.ts b/src/lib/__tests__/resetDemoTenant.test.ts index 7a88476..e7dddd0 100644 --- a/src/lib/__tests__/resetDemoTenant.test.ts +++ b/src/lib/__tests__/resetDemoTenant.test.ts @@ -193,6 +193,25 @@ describe("resetDemoTenant", () => { expect(jobs).toHaveLength(demoJobs.length); }); + it("is repeatable: running it twice in a row lands on the same baseline both times (issue #75)", async () => { + const first = await resetDemoTenant(PREVIEW_DEMO_ID); + const firstJobs = (store.get("jobs") ?? []).filter((j) => j.company_id === PREVIEW_DEMO_ID); + const firstJobIds = new Set(firstJobs.map((j) => j.id)); + + const second = await resetDemoTenant(PREVIEW_DEMO_ID); + const secondJobs = (store.get("jobs") ?? []).filter((j) => j.company_id === PREVIEW_DEMO_ID); + const secondJobIds = new Set(secondJobs.map((j) => j.id)); + + expect(second.jobsSeeded).toBe(first.jobsSeeded); + expect(secondJobs).toHaveLength(demoJobs.length); + // The second reset's wipe fully replaced the first run's rows -- no + // leftover/duplicated jobs from run one still present after run two. + expect([...secondJobIds].some((id) => firstJobIds.has(id))).toBe(false); + + const templates = (store.get("quote_templates") ?? []).filter((t) => t.company_id === PREVIEW_DEMO_ID); + expect(templates).toHaveLength(1); + }); + it("refuses an explicit targetCompanyId on a non-sandbox company and performs no wipe", async () => { store.set("jobs", [ { id: "existing-job-1", company_id: REAL_COMPANY_ID, customer_name: "Real Customer" }, diff --git a/src/lib/technicianReconciliation.ts b/src/lib/technicianReconciliation.ts new file mode 100644 index 0000000..3b95256 --- /dev/null +++ b/src/lib/technicianReconciliation.ts @@ -0,0 +1,82 @@ +import { isCompanySandboxDemo } from "@/lib/demo"; +import type { createSupabaseServerClient } from "@/lib/supabase/server"; +import type { JobStatus } from "@/lib/stateMachine"; + +// 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"]; + +// supabase/migrations/202505010001_job_timestamp_columns.sql's check +// constraint still permits the pre-migration capitalized spellings +// ('New', 'Assigned', 'En Route', 'Completed' -- see LegacyJobStatus in +// src/types/db.ts), so a legacy-terminal row must be excluded at the query +// level too, not just via the client-side LEGACY_STATUS_MAP normalization +// KanbanBoard/TechPhoneModal apply for display. Only 'Completed' has a +// legacy terminal counterpart; the constraint has no legacy spelling for +// cancelled/no_access. +const TERMINAL_STATUS_FILTER = '("completed","cancelled","no_access","Completed")'; + +type SupabaseLike = Awaited>; + +/** + * Release a technician from a job that just reached a terminal status -- + * or, if they hold another active (nonterminal) assignment, promote it + * instead of reporting them available while real work remains assigned to + * them. SwiftDispatch allows one technician to hold multiple simultaneous + * nonterminal jobs (the demo seed does this deliberately, and nothing in + * the assignment API prevents it for real tenants either), while + * `technicians.current_job_id` tracks only one of them at a time. + * + * Shared by every path that can complete/cancel/no-access a job on a + * technician's behalf: PATCH /api/jobs/[id] (status-only completion, e.g. + * the real technician "Complete" button or a dispatcher's kanban drag) and + * POST /api/quotes/[id]/accept (quote acceptance completes the job + * directly, bypassing PATCH /api/jobs/[id] entirely). Both used to release + * unconditionally; extracted here after finding the same gap in both + * places rather than fixing it twice (issue #75). + * + * Scoped by `.eq('current_job_id', completedJobId)` at write time so a + * pointer that moved concurrently (reassignment mid-request) is never + * clobbered -- callers must not call this before their own job write has + * already succeeded, or a rejected job update could still release a + * technician whose job was never actually completed. + * + * The "next active job" candidate is also is_demo-scoped: for an ordinary + * (non-sandbox) company, load-test/live-QA rows (is_demo=true, seeded by + * scripts/load-tech-actions.mjs etc.) are otherwise-invisible to operators + * -- promoting one of those as a real technician's current_job_id would + * point the tech rail at a job no dispatcher can see. + */ +export async function reconcileTechnicianAfterTerminalJob( + supabase: SupabaseLike, + params: { technicianId: string; companyId: string; completedJobId: string }, +): Promise { + const { technicianId, companyId, completedJobId } = params; + const isSandbox = await isCompanySandboxDemo(supabase, companyId); + + let nextActiveJobQuery = supabase + .from("jobs") + .select("id") + .eq("technician_id", technicianId) + .eq("company_id", companyId) + .not("status", "in", TERMINAL_STATUS_FILTER) + .neq("id", completedJobId); + if (!isSandbox) nextActiveJobQuery = nextActiveJobQuery.eq("is_demo", false); + + const { data: nextActiveJob } = await nextActiveJobQuery + .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", technicianId) + .eq("current_job_id", completedJobId); +} + +export { TERMINAL_STATUSES };