# FleetTruck360: Backend API Specification (API-first)

> Design phase · v1 · 2026-11-14
> Companion to [SOFTWARE_DETAILS.md](SOFTWARE_DETAILS.md) (business rules, DB schema) and [DESIGN_GUIDE.md](DESIGN_GUIDE.md) (UI).
> Audience: backend developers building the API and developers building any client (web, phone, integrations).

---

## Contents
1. [Architecture: separate backend and frontend](#1-architecture-separate-backend-and-frontend)
2. [Clients that use the API](#2-clients-that-use-the-api)
3. [Authentication & sessions](#3-authentication--sessions)
4. [Tenancy, permissions & plan checks](#4-tenancy-permissions--plan-checks)
5. [Request conventions](#5-request-conventions)
6. [Response format](#6-response-format)
7. [Errors](#7-errors)
8. [Lists: pagination, filters, sorting, export](#8-lists-pagination-filters-sorting-export)
9. [Files & uploads](#9-files--uploads)
10. [Phone app support: bootstrap, offline sync, push](#10-phone-app-support-bootstrap-offline-sync-push)
11. [Versioning, rate limits, CORS, security](#11-versioning-rate-limits-cors-security)
12. [API documentation & testing](#12-api-documentation--testing)
13. [Endpoint catalogue](#13-endpoint-catalogue)
14. [Example requests & responses](#14-example-requests--responses)
15. [Webhooks & integration keys (later phases)](#15-webhooks--integration-keys-later-phases)

---

## 1. Architecture: separate backend and frontend

The **backend** and **frontend** are two independent applications. Each has its own folder (or its own git repository), its own dependencies, its own build and its own deployment. They talk **only** through the HTTP JSON API.

```
                 ┌───────────────────────────── clients ─────────────────────────────┐
                 │ Web app (React)   Phone PWA    Super Admin   Native app    Partner  │
                 │ company staff     drivers/     (platform)    (later)       systems  │
                 │                   owners                                 (later)  │
                 └───────┬──────────────┬─────────────┬────────────┬───────────┬──────┘
                         │   HTTPS + JSON · Bearer token · /api/v1                │
                 ┌───────▼────────────────────────────────────────────────────────▼──────┐
                 │                     BACKEND: Laravel 12 API only                        │
                 │  routes/api/*.php → Controllers → Services → Models (BelongsToCompany)  │
                 │  Sanctum · Spatie Permission (team = company) · Queue · Scheduler       │
                 └───────┬───────────────────────┬──────────────────────┬────────────────┘
                         │                       │                      │
                     MySQL 8               File storage           Mail / Web Push
```

| | Backend | Frontend |
|---|---|---|
| Folder | `keep-trucking/backend/` (or repo `fleet-tms-api`) | `keep-trucking/frontend/` (or repo `fleet-tms-web`) |
| Tech | Laravel 12, PHP 8.3, MySQL 8 | React 18 + Vite + Bootstrap 5, PWA |
| Output | JSON API only. No Blade pages; Blade is used only for email and PDF templates | Static files (HTML/JS/CSS) served from any web server or CDN |
| URL (example) | `https://api.fleettruck360.com/api/v1` · local `http://localhost:8000/api/v1` | `https://app.fleettruck360.com` · local `http://localhost:5174` |
| Config | `.env`: DB, mail, storage, `FRONTEND_URLS` (CORS), `SANCTUM_TOKEN_EXPIRY` | `.env`: `VITE_API_URL` |
| Deploy | Independently (Apache/Nginx + PHP-FPM, queue worker, cron) | Independently (any static host) |

**Rules**
- The backend must **never assume which client is calling**. Every business rule lives in the API (permission, plan limit, validation, calculations, workflow). Clients only display the data and collect input.
- **All calculations happen on the server**: Total Miles, Total Gallons, expense TOTAL, MPG, cost per mile, driver pay, profit, settlement totals, plan usage. Clients may show live previews while the user types, but the server's values are always the official ones.
- Any new client (for example a native Android/iOS app) must work **without any backend change**.
- One frontend project contains all three areas (public site, company app, Super Admin) and uses route guards to keep them apart. Because everything goes through the API, the Super Admin panel can be split into its own frontend later without changing the backend.

---

## 2. Clients that use the API

| Client | Users | Token type | Main endpoint groups | `X-Client` header |
|---|---|---|---|---|
| **Web app** (desktop) | Owner, managers, dispatchers, accountants | User token | Company + reports + billing | `web` |
| **Phone app / PWA** | Drivers, owners on the move | User token (per device) | `/app/*` bootstrap, trips, portal, notifications, sync | `pwa` |
| **Super Admin panel** | Platform staff | User token (`super_admin`/`platform_staff`) | `/platform/*` | `web` |
| **Public website** | Visitors | none | `/public/*`, `/auth/*` | `web` |
| **Native app** (Phase 3) | Same as PWA | User token (per device) | Same as PWA | `android` / `ios` |
| **Integrations** (Phase 3) | Partner systems, accounting tools | Company API key | Selected read and write endpoints | `integration` |

All clients use **the same endpoints**. What a caller can do depends on the user's permissions and the company's plan, not on which app is calling.

---

## 3. Authentication & sessions

Every client uses **Laravel Sanctum personal access tokens** (bearer tokens). This works the same way in browsers, PWAs and native apps, with no cookies or CSRF.

### 3.1 Flow
```
POST /api/v1/auth/login          {email, password, device_name, remember?}
  → 200 {data: {token, token_type:"Bearer", expires_at, user, company, plan, permissions, features}}
then on every request:  Authorization: Bearer <token>
POST /api/v1/auth/logout         revoke this device's token
POST /api/v1/auth/logout-all     revoke every token for this user
GET  /api/v1/auth/sessions       list devices (name, client, last_used_at, ip) · DELETE /auth/sessions/{id}
```

### 3.2 Rules
- **One token per device.** `device_name` is shown in the user's session list, e.g. "John's iPhone · PWA".
- **Expiry:**
  - Default: tokens expire 30 days after last use (sliding).
  - With "Remember me": 90 days.
  - Super Admin tokens: 12 hours.
- **Token abilities:**
  - Normal user tokens have `['*']`.
  - Impersonation tokens have `['impersonate']`, an `impersonated_by` link and a 60-minute expiry.
  - Integration keys have the scopes they were given.
- **Login as Owner** (Super Admin): `POST /platform/companies/{id}/impersonate` returns a short-lived token for the company owner. Every request made with it is written to the audit log with the Super Admin's id, and the UI shows a red "Viewing as …" banner.
- **Login protection:** after 5 failed logins in 15 minutes the account and IP are locked for 15 minutes. Every login is recorded in `login_histories`.
- **Status checks at login:**
  - Suspended company: login is refused with code `company_suspended`.
  - Inactive user: login is refused with code `user_inactive`.
  - Expired subscription: login is allowed, but the session is read-only (see §4).
- **Password reset and email verification** work by code or link, sent by email (`/auth/forgot-password`, `/auth/reset-password`, `/auth/verify-email`, `/auth/resend-verification`).

---

## 4. Tenancy, permissions & plan checks

Each request passes through these checks in order (middleware):

| # | Check | Fails with |
|---|---|---|
| 1 | `auth:sanctum`: valid token | 401 `unauthenticated` |
| 2 | `tenant`: sets `Tenant::id()` from **the token's user** (never from the request body or a header) | 403 `no_company` |
| 3 | `company.active`: the company is not suspended | 403 `company_suspended` |
| 4 | `subscription`: if the trial or plan has expired (after the grace period), **only GET requests and the billing endpoints** are allowed | 402 `subscription_expired` |
| 5 | `plan.feature:<key>`: the module is in the company's plan | 403 `feature_locked` (+ `required_plan`) |
| 6 | Permission check in the controller (`can('trips.approve')`) | 403 `permission_denied` |
| 7 | Plan limit check on create (trucks, drivers, users, trailers, storage, trips per month) | 403 `plan_limit_reached` (+ `limit`, `used`) |
| 8 | Record scope (`Access::scopeTrips`): drivers only reach their own records | 404 (the record is invisible, not forbidden) |

Notes:
- Platform routes (`/platform/*`) replace checks 2–7 with a `platform` middleware (`user_type` must be `super_admin` or `platform_staff`) plus `platform.*` permissions.
- Every model with `company_id` uses the `BelongsToCompany` global scope. Foreign ids in the request are validated against the caller's company (`existsInCompany`).
- `company_id` sent in a request body is **ignored**.

---

## 5. Request conventions

| Item | Rule |
|---|---|
| Base URL | `{API_URL}/api/v1` |
| Format | JSON (`Content-Type: application/json`). File uploads use `multipart/form-data`; updates with files are `POST` + `_method=PUT` |
| Required headers | `Authorization: Bearer …` (except public endpoints) · `Accept: application/json` |
| Optional headers | `X-Client: web\|pwa\|android\|ios\|integration` · `X-Client-Version: 1.4.2` · `X-Timezone: America/Chicago` · `Accept-Language: en` · `Idempotency-Key: <uuid>` |
| URLs | kebab-case nouns, plural: `/expense-categories`, `/trips/{id}/submit`. Ids are numbers |
| CRUD | `GET /x` (list) · `POST /x` (create) · `GET /x/{id}` · `PUT /x/{id}` · `DELETE /x/{id}` (`Route::crud`) |
| Actions | `POST /x/{id}/<verb>`: `submit`, `approve`, `reject`, `reopen`, `finalize`, `pay`, `suspend`… |
| Field names | snake_case in both requests and responses |
| Dates | `YYYY-MM-DD` for dates. Date-times are ISO 8601 with offset (`2026-11-14T09:30:00-06:00`), stored in UTC and returned in the company's timezone |
| Numbers | Money: number, 2 decimals (`1382.40`). Gallons: 3 decimals. Miles and odometer: 1 decimal / integer. Percentages: number (`2.5`) |
| Booleans | `true`/`false` (multipart: `1`/`0`) |
| Idempotency | `POST` requests that create records (`/trips`, `/billing/invoices/{id}/payments`, `/settlements/generate`, `/sync/push`) accept `Idempotency-Key`. Sending the same key again within 24 hours returns the first result |

---

## 6. Response format

**One record**
```json
{ "data": { "id": 42, "trip_no": "TRP-2026-00042", "...": "..." }, "message": "Trip submitted" }
```

**List (paginated)**
```json
{
  "data": [ { "id": 42, "...": "..." } ],
  "meta":  { "current_page": 1, "per_page": 25, "last_page": 1, "total": 12, "from": 1, "to": 12,
             "total_unfiltered": 340, "filters_applied": { "status": ["submitted"], "driver_id": [7], "date_preset": "this_month" },
             "sort": ["-trip_date"] },
  "links": { "first": "...?page=1", "last": "...?page=1", "prev": null, "next": null }
}
```
`meta.total_unfiltered` and `meta.filters_applied` let any client show "Showing **12** of 340" and the active filter chips.

**Dropdown list** (`?all=1`)
```json
{ "data": [ { "id": 4, "label": "T-104 · Freightliner Cascadia", "...": "..." } ] }
```

**Action result**: `{ "data": { ...updated record... }, "message": "Trip approved" }`

**Shape rules**
- Responses are built with Laravel API Resources (`TripResource`, …). Database columns are never returned directly.
- Related records appear as nested objects (`driver: {id, name}`), and `?include=` loads extra relations.
- Money fields the user is not allowed to see (`load_rate`, `driver_pay`, `net_profit` without `trips.view_revenue`) are **left out entirely**, not returned as `null`.
- Every record includes a `can` object with the actions the current user may take, so every client can show or hide buttons the same way:
  `"can": { "update": true, "submit": true, "approve": false, "delete": true }`

---

## 7. Errors

Every error has the same shape:
```json
{ "message": "Human readable message", "code": "machine_code", "errors": { "field": ["Validation message"] } }
```

| HTTP | `code` | When |
|---|---|---|
| 400 | `bad_request` | Malformed request |
| 401 | `unauthenticated` | Missing, invalid or expired token |
| 402 | `subscription_expired` | Trial or plan expired; the account is read-only (body includes `billing_url`) |
| 403 | `permission_denied` | The user lacks the permission |
| 403 | `feature_locked` | The module isn't in the plan (`required_plan: "Professional"`) |
| 403 | `plan_limit_reached` | `{limit: "trucks", max: 15, used: 15}` |
| 403 | `company_suspended` / `user_inactive` | Account status |
| 404 | `not_found` | Missing or out of scope |
| 409 | `conflict` | State conflict (e.g. approving an already approved trip, or editing a locked trip) |
| 409 | `duplicate` | Same `Idempotency-Key` sent with a different payload |
| 413 | `file_too_large` | Upload over the limit (10 MB) |
| 422 | `validation_failed` | Field errors in `errors` |
| 423 | `record_locked` | Trip approved/settled, or settlement paid |
| 429 | `too_many_requests` | Rate limit (`Retry-After` header) |
| 500 | `server_error` | Unexpected (logged with a request id; `X-Request-Id` header) |

Warnings that don't block saving are returned with the record in `meta.warnings`, for example:
```json
"meta": { "warnings": [ { "code": "mileage_variance", "message": "State miles are 5 mi (0.4%) less than odometer miles." },
                        { "code": "duplicate_load_no", "message": "Load 458812 is already used on TRP-2026-00031." } ] }
```

---

## 8. Lists: pagination, filters, sorting, export

All list endpoints use the same query parameters:

| Param | Example | Meaning |
|---|---|---|
| `q` | `q=phoenix` | Searches the endpoint's `$searchable` columns |
| `page`, `per_page` | `per_page=25` | Default 25, max 100 |
| `all` | `all=1` | Unpaginated dropdown list (max 500, `id` + `label`) |
| `sort` | `sort=-trip_date,driver_name` | Comma-separated; `-` means descending. Only whitelisted fields (`$sortable`), including related names |
| Filter (single) | `truck_id=4` | Exact match |
| Filter (multi) | `status[]=submitted&status[]=draft` | Matches any of the values |
| Range | `miles_min=100&miles_max=2000` | `_min` / `_max` suffixes |
| Dates | `date_from=2026-11-01&date_to=2026-11-30` or `date_preset=this_month` | Presets: `today, yesterday, this_week, last_week, this_month, last_month, this_quarter, this_year` |
| Booleans | `has_receipts=1` | |
| `include` | `include=stops,expenses` | Load extra relations |
| `fields` | `fields=id,trip_no,status,total_miles` | Return only these fields (smaller responses for phones) |
| `export` | `export=xlsx` or `export=pdf` | Same filters and sort; returns a file download (large exports are queued and announced by notification) |

The filter list for each endpoint follows SOFTWARE_DETAILS.md §11. Each list endpoint documents its `searchable`, `filterable` and `sortable` fields in the generated API docs (§12).

Saved views: `CRUD /saved-filters` with `{page_key, name, filters: {...}, is_default}`. Any client can store and re-apply them.

---

## 9. Files & uploads

- **Upload:** use `multipart/form-data` on the parent record (e.g. `POST /trips/{id}/attachments` with `file`, `type`), or on the dedicated endpoints for logo, proof and signature.
- **Limits:**
  - Images (jpg/png/webp/heic) and PDF only.
  - 10 MB per file.
  - Uploads count toward the plan's storage limit.
  - Phone clients compress photos before upload (about 200 KB).
- **Response:** each file is returned as an object:
  ```json
  { "id": 91, "type": "receipt", "name": "toll.jpg", "mime": "image/jpeg", "size": 184220, "url": "https://…signed…", "thumb_url": "…" }
  ```
- **Access:**
  - Private files (receipts, proofs, signatures, ticket attachments) use **signed URLs that expire after 30 minutes**.
  - Company logos are public.
- **Signature:** `POST /trips/{id}/submit` accepts `signature` as a PNG file, or `signature_base64` (data URL) for clients that draw on a canvas.

---

## 10. Phone app support: bootstrap, offline sync, push

### 10.1 Single startup call
`GET /app/bootstrap` returns everything the app needs to start in **one request**:

```json
{ "data": {
  "user": { "id": 12, "name": "John Smith", "user_type": "driver", "employee_id": 7, "preferences": { "theme": "ocean", "mode": "light" } },
  "company": { "id": 3, "name": "RanaBros", "logo_url": "…", "timezone": "America/Chicago", "week_start": "monday" },
  "subscription": { "status": "trial", "plan": "Professional", "trial_days_left": 5, "read_only": false },
  "permissions": ["trips.view", "trips.create", "trips.submit", "settlements.view"],
  "features": ["trip_sheets", "driver_mobile", "settlements"],
  "menu": { "area": "driver",
            "sections": [ { "key": "main", "label": "Main", "sort_order": 0 } ],
            "items": [ { "key": "driver.home", "section": "main", "label": "Home", "icon": "house", "path": "/", "exact": true,
                         "permission": null, "feature": null, "badge": null, "sort_order": 0 } ] },
  "settings": { "trips.variance_pct": 2, "trips.require_signature": true, "trips.require_approval": true },
  "lookups": { "trucks": [...], "trailers": [...], "drivers": [...], "jurisdictions": [...], "expense_categories": [...], "parties": [...] },
  "counts": { "unread_notifications": 2, "draft_trips": 1, "pending_approvals": 0 },
  "lookups_version": "2026-11-14T09:02:11Z"
} }
```

- `menu` is the **database-driven sidebar** (tables `menu_sections`, `menu_items`, managed in Platform → Menu Manager): the active sections and the active items of the user's area (`company` · `driver` · `platform`), sorted by section then item order. Clients still hide items the user has no `permission` for and show a lock on items whose plan `feature` is missing; routes are always enforced by the API.
- `GET /app/version`: `{ min_supported, latest, force_update }`, for native apps and PWA update prompts.
- `GET /lookups?since=<lookups_version>`: returns only the lookup items that changed, so the app can refresh its stored copy cheaply.

### 10.2 Offline trip drafts
- The client gives each draft a `client_uuid`. `POST /trips` and `PUT /trips/{id}` are **upserts by `client_uuid`**, so sending the same draft twice never creates a duplicate.
- Batch upload when the connection returns:
  ```
  POST /sync/push   { "trips": [ { "client_uuid": "…", "updated_at_client": "…", ...full trip payload... } ] }
  → { "data": { "results": [ { "client_uuid": "…", "status": "created|updated|conflict|error", "id": 42, "errors": {} } ] } }
  ```
- **Conflict rule:** the server copy wins once the trip has been Submitted or Approved. A Draft takes the newest `updated_at_client`.
- Receipt photos taken offline are uploaded afterwards to `/trips/{id}/attachments`.

### 10.3 Push & polling
- **Web Push (live, 17 Nov):**
  - `GET /push/key` returns `{public_key, enabled}`, the server's VAPID key for `PushManager.subscribe({ userVisibleOnly: true, applicationServerKey })`.
  - `POST /push/subscribe {platform: "webpush", endpoint (https), keys: {p256dh, auth}, device_name}` saves a subscription. `{ platform: "fcm", token }` is reserved for native apps (Phase 3). Remove with `DELETE /push/subscribe {endpoint}`.
  - `POST /push/test` sends a test push to the user's devices right away. It returns 422 `push_no_device` when none received it, and 503 `push_unavailable` when the server has no VAPID keys.
  - Every notification (`Notifier`) is also pushed, unless the user turned push off for that type (`notifications.<type>.push`). It is sent by a queued job after commit.
  - Payload: `{title, body, url, tag, icon, badge}`. `tag` replaces the older notification on the phone: `trip-<id>`, `truck-doc-<id>`, `maintenance-<id>`. Tapping it opens `url`.
  - Devices that answer 404 or 410 are removed.
- `GET /notifications/unread-count` is a cheap endpoint for 60-second polling. Real-time updates (Reverb) come in Phase 2.

---

## 11. Versioning, rate limits, CORS, security

- **Versioning:**
  - Everything is under `/api/v1`. Adding fields or endpoints is not a breaking change.
  - Breaking changes go to `/api/v2`, with `v1` kept for at least 6 months.
  - Deprecated endpoints send `Deprecation` and `Sunset` headers.
- **Rate limits** (per token, falling back to per IP):

  | Group | Limit |
  |---|---|
  | `auth/login`, `forgot-password` | 10 / min / IP |
  | `public/signup` | 5 / hour / IP |
  | General API | 120 / min |
  | Uploads | 30 / min |
  | Exports | 10 / min |
  | Integration keys | 60 / min |

- **CORS:** only the frontend origins listed in `FRONTEND_URLS` (e.g. `https://app.fleettruck360.com,http://localhost:5174`). Credentials aren't needed because tokens are used instead of cookies.
- **Security:**
  - HTTPS only; HSTS.
  - Passwords hashed with bcrypt.
  - Tokens are stored hashed (Sanctum).
  - Every query is scoped by company.
  - Mass assignment is guarded (`$guarded = ['id']` + FormRequest validation).
  - Uploads are checked by MIME type and stored outside the public web root.
  - All changes are audit-logged (`Auditable`).
  - Every response has an `X-Request-Id`, and errors are logged with it.
- **Performance targets:**
  - p95 under 300 ms for list and detail requests at 25 rows.
  - `/app/bootstrap` under 500 ms.
  - Related records are loaded in advance (`$with`) to avoid N+1 queries.
  - Indexes per SOFTWARE_DETAILS.md §16.
  - Lookups and plan features are cached per company (cleared when they change).

---

## 12. API documentation & testing

- **Generated docs:** `knuckleswtf/scribe` builds **OpenAPI 3** docs and a **Postman collection** from the routes, FormRequests and Resources. They're published at `{API_URL}/docs` (protected in production) and regenerated on every release.
- **API contract tests:** a Pest/PHPUnit feature test per endpoint covering:
  - Success path, plus validation (422).
  - Permission denied (403), feature locked (403), plan limit (403).
  - Tenant isolation: company A can never see company B's data.
  - Read-only subscription (402).
- **Demo data:** seeders create a demo platform (Super Admin) and the demo company **RanaBros**, with an owner, a dispatcher, an accountant, two drivers, trucks, trailers and trips, so every client can be tested against the same data.
- **Local URLs:** API at `http://localhost:8000` (`php artisan serve`), frontend at `http://localhost:5174` (`npm run dev`).

---

## 13. Endpoint catalogue

**Column meanings:**
- **Perm**: the permission required (`own` means drivers are scoped to their own records). Endpoints that only need a valid login are marked `auth`.
- **Feature**: the plan module required.
- `crud` expands to the 5 routes in §5.

### 13.1 Public (no token)
| Method | Path | Notes |
|---|---|---|
| GET | `/public/plans` | Standard plans for the pricing page (limits + modules) |
| GET | `/public/posts` · `/public/posts/{slug}` | Website blog: live posts only (`?category, tag, q, per_page≤200`; detail adds body, SEO fields and 3 related posts) |
| POST | `/public/posts/{slug}/view` | View counter beacon from the article page (own limit `post-views`, 30 / min per IP; it does not use the forms' `public-form` budget) |
| POST | `/public/signup` | `{company_name, owner_name, email, phone, password, usdot?, accept_terms}` creates the company, owner and trial subscription, and sends the verification email |
| GET | `/public/settings` | Public platform info (support phone, terms URL, trial days) |

### 13.2 Auth & account
| Method | Path | Perm | Notes |
|---|---|---|---|
| POST | `/auth/login` | – | Returns token + bootstrap summary |
| POST | `/auth/logout` · `/auth/logout-all` | auth | |
| GET | `/auth/me` | auth | User, company, permissions, features |
| GET / DELETE | `/auth/sessions` · `/auth/sessions/{id}` | auth | Device list / revoke |
| POST | `/auth/forgot-password` · `/auth/reset-password` | – | |
| POST | `/auth/verify-email` · `/auth/resend-verification` | – / auth | |
| PUT | `/auth/password` | auth | Change own password |
| PUT | `/auth/profile` · POST `/auth/avatar` | auth | Own name, phone, photo |
| PUT | `/auth/preferences` | auth | Theme, mode, sidebar, language |

### 13.3 App (phone / any client)
| Method | Path | Perm | Notes |
|---|---|---|---|
| GET | `/app/bootstrap` | auth | §10.1 |
| GET / POST | `/notifications` · `/notifications/unread-count` · `/notifications/read-all` · `/notifications/{id}/read` | auth (any user type, incl. Super Admin) | Personal notifications |
| GET | `/search?q=` (company & driver) · `/platform/search?q=` (Super Admin) | auth | Global search (top bar), min 2 chars: groups `[{key, label, icon, items:[{id, title, subtitle, badge, url}], more, see_all}]`; company: trip sheets, trucks, trailers, drivers & employees, shippers & consignees, settlements, invoices, tickets; Super Admin: companies, company users, invoices, tickets, demo requests, platform users. Only groups the user may see; drivers only their own trips / pay / tickets |
| GET | `/app/version` | – | Update prompt |
| GET | `/lookups` | auth | `?since=`. Trucks, trailers, drivers, parties, jurisdictions, expense categories |
| POST | `/sync/push` | trips.create | Offline batch (§10.2) |

### 13.4 Dashboard
| Method | Path | Perm | Feature | Notes |
|---|---|---|---|---|
| GET | `/dashboard` | dashboard.view | – | Widgets merged from each module (`?date_from&date_to&date_preset&truck_id&driver_id`). Finance widgets need `dashboard.finance` |
| GET | `/dashboard/driver` | trips.view (own) | driver_mobile | Driver home: drafts, week stats, week pay |

### 13.5 Company profile, settings, users, roles
| Method | Path | Perm | Feature |
|---|---|---|---|
| GET / PUT | `/company/profile` | company.profile | – |
| POST | `/company/logo` | company.profile | – |
| POST | `/company/transfer-ownership` | owner only | – |
| POST | `/company/export` | owner only | – (queued; download link sent by notification) |
| POST | `/company/close-request` | owner only | – |
| GET / PUT | `/settings` | settings.manage | – |
| GET | `/menus` · POST `/menus/sync` · crud `/menus` | auth / menus.manage | – |
| crud | `/users` · POST `/users/{id}/reset-password` · `/users/{id}/toggle-active` | users.view / create / update / delete | – · People with more access than the caller (owner, Owner role, or — without `roles.manage` — any permission the caller lacks) are left out and answer 404. Role and direct `permissions` given must be ones the caller has (Owner role only from the owner), else 403 `permission_denied` (`App\Support\RoleGrants`) |
| crud | `/roles` · GET `/permissions` | roles.manage (GET: also users.view / create / update, employees.view / manage_login) | custom_roles (create/edit custom roles). Without `roles.manage` the GETs list only the roles / permissions the caller may give |
| GET | `/audit-logs` | audit.view | audit_log |
| crud | `/saved-filters` · POST `/tours/{key}/complete` · DELETE `/tours` (reset) | auth | – |

### 13.6 Fleet, employees, parties, lookups
| Method | Path | Perm | Notes |
|---|---|---|---|
| crud | `/trucks` | trucks.* | Plan limit `max_trucks` on create |
| GET | `/trucks/{id}/last-odometer` | trucks.view or trips.create | Pre-fills Starting Miles |
| crud | `/trailers` | trailers.* | Plan limit `max_trailers` |
| crud | `/truck-documents` | truck_documents.* | Multipart `file`. Filters: `truck_id`, `type`, `status[]=expired\|expiring\|ok\|none`, `expiring=<days>\|expired\|valid`, `date_from/date_to` (on expiry). Types: registration, insurance, dot_inspection, ifta, irp, title, lease, permit, other (`title` required). Registration / insurance keep `trucks.registration_expiry / insurance_expiry` in sync both ways |
| crud | `/maintenance-items` | maintenance.* | Service schedules. `interval_miles` and/or `interval_days`. Empty "last done" means today and the truck's odometer. Rows add `status` (overdue / due_soon / ok / paused), `miles_left`, `days_left`, `due_text` and `interval_text`. Filter `status[]`, `truck_id`, `type`; default sort `due` (most urgent first) |
| POST | `/maintenance-items/{id}/complete` | maintenance.update | Log a service `{service_date, odometer?, shop_name?, cost?, invoice_no?, notes?, file?}`. Writes a service record, moves "last done" and the next due point, resets the alert, and raises the truck odometer if the service odometer is higher |
| GET | `/maintenance-items/templates` | maintenance.view | Ready-made schedules + the "due soon" window |
| GET | `/maintenance-history` | maintenance.view | Service records **plus repairs from trip sheets** (not drafts), newest first. Filters: `truck_id[]`, `source[]=service\|trip`, `q`, `date_from/date_to`. `meta.total_cost`. Trip rows are read-only (`link` → the trip) |
| POST · GET/PUT/DELETE | `/maintenance-history[/{id}]` | maintenance.* | Service records entered in the office (multipart `file`) |
| crud | `/employees` (`?is_driver=1`) | employees.* | Driver fields in `driver_details` (pay fields need `drivers.view_pay`). Plan limit `max_drivers` when `is_driver` |
| POST | `/employees/{id}/login` · DELETE `/employees/{id}/login` | employees.manage_login | Create or remove a login with role + extra permissions. Plan limit `max_users`. Same role rule as `/users`; the login of someone with more access is shown as `login: {restricted: true}` and answers 403 |
| crud | `/driver-documents` (multipart `file`) · GET `/driver-files` · `/driver-files/{employee}` · `/driver-files/{employee}/audit` (PDF) · `/driver-files/{employee}/zip` | driver_files.* | Driver Qualification Files: documents per driver; overview with `clearance` (cleared / expiring / not_cleared), `blockers`, `warnings`; checklist `items[]` with status ok / expiring / expired / overdue / missing / needs_date / not_due / optional |
| GET/POST | `/driver-applications` · GET `/driver-applications/{id}` · `/{id}/pdf` · `/{id}/ssn` · POST `/{id}/link` · `/{id}/approve` {hire_date} · `/{id}/reject` {note} · DELETE `/{id}` | driver_files.* | Driver self-onboarding (office side); invite returns the private `link` once |
| public | GET/PUT `/public/driver-applications/{token}` {data, ssn} · POST `/{token}/files` {type: cdl_front\|cdl_back\|medical\|other, file} · POST `/{token}/submit` {signature} | link token | The driver's DOT employment application (no login); `missing` lists what is still needed |
| crud | `/company-filings?status=open|done|skipped|overdue|due_soon` · GET `/company-filings/types` · POST `/company-filings/{id}/done` {done_on, reference_no, amount, notes, file} · `/company-filings/{id}/skip` · `/company-filings/types/{type}/enable` | filings.* | Compliance calendar; GET open first creates the next auto filings (MCS-150 from USDOT, UCR, IFTA return + licence, HVUT 2290); done → `next` occurrence returned |
| GET | `/dispatch/live` · GET/POST `/trucks/{truck}/trackers` {kind: screen\|gps, name} (code + setup shown once) · DELETE `/trackers/{id}` | dispatch.view / dispatch.manage_trackers | Live Dispatch: trucks (state, position, trip, trail), trips on the road with map points, counts |
| public | GET\|POST `/track/osmand?id=CODE&lat=&lon=&timestamp=&speed=&bearing=&accuracy=&batt=` (OsmAnd: Traccar Client, GPS trackers; speed in knots) · GET/POST `/track/{code}` (cab screen; speed m/s, timestamp ms) | device code | Truck positions, no login; throttle `tracking` |
| POST | `/employees/{id}/photo` | employees.update | |
| crud | `/departments` · `/designations` | employees.* | |
| crud | `/parties` (`?type=shipper\|consignee`) | parties.* | |
| crud | `/expense-categories` | categories.manage | System categories: rename/hide only |
| crud | `/jurisdictions` | jurisdictions.manage | The company's own additions; platform ones are read-only |

### 13.7 Trips (trip sheets)
| Method | Path | Perm | Notes |
|---|---|---|---|
| GET | `/trips` | trips.view (own) / trips.view_all | All filters from SOFTWARE_DETAILS.md §11 |
| POST | `/trips` | trips.create (self) / trips.create_any | Full payload (header + stops + state_mileages + expenses). Upsert by `client_uuid`. Returns calculated totals + warnings |
| GET | `/trips/{id}` | trips.view | `include=stops,state_mileages,expenses,attachments,status_logs` |
| PUT | `/trips/{id}` | trips.update (own) / trips.update_any | Draft/Rejected only, otherwise 423 |
| DELETE | `/trips/{id}` | trips.delete | Draft only |
| POST | `/trips/{id}/submit` | trips.submit | Signature required when `trips.require_signature`. Auto-approves when `trips.require_approval=false` |
| POST | `/trips/{id}/approve` | trips.approve | |
| POST | `/trips/{id}/reject` | trips.approve | `{note}` is required; the driver is notified |
| POST | `/trips/{id}/reopen` | trips.reopen | Approved → Draft (not allowed once settled) |
| POST | `/trips/{id}/duplicate` | trips.create | New draft with the same driver/truck/route; odometer and expenses cleared |
| GET | `/trips/{id}/pdf` | trips.view | Copy of the paper sheet. Revenue only appears with `view_revenue` and `?copy=office` |
| POST / DELETE | `/trips/{id}/attachments` · `/trips/{id}/attachments/{aid}` | trips.update | `type: bol\|pod\|receipt\|signed_sheet\|other`, optional `trip_expense_id` |
| POST | `/trips/calculate` | trips.create | Optional preview: send a draft payload, get server totals and warnings without saving |
| GET | `/portal/trips` · POST `/portal/trips` · PUT `/portal/trips/{id}` | trips.create (self) | Same as `/trips` but always limited to the logged-in driver |

**Repairs on the trip payload** (POST/PUT `/trips`, `/portal/trips`, `/trips/calculate`): optional `repairs[]` (max 20). Sending `repairs` replaces the trip's repairs (`[]` removes them); leaving it out keeps them. Empty repair cards and parts without a name are skipped.
```json
"repairs": [{
  "repair_date": "2026-11-15", "location_city": "Amarillo", "location_state": "TX", "odometer": 412910, "downtime_hours": 6,
  "problem": "Air brake line leaking", "work_done": "Replaced rear air line",
  "shop_name": "Big Rig Road Service", "shop_phone": "806-555-0142", "shop_address": "1200 I-40 E, Amarillo TX",
  "mechanic_name": "Carlos Diaz", "mechanic_phone": "806-555-0199",
  "labor_cost": 180, "payment_method": "cash|comcheck|fuel_card|company_card|shop_invoice|other", "invoice_no": "BR-7781", "notes": null,
  "parts": [{ "name": "Air brake hose", "part_no": "AH-38", "action": "replaced|new|repaired|adjusted", "qty": 2, "unit_cost": 42.5 }]
}]
```
The response adds `repairs_total` (always) and `repairs[]` with `parts_cost`, `total_cost` and each part's `line_total` (detail, or `?include=repairs` on lists). `expenses_total` includes `repairs_total`.

#### Trip templates + duplicate (18 Nov)
| Method | Path | Perm | Notes |
|---|---|---|---|
| POST | `/trips/{id}/duplicate` | trips.create_any, or own trip + trips.create | New draft with the repeating parts: driver + co-drivers, truck, trailer, route, stops, states (0 / 0), load rate (only with trips.view_revenue) |
| GET | `/trip-templates?search=` | trips.create \| trips.create_any | Company templates: name, driver, co_drivers, truck, trailer, load_from, destination, shipper, consignee, states[], uses_count, can.manage; load_rate only with trips.view_revenue |
| POST | `/trip-templates` | trips.manage_templates | `{name, trip_id}` save from a trip (name unique per company → 422) |
| PUT / DELETE | `/trip-templates/{id}` | trips.manage_templates | `{name}` rename · delete |
| POST | `/trip-templates/{id}/use` | trips.create \| trips.create_any | New draft (trip detail shape). A driver entering own sheets becomes the main driver. Driver / truck no longer active → 422 `template_outdated` |

### 13.8 Settlements
| Method | Path | Perm | Feature |
|---|---|---|---|
| GET | `/settlements` | settlements.view (own) / view_all | settlements |
| POST | `/settlements/generate` | settlements.create | settlements. `{period_start, period_end, driver_ids[]}` creates one draft per driver from approved trips not yet settled for that driver. Team trips: every driver owed something gets their own wage; the trip's reimbursements / deductions go to the main driver only |
| GET / PUT / DELETE | `/settlements/{id}` | settlements.* | settlements |
| POST / DELETE | `/settlements/{id}/items` · `/settlements/{id}/items/{iid}` | settlements.create | Manual deduction, bonus or reimbursement |
| POST | `/settlements/{id}/finalize` | settlements.finalize | |
| POST | `/settlements/{id}/pay` | settlements.pay | `{paid_on, payment_method, payment_ref}`. Marks a trip Settled once every driver owed something on it is paid |
| GET | `/settlements/{id}/pdf` | settlements.view | |
| GET | `/portal/settlements` · `/portal/settlements/{id}` | own | Driver's own pay |

### 13.9 Reports
| Method | Path | Perm | Feature |
|---|---|---|---|
| GET | `/reports/trip-summary` | reports.view | reports_basic |
| GET | `/reports/expenses` | reports.view | reports_basic |
| GET | `/reports/driver-performance` · `/reports/truck-performance` | reports.view | reports_basic |
| GET | `/reports/state-mileage` | reports.ifta | reports_advanced |
| GET | `/reports/profit` · `/reports/driver-pay` | reports.finance | revenue_profit |

All reports accept the list filters + `group_by=truck|driver|state|category|month` + `export=xlsx|pdf` (export needs the `excel_pdf_export` feature).

### 13.10 Billing (company side; still works when the subscription has expired)
| Method | Path | Perm | Notes |
|---|---|---|---|
| GET | `/billing/overview` | billing.view | Plan, status, trial/grace days, usage vs limits |
| GET | `/billing/plans` | billing.view | Standard plans + custom plans assigned to this company |
| POST | `/billing/subscribe` | billing.manage | `{plan_id, cycle}` creates a Pending invoice. Downgrades are refused if usage is over the new limits (422 with details) |
| GET | `/billing/invoices` · `/billing/invoices/{id}` · `/billing/invoices/{id}/pdf` | billing.view | |
| POST | `/billing/invoices/{id}/payments` | billing.manage | Multipart: `method (cash\|bank_transfer)`, `amount`, `paid_on`, `platform_bank_account_id?`, `transaction_ref?`, `proof`. Invoice → Under Review |
| GET | `/billing/bank-accounts` | billing.view | Active platform bank accounts + cash instructions |

### 13.11 Communication & support
| Method | Path | Perm | Feature |
|---|---|---|---|
| GET | `/notifications` (`?category=announcement\|alert`) · `/notifications/unread-count` | auth | – |
| POST | `/notifications/{id}/read` · `/notifications/read-all` | auth | – |
| GET / PUT | `/notification-preferences` | auth | – |
| POST / DELETE | `/push/subscribe` | auth | – |
| GET | `/announcements/feed` | auth | – (platform + company announcements for this user: banners, popups) |
| POST | `/announcements/{id}/ack` | auth | – |
| crud | `/announcements` · GET `/announcements/{id}/reads` | announcements.manage | company_announcements |
| crud | `/tickets` (own company) · POST `/tickets/{id}/replies` · `/tickets/{id}/rate` · `/tickets/{id}/close` | tickets.view / tickets.create | – |
| GET | `/help/categories` · `/help/articles` (`?q&module_key&audience`) · `/help/articles/{slug}` | auth | – |
| POST | `/help/articles/{id}/feedback` | auth | – |

### 13.12 Platform (Super Admin)
All routes below are under `/platform/*` with the `platform` middleware + `platform.*` permissions.

| Method | Path | Notes |
|---|---|---|
| GET | `/platform/dashboard` | KPIs, charts, expiring subscriptions, payments to verify, signups, top companies, tickets, health |
| crud | `/platform/companies` | Create = company + owner + subscription (provisions roles, menus, categories, settings) |
| POST | `/platform/companies/{id}/suspend` · `/activate` | Reason required for suspend |
| POST | `/platform/companies/{id}/impersonate` | Short-lived owner token (§3.2) |
| PUT | `/platform/companies/{id}/subscription` | Change plan, extend trial, set `custom_limits`, set custom plan visibility |
| POST | `/platform/companies/{id}/cash-payment` | Record a cash payment directly |
| GET | `/platform/companies/{id}/usage` · `/activity` · `/users` | |
| crud | `/platform/plans` · PUT `/platform/plans/{id}/companies` | Standard/custom plans, limits, modules; custom plan visibility |
| GET | `/platform/subscriptions` · `/platform/invoices` · `/platform/invoices/{id}` | |
| GET | `/platform/payments` (`?status=pending`) | Verification queue |
| POST | `/platform/payments/{id}/approve` · `/reject` | Approve: invoice paid → subscription activated/extended → receipt → notify. Reject: `{reason}` |
| crud | `/platform/bank-accounts` | |
| GET | `/platform/tickets` · `/platform/tickets/{id}` | |
| POST | `/platform/tickets/{id}/assign` · `/replies` (`is_internal`) · `/status` | |
| crud | `/platform/canned-replies` · `/platform/help-categories` · `/platform/help-articles` | |
| crud | `/platform/announcements` · GET `/platform/announcements/{id}/reads` | Audience: all / plans / companies / roles; channels; schedule |
| crud | `/platform/jurisdictions` · `/platform/users` | |
| GET / PUT | `/platform/ifta-rates?quarter=2026Q4` · body `{quarter, rates:[{code, rate, surcharge}]}` (empty rate removes it) | platform.ifta_rates.view / manage — IFTA diesel tax rates per quarter; `/reports/state-mileage` (group by state, one quarter) adds `tax_due` per row + summary and `meta.ifta {quarter, due_date, missing_rates}` |
| GET / PUT | `/platform/settings` | Trial days, trial plan, grace days, reminders, retention, invoice prefix, payment methods, branding |
| GET | `/platform/audit-logs` | |
| GET | `/platform/menu` | `platform.menu.manage`. All sections + items of every area |
| POST · PUT · DELETE | `/platform/menu/items` · `/platform/menu/items/{id}` | Add a custom link `{area, section, label, icon, path, permission?, feature?, badge?, exact?, is_active?}`, edit/hide a link; only custom links can be deleted (`menu_item_system` 422 otherwise) |
| PUT | `/platform/menu/reorder` | `{items: [{id, section, sort_order}]}` move/reorder |
| PUT | `/platform/menu/sections/{id}` | `{label, sort_order?, is_active?}` rename / reorder / hide a section |
| POST | `/platform/menu/reset` | Restore shipped links and sections to defaults (custom links are kept) |
| GET | `/platform/backups` | `platform.backups.view`. Backups (newest first, `?type[]=manual|scheduled|pre_restore`, `?status[]`) + `meta.stats` (count, total size, last / next backup), `meta.settings`, `meta.tools` (mysqldump / mysql found), `meta.timezone` |
| POST | `/platform/backups` | `platform.backups.create`. Back up now (`{note?}`); 422 `backup_failed` with the reason if mysqldump fails |
| GET | `/platform/backups/{id}/download` | `platform.backups.download`. The `.sql.gz` file |
| POST | `/platform/backups/{id}/restore` | `platform.backups.restore`. `{confirm: "RESTORE"}`. Makes a `pre_restore` safety backup first, loads the file, runs pending migrations, clears caches |
| DELETE | `/platform/backups/{id}` | `platform.backups.delete` |
| PUT | `/platform/backups/settings` | `platform.backups.settings`. `{auto_enabled, frequency: daily|weekly, time: "HH:MM" (server time), keep: 1–365}` |
| crud | `/platform/posts` | `platform.posts.*`. Blog posts: `{title, slug?, excerpt?, body (HTML or plain text), cover (image), cover_alt, category, tags[], status: draft\|published, published_at? (future = scheduled), is_featured, meta_title (≤70), meta_description (≤170), focus_keyword, keywords, noindex}`; `?state=draft\|scheduled\|published`, `?category=`. Body is sanitized (article tags + images); slug, excerpt and reading time are generated |
| GET | `/platform/logs` | `platform.logs.view`. Days found in `storage/logs/laravel.log` / `laravel-YYYY-MM-DD.log`: `[{date, count, bytes, levels:{error:n,…}, files}]` + files and total size |
| GET | `/platform/logs/{date}` | Entries of the day (newest first): `?level, type (exception|database|http|queue|message), status, exception, source (app|vendor|…), search (message, SQL, stack trace), from, to (HH:MM)`; `meta.facets` for the filter lists, `total` / `matched` / `shown` |
| GET | `/platform/logs/entry` | `?file=laravel.log&offset=<byte>` full entry: message, exception + code, file:line, context, stack trace |
| GET | `/platform/logs/{date}/download` | `platform.logs.download`. The day's raw log lines as `laravel-<date>.log` |

---

## 14. Example requests & responses

### 14.1 Login
```http
POST /api/v1/auth/login
Content-Type: application/json
X-Client: pwa

{ "email": "owner@ranabros.test", "password": "••••••••", "device_name": "Owner iPhone", "remember": true }
```
```json
{ "data": {
  "token": "12|Qw3…", "token_type": "Bearer", "expires_at": "2027-02-12T09:30:00-06:00",
  "user": { "id": 2, "name": "Owner", "user_type": "staff", "is_owner": true },
  "company": { "id": 3, "name": "RanaBros" },
  "subscription": { "status": "trial", "plan": "Professional", "trial_days_left": 5, "read_only": false }
} }
```

### 14.2 Trip list with filters
```http
GET /api/v1/trips?date_preset=this_month&driver_id[]=7&status[]=submitted&sort=-trip_date&per_page=25
Authorization: Bearer 12|Qw3…
```
```json
{ "data": [ {
    "id": 42, "trip_no": "TRP-2026-00042", "load_no": "458812", "trip_date": "2026-11-14", "status": "submitted",
    "driver": { "id": 7, "name": "John Smith" }, "truck": { "id": 4, "truck_no": "T-104" }, "trailer": { "id": 9, "trailer_no": "TR-22" },
    "load_from": "Dallas, TX", "destination": "Phoenix, AZ",
    "total_miles": 1245, "total_gallons": 198.5, "expenses_total": 1382.40, "mpg": 6.27, "cost_per_mile": 1.11,
    "has_receipts": true, "variance_warning": true,
    "can": { "update": false, "approve": true, "reject": true, "delete": false }
  } ],
  "meta": { "current_page": 1, "per_page": 25, "total": 12, "total_unfiltered": 340,
            "filters_applied": { "date_preset": "this_month", "driver_id": [7], "status": ["submitted"] }, "sort": ["-trip_date"] } }
```

### 14.3 Create a trip sheet (one payload)
```http
POST /api/v1/trips
Idempotency-Key: 6f1c…   (or client_uuid in body for offline drafts)
```
```json
{
  "client_uuid": "b6b2c1d0-…",
  "trip_date": "2026-11-14", "load_no": "458812",
  "driver_id": 7, "truck_id": 4, "trailer_id": 9,
  "drivers": [                                   // optional — team driving (max 4, main driver first)
    { "driver_id": 7, "hours": 10 },             // pay empty = the driver's usual rate
    { "driver_id": 12, "hours": 10.5, "pay": 300.00 }   // pay only kept with trips.view_revenue
  ],
  "stops": [
    { "type": "shipper",   "party_id": 31, "name": "Lone Star Foods",       "city": "Dallas",  "state": "TX" },
    { "type": "consignee", "party_id": null, "name": "Desert Retail DC #21", "city": "Phoenix", "state": "AZ" }
  ],
  "state_mileages": [
    { "jurisdiction_code": "TX", "gallons": 91.0, "miles": 450 },
    { "jurisdiction_code": "NM", "gallons": 62.5, "miles": 410 },
    { "jurisdiction_code": "AZ", "gallons": 45.0, "miles": 380 }
  ],
  "expenses": [
    { "category_code": "cash_fuel", "amount": 812.40, "payment_method": "cash" },
    { "category_code": "com_check", "amount": 300.00, "payment_method": "comcheck", "reference_no": "CK-55120" },
    { "category_code": "advance",   "amount": 100.00 },
    { "category_code": "toll_fee",  "amount": 45.00 },
    { "category_code": "scales",    "amount": 12.00 },
    { "category_code": "lumper",    "amount": 113.00 }
  ],
  "load_from_city": "Dallas", "load_from_state": "TX", "destination_city": "Phoenix", "destination_state": "AZ",
  "starting_miles": 412300, "ending_miles": 413545,
  "load_rate": 3200.00,
  "notes": ""
}
```
```json
{ "data": {
    "id": 42, "trip_no": "TRP-2026-00042", "status": "draft",
    "total_miles": 1245, "state_miles_total": 1240, "total_gallons": 198.5,
    "expenses_total": 1382.40, "mpg": 6.27, "cost_per_mile": 1.11,
    "driver_pay": 684.75, "net_profit": 1132.85,
    "can": { "update": true, "submit": true, "delete": true }
  },
  "meta": { "warnings": [ { "code": "mileage_variance", "message": "State miles are 5 mi (0.4%) less than odometer miles." } ] },
  "message": "Trip sheet saved as draft" }
```
`driver_pay`/`net_profit` are only returned with `trips.view_revenue`. The server ignores any totals the client sends and calculates its own (SOFTWARE_DETAILS.md §7).

### 14.4 Submit with signature
```http
POST /api/v1/trips/42/submit
Content-Type: multipart/form-data
signature=<png file>        (or signature_base64=data:image/png;base64,…)
```
```json
{ "data": { "id": 42, "status": "submitted", "signed_at": "2026-11-14T18:20:00-06:00" }, "message": "Trip submitted for approval" }
```

### 14.5 Plan limit / feature errors
```json
{ "message": "You've reached 15/15 trucks on the Professional plan. Upgrade to add more.",
  "code": "plan_limit_reached", "limit": "trucks", "max": 15, "used": 15, "upgrade_url": "/billing" }
```
```json
{ "message": "Driver Settlements is available on the Professional plan and above.",
  "code": "feature_locked", "feature": "settlements", "required_plan": "Professional" }
```

### 14.6 Pay an invoice by bank transfer
```http
POST /api/v1/billing/invoices/12/payments
Content-Type: multipart/form-data
method=bank_transfer  amount=59.00  paid_on=2026-11-14  platform_bank_account_id=1  transaction_ref=TX99812  proof=<receipt.jpg>
```
```json
{ "data": { "id": 77, "status": "pending", "invoice": { "invoice_no": "INV-2026-0012", "status": "under_review" } },
  "message": "Thanks! We'll verify your payment within 24 hours." }
```

### 14.7 Super Admin approves the payment
```http
POST /api/v1/platform/payments/77/approve
```
```json
{ "data": { "payment": { "id": 77, "status": "approved" },
            "invoice": { "invoice_no": "INV-2026-0012", "status": "paid" },
            "subscription": { "plan": "Professional", "status": "active", "ends_at": "2026-12-14" } },
  "message": "Payment approved. RanaBros is active until 12/14/2026." }
```

---

## 15. Webhooks & integration keys (later phases)

- **Company API keys** (Phase 3, plan feature `api_access`):
  - `CRUD /api-keys` with scopes (`trips:read`, `trips:write`, `reports:read`, `fleet:read`).
  - Each key is shown once, stored hashed, and has its own rate limit.
- **Webhooks** (Phase 3):
  - `CRUD /webhooks` with `{url, events[], secret}`.
  - Events: `trip.submitted`, `trip.approved`, `trip.rejected`, `settlement.paid`, `invoice.paid`.
  - Requests are signed with HMAC-SHA256 in the `X-Fleet-Signature` header and retried with exponential backoff.
- **Online payments** (Stripe, Phase 3) plug into the same invoice and payment model: a new `method=card`, confirmed by webhook instead of manual verification.


## Website assistant (no AI) — 16 Nov

| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/public/assistant` | public | `{data:{version, answers:[{id,q,v,k,a,u,l,c,s}]}}` — active answers, placeholders filled; `Cache-Control: public, max-age=300` |
| POST | `/public/assistant/ask` | public, throttle `assistant` (30/min/IP) | `{question, page?, answer_id?, picked?, off_topic?}` — answer_id → `hits+1`; + picked → also saved as answered/linked (for *Add as a way to ask*); none → open question (grouped, `times`); off_topic → saved as ignored |
| POST | `/public/assistant/{id}/feedback` | public, throttle `assistant` | `{helpful: bool}` → `helpful_yes` / `helpful_no` |
| GET/POST/PUT/DELETE | `/platform/assistant/answers[/{id}]` | `platform.assistant.*` | CRUD; `from_question_ids[]` on save marks those visitor questions answered |
| GET/PUT/DELETE | `/platform/assistant/questions[/{id}]` | `platform.assistant.*` | filter `status=open|answered|ignored`; PUT `{status}` |
| POST | `/platform/assistant/questions/{id}/learn` | `platform.assistant.update` | `{answer_id?}` — adds the visitor's wording to the answer's variants (dedup), marks it answered |
| GET | `/platform/assistant/knowledge` | `platform.assistant.view` | same as public + `categories`, `placeholders`, `open_questions` (Try it tab) |


## Recycle Bin — 16 Nov

Same endpoints under `/recycle-bin` (company, `recycle_bin.*`) and `/platform/recycle-bin` (Super Admin, `platform.recycle_bin.*`); each item also needs the module's delete permission.

| Method | Path | Notes |
|---|---|---|
| GET | `…/recycle-bin` | `?q, group, type, deleted_by, date_preset|date_from|date_to, sort=-deleted_at, page, per_page` → rows `{id:"truck:12", type, record_id, type_label, group, icon, tint, title, subtitle, deleted_at, deleted_by:{id,name}, can_restore, can_purge, purge_blocked}` + pagination meta |
| GET | `…/recycle-bin/summary` | `{groups:[{key,label,icon,count}], types:[{key,label,group,count}], deleters:[{id,name}], total}` |
| POST | `…/recycle-bin/{type}/{id}/restore` | 409 `restore_conflict` (code in use / trips settled elsewhere), 409 `restore_parent`, 403 `plan_limit_reached` |
| DELETE | `…/recycle-bin/{type}/{id}` | delete forever; 409 `purge_blocked` with the reason |
| POST | `…/recycle-bin/bulk` | `{action: restore|delete, items:[{type,id}]}` → `{done, failed:[{type,id,title,message}]}` |


## Export formats — 16 Nov

Lists (any CrudController index) and reports accept `export=docx|xlsx|csv` (reports and lists also `pdf`). `docx` → `application/vnd.openxmlformats-officedocument.wordprocessingml.document`. Needs the plan module `excel_pdf_export` and the module's export permission (reports: `reports.export`); 403 `feature_locked` otherwise; unknown format on reports → 422.


## Billing cycles — 16 Nov

`cycle` = `monthly` | `quarterly` (3 months) | `half_yearly` (6 months) | `yearly` (+ `trial` on subscriptions) — `POST billing/subscribe`, Super Admin company create / change plan / record cash. Plans (public + platform) return `price_monthly`, `price_quarterly`, `price_half_yearly`, `price_yearly` and `cycles: [{key, label, per, months, price, per_month, save_pct}]`. Plan editor accepts `price_quarterly` / `price_half_yearly` (nullable = monthly × 3 / × 6).

## Refer & Earn + wallet points — 16 Nov

Company (needs `billing.view`, writes `billing.manage`; 403 `referrals_off` while the program is off):
- `GET referrals` (link, wallet, referrals) · `POST referrals/link` (no body) · `GET wallet/transactions`
- `GET billing/invoices/{id}/points` (quote: balance, min / max points, max %, eligible, applied)
- `POST billing/invoices/{id}/points` `{points:int, request_key?:[A-Za-z0-9-]{≤64}}`
- `DELETE billing/invoices/{id}/points`

Super Admin:
- `GET|PUT platform/referrals/settings` `{referral:{enabled,points,link_valid_days,reward_window_days,reward_on}, wallet:{points_per_dollar,max_redeem_pct,min_redeem_points}}`
- `GET platform/referrals` · `POST platform/referrals/{id}/approve {note?}` · `POST platform/referrals/{id}/reject {note}`
- `GET platform/wallets` · `GET platform/wallets/verify` · `POST platform/wallets/{companyId}/adjust {points, reason, request_key}` · `GET platform/wallet-transactions`

Public: `GET public/referral/{code}` (signup banner) · `POST public/signup` accepts `ref`.

## Billing safety — 16 Nov

All money endpoints (above, plus `billing/subscribe`, `billing/invoices/{id}/payments`, `platform/payments/{id}/approve|reject`, `platform/companies/{id}/cash-payment`):
- **422 `unexpected_fields`** `{fields:[…]}`: the request had a key the endpoint does not take (query, body or file).
- **409 `billing_busy`**: another billing action for the same company is running (second tab / double click). Retry after it finishes.
- **409 `conflict`**: the state changed (invoice already paid or under review, payment already reviewed, referral not waiting for review).

## Billing Log & History — 16 Nov (`platform.billing_log.view`)

- `GET platform/billing-events`:
  - filters `group` (invoice|payment|subscription|points|wallet|referral|security|settings), `event`, `company_id`, `invoice_id`, `payment_id`, `actor_type`, `actor_id`, `ip`, `q` (text / event / request id), `date_from`, `date_to`;
  - `export=xlsx|csv|pdf|docx`;
  - `meta.events`, `meta.groups`.
- `GET platform/billing-events/summary` (same filters) → `{total, groups[], payments_approved, payments_approved_count, payments_rejected_count, points_earned, points_used, refused, security}`
- `GET platform/billing-events/{id}` → all fields + `actor_email` + `same_request[]`
- `GET platform/billing-history?type=company|invoice|payment|referral|request&id=` → `{title, items[] (kind log|ledger, in order), invoices[], payments[], referrals[]}`

## Atomic writes (every POST / PUT / PATCH / DELETE) — 16 Nov

- **409 `request_in_progress`**: the same user is already running this same action (another tab / double click). Wait for it.
- **409 `write_busy`**: another user of the company has run the same action for longer than 15 s. Retry.
- **409 `write_conflict`**: database deadlock or lock-wait timeout. Nothing was saved; retry.
- Any error response means **nothing from that request was saved** (one transaction per request). Failed logins and billing security lines are kept anyway.

## IP Block Management — 16 Nov (`platform.ip_blocks.view` / `.manage`)

Any request from a blocked IP / range → **403 `ip_blocked`** `{message, until}` (before login or anything else).

- `GET platform/ip-rules` filters `status` (active|expired|removed), `action` (block|allow), `type` (manual|auto), `source` (manual|flood|login|security|scan|attack), `q`
- `GET platform/ip-rules/summary` → `{blocked_now, auto_24h, allowed, refused_requests, permanent, my_ip, auto_enabled}`
- `GET platform/ip-rules/check?ip=` → `{status: block|allow|open, rule, strikes, details, auto_blockable}`
- `POST platform/ip-rules` `{ip, action: block|allow, duration: 1h|24h|7d|30d|permanent|custom, expires_at? (custom), reason}`: only these fields (422 `unexpected_fields`); 422 for invalid IP, range wider than /16 (IPv6 /32), localhost, or your own IP; 409 when blocking an allow-listed IP; the same IP again → the rule is updated
- `POST platform/ip-rules/{id}/remove` `{reason?}`: unblock / remove from the allow list (kept as history; 409 if already removed)
- `GET|PUT platform/ip-rules/settings` `{auto, strikes (5–10000), window_minutes, minutes, permanent_after (0 = never)}`

## Live tracking devices — 18 Nov (`dispatch.manage_trackers`)
| Method | Path | Notes |
|---|---|---|
| GET / POST | `/trucks/{id}/trackers` | list · create `{kind: screen|gps, name, code?}` → code + setup shown once (`code` from setup-preview, must be unused) |
| GET | `/trackers/setup-preview` | a fresh code + screen link / GPS server URL to show before the truck exists (nothing stored); send it as `code` when creating the device |
| PUT | `/trackers/{id}` | `{kind, name}` rename / change type (same code works for both) |
| POST | `/trackers/{id}/use` | this device is the one in use for its truck (only its positions move the truck; others are backups) |
| POST | `/trackers/{id}/new-code` | fresh code + setup info; the old code stops working |
| DELETE | `/trackers/{id}` | remove the device |

**Driver's phone (FleetTruck360 app) — 19 Nov:** `POST /portal/position` (drivers only, throttle 12/min per user)
`{positions: [{lat, lng, speed (m/s)?, heading?, accuracy (m)?, timestamp (ms)?}]}` (1–100, queued while offline) →
`{saved, tracking, interval_seconds (30 on a trip, 300 otherwise), trip_no?, truck_no?}`. Saved only while the driver has a trip on the road
(draft / rejected, last 7 days, main or co-driver) for that trip's truck; a cab screen / GPS device in use that reported in the last 10 min wins.
Position source `driver_app`. `GET /dispatch/live`: each trip now includes `truck_id` + `truck_no` (were hidden by a comment — fixed);
`counts.tracked` = trucks with a device **or** a position.

## Global search — 18 Nov
`GET /search?q=` groups (only what the user may see): trips (also by shipper / consignee name), trip_templates, trucks, trailers, truck_documents, maintenance, employees, driver_files, driver_applications, parties, filings, settlements, users, invoices, tickets, help. Type names match ("insurance", "UCR"). The dashboard adds a client-side "Features" group (`layout/searchShortcuts.js`).

## Export everywhere — 18 Nov
Every list endpoint takes `?export=xlsx|csv|pdf|docx` with the same filters as the list (all pages, max 5000 rows); unknown format → 422. Company users need plan module `excel_pdf_export`; platform users don't. New on: `/billing/invoices`, `/maintenance-history`, `/tickets`, `/audit-logs`, `/recycle-bin`, `/referrals`, `/wallet/transactions`, `/platform/ip-rules`, `/platform/referrals`, `/platform/wallets`, `/platform/audit-logs`, `/platform/users`, `/platform/contact-messages`, `/platform/canned-replies`, `/platform/recycle-bin`, `/platform/ifta-rates?quarter=`. Never exported: password hashes, tokens, secrets, tracker codes.

## Company documents + contacts — 18 Nov
| Method | Path | Perm | Notes |
|---|---|---|---|
| GET / POST | `/company-documents` | company_documents.view / create | `{name, category?, expires_on?, notes?, new_files[]}` multipart; filters `status[]=expired|expiring|ok|none`, `category`; export |
| GET / PUT / DELETE | `/company-documents/{id}` | company_documents.* | PUT also `remove_files[]` (file ids). Output `files[]: {id, name, mime, size, url, download_url}` (signed, 30 min) |
| GET | `/company-documents/categories` | company_documents.view | standard list + categories already used |
| GET / POST / PUT / DELETE | `/contacts`, `/contacts/{id}` | contacts.view (drivers too) / create / update / delete | `{name, phone?, email?, notes?}` |

## Fuel stops — 19 Nov
| Method | Path | Perm | Notes |
|---|---|---|---|
| GET / POST / PUT / DELETE | `/fuel-stops`, `/fuel-stops/{id}` | fuel_stops.* (create also with trips.create / create_any) | `{name, address?, city?, state? (US or Canada code), zip?, phone?, notes?}`; filter `state`; export |
| — | `POST/PUT /trips` | trips.* | optional `fuel_stops: [{id? (keep row + its receipts), fuel_stop_id, purchased_on?, fuel_type? (diesel·biodiesel·gasoline·propane·cng·lng·reefer), invoice_no?, odometer?, gallons?, cost?}]` (rows without id are new, missing ones removed). Output `fuel_stops[]` with name, city, state, purchased_on, fuel_type, invoice_no, odometer, gallons, cost, price_per_gallon, `receipts[]`; `fuel_stops_gallons`, `fuel_stops_cost`. Not added to TOTAL; **non-reefer gallons replace the state gallons** (per fuel-stop state) |

## Trip form helpers — 19 Nov
| Method | Path | Notes |
|---|---|---|
| GET | `/trips/lane?from_city=&from_state=&to_city=&to_state=&exclude=` | "Same as last time": latest non-draft trip on that lane with state miles → `{trip_id, trip_no, trip_date, trips_on_lane, total_miles, states[{jurisdiction_id, code, name, miles, route}]}` or `data: null`. trips.create/create_any/update/update_any; drivers see only their own trips |
| POST/PUT | `/trips` | `stops[]` without a known `party_id` → matched by name (+city) in Shippers & Consignees or **added** to it (plan feature parties); party ids of another company are ignored |
| GET | `/app/bootstrap` | `lookups.cities[{city, state, uses}]` (company's cities, most used first); `lookups.parties` up to 1000 |

## IFTA record keeping — 19 Nov
| Method | Path | Notes |
|---|---|---|
| POST/PUT | `/trips` | + `end_date?` (≥ trip_date), `empty_miles?`, `state_mileages[].route?` (≤150), `state_mileages[].odometer_in?`. Warnings `crosses_quarter`, `odometer_gap` |
| POST | `/trips/{id}/attachments` | + `trip_fuel_stop_id?` (must be a fuel stop of this trip) → receipt photo of that fuel stop |
| POST/PUT | `/trucks` | + `ifta_qualified` (bool, default true), `ifta_decal_no?`, `fleet_no?` |
| PUT | `/company/profile` | + `ifta_account_no?`, `ifta_base_state?` |
| GET | `/reports/ifta-return` | `quarter` (2026Q4, required), `format` pdf\|xlsx, `receipts` none\|pdf\|zip, + truck_id / driver_id / status. File download: IFTA return layout + schedules (miles by truck, fuel purchases, trips); `receipts=pdf` one PDF with every fuel receipt page; `receipts=zip` PDF + Excel + receipts/ folder. Perms reports.ifta + reports.export; plan reports_advanced + excel_pdf_export |
| GET | `/reports/state-mileage` | `meta.quarter_years[]`, `meta.ifta.receipts`, `meta.ifta.fuel_stops`; only `ifta_qualified` trucks; whole numbers for one quarter; summary `loaded_miles`, `empty_miles`; `meta.ifta.account_no / base_state`; `meta.notices[]: {level: info\|warn, text}` |


## Mobile app logs + security sweep — 19 Nov
| Method | Path | Notes |
|---|---|---|
| POST | `/app/logs` | Public (a crash on the login screen too); the Bearer token, when sent, adds the user. Throttle 20/min per IP. `{app?: {version, build, platform android\|ios, os, device}, logs: [{level error\|warning, kind crash\|error\|api, message ≤1000, error_type?, stack? ≤10000, screen?, method?, path?, status?, at (ms)?, count?}]}` (1–20). Signed out: at most 3 entries, stack ≤2000. Written to `storage/logs/mobile-YYYY-MM-DD.log` (one line per entry; tokens / passwords removed); daily cap `tms.logs.mobile_max_mb` (50). |
| GET | `/platform/logs?channel=mobile` (also `/{date}`, `/entry`, `/{date}/download`) | Application Logs → **Mobile app**: same viewer; type = crash / error / api, exception = Dart error class, source = android / ios, location = app screen. Platform dashboard: `mobile_errors` list widget (last 24 h) for `platform.logs.view`. |

Security fixes (review 19 Nov, tests `tests/Feature/Security/*`): platform staff cannot create / edit / see Super Admins or give permissions they don't hold (incl. to themselves);
the Owner role only from the owner; signatures must be real PNG / JPEG / WebP; private files: only images + PDF inline, everything with `nosniff` and a sandbox CSP;
Recycle Bin hides deleted logins with more access; `users.employee_id` must be a free employee of the company; after a transfer the old owner becomes Manager;
pay sort only with `drivers.view_pay`; tracking also limited per IP; bad device times no longer 500; signup checks the captcha before the email;
ticket replies / rate / close need ticket rights; access checked before validation on trips/{id}/reject, recycle-bin/bulk, reports/ifta-return; `dashboard/driver` only for drivers.
`RouteAuthorizationTest` checks every route on every run (public list, 401 without token, no-permission user 403/404, platform area, company scope of every table).

### Reports — 1-year limit (20 Nov)
Every `GET /reports/*` covers at most 1 year: `date_preset` values are always allowed; a custom `date_from`/`date_to` range longer than 1 year → **422** `errors.date_to` ("The period can be at most 1 year (…). Pick a shorter range — older years can be opened one year at a time."); `date_to` before `date_from` → 422; no dates → the last 12 months; only one date → the other side makes 1 year. The resolved range is in `meta.period`.

