Skip to the lesson
CivOps AI Academy · M18Field Service: the Installed Base, Contracts and SLAs, Dispatch, Offline Technicians and Van Stock
0%

Chapter 1 · Sessions 1 and 2

What the old tool does, and the tables that replace it

Session 1 inventories your field service tool from its own reports and bills, and tests its two classic failures on your own data. Session 2 adds the module's thirteen tables to your Foundation schema, with the rules the database holds itself and a small made-up service business you can count by hand, tried first on the development project.

35 minSteps 1–5About 2 hours 15 minutes hands-on in these two sessionsAbout 7 hours hands-on across six sessions

By the end of this chapter you can

  • Inventory the old tool from its own reports and invoices, without estimating anything and without copying customers' personal data.
  • Test the two pitfalls on real data: installed assets not tied to shipped serials, and schedules that ignore driving time.
  • Have Claude Code add the missing spine tables, then the thirteen fsm_ tables with their rules and tests.
  • Seed the lab service business, count it by hand, and try the migrations and the seed on the development project yourself.

What the module does, and what it leaves alone

Field service management (FSM) services the equipment you delivered and still look after at customer sites: installed assets and warranties, service contracts and their service level agreements (SLAs: the promised time to respond and to resolve), work orders from cases or preventive plans, dispatch by skill, territory and travel, an offline technician phone, van stock and the hand-off of billable lines. It replaces tools such as Salesforce Field Service, Microsoft Dynamics 365 Field Service, ServiceTitan, PTC ServiceMax, IFS FSM, Jobber, Housecall Pro and FieldEdge [3].

The edge of field serviceInside: installed base and sites, contracts and SLAs, work orders, dispatch board, technician app, van stock and parts, billing hand-off and warranty claims. Outside, each with its owner: case intake in M19, invoicing and AR in accounting, internal plant maintenance in M05. INSIDE FIELD SERVICE (M18)Installed base, sitesContracts and SLAsWork ordersDispatch boardTech app (offline)Van stock and partsBilling hand-offWarranty claimsOUTSIDE, WITH ITS OWNERCase intake, support chatowned by M19Invoicing and ARowned by accountingInternal plant maintenanceowned by M05
The edge of the module. Taking the customer's call is M19; the invoice and accounts receivable stay in accounting; the plant's own machines are M05. Field service starts when a job at a customer's site is needed and ends when billable lines are handed on.
StandardWhat it asksWhere the module meets it
ISO 9001:2015, clause 8.5.5Meet the requirements for post-delivery activities, such as warranty and maintenance service [1]Installed assets with warranty dates, contracts, work orders, signed service reports
ISO 10002:2018Guidelines for handling complaints [2]A job keeps its link to the case that caused it (case_ref)
ITIL 4 service level managementDefine service levels with the customer, then measure themResponse and resolution hours on the contract; SLA attainment from the job's own times
CapabilityTierBuilt in this course
Installed base from shipped serialsMVPYes (Sessions 2 and 4)
Work orders from cases and preventive plansMVPYes (Session 4)
Scheduling and dispatch by skills, territory and travelMVPYes, one job at a time (Session 4)
Technician phone, offlineMVPYes (Sessions 3 and 4)
Contracts, entitlements and SLAsSTDYes (Session 4)
Van stock and parts requestsSTDYes, through the inventory ledger (Session 4)
Billing hand-off and analyticsSTDCSV export and four measures (Session 4)
Customer messages, warranty recovery, schedule optimisationSTD and BICLater: nothing in this course texts or emails a customer
Step 1

Session 1: Inventory the tool you pay for today, from its own reports

40 minutes

Why

The module has to replace real things, not guesses. Counting what the old tool holds from its own reports, and reading every bill from an invoice, tells you exactly what must come across and makes the saving at the end arithmetic anyone can check. Writing only counts, serials and job numbers keeps customers' personal data out of the repository from the first day.

Do this

From the tool's own reports: count customers, service sites, installed assets, contracts (active, ended in the last 90 days, with no end date), work orders open and closed, appointments, technicians, van stock locations and billing lines. Copy its own figures for the last four full weeks: jobs completed, first-time fix, SLA attainment, utilisation, repeat visits, each with its report name and definition (or "not reported"). List every tool around it (a routing app, a texting service, a contract spreadsheet, a whiteboard) with its bill from the invoice. Ask a technician to put a phone in airplane mode and open a job: note what still works. Then:

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code, after replacing the <...> part
I am inventorying the field service tool Acme Bottling rents today, so a module on our platform can replace it. I will paste counts and figures I read from the tool's own reports and from our invoices. Never estimate or fill in a figure I have not given you: write "not yet read" and who can read it. No customer names, addresses or signatures go in this file: counts, serials and job numbers only.

On a new branch fsm/inventory, write docs/fsm-inventory.md with:
1. Records: a table of each kind (customers, service sites, installed assets, contracts by state, work orders open and closed, appointments, technicians, van stock locations, billing lines), its count, the report it came from and the date.
2. Tools: each tool and helper (name, owner as a job, seats, bill per year, renewal date, notice period, export route), from invoices.
3. Who signs in: dispatchers, technicians, service managers and customers (is there a portal?), and on which devices.
4. Offline: what a technician's phone still does in airplane mode (job details, history, parts, time, photos, signature).
5. The tool's own figures for the last four full weeks: jobs completed, first-time fix, SLA attainment, utilisation, repeat visits, mean time to repair, each with its report and definition, or "not reported".
6. Van stock and billing: where van counts live, whether a used part comes off the van by itself, how warranty parts are claimed from suppliers, how billable lines reach accounting.
7. Workarounds, in the dispatcher's and technicians' own words.

My figures:
<paste what you read, section by section>

Open a pull request titled "Field service inventory" and show me the link.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/fsm-inventory.md)
+## 1. Records (from the tool's Assets and Jobs reports, 2026-11-03)
+Installed assets: 1,286 · contracts active 214, no end date 37
+## 2. Tools
+Routing add-on: bill not yet read. Accounts payable holds the invoice.
1
⏺ Write(docs/fsm-inventory.md)
+## 5. The tool's own figures, 2026-10-06 to 2026-11-02
+First-time fix: 71% (report: Service KPIs; counts closed jobs with one visit)
+SLA attainment: not reported
2
⏺ Pull request #81 adds docs/fsm-inventory.md. Two figures are marked not yet read; I estimated neither. The file holds counts and report names only, no customer details.
Claude Code writes only what you gave it, and no customer's name or address.
  1. "Not yet read" is an honest answer. An estimate would become the saving you claim in Session 6.
  2. Each figure with its definition. Two tools can both say first-time fix and mean different things.

Check it worked

The pull request has one file, docs/fsm-inventory.md, with all seven sections; every figure names its source; no customer name, address or signature appears.

If it goes wrong

Claude Code filled in a price, a count or a figure you never gave it

Say: Remove every figure I did not give you and mark it not yet read. On our own platform a screen showed savings nobody had measured, labelled as the ledger. A number nobody read is the same mistake, made earlier.

You pasted a report with customers' names in it

Say: Remove every customer name, address, phone number and access note from the branch, and keep counts only. If it was pushed, delete the branch on GitHub and open a fresh one: a later commit does not remove it from history.

The tool does not report first-time fix or SLA attainment

Write "not reported". Session 6 then uses the module's own figure as the baseline. Never back-fill a figure from memory.

Step 2

Session 1: Test the two pitfalls on your own data

20 minutes

Why

Field service fails in two classic ways: an installed base typed in by hand, so warranty cannot be proved and nobody knows which unit shipped, and schedules that ignore driving time, so a technician is promised in two towns at once. Testing both on ten real assets and one real day tells you how much the module will fix, and gives the dispatcher and the service manager numbers they recognise.

Do this

Pick 10 installed assets in the tool. For each, look up its serial in your own shipping records (packing lists, sales orders or your ERP) and write exact, near (a typo, a dash) or no match, and whether the tool's asset carries the order that shipped it. Then take one technician's day with five or more appointments: for each back-to-back pair, the gap the schedule allows and the driving time from a map you already use. Then:

Paste into Claude Code, after replacing the <...> parts
Add to docs/fsm-inventory.md on the same branch:
8. Pitfall 1, installed base and shipped serials: 10 assets checked on <date>; exact <n>, near <n>, no match <n>; matched share <n>/10; assets carrying the shipping order <n>/10.
9. Pitfall 2, travel time: technician <job title>, <date>, <n> appointments; pairs where the gap is shorter than the drive: <n> of <n>; the worst: gap <minutes> against a drive of <minutes>.
10. Baseline: 10 recently closed jobs (job numbers only), first visit fixed <n>/10; another job on the same asset within 30 days <n>/10.

Push to the same pull request.

The dispatcher and the service manager read it; owner two approves; it merges.

You will see recreated screen

github.com/acme-ops/acme-platform/pull/81/files
ConversationCommitsFiles changed
docs/fsm-inventory.md
8. Pitfall 1Exact 6, near 3, no match 1. Assets carrying the shipping order: 2 of 10.1
9. Pitfall 2Pairs shorter than the drive: 3 of 5. Worst: 15 minutes allowed for a 40-minute drive.2
The pitfalls on GitHub, as the service manager reads them.
  1. Six of ten provable is the case for creating assets from shipments.
  2. The day the dispatcher already knows goes wrong, now in numbers.

Check it worked

docs/fsm-inventory.md is on main with both pitfalls counted and a ten-job baseline, read by the dispatcher and the service manager.

If it goes wrong

You have no shipping records to compare with

Write which system would hold them (the ERP, the accounts package, packing lists in a drawer) and who owns it. Session 5 matches assets to shipped serials; it needs that source.

The dispatcher says travel is "in their head"

That is the finding. Write it down as it was said, with the one day you measured.

Knowledge check

Why does an installed asset keep serial_unit_id and sales_order_ref as well as the serial text?

The installed base starts at the shipment

An installed asset is a customer-owned product in service, created from the shipment of its serial: the serial unit, the order that shipped it, the service site, optionally a parent (a drive module hangs under its pump), and warranty dates from the shipping date. A contract lists the assets it covers, with response and resolution hours and the business hours its clock counts. When a job is booked, the entitlement check decides whether it is covered.

From a shipment to an installed assetSales order SO-1 ships a pump unit and a drive module as two serial shipments; each becomes an installed asset, the drive module a child of the pump, with warranty dates counted from the shipping date. A pitfall box warns against an installed base typed in by hand. Sales order SO-1shipped 2025-09-01ship-to address: Site AShipment: SN-1001Pump unit,serial controlledShipment: SN-1001-DDrive module,serial controlledAsset SN-1001warranty 2025-09-01to 2026-08-31Asset SN-1001-Dchild of SN-1001,same datesINSTALLED ASSETSwarranty_end = shipping date + the item's warranty months − 1 day (12 months from 2025-09-01 ends 2026-08-31)Pitfall 1: an installed base disconnected from shipped serialsTyped by hand, an asset has no order and no serial unit, so nobody can prove its warranty
One order, two assets. Sales order SO-1 shipped a pump unit and its drive module. Each serial becomes an installed asset, the drive a child of the pump, with the warranty from the shipping date.
The entitlement checkA job is booked for an asset on a date. If warranty dates are set and include the date, it is covered by warranty and not billable. Otherwise, if an active contract lists the asset and includes the date, it is covered by contract and not billable. Otherwise it is not covered and billable. Job bookedWarranty dates set andthe date between them(both ends included)?yesUnder warranty: not billablenoAn active contract liststhe asset, and its startand end include the date?yesUnder contract: not billablenoNot covered: billablecontract_id is anyactive contractcovering the date,even when thewarranty applies:it still sets the SLA
The entitlement check, at the booking date. Warranty first, then an active contract that lists the asset; only an asset covered by neither is billable. Both ends of every date range count.

Thirteen tables on the shared spine

