# iDrv4 → iDrv5 Carryover Features & Migration Specification

**Audience:** iDrv5 (JATT LOS) engineering team
**Purpose:** A complete inventory of the **already-built, production iDrv4 features** that must be re-implemented ("carried over") in iDrv5, in addition to the brand-new LOS capabilities described in the *JATT iDrv v5 — LOS Architecture Master Specification v1.1*.
**Status:** Reference / scoping document — derived directly from the iDrv4 source repositories and the legacy product documentation.

> **Read this first.** iDrv5 is not a greenfield product. It is a re-platforming of a mature, ~10-year-old Transport Management System (originally branded **LOGICOR**, now **iDrv / Ceres**) that already runs real freight operations for JATT. The new architecture spec describes *where we are going*. **This document describes the enormous body of working functionality we are obligated to bring with us.** Almost every "module" in the v5 spec (TMS, FMS, FleetM, FuelM, ComplianceM, FinSM, DriverM, etc.) has a substantial iDrv4 predecessor that is feature-rich, battle-tested, and full of edge cases. Overlooking this is the single biggest risk to the v5 program if not documented properly.

---

## 1. The iDrv4 system at a glance

iDrv4 is **five separate codebases** plus a Python OCR sidecar:

| # | Repo (codename) | Stack | Role in iDrv4 | Maps to iDrv5 Experience Layer |
| - | --------------- | ----- | ------------- | ------------------------------ |
| 1 | **ceres-laravel8-restapi** (`ceres`) | Laravel 8 / PHP, OAuth2 (Passport), MySQL | **The backend.** All business logic, data, documents, integrations. | Business Capability Layer + Platform & Automation Layer (almost everything) |
| 2 | **nadja-ionic5-mobile-app** (`nadja`) | Ionic 5 / Angular 11 / Capacitor + Cordova | **Driver Companion app** (iOS + Android). | Driver App |
| 3 | **nicola-angular11-webclient** (`nicola`) | Angular 11 | **Admin / Operations Portal** — dispatch, fleet, drivers, payroll, invoicing, compliance, settings. The "command centre". | Operations Portal + Admin Portal + Finance Portal |
| 4 | **narwhal-angular11-webclient** (`narwhal`) | Angular 11 + Firebase | **Customer Portal** (authenticated) — bookings, tracking, compliance docs, rates, invoices. | Customer Portal |
| 5 | **nebula-angular11-webclient** (`nebula`) | Angular 11 | **Public Quote & Booking Portal** (unauthenticated) — instant quotes, self-service booking, Dyspach integration. | Customer Portal (public quoting funnel) |

### Scale of the thing we are migrating (measured, not estimated)

| Metric | Count | Notes |
| ------ | ----- | ----- |
| Backend controllers | **146** | Across TMS, API, V3 API, Customers, PublicBooking, ThirdParty, Transvirtual, DMS, Staff, Export, Xero |
| Backend models | **283** | ~20 domains |
| Database tables | **~205** | See §16 for domain breakdown |
| PDF document templates | **57 Blade templates** | 8 document categories (§9) |
| Largest backend controllers | InductionController **9,920 LOC**, DispatchController **5,126**, MailController **3,716**, InvoiceController **3,397**, BookingController **3,177** | Single files |
| Mobile app screens | **60+** | Background GPS, offline-aware, POD, work diary, inspections, fuel |
| Admin portal (nicola) | **~130k LOC** functional | Dispatch planner alone: 5,511 LOC component + 38,934 LOC service |
| External integrations | **7+** | Xero, Transvirtual, OneSignal, Twilio, AWS SES, AWS S3, Google Maps, Dyspach |

**Bottom line:** there are on the order of **40+ distinct feature areas** with real, in-production behaviour. The new v5 modules do not replace these — they *re-home* them. Plan for that.

### Business flow (legacy LOGICOR flow chart, still accurate)

```
BOOKING ─────▶ JOB CREATION ─────▶ JOB DISPATCH ─────▶ JOB PROCESSING ─────▶ POST TRIP
  │                  │                    │                    │                  │
  ├ online booking   ├ supervisor         ├ dispatch/cancel    ├ job progress     ├ invoice processing
  ├ phone/email      │  accepts/rejects   ├ dispatch to        │  monitored       ├ payroll processing
  │  → operator      │  → new job created │  driver & fleet     │  real-time       ├ production cost
  │     books        │                    ├ driver app:         │                  ├ payslip
  │                  │                    │  accept/reject      │                  └ invoice to customer
  CUSTOMER ◀────────────────────────── ADMIN DASHBOARD ──────────────────────────▶ DRIVER MOBILE APP
```

This 5-stage flow (**Booking → Job Creation → Dispatch → Processing → Post-Trip**) is the spine of iDrv4 and maps onto the v5 freight backbone (`Quote → Booking → Consignment/Connote → Pickup → … → Delivery → POD → Invoice`). Every carryover feature below lives somewhere on this spine.

---

## 2. How to read the rest of this document

Each feature area is documented with:

- **What it does** (business behaviour, including the gnarly edge cases)
- **Where it lives in iDrv4** (repo + concrete file paths / line counts so you can feel the weight)
- **iDrv5 target** (which v5 module/portal it belongs to, and terminology mapping)
- **Migration weight** 🟢 Port / 🟡 Rework / 🔴 Hard rebuild — and *why*

Complexity legend:

- 🟢 **Port** — well-understood CRUD/UI; mostly translation work.
- 🟡 **Rework** — non-trivial logic or external dependency; needs design, not just translation.
- 🔴 **Hard rebuild** — deep logic, regulatory exposure, custom native code, or financial correctness. These are the features that decide the schedule. **Do not let anyone scope these as "we already have it."**

---

## 3. CARRYOVER FEATURE CATALOG

