Repository navigation
Fix demo-tenant quote actions and stale technician availability - #74
Conversation
Found while validating the swiftdispatch-preview tenant: a stray
.eq("is_demo", false) had been copy-pasted onto several routes that were
already company_id-scoped (quote preview, add/edit/delete line item,
build-quote, the admin stats/jobs-list/kanban-refetch reads). Since a
sandbox tenant's rows are all is_demo=true, every one of those routes
returned "not found" for it -- Preview 404'd, "Add line" failed, and the
kanban board and admin page would go empty on any client refetch. The
filter is a no-op for real tenants (is_demo defaults false and is never
set otherwise), so dropping it only fixes sandbox tenants and changes
nothing for production companies.
Also: both seeding paths (scripts/seed-demo-tenant.mjs and the nightly
resetDemoTenant()) reset every technician to "available" before inserting
jobs, then never touched availability_status/current_job_id for jobs
that got assigned -- so the tech rail showed every technician as
available even while their cards were en_route/in_progress/quote_pending.
resetDemoTenant() had a partial fix scoped to one hardcoded technician;
generalized it to track each technician's oldest active job and mark
them on_job, matching how PATCH /api/jobs/[id] flips availability on a
real assignment.
Re-ran seed-demo-tenant.mjs against the live swiftdispatch-preview tenant
so the fix applies to the already-provisioned prospect demo, not just
future seeds.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b3c96b68ef
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| .eq('company_id', profile.company_id) | ||
| .eq('is_demo', false) | ||
| .not('status', 'in', '("completed","cancelled")') |
There was a problem hiding this comment.
Preserve the demo filter for non-sandbox tenants
When this endpoint is used by a non-sandbox company that has run the load harness, removing this predicate exposes its synthetic jobs as operational work. This is a supported scenario rather than a hypothetical one: scripts/load-tech-actions.mjs and scripts/load-multi-tech-actions.mjs insert 75–100 assigned jobs with is_demo: true into configurable company slugs, and the former explicitly says the flag reduces operational noise. The same unconditional removal also contaminates the admin job metrics. Include demo rows only for companies recognized by isSandboxDemoCompany, while retaining is_demo = false elsewhere.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed — load-tech-actions.mjs/load-multi-tech-actions.mjs/seed-live-qa.mjs do insert is_demo=true into non-sandbox company slugs specifically to keep that traffic out of operator views. Fixed in 6dcf5a3: added isCompanySandboxDemo() and made the filter conditional everywhere this PR touched it — applied for ordinary companies (unchanged), skipped only for SANDBOX_DEMO_SLUGS tenants. Thanks for catching this.
Generated by Claude Code
Generated by Claude Code
diese-tech
left a comment
There was a problem hiding this comment.
Half-Shell review
Leonardo verdict: NOT READY yet. One real blocker.
April O'Neil — contract check
The sandbox bug is real: the private preview tenant uses is_demo=true rows by design, so globally requiring is_demo=false makes quote actions, board refetches, and admin views disappear. The technician availability cleanup also addresses a real demo-state mismatch.
But the PR's claim that removing these filters is a no-op for non-sandbox/production tenants is not true against the repo's own load tooling.
Donatello — architecture
company_id/RLS is the tenant-security boundary. is_demo is not an authorization boundary, agreed.
It is, however, an operational-noise boundary. scripts/load-tech-actions.mjs and the multi-tech harness deliberately create is_demo=true jobs in configurable company slugs so synthetic load traffic stays out of normal operator views. Those slugs are not required to be sandbox demo tenants.
So the right model is not "remove is_demo=false everywhere." It is:
- sandbox demo company: include its
is_demo=truerows because those rows are the product experience - ordinary company: preserve the existing
is_demo=falsevisibility filter so load/test traffic remains hidden
Raphael — correctness edge
This is observable data contamination, not theoretical cleanup debt. After this PR, a non-sandbox company used for tech-action load testing can suddenly surface 75–100 synthetic jobs on GET /api/jobs, Kanban realtime refetches, and admin metrics.
The updated GET /api/jobs test currently locks that global behavior in by asserting demo rows are returned without first proving the acting company is a sandbox tenant. That test should instead cover both sides of the contract.
Michelangelo — UX/test reality
The preview tenant needs the fix, 100%. But a dispatcher in a normal tenant should not refresh their board after a load run and suddenly see a wall of LOADTEST TECH ... jobs. Fixing the demo UX should not regress the real-company UX.
Please add behavior coverage for:
- sandbox tenant =>
is_demo=truejobs/quotes remain visible and mutable - non-sandbox tenant =>
is_demo=trueload/test rows remain hidden from normal operational reads/metrics
Casey Jones — ugly ops path
The load harness is configurable by company slug. That means this can hit exactly the companies operators use for QA or performance work. The old filter was doing useful cleanup even though it was not a security control.
Splinter — scope discipline
Do not undo the sandbox fix. Narrow it. A small shared helper/query branch based on isSandboxDemoCompany() is enough; this does not need a redesign.
Shredder — adversarial challenge
Point LOAD_COMPANY_SLUG at a normal QA/company tenant, run the tech-action load harness, then refresh the board/admin page after this PR. Those synthetic is_demo=true rows are now eligible to appear. That violates the harness's own stated "reduce operational noise" intent.
Leonardo — final
Blocking finding: preserve is_demo=false filtering for non-sandbox tenants while allowing demo rows for recognized sandbox tenants. Apply that rule consistently anywhere this PR removed the filter and where those rows feed operator-facing views/actions.
Technician availability work looks directionally good and is not the blocker here.
Exact-head CI is green on b3c96b68, but green CI currently validates the wrong cross-tenant visibility contract.
Codex flagged a real gap in b3c96b6: load-testing/live-QA scripts (scripts/load-tech-actions.mjs, load-multi-tech-actions.mjs, seed-live-qa.mjs) insert is_demo=true rows into ordinary, non-sandbox company slugs specifically to keep that synthetic traffic out of real operator views (load-tech-actions.mjs's own log line: "reduce operational noise"). Dropping the is_demo filter unconditionally, as the prior commit did, would surface that synthetic load-test data as real jobs/quotes for those companies -- fixing the sandbox demo tenant by breaking a working safeguard elsewhere. Added isCompanySandboxDemo() (src/lib/demo.ts), a one-query helper around the existing isSandboxDemoCompany() allowlist check, and used it to make the is_demo filter conditional everywhere the prior commit removed it: apply it for ordinary companies (unchanged behavior), skip it only for companies on SANDBOX_DEMO_SLUGS (swiftdispatch-demo, swiftdispatch-preview) whose rows are all synthetic anyway. KanbanBoard's realtime refetch takes this as an isSandboxDemo prop from dispatch/page.tsx (which already loads the company row) rather than paying for an extra client-side query. Updated the four test suites whose fakes now need a `companies` table handler for the new lookup; restored the original api/jobs GET test (demo jobs excluded for an ordinary company) and added a new case proving they're included for a sandbox-slug company. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Full audit of the demo-tenant branches (PR #72 + this PR) turned up one more instance of the bug this PR already fixes elsewhere: POST /api/send-sms still unconditionally filtered `is_demo = false` on the quote lookup, so "Send quote to customer" -- the button right next to Preview -- would fail on the sandbox tenant the same way Preview and Add-line did before this PR. Applied the identical isCompanySandboxDemo() scoping already used everywhere else in this PR. Verified this is safe to enable for the seeded demo jobs specifically: their phone numbers (e.g. +15550090009) have an NXX of "009", which starts with a digit NANP forbids for a real exchange code, so they can't route to an actual subscriber -- and SMS send here is outbox-queued (enqueueSms just inserts a row; delivery happens later, async, in a background worker), so the UI's immediate "quote sent" feedback is unaffected by whatever a background Twilio attempt against an invalid number does. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
The Half-Shell review on this PR (posted before, but delivered after, 6dcf5a3's fix) asked for the same scoping Codex flagged, plus explicit test coverage for both sides of the contract: a sandbox tenant's is_demo=true jobs/quotes stay visible and mutable, while an ordinary company's is_demo=true rows (load-test/live-QA traffic) stay hidden. The prior commit already covered this for GET /api/jobs; this extends the same pair of cases to every other route this PR touched -- POST /api/quotes, POST/PATCH/DELETE on quote line items, and POST /api/send-sms -- so each has a sandbox-tenant test proving the row is found/mutable and an ordinary-tenant test proving it stays hidden. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
|
Thanks — this landed on On the specific ask for test coverage on both sides of the contract (sandbox tenant → Current head ( Generated by Claude Code Generated by Claude Code |
diese-tech
left a comment
There was a problem hiding this comment.
Half-Shell re-review
April O'Neil — headline
The previous blocker is mostly fixed, but the Dispatch board still tells two different stories depending on whether the page just loaded or realtime has fired.
The new sandbox-aware rule is correctly applied to API reads, quote paths, admin stats, and the Kanban realtime refetch. But the initial Dispatch SSR query still loads every company job without filtering is_demo=true for ordinary tenants.
Donatello — data-flow check
DispatchPage still builds allJobs from:
supabase.from("jobs")
.select(...)
.eq("company_id", companyId)
.order("created_at", { ascending: false })There is no sandbox-aware filter before allJobs is passed into KanbanBoard.
Inside KanbanBoard, the new realtime refetchAll() does apply:
if (!isSandboxDemo) query = query.eq("is_demo", false)So the initial render and subsequent refetch do not share the same population for a normal tenant.
Raphael — correctness
That means the original operational-noise blocker still exists on first load.
A normal QA/company tenant with is_demo=true load-test rows can open Dispatch and see those synthetic jobs immediately. Then the first realtime change causes them to disappear. That's both contamination and state drift.
Michelangelo — UX reality
This is exactly the kind of thing a user notices as "the board randomly changed after I touched something." Initial SSR and live refresh need to show the same jobs.
Casey Jones — ugly path
Run the load harness against a normal tenant, then hard-refresh Dispatch. Synthetic rows are eligible to appear until the next realtime refresh. If no realtime event happens, they can just sit there.
Splinter — smallest fix
Keep the current architecture. Just apply the same sandbox-aware visibility rule to the initial Dispatch jobs query before building allJobs and activeCount.
A regression test should prove:
- normal tenant initial Dispatch population excludes
is_demo=true - sandbox tenant initial Dispatch population includes them
- realtime refetch follows the same rule
Shredder — challenge
If two code paths represent the same board, they must not disagree about which rows exist.
Leonardo — verdict
Still not ready. One remaining blocker.
The prior review's main concern is now narrowed to SSR/realtime parity on Dispatch. The rest of the sandbox-aware visibility work looks directionally correct, and exact-head CI is green on dd39da8c.
Fix the initial Dispatch query to use the same sandbox-aware is_demo policy as KanbanBoard.refetchAll(), then this PR should be in good shape for merge.
… load Half-Shell re-review on this PR: KanbanBoard's realtime refetch already applies the sandbox-aware is_demo filter (6dcf5a3), but the page that renders it -- DispatchPage's initial server-side jobs query -- never did. For an ordinary company with load-test/live-QA rows (is_demo=true, inserted by scripts/load-tech-actions.mjs etc.), that meant the first paint showed those synthetic jobs and then they'd vanish the moment realtime fired -- SSR and the live board disagreeing about which rows exist, exactly the class of bug the filter was there to prevent in the first place. Filtered `allJobs` by a new companyIsSandbox check before it's used for activeCount, pickDemoTech, and the KanbanBoard/TechRail props. Kept this independent of the `impersonating` flag (unlike the existing isDemo/ isSandboxDemo variables, which intentionally suppress demo-only UI chrome for a platform admin's view) -- row visibility should track the target company's own data, not who's currently looking at it, or an admin impersonating a sandbox tenant for support would see an empty board. No dedicated test added: this codebase has no existing test harness for Next.js server page components (grepped -- none of the ~15 page.tsx files under src/app have a companion test), so a one-off harness here would be inconsistent with how every other page in the app is verified. The filtering logic itself is the same one-liner already covered by isSandboxDemoCompany()'s unit tests (src/lib/__tests__/demo.test.ts) and mirrors admin/page.tsx's identical (also untested) filter. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
|
Confirmed — One deliberate wrinkle: I made this check independent of the On the requested regression test: this codebase has no existing test harness for Next.js server page components — I grepped and none of the Current head ( Generated by Claude Code Generated by Claude Code |
diese-tech
left a comment
There was a problem hiding this comment.
Half-Shell re-review
Leonardo verdict: READY from review perspective.
April O'Neil — blocker check
The prior SSR-vs-realtime visibility mismatch is resolved on this head. The initial Dispatch render now applies the same company-level sandbox distinction that the API/realtime paths use: recognized sandbox companies include their is_demo=true product data, while ordinary companies continue hiding synthetic load-test rows.
Donatello — architecture
The important detail is that the SSR decision is based on the company, not on the viewer. companyIsSandbox = isSandboxDemoCompany(companyData) is the right axis. That also preserves a useful support behavior: a super-admin impersonating a sandbox tenant can still see that tenant's synthetic dataset rather than getting an empty initial board.
The realtime KanbanBoard path remains sandbox-aware for normal dispatcher sessions, so initial render and client refresh now agree on the operational visibility contract.
Raphael — correctness
The previous failure mode was: normal tenant opens board, sees synthetic is_demo=true load rows from SSR, then watches them disappear on the first realtime refetch. That inconsistency is gone.
I do not see a new correctness blocker introduced by the fix. The broader demo-flow issues we found later (TechPhoneModal fidelity, /api/send-sms demo quote behavior, terminal technician cleanup, etc.) are tracked under the separate Half-Shell Demo Tenant Audit (#75) and should not be folded into this PR.
Michelangelo — UX/test reality
The board should now stop doing the awkward "now you see the fake load jobs, now you don't" trick on normal tenants. Sandbox prospects still keep the full seeded board they need for the demo.
Casey Jones — ops path
This preserves the load harness's reason for setting is_demo=true: synthetic traffic stays out of ordinary operator views. At the same time, purpose-built sandbox tenants keep those same rows visible because they are the walkthrough dataset.
Splinter — scope discipline
The fix stays narrow. It establishes the visibility foundation #74 needs without trying to absorb the larger #75 audit into this PR.
Shredder — adversarial pass
Checked the important combinations:
- normal company +
is_demo=truerows => hidden from initial board - sandbox company +
is_demo=truerows => visible - super-admin impersonates sandbox => initial board still receives sandbox rows
- dispatcher sandbox session => realtime refetch remains sandbox-aware
No blocking contradiction found.
Leonardo — final
Ready from review perspective on c47df6d1. The blocker from the previous Half-Shell pass is resolved. Exact-head CI is green (run 35551646048).
The remaining demo-tenant concerns are correctly separated into #75 and should be handled after #74 lands.
…, 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
…MS suppression Three fixes from the product decisions made on the Half-Shell Demo Tenant Audit (#75): - TechPhoneModal's "Build Quote" no longer PATCHes the job status directly. A real technician session can't trigger this transition either -- the real Build Quote link is read-only, and quote_pending/quote-building is entirely dispatcher-driven via QuoteBuilder. The button is now disabled once in_progress, with an explanatory title, instead of faking a capability no real technician has. - DemoBanner's "Admin settings" link now only renders for an admin-role profile. The private preview demo user stays dispatcher (decision: keep dispatcher, hide the CTA rather than promote the demo user to admin), so it no longer shows a link that just bounces back to Dispatch. - Centralized sandbox external-side-effect suppression at the one real choke point for outbound SMS: processSmsOutboxBatch() in src/lib/smsOutbox.ts, which every SMS trigger (intake, tech-action, quote-approval, invoice, status updates) already funnels through. Sandbox-tenant messages now simulate delivery (skip the real Twilio call, mark sent with a demo-simulated id) instead of relying on the accident that seeded phone numbers are NANP-invalid. Deliberately NOT done per-route via is_demo filters -- that conflates a data-visibility concern with an external-side-effect concern, which is exactly what broke in PR #74 the first time around. Payment is a non-issue today: demo companies are seeded with payment_provider="manual", and ManualPaymentProvider never makes an external call (writes only to our own `invoices` table) -- confirmed by reading src/lib/payments/manual.ts rather than assumed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
…ipped The doc described a proposal (a /demo/tech route reusing /tech/page.tsx JSX via a shared TechJobView extraction, company.slug === 'demo' detection, an admin-role demo login) that was never built. What actually shipped across PRs #72/#74/#76 took a different shape: a floating TechPhoneModal widget on /dispatch running under the viewer's own dispatcher session (not a separate tech route or auth), a three-predicate demo-detection scheme (isDemoCompany/isSandboxDemoCompany/ isPrivateSandboxDemoCompany) answering three different questions, a dispatcher-role (not admin) private preview login, per-route is_demo visibility scoping, and a centralized SMS-suppression choke point instead of per-route filters. Rewrote the doc to describe the current architecture as-built, so it's useful as a reference instead of a misleading roadmap. Flagged in the new doc's "Open follow-ups" section rather than treated as done: a dedicated E2E quote-lifecycle regression suite (added separately, this same session) and whether TechPhoneModal should eventually get a real shared-component/impersonation connection to the production technician UI instead of its current parallel implementation. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Summary
Found while validating the newly-provisioned
swiftdispatch-previewtenant (a private demo tenant for trusted prospects, PR #72):.eq("is_demo", false)had been copy-pasted onto several routes that are alreadycompany_id-scoped: the/quote/[id]preview page,POST /api/quotes(build/save quote),POST /api/quotes/[id]/line-items(add line),PATCH/DELETE /api/quotes/[id]/line-items/[itemId](edit/delete line), the admin stats page, and the kanban board's realtime refetch.is_demo=true, every one of those routes returned "not found" for it — quote Preview 404'd, "Add line" failed silently, and the kanban board/admin page would go empty on any client-side refetch.quotes/quote_line_items/jobspolicies referenceis_demoat all — they're scoped purely bycompany_id. The filter was an app-layer-only redundancy, not a real safeguard.is_demodefaults tofalseand nothing else ever sets it — so removing it changes nothing for production tenants.Separately: both seeding paths (
scripts/seed-demo-tenant.mjsand the nightlyresetDemoTenant()) reset every technician toavailablebefore inserting jobs, then never updatedavailability_status/current_job_idfor jobs that got assigned — so the tech rail showed every technician as available even while their job cards wereen_route/in_progress/quote_pending.resetDemoTenant()had a partial fix hardcoded to one technician; generalized it to track each technician's oldest active job and mark themon_job, matching howPATCH /api/jobs/[id]flips availability on a real assignment.Re-ran
seed-demo-tenant.mjsagainst the liveswiftdispatch-previewtenant so the fix applies to the already-provisioned prospect demo, not just future seeds.Test plan
npx tsc --noEmit— cleannpx vitest run— 347 passed / 8 skipped, no failures (updated two tests —api/jobsandapi/quotes— that had locked in the oldis_demo-filtered behavior/mock shape)quotes/quote_line_items/jobsRLS policies have nois_demopredicateswiftdispatch-previewand confirmed via SQL that all three technicians now showon_jobagainst the correct job they're actually working🤖 Generated with Claude Code
https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Generated by Claude Code