The module keeps no customer list, parts list, people table or stock location of its own. It points at spine tables (core_party, core_address with latitude and longitude, core_site, core_person, core_item, core_serial_unit, core_storage_location, core_calendar, core_shift_definition, core_attachment, core_number_sequence, core_event_outbox), and parts move through the inventory ledger of module M12 (inv_sales_order, inv_inventory_transaction, inv_inventory_balance). Every table also has the spine's standard columns, not repeated below, with site_id in place of the specification's tenant_id, so each table keeps one simple access rule. An arrow (→) is a foreign key; req means required; a list after a colon is the only values allowed; a soft link is a uuid with no foreign key, because that module may not be installed.

The thirteen tablesThirteen fsm_ tables in four groups: where and what (territory, service site, installed asset), cover (contract, contract asset, PM plan), the work (work order, appointment, service line, customer signoff) and people and parts (technician, parts request, warranty claim), all resting on the shared core_ tables. WHERE AND WHATfsm_territoryfsm_service_sitefsm_installed_assetCOVERfsm_service_contractfsm_contract_assetfsm_service_pm_planTHE WORKfsm_service_work_orderfsm_appointmentfsm_service_linefsm_customer_signoffPEOPLE AND PARTSfsm_technicianfsm_parts_requestfsm_warranty_claimTHE SPINE · USED, NEVER REPEATEDcore_party · core_address · core_item · core_serial_unitcore_person · core_storage_location · core_attachment
The thirteen tables. Where and what, cover, the work, and people and parts, all resting on the shared core_ tables.
TableOne row isColumns
fsm_territoryA service territoryname req, unique; geo_polygon json; base_site_id → core_site; manager_id → core_person
fsm_service_siteA customer location servedparty_id → core_party req; address_id → core_address req; name req; access_notes; timezone; territory_id → fsm_territory
fsm_installed_assetA customer-owned product in serviceparty_id → core_party req; service_site_id → fsm_service_site; item_id → core_item req; serial_no; serial_unit_id → core_serial_unit; parent_installed_asset_id → fsm_installed_asset; installed_at date; warranty_start date; warranty_end date; status req: active, inactive, decommissioned, returned; sales_order_ref uuid (soft link)
fsm_service_contractA contract with its SLA and entitlementscontract_no req, unique; party_id → core_party req; contract_type req: warranty, maintenance, full_service, time_and_materials, subscription; start_at date req; end_at date req; sla_response_hours num; sla_resolution_hours num; entitlements json; billing_terms; status req: draft, active, expired, cancelled
fsm_contract_assetAn asset a contract coversservice_contract_id → fsm_service_contract req; installed_asset_id → fsm_installed_asset req
fsm_technicianA field technician's profileperson_id → core_person req, unique; territory_id → fsm_territory; home_lat num; home_lon num; vehicle_location_id → core_storage_location; calendar_id → core_calendar; active bool req
fsm_service_work_orderA field service jobswo_no req, unique; party_id → core_party req; service_site_id → fsm_service_site req; installed_asset_id → fsm_installed_asset; service_contract_id → fsm_service_contract; case_ref uuid (soft link to M19); swo_type req: install, repair, preventive, inspection, warranty, upgrade, decommission; priority req: p1, p2, p3, p4; status req: new, scheduled, dispatched, en_route, on_site, completed, incomplete, cancelled, ready_to_bill, billed; problem_description; resolution; billable bool req; sla_due_at ts; first_time_fix bool
fsm_appointmentOne scheduled visitservice_work_order_id → fsm_service_work_order req; technician_id → fsm_technician req; window_start ts; window_end ts; scheduled_start ts req; scheduled_end ts req; actual_arrival ts; actual_departure ts; travel_minutes num; status req: scheduled, dispatched, en_route, on_site, completed, cancelled, no_access
fsm_service_lineA labour, part, travel or expense lineservice_work_order_id → fsm_service_work_order req; line_type req: labor, part, travel, expense; item_id → core_item; description; qty req; unit_price money; billable bool req; warranty_covered bool req; storage_location_id → core_storage_location
fsm_customer_signoffThe customer's signature and the reportappointment_id → fsm_appointment req; signer_name req; signed_at ts req; signature_attachment_id → core_attachment; report_attachment_id → core_attachment; satisfaction int
fsm_parts_requestA technician's parts requesttechnician_id → fsm_technician req; item_id → core_item req; qty req; needed_by ts; service_work_order_id → fsm_service_work_order; status req: requested, picked, shipped, received, cancelled; fulfil_from_location_id → core_storage_location
fsm_warranty_claimA claim on a supplier for a failed partclaim_no req, unique; service_work_order_id → fsm_service_work_order req; installed_asset_id → fsm_installed_asset; supplier_party_id → core_party req; failed_item_id → core_item; amount_claimed money; amount_recovered money; status req: draft, submitted, approved, rejected, paid
fsm_service_pm_planA preventive plan for an assetinstalled_asset_id → fsm_installed_asset req; service_contract_id → fsm_service_contract; interval_months int req; checklist_template_ref uuid (soft link to M01); next_due_at date; active bool req
Step 3

Session 2: Check the spine and the ledger, and add only what is missing

20 minutes

Why

The fsm_ tables point at shared spine tables and at the inventory ledger. If one is missing the module's migration fails; if the module makes its own copy, the business has two customer lists and two stock counts that drift apart. Checking first, and adding only what is missing in its own migration, keeps one of everything and lets other modules reuse it.

Do this

Paste into Claude Code
Read docs/SCHEMA-PLAN.md, docs/naming-standard.md and every file in supabase/migrations. Change nothing yet.

The field service module needs:
- spine tables: core_party (party_type), core_address (with lat and lon), core_site, core_person (person_type, job_role_id, ext), core_job_role, core_item (item_type, ext), core_serial_unit, core_storage_location (location_type: warehouse, vehicle, customer_site), core_calendar, core_shift_definition (start, end, paid_break_min), core_attachment (with sha256), core_comment, core_notification, core_number_sequence, core_event_outbox, core_audit_log; and core_current_tenant(), core_touch_row(), core_audit_row() and a security definer number function;
- the inventory ledger of module M12: inv_sales_order, inv_inventory_transaction (txn_no unique per tenant; at least one of from_location_id and to_location_id; append-only, a reversal is a new row naming reversal_of_id; a unique partial index on ref_type, ref_id, txn_type where reversal_of_id is null and ref_type starts with fsm_) and inv_inventory_balance, kept only by a security definer trigger on the ledger that ignores customer_site locations.

Show me a table: each one exists, exists under another name, or is missing. If an existing table overlaps, propose how they relate and wait for my answer.

When I answer, on a new branch fsm/spine, add a section "## M18 Field service" to docs/spine-map.md, the one spine map every module shares (if it does not exist yet, create it with the heading "# Spine map" first; never a separate map file for this module), holding that table and my answers, and saying that the fsm_ tables carry site_id in place of the specification's tenant_id. Then write ONE migration (npx supabase migration new fsm_spine) that adds only what is missing, following the naming standard, with row-level security on and no policies, every function security definer with set search_path = '', and pgTAP tests in supabase/tests/fsm_spine.test.sql, including that a ledger row cannot be updated or deleted. Do not alter any existing table and do not connect to any Supabase project. Push, open a pull request titled "Spine and ledger for field service" with the map and the migration, wait for the schema check and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ Exist (from M14): core_item, core_party, core_person, core_attachment, core_number_sequence, core_event_outbox, the four functions. Missing: core_address, core_site, core_serial_unit, core_storage_location, core_calendar, core_shift_definition, core_notification, and the three inv_ tables.1
⏺ Bash(npx supabase migration new fsm_spine)
⎿ Created new migration at supabase/migrations/20261118091000_fsm_spine.sql
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m12s
⏺ Pull request #82 is green: 7 spine tables and the minimal ledger, 36 tests, including update and delete refused on the ledger. No existing table was changed.2
Claude Code reports first, and waits where a decision is yours.
  1. Tables another module already made are reused, not copied.
  2. The ledger is append-only from its first day: a mistake is a reversing row.

Check it worked

Pull request Spine and ledger for field service is green, adds the M18 section to docs/spine-map.md, one migration and one test file, and changes no existing table.

If it goes wrong

It put the spine or the ledger inside an fsm_ migration

Say: Move them into their own migration, fsm_spine, merged first. Other modules use them; they must not depend on field service being installed.

It wants a stock column on the technician or the van

Say: Stock moves only through the ledger. No fsm_ table holds a count. A number someone can edit is a number nobody can trust.

The check is red: a function is used before it is created

Say: Order the migration so functions come before the tables and triggers that use them, and run the check again.

Step 4

Session 2: The thirteen tables and the rules the database holds

30 minutes

Why

Writing the tables, the rules and the tests that prove each rule in one pull request means the proof arrives with the change. Rules in the database (one asset per serial, one open job per preventive plan, a sign-off that can never be changed) hold for every screen, the importer and any agent, including ones not built yet. A rule nobody tests is a rule a later change can quietly remove.

Do this

Paste into Claude Code
Read docs/naming-standard.md, docs/matrix.json and the spine migration on main.