### 3.1 Booking & Quoting (→ FMS)

**What it does.** Capture a freight job before it exists operationally. Two front doors:
- **Public instant quote + self-service booking** (`nebula`): suburb/postcode autocomplete, Economy vs Express pricing, dynamic pallet list with **volumetric (cubic) weight** calc (`Volume × 333 kg/m³`, charge weight = max(physical, cubic), chargeable-pallet rounding), DG classification + doc upload, quote reference generation & retrieval, email-quote, duplicate-booking prevention, and a **third-party Dyspach quote engine** integration with price-lock.
- **Authenticated customer booking** (`narwhal`) and **operator booking** (`nicola`): full multi-tab booking form (Load Details / Pickup / Delivery / Local Start / Misc), multi-point pickup & delivery with **Google Maps address autocomplete + reverse geocode → AU state mapping + business-hours lookup**, booking templates, driver/equipment pre-assignment, charging-method selection, cost preview.

**Where it lives.**
- `nebula/src/app/pages/getquote/getquote.component.ts` (948 LOC), `booking/booking.component.ts` (1,734 LOC), `services/dyspach-*.service.ts`
- `narwhal/src/app/pages/bookings/addbooking2/` (4,995 LOC TS + 1,654 LOC HTML), `addbooking/` (4,833 LOC)
- `nicola/src/app/pages/bookings/addbooking2/` (5,273 LOC), `addbooking/` (5,029 LOC)
- Backend: `ceres` `BookingController.php` (3,177 LOC), `BookingControllerv2.php`, `WhBookingController.php` (CSV import, 1,257 LOC), `PublicBooking/*`, `Customers/*`
- Business spec: `working documents/BOOKING FORM.docx`, `Rate Computations.docx`

**iDrv5 target.** FMS (Quote, Booking, Service Product). Terminology: legacy "job/booking" → v5 **Booking → Consignment**. The public quote funnel maps to FMS `generateQuote()`/`convertQuoteToBooking()`.

**Migration weight.** 🔴 The booking form is the single most complex UI in the system: **~5,000-line components replicated across three portals**, 100+ conditional fields, multi-address FormArrays, live cost recompute, DG handling, templates, edit/rebook modes. The cubic-weight/chargeable-pallet math and the Maps reverse-geocode→state-ID logic are full of edge cases. Treat "the booking form" as its own sub-project. The three near-duplicate implementations are an opportunity to consolidate into one v5 booking experience — but that consolidation *is* the work.

---

### 3.2 Connote / Consignment management (→ TMS)

**What it does.** The connote (consignment note) is the operational job record. Management includes: connote list with multi-axis filtering (date range, status, job type, service type), bulk select + bulk actions, CSV/PDF/Excel export with cost aggregation, the multi-tab **connote details** view (job info, sites, drivers, documents, dispatch, history, tests, costs, notes, invoice-readiness), document attach/preview/delete, POD/signature, activity feed, admin upload of legacy connotes, and per-connote prefixed control numbers.

**Where it lives.**
- `nicola/.../connotelistv2` (1,743 LOC), `connotelist` (1,451 LOC), `connotedetails` (1,407 LOC), `importbookings` (790 LOC)
- `narwhal/.../connotelistv2` (1,219 LOC), `connotedetails`
- Backend: `ConnoteController`, `ConnoteSiteController`, `ConnoteDocumentController` (1,026 LOC), `ConnoteNotesController`, `ConnoteAdminUploadController`; ~10 `connote*` tables.

**iDrv5 target.** TMS (Consignment, Leg, Task, Milestone, POD). **Critical terminology shift:** v5 deprecates "shipment" and standardises on **`consignment_id` (UUID) + `connote_number` (customer-facing)**. iDrv4 already uses "connote" everywhere — good — but the internal data model uses integer IDs and "booking/job" loosely; the v5 canonical split (Consignment vs Connote, owner vs custodian) must be imposed during migration.

**Migration weight.** 🟡–🔴 The list/grid/export pieces are 🟡. The connote-details aggregation (pulling from many data sources, document lifecycle, invoice-readiness gating) is 🔴 and is the operational heart of TMS.

---

### 3.3 Job Dispatch & the Dispatch Editor (→ TMS + Operations Portal) 🔴 FLAGSHIP

**What it does.** This is the crown jewel and the hardest single carryover. Operators turn unplanned connotes into executable **Runs** (truck + driver(s) + trailer(s) + ordered sequence of pickup/delivery tasks).

- **Drag-and-drop dispatch planner** (`ng2-dragula`): driver / fleet / equipment / trailer panes, activities list, route map (`@ngui/map`), pre-dispatch modal, manifest summary.
- **Linehaul vs Local** dispatch — two different UIs, each with v1 and v2 variants, plus a separate local dispatch board.
- **Run editor**: task editor, location picker, connote picker, draggable containers.
- **15 cross-field validator directives** enforcing real operational rules: driver **licence class** must match **service type**, fleet type must match service type, no duplicate tasks, changeover logic, weekend/date-time constraints, geofence rules, mass/load constraints.
- **Run model**: `RunPlanActivity` (planned: run_id, connote_id, run_action_id pickup=1/delivery=2/rest/refuel, order, geofence_id, timing) vs `RunEvent` (actual, captured by driver app). Multiple drivers per run (relief/changeover, sequence), multiple trailers (trailer_order_number).
- **Pre-dispatch compliance gates** (6 flags): fitness-for-duty checked, fleet checked, fatigue checked, location checked, load-restraint checked, mass/weights checked, plus a non-compliant override.
- On dispatch: generates **Safe Driving Plan**, **manifest**, **runsheet** PDFs, fires driver push notifications, creates geofence events.

