# FleetTruck360 — Truck Fleet & Transport Business Management System
## Complete Software Specification (v3 — consolidated)

| | |
|---|---|
| **Document** | Software specification (requirements + technical design) |
| **Status** | Design phase — approved decisions v1 → v3 consolidated. **No implementation yet.** |
| **Date** | 2026-11-14 |
| **Audience** | Developers who will build the system, and the owner/client who approves it |
| **Visual design** | `doc/design/*.html` (clickable mockups) · `doc/DESIGN_GUIDE.md` |

> **Source documents**
> 1. `Truck Fleet & Transport Business Management System – Complete Development Prompt.txt` — the **system / coding conventions**. ⚠️ This file is written for a **School Management System**. Every rule in it is adopted here with **School → Company** (e.g. `school_id` → `company_id`, `BelongsToSchool` → `BelongsToCompany`). School-only concepts (academic sessions, classes, exams…) are dropped.
> 2. `truck_driver_trip_sheet_details.docx` + `Screenshot from 2026-11-14 08-32-21.png` — the **trip sheet logic** (the paper "Truck Driver Trip Sheet" used by RanaBros, Fort Worth TX). The digital trip sheet reproduces this form exactly.
> 3. Client decisions given during design rounds v1, v2, v3 (latest decision wins).

---