On a new branch fsm/tables, add the tables below under "### Tables" in the M18 section of docs/spine-map.md (never a separate tables file), then ONE migration (npx supabase migration new fsm_tables). Every table: id uuid primary key; site_id -> core_site req (in place of the specification's tenant_id), indexed; created_at, created_by, updated_at, updated_by, row_version, archived_at, ext jsonb; row-level security on, no policies; the core_touch_row() and core_audit_row() triggers. req = not null; a list after a colon = a check; qty = numeric(18,6); money = numeric(18,4); num = numeric; ts = timestamptz.

fsm_territory: name req, unique per site; geo_polygon jsonb; base_site_id -> core_site; manager_id -> core_person.
fsm_service_site: party_id -> core_party req; address_id -> core_address req; name req; access_notes; timezone; territory_id -> fsm_territory.
fsm_installed_asset: party_id -> core_party req; service_site_id -> fsm_service_site; item_id -> core_item req; serial_no; serial_unit_id -> core_serial_unit; parent_installed_asset_id -> fsm_installed_asset; installed_at date; warranty_start date; warranty_end date; status req: active, inactive, decommissioned, returned; sales_order_ref uuid (no foreign key).
fsm_service_contract: contract_no req, unique per site; party_id -> core_party req; contract_type req: warranty, maintenance, full_service, time_and_materials, subscription; start_at date req; end_at date req; sla_response_hours num; sla_resolution_hours num; entitlements jsonb; billing_terms; status req: draft, active, expired, cancelled.
fsm_contract_asset: service_contract_id -> fsm_service_contract req; installed_asset_id -> fsm_installed_asset req.
fsm_technician: person_id -> core_person req, unique; territory_id -> fsm_territory; home_lat num; home_lon num; vehicle_location_id -> core_storage_location; calendar_id -> core_calendar; active bool req.
fsm_service_work_order: swo_no req, unique per site; party_id -> core_party req; service_site_id -> fsm_service_site req; installed_asset_id -> fsm_installed_asset; service_contract_id -> fsm_service_contract; case_ref uuid (no foreign key); swo_type req: install, repair, preventive, inspection, warranty, upgrade, decommission; priority req: p1, p2, p3, p4; status req: new, scheduled, dispatched, en_route, on_site, completed, incomplete, cancelled, ready_to_bill, billed; problem_description; resolution; billable bool req; sla_due_at ts; first_time_fix bool.
fsm_appointment: service_work_order_id -> fsm_service_work_order req; technician_id -> fsm_technician req; window_start ts; window_end ts; scheduled_start ts req; scheduled_end ts req; actual_arrival ts; actual_departure ts; travel_minutes num; status req: scheduled, dispatched, en_route, on_site, completed, cancelled, no_access.
fsm_service_line: service_work_order_id -> fsm_service_work_order req; line_type req: labor, part, travel, expense; item_id -> core_item; description; qty req; unit_price money; billable bool req; warranty_covered bool req; storage_location_id -> core_storage_location.
fsm_customer_signoff: appointment_id -> fsm_appointment req; signer_name req; signed_at ts req; signature_attachment_id -> core_attachment; report_attachment_id -> core_attachment; satisfaction int.
fsm_parts_request: technician_id -> fsm_technician req; item_id -> core_item req; qty req; needed_by ts; service_work_order_id -> fsm_service_work_order; status req: requested, picked, shipped, received, cancelled; fulfil_from_location_id -> core_storage_location.
fsm_warranty_claim: claim_no req, unique per site; service_work_order_id -> fsm_service_work_order req; installed_asset_id -> fsm_installed_asset; supplier_party_id -> core_party req; failed_item_id -> core_item; amount_claimed money; amount_recovered money; status req: draft, submitted, approved, rejected, paid.
fsm_service_pm_plan: installed_asset_id -> fsm_installed_asset req; service_contract_id -> fsm_service_contract; interval_months int req; checklist_template_ref uuid (no foreign key); next_due_at date; active bool req.

Rules the database holds:
1. One asset per item and serial (partial unique index where serial_no is not null); an asset is never its own parent.
2. swo_no and claim_no come from core_number_sequence through the security definer number function; sequences SWO- and WC- padded to 4.
3. A contract's end_at is not before start_at; an appointment's scheduled_end is after scheduled_start.
4. One open job per preventive plan: a partial unique index on ext->>'pm_plan_id' while status is new, scheduled, dispatched, en_route, on_site or incomplete.
5. fsm_customer_signoff refuses any update or delete.
6. Delete is refused on every fsm_ table.
Also write docs/fsm-rules.md with the two JSON shapes the rules will read: the contract's entitlements (covers: a list of line types; business_hours: timezone, a weekly schedule of opening periods, holidays) and the technician's ext (skills, van_min per item, replenish_from).

pgTAP tests in supabase/tests/fsm_tables.test.sql: every table exists with row-level security on; and the database refuses: an asset with status broken; a work order with swo_type visit; a second asset with the same item and serial; a contract ending before it starts; an appointment ending before it starts; two open jobs with the same pm_plan_id (in a rolled-back transaction); an update of a sign-off. Add the thirteen tables to docs/matrix.json with no rights yet. Do not connect to any Supabase project.

Push, open a pull request titled "Field service tables", wait for the schema check, and tell me the result in plain words. If it fails, fix it and try again before reporting.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase migration new fsm_tables)
⎿ Created new migration at supabase/migrations/20261119093000_fsm_tables.sql
⏺ Write(supabase/migrations/20261119093000_fsm_tables.sql)
+create unique index fsm_one_open_job_per_plan on public.fsm_service_work_order
+ (site_id, (ext->>'pm_plan_id')) where status in
+ ('new','scheduled','dispatched','en_route','on_site','incomplete');
+create trigger fsm_signoff_frozen before update or delete on public.fsm_customer_signoff
1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m40s
⏺ Pull request #83 is green: 13 tables, 6 rules, 61 tests, including the seven refusals. Nothing is readable through the website until Session 3 adds access rules.2
Two rules that matter, in the database itself, and the tests that try to break them.
  1. A repeated run of the preventive engine can never make a second open job for one plan.
  2. Every refusal is a test that passes only if the database says no.

Check it worked

Pull request Field service tables is green; the summary names the seven refusals; the M18 section of docs/spine-map.md, docs/fsm-rules.md and the matrix rows are in the same pull request.

Fastest path

One prompt with the tables, the rules, the tests and "wait for the check and fix it before reporting" replaces half a dozen rounds of adding one rule at a time.

If it goes wrong

The duplicate-serial test passes when it should fail

A unique rule on a column that can be empty needs care: Postgres treats two empty values as different. Say: Show me the duplicate test failing with the index removed and passing with it.

After merging main into the branch, a rule or its test has gone

We hit this: undoing a batch on main silently removed another branch's schema change, with no conflict reported. Say: I merged main. List every table, rule and test this branch adds and confirm each is still there.

Claude Code reports green but the check on GitHub is red

Say: The schema check is red. Run gh pr checks, read the failed log, fix the cause and wait for green before you report.

The seed: a small service business you can count by hand