**Where it lives.**
- `nicola/src/app/pages/dispatch/` (~25k LOC total): `dispatchplanner/` (5,511 LOC), `manifestdetails/` (4,042), `manifestlistv2/` (1,809), `local-dispatch/` (1,730), `run/` editor suite, `validators/*.directive.ts` (15 files)
- `nicola/src/app/services/dispatch.service.ts` (**38,934 LOC**), `model/dispatch.model.ts` (5,344 LOC)
- Backend: `DispatchController.php` (5,126 LOC), `LocalDispatchController`, `LocalDispatchControllerv2`, `Run*` controllers; 15 `run*` tables.

**iDrv5 target.** TMS `planLegs()`/`assignDriver()`/`buildManifest()`, Operations Portal, WorkM (dispatch tasks), Dispatch & Routing Model (§28 of spec), Manifest control (§29).

**Migration weight.** 🔴🔴 The most expensive carryover in the entire program. The combination of (a) drag-drop UX, (b) a 39k-LOC service, (c) 15 interlocking business-rule validators, (d) the planned-vs-actual run model, (e) compliance gating, and (f) document/notification side-effects means this is effectively a product within the product. **Allocate a dedicated squad and several months.** The v5 spec's WorkM/Workflow/Rules-Engine abstractions are the right home, but they must be built before this can land cleanly.

---

### 3.4 Driver Companion mobile app (`nadja`) (→ Driver App) 🔴

The mobile app is a second flagship. 60+ screens and several genuinely hard subsystems.

#### 3.4.1 Background GPS / geofencing / demurrage 🔴🔴 (top blocker)
- **Custom embedded Cordova plugin** `cordova-background-geolocation` v4.10.0 (Transistor Software, **commercial licence**) vendored in `nadja/bggeo/`.
- Config: `Always` auth, `stopOnTerminate:false`, `startOnBoot:true`, foreground service, heartbeat 60s, distanceFilter 500m, geofence high-accuracy, `autoSync`, `maxDaysToPersist:7`. Posts to `POST /api/geofence` with `driver_id`.
- **Geofences are created dynamically from job sites** when a run goes "En Route" (run_status=3). Tracks ENTER/EXIT/DWELL, de-dupes events, merges failed submissions with server events, and **computes demurrage** (waiting-time breach) against per-customer/per-job rate limits.
- `nadja/src/app/services/bggeo.service.ts` (17 KB), `breach.service.ts`.

**Weight.** 🔴🔴 Commercial-licensed native plugin + bespoke event-queue/merge/demurrage logic. Plugin choice is a **hard blocker** (re-license, replace, or rebuild native layer) that gates all location, geofence and demurrage features. Budget 5–6 weeks minimum.

#### 3.4.2 POD capture (signature + photos) 🟡
- `angular2-signaturepad` for recipient signature; camera + gallery multi-photo (min 4 images enforced on pickup); files → multipart → `POST /api/podReason`. `photographer.service.ts`.
- **Weight.** 🟡 Signature lib likely unmaintained; photo pipeline + validation is moderate.

#### 3.4.3 Electronic Work Diary / fatigue (→ ComplianceM/DriverM) 🔴
- Multi-tier logbook UI (Year → Month → Date → Entry → Details), manual entry, edit, email export; `compliance-checker.service.ts`, `logbookdata-refresh.service.ts`. Driving-hours & rest-period compliance. Backend: `DriverDiary`, `Logsheet`, `LogsheetJob`, `LogEntry` (`dwd_*` tables).
- **Weight.** 🔴 Regulatory (NHVR fatigue) correctness + complex state/date logic. Errors here are legal exposure.

#### 3.4.4 Vehicle inspection / pre-start / damage report 🟡
- Pre-start compliance checklist (`compasset.page.ts`, 31 KB), odometer/rego/VIN capture, photo-based damage reports, weekly inspection cycle.
- **Weight.** 🟡 Dynamic checklists + photo linkage.

#### 3.4.5 Fuel entry + receipt capture 🟡 (OCR is server-side — see §3.10)
- `addfuel.page.ts` is **enormous** (cited ~798 KB on disk); photo receipt capture, odometer, provider, location, per-shift date/time validation. **No on-device OCR** — manual entry; photos go to backend.

#### 3.4.6 Other mobile features
- Job/run workflow & status events (accept/reject, start, arrive, load, depart, deliver, finish, changeover, empty-run start/finish, collect/release, local variants), breach protocol, incident/traffic-ticket/stall/NCR reports, repair requests, payroll/payslip view, documents/licences, induction & licences, rest mode, change-departure-time, add-trailer, contacts.
- **Push:** OneSignal (`onesignal.service.ts`), geofence-driven navigation payloads.
- **Offline:** network-aware (blocks form submit when offline) + localStorage/Ionic Storage caching. **Not true offline-first** — no queued form sync. *(v5 spec §34/§24 expects offline UUID → `correlation_id` on sync; this is new work, not a carryover.)*

**Overall mobile weight.** 🔴 Full Ionic 5 → modern framework uplift + the two 🔴🔴 subsystems (background geo, work diary). Realistic feature-parity effort: **~9–11 months** of mobile work on its own.

---

### 3.5 Fleet / Asset Management (→ FleetM) 🟡–🔴

**What it does.** Vehicles & trailers with full lifecycle: specs, fleet types/subtypes, **insurance** (+ payments), **registration**, **tyre** lifecycle, **other costs**, **certificates / compliance modules**, maintenance/service history, repairs, **expiry tracking with alerts**, driver–truck **pairing** constraints, document/cert uploads, dynamic field visibility.

**Where it lives.**
- `nicola/src/app/pages/fleet/` (4.3k LOC) + `fleetassets/` (1,987 LOC), `viewfleet` (2,106 LOC)
- Services: `fleet.service.ts` (15k LOC), `fleetassets.service.ts` (11.2k LOC), `fleet-pairing.service.ts` (7.2k LOC), `fleet-subtype.service.ts`; `model/fleet.model.ts` (6.5k LOC)
- Backend: `TMS/FleetDetails/*`, ~15 fleet tables.

