Architecture Note · Operations & RevOps

Deterministic Dispatch & Margin Guardrails for Commercial Trades

How commercial HVAC, high-voltage, and MEP contractors replace brittle dispatch guesswork with rule-bound crew matching, hard invoice release gates, and tamper-evident SQLite audit logs.

The Operational Problem

Commercial HVAC, refrigeration, gas, and high-voltage contractors operate on tight service-level windows across distributed buildings. When a P1 chiller bearing fault or 13.8 kV tie-breaker lockout hits a dispatch desk, sending a technician who lacks the active trade license or the exact replacement component on the truck forces a second truck roll. In multi-city portfolios spanning London, Chicago, Toronto, Sydney, and Frankfurt, a single missed part or unapproved overtime shift rapidly turns a profitable Preventative Maintenance (PM) agreement into negative gross margin and SLA penalty exposure.

Why Naive AI Wrappers Fail

Generic LLM dispatch and billing assistants break down in commercial trades along four predictable failure modes:

  • Soft matching on hard safety constraints: Free-text prompt ranking routinely suggests an available technician nearby while overlooking missing High-Voltage or Gas certifications, depleted van stock, or weekly overtime thresholds.
  • Nondeterministic billing math: Letting a generative model calculate regular hours, 1.5x or 2.0x overtime multipliers, truck-roll fees, parts markups, and PM contract credits invites silent arithmetic drift and unapproved margin erosion.
  • Uncontrolled outbound automation: Bots that trigger outbound voice calls or SMS blasts annoy facility managers and create compliance risk when field updates should remain strictly inbound.
  • Missing custody and retention limits: Storing inspection photos indefinitely or exporting raw spreadsheets without formula-injection sanitization exposes customer sites and back-office accounting teams.

The Deterministic Architecture That Fixes It

The Trades-FSM architecture treats scheduling, job costing, and compliance verification as deterministic state transitions in FastAPI and SQLite (WAL mode), backed by automated pytest coverage.

  1. Scored crew matching with 409 Conflict override gates: POST /api/dispatch/assign scores candidate technicians on a deterministic 100-point rubric—45 points for matching trade certification (HVAC, High-Voltage, Refrigeration, Gas), 35 points for required van inventory, and 20 points for local-city SLA capacity within overtime limits. Any assignment missing a certification, part, or capacity threshold returns 409 Conflict unless explicit dispatcher_override=true and dispatcher_name fields are submitted and written to an immutable SHA-256 hash-chained audit_logs table.
  2. Inbound-only check-ins and 1-hour upload wipes: Field updates enter exclusively through verified Official WhatsApp Business Cloud API webhooks or inbound voice-note transcripts—zero outbound AI calls or SMS blasts. POST /api/work-orders/{id}/complete records consumed parts, labour hours, and first_time_fix outcomes via JSON or multipart/form-data, restricting inspection uploads to 5 MB and an explicit extension allowlist with UUID filenames. A background periodic_cleanup_loop runs purge_expired_data(ttl_seconds=3600) to wipe temporary inspection uploads and expired invite tokens after one hour while preserving baseline fleet records.
  3. Two-stage billing drafts and human release gates: POST /api/invoices/generate computes time-and-materials or PM-contract drafts using OfflineDeterministicAdapter by default for zero external API egress. Every draft starts in pending_manager_review; quotes breaching the 32% margin target or 22% floor surface explicit warnings. Both customer PO capture and manager sign-off (POST /api/invoices/{id}/approve) are required before POST /api/invoices/{id}/finalize or GET /api/invoices/{id}/export.csv will succeed, otherwise returning 409 Conflict.
  4. Fleet KPIs, asset warranties, and sanitized exports: GET /api/analytics/fleet aggregates First-Time-Fix (FTF) rates, technician utilization, job gross margin, and PM contract profitability against a 35.0% commercial target across currencies (USD, GBP, CAD, AUD, EUR), while equipment serial records track active or expiring OEM warranties and F-Gas or CSA inspection logs. GET /api/analytics/export.csv formats RFC 4180 output with OWASP formula-injection neutralization (prefixing leading =, +, -, @, tab, or carriage-return cells). All /api/* routes enforce time-boxed invite tokens checked via hmac.compare_digest and atomic per-token rate limits (429 Too Many Requests).

Operational Takeaway

Commercial contractors gain margin and SLA reliability not by letting models guess who to roll or what to bill, but by enforcing license, van-stock, and human release rules deterministically in code before a truck rolls or an invoice leaves the building.

Test deterministic dispatch & margin guardrails on your fleet

Start with a free 30-minute workflow check. Bring one week of commercial work orders and PM contracts, and leave with one concrete recommendation in writing within one business day.