Every number the later steps check comes from one fixed, made-up worked example, kept as a test fixture (the development project's seed holds the same rows shifted onto today), on one line of longitude so distances can be done by hand: two territories (North and South), three customer sites (Site A at latitude 41.10 and Site B at 41.30 for Customer One, Site C at 40.60 for Customer Two), five installed assets (SN-1001 to SN-1004, with SN-1001-D a child of SN-1001; SN-1005 is shipped but not yet installed), three contracts (C-100 active with business hours, C-200 expired, C-300 a draft), three technicians, three preventive plans, eight completed jobs and two dispatched ones.

Asset and dateEntitlement resultWhy
SN-1001 on 2026-06-18Warranty, contract C-100, not billableWarranty runs 2025-09-01 to 2026-08-31; C-100 is active and lists it
SN-1002 on 2026-06-18Contract C-100, not billableWarranty ended 2025-01-14; the contract covers it
SN-1003 on 2026-06-11Warranty, not billableThe last day of its warranty counts: both ends are included
SN-1003 on 2026-06-12Not covered, billableWarranty over, and C-200 has expired
SN-1004 on 2026-06-18Not covered, billableNo warranty dates, and C-300 is only a draft
Step 5

Session 2: Seed the lab business, then try it all on the development project

25 minutes

Why

A fixed, made-up worked example makes every later number checkable by hand, and a test that asserts its counts from the fixture stops the seed and the later steps drifting apart. Trying the migrations and the seed on the development project yourself, before merge, means production only ever receives what has run cleanly on a real Supabase project. Seed rows never reach production: the pipeline applies migrations, not seeds.

Do this

Paste into Claude Code
On a new branch fsm/seed, write the worked example below in two places. tests/fixtures/fsm-worked.json holds it with its fixed dates in one time zone (write it in docs/fsm-rules.md); every test with a date, an SLA clock or a measure loads it, never the seed. supabase/seeds/fsm.sql holds the same rows shifted onto today (every date moved by the same whole number of weeks, so weekdays stay weekdays, the holiday moves with them and the two dispatched jobs fall on the coming Monday), listed under [db.seed] sql_paths in supabase/config.toml so CI and scripts/seed-dev load it, never appended to supabase/seed.sql; the deploy workflow never seeds production. Made-up names only, marked SYNTHETIC (a header saying so, and ext synthetic true on every row), every insert skipping a row that already exists, so it is safe to run twice. Money figures are lab values.
- Sites North depot and South depot. Customer One, Customer Two (customer), Supplier One (supplier). Addresses on longitude -81.50: Site A 41.10 and Site B 41.30 (Customer One), Site C 40.60 (Customer Two). Territories North (Sites A, B) and South (Site C), managed by the service manager.
- Items: PUMP-UNIT (serial controlled, skills pump, warranty_months 12), DRIVE-MODULE (serial controlled, skills controls, warranty_months 12), PUMP-SEAL (list_price 40), FILTER (20), LABOR-HOUR (100), TRAVEL-HOUR (50). Serial units SN-1001, SN-1001-D, SN-1002, SN-1003, SN-1004, SN-1005.
- Locations WH-1 (warehouse), VAN-1, VAN-2, VAN-3 (vehicle), CUSTOMERS (customer_site). Calendar FIELD with shift DAY 07:00 to 17:00, paid_break_min 60 (540 available minutes).
- People: Technician One (North, home 41.00, VAN-1, skills pump and controls), Technician Two (North, home 41.40, VAN-2, skills pump), Technician Three (South, home 40.50, VAN-3, skills pump and controls), a dispatcher, a service manager, a customer contact of Customer One. Every technician: van_min PUMP-SEAL 2 and FILTER 2, replenish_from WH-1.
- Sequences: SWO- next 11, WC- next 1, TXN- (padding 6) next 1.
- Sales orders: SO-1 (Customer One, 2025-09-01, Site A: SN-1001, SN-1001-D), SO-2 (2024-01-15, Site A: SN-1002), SO-3 (2025-06-12, Site B: SN-1003), SO-4 (Customer Two, 2024-03-01, Site C: SN-1004), SO-5 (2026-06-10, Site C: SN-1005). Six shipment ledger rows to CUSTOMERS, and eight opening adjustments: VAN-1 3 seals 2 filters, VAN-2 1 seal 2 filters, VAN-3 2 seals 2 filters, WH-1 20 of each (14 ledger rows, 8 balance rows).
- Installed assets: SN-1001 Site A, warranty 2025-09-01 to 2026-08-31; SN-1001-D its child, same dates; SN-1002 Site A, 2024-01-15 to 2025-01-14; SN-1003 Site B, 2025-06-12 to 2026-06-11; SN-1004 Site C, no warranty dates. Each with its serial unit and order. None for SN-1005.
- Contracts: C-100 (Customer One, maintenance, active, 2026-01-01 to 2026-12-31, response 4 h, resolution 24 h, covers labor and travel, Mon to Fri 08:00 to 17:00, holiday 2026-06-19) covering SN-1001 and SN-1002; C-200 (Customer One, maintenance, expired, 2025, response 8, resolution 48, covers labor, no business hours) covering SN-1003; C-300 (Customer Two, full_service, draft, 2026-07-01 to 2027-06-30, covers labor, travel, part, same hours as C-100) covering SN-1004. PM plans: PM-A on SN-1002 under C-100, every 6 months, next 2026-06-22, active; PM-B on SN-1003, 12 months, next 2026-09-01, active; PM-C on SN-1004 under C-300, 6 months, next 2026-05-01, not active.
- Eight completed jobs with their visits, sign-offs on the last visit, and ext.response_due_at and sla_due_at from C-100's hours:
  SWO-0001 repair p2 SN-1002 C-100, booked Fri 2026-05-29 14:00, due Mon 06-01 09:00 / Wed 06-03 11:00; Technician One Mon 06-01, scheduled 08:30-10:30, on site 08:45-10:25, travel 30; fixed first time.
  SWO-0002 preventive p3 SN-1002 C-100, no SLA; Technician One Tue 06-02 13:00-15:00, on site 13:00-14:30, travel 25; first time.
  SWO-0003 repair p2 SN-1002 C-100, booked Fri 06-05 16:00, due Mon 06-08 11:00 / Wed 06-10 13:00; Technician Two Mon 06-08 10:00-12:00, on site 10:05-12:00, travel 35, not fixed; Tue 06-09 14:00-16:00, on site 14:00-15:30, travel 35, fixed; not first time.
  SWO-0004 repair p1 SN-1002 C-100, booked Mon 04-27 08:30, due 04-27 12:30 / Wed 04-29 14:30; Technician Two Wed 04-29 15:00-17:00, on site 15:00-16:30, travel 30; first time; SLA missed.
  SWO-0005 inspection p4 SN-1002 C-100, no SLA; Technician One Thu 06-04 08:00-09:00, on site 08:00-08:50, travel 15; first time.
  SWO-0006 warranty p2 SN-1001 (covered_by warranty, under C-100), booked Tue 06-02 08:00, due 12:00 / Thu 06-04 14:00; Technician One Tue 06-02 10:00-12:00, on site 10:00-11:45, travel 30, not fixed; Fri 06-05 10:00-11:30, on site 10:10-11:20, travel 30, fixed; not first time; resolution missed.
  SWO-0007 warranty p3 SN-1003, no contract, no SLA; Technician Two Mon 06-08 13:00-14:00, on site 13:05-13:55, travel 20; first time.
  SWO-0008 repair p3 SN-1004, covered_by none, billable, no SLA; Technician Three Tue 06-09 09:00-10:00, on site 09:00-09:50, travel 60; first time.
- Nine service lines, ext history true, prices from list_price: SWO-0001 labor 2 and travel 0.5 (not billable) and one PUMP-SEAL from VAN-1 (billable); SWO-0006 labor 3, travel 1, one PUMP-SEAL, all warranty_covered; SWO-0008 labor 1, travel 1, one FILTER from VAN-3, all billable.
- Two dispatched jobs for Mon 2026-06-22 07:00 to 09:00: SWO-0009 repair p3 SN-1003 Site B, Technician One, billable, booked Thu 06-18 09:00; SWO-0010 repair p2 SN-1002 Site A, Technician Two, C-100, booked Thu 06-18 16:00, due Mon 06-22 11:00 / Wed 06-24 13:00.

Put the hand counts in tests/fixtures/fsm-counts.json and a test supabase/tests/fsm_seed.test.sql asserting, on the fixture and on the seed run twice: 2 territories, 3 sites, 5 assets, 3 contracts, 4 contract-asset links, 3 technicians, 3 PM plans, 10 work orders (8 completed, 2 dispatched), 12 appointments, 9 service lines, 8 sign-offs, 5 sales orders, 14 ledger rows, 8 balance rows. Push, open a pull request titled "Field service seed", wait for the checks, and tell me the result.

When it is green, apply the migrations and the seed to the development project yourself, in a terminal (not inside Claude Code): db push --include-seed loads the new seed file the first time; after that, npm run seed:dev reloads it. Never reset the database. The password is in the password manager as Supabase: acme-platform-dev database password.

Terminal or PowerShell
cd ~/code/acme-platform && git switch fsm/seed && git pull
Terminal or PowerShell
npx supabase link --project-ref tsrqponmlkjihgfedcba
Terminal or PowerShell
npx supabase db push --include-seed
Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor

The development project's Table Editor: open fsm_service_work_order.

You will see recreated screen

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.1
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261118091000_fsm_spine.sql • 20261119093000_fsm_tables.sql [Y/n] y2
Seeding data from supabase/seeds/fsm.sql...
Finished supabase db push.
The development project, never production. It lists what it will apply before it does.
  1. Check the reference is tsrqponmlkjihgfedcba. If it shows abcdefghijklmnopqrst, stop: that is production.
  2. Only the field service migrations should be listed. Anything else, answer n and ask why.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
fsm_appointmentfsm_installed_assetfsm_service_contractfsm_service_linefsm_service_work_order
fsm_service_work_order
1
swo_noswo_typestatusbillablefirst_time_fix
SWO-0001repaircompletedfalsetrue
SWO-0003repaircompletedfalsefalse
SWO-0008repaircompletedtruetrue
SWO-0010repairdispatchedfalse
The seeded jobs in the development project.
  1. Ten rows: eight completed, two dispatched for the coming Monday (2026-06-22 in the fixture).

Check it worked

The pull request is green; the development project shows the counts in tests/fixtures/fsm-counts.json; running the push again adds no rows. Then owner two approves, it merges, and the pipeline applies the migrations (not the seed) to production.

If it goes wrong

The terminal shows the production reference abcdefghijklmnopqrst

Answer n. Run npx supabase link --project-ref tsrqponmlkjihgfedcba again and read the reference before pushing. In this module only the pipeline changes production.

A later step expects a number the seed never made

We hit this in five Academy modules: exercises written against counts the seed did not create. Say: List every count tests/fixtures/fsm-counts.json promises and the seed line that creates each. Fix the seed, not the check.

Seed rows appear twice in the development project

Say: The seed added duplicates on a second run. Make every insert skip a row that already exists, on its natural key, and add a test that runs the seed twice.

Knowledge check

An asset's warranty ended yesterday, and the only contract that listed it has expired. A job is booked today. What does the entitlement check return?

Knowledge check

Where do you first apply a new field service migration and the seed?

References

  1. ISO 9001:2015, Quality management systems: requirements (clause 8.5.5, post-delivery activities). https://www.iso.org/standard/62085.html
  2. ISO 10002:2018, Customer satisfaction: guidelines for complaints handling in organizations. https://www.iso.org/standard/71580.html
  3. Salesforce Trailhead: Field Service basics. https://trailhead.salesforce.com/content/learn/modules/field_service_basics/field_service_basics_intro
  4. Supabase Docs: Seeding your database. https://supabase.com/docs/guides/local-development/seeding-your-database
  5. Supabase CLI reference: supabase db push. https://supabase.com/docs/reference/cli/supabase-db-push

Chapter 2 · Sessions 3 and 4

Who may do what, the screens, and a job from booking to billing

Session 3 writes the four field service roles into your role matrix, generates the access rules and builds four screens, including a phone screen that works with no signal. Session 4 builds the rules a job runs on (cover, the service clock, dispatch with travel time), completes a job offline with parts reaching the van's stock once, hands billable lines to accounting, and checks the measures against a hand count.

40 minSteps 6–11About 3 hours 15 minutes hands-on in these two sessions

By the end of this chapter you can

  • Add the four roles, their scopes and four machine accounts to docs/matrix.json, and test the generated rules both ways.
  • Build the dispatch board, the offline phone screen, the customer sign-off and the manager's desk, and pass the phone check.
  • Prove the entitlement check, the service clock and dispatch with travel time against tables worked by hand.
  • Complete a job offline so parts, time and the signature arrive once, hand billable lines on, and match the four measures.

Four roles, four machine accounts, three scopes

RoleWhat it doesScreenScope
dispatcherBooks and schedules jobs; never releases to billing or changes billable/service/dispatchWhole site
technicianDoes the work on a phone, often offline; reads past jobs on its own jobs' assets/service/workOwn jobs, own van
service_managerContracts, territories, billing release and waivers, warranty claims, measures/service/manage, /service/dispatchWhole site
customerA customer's contact: sees and signs off only its own company's jobs; never prices/service/signoffOwn party
fsm_install_route, fsm_pm_engine, fsm_stock_routeMachine accounts: assets from shipments; preventive jobs and the SLA watch; parts to the ledger and replenishmentNoneNarrow, per job
fsm_importThe importer, only through import-fsm.yml (Sessions 5 and 6), its password set by a person and named in docs/KEYS.md; set NOLOGIN at cut-overNoneInsert only

Remember how Postgres applies a right: an update only finds rows the role can read, and the changed row must still pass the read rule; an insert that hands its new row back needs the read right too [1]. So each role reads every status of what it updates, and the narrower conditions (which status moves are allowed) live in the Session 4 status trigger.

Step 6

Session 3: The roles into the matrix, the scopes in the generator, tested both ways

35 minutes

Why

Every access rule is generated from docs/matrix.json, so a right written there is enforced by the database for every screen, route and import, and a right missing there stops a technician in the middle of a job. The three scopes (own jobs, own van, own party) are what keep a technician out of other technicians' work and a customer out of another company's jobs and your prices; testing them both ways proves it.

Do this

Paste into Claude Code
Read docs/matrix.json, scripts/gen-policies.mjs, supabase/tests/access.test.sql and the M18 section of docs/spine-map.md.

On a new branch fsm/access:
1. Add three scopes to the generator, each with tests: own jobs (work orders with an appointment held by the signed-in technician), own van (the storage location on the technician's row), own party (rows whose party_id is the party in the signed-in contact's core_person.ext; appointments, sign-offs and attachments follow their work order).
2. Add the roles to docs/matrix.json, following how it already names roles and rights. Nobody gets delete.
- dispatcher (whole site): read the fsm_ tables except claims, sites, people (names only), items, van balances; insert work orders (status new, through the booking route) and appointments; update work orders (new to scheduled to dispatched, incomplete back to scheduled, cancel, priority, problem, required skills before on site), appointments, and parts requests to picked, shipped or cancelled.
- technician (own jobs, own van): read its jobs, their sites, assets, contracts, plans, lines and sign-offs, and past jobs on those assets (read only); its van's balance; insert service lines, sign-offs, parts requests (requested), attachments and comments on own jobs; update its appointments (arrival, departure, travel, the moves to en_route, on_site, completed, no_access) and its jobs (en_route, on_site, completed, incomplete, resolution, first_time_fix).
- service_manager (whole site): read everything in the module and the ledger; insert and update territories, sites, assets, contracts and their assets, technicians, PM plans, warranty claims, lines before billing, parts requests; on work orders also billable, service_contract_id, sla_due_at, ext.billing_waived (with a core_comment) and completed to ready_to_bill to billed.
- customer (own party): read its work orders, appointments, sites, assets, contracts, sign-offs and its reports; insert a sign-off for its own completed appointment with a typed name. Nothing on service lines or technicians.
- machine accounts: fsm_install_route (read shipments and serial units, insert installed assets); fsm_pm_engine (read plans and jobs, update next_due_at, insert work orders); fsm_stock_route (read lines, jobs, appointments, technicians, requests, calendars, balances and ledger; insert ledger rows and parts requests; update only a line's ext.inventory_txn_id and requests to received); fsm_import (insert only: the module's tables, a stand-in technician; read what it matches; never update or delete). Every machine account signs in with its own password, set by a person and listed by name in docs/KEYS.md, never the service key.
- core_event_outbox, core_audit_log, inv_inventory_balance and core_number_sequence: no role gets any right; triggers and security definer functions write them.
3. Run node scripts/gen-policies.mjs (Session 8). Add supabase/tests/fsm_access.test.sql with one allowed and one refused case per role and table, and these refusals: a technician reading another technician's job; the Customer One contact reading Customer Two's jobs or any service line; a dispatcher moving a job to ready_to_bill; a technician whose membership has ended reading anything. For an update, check the row really changed.
4. Write docs/fsm-rights-check.md: one line per action of Sessions 4 to 6 (book, generate preventive jobs, dispatch, complete offline, post parts, release and export billing, replenish, import), who does it, the table, the action and the matrix cell; and a test that fails if a line has no cell, skipping lines marked retired.

If the matrix cannot express a rule, stop and tell me which before writing anything around it. Push, open a pull request titled "Field service access rules", wait for the checks and tell me the result.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/matrix.json)
+"customer": { "fsm_service_work_order": { "read": { "scope": "own_party" } },
+ "fsm_service_line": {} }
1
⏺ Bash(node scripts/gen-policies.mjs)
⎿ Wrote supabase/migrations/20261124080000_policies.sql (71 policies)
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass · access / rights-check pass
⏺ Pull request #85 is green. 118 access tests. The Customer One contact sees none of Customer Two's jobs and no service line; a technician sees only its own jobs; the dispatcher cannot release to billing. docs/fsm-rights-check.md: 24 lines, each with a cell.2
The scopes are generated once and tested from both sides.
  1. The customer has no right at all on service lines, so a customer never reads your prices.
  2. Allowed and refused are both tested. A test that only checks refusals passes even when nothing works.

Check it worked

Pull request Field service access rules is green, including the four named refusals and the rights-check test.

If it goes wrong

A technician's Complete reports success but the job does not change

We hit this in three Academy modules: an update only finds rows the role can read, and the changed row must still pass the read rule. Say: Make the technician's read rule cover the job before and after the move, and add a test that the row really changed.

The "policies" or "rights-check" check fails though your change looks right

It compares a generated list with the code. Say: Open the failing check's log, regenerate the list it compares against, commit it, and show me what changed.

Claude Code loosened a test to make it pass

Say: Never edit, skip or loosen a test or a check to get to green. Put it back, and explain why you think it is wrong; I will decide.

Step 7

Session 3: Four screens, and a phone screen that works with no signal

40 minutes

Why

A technician is often where there is no signal, and a job recorded on paper and typed later loses parts, times and signatures. Reusing the Foundation offline outbox, with an id made on the phone for every entry, means a job completed in a basement arrives once, however many times the phone retries. Building every screen behind the default-deny sign-in and testing it at phone width, with gloves in mind, is what makes it usable on the van.

Do this