**iDrv5 target.** FleetM (Vehicle, Trailer, Equipment, Defect, Maintenance Event) + Assets domain. Note v5 spec keeps FuelM separate from FleetM.

**Weight.** 🟡 mostly, 🔴 for the compliance/expiry/pairing logic that feeds dispatch validation (a fleet's licence-class/subtype gates which service types it can run).

---

### 3.6 Driver Management (→ DriverM) 🟡

**What it does.** Driver records, licences & **licence classes** (drive dispatch eligibility), certifications, photos, compliance history, truck pairing, registrations, contact directories, fitness tests.

**Where it lives.** `nicola/.../drivers/driverdetails` (2,320 LOC), `driverslist` (1,023), `drivers.service.ts` (9.3k LOC), `driver-truck-pairing.service.ts` (6.5k LOC), `model/driver.model.ts` (3.3k LOC); backend `DriverController`, `driver*` tables.

**iDrv5 target.** DriverM (Driver, Licence Class, Availability) — with the rule that licence class governs dispatch eligibility (Rules Engine input per v5 §7/§19).

**Weight.** 🟡 CRUD-heavy but tightly coupled to dispatch validation and compliance expiry.

---

### 3.7 Customer Management (→ FMS / Master Data) 🟡

**What it does.** Customers, contacts & contact types, **per-customer default rates**, customer requests, search keys, customer registrations, customer-portal self-registration with email verification, billing addresses, branding/logo. New-subscriber onboarding (multi-step, ABN, company codes, control-number prefixes per document type) — see `NEW SUBSCRIBERS REGISTRATION PROCESS.docx`.

**Where it lives.** `narwhal` register/profile/rates; `nicola` customer admin; backend `Customers/*`, `customer*` tables.

**iDrv5 target.** Master Data (Customer) + FMS (Commercial Agreement, rate cards) + Customer Portal onboarding.

**Weight.** 🟡 — but the **control-number-prefix-per-document-type** scheme and per-customer rate cards need careful mapping to v5 Service Product / Commercial Agreement and sequence design.

---

### 3.8 Compliance system (→ ComplianceM) 🔴 (regulatory)

iDrv4 has a deep, audit-grade compliance stack. This is where v5's ComplianceM/NCR/LearningM converge.

- **NCR (Non-Conformance Reports):** category/code/classification/status taxonomy, driver/fleet/customer linkage, corrective actions, file evidence, PDF (`pdf/ncr.blade.php`), task creation. `nicola/qar/qar.component.ts` (1.8k LOC), backend `NcrController`, `ncr*` tables. → v5 **NCR Management (§51)** lifecycle Raised→…→Closed.
- **Safe Driving Plan (SDP):** generated per run, work/rest schedule, fatigue rules, driver+supervisor sign-off. `SDPController` (2,853 LOC), `pdf/sdp*.blade.php`. 🔴 regulatory.
- **Driver Work Diary / fatigue / breach** engine: `breach_requests`/`breach_responses`, work-hour & rest-period rules, geofence/fatigue breach detection → BreachRequest → notification.
- **Incident reports:** types, investigation sub-views, PDF, workflow.
- **Induction & competency:** `InductionController` is the **largest single file at 9,920 LOC** — multi-role induction sets, document-embedded questionnaires, multiple question types (MCQ/text/numeric/date/image), expiry tracking, PDF certificates. Question libraries D/L/T/R/V/Weekly. → v5 **LearningM**.
- **Alert/Expiry engine:** configurable AlertRule (trigger × action × timing × target) for licence/medical/rego/insurance/test/induction expiries, invoice/bill dues, task deadlines, booking start times, non-compliant driver/fleet tests, damage/incident reports. See `Task, Alerts and Reminders.docx`.
- **NHVAS / WAHVAS** accreditation tracking (numbers + expiry) per company.

**iDrv5 target.** ComplianceM (Declarations, Incidents, NCR, Corrective/Preventive Action, Verification), LearningM (Induction/competency), DriverM (fatigue), Rules Engine + Exception Framework + Notification Service.

**Weight.** 🔴 Across the board. Regulatory exposure (Chain of Responsibility, NHVR fatigue), the 9,920-LOC induction engine, and the alert-rule engine are each multi-week efforts. This is *not* a checkbox feature.

---

### 3.9 Fuel Management (→ FuelM) 🟡

**What it does.** Fuel entries (mobile + admin), fuel cards & card-change tracking, **fuel levy** computation feeding pricing, reconciliation, fuel sheets/receipts PDFs.

**Where it lives.** `nadja/addfuel`, `nicola/fuel/*`, `fuel_cards.service.ts` (3.9k LOC), `fuellevy.service.ts` (2.1k LOC); backend `FuelItemController` (2,458 LOC); `fuel_*` tables.

**iDrv5 target.** FuelM (`recordFuelEntry()`, `importFuelStatement()`, `reconcileFuelTransactions()`).

**Weight.** 🟡 plus the OCR sidecar (next).

---

### 3.10 Fuel receipt OCR 🔴 (external dependency)

**What it does.** Server-side OCR of fuel-receipt images. `API/TextExtractController.php` (`ExtractText()`) shells out via Symfony Process to a **Python script at `/usr/share/pyshared/ocr.py`** (NOT in any repo — external host dependency), passing S3 bucket+key, parsing JSON fields back, then ingesting in `FuelItemController`. Likely Tesseract / AWS Textract / Google Vision behind `ocr.py`.

**iDrv5 target.** FuelM + Integration Layer + Document Service. The v5 AI-native model is a natural home (a "fuel receipt extraction" agent/service).

**Weight.** 🔴 **The OCR implementation is not in the codebase** — it's an undocumented external Python script on the server. Reproducing it means rediscovering/rebuilding the extraction logic and field mapping. Flag as a discovery item *now*.

---

### 3.11 Document / PDF generation (→ Document Service) 🔴 (volume)

**What it does.** **57 Blade PDF templates** rendered via **WeasyPrint** (`rockett/weasyprint` v4) HTML→PDF, stored to S3. Barcodes via `milon/barcode`. Categories & examples:

- **Shipping:** Connote (modular header/body/footer), Manifest (+ variants), Runsheet/Tripsheet, Pickup/Delivery/Collect/Release dockets, **Proof of Pickup & Delivery (POD)**, Changeover, Packaging label (barcoded).
- **Finance:** Invoice (+ email variant), Credit Note.
- **Compliance/Safety:** Safe Driving Plan, NCR, Incident Report (modular), Work/Rest Timeline, Driver/User Responsibility & Commitment statements, Vehicle Policy Agreement, Fitness-for-Duty test (EN variants), Pre-Trip Vehicle Inspection (EN variants), Vehicle Damage Report.
- **Fleet/Maint:** Repair Request (+ EN/TMS variants), Inspection reports.
- **Fuel:** Fuel sheet, Fuel item.
- **Induction/Training:** Approval letters/certificates, assessment checklists/sheets, acknowledgements.
- **Other:** Weekly report, ticket, generic TMS table export.

**iDrv5 target.** Platform **Document Service** (secure object store + pre-signed URLs per v5 §23). Every document above is operational/legal evidence.

**Weight.** 🔴 by **volume and fidelity**. 57 templates, many with company-branding tokens, control numbers, barcodes, and signatures. Each is a real document a customer/regulator sees — pixel/format fidelity matters. WeasyPrint dependency + per-tenant branding must be reproduced. Budget this as a dedicated workstream, not an afterthought.

---

### 3.12 Location tracking & live map (→ TelematicsM + Operations/Customer Portal) 🔴

**What it does.** Two halves:
- **Ingestion:** driver app posts coordinates/geofence events → `POST /api/geofence` → `gps_logs`, `geofences`, `geofence_activities`, `RunPlanGeofenceEvent`, `RunPlanBreach`; pre-computed `routes_klms` distance/time matrix; `getTotalKlmsHrsByCoordinates()` for costing.
- **Live map UI:** `nicola` + `narwhal` **map trackers** read **Firebase Firestore** `Drivers` collection (lat/lng/ETA/job/fleet), Google Maps markers + info windows, driver search, **5-minute polling refresh**.

**Where it lives.** `nicola/maptracker` (254 LOC) + dashboard map; `narwhal/maptracker` (241 LOC) + `maptracker.service.ts`; backend `GeofenceController`, `MapController`, geofence/location models.

**iDrv5 target.** TelematicsM (v5 §21 mandates **high-frequency GPS routes through a dedicated time-series pipeline, e.g. TimescaleDB**, before aggregated business events hit the Event Bus). The current Firestore-polling approach is **not** what v5 prescribes — this is a re-architecture, not a port.

**Weight.** 🔴 Custom geofence/breach/demurrage logic (shared with §3.4.1), plus the Firestore→TimescaleDB re-platform. The hardcoded Google Maps API keys in client source are a security item to fix in transit.

---

### 3.13 Rate / Pricing engine (→ FMS Rate Engine + Charge Engine) 🔴 (financial)

**What it does.** Computes job cost. Per `Rate Computations.docx` (and implemented in `BookingController`/`InvoiceController`):

- **Total Job Cost = Basic Rate + Other Costs − Service Fee.**
- **5 charging methods:** Hourly, Distance, Tonnes, Load, **Pallets** (with cubic-weight: `Cubic Weight = Volume m³ × 333 kg/m³`, charge weight = max(physical, cubic), chargeable pallets = charge weight ÷ max-weight-per-pallet).
- **Other costs (surcharges):** Fuel Levy, Tail Lift (per pallet, HR/Semi only), Hand Unload (per pallet, HR only), Residential location fee, Extra Pickup/Delivery (BDBL linehaul), DG Freight (10% packed / 20% bulk), Trailer Split (BDBL), Extra Crew/Jockey (per pallet), After-Hours (5PM–6AM), Overnight Holding (HR/Semi/BDBL tiers), Futile Pickup/Delivery (per pallet), **Demurrage** (per-vehicle-class hourly after 90-min free wait).
- **Rate sources:** `CustomerDefaultRate` (per-customer) → `JobCostDefault` (fallback) → `CostingAddon`; default rates in Settings.

**iDrv5 target.** FMS **Rate Engine (§26)** + **Charge Engine (§27, incl. demurrage formula)**. v5 adds rate-card versioning (`effective_from`/`effective_to`) and zone-pair evaluation — **new structure to map the legacy flat rates onto.** The JATT Excel rate sheets (`JATT FTL Rates.xlsx`, `JATT Rates/`) are the data side of this.

**Weight.** 🔴 Financial correctness + many conditional surcharge rules tied to vehicle class (HR/Semi/BDBL) and service. Every rule is money. Must be ported exactly *and* restructured into v5's versioned rate-card model.

---

### 3.14 Invoicing & Billing (→ FinSM) 🔴 (financial + integration)

**What it does.** Invoice create/edit/list/details/email; multi-job line items (FormArray); mark-paid, due dates, notes, statuses, histories; credit notes (+ allocations, regions, accounts, types); invoice banks; payment terms/types/currencies; **Xero sync**; invoice/credit-note PDFs + email; "is_invoice_ready" gating from operations.

**Where it lives.** `nicola/invoices/*` (5k LOC) + `bills/*`; `invoiceedit` (1,336 LOC), `invoicecreate` (1,106); `bills.service.ts` (10.2k LOC); backend `InvoiceController` (3,397 LOC); ~20 invoicing/billing tables; Xero integration (§3.17).

**iDrv5 target.** FinSM (`createCharge()`, `prepareInvoice()`, `issueInvoice()`, `applyPayment()`, `adjustInvoice()`) + Billing Release controls (v5 §30) + Supplier Invoice (v5 §49, **new AP three-way-match** — partially new).

**Weight.** 🔴 Revenue-critical, Xero-coupled, gated by operational completion. v5 adds formal billing-release conditions and supplier-invoice AP — map carefully.

---

### 3.15 Payroll (→ FinSM / StaffM) 🔴 (financial)

**What it does.** Driver pay computed from runs/manifests: distance/hourly/tonne/load/pallet rates, weekly/fortnightly/monthly periods, manifest-level aggregation, rate tiers & surcharges, payslip PDFs, driver totals/summaries.

**Where it lives.** `nicola/payrolls/*` (2k LOC), `payrolldetails` (761 LOC); backend `PayrollController` (2,174 LOC); ~15 `payroll_*` tables.

**iDrv5 target.** FinSM (carrier costing/settlements) / StaffM. **Note:** payroll is only lightly addressed in the v5 spec — confirm whether it stays in scope. If yes, it is a 🔴 financial workstream; if it moves to an external payroll system, that's a new integration decision.

**Weight.** 🔴 (if in scope) — financial calcs, audit requirements, tied to dispatch/manifest data.

---

### 3.16 Notifications, Alerts, Reminders & Tasks (→ Platform: Notification Service + WorkM) 🟡–🔴

**What it does.** Three-tier notification settings (Global / Business / Customer), per-event email/SMS/push routing, attachments + recipient types; the **AlertRule engine** (§3.8); **Tasks** (assignable, statuses, priorities, created from alerts/NCRs); reminders (global, recurring); in-app messaging; job/task notification feeds. Channels: SES email, Twilio SMS, OneSignal push.

**Where it lives.** Backend `NotificationController` (990 LOC), `AlertController` (144 LOC), `TaskController`, `MailController` (3,716 LOC); `nicola` messaging/tasks/jobnotifications; ~10 notification tables + ~10 alert tables.

**iDrv5 target.** Platform **Notification Service** + **WorkM** (tasks) + **Rules Engine** (alert triggers) + **Exception Framework**. Strong alignment with v5 — but the iDrv4 alert-rule combinatorics (trigger × timing × action × target with validation tables) must be reproduced.

**Weight.** 🟡 routing; 🔴 the alert-rule engine + the 3,716-LOC mail orchestration.

---

### 3.17 Integrations (→ Integration Layer) 🔴 (Xero) / 🟡 (rest)

| Integration | What | Where | v5 target | Weight |
| ----------- | ---- | ----- | --------- | ------ |
| **Xero accounting** | OAuth2 (`webfox/laravel-xero-oauth2`), invoice/bill/credit-note/contact/account sync, webhooks (paid status), 35 PHP files + UI mapping screens in narwhal/nicola | `ceres/app/Integrations/xero/`, `nicola/src/lib/integrations/xero/` | FinSM ↔ Accounting (v5 §21 field-mapping: Invoice→Invoice, charge_code→Account Code, GST→Tax Rate) | 🔴 financial state-sync |
| **Transvirtual** freight exchange | Publish connote/POD, receive status; event-driven listeners | `ceres/Transvirtual/*` | TMS/Integration (EDI-style carrier exchange) | 🟡–🔴 |
| **Dyspach** quote engine | External quote API, response mapping, price-lock | `nebula/services/dyspach-*` | FMS rate/quote integration | 🟡 |
| **OneSignal** push | Driver/staff push (dispatch, breach, reminders) | `ceres` + `nadja` | Notification Service | 🟡 |
| **Twilio** SMS | Job/POD/breach SMS | `ceres` NotificationController | Notification Service | 🟢 |
| **AWS SES** email | All transactional email | `ceres` MailController | Notification Service | 🟢 |
| **AWS S3** storage | All documents, uploads, receipts | `ceres` | Document Service | 🟡 (→ pre-signed URLs per v5 §23) |
| **Google Maps** | Geocode, distance matrix, autocomplete, tracking display | all front-ends + `MapController` | Master Data / Telematics | 🟡 (centralise keys) |
| **Third-party OAuth API** | External systems get scoped OAuth clients (consignment.read/write/status), rate-limit tiers, webhooks (`CallWebhookJob` w/ backoff) | `ceres/ThirdParty/*`, `API/V3/*`, `Postman - iDrv4 Integration/` | Integration Layer + Capability API (v5 `/v1/` versioning) | 🟡 |

**Weight.** Xero is 🔴 (financial integrity, token refresh, webhook signing, bidirectional state). The third-party scoped-OAuth API is itself a carryover *contract* — external customers already integrate against it; v5 must honor or formally version it (see `Postman - iDrv4 Integration` collection in Downloads).

---

### 3.18 Auth & Multi-tenancy (→ IAM) 🔴 (security)

**What it does.** Laravel Passport OAuth2; role + sub-role permissions; four login contexts (Driver/Admin/Customer/Staff middleware injecting context); API-key auth; **per-domain multi-tenancy** (`gecche/laravel-multidomain` — per-domain `.env`, shared codebase, tenant scoping via customer_id/business_id); scoped OAuth clients with `ResolveClientCustomer` + `CheckClientScope`; **component-settings feature-flag system** (`nicola/components_settings.service.ts`, 8.2k LOC) that drives per-role dynamic routing/menus.

**iDrv5 target.** IAM + v5 multi-tenant standard: **Row-Level Security (RLS) at the DB layer**, OAuth2/JWT, API-gateway rate limiting per tenant (v5 §23). The iDrv4 per-domain model is materially different from v5's RLS multi-tenant model — **this is a re-architecture**, and every data-access path depends on getting tenant isolation right.

**Weight.** 🔴 Security-critical; the tenancy model itself changes.

---

### 3.19 Reporting & Dashboards (→ AnalyticsM + Control Tower) 🟡

**What it does.** Operations dashboard (cost summary: total/fleet/wage/fuel/maintenance, profit/loss, expiries, activity feed, live driver map, available drivers/customers, booking counts); customer dashboard (KPIs, profit/cost charts via ngx-charts/d3); **DIFOT** reporting (Delivery In Full On Time — a named legacy feature); additional TMS reports; CSV/PDF/Excel export everywhere.

**Where it lives.** `nicola/dashboard` (413 LOC) + `dashboard.service.ts` (1.8k LOC); `narwhal/dashboard`; backend report controllers.

**iDrv5 target.** AnalyticsM + **Control Tower** (v5 §22/§41) read model. v5's event-driven analytics store supersedes the current direct-aggregation approach.

**Weight.** 🟡 Re-implement on v5 analytics/read-model; DIFOT and the cost/profit aggregations carry specific business definitions to preserve.

---

### 3.20 Settings & Configuration (→ Admin Portal + Master Data) 🟡

**What it does.** ~22 settings areas in `nicola/settings/`: business profile/branding, alert rules & templates, costing/default rates, job-cost defaults, fleet service intervals, fleet subtypes, **checklists** (driver/vehicle pre-trip), corrective-action templates, employee positions, invoice banks, notification settings, payroll settings, **route templates** (reusable dispatch routes), service types, weekly-report settings. Plus super-admin: cross-org accounts + component/feature flags.

**iDrv5 target.** Admin Portal + Master Data + Rules Engine config.

**Weight.** 🟡 large surface, mostly CRUD, but it's the configuration backbone every other module reads.

---

## 4. The genuinely hard features — ranked (where the schedule is won or lost)

Sorted by migration risk × effort. **These nine are the program.**

| Rank | Feature | iDrv4 weight signal | Why it's hard | v5 home |
| ---- | ------- | ------------------- | ------------- | ------- |
| 1 | **Dispatch editor & run planning** | 5.5k-LOC component + **38.9k-LOC service** + 15 validators + 5.1k-LOC backend ctrl | Drag-drop UX, planned-vs-actual model, interlocking compliance rules, doc/notification side-effects, linehaul+local×v1/v2 | TMS, WorkM, Operations Portal |
| 2 | **Driver mobile app** (whole) | 60+ screens, Ionic 5 | Full framework uplift + two 🔴🔴 subsystems below | Driver App |
| 3 | **Background GPS / geofence / demurrage** | Commercial native plugin + bespoke event engine | Licensed Cordova plugin (blocker), event de-dup/merge, demurrage calc, offline | TelematicsM, Driver App |
| 4 | **Induction & competency engine** | **9,920 LOC** (largest file) | Multi-role sets, embedded questionnaires, expiry, certificates, question libraries | LearningM, ComplianceM |
| 5 | **Rate + Charge engine** | dozens of conditional surcharge rules | Financial correctness, vehicle-class-specific rules, cubic-weight math, must restructure to versioned rate cards | FMS Rate/Charge Engine |
| 6 | **Invoicing + Xero sync** | 3.4k-LOC ctrl + 35-file Xero integration | Revenue integrity, bidirectional state, webhooks, billing-release gating | FinSM, Integration |
| 7 | **Compliance / SDP / fatigue / NCR / alerts** | SDP 2.8k-LOC ×2, breach + alert engines | Regulatory exposure (NHVR/CoR), document fidelity, alert combinatorics | ComplianceM |
| 8 | **PDF document service (57 templates)** | 57 Blade + WeasyPrint + barcodes | Volume + legal fidelity + per-tenant branding | Document Service |
| 9 | **Multi-tenancy & IAM** | per-domain model + 8.2k-LOC feature-flag svc | Tenancy model *changes* (per-domain → RLS); every query depends on it | IAM, Platform |

Honourable mentions (🔴 but more contained): **Fuel receipt OCR** (external script — discovery risk), **Payroll** (if in scope), **booking form** (~5k-LOC × 3 portals).

---

## 5. External dependencies & blockers to resolve NOW

These gate other work; surface them in week 1.

1. **`cordova-background-geolocation` (Transistor) — commercial licence.** Decide: re-license for v5 stack, swap to an equivalent (e.g. a Capacitor background-geolocation), or rebuild the native layer. Blocks all location/geofence/demurrage. *(Also a security note: hardcoded Google Maps API keys live in client source today.)*
2. **`ocr.py` fuel-receipt OCR — not in any repo.** It's a Python script on the server (`/usr/share/pyshared/ocr.py`). Find it, or treat the extraction logic as a rebuild/discovery item.
3. **WeasyPrint** HTML→PDF + **milon/barcode** — confirm the v5 stack's document-rendering choice; 57 templates depend on it.
4. **Xero** OAuth app, scopes, webhook key, and the GL **account-mapping** config are live financial config — inventory before touching FinSM.
5. **Firebase Firestore** currently backs live tracking. v5 §21 mandates a time-series pipeline (TimescaleDB) instead — decide migration path and dual-run strategy.
6. **Third-party OAuth API consumers** already integrate against iDrv4 (`Postman - iDrv4 Integration` collection). v5 must version (`/v1/`) and maintain or deprecate these contracts deliberately — external partners depend on them.
7. **`angular2-signaturepad`** and several Angular-11-era libs (ngx-datatable 18, @agm/core, ng2-dragula, mydatepicker) are aging — choose v5 replacements up front.
8. **Per-customer control-number prefixes & sequences** (connote, manifest, invoice, runsheet, SDP, POD, work diary, fuel, NCR, etc.) are tenant config that must survive migration intact (legal document numbering).

---

## 6. Terminology & canonical-model mapping (iDrv4 → iDrv5)

| iDrv4 term / structure | iDrv5 canonical | Action |
| ---------------------- | --------------- | ------ |
| Booking / Job | Booking → **Consignment** | Split commercial (Booking, FMS) from operational (Consignment, TMS) |
| Connote (integer id + control_no) | **`consignment_id` (UUID) + `connote_number`** | Adopt UUID PKs; connote_number stays customer-facing |
| "Shipment" (any legacy use) | **deprecated** | Remove; never use in v5 |
| Run / RunPlanActivity / RunEvent | Leg / Task / Manifest + Milestone/POD | Re-home in TMS; keep planned-vs-actual distinction |
| Customer default rate / job cost default | Commercial Agreement + **versioned Rate Card** | Add `effective_from`/`effective_to`, zone pairs |
| Fleet / fleet subtype | Vehicle / Trailer / Equipment | FleetM; subtype→service-type eligibility = Rules Engine |
| NCR / breach / SDP / induction | NCR, Declaration, Incident, Verification, Competency | ComplianceM + LearningM |
| Per-domain tenant (`.env` per domain) | **Row-Level Security** + `tenant_id` | Re-architect to RLS multi-tenancy |
| Geofence event / demurrage | Telematics event → business event + Charge Engine demurrage | Route via time-series pipeline first |
| Document (WeasyPrint Blade → S3) | Document Service + pre-signed URLs | Re-home, keep template fidelity |

---

## 7. Recommended migration sequencing (carryover lens)

This complements the v5 spec's build-readiness prerequisites (§25):

1. **Foundations:** canonical domain + UUIDs, **RLS multi-tenancy & IAM**, Event Bus, Document Service, Master Data (customers, rates, sequences/prefixes). *Nothing real ships until tenancy is right.*
2. **Commercial intake:** FMS Booking/Quote + **Rate & Charge engine** (port the surcharge rules exactly, restructure into rate cards) + public quote funnel.
3. **Operational core:** TMS Consignment/Connote management → **Dispatch editor & run planning** (the long pole — start the squad early) → manifests/runsheets/SDP documents.
4. **Driver app:** in parallel with #3 — resolve the geolocation-plugin blocker first, then job workflow, POD, work diary, inspections, fuel.
5. **Compliance & Learning:** NCR, fatigue/breach, alert-rule engine, induction engine.
6. **Finance:** charges → billing release → invoicing → **Xero** → payroll (if in scope).
7. **Visibility:** AnalyticsM + Control Tower; DIFOT and cost/profit dashboards.
8. **Integrations & long tail:** Transvirtual, Dyspach, third-party OAuth API (versioned), fuel OCR.

---

## 8. Appendix

### A. Source repositories
- `ceres-laravel8-restapi` — backend (Laravel 8, 146 controllers, 283 models, ~205 tables, 57 PDFs)
- `nadja-ionic5-mobile-app` — driver app (Ionic 5, 60+ screens, `bggeo/` custom plugin)
- `nicola-angular11-webclient` — Admin/Operations Portal (~130k LOC; dispatch, fleet, drivers, payroll, invoicing, compliance, settings)
- `narwhal-angular11-webclient` — Customer Portal (bookings, tracking, compliance, rates, invoices)
- `nebula-angular11-webclient` — Public Quote/Booking Portal (+ Dyspach)

### B. Legacy product documentation reviewed (`working documents/`)
- *Admin Portal User Manual.pdf*, *Driver Companion App Manual.pdf* — full UX of the systems being replaced.
- *BOOKING FORM.docx*, *Rate Computations.docx* — exact booking fields & all pricing/surcharge formulas (authoritative for §3.13).
- *Task, Alerts and Reminders.docx* — the default + custom alert catalogue (authoritative for §3.16/§3.8).
- *NEW SUBSCRIBERS REGISTRATION PROCESS.docx* — onboarding + per-document control-number prefixes (authoritative for §3.7).
- *CUSTOMER PORTAL.docx*, *Logicor Services.docx*, *LOGICOR TMS AND APPS.docx*, *LOGICOR system overview.pdf*, *logicor-2.pdf*, *terms_and_conditions.pdf*, *LOGICOR TMS Flow Chart.png* — product context & the 5-stage business flow (§1).

### C. Companion data assets (in `~/Downloads/`)
- `JATT FTL Rates.xlsx`, `JATT Rates/` — rate-card source data for the Rate Engine.
- `Postman - iDrv4 Integration/` — live third-party API contracts (carryover obligations).
- DB dumps (`dump-*idrv*`, `jatt-ceres.sql*`) — the production schema/data to migrate.

### D. Document inventory (57 PDF templates) — categories
Shipping (connote, manifest, runsheet/tripsheet, dockets ×4, POD, changeover, packaging label) · Finance (invoice, credit note) · Compliance (SDP, NCR, incident, work/rest timeline, responsibility/commitment statements, vehicle policy, fitness-for-duty, pre-trip inspection, damage report) · Fleet/Maint (repair request, inspections) · Fuel (fuel sheet, fuel item) · Induction/Training (approval letters/certificates, assessments, acknowledgements) · Reporting (weekly report, ticket, TMS table export).

---

*Prepared from direct inspection of the iDrv4 source repositories and legacy product documentation. Every line count, file path, and table count in this document is measured from the code, not estimated. Use it to scope the v5 program with eyes open: the new LOS features are roughly half the job — the other half is faithfully carrying ten years of working freight operations across.*