## Table of Contents
1. [Overview & Goals](#1-overview--goals)
2. [Technology Stack](#2-technology-stack)
3. [Architecture & Conventions](#3-architecture--conventions)
4. [SaaS Model — Tenancy, Signup, Trial, Plans, Billing](#4-saas-model)
5. [Users, Employees, Roles & Permissions](#5-users-employees-roles--permissions)
6. [Modules](#6-modules)
7. [Trip Sheet — Full Logic](#7-trip-sheet--full-logic)
8. [Driver Weekly Settlements](#8-driver-weekly-settlements)
9. [Dashboards](#9-dashboards)
10. [Reports](#10-reports)
11. [Filters & Sorting Standard](#11-filters--sorting-standard)
12. [Support Tickets](#12-support-tickets)
13. [Help Center & User Guidance](#13-help-center--user-guidance)
14. [Notifications & Announcements](#14-notifications--announcements)
15. [Company Profile & Settings](#15-company-profile--settings)
16. [Database Schema](#16-database-schema)
17. [API Endpoint Catalogue](#17-api-endpoint-catalogue)
18. [Frontend Structure](#18-frontend-structure)
19. [UI/UX & Design System](#19-uiux--design-system)
20. [Non-Functional Requirements](#20-non-functional-requirements)
21. [Delivery Phases](#21-delivery-phases)
22. [Open Items & Assumptions](#22-open-items--assumptions)

---

## 1. Overview & Goals

**FleetTruck360** is a multi-company **SaaS** web application (installable on phones as an app) for trucking companies to digitise the paper **Truck Driver Trip Sheet** and run the related business: fleet, drivers, trips, fuel & state mileage, expenses, revenue, driver pay, reports — plus the SaaS business around it (plans, trials, payments, support).

### 1.1 Goals
| # | Goal |
|---|---|
| G1 | Replace the paper trip sheet with a digital one that matches it field-for-field, with automatic totals and validation. |
| G2 | Let drivers **or** office staff fill trip sheets — controlled entirely by permissions the company owner grants. |
| G3 | Give owners real-time visibility: miles, gallons, MPG, expenses, revenue, driver pay, profit, per truck/driver/state. |
| G4 | Capture state-wise miles and gallons per trip as source data for IFTA record-keeping. |
| G5 | Weekly driver settlement (pay) statements. |
| G6 | Run as SaaS: many companies, public signup with a 14-day trial, plans with limits and module locks, cash/bank-transfer payments verified by the Super Admin. |
| G7 | **Mobile-first, app-like, attractive, simple and fast** — most usage is on phones. |

### 1.2 Actors
| Actor | Description |
|---|---|
| **Super Admin** (and platform staff) | Owns the platform. Manages companies, plans, subscriptions, payments, tickets, help articles, announcements, jurisdictions. Not tied to any company. |
| **Company Owner** | Created at signup/onboarding. Has every permission in the company; cannot be locked out. |
| **Company Employee (staff)** | Dispatcher, Accountant, Manager or any custom role — login + role assigned by the owner. |
| **Driver** | An employee flagged as driver. May have a login; what they can do depends on permissions granted by the owner. |

### 1.3 Out of scope (current phases)
Branches/yards/terminals (removed by client decision), GPS/ELD integration, customer invoicing, online card payments (Phase 3), IFTA tax calculation (Phase 2).

---

## 2. Technology Stack

| Layer | Technology |
|---|---|
| Backend | **Laravel 12** (PHP 8.3), REST JSON API under `/api/v1` |
| Auth | **Laravel Sanctum** (bearer tokens for the SPA/PWA) |
| Roles / permissions | **Spatie laravel-permission** with **teams = `company_id`** |
| Database | **MySQL 8** (InnoDB, `utf8mb4_unicode_ci`); local dev on **XAMPP** (`/opt/lampp`) |
| Queue / scheduler | Laravel database queue driver; Laravel scheduler (cron) for trial reminders, renewals, expiry alerts |
| PDF | `barryvdh/laravel-dompdf` — trip sheet (paper replica), settlement statement, invoice, receipt |
| Excel | `maatwebsite/excel` — export of every list/report, data export |
| Files | Laravel Storage (`public` disk locally; S3-compatible later) — logos, receipts, BOL/POD, signatures, payment proofs, ticket attachments |
| Push | `laravel-notification-channels/webpush` (VAPID Web Push) |
| Mail | Laravel Mail (SMTP) |
| Frontend | **React 18 + Vite + React Router 6** (separate SPA) |
| UI | **Bootstrap 5** + bootstrap-icons, custom design tokens (§19) |
| Charts | **Chart.js** |
| HTTP | Axios (token header) |
| Mobile app feel | **PWA** via `vite-plugin-pwa` (installable, splash, icons, offline shell, offline drafts) |
| Other FE libs | `react-signature-canvas` (signatures), `browser-image-compression` (receipt photos), `driver.js` (page tours) |
| Real-time (Phase 2) | Laravel Reverb (WebSockets). Phase 1 uses 60-second polling + Web Push. |

---

## 3. Architecture & Conventions

### 3.1 Repository layout
### 3.1 Repository layout — backend and frontend are separate applications
The **backend (Laravel API) and frontend (React) are two independent applications**: own folder/repo, own dependencies, own build and deployment. They communicate **only through the versioned JSON API** (`/api/v1`). The same API serves every client — company web app, phone PWA, Super Admin panel, a future native app and partner integrations — and all business rules, calculations, permissions and plan limits live in the API. Full API design: **[API_SPEC.md](API_SPEC.md)**.

```
keep-trucking/
├── backend/        Laravel 12 REST API
│   ├── app/Http/Controllers/Api/<Module>/...
│   ├── app/Models/ (+ Concerns/BelongsToCompany, Concerns/Auditable)
│   ├── app/Services/<Module>/...
│   ├── app/Support/{Access, Settings, Tenant, Permissions/<module>.php, Dashboard/<module>.php}
│   ├── routes/api.php  (+ routes/api/<module>.php auto-required)
│   └── database/{migrations, seeders/Modules, data/menus.json}
├── frontend/       React 18 SPA / PWA
│   └── src/{api, auth, components, modules/<module>/index.jsx, styles, utils}
└── doc/            This specification + design mockups
```

### 3.2 Conventions mapping (.txt School system → this project)
| .txt (School system) | FleetTruck360 |
|---|---|
| `schools`, `school_id`, `BelongsToSchool` | **`companies`, `company_id`, `BelongsToCompany`** — global scope on current company + auto-fill `company_id` |
| `Tenant::id()` | `Tenant::id()` = current company id (null for Super Admin platform routes) |
| `SubscriptionPlan`, `SchoolSubscription` | `SubscriptionPlan`, `CompanySubscription` |
| `Campus` | **Removed** (no branches) |
| `SchoolSetting`, `Settings::get()` | `CompanySetting`, `Settings::get('trips.variance_pct')` |
| `Employee` (`is_teacher`), `Department`, `Designation` | `Employee` (**`is_driver`**), `Department`, `Designation` |
| `AcademicSession` | **Removed** — reports use date ranges / quarters |
| `Student`, `Guardian`, classes, exams… | **Removed** |
| `Auditable`, `AuditLog`, `LoginHistory`, `UserNotification`, `Notifier` | Kept as-is |
| `CrudController`, `Route::crud`, `routes/api/<module>.php` | Kept as-is |
| `app/Support/Permissions/<module>.php`, `php artisan sms:sync-permissions` | Kept; command renamed **`php artisan tms:sync-permissions`** |
| `Access::portalStudentIds()` etc. | **`Access::scopeTrips($q, $user)`**, **`Access::ensureTrip($user, $tripId)`**, `Access::isDriverOnly($user)`, `Access::driverEmployeeId($user)` |
| `app/Support/Dashboard/<module>.php` | Kept — each module contributes dashboard widgets |
| Portal endpoints `/portal/...` | **`/portal/...`** = driver self-service endpoints (own trips, own pay) |
| Dynamic `menus` table + Menu Manager | Kept; `company_id NULL` = Super Admin platform menu |
| Appearance (`data-theme`, `data-bs-theme`, `data-sidebar`, CSS vars `--sms-*`) | Kept; CSS vars renamed **`--tms-*`** |
| `.print-sheet` + `window.print()` | Kept — printable trip sheet, settlement, invoice |

### 3.3 Backend rules (restated for this project)
**Multi-tenancy**
- Every company-owned table has `company_id` (FK → `companies`, cascade delete); the model uses `BelongsToCompany`.
- Models whose changes matter use `Auditable` (trips, trip lines, expenses, settlements, payments, plans, settings, users/roles, employees, trucks).
- **Never trust `company_id` from the request.** Foreign-id validation must be tenant-safe: in a `CrudController` use `$this->existsInCompany('table')` / `$this->uniqueInCompany('table','column',$model)`; elsewhere `Rule::exists('table','id')->where('company_id', Tenant::id())`.
- Middleware stack for company routes: `auth:sanctum` → `tenant` → `subscription` (read-only enforcement) → per-route `plan.feature:<key>` and permission checks.

**Models** — `protected $guarded = ['id'];` + `casts()`; typed relationships. Relations serialize snake_case (`expenseCategory` → `expense_category`).

**Migrations** — module timestamp prefixes:

| Prefix | Module |
|---|---|
| `2026_01_01_*` | Core (companies, users, settings, audit, menus, notifications, roles) |
| `2026_01_02_*` | Fleet (trucks, trailers) |
| `2026_01_03_*` | Employees & drivers (departments, designations, employees, driver_details) |
| `2026_01_04_*` | Parties (shippers/consignees) + lookups (jurisdictions, expense_categories) |
| `2026_01_05_*` | Trips (trips, stops, state mileages, expenses, attachments, status logs) |
| `2026_01_06_*` | Pay / settlements |
| `2026_01_07_*` | Notifications, announcements, push, tours, saved filters |
| `2026_01_08_*` | Platform & billing (plans, subscriptions, invoices, payments, bank accounts, tickets, help) |

FKs only to core tables or the module's own tables; cross-module references use a nullable indexed `unsignedBigInteger` without FK. Soft deletes where records must be recoverable. Scoped unique constraints (`unique(['company_id','trip_no'])`).

**Controllers** — simple CRUD extends `App\Http\Controllers\Api\CrudController` (`$model`, `$permission`, `$with`, `$searchable`, `$filterable`, `$sortable`, `$defaultSort`, `$fileFields`, `rules()`, hooks `indexQuery/beforeSave/afterSave/beforeDelete/dateColumn`). Index supports `?q=`, filters, `?sort=-col,col2`, `?per_page=`, `?all=1`, `?date_from/date_to`. Workflow actions (submit, approve, pay, verify…) are extra controller methods wrapped in `DB::transaction` with `abort_unless($user->can('x.approve'), 403)`. Responses: list = paginator JSON or `{data:[...]}`; single = `{data:{...}, message?}`; errors = `abort(422,'msg')` / validation exceptions. Namespace `App\Http\Controllers\Api\<Module>\...`; reusable logic in `app/Services/<Module>/...`.

**Routes** — `routes/api/<module>.php`, auto-required inside the `auth:sanctum` + `tenant` group. `Route::crud('uri', Controller::class)` macro + explicit custom routes with `{id}`. kebab-case URIs. Uploads = multipart POST with `_method=PUT` for updates. Platform routes live in `routes/api/platform.php` inside an `auth:sanctum` + `super_admin` group.

**Permissions** — `app/Support/Permissions/<module>.php` returns `['group'=>..., 'permissions'=>[...], 'roles'=>[...]]`. Company Owner gets everything automatically. Run `php artisan tms:sync-permissions` after changes.

**Settings** — `App\Support\Settings::get('key')` with `Settings::DEFAULTS` (keys in §15).

**Notifications** — `App\Services\Notifier::toUsers($ids, $title, $body, ['type'=>..,'link'=>..])`, `Notifier::toRoles(...)`, `Notifier::toDrivers(...)`, `Notifier::toCompanyOwners($companyIds, ...)` — in-app + email + push per user preference.

**Dashboard** — `app/Support/Dashboard/<module>.php` returns `fn (Request $r): ?array`; keys are merged into `GET /dashboard`. Each widget checks permission **and plan feature** and returns `null` if not allowed. Honours `date_from`, `date_to`, `truck_id`, `driver_id`.

**Seeders** — demo data in `database/seeders/Modules/<Module>Seeder.php`, idempotent, small. Platform seeders: jurisdictions, standard plans, default expense categories template, help categories, Super Admin user.

### 3.4 Frontend rules
- Module = `src/modules/<module>/index.jsx` default-exporting `{ menu, routes, widgets?, dashboards? }`; auto-discovered by `src/modules/registry.js` (do not edit `App.jsx`).
- Menu item `{ label, path, permission, feature?, order, userTypes? }`; route `{ path, element, permission, feature? }` (router guards both).
- Building blocks in `src/components`: `ResourcePage`, `FormField`/`FormRenderer`, `DataTable`, `FilterBar`, `FilterSheet`, `Modal`, `BottomSheet`, `ui.jsx` (`PageHeader`, `Card`, `StatCard`, `StatusBadge`, `Pagination`, `Tabs`, `Loading`/`Skeleton`, `EmptyState`), `hooks.js` (`useFetch`, `useOptions`, `useUrlFilters`), `Toast`.
- `src/api/client.js` — `api`, `errorMessage`, `validationErrors`, `toFormData`, `fileUrl`, `download`.
- `src/auth/AuthContext.jsx` — `useAuth()` → `user`, `company`, `plan`, `can()`, `hasFeature()`, `isDriver`, `isSuperAdmin`; `<Can permission>`, `<Feature name>`.
- Printables render inside `.print-sheet` and call `window.print()`; PDFs also available from the API.
- Appearance via `<html data-theme data-bs-theme data-sidebar>`; use CSS variables only, never hard-coded brand colours; charts use `themeColors()`.

### 3.5 Modules (backend namespace ↔ frontend module)
| Module | Backend namespace | Frontend module | Menu group (order) |
|---|---|---|---|
| Platform (Super Admin) | `Api\Platform` | `platform` | platform (5) |
| Core (auth, users, roles, settings, menus, profile) | `Api\Core` | `settings`, `account` | settings (180) |
| Dashboard | `Support\Dashboard\*` | `dashboard` | dashboard (0) |
| Fleet (trucks, trailers) | `Api\Fleet` | `fleet` | fleet (40) |
| Employees & Drivers | `Api\Employees` | `employees` | employees (50) |
| Parties (shippers/consignees) | `Api\Parties` | `parties` | parties (60) |
| Trips (trip sheets) | `Api\Trips` | `trips` | trips (10) |
| Settlements | `Api\Settlements` | `settlements` | settlements (20) |
| Reports | `Api\Reports` | `reports` | reports (100) |
| Billing (company side) | `Api\Billing` | `billing` | billing (170) |
| Support & Help | `Api\Support` | `support` | support (150) |
| Communication (announcements, notifications) | `Api\Communication` | `communication` | communication (140) |
| Driver portal | `Api\Portal` | `portal` | portal (1, driver only) |

---

## 4. SaaS Model

### 4.1 Tenancy
- One database, row-level tenancy by `company_id`.
- `users.company_id` is `NULL` for Super Admin / platform staff; such users only access `/platform/*`. They can **"Login as Owner"** (impersonation) — every impersonation is written to `audit_logs`.

### 4.2 Public signup & onboarding
1. **Landing / pricing page** shows standard plans (monthly/yearly toggle) and **Start Free Trial**.
2. **Signup form:** company name, owner full name, email, phone, password, USDOT No (optional), accept terms.
3. Email verification.
4. System **provisions the company**: `companies` row, trial `company_subscriptions` row, owner user (`is_owner = 1`), default roles & permissions, menus (from `menus.json`), the 11 expense categories, default settings, jurisdiction preferences.
5. Owner lands on the **Setup Wizard / checklist** (§13.3).
- The Super Admin can also create a company manually (same provisioning) from Platform → Companies.

### 4.3 Trial rules
| Rule | Value (platform settings) |
|---|---|
| Trial length | **14 days** (`platform.trial_days`) |
| Features during trial | Those of the plan set as `platform.trial_plan_id` (default **Professional**) |
| Reminders | In-app + email + push on **day 7, 3, 1 and 0** before expiry; trial banner always visible ("⏳ N days left · Choose a plan") |
| After expiry | Company becomes **read-only**; every login lands on **Choose Plan**; data retained **90 days** (`platform.data_retention_days`) |

### 4.4 Plans
**Plan types**
- **Standard** — always visible to **every** company on the Billing page for upgrade, and on the public pricing page.
- **Custom** — visible only to companies the Super Admin explicitly assigns (`plan_company_access`). Shown with a "Special offer for you" ribbon.

**Plan fields**
| Group | Fields |
|---|---|
| Display | name, description, badge (e.g. "Most Popular"), colour, sort order, active |
| Price | monthly price, yearly price (or yearly discount %) |
| **Limits** (NULL = Unlimited) | max **trucks**, max **drivers**, max **users**, max trailers, **storage (MB)**, max trip sheets / month |
| **Modules** (✓/✕, JSON `modules`) | `trip_sheets`, `fleet`, `employees`, `parties`, `driver_access` (driver mobile access), `revenue_profit`, `settlements`, `reports_basic`, `reports_advanced` (incl. state mileage / IFTA data), `export` (Excel/PDF), `custom_roles`, `announcements` (company announcements), `audit_log` |
| Support | `support_level` = standard / priority |
| Trial | `trial_allowed` |

**Example standard plans** (all values editable by Super Admin; prices are placeholders)
| | Starter | Professional ⭐ | Business | Custom / Enterprise |
|---|---|---|---|---|
| Trucks / Drivers / Users | 3 / 5 / 3 | 15 / 25 / 10 | 50 / 80 / 30 | any |
| Storage | 2 GB | 10 GB | 50 GB | any |
| Trip sheets, Fleet, Employees, Parties | ✓ | ✓ | ✓ | ✓ |
| Driver mobile access | ✕ | ✓ | ✓ | ✓ |
| Revenue & profit, Settlements | ✕ | ✓ | ✓ | ✓ |
| Advanced reports / IFTA data | ✕ | ✕ | ✓ | ✓ |
| Custom roles, Audit log | ✕ | ✓ | ✓ | ✓ |
| Company announcements | ✕ | ✓ | ✓ | ✓ |
| Support | Standard | Standard | Priority | Priority |

### 4.5 Enforcement
- **Limits:** checked in `beforeSave` of the relevant create (truck, driver, user, trailer, trip, upload). Over limit → `422 "You've reached 10/10 trucks. Upgrade your plan to add more."`; the UI shows an **Upgrade** button. At **90 %** usage the owner gets a notification.
- **Modules:** route middleware `plan.feature:<key>`; menu items with a `feature` that the plan lacks show a 🔒 badge and open an **"Unlock with <Plan>"** upsell page (not hidden). Dashboard widgets return `null`.
- **Downgrade** blocked when current usage exceeds the target plan's limits ("Remove 4 trucks first").
- **Custom limits:** Super Admin may override limits for one company (`company_subscriptions.custom_limits` JSON); effective limit = override ?? plan limit.

### 4.6 Invoices & payment (Cash / Bank Transfer)
```
Company:  Billing → choose plan + cycle (monthly/yearly) → invoice INV-YYYY-NNNN (status: pending)
          → Pay screen:  Bank Transfer (platform bank accounts, copy buttons, reference = invoice no.)
                         Cash (platform cash instructions)
          → "I have paid": amount, paid date, method, bank account used, transaction ref, proof upload
          → invoice status: under_review   (banner "We'll verify within 24 hours")
Super Admin: Payments → Verify queue → view proof → Approve | Reject(reason)
          → Approve: payment approved, invoice paid, subscription activated/extended, receipt PDF,
                     notification to owner
          → Reject:  owner notified with reason, can resubmit
```
- Super Admin can **record a cash payment directly** (in-person payment) — creates an approved payment.
- Multiple **platform bank accounts** and editable cash instructions (platform settings).
- **Renewal:** invoice auto-generated **7 days** before `ends_at`; reminders on day 7/3/1/0.
- **Upgrade mid-cycle:** new subscription starts when the payment is approved (no proration in Phase 1; Super Admin may apply a manual discount on the invoice).

### 4.7 Subscription states & read-only mode
| Status | Meaning | Access |
|---|---|---|
| `trial` | Within trial | Full (trial plan features) |
| `active` | Paid, within period | Full (plan features) |
| `past_due` | Period ended, within **grace (5 days, `platform.grace_days`)** | Full + red banner |
| `expired` | Trial or grace ended | **Read-only** (GET only; writes return 402/423 with "Choose a plan") |
| `suspended` | Suspended by Super Admin | Login blocked with message + support link |

### 4.8 Company account management (Super Admin)
Company detail page tabs: **Overview** (plan, usage meters, trial/expiry, last login, counts) · **Profile** (edit all company fields) · **Subscription** (change plan, extend trial, set custom limits, **assign custom plans visible to this company**) · **Invoices & Payments** · **Users** · **Tickets** · **Activity Log** · actions **Suspend / Activate / Login as Owner / Record cash payment**.

---

## 5. Users, Employees, Roles & Permissions

### 5.1 Model
- **User** = login account (`user_type`: `super_admin | staff | driver`; `is_owner`).
- **Employee** = company person record (staff or driver). `employees.is_driver = 1` + `driver_details` (CDL, pay) makes them a driver. An employee may or may not have a user login.
- Roles via Spatie (team = `company_id`). Plus **direct per-user permissions** for exceptions.

### 5.2 How the owner grants rights
1. **Employees → Add Employee** → profile → toggle **Is Driver** (shows CDL & pay fields) → toggle **Create login** → choose **Role** → optionally **Extra permissions**.
2. **Settings → Roles** → create custom roles (plan feature `custom_roles`) and toggle permissions in a grid (View / Create / Edit / Delete / Approve / special).
3. **Per-user extra permissions** — grant one person something extra without changing their role.

### 5.3 Permission catalogue
| Group | Permissions |
|---|---|
| Dashboard | `dashboard.view`, `dashboard.finance` |
| Trips | `trips.view` (own), `trips.view_all`, `trips.create` (for self), `trips.create_any` (for any driver), `trips.update` (own), `trips.update_any`, `trips.submit`, `trips.approve`, `trips.reopen`, `trips.delete`, `trips.view_revenue`, `trips.export` |
| Settlements | `settlements.view` (own), `settlements.view_all`, `settlements.create`, `settlements.finalize`, `settlements.pay`, `settlements.delete` |
| Fleet | `trucks.view/create/update/delete`, `trailers.view/create/update/delete` |
| Employees | `employees.view/create/update/delete`, `employees.manage_login`, `drivers.view_pay` |
| Parties | `parties.view/create/update/delete` |
| Reports | `reports.view`, `reports.finance`, `reports.ifta`, `reports.export` |
| Communication | `announcements.view`, `announcements.manage` |
| Support | `tickets.view`, `tickets.create` |
| Billing | `billing.view`, `billing.manage` |
| Settings | `settings.manage`, `company.profile`, `roles.manage`, `users.manage`, `categories.manage`, `jurisdictions.manage`, `menus.manage`, `audit.view` |
| Platform (Super Admin) | `platform.*` — companies, plans, subscriptions, payments, bank_accounts, tickets, help, announcements, jurisdictions, users, settings, audit |

### 5.4 Default roles (editable by the owner)
| Capability | Owner | Manager | Dispatcher | Accountant | Driver |
|---|:-:|:-:|:-:|:-:|:-:|
| Enter trip sheet for any driver (`create_any`) | ✓ | ✓ | ✓ | – | – |
| Enter own trip sheet (`create`) | ✓ | ✓ | ✓ | – | **only if granted** |
| View all trips | ✓ | ✓ | ✓ | ✓ | own only |
| Approve / reject sheets | ✓ | ✓ | – | ✓ | – |
| Reopen approved sheet | ✓ | – | – | – | – |
| Revenue / pay / profit | ✓ | ✓ | – | ✓ | own pay only |
| Settlements (create/pay) | ✓ | ✓ | – | ✓ | view own |
| Fleet & employees | ✓ | ✓ | view | view | – |
| Reports | ✓ | ✓ | trips | all | own |
| Announcements (company) | ✓ | ✓ | – | – | view |
| Billing | ✓ | – | – | view | – |
| Settings / roles / users | ✓ | ✓ (no roles) | – | – | – |

Drivers always use `Access::scopeTrips()` → only their own trips unless `trips.view_all`.

---

## 6. Modules

| # | Module | Purpose | Screens | Key rules |
|---|---|---|---|---|
| 1 | **Company & Settings** | Company profile, users, roles, categories, jurisdictions, menus, appearance | Company Profile (tabs), Users, Roles grid, Expense Categories, Jurisdictions, Menu Manager, Appearance, My Profile | Profile feeds the printed trip sheet header |
| 2 | **Employees & Drivers** | Staff and driver records, logins, roles | List (cards on mobile), Add/Edit (Is Driver, Create login, Role, Extra permissions), Driver detail (trips, pay, documents) | Driver limit per plan; CDL/medical expiry alerts |
| 3 | **Fleet — Trucks** | Truck records | List, form, detail (odometer history, trips, expenses, MPG) | `truck_no` unique per company; truck limit per plan; `current_odometer` updated from approved trips |
| 4 | **Fleet — Trailers** | Trailer records | List, form | `trailer_no` unique per company |
| 5 | **Shippers & Consignees** | Address book (parties) | List, form | Auto-complete in trip sheet; a party can be both shipper and consignee |
| 6 | **Trips (Trip Sheet)** ⭐ | Digital paper trip sheet | List, New/Edit (6-step wizard on mobile, single page on desktop), Detail (tabs), Print/PDF, Pending approval | Full logic in §7 |
| 7 | **State Mileage & Fuel** | Gallons & miles per jurisdiction per trip | Part of trip sheet; State Mileage report | IFTA source data |
| 8 | **Trip Expenses** | 11 paper categories + custom | Part of trip sheet; Expense report | All lines add to TOTAL |
| 9 | **Settlements** | Weekly driver pay statements | List, Generate, Detail, PDF, driver "My Pay" | §8 |
| 10 | **Reports** | Analysis + export | Report pages with filters/group-by | §10 |
| 11 | **Dashboard** | Module widgets | Company, Driver, Super Admin dashboards | §9 |
| 12 | **Billing & Plan** | Trial, plans, invoices, payments | Billing overview, Plans compare, Pay invoice, Invoices | §4 |
| 13 | **Support** | Tickets to platform | My tickets, New ticket, Thread | §12 |
| 14 | **Help Center & Guidance** | Articles, tours, checklist | Help Center, Help panel, Setup checklist | §13 |
| 15 | **Communication** | Announcements & notifications | Bell inbox, Announcements (company), Notification preferences | §14 |
| 16 | **Platform (Super Admin)** | SaaS administration | Dashboard, Companies, Plans, Subscriptions, Invoices, Payments verify, Bank accounts, Tickets, Help articles, Announcements, Jurisdictions, Platform users, Audit, Settings | §4, §9.3 |

---

## 7. Trip Sheet — Full Logic

The digital trip sheet reproduces the paper **Truck Driver Trip Sheet** (screenshot) section by section. One trip sheet = one trip of one truck.

### 7.1 Printed header (from Company Profile)
Logo · company name · address (e.g. *4133 SW LOOP 820 APT 814, FORT WORTH, TX 76123*) · phones (*Tel: 817-988-9128, 817-825-8666*) · truck illustration. Configured in **Company Profile → Trip Sheet Header** with live preview.

### 7.2 Sections & fields
| § | Section (paper) | Field | Type / source | Required |
|---|---|---|---|---|
| 1 | Driver & Truck | **Driver** | employee where `is_driver=1` (driver users: locked to self) | ✓ |
| | | **Date** | date (default today) | ✓ |
| | | **Load No.** | text, unique per company (warning on duplicate) | ✓ |
| | | **Truck No.** | truck (active) | ✓ |
| | | **Trailer No.** | trailer (auto from truck's default trailer) | – |
| | | Trip No. | auto `TRP-YYYY-NNNNN` (prefix setting) | auto |
| 2 | Shipment | **Shipper** (1..n rows) | party (shipper) or free text + **City** (+ state) | ≥1 |
| | | **Consignee** (1..n rows) | party (consignee) or free text + **City** (+ state) | ≥1 |
| 3 | State-wise Fuel & Mileage | per jurisdiction: **Gallons**, **Miles** | decimal(10,3) / decimal(10,1), ≥ 0 | ≥1 state with miles on submit |
| 4 | Truck Expenses | 11 paper lines (+ custom), each: **amount**, payment method, ref, receipt photo, note | decimal(12,2) ≥ 0 | – |
| 4b | Repairs & Breakdown *(optional, 0..n)* | per repair: date, city/state, odometer, downtime hrs, **what went wrong**, **repair shop** (name, phone, address), **mechanic** (name, phone), **parts** (name, part #, replaced / new / repaired / adjusted, qty, unit cost), labor, paid by, invoice #, **work done**, notes | `trip_repairs` + `trip_repair_parts` | – |
| 5 | Totals | **Total Gallons**, **TOTAL** | calculated | auto |
| 6 | Trip & Mileage | **Load From City**, **Destination** | text + state (default: first shipper / last consignee) | ✓ |
| | | **Starting Miles** | integer (auto from truck's last ending miles) | ✓ |
| | | **Ending Miles** | integer | ✓ on submit |
| | | **Total Miles** | calculated | auto |
| 7 | Driver Authorization | **Driver's Signature** | drawn signature (PNG) **or** photo/scan of signed paper sheet | ✓ on submit (setting `trips.require_signature`) |
| + | Revenue & Pay *(only with `trips.view_revenue`; not printed on driver copy)* | Load Rate, Driver Pay (auto, overridable), Net Profit | decimal | – |
| + | Attachments | BOL, POD, receipts, signed sheet, other | files | – |
| + | Notes | free text | | – |

### 7.3 Jurisdictions
Display order on the sheet follows the paper:

| Column | Codes (paper order) |
|---|---|
| **Left (21)** | AZ, AR, CA, CO, CT, DE, FL, GA, IL, IN, IA, KS, KY, LA, ME, MD, AL, MI, MN, MS, MO |
| **Right (21)** | MT, NV, NH, NJ, NM, NY, NC, ND, OH, OK, OR, PA, RI, SC, TN, TX, UT, VT, VA, WA, WV |
| **Extra — US states not on paper (6)** | ID, MA, NE, SD, WI, WY |
| **Extra — Canada** | AB, BC, MB, NB, NL, NS, ON, PE, QC, SK |
| **Admin-added** | Super Admin adds platform-wide jurisdictions; company admins add company-only ones (`company_id` set). Each can be activated/deactivated. |

`jurisdictions.sheet_side` = `left | right | extra`, `sheet_order` keeps the paper order. Mobile UI shows only the states actually driven (added via a state-picker bottom sheet with "Recent" chips); desktop shows the full 3-column grid with a "show used only" toggle.

### 7.4 Expense categories (paper order, seeded per company, `is_system = 1`)
| # | Category | Description | Default settlement effect |
|---|---|---|---|
| 1 | Total Cash Fuel | Cash paid for fuel | reimburse |
| 2 | Com Check | Comcheck payment / fuel or expense advance | **deduct** |
| 3 | Advance | Advance amount received by driver | **deduct** |
| 4 | Toll Fee | Road and highway tolls | reimburse |
| 5 | Scales | Truck weighing / scale fees | reimburse |
| 6 | Tires | Tire purchase or repair | reimburse |
| 7 | Lumper | Loading / unloading service | reimburse |
| 8 | Parts | Truck or trailer parts | reimburse |
| 9 | Lodging | Hotel / accommodation | reimburse |
| 10 | Truck Wash | Truck washing | reimburse |
| 11 | Misc. | Other expenses | reimburse |

System categories can be renamed or hidden but not deleted. Companies may add **custom categories**; they also add into TOTAL. If a line's payment method is `company_card` or `fuel_card`, settlement effect is treated as `none` regardless of the category default.

### 7.5 Calculations
```
Total Miles        = Ending Miles − Starting Miles
Total Gallons      = Σ trip_state_mileages.gallons
State Miles Total  = Σ trip_state_mileages.miles
Mileage Variance   = Total Miles − State Miles Total   (% = |variance| ÷ Total Miles × 100)
Repair total       = Σ (part qty × unit cost) + labor   (per repair; qty defaults to 1)
REPAIRS            = Σ repair totals                    (own line on the sheet, above TOTAL)
TOTAL (expenses)   = Σ ALL trip_expenses.amount + REPAIRS ← includes Com Check & Advance (same as paper)
MPG                = Total Miles ÷ Total Gallons        (blank if gallons = 0)
Cost per Mile      = TOTAL ÷ Total Miles
Driver Pay         = per_mile:   Total Miles × pay_rate
                     percentage: Load Rate × pay_rate %
                     flat:       pay_rate
                     (editable override, flagged `driver_pay_overridden`)
Net Profit         = Load Rate − TOTAL − Driver Pay
```
Repairs paid by the driver (**Cash** / **Com Check**) are added automatically as reimbursements when the settlement is generated; company card, fuel card and "shop bills the office" are not.
Duplicating a trip does not copy its repairs.

Totals are recalculated server-side on every save (`TripCalculator` service) and stored on `trips` for fast reporting; the UI shows them live while typing.

### 7.6 Validations
| Rule | Severity |
|---|---|
| Ending Miles > Starting Miles | error |
| Starting Miles ≥ truck's last approved ending miles | warning (error if setting `trips.strict_odometer`) |
| Mileage variance > `trips.variance_pct` (default 2 %) | warning shown in amber; submit allowed |
| Load No. duplicate in company | warning |
| At least one shipper and one consignee | error on submit |
| At least one jurisdiction with miles > 0 | error on submit |
| Signature present (if `trips.require_signature`) | error on submit |
| Same jurisdiction twice on one trip | error (unique) |
| Driver/truck/trailer belong to company and are active | error |
| Trip date not in future beyond 1 day | error |
| Plan limit `max_trips_month` | error with upgrade prompt |

### 7.7 Workflow
```
DRAFT ──(sign + submit)──► SUBMITTED ──approve──► APPROVED ──(settlement paid)──► SETTLED
  ▲                            │
  └──────── REJECTED ◄─────────┘  (reason required → driver notified → edit → resubmit)
APPROVED ──reopen (trips.reopen)──► DRAFT   (audited)
```
- Edit allowed only in `draft` / `rejected` (own with `trips.update`, any with `trips.update_any`).
- `trips.require_approval = false` → submit auto-approves.
- On **approve**: truck `current_odometer` = ending miles (if greater).
- Every transition writes `trip_status_logs` (from, to, user, note, time) and is audited.
- Notifications: submitted → approvers; approved/rejected → driver (and entered_by if different).
- Office entry from paper: staff with `trips.create_any` creates the sheet for the driver, attaches the photo of the signed paper sheet instead of a drawn signature.

### 7.8 Auto-fill rules
| Field | Auto-fill |
|---|---|
| Driver | Driver user → self (locked) |
| Truck | Driver's `default_truck_id` |
| Trailer | Truck's `default_trailer_id` |
| Starting Miles | Truck's last trip ending miles (`GET /trucks/{id}/last-odometer`) |
| Shipper/Consignee city & state | From selected party |
| Load From City / Destination | First shipper city / last consignee city |
| Driver Pay | From driver's pay type & rate |
| Trip No | Next number for company/year |

### 7.9 Other trip features
Duplicate trip (copies stops/route, not amounts) · Print/PDF (paper replica) · Attachments · Status log tab · Offline draft (phone) with automatic sync.

---

## 8. Driver Weekly Settlements

- **Period:** one week; start day from setting `settlements.week_start` (default Monday).
- **Generate:** choose period + one or many drivers → system collects **approved, not yet settled** trips of those drivers with trip date in period.
- **Settlement effect** per expense category (`none | deduct | reimburse`, see §7.4). Trip **TOTAL** is unchanged (paper rule); the effect only affects pay.

```
Gross Pay        = Σ settlement_trips.driver_pay
+ Reimbursements = Σ trip expenses with effect "reimburse"
− Deductions     = Σ trip expenses with effect "deduct" + manual deductions (ELD fee, insurance, escrow…)
+ Bonuses        = manual
= NET PAY
```
- **Statuses:** `draft` (editable, manual items) → `finalized` (locked, driver can see) → `paid` (method cash/bank/cheque, date, reference).
- On **paid**: all included trips → `settled`.
- Settlement statement **PDF** (company header, trips table, reimbursements, deductions, net pay). Drivers see their own under **My Pay**.
- A trip can belong to only one settlement (unique `trip_id` in `settlement_trips`).

---

## 9. Dashboards

### 9.1 Company dashboard (module widgets)
Filter bar: **date preset**, **truck**, **driver** (prominent when applied, §11).

| Widget (module) | Content | Requires |
|---|---|---|
| Trips | KPIs: Trips, Miles, Gallons, Avg MPG (with trend vs previous period); **status pipeline** Draft → Submitted → Approved → Settled (clickable); trips per day chart; pending approvals list | `dashboard.view` |
| Finance | Revenue, Expenses, Driver Pay, **Net Profit**; revenue vs expenses area chart; profit per truck; **expenses by category** donut; cost-per-mile trend | `dashboard.finance` + feature `revenue_profit` |
| Fleet | Truck status (active / in shop / inactive); miles per truck; MPG ranking | `trucks.view` |
| States | **US state tile map** (shade = miles) + top-10 states bar | `reports.view` |
| Drivers | Top drivers by miles; CDL & medical card expiring | `employees.view` |
| Settlements | Unpaid settlements, amount due this week | `settlements.view_all` + feature `settlements` |
| Billing | Trial/plan days left; usage meters (trucks, drivers, users, storage) | owner / `billing.view` |
| Announcements | Latest pinned announcement | all |
| Onboarding | Setup checklist until complete | owner |
| Needs attention | Pending approvals, expiring documents, pending invoice | per permission |

### 9.2 Driver dashboard
Big **＋ New Trip Sheet** (if permitted) · my unfinished drafts · this week's trips & miles · **this week's pay** (estimated) · last settlement · rejected sheets to fix · announcements.

### 9.3 Super Admin dashboard (Royal theme)
KPIs: Companies, Active, Trial (ending soon), Suspended, **MRR**, Trucks on platform, Trips this month · Charts: new companies / month, revenue / month · Tables: subscriptions expiring in 14 days (Renew), **payments awaiting verification**, recent signups, top companies by trips, open tickets / SLA breaches · System health: failed jobs, storage used, last backup.

---

## 10. Reports
All reports: full filters (§11), group-by, phone card view, Excel/PDF export (feature `export`), sortable columns.

| Report | Content | Feature / permission |
|---|---|---|
| Trip Summary | Per trip: miles, gallons, MPG, expenses, CPM, revenue, pay, profit | `reports_basic` |
| State Mileage (IFTA data) | Miles & gallons per jurisdiction per truck / fleet, by date range or quarter | `reports_advanced`, `reports.ifta` |
| Expenses | By category / truck / driver / month | `reports_basic` |
| Profit | Per trip / truck / driver / month | `revenue_profit`, `reports.finance` |
| Driver Pay | Pay, deductions, reimbursements, net per driver / period | `settlements` |
| Driver Performance | Trips, miles, MPG, expenses, rejected sheets | `reports_basic` |
| Truck Performance | Miles, MPG, CPM, odometer history | `reports_basic` |

> The State Mileage report provides base data only. Quarterly IFTA tax calculation is Phase 2; carriers must confirm official IFTA filing rules.

---

## 11. Filters & Sorting Standard

### 11.1 Behaviour (every list and report)
- **Desktop:** filter bar = search box + 3–4 quick filters + **More Filters** drawer (right side).
- **Date presets:** Today, Yesterday, This Week, Last Week, This Month, Last Month, This Quarter, This Year, Custom.
- **Prominent when applied:**
  - Filter button turns **solid primary with a count badge** — `Filters (3)`.
  - A **chip row** (tinted, dashed border) lists each active filter — `Driver: J. Smith ✕` — plus **Clear all**.
  - **Result count** highlighted — "Showing **12** of 340 trips".
  - Quick-filter dropdowns that are set get a tinted "is-set" style; headers of filtered columns show an amber dot.
- Filters live **in the URL query string** (survive refresh, shareable). **Save view** stores named presets per user (`saved_filters`), one may be default.
- **Sorting:** every column sortable — click cycles **▲ asc → ▼ desc → off**; sorted header highlighted; **Shift-click** = multi-sort. Server-side (`?sort=-trip_date,driver_name`) incl. related-name columns (driver, truck, shipper) via joins in `$sortable`.
- **Table tools:** column chooser, density toggle, export of exactly the filtered set, pagination with per-page.
- **Mobile:** filter icon with count badge → full-height bottom sheet with chips; sticky **Apply (N results)** showing the live count; **Sort** bottom sheet; active filter chips scroll horizontally under the search bar.

### 11.2 Filter matrix
| List | Filters |
|---|---|
| Trips | search (trip no, load no, shipper, consignee, city) · date · status (multi) · driver · truck · trailer · shipper · consignee · from state/city · destination state · **jurisdiction driven** · miles range · gallons range · expense range · profit range* · has receipts · mileage variance ⚠ · settled yes/no · entered by |
| Trucks | search · status · ownership · make · year range · insurance expiring/expired · registration expiring · default driver |
| Trailers | search · type · status · registration expiring |
| Employees / Drivers | search · driver/staff · department · designation · role · status · has login · CDL expiring · medical expiring · pay type |
| Shippers / Consignees | search · type · city · state |
| Settlements | period · driver · status · net pay range · payment method |
| Reports | same as source list + group-by (truck, driver, jurisdiction, category, month) |
| Tickets | search · status · priority · category · date · (SA: company, assigned to, SLA breached) |
| Announcements | type · status (scheduled/live/expired) · audience |
| Companies (SA) | search · status · plan · plan type · trial ending in N days · signup date · payment status · state |
| Invoices / Payments | status · method · company (SA) · date · amount range |
| Audit log | user · module · action · date |
| Users | search · role · user type · active · last login |

\* only with `trips.view_revenue`.

---

## 12. Support Tickets
| Item | Detail |
|---|---|
| Who | Any company user with `tickets.create` → Super Admin / platform staff |
| New ticket | category (Billing, Technical, Account, Feature Request, Other), priority (Low, Normal, High, Urgent), subject, description, attachments (screenshots); current page URL + app version captured automatically |
| Thread | Chat-style bubbles (company right, support left), attachments, status badge; **⭐ satisfaction rating** (1–5 + comment) on resolve |
| Statuses | `open` → `in_progress` → `waiting_customer` → `resolved` → `closed` (auto-close 7 days after resolved) |
| Super Admin inbox | Filters, **assign to** staff, **internal notes** (hidden from company), **canned replies**, SLA badges (first-response due / overdue), priority-support plans sorted first |
| SLA (setting) | first response: standard 24 h, priority 4 h |
| Notifications | New ticket → platform staff; every reply → other side (in-app, email, push) |

---

## 13. Help Center & User Guidance

### 13.1 Help Center
Categories (Getting Started, Trip Sheets, Fleet, Drivers, Settlements, Billing, Reports) · search · articles with rich text + video link · audience (all / owner / driver) · linked module key (for contextual help) · "Was this helpful? 👍 👎" · view counts. Authored by Super Admin.

### 13.2 Floating Help (?)
Desktop: floating button bottom-right; mobile: in **More**. Opens a panel with: tips for the current page (articles where `module_key` matches), search, **Start page tour**, **Open a ticket**, phone / WhatsApp contact.

### 13.3 Setup checklist (new company)
① Complete company profile ② Add a truck ③ Add a trailer ④ Add a driver ⑤ Invite a staff member ⑥ Create the first trip sheet ⑦ Choose a plan — progress ring on dashboard, confetti at 100 %. Stored in company settings (`onboarding.*`), each item auto-ticks when the data exists.

### 13.4 Tours, hints, empty states
- **Page tours** (`driver.js`) on first visit to Trips, Trip Sheet, Settlements, Billing; separate **driver tour** for the mobile app; completion stored in `user_tours`; replay from Help panel.
- **Inline hints** — ⓘ tooltip on non-obvious fields (e.g. Com Check: "Comcheck payment or advance given to driver").
- **Empty states** — illustration + one sentence + primary action ("No trucks yet — add your first truck to start creating trip sheets. [+ Add Truck]").
- **What's New** — changelog popup after releases.

---

## 14. Notifications & Announcements

### 14.1 Announcements
| | Platform (Super Admin) | Company (Owner / `announcements.manage`) |
|---|---|---|
| Audience | all companies · selected plans · selected companies · roles (owners only / all users / drivers) | all staff · selected roles · selected employees · drivers |
| Type | Info · New Feature · Maintenance · Billing · **Urgent** | Info · Policy · Urgent |
| Channels | in-app inbox · **top banner** · **popup** (urgent / first view) · email · push | in-app · popup · push |
| Options | schedule (`publish_at`), `expires_at`, pin, require acknowledgement ("I've read") | same |
| Tracking | read count + who read / acknowledged | same |

Company announcements require plan feature `announcements`.

### 14.2 System notifications (automatic)
| Event | Recipients |
|---|---|
| Trip submitted | users with `trips.approve` |
| Trip approved / rejected | driver (+ entered_by) |
| Settlement finalized / paid | driver |
| CDL / medical card / insurance / registration expiring (30, 7, 0 days) | owner + `employees.view` / `trucks.view` |
| Trial ending (7, 3, 1, 0 days) / subscription renewal / past due | owner |
| Invoice created; payment approved / rejected | owner |
| New payment to verify; new ticket | platform staff |
| Ticket reply | other side |
| Plan usage ≥ 90 % | owner |

### 14.3 Delivery
- **Bell** with unread badge; tabs **All · Announcements · Alerts**; clickable items (`link`); "Mark all read".
- **Web Push** to installed PWA (VAPID) + email; in-app polling every 60 s (Reverb real-time in Phase 2).
- **Preferences** per user: event × channel grid (in-app always on; email/push toggles), stored in `users.preferences`.

---

## 15. Company Profile & Settings

### 15.1 Company Profile (Settings → Company Profile, `company.profile`)
| Tab | Fields |
|---|---|
| General | logo, company name, USDOT No, MC No, EIN (optional) |
| Contact & Address | address, city, state, zip, phone 1, phone 2, email |
| Trip Sheet Header | live preview of printed header (logo, name, address, phones, truck image toggle) |
| Regional | timezone, date format, currency, week start day |
| Appearance | theme (8), sidebar style (dark / light / brand), default dark mode |
| Account (owner) | owner email & password, **transfer ownership**, export all data (Excel zip), request account closure |

**My Profile** (every user): photo, name, phone, password, notification preferences, personal theme / dark mode.

### 15.2 Company setting keys (`Settings::DEFAULTS`)
| Key | Default | Meaning |
|---|---|---|
| `company.timezone` | `America/Chicago` | |
| `company.date_format` | `m/d/Y` | |
| `company.currency` | `USD` | |
| `trips.number_prefix` | `TRP` | Trip number `TRP-YYYY-NNNNN` |
| `trips.require_approval` | `true` | false → submit auto-approves |
| `trips.require_signature` | `true` | |
| `trips.variance_pct` | `2` | mileage variance warning threshold |
| `trips.strict_odometer` | `false` | starting miles must ≥ last ending miles |
| `trips.allow_future_days` | `1` | |
| `trips.receipt_required_over` | `null` | require receipt above amount |
| `settlements.week_start` | `monday` | |
| `settlements.number_prefix` | `STL` | |
| `notifications.channels` | `["in_app","email","push"]` | company-wide enabled channels |
| `notifications.expiry_days` | `[30,7,0]` | document expiry alert days |
| `appearance.theme` | `ocean` | |
| `appearance.sidebar` | `dark` | |
| `appearance.mode` | `light` | |
| `onboarding.*` | — | checklist state |

### 15.3 Platform setting keys (`platform_settings`)
`platform.trial_days` (14) · `platform.trial_plan_id` · `platform.grace_days` (5) · `platform.data_retention_days` (90) · `platform.renewal_invoice_days` (7) · `platform.cash_instructions` · `platform.support_phone` · `platform.support_whatsapp` · `platform.sla_hours` ({standard:24, priority:4}) · `platform.signup_enabled` (true) · `platform.terms_url` · `platform.invoice_prefix` (`INV`).

---

## 16. Database Schema

Conventions: every table has `id` BIGINT UNSIGNED PK, `created_at`, `updated_at`. **Company tables** have `company_id` BIGINT UNSIGNED FK → `companies.id` ON DELETE CASCADE, indexed. `SD` = soft deletes (`deleted_at`). Money = DECIMAL(12,2). All enums stored as VARCHAR with validation (easier migrations).

### 16.1 Core / platform
**`companies`** (SD)
| Column | Type | Notes |
|---|---|---|
| name | varchar(150) | |
| slug | varchar(160) | unique |
| logo_path | varchar(255) null | |
| address, city | varchar null | |
| state | char(2) null | |
| zip | varchar(10) null | |
| phone_1, phone_2, email | varchar null | |
| usdot_no, mc_no, ein | varchar(30) null | |
| timezone | varchar(50) | |
| status | varchar(20) | trial / active / past_due / expired / suspended (mirror of subscription) — index |
| suspended_reason | varchar(255) null | |
| owner_user_id | bigint null | index |
| signup_source | varchar(20) | public / admin |

**`subscription_plans`**
| Column | Type | Notes |
|---|---|---|
| name | varchar(80) | |
| type | varchar(10) | standard / custom — index |
| description | text null | |
| badge, color | varchar null | |
| price_monthly, price_yearly | decimal(10,2) | |
| yearly_discount_pct | decimal(5,2) null | |
| max_trucks, max_drivers, max_users, max_trailers, max_trips_month | int null | NULL = unlimited |
| storage_mb | int null | |
| modules | json | feature keys → bool |
| support_level | varchar(10) | standard / priority |
| trial_allowed | bool | |
| sort_order | int | |
| is_active | bool | index |

**`plan_company_access`** — `plan_id` FK, `company_id` FK; unique(plan_id, company_id). Visibility of custom plans.

**`company_subscriptions`** — company_id, plan_id FK, cycle (monthly/yearly/trial), status (trial/active/past_due/expired/suspended), is_trial bool, starts_at, ends_at, trial_ends_at null, grace_ends_at null, amount decimal, custom_limits json null, cancelled_at null. Index (company_id, status), (ends_at).

**`subscription_invoices`** — company_id, plan_id, subscription_id null, invoice_no (unique), cycle, period_start, period_end, amount, discount, total, due_date, status (pending/under_review/paid/cancelled), paid_at null, notes. Index (company_id, status), (status, due_date).

**`subscription_payments`** — invoice_id FK, company_id, method (cash/bank_transfer), amount, paid_on date, platform_bank_account_id null, transaction_ref, proof_path null, status (pending/approved/rejected), submitted_by, reviewed_by null, reviewed_at null, rejection_reason null, recorded_by_admin bool. Index (status), (company_id).

**`platform_bank_accounts`** — bank_name, account_title, account_no, iban null, routing_swift null, branch null, instructions text null, is_active, sort_order.

**`platform_settings`** — key (unique), value json.

**`users`** (SD)
| Column | Type | Notes |
|---|---|---|
| company_id | bigint null | NULL = platform user |
| employee_id | bigint null | FK employees, unique |
| name, email | varchar | unique(email) |
| phone | varchar null | |
| password | varchar | |
| user_type | varchar(15) | super_admin / platform_staff / staff / driver |
| is_owner | bool | |
| is_active | bool | |
| avatar_path | varchar null | |
| preferences | json null | theme, mode, notification prefs |
| email_verified_at, last_login_at | timestamp null | |

**`company_settings`** — company_id, key, value json; unique(company_id, key).
**`audit_logs`** — company_id null, user_id null, impersonator_id null, model_type, model_id, action (created/updated/deleted/status/login_as…), old json, new json, ip, user_agent. Index (company_id, created_at), (model_type, model_id).
**`login_histories`** — user_id, company_id null, ip, user_agent, logged_in_at, success bool.
**`menus`** — company_id null, parent_id null, key, label, icon, path / url, permission, feature null, user_types json null, order, is_hidden, is_custom.
**Spatie tables** — `roles` (team_id = company_id), `permissions`, `model_has_roles`, `model_has_permissions`, `role_has_permissions`.

### 16.2 Employees & drivers
**`departments`**, **`designations`** — company_id, name; unique(company_id, name).

**`employees`** (SD)
| Column | Type | Notes |
|---|---|---|
| company_id | FK | |
| department_id, designation_id | bigint null | FK |
| employee_code | varchar(30) | unique(company_id, employee_code) |
| first_name, last_name | varchar(80) | |
| phone, email | varchar null | |
| address, city, state, zip | varchar null | |
| photo_path | varchar null | |
| hire_date | date null | |
| is_driver | bool | index (company_id, is_driver) |
| status | varchar(10) | active / inactive |
| notes | text null | |

**`driver_details`** — employee_id FK unique, cdl_number, cdl_state char(2), cdl_expiry date null, medical_card_expiry date null, pay_type (per_mile/percentage/flat), pay_rate decimal(10,4), default_truck_id null. Index (cdl_expiry), (medical_card_expiry).

### 16.3 Fleet, parties, lookups
**`trucks`** (SD) — company_id, truck_no (unique per company), vin, make, model, year smallint, plate_no, plate_state char(2), ownership (company/owner_operator/leased), current_odometer int, default_trailer_id null, registration_expiry date null, insurance_expiry date null, status (active/in_shop/inactive), photo_path, notes. Index (company_id, status).

**`trailers`** (SD) — company_id, trailer_no (unique per company), type (dry_van/reefer/flatbed/tanker/other), vin, plate_no, plate_state, year, registration_expiry, status, notes.

**`parties`** (SD) — company_id, name, is_shipper bool, is_consignee bool, contact_person, phone, email, address, city, state, zip. Index (company_id, name).

**`jurisdictions`** — company_id null (NULL = platform), code varchar(3), name, country (US/CA/MX), sheet_side (left/right/extra), sheet_order int, is_active. Unique(company_id, code).

**`expense_categories`** — company_id, name, code, description, settlement_effect (none/deduct/reimburse), sort_order, is_system, is_active. Unique(company_id, code).

### 16.4 Trips
**`trips`** (SD)
| Column | Type | Notes |
|---|---|---|
| company_id | FK | |
| trip_no | varchar(20) | unique(company_id, trip_no) |
| load_no | varchar(50) | index (company_id, load_no) |
| trip_date | date | index (company_id, trip_date) |
| driver_id | bigint | FK employees, index |
| truck_id | bigint | FK trucks, index |
| trailer_id | bigint null | FK trailers |
| load_from_city, destination_city | varchar(100) | |
| load_from_state, destination_state | varchar(3) | |
| starting_miles, ending_miles | int unsigned null | |
| total_miles | int null | stored calc |
| total_gallons | decimal(10,3) | stored calc |
| state_miles_total | decimal(10,1) | stored calc |
| mileage_variance_pct | decimal(6,2) null | stored calc |
| expenses_total | decimal(12,2) | stored calc |
| load_rate | decimal(12,2) null | |
| driver_pay | decimal(12,2) null | |
| driver_pay_overridden | bool | |
| net_profit | decimal(12,2) null | stored calc |
| status | varchar(12) | draft/submitted/approved/rejected/settled — index (company_id, status) |
| signature_path | varchar null | |
| signed_at, submitted_at, approved_at | timestamp null | |
| approved_by | bigint null | users |
| rejection_note | text null | |
| entered_by | bigint | users |
| client_uuid | char(36) null | offline-sync idempotency, unique |
| notes | text null | |

**`trip_stops`** — trip_id FK cascade, type (shipper/consignee), sequence tinyint, party_id null, name, city, state. Index (trip_id, type).
**`trip_state_mileages`** — trip_id FK cascade, jurisdiction_id FK, gallons decimal(10,3), miles decimal(10,1). Unique(trip_id, jurisdiction_id). Index (jurisdiction_id).
**`trip_expenses`** — trip_id FK cascade, expense_category_id FK, amount decimal(12,2), payment_method (cash/comcheck/fuel_card/company_card/other), reference_no null, receipt_path null, expense_date null, notes null. Index (trip_id), (expense_category_id).
**`trip_attachments`** — trip_id FK cascade, type (bol/pod/receipt/signed_sheet/other), file_path, original_name, size_kb, uploaded_by.
**`trip_status_logs`** — trip_id FK cascade, from_status null, to_status, user_id, note null, created_at.

### 16.5 Settlements
**`driver_settlements`** (SD) — company_id, settlement_no (unique per company), driver_id, period_start, period_end, gross_pay, reimbursements, deductions, bonuses, net_pay, status (draft/finalized/paid), finalized_at, paid_on null, payment_method null, payment_ref null, notes, created_by. Index (company_id, driver_id, period_start).
**`settlement_trips`** — settlement_id FK cascade, trip_id (unique), driver_pay.
**`settlement_items`** — settlement_id FK cascade, type (deduction/bonus/reimbursement), description, amount, trip_expense_id null.

### 16.6 Support, help, communication
**`support_tickets`** — ticket_no (unique), company_id, user_id, category, priority, subject, description, status, assigned_to null, page_url null, app_version null, first_response_at, last_reply_at, resolved_at, closed_at, rating tinyint null, rating_comment null. Index (status, priority), (company_id).
**`ticket_replies`** — ticket_id FK cascade, user_id, body, is_internal bool, attachments json null.
**`canned_replies`** — title, body.
**`help_categories`** — name, icon, sort_order.
**`help_articles`** — category_id FK, title, slug (unique), body longtext, video_url null, audience (all/owner/driver), module_key null, is_published, views, helpful_yes, helpful_no.
**`announcements`** — company_id null (NULL = platform), title, body, type, audience json, channels json, is_pinned, require_ack, publish_at, expires_at null, created_by. Index (company_id, publish_at).
**`announcement_reads`** — announcement_id, user_id, read_at, acknowledged_at null; unique(announcement_id, user_id).
**`user_notifications`** — user_id, company_id null, type, category (alert/announcement/system), title, body, link null, data json null, read_at null. Index (user_id, read_at).
**`push_subscriptions`** — per webpush package.
**`user_tours`** — user_id, tour_key, completed_at; unique(user_id, tour_key).
**`saved_filters`** — user_id, page_key, name, filters json, is_default.

### 16.7 Phase 2 tables (reserved)
`fuel_tax_rates` (jurisdiction_id, year, quarter, rate_per_gallon, surcharge) · `maintenance_records` · `document_reminders` · `fuel_card_imports`.

### 16.8 Key relationships
```
Company 1─* Users, Employees, Trucks, Trailers, Parties, Trips, Settlements, Tickets, Invoices
Company 1─* CompanySubscriptions *─1 SubscriptionPlan;  Plan *─* Company (plan_company_access)
Employee 1─1 DriverDetails;  Employee 1─0..1 User
Trip *─1 Driver(Employee), Truck, Trailer;  Trip 1─* Stops, StateMileages, Expenses, Attachments, StatusLogs
StateMileage *─1 Jurisdiction;  Expense *─1 ExpenseCategory
DriverSettlement 1─* SettlementTrips (─1 Trip), SettlementItems
Invoice 1─* SubscriptionPayments
```

---

## 17. API Endpoint Catalogue
> Summary only — the complete API design (auth per client, response/error formats, filter grammar, offline sync, rate limits, permissions per endpoint, examples) is in **[API_SPEC.md](API_SPEC.md)**.

Base `/api/v1`, JSON, Sanctum bearer token. CRUD = `GET index`, `POST store`, `GET {id}`, `PUT {id}`, `DELETE {id}` via `Route::crud`.

### 17.1 Public & auth
```
GET  /public/plans                       standard plans for pricing page
POST /public/signup                      create company + owner (trial)
POST /auth/login · /auth/logout · GET /auth/me · PUT /auth/preferences
POST /auth/forgot-password · /auth/reset-password · /auth/verify-email
```

### 17.2 Company core
```
GET  /dashboard                          ?date_from&date_to&truck_id&driver_id
GET|PUT /company/profile · POST /company/logo · POST /company/transfer-ownership · POST /company/export
GET|PUT /settings · GET /menus · POST /menus/sync · CRUD /menus
CRUD /users · CRUD /roles · GET /permissions
CRUD /employees (?is_driver=1) · CRUD /departments · CRUD /designations
CRUD /trucks · GET /trucks/{id}/last-odometer · CRUD /trailers · CRUD /parties
CRUD /expense-categories · CRUD /jurisdictions · GET /lookups/jurisdictions
GET  /audit-logs
CRUD /saved-filters · POST /tours/{key}/complete
```

### 17.3 Trips
```
GET    /trips      ?q&date_from&date_to&status[]&driver_id[]&truck_id[]&trailer_id&shipper&consignee
                   &from_state&to_state&jurisdiction_id&miles_min&miles_max&expense_min&expense_max
                   &profit_min&profit_max&has_receipts&variance_warning&settled&entered_by&sort&per_page
POST   /trips      header + stops[] + state_mileages[] + expenses[] (one payload; client_uuid for offline)
GET    /trips/{id} · PUT /trips/{id} · DELETE /trips/{id}
POST   /trips/{id}/submit (signature) · approve · reject {note} · reopen · duplicate
GET    /trips/{id}/pdf
POST   /trips/{id}/attachments · DELETE /trips/{id}/attachments/{aid}
GET    /portal/trips · POST /portal/trips · PUT /portal/trips/{id}     (driver self-service)
```

### 17.4 Settlements
```
GET  /settlements · POST /settlements/generate {period_start, period_end, driver_ids[]}
GET|PUT|DELETE /settlements/{id} · POST /settlements/{id}/items · DELETE /settlements/{id}/items/{iid}
POST /settlements/{id}/finalize · /settlements/{id}/pay · GET /settlements/{id}/pdf
GET  /portal/settlements (driver own)
```

### 17.5 Reports
```
GET /reports/trip-summary · state-mileage · expenses · profit · driver-pay · driver-performance · truck-performance
    (all accept list filters + group_by + export=xlsx|pdf)
```

### 17.6 Billing (company)
```
GET  /billing/overview                   plan, status, trial days left, usage vs limits
GET  /billing/plans                      standard + custom plans visible to this company
POST /billing/subscribe {plan_id, cycle} → invoice
GET  /billing/invoices · GET /billing/invoices/{id} · GET /billing/invoices/{id}/pdf
POST /billing/invoices/{id}/payments     multipart: amount, paid_on, method, bank_account_id, ref, proof
GET  /billing/bank-accounts
```

### 17.7 Support, help, communication
```
CRUD /tickets (own company) · POST /tickets/{id}/replies · POST /tickets/{id}/rate · POST /tickets/{id}/close
GET  /help/categories · GET /help/articles?q&module_key · GET /help/articles/{slug}
POST /help/articles/{id}/feedback
CRUD /announcements (company) · POST /announcements/{id}/ack · GET /announcements/{id}/reads
GET  /notifications?category · POST /notifications/{id}/read · POST /notifications/read-all
GET|PUT /notification-preferences · POST /push/subscribe · DELETE /push/subscribe
```

### 17.8 Platform (Super Admin)
```
GET  /platform/dashboard
CRUD /platform/companies + POST {id}/suspend · {id}/activate · {id}/impersonate · {id}/cash-payment
PUT  /platform/companies/{id}/subscription  (change plan, extend trial, custom_limits)
CRUD /platform/plans · PUT /platform/plans/{id}/companies   (custom plan visibility)
GET  /platform/subscriptions · GET /platform/invoices
GET  /platform/payments?status=pending · POST /platform/payments/{id}/approve · /reject
CRUD /platform/bank-accounts · /platform/announcements · /platform/help-categories · /platform/help-articles
CRUD /platform/canned-replies · /platform/jurisdictions · /platform/users
GET  /platform/tickets · POST /platform/tickets/{id}/assign · /replies · /status
GET|PUT /platform/settings · GET /platform/audit-logs
```

---

## 18. Frontend Structure

### 18.1 Modules
`src/modules/`: `dashboard`, `trips`, `settlements`, `fleet`, `employees`, `parties`, `reports`, `billing`, `support`, `communication`, `settings`, `account`, `portal` (driver), `platform` (super admin), `public` (landing, signup, login — outside the app shell).

### 18.2 Menus
| Super Admin (Royal theme) | Company (Fleet Blue) | Driver (mobile) |
|---|---|---|
| Dashboard | Dashboard | Home |
| Companies | Trips (All · New · Pending Approval) | My Trips |
| Plans (Standard · Custom) | Settlements | ＋ New Trip Sheet |
| Invoices · **Payments to Verify** (badge) | Fleet (Trucks · Trailers) | My Pay |
| Bank Accounts | Employees & Drivers | Notifications |
| **Support Tickets** (badge) | Shippers & Consignees | Help & Support |
| Help Center (articles) | Reports | My Profile |
| Announcements | Announcements | |
| Jurisdictions | Support · Help Center | |
| Platform Users · Audit · Settings | Billing & Plan | |
| | Settings (Company Profile, Users, Roles, Categories, Jurisdictions, Menus, Appearance) | |

**Mobile bottom tab bar:** company = Home · Trips · (＋ New) · Fleet · More; driver = Home · My Trips · (＋) · My Pay · More.

### 18.3 Key routes
```
/login  /signup  /forgot-password  /pricing
/dashboard
/trips  /trips/new  /trips/:id  /trips/:id/edit  /trips/:id/print  /trips/pending
/settlements  /settlements/generate  /settlements/:id
/fleet/trucks  /fleet/trucks/:id  /fleet/trailers
/employees  /employees/:id  /parties
/reports/:report
/billing  /billing/plans  /billing/invoices/:id/pay
/support  /support/new  /support/:id  /help  /help/:slug
/announcements  /notifications
/settings/company  /settings/users  /settings/roles  /settings/categories  /settings/jurisdictions  /settings/menus  /settings/appearance
/profile
/portal/home  /portal/trips  /portal/pay
/platform/dashboard  /platform/companies  /platform/companies/:id  /platform/plans  /platform/payments
/platform/invoices  /platform/bank-accounts  /platform/tickets  /platform/help  /platform/announcements
/platform/jurisdictions  /platform/users  /platform/settings
```

### 18.4 Shared components
`AppShell` (sidebar + topbar desktop / header + bottom tabs mobile), `ResourcePage`, `DataTable` (sortable, column chooser, density), `FilterBar` + `FilterChips` + `FilterSheet` (mobile) + `useUrlFilters`, `SortSheet`, `StatCard`/`KpiCard`, `StatusBadge`, `Pipeline`, `UsageMeter`, `PlanCard`, `BottomSheet`, `Wizard`, `SignaturePad`, `ReceiptUploader` (compression), `StatePicker`, `ChatThread`, `EmptyState`, `Skeleton`, `TourLauncher`, `HelpPanel`, `NotificationBell`, `AnnouncementBanner`, `UpgradeGate`, `PrintSheet`.

### 18.5 PWA & offline
- Manifest (name, icons, theme colour, `display: standalone`), splash screens, install prompt.
- Service worker caches the app shell + lookup lists (drivers, trucks, trailers, jurisdictions, categories).
- **Trip sheet drafts auto-save locally every few seconds** (IndexedDB); if offline, submission is queued and synced when online (`client_uuid` makes it idempotent). Offline indicator in header.
- Receipt photos compressed on device (~200 KB) before upload.

### 18.6 Performance
Route-level code splitting (lazy modules) · skeleton loaders instead of spinners · cached dropdown options (`useOptions`) · server pagination · debounced search · eager loading + indexes server-side · cached lookup endpoints · gzip/brotli · images lazy-loaded.

---

## 19. UI/UX & Design System

Visual mockups: **`doc/design/index.html`** (overview) · `design-system.html` · `public.html` (landing, pricing, signup, login) · `mobile.html` (phone screens) · `company.html` (company web app) · `super-admin.html` (platform). Detailed component guide: **`doc/DESIGN_GUIDE.md`**. Open via XAMPP: `http://localhost/keep-trucking/doc/design/`.

### 19.1 Principles
1. **Mobile-first, app-like** — installable PWA, bottom tab bar, raised amber ＋ button, swipe-up bottom sheets, glass headers.
2. **Easy to understand** — one task per screen, big labels, plain words; trip sheet = 6-step wizard on phone (Trip info → Shipment → Fuel & Miles → Expenses → Odometer → Review & Sign).
3. **Thumb-friendly** — tap targets ≥ 44–48 px, primary action pinned at bottom, numeric keyboards (`inputmode="decimal"`).
4. **Live feedback** — totals update as you type, amber warnings inline, ✓ per completed step, "Saved ✓" indicator.
5. **Cards on phone, tables on desktop.**
6. **Prominent filters** and sortable columns everywhere (§11).
7. **Attractive** — gradient hero headers, coloured KPI icons, soft shadows, rounded shapes, consistent status colours, light & dark mode.

### 19.2 Tokens (exactly as in `doc/design/assets/tms.css`)
**Default theme `ocean` = "Fleet Blue"**
| Token | Light | Dark |
|---|---|---|
| `--tms-primary` | `#2563EB` (rgb 37,99,235) | same |
| `--tms-primary-dark` | `#1E40AF` | same |
| `--tms-gradient` | `linear-gradient(135deg, #1E3A8A 0%, #2563EB 55%, #06B6D4 100%)` | same |
| `--tms-accent` | `#F59E0B` (rgb 245,158,11) | same |
| `--tms-surface` | `#FFFFFF` | `#111A2E` |
| `--tms-surface-2` (page bg) | `#F4F7FC` | `#0B1220` |
| `--tms-surface-3` | `#EEF2F9` | `#17223A` |
| `--tms-border` | `#E5E9F2` | `#24324D` |
| `--tms-text` | `#0F172A` | `#E2E8F0` |
| `--tms-muted` | `#64748B` | `#94A3B8` |
| `--tms-radius` / `--tms-radius-sm` | 16px / 12px | |

**Themes** (`<html data-theme>`)
| Theme | Primary | Gradient | Accent |
|---|---|---|---|
| ocean (Fleet Blue, default) | `#2563EB` | `#1E3A8A → #2563EB → #06B6D4` | `#F59E0B` |
| indigo | `#4F46E5` | `#312E81 → #4F46E5 → #818CF8` | `#F59E0B` |
| emerald | `#059669` | `#064E3B → #059669 → #34D399` | `#F59E0B` |
| sunset | `#EA580C` | `#7C2D12 → #EA580C → #F59E0B` | `#0EA5E9` |
| royal (**Super Admin**, locked) | `#7C3AED` | `#4F46E5 → #7C3AED → #DB2777` | `#F59E0B` |
| rose | `#E11D48` | `#881337 → #E11D48 → #FB7185` | `#F59E0B` |
| teal | `#0D9488` | `#134E4A → #0D9488 → #22D3EE` | `#F59E0B` |
| slate | `#334155` | `#0F172A → #334155 → #64748B` | `#F59E0B` |

Dark mode: `<html data-bs-theme="dark">`. Sidebar style: `<html data-sidebar="dark|light|brand">` (dark sidebar `#0F172A`).

**Status colours** — Draft `#64748B` · Submitted `#3B82F6` · Approved `#10B981` · Rejected `#EF4444` · Settled `#8B5CF6` · Warning `#F59E0B` · Trial `#06B6D4` (badges use tinted background + dot; cards use a 4 px left colour edge).

**Chart palette** — `#2563EB` (follows theme primary), `#10B981`, `#F59E0B`, `#8B5CF6`, `#EF4444`, `#06B6D4`, `#EC4899`, `#84CC16`.

**KPI icon tints** — blue, green, amber, violet, rose, cyan, pink, slate (`.tint-*`).

### 19.3 Typography & shape
Headings **Plus Jakarta Sans** (700–800); body **Inter** 14 px; tabular numbers for figures. Cards radius 16 px, inputs/buttons 12 px, phone cards 18 px, bottom sheets 26 px top radius; soft layered shadows; frosted-glass top bar and tab bar.

### 19.4 Components (see DESIGN_GUIDE.md)
Buttons (primary, accent, soft, ghost, gradient, success/danger soft) · KPI cards (normal + gradient hero, trend chip, sparkline) · status badges · filter bar, filter chips, count badge, result count · sortable table headers (asc/desc/filtered dot) · usage meters · status pipeline · plan cards (popular, custom ribbon) with limits grid and ✓/✕ feature list · segmented control · chat bubbles (me/them/internal note) · signature pad · state grid & mobile state cards · expense rows with receipt camera · state-picker bottom sheet · wizard stepper · empty states · tour popover · setup checklist with progress ring · banners (trial, warning, info, urgent) · US state tile map · paper-replica print sheet.

### 19.5 Mobile patterns
Gradient hero header with greeting + KPI grid overlapping it · trip cards with route line and status edge · horizontally scrollable chip filters · bottom sheets for filters/sort/pickers with sticky "Apply (N results)" · sticky bottom action bar in forms · segmented tabs on detail pages · pull-to-refresh · bottom tab bar with raised accent FAB.

---

## 20. Non-Functional Requirements

| Area | Requirement |
|---|---|
| Security | Sanctum tokens; bcrypt passwords; rate-limited login (5/min) and signup; email verification; tenant scope on every company query; tenant-safe validation; file uploads validated (type, size ≤ 10 MB, images re-encoded); signed/private URLs for receipts & proofs; CSRF-safe token auth; HTTPS in production; impersonation audited; password reset tokens expire 60 min |
| Authorization | Permission + plan feature on every route and menu; drivers scoped to own data via `Access` |
| Audit | `Auditable` on key models; status logs on trips; login history; payment verification audited |
| Backups | Daily MySQL dump + storage backup (retention 14 days); restore tested |
| Performance targets | API p95 < 300 ms for lists (25 rows); dashboard < 800 ms; first load on 4G < 3 s, repeat load < 1 s (PWA cache); JS bundle per route < 200 KB gz |
| Scalability | Indexes as in §16; heavy reports and PDFs via queue when large |
| Reliability | Offline drafts; idempotent trip creation (`client_uuid`); queued notifications with retries |
| Browser support | Latest Chrome, Edge, Safari (iOS 15+), Firefox, Samsung Internet; Android 9+ PWA install |
| Accessibility | WCAG 2.1 AA colour contrast; keyboard navigation on desktop; labels on all inputs; focus rings; tap targets ≥ 44 px; status not by colour alone (text + dot) |
| Localization | English UI; US formats (miles, gallons, USD, MM/DD/YYYY) configurable via company settings |
| Data retention | Expired companies' data kept 90 days, then purge after notice; owner can export all data anytime |

---

## 21. Delivery Phases

| Phase | Scope |
|---|---|
| **Phase 1 — MVP** | SaaS core (companies, tenancy, auth, roles & permissions, menus, appearance) · **Super Admin** (dashboard, companies, standard & custom plans + visibility, subscriptions, invoices, cash/bank payment verification, bank accounts, jurisdictions, platform users, settings) · public landing/pricing, **signup + 14-day trial**, read-only on expiry · company profile & account · employees & drivers (logins, roles, extra permissions) · trucks, trailers, shippers/consignees · **full Trip Sheet** (wizard + desktop form, stops, state mileage, expenses, receipts, signature, workflow, auto-fills, validations, print/PDF) · **revenue, driver pay, profit** · **weekly settlements** · company / driver / platform dashboards (module widgets) · reports (trip summary, state mileage, expenses, profit, driver pay, performance) + export · filters, sorting, saved views everywhere · **support tickets** · **help center**, setup checklist, page tours, empty states · **announcements & notifications** (in-app, email, push) · PWA with offline drafts |
| **Phase 2** | IFTA quarterly tax calculation (`fuel_tax_rates`), document reminders by SMS, maintenance log, fuel card CSV import, real-time updates (Laravel Reverb) |
| **Phase 3** | Online subscription payments (Stripe), GPS/ELD integration, customer invoicing, native wrapper (Capacitor) if needed |

Suggested Phase 1 build order: core & SaaS → masters (fleet, employees, parties) → trip sheet → settlements → dashboards & reports → billing & platform → support/help/notifications → PWA/offline polish.

---

## 22. Open Items & Assumptions

| # | Item | Assumption used in this spec |
|---|---|---|
| A1 | The .txt "Complete Development Prompt" is a School Management System conventions file | Adopted as architecture/coding conventions with School → Company; school-only modules dropped |
| A2 | Plan prices | Placeholders; Super Admin sets real prices |
| A3 | Currency of SaaS billing | Plan prices in USD; bank accounts/cash instructions configurable by Super Admin |
| A4 | Settlement effect defaults | Advance & Com Check = deduct; other categories = reimburse; company/fuel card lines = none — editable per category |
| A5 | Mid-cycle upgrades | No automatic proration in Phase 1; manual invoice discount |
| A6 | Trip ↔ load relationship | One trip sheet = one load number (as on paper); multiple shippers/consignees supported via stops |
| A7 | Jurisdiction list | Paper's 42 + ID, MA, NE, SD, WI, WY + 10 Canadian provinces; more can be added by Super Admin (platform) or company admin (company-only) |
| A8 | Signature | Drawn signature or photo of signed paper sheet both accepted |
| A9 | Trial plan features | Professional plan features (setting `platform.trial_plan_id`) |
| A10 | IFTA | State mileage report = base data only; tax calculation Phase 2; official IFTA rules to be confirmed by the carrier |
| A11 | Branches / yards | Not in scope (client decision v3) |