Paste into Claude Code
Read node_modules/next/dist/docs/ first: this Next.js version differs from older guides, and request middleware lives in proxy.ts. Then read proxy.ts, lib/access/routes.ts, docs/matrix.json and the operator screens and offline outbox from Foundation Session 12.

On a new branch fsm/screens, add four screens, each listed in docs/matrix.json with its roles and regenerated into lib/access/routes.ts with scripts/gen-routes.mjs:
1. /service/dispatch (dispatcher, service_manager): each technician's day in time order, and jobs waiting; on a desktop drag a job onto a technician; on a phone the same move is two taps.
2. /service/work (technician): today's and the next days' jobs; one job with site, asset, history, problem; buttons On my way, Arrived, Add part, Add time, Photo, Resolution, Customer signs, Complete. Save the jobs, sites, assets, history and the van's parts to IndexedDB at sign-in with a "last updated" time, and put every action in the Session 12 outbox with an id from crypto.randomUUID(), so a repeat send adds nothing. Main buttons 64 px for gloves.
3. /service/signoff (customer; and the same component inside /service/work, handed to the customer): its own completed jobs, the report, a typed name and a satisfaction score.
4. /service/manage (service_manager): contracts, billing release, claims and measures.
Every read and write uses the signed-in person's session, never the secret key; authors and times come from the session and the server. Customer names and addresses never go to the logs. If a value is not stored, show "No data".

Add screen tests at 360 and 390 px (no sideways scroll, 44 px targets, 16 px fields), per screen a signed-out request landing on sign-in and a refused role, and a test with the browser offline that queues an action and sends it once on reconnect. Push, open a pull request titled "Field service screens", wait for the checks, and give me the preview link.

Open the preview on your phone, sign in as yourself, and put the phone in airplane mode on /service/work: the screen must still open. Then sit a dispatcher at the board and a technician at the phone screen, and do not explain. Write down where each stops.

You will see recreated screen

acme-platform-git-fsm-screens-acme-ops.vercel.app/service/work
SWO-0010 · Repair · Site A
AssetSN-1002 Pump unit
CoverContract C-100
Arrived
Add part
Customer signs2
The technician's phone screen with no signal: the job is still there, and the queue waits.
  1. Actions queue on the phone with their own ids and send once when the signal returns.
  2. The customer signs on the technician's phone; the image is uploaded with the entry.

You will see recreated screen

claude — acme-platform
⏺ I read the proxy guide in node_modules/next/dist/docs/ and the Session 12 outbox in lib/offline/. I extended the outbox with field service actions instead of writing a new queue.1
⏺ Bash(gh pr checks --watch)
⎿ screens / phone pass · screens / offline-once pass
⏺ Pull request #86 is green with 22 screen tests. Offline: an action queued with no network sent once on reconnect and once more on a forced retry; the server kept one copy.
Claude Code reuses the Foundation outbox instead of writing a second one.
  1. One offline queue for the whole platform. Two would mean two ways for data to be lost.

Check it worked

The pull request is green with the phone, refused-role and offline-once tests; the preview's phone screen opens in airplane mode; you have the dispatcher's and technician's notes.

If it goes wrong

Claude Code creates middleware.ts

Say: Read node_modules/next/dist/docs/ for this version. Request middleware is proxy.ts here; use the existing one.

The phone screen is blank in airplane mode

The data was never saved to the phone. Say: Save the next days' jobs and the van's parts to IndexedDB at sign-in, show the last updated time, and add a test that opens the screen with the network off.

A link on the new screens opens a blank 404

We hit this: a link that compiles is not a link that resolves. Say: Open every page and every link on the four screens as each role and list every 404 or error.

The preview asks you to sign in to Vercel

That is Vercel's deployment protection on previews, not your code. Sign in with your team account.

Knowledge check

A phone sends the same completed-job entry twice because the first confirmation was lost. What must the server do?

The rules a job runs on

The ten work order statusesMain path: new, scheduled, dispatched, en_route, on_site, completed, ready_to_bill, billed. A visit that does not finish ends as incomplete, which is still open, and the dispatcher moves it back to scheduled for a revisit; a job in any open status can be cancelled. newscheduleddispatcheden_routeon_sitecompletedready_to_billbilledincompletestill open:needs a visitrevisit: back to scheduledcancelledfrom any openstatusDispatcher and technician: top and middle rows;the dispatcher books a revisit or cancels.Service manager: completed to ready_to_bill,only with the right evidence.billed: only after the export.
The ten statuses of a job. Completed becomes ready_to_bill only when the service manager releases it; an incomplete job goes back to scheduled for a revisit; any open job can be cancelled.

The service clock counts only hours inside the contract's opening periods on days that are not holidays; a booking outside opening hours starts counting at the next opening; a contract with no business hours counts every hour. Only repair and warranty jobs under a contract carry an SLA due time.

The service clock counts business hoursFive day-strips to scale. Thursday 16:00 to 17:00 counts one hour; Friday is a holiday and the weekend is closed; Monday 08:00 to 11:00 counts three hours, so a 4-hour response from Thursday 16:00 is due Monday at 11:00. Response clock, contract C-100: 4 hours from Thursday 16:00 (open Monday to Friday 08:00 to 17:00; Friday 19 June is a holiday)00:0004:0008:0012:0016:0020:0024:00Thu 18 JunFri 19 JunSat 20 JunSun 21 JunMon 22 Jun1 hour countedholiday: 0weekend: 0weekend: 03 hours counteddue Monday 22 June, 11:00not Thursday 20:00countedopen hoursclosed: not counted
Four hours from Thursday 16:00. One hour counts on Thursday; Friday is a holiday and the weekend is closed; three hours count on Monday. Due Monday 11:00.
ContractStartsTargetDue
C-100Fri 12 Jun 16:004 hoursMon 15 Jun 11:00
C-100Fri 12 Jun 16:0024 hoursWed 17 Jun 13:00
C-100, Fri 19 Jun a holidayThu 18 Jun 16:004 and 24 hoursMon 22 Jun 11:00 and Wed 24 Jun 13:00
C-200 (no business hours)Fri 12 Jun 16:008 hoursSat 13 Jun 00:00

Dispatch offers a technician only if active, in the job's territory and holding every skill the job needs, ordered by earliest arrival: the later of the window start and the previous appointment's end (or the shift start) plus the travel time. Travel is the straight-line distance at 111.2 km per degree of latitude and 60 km/h, rounded to minutes: lab values, so measure your own speed, and use a great-circle distance for real sites. Nothing in this course needs a paid routing service.

Travel time between jobsSix places on one line of longitude drawn to scale: technician homes and sites, 11, 22, 11 and 11 minutes apart within the North and South territories. For job SWO-0014 at Site A, Technician Two arrives at 09:00 and Technician One at 09:22. Latitude of each place, drawn to scale: 4 px = 1 minute of drivingTechnician Two home 41.40Site B 41.30Site A 41.10Technician One home 41.00Site C 40.60Technician Three home 40.5011 min22 min11 min11 minNorth territorySouth territoryMonday 22 June,window 09:00 to 12:00SWO-0014 at Site A, skill: pumpTechnician Two: 0 min,ETA 09:00 (their 07:00job is at Site A)Technician One: 22 min fromSite B, ETA 09:22Technician Three: not offered(South territory)Ignore travel: One and Twoboth look like 09:00Straight line at 60 km/h, 111.2 km per degree of latitude: lab values. Roads are longer than straight lines.
The drive decides. For SWO-0014 at Site A, Technician Two arrives at 09:00 and Technician One, coming from Site B, at 09:22. Technician Three is in South and is not offered.
Step 8

Session 4: Cover, the service clock and booking, proven against the tables

25 minutes

Why

Booking is where money is decided: a job for an asset out of warranty and out of contract must be billable, and a job under a contract must carry the due times its business hours give. These are pure rules with known answers, so checking every row of the tables above before any screen uses them is the cheapest place to find a wrong one. Every function takes the time as a parameter, so no test ever depends on today's date.

Do this

Paste into Claude Code
Read docs/fsm-rules.md, tests/fixtures/fsm-worked.json, tests/fixtures/fsm-counts.json and docs/matrix.json. Every test below with a fixed date runs on the fixture, never on the shifted seed.

On a new branch fsm/rules, a migration (npx supabase migration new fsm_rules) and tests in supabase/tests/fsm_rules.test.sql:
1. fsm_create_installed_base(sales_order_id), behind /api/fsm/install (fsm_install_route): one active asset per serial-carrying shipment row of the order, with party, site (the customer's site at the order's ship-to address), serial unit, order, and warranty from the shipping date for the item's warranty_months less one day; a serial-controlled shipment with no serial is refused and listed, never guessed; a repeat run adds nothing. Test: SO-5 gives SN-1005 at Site C, warranty 2026-06-10 to 2027-06-09; a second run still 6 assets.
2. fsm_check_entitlement(installed_asset_id, as_of date) returning covered_by, contract_id, billable: warranty if both dates are set and include the date (both ends included); else contract if an active contract lists the asset and its dates include the date; else none and billable. Test: SN-1001 2026-06-18 warranty with C-100; SN-1001-D warranty; SN-1002 contract C-100; SN-1003 2026-06-11 warranty, 2026-06-12 none and billable; SN-1004 2026-06-18 and 2026-07-01 none and billable; SN-1005 2026-06-18 warranty.
3. fsm_sla_due(contract_id, from_ts, hours) reading entitlements.business_hours. Test every row: C-100 from Fri 2026-06-12 16:00: 4 h Mon 06-15 11:00, 24 h Wed 06-17 13:00; from Thu 06-18 16:00: Mon 06-22 11:00 and Wed 06-24 13:00; from Fri 06-19 09:00 (the holiday): Mon 06-22 12:00 and Wed 06-24 14:00; C-200 from Fri 06-12 16:00, 8 h: Sat 06-13 00:00. SWO-0010 in the seed carries the Thursday answers.
4. fsm_book_job and /api/fsm/book (dispatcher, service_manager): party and site from the asset; the entitlement check at booked_at; billable, contract and ext.covered_by; ext.required_skills from the item; swo_no from the sequence; status new; ext.response_due_at and sla_due_at only for repair and warranty jobs under a contract; case_ref kept when given. Only the service_manager may later change billable, service_contract_id, sla_due_at or ext.billing_waived, with a core_comment. Test: SN-1004 repair p3 at Thu 06-18 10:00 gives SWO-0011, billable, no SLA; SN-1001-D repair p2 at Thu 06-18 16:30 gives SWO-0012, warranty, skill controls, no SLA; SN-1002 repair p2 at Fri 06-19 09:00 gives SWO-0013, C-100, due Mon 06-22 12:00 and Wed 06-24 14:00; the dispatcher changing billable is refused.
Show each test failing once with its function deliberately broken, then passing. Push, open a pull request titled "Field service rules", wait for the checks, and tell me the result.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ fsm_rules.test.sql .. 1/27 FAILED: SN-1003 on 2026-06-11 expected warranty, got none
1
⏺ That was with the last day of the warranty excluded on purpose. Restored: both ends count.
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 3m02s
⏺ Pull request #87 is green. SWO-0011 is billable (SN-1004, no cover); SWO-0013 carries C-100's due times, Monday 12:00 and Wednesday 14:00, because Friday 19 June is a holiday. SN-1005 is installed once, however many times the route runs.2
The rules checked against the tables you can work out by hand.
  1. Red first, on purpose: proof the test can fail.
  2. The first item of the module's definition of done: out of warranty and out of contract means billable.

Check it worked

The pull request is green; every entitlement row and every service-clock answer matches the tables; booking SN-1004 gave a billable SWO-0011; you have applied it to the development project by the routine after Step 5.

If it goes wrong

SN-1003 on its last warranty day comes out as not covered

The function leaves out the end date. Say: Both ends of the warranty dates are included. Keep the test; fix the function.

The 4-hour answer for Thursday 16:00 is Thursday 20:00

The clock counts calendar hours. Say: Count only hours inside the contract's opening periods on days that are not holidays, starting at the next opening. This is the third item of the definition of done.

A test depends on today's date and fails tomorrow

Say: Every function takes the time as a parameter. No test may read the clock.

Step 9

Session 4: Preventive jobs, dispatch with travel time, and no double booking

30 minutes

Why

A board that only checks who is free puts a technician in two towns at once; counting the drive between jobs is what makes a promise to a customer keepable. Preventive jobs must come from the plan by themselves, once, so a repeated run never floods the board. The status trigger and the overlap rule make the board's mistakes impossible to save, whoever makes them.

Do this

Paste into Claude Code
On a new branch fsm/dispatch, a migration (npx supabase migration new fsm_dispatch) and tests in supabase/tests/fsm_dispatch.test.sql:
1. fsm_generate_pm(as_of timestamptz), run by fsm_pm_engine: for each active plan due on or before the date with no open job carrying its pm_plan_id, book a preventive job through fsm_book_job (no SLA) and move next_due_at forward from the previous due date by interval_months. Test: as_of 2026-06-22 06:00 gives exactly one job, SWO-0014, SN-1002, C-100, not billable; PM-A next due 2026-12-22; a second run makes nothing; a second open job for PM-A inserted by hand is refused.
2. fsm_suggest_technicians(work_order_id, window_start, window_end, ignore_travel): active, same territory, every required skill; ETA = the later of window_start and (previous appointment's end, or the shift start, plus travel); travel = straight-line distance from core_address at 111.2 km per degree of latitude and 60 km/h, rounded to minutes; ordered by ETA then travel. Write the rules in docs/fsm-rules.md. Test, Mon 2026-06-22, window 09:00 to 12:00: SWO-0014 offers Technician Two at 09:00 (0 min) then Technician One at 09:22 (22 min), not Technician Three; with travel ignored both show 09:00; SWO-0012 offers only Technician One at 09:22; SWO-0011 offers only Technician Three at 09:00.
3. A status trigger: new, scheduled, dispatched, en_route, on_site, then completed or incomplete; incomplete back to scheduled; completed to ready_to_bill to billed only by the service_manager; any open status to cancelled.
4. An exclusion constraint (btree_gist) so one technician cannot hold overlapping appointments, on tstzrange(scheduled_start, scheduled_end, '[)'), ignoring cancelled and imported rows.
5. When an appointment moves to dispatched, a security definer trigger writes fsm.appointment.dispatched to core_event_outbox and an in-app core_notification for the technician. Nothing is texted or emailed.
Test: assign SWO-0014 to Technician Two 09:00 to 10:00 and SWO-0012 to Technician One 09:22 to 10:22, dispatch both: 14 appointments, 2 notifications, 2 events; a second Technician Two appointment 09:30 to 10:30 is refused.
Show each test failing once with its rule removed. Push, open a pull request titled "Field service dispatch", wait for the checks, and tell me the result.

You will see recreated screen

acme-platform-git-fsm-dispatch-acme-ops.vercel.app/service/dispatch
Mon 2026-06-22 · North
SWO-0014 · preventive · Site A · window 09:00–12:00Suggested: Technician Two 09:00 (0 min) · Technician One 09:22 (22 min)1
2
Technician07:0009:0009:22
Technician OneSWO-0009 Site BSWO-0012 Site A
Technician TwoSWO-0010 Site ASWO-0014 Site A
The dispatch board for Monday 22 June: the suggestion counts the drive.
  1. Without the drive, both technicians would show 09:00.
  2. Each day in time order, with the drive between jobs.
  3. The database refuses the overlap, whoever drags the job.

Check it worked

The pull request is green; the suggestions come in the order and at the times above; one preventive job and no second; the overlap is refused; you have applied it to the development project.

If it goes wrong

Technician Three is offered at 09:11, not 09:00

The drive was added to the window start. Say: Add the travel time to the previous end or the shift start only, then take the later of that and the window start.

Two visits back to back at 09:00 are refused

The range includes its end. Say: Use a half-open range, [scheduled_start, scheduled_end), so a visit ending at 09:00 and one starting at 09:00 do not clash.

The preventive engine made a second job on a second run

Say: Show me the partial unique index refusing a second open job for one plan, and move next_due_at forward from the previous due date.

Completed offline, parts on the ledger, lines to accounting

An offline job reaching the server onceOn the phone with no signal: download jobs, work, customer signs, complete into a queue entry with its own id. On the server when the signal returns: skip an entry already seen, refuse a job cancelled meanwhile, insert the visit with prices set by the server, and post parts from the van once per line. ON THE PHONE · NO SIGNAL1 · Downloadjobs, assets,history, van2 · Work offlineown arrival anddeparture times3 · Customer signssignature keptas a file4 · Completequeue entry,id made hereON THE SERVER · SIGNAL BACKSeen this entry?yes: add nothingJob cancelled?conflict: refuse,keep and show itInsert the visitphone times kept,received time notedPost van partsone ledger rowper linesync when the signal returns
Once, however many times it is sent. The phone keeps its own times; the server sets prices, refuses an entry for a job cancelled meanwhile, and posts parts from the van once per line.
Pump seals on the van and in the warehouseThree stages drawn to scale. At the start VAN-2 holds 1 pump seal and WH-1 holds 20. After SWO-0010 uses one, VAN-2 holds 0. After the parts request for 2 is received, VAN-2 holds 2 and WH-1 holds 18, each move a row in the ledger. Seed: opening stockVAN-2WH-1120Opening stock: adjustment rows in theledger; a trigger keeps the balanceAfter SWO-0010 uses one sealVAN-2WH-1020Ledger: the part leaves VAN-2 for the jobref_type fsm_service_line, once per lineAfter the request is receivedVAN-2WH-1218Request for 2 (minimum 2, balance 0):transfer_out WH-1 + transfer_in VAN-2,one transactionTHE REQUEST, IN ORDERrequestedpickedshippedreceivedReturnsunused parts, or a returnto a supplier:reversing entries
Parts follow the ledger. A used part is one ledger row from the van; a replenishment is two rows, out of the warehouse and into the van. A mistake is a reversing row, never an edit.
LineBillable?Rule
Any line on a job covered by warrantyNowarranty_covered is true
A line whose type is in the contract's coversNoCovered by contract
Any line on a job the manager waivedNoext.billing_waived true, with the reason in a core_comment
Any other lineYesPriced by the server from the item's list price
Step 10

Session 4: Complete a job offline, post the parts once, and hand billing on

35 minutes

Why

This is the module's second promise: a job completed with no signal syncs parts usage to the van's stock without losing parts, time or the signature, and without counting anything twice. The server, never the phone, sets prices and billable, so a phone cannot change what a customer pays. A CSV export of the billable lines is the free hand-off accounting can import and re-check.

Do this

Paste into Claude Code
Read node_modules/next/dist/docs/ for route handlers in this Next.js version, then docs/fsm-rules.md and docs/matrix.json.

On a new branch fsm/complete:
1. Extend the sync route for /service/work: each entry applied once by its id; an entry for a job cancelled meanwhile is refused with a conflict, kept in the queue and shown to the technician; the phone's arrival and departure kept, with the server's synced_at. The server sets each line's unit_price from list_price and billable and warranty_covered by the table in docs/fsm-rules.md (warranty: none billable; contract: types in covers not billable; waived: none billable; otherwise billable). Attachments (photo, signature, report) are core_attachment owned by the appointment, in a private bucket that allows insert and read only.
2. /api/fsm/parts (fsm_stock_route): for each part line of the caller's own van and job with no ext.inventory_txn_id, one ledger row from the van (ref_type fsm_service_line), and the ledger id written back on the line, in one transaction. A used part is never refused for lack of stock.
3. On completion: the service report as an HTML page with its sha256, first_time_fix true when the job had one visit, fsm.work_order.completed from a security definer trigger.
4. /api/fsm/signoff for the customer's typed sign-off, with the server clock and the existing report.
5. A security invoker view fsm_v_billable_lines; the service_manager's Release to billing (completed to ready_to_bill only with a billable line, a sign-off, and a ledger id on every part line, history lines exempt); /api/fsm/billing-export returning the lines as CSV and moving those jobs to billed.
Then a journey test, signing in the seed people the way the Session 19 journeys sign in test users, with the browser offline for the technician:
- Technician Two completes SWO-0010 offline (arrived 07:10, labour 1.5 h, travel 30 min, one PUMP-SEAL, a photo, a made-up signer, satisfaction 5, left 08:45), then reconnects: 3 lines (labour and travel not billable, the seal billable at 40), VAN-2 seal balance 1 to 0, one sign-off, 3 attachments, one completed event. Sending the same entry and part line again changes nothing; updating the sign-off is refused.
- Technician Two completes SWO-0014 with no customer present; the Customer One contact signs it off on /service/signoff and sees none of Customer Two's jobs (no SWO-0008 or SWO-0011).
- The service manager releases SWO-0001, SWO-0008 and SWO-0010; the export has 5 lines totalling 250 (40 + 100 + 50 + 20 + 40); the three jobs are billed; a second export is empty; releasing SWO-0014 or SWO-0011, or a dispatcher's release, is refused.
Print a short summary of each check. Push, open a pull request titled "Field service completion and billing", wait for the checks, and tell me the result.

You will see recreated screen

claude — acme-platform
⏺ Bash(gh pr checks --watch)
⎿ journeys / fsm-offline pass 5m02s
⏺ SWO-0010 completed offline and synced on reconnect: 3 lines, VAN-2 pump seals 1 to 0, 1 sign-off, 3 attachments, 1 completed event. Sent again: no change. Sign-off update: refused.1
⏺ Customer One contact signed SWO-0014 and saw 0 of Customer Two's jobs. Billing export: 5 lines, total 250; second export empty; dispatcher's release refused.2
The journey's summary: one job completed with no signal, arriving once.
  1. The second promise of the module, proven: parts reach the van's stock once.
  2. The numbers you can check by hand: 5 lines, 250.

You will see recreated screen

acme-platform-git-fsm-complete-acme-ops.vercel.app/service/signoff
SWO-0014 · Preventive · Site A
VisitMon 2026-06-22 09:00–09:50
Work donePreventive service, 1 hour
Your nameSeed Contact
Satisfaction4 ▾1
Sign off
The service report the customer signs, as the customer contact sees it. No prices: the customer has no right on service lines.
  1. The signed-off report is stored with its fingerprint and can never be changed.

Check it worked

The journey is green and its summary shows SWO-0010's lines, VAN-2 at 0, nothing changed on a second send, the sign-off refused on update, Customer Two's jobs hidden and the export of 5 lines totalling 250. You have applied it to the development project.

Fastest path

One journey test replaces a morning of switching between four sign-ins and a phone in airplane mode, and it runs again on every pull request from now on.

If it goes wrong

The van's balance went down twice for one part

Say: Skip a line whose ext.inventory_txn_id is set, and add the unique index on ref_type, ref_id and txn_type to the ledger, with a test that posts the same line twice.

The phone sends a price and the server keeps it

Say: Ignore any price or billable flag from the phone; set them on the server from the item and the job.

The summary says passed but the check on GitHub is red

Say: Show me the exact command, its exit code and the last 20 lines of its output. We recorded a run that printed npm: not found and, minutes later, reported 1,326 tests passing.

Step 11

Session 4: Vans, the SLA watch and the four measures, against a hand count

30 minutes

Why

A measure without its definition, or one never checked against a count you did yourself, is a number on a screen. Writing each definition down and matching the views to the seed's hand count means the figures you compare with the old tool in Session 6 are real. Replenishment and the SLA watch turn the van's shortfall and a job close to its due time into something someone sees, without a message being sent.

Do this

Paste into Claude Code
On a new branch fsm/measures, a migration (npx supabase migration new fsm_measures) and tests:
1. fsm_replenish_vans(), behind /api/fsm/replenish (fsm_stock_route): for each active technician and item in ext.van_min, when the van is below the minimum and no request is open, one parts request for the difference, needed by the start of the next shift. Receiving posts two ledger rows in one transaction (out of WH-1, into the van). Test after SWO-0010: one request, Technician Two, 2 seals; a second run still one; received: VAN-2 2, WH-1 18, 17 ledger rows.
2. fsm_sla_watch(as_of), security definer, run by fsm_pm_engine: one fsm.sla.breach_risk event per open job due within 2 hours (a lab value). Test: 2026-06-24 11:30 none; 12:30 exactly one, for SWO-0013; again, still one.
3. fsm_kpi(period_from, period_to), security invoker, with definitions written in docs/fsm-rules.md: first-time fix (jobs that reached completed, ready_to_bill or billed, with first_time_fix true, over those with it filled in); SLA attainment (first arrival not after ext.response_due_at and last departure not after sla_due_at, over jobs with sla_due_at); utilisation (on-site plus travel minutes of completed visits over 540 minutes a day); repeat visits (repair and warranty jobs starting within 30 days after an earlier one on the same asset, over repair and warranty jobs). Test for 2026-04-01 to 2026-06-11: first-time fix 6 of 8, 75.0%; SLA attainment 2 of 4, 50.0%; repeat visits 1 of 6, 16.7%; Technician One on 2026-06-02: 250 of 540 minutes, 46.3%.
4. The measures on /service/manage, each with its definition beside it, and "No data" where a measure has nothing to count.
Show each test failing once with its rule broken. Push, open a pull request titled "Field service measures", wait for the checks, and tell me the result.

You will see recreated screen

acme-platform-git-fsm-measures-acme-ops.vercel.app/service/manage
Measures · 2026-04-01 to 2026-06-11
1
MeasureValueCountDefinition
First-time fix75.0%6 of 8completed jobs fixed on the first visit
SLA attainment50.0%2 of 4jobs under SLA meeting both targets
Repeat visits16.7%1 of 6repair or warranty within 30 days on the same asset
Utilisation, Technician One, 2 Jun46.3%250 of 540 minon-site plus travel over available
The manager's desk: each measure with its definition and the count behind it.
  1. Your hand count from the seed, exactly. If they differ, fix the query, not the count.
  2. Nothing is texted or emailed; the free way comes first.

Check it worked

The pull request is green; the four measures match 75.0%, 50.0%, 16.7% and 46.3% exactly; replenishment gives one request and the right balances; the SLA watch writes its one event once; you have applied it to the development project.

If it goes wrong

First-time fix drops after billing

The query counts status completed only. Say: Count jobs that reached completed: status completed, ready_to_bill or billed.

Repeat visits says 2 of 6

SWO-0004 is 33 days before SWO-0001, outside the 30 days. Say: Measure from the earlier job's last departure to the later job's first arrival, and keep the test at 1 of 6.

A measure shows 0% where nothing was measured

Say: Show No data when the denominator is zero. On our platform a chart graded twelve made-up points "In control"; a zero that means nothing is the same mistake.

Knowledge check

Contract C-100 counts Monday to Friday, 08:00 to 17:00, with no holiday that week. A 4-hour response starts on Friday at 16:00. When is it due?

Knowledge check

Who sets the unit price and the billable flag on a service line?

References

  1. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  2. ISO 9001:2015, Quality management systems: requirements. https://www.iso.org/standard/62085.html
  3. W3C: Indexed Database API (the browser database used for offline work). https://www.w3.org/TR/IndexedDB/
  4. PostgreSQL Documentation: Exclusion constraints. https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-EXCLUSION
  5. ServiceTitan: field service dispatch app. https://servicetitan.com/blog/field-service-dispatch-app

Chapter 3 · Sessions 5 and 6

Move the real data, cut over and switch the old tool off

Session 5 builds the importer and the pre-cut-over checks and rehearses them on the development project with a copy IT has approved. Session 6 imports the real records into production through the import workflow, started by a person from main with an export owner two approved, checks the counts, runs both tools side by side for a week, completes a real job on a real phone in airplane mode, cuts over, closes the importer and cancels the old tool with the saving written down.

30 minSteps 12–14About 2 hours 15 minutes hands-on in these two sessions, plus a side-by-side week

By the end of this chapter you can

  • Build an import that is a dry run by default, adds nothing on a second run, and accounts for every row.
  • Rehearse on the development project with an IT-approved copy, then import into production through import-fsm.yml from main with an approved export, never from a laptop.
  • Check before cut-over that every asset has a site and every active contract an end date in the future.
  • Cut over, close the importer, and cancel the old tool with the saving taken from invoices.

Six imports, in order

Moving out of the old toolSix imports in order: sites and territories, assets by shipped serial, contracts, PM plans, open jobs and closed jobs as history. Then counts reconcile, pre-cutover checks, a side-by-side week, cut-over, and cancelling with the saving recorded. 1 · Siteswith theirterritories2 · Assetsby shippedserial3 · Contractswith anend date4 · PM plansnext duedates5 · Open jobskeep olddue times6 · Closedjobs, ashistory onlyCounts reconcilerows: imported,matched orskippedCut-over checkseach check is 0or has a decisionSide by sideone week, bothtools running,gaps explainedCut overold toolread-only, deltaimport runCancel, recordfinal exportkept; savingfrom invoices
Six imports, then the road to cut-over. Parents before children inside each kind; closed jobs last, because they depend on everything else.
  • Every row keeps where it came from (the old tool's name and old id in ext), and the importer finds rows by them, so a re-run or a resumed import adds nothing twice.
  • Assets are matched to shipped serials: matched (unit and order taken from the shipment), near match (a person decides), no match (imported with the serial as text, and listed). Write the matched share: this is pitfall 1 on real data.
  • Every contract needs an end date. One the old tool rolls over with none gets its next renewal date and is listed for the service manager; one whose end is past is imported as expired.
  • Open jobs keep the old number as OLD- followed by it, so it never clashes with the sequence; the entitlement check is re-run as of each booking date and every difference from the old billable flag is listed and decided.
  • Closed jobs arrive as history in their final state: nothing fires, nothing posts to the ledger, nothing is billed again. Import at least 30 days before the period you measure, for repeat visits.
  • Counts reconcile: for each kind, rows in the export = imported + matched + skipped, with every skipped row explained.
Check before cut-overMust be
Installed assets with no service site0
Active contracts whose end date is past0
Assets of serial-controlled items with no serial unitEach has a written decision
Open jobs with no site; scheduled or dispatched jobs with no appointment0
Two assets with one item and serial0
Step 12

Session 5: The importer and the checks, rehearsed on the development project

45 minutes

Why

An import is the one time a large amount of data enters at once, so it must be repeatable, honest about every row it could not place, and impossible to run from a laptop by accident. Customer sites and contacts are personal data, so even a rehearsal needs IT's written yes. A dry run, a second run that adds nothing and counts that reconcile prove the importer before any real record moves; the development project is where a mapping error costs nothing.

Do this

Real records include customers' sites, contacts and signatures. Before they go anywhere but the old tool, get IT's written yes:

Email to send (copy, then fill in the old tool's name)
To: IT
Subject: Rehearsing the field service import on our development project

We are replacing <old tool> with the field service module on the Acme Bottling platform. Before importing into production, we want to rehearse once on our development Supabase project (acme-platform-dev) with a copy of the export: customers and sites (names, addresses, access notes), installed assets and serials, contracts, preventive plans, open jobs and closed jobs. This includes personal data, which would be redacted first (contact names, phone numbers and access notes replaced). No signature images.

The copy would be uploaded by me to a private storage bucket in that project, used for one rehearsal, and removed from the project the same day, with the date recorded in docs/imports/fsm-approved.md. Logs and reports show counts and job numbers only.

Please reply "approved", or tell us what to change.
Paste into Claude Code
Read docs/fsm-inventory.md, the M18 section of docs/spine-map.md, docs/fsm-rules.md, docs/matrix.json and the deploy workflow from Session 11.

On a new branch fsm/import:
1. docs/fsm-import-plan.md: for each of the six kinds (customers and sites, assets, contracts, preventive plans, open jobs, closed jobs) the old fields beside the new columns, and the fields the export lacks; the old statuses mapped to the ten; the old contract types mapped to the five; what stays in the final export.
2. scripts/fsm-import.mjs, running as the fsm_import database role, which is insert-only (no update, no delete; created NOLOGIN by a migration, its login turned on by a person with a password they set and name in docs/KEYS.md): a dry run by default that writes nothing; --apply to write; the six kinds in order, parents before children; ext.imported_from and ext.old_id on every row, used to find rows on a re-run; assets matched to shipped serials (matched, near, none); contracts with no end date given the next renewal date and listed; open jobs as OLD-<number>, technicians matched by work email, the entitlement check re-run and every difference listed; closed jobs as history (lines ext.history true, nothing to the ledger, no events). Every row ends imported, matched or skipped with a reason; counts per kind reconcile.
3. scripts/fsm-precheck.sql, read only, as the service_manager: the five checks before cut-over.
4. .github/workflows/import-fsm.yml, run by hand only (workflow_dispatch) from main, refusing any other branch, inputs target (development or production) and mode (dry-run or apply). It fetches the export from the private Storage bucket imports in the target project; refuses it unless every file's sha256 and expected counts are listed in docs/imports/fsm-approved.md on main; runs the importer in one transaction and then the pre-checks; fails, keeping nothing, on any count that differs from the approved file; and writes counts, job numbers of exceptions and the matched-serial share to the job summary: never names, addresses or notes. It signs in as fsm_import with that target's password secret (FSM_IMPORT_PASSWORD_DEV or FSM_IMPORT_PASSWORD), which I add; tell me if it needs any other secret. No GitHub environment with required reviewers (the Team plan does not offer them for private repositories): the reviewed pull request that merges the approved file is the approval.
5. Tests with a small synthetic export: dry run writes nothing; apply then apply again adds nothing; an asset with no site is caught by the pre-check; counts reconcile; a file whose sha256 is not approved is refused; a count mismatch fails and keeps nothing; fsm_import cannot update or delete.

Push, open a pull request titled "Field service importer", wait for the checks, and tell me the result.

When IT has approved and the pull request has merged: in the development project's SQL editor turn on fsm_import's login with a password you make (alter role fsm_import login password '…'), keep it in the password manager, add it as the Actions secret FSM_IMPORT_PASSWORD_DEV and name it in docs/KEYS.md. Upload the redacted copy to the bucket imports in the development project and record its fingerprints.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets

Create a private bucket named imports (Public off) and upload the export copy.

Terminal (Mac or Git Bash on Windows), in the export folder
shasum -a 256 *
Paste into Claude Code, after replacing the last line
On a new branch fsm/import-approval, write docs/imports/fsm-approved.md with a section "Rehearsal (development project only)": each file's name, sha256 and expected rows per kind (I paste them below), the date taken, what was redacted, and IT's written approval (date and role). File names, fingerprints and counts only: no customer data. Open a pull request titled "Field service: approve rehearsal export".

<paste the shasum lines and the counts>

Owner two reviews and approves; merge. Then run the workflow on the development project as a dry run, then apply, then apply again.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-fsm.yml

Run workflow: target development, mode dry-run. Read the summary. Then apply, then apply once more.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/runs/1210
Import FSM · development · apply
1
KindExportImportedMatchedSkipped
Sites412398122
Assets1,2861,251035
Contracts25125100
Open jobs646400
Closed jobs3,9043,90400
The import's summary on GitHub: counts and job numbers, never names or addresses.
  1. Export = imported + matched + skipped, for every kind.
  2. Pitfall 1 on your real data, as a number.
  3. Zero before anything goes to production.

Check it worked

The dry run wrote nothing; apply reconciled every kind with every skipped row explained; the second apply added nothing; the pre-checks are at zero. Then remove the copy from the development project the same day (its imported rows and the file in the bucket) and record the date in docs/imports/fsm-approved.md.

If it goes wrong

The workflow refuses: sha256 not approved

The file changed since you recorded it (often opened and saved in a spreadsheet, which rewrites it). Upload the approved file again, or record the new fingerprint through a pull request owner two approves.

The workflow fails with Invalid URL, or the address is refused

We hit this: a database address pasted with quotes, a NAME= prefix, a space or an unencoded character in the password. Re-enter the secret with the value only. Say: Report which problem the address has without printing it.

The job summary shows a customer's name or address

Stop. Say: Remove every name, address and note from the summary and the logs; counts and job numbers only. Then delete the run's logs on GitHub.

The second apply added rows

Say: The importer is not idempotent. Find each kind where a second run inserts, match on ext.old_id, and add the test.

IT has not answered

Wait. Rehearse with the synthetic export only. Real records do not move without the written yes.

Knowledge check

Why are closed jobs from the old tool imported as history?

Four measures, written next to their numbers

MeasureHow the module counts it
First-time fix rateJobs that reached completed with first_time_fix true, over those where it is filled in
SLA attainmentJobs whose first arrival met the response due and last departure met sla_due_at, over jobs with an SLA
Technician utilisationOn-site plus travel minutes of completed visits, over the shift less the paid break (a lab choice: write yours)
Repeat visit rateRepair and warranty jobs within 30 days after an earlier one on the same asset, over repair and warranty jobs
The four measures from the seedHorizontal bars to scale: first-time fix 75.0 percent, SLA attainment 50.0 percent, repeat visits 16.7 percent and technician utilisation 46.3 percent. 0%25%50%75%100%First-time fix6 of 8 completed jobs75.0%SLA attainment2 of 4 jobs with an SLA50.0%Repeat visits1 of 6 repair jobs16.7%Utilisation250 of 540 minutes, one day46.3%Seed hand count, 1 April to 11 June 2026. Utilisation: Technician One on Tuesday 2 June, 195 on site plus 55 travel.
The seed, counted by hand. 75.0%, 50.0%, 16.7% and 46.3%: the numbers the views had to match in Session 4. Two tools can both say first-time fix and mean different things, so explain every difference from the old tool's figure [1][2].
Step 13

Session 6: Import into production through the pipeline, and check the counts

30 minutes

Why

Production changes only through reviewed code run by the pipeline, never from a laptop: a deploy from a laptop once sent local settings to our production and broke three pages. Running the same workflow that passed the rehearsal, started by you from main, on an export whose fingerprints and counts owner two approved in a reviewed pull request, means the import that reaches production is exactly the one you checked, and the counts prove nothing was lost or added twice.

Do this

Take the final export. Upload it to a private bucket imports in the production project. Turn on fsm_import's login in production with a new password you make, keep it in the password manager, add it as the Actions secret FSM_IMPORT_PASSWORD and name it in docs/KEYS.md.

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets

Production project storage: a private bucket imports, Public off. Upload the export.

Paste into Claude Code, after replacing the last line
On a new branch fsm/import-production, add a section "Production" to docs/imports/fsm-approved.md: each file's name, sha256 and expected rows per kind, and the date taken. Open a pull request titled "Field service: approve production export".

<paste the shasum lines and the counts>

Owner two reviews and approves; merge. Then run the workflow, first as a dry run.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-fsm.yml

Run workflow from main: target production, mode dry-run. Compare with the rehearsal and the approved file. Then mode apply.

Then record the result and the baseline:

Paste into Claude Code
The production import has run (run <paste the run link>). On a new branch fsm/import-report, add to docs/fsm-import-plan.md from its job summary: the date, who ran it and who watched, the counts per kind, every skipped row's reason, the matched-serial share, the pre-checks, and the date the development copy was removed (from docs/imports/fsm-approved.md). Then run fsm_kpi over the imported closed jobs for the four weeks in docs/fsm-inventory.md section 5, and put the four measures beside the old tool's own figures, explaining every difference by definition. No customer names or addresses. Open a pull request titled "Field service import report".

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-fsm.yml
Run workflow
Use workflow fromBranch: main ▾1
targetproduction ▾
modeapply ▾
Run workflow
Running the import on production: from main, the same workflow as the rehearsal, on an approved export.
  1. Always main: the code that ran in the rehearsal, reviewed and merged.
  2. Owner two approved these fingerprints and counts in a reviewed pull request; any other file is refused.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/fsm-import-plan.md)
+First-time fix: old tool 71%, module 68% over the same 4 weeks (412 jobs).
+Difference: the old tool leaves out jobs closed as incomplete; the module counts them.
+SLA attainment: old tool not reported; module 83% (96 jobs under SLA). This is the baseline.
1
The baseline beside the old tool's own figures, each difference explained.
  1. A difference explained by definition is not a defect. One you cannot explain means you are not ready.

Check it worked

Production's counts match docs/imports/fsm-approved.md with the same explained skips as the rehearsal, the pre-checks are at zero, and the import report with the baseline is merged.

If it goes wrong

The run fails: a count differs from the approved file

Nothing was kept: the import runs in one transaction. Find why (a re-export, a filter in the old tool) and approve the right file through a new pull request. Never edit the counts to fit.

Someone suggests a GitHub environment with required reviewers

Not available on the Team plan for private repositories. The reviewed pull request that merges docs/imports/fsm-approved.md is the approval.

A count differs from the rehearsal

Stop before cut-over. Say: Compare the production and rehearsal summaries and list every count that differs, with the job numbers behind it.

Someone suggests running the importer from a laptop to save time

Do not. Production comes only from main through the pipeline. A laptop run uses whatever is on that laptop.

The module's first-time fix is far from the old tool's

Read both definitions first: business against calendar hours, incomplete visits left in or out, travel counted as work. Write the cause beside the number; never adjust the query to match.

Step 14

Session 6: Side by side, a real phone offline, cut over, and cancel

60 minutes, after a side-by-side week

Why

A week in which every job of one pilot territory is booked and completed in both tools shows whether the module does the same work before anyone depends on it alone. A real job completed on a real phone in airplane mode is the test the journey cannot be. Closing the importer, and cancelling the old tool only after the final export is stored, turns the saving into a fact with a date.

Do this

For one week, the dispatcher books every job of one pilot territory in both tools, and the technicians complete it in both. During the week, one technician completes a real job on the phone screen with the phone in airplane mode, then reconnects. Then:

Paste into Claude Code
On a new branch fsm/cutover, write docs/fsm-cutover.md:
1. The side-by-side week: jobs booked, completed and open, first-time fix, SLA attainment, utilisation, repeat visits, and billable lines with their total, from the old tool's report (I will paste it) beside fsm_kpi and the billing view; every difference explained.
2. The module's promises, each with one query run as the right role on production: (a) every job booked this week for an asset out of warranty and out of contract is billable, or has the service manager's comment saying why; (b) every completed part line has a ledger id, and each van's balance equals its ledger; (c) three SLA due times worked out by hand match the stored ones; (d) every completed job has a sign-off or a written reason, and a sign-off update is refused; (e) every asset has a site.
3. The real-phone test: the job number, the counts before and after reconnecting, and that a second send changed nothing.
4. The cut-over: the date, who tells the technicians and the customers (any texts the old tool sent will stop, because this module sends none), the delta import through the same workflow (its export's sha256 and counts approved in docs/imports/fsm-approved.md first), who keeps the final export and where, and the rollback plan.
Then close the importer: remove fsm_import from docs/matrix.json, regenerate the access rules, add a migration that sets the fsm_import role to NOLOGIN (I delete its password secrets and note the date in docs/KEYS.md), mark its lines in docs/fsm-rights-check.md retired with the date, and add a test that an import is now refused.

My figures:
<paste the old tool's report for the week>

Push, open a pull request titled "Field service cut-over", wait for the checks and tell me the result.

On the cut-over date, before the cut-over pull request merges and sets fsm_import NOLOGIN: stop booking in the old tool, approve the delta export's sha256 and counts in docs/imports/fsm-approved.md through a pull request owner two approves, run the delta import through the workflow from main (it adds nothing twice), take the old tool's final full export into company storage, and set the old tool read-only. Read the cancellation terms on your own account page, cancel, and record it:

Paste into Claude Code, after replacing the <...> part
On a new branch fsm/retired, update docs/fsm-inventory.md: each kind of record and each tool marked replaced, retired or still in use, with the date; the workarounds from Session 1 the module removed; the cancellation (date, notice period, last invoice amount as I give it); and the saving as arithmetic: the old yearly cost plus the helper tools dropped, minus what the module adds to services we already pay for, from our own bills. My figures: <paste from the invoices>. Open a pull request titled "Field service tool retired".

You will see recreated screen

claude — acme-platform
⏺ Write(docs/fsm-cutover.md)
+Week: 46 jobs in both tools; 1 in the old tool only (booked by phone on Tuesday, added Wednesday).
+Real phone, SWO-0412, airplane mode: 4 lines, 1 sign-off, van seal 3 to 2; second send: no change.
1
⏺ Bash(gh pr checks --watch)
⎿ access / fsm-import-refused pass
⏺ Pull request #96 is green. The importer is closed: an import is refused. All five promise checks hold on production, and every difference in the week is explained.2
The cut-over record: the week compared, the promises proven, the importer closed.
  1. The test that matters most: a real job, a real phone, no signal.
  2. After cut-over nothing can bulk-write service data again.

Check it worked

docs/fsm-cutover.md is merged with every difference explained, the five checks and the real-phone test recorded; the importer is refused; the final export is stored; the old tool is read-only or cancelled, with the saving as arithmetic from invoices in docs/fsm-inventory.md.

If it goes wrong

A job exists in only one tool

That is a finding, not noise. Find who booked it and why it skipped the other tool, and fix the habit before cut-over.

The real phone lost an action after reconnecting

Do not cut over. Say: Show me the outbox entries for that job on the phone and on the server, with their ids, and find where the entry was dropped.

The vendor's notice period has passed for this year

Write the date the plan ends and a reminder for the next notice date. Keep the old tool read-only until then.

Before you go on · The module is done whenTick each one

Knowledge check

In a period 10 jobs were completed; 4 carried an SLA and 3 of those met both targets. What is SLA attainment?

References

  1. FieldProxy: seven must-have features in modern field service management software. https://www.fieldproxy.ai/resources/blog/7-must-have-features-in-modern-field-service-management-software-d1-38
  2. ERP Research: Salesforce Field Service overview. https://erpresearch.com/erp-add-ons/field-service/salesforce-field-service
  3. GitHub Docs: Events that trigger workflows (workflow_dispatch). https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_dispatch
  4. GitHub Docs: Using secrets in GitHub Actions. https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions

Chapter 4 · 12 questions · 80% passes

Final assessment

Twelve questions across the element. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.

15 min12 questions≈ 15 minutesRetake allowed

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. Which module owns taking the customer's call and the support conversation, which field service leaves out?
2. An asset's warranty ran to 2026-06-11 and no active contract lists it. A job is booked on 2026-06-12. What is the result?
3. What does pitfall 1, an installed base disconnected from shipped serials, cost the business?
4. Contract C-100 counts Monday to Friday, 08:00 to 17:00, and Friday is a holiday. A 4-hour response starts on Thursday at 16:00. When is it due?
5. How does the dispatch board work out a technician's earliest arrival at a job?
6. A phone sends the same completed-job entry twice because the first confirmation was lost. What must the server do?
7. Who decides the unit price and the billable flag on a service line?
8. How does a part used on a job reduce the van's stock?
9. A pull request adds a field service migration and CI is green. What happens next?
10. In a period 8 jobs were completed and 2 of them needed a second visit. What is the first-time fix rate?
11. How are closed jobs from the old tool imported?
12. What is the amount_claimed on a supplier warranty claim for a job?