# FleetTruck: project memory and handover

> Last updated: **Monday 16 Nov 2026**.
> This file records what has been built, the decisions behind it, where things live, and what is open.
> The full specification lives in [SOFTWARE_DETAILS.md](SOFTWARE_DETAILS.md), the API contract in [API_SPEC.md](API_SPEC.md),
> and the design system in [DESIGN_GUIDE.md](DESIGN_GUIDE.md). This file does not repeat them.

---

## 1. What the product is

**FleetTruck** is a multi-company SaaS for US trucking companies. The demo company is **RanaBros, Fort Worth TX**.

- **Digital driver trip sheets.** They follow the paper sheet: same sections, same order, same totals rule.
- **State-wise fuel and mileage** (IFTA data), **expenses with receipt photos**, and **road repairs and breakdowns**.
- **Weekly driver settlements**: pay per mile, percentage or flat; advances and Com Checks deducted; driver-paid items reimbursed.
- **Fleet, drivers, shippers and consignees**, with document expiry alerts.
- **Reports**, an **owner dashboard**, **roles and permissions**, an **audit log**, **announcements**, **support tickets** and a **help center**.
- **Super Admin**:
  - companies;
  - standard and custom plans, with a 14-day trial;
  - billing by cash or bank transfer, with proof-of-payment review;
  - demo requests;
  - a **Test Cases** dashboard.
- **Mobile first.** Drivers use the app on the phone as an installable PWA.

## 2. Apps, ports and how to run

| App | Folder | Tech | Dev URL |
|---|---|---|---|
| API (serves every client) | `backend/` | Laravel 12, Sanctum (per-device tokens), Spatie Permission (teams = company), MariaDB 10.4 | http://127.0.0.1:8010/api/v1 |
| Dashboard (company, driver PWA, Super Admin) | `frontend/` | React 18, Vite 5, Bootstrap 5, Chart.js, Vitest | http://127.0.0.1:5174 |
| Marketing website (SEO, static) | `website/` | Astro 4, sitemap, inline SVG icons, almost no JS | http://127.0.0.1:4321 |
| Docs and mockups | `doc/` | Markdown and HTML | — |

```bash
scripts/dev.sh start     # private DB (port 3307), API 8010, queue, scheduler, dashboard 5174, website 4321
# dashboard moved 5173 → 5174 on 18 Nov: another project on this computer ("LabCore") uses 5173
scripts/dev.sh status
scripts/dev.sh reset     # rebuild the database with demo data
scripts/dev.sh stop
```

- **Database.** The system MySQL's root account uses socket login, so the project runs its own MariaDB from the XAMPP binaries:
  - port **3307**, data in `~/.local/share/fleet-tms/`;
  - `backend/.env` sets `DB_CONNECTION=mariadb` and `DB_PORT=3307`.
- **Databases:**
  - `fleet_tms`: live demo data;
  - `fleet_tms_test`: default test database;
  - `fleet_tms_test_unit`: unit tests;
  - `fleet_tms_test_qa`: QA runner only (it refuses to run against the app database).
- **Captcha.** Cloudflare Turnstile with test keys:
  - site key `1x00000000000000000000AA`;
  - test token `XXXX.DUMMY.TOKEN.XXXX`.
  - Set real keys in `backend/.env`, `frontend/.env` and `website/.env` before going live.

### Demo accounts
| Role | Email | Password |
|---|---|---|
| Super Admin | `admin@fleettms.test` | `Admin@12345` |
| Owner (RanaBros) | `owner@ranabros.test` | `Password@123` |
| Manager / Dispatcher / Accountant | `manager@` · `dispatcher@` · `accountant@ranabros.test` | `Password@123` |
| Driver (John Smith) | `driver@ranabros.test` | `Password@123` |
| Other companies | `owner@<companyname>.test` (e.g. `owner@starhaulllc.test`) | `Password@123` |

RanaBros is on the **Professional** plan. The State Mileage (IFTA) report needs **Business**.

## 3. Code conventions (where to look)

### Backend
- **Tenancy:** `company_id` with the `BelongsToCompany` global scope and the `Tenant` class. Platform context uses team `0`.
- **CRUD:** `CrudController` plus the `Route::crud` macro. Route files in `routes/{public,api,platform}/*.php` are loaded automatically.
- **Registries** (one file per module): `app/Support/{Permissions,Dashboard,DriverDashboard,Lookups,Provisioning,Usage}/*.php`.
- **Errors** follow the shape `{message, code, errors}` (`ApiException`).
- **Support classes:** `Plan` (features, limits, read-only), `Settings`, `PlatformSettings`, `Notifier`, `Files` (signed URLs), `Numbering`, `DateRange` presets.

### Frontend
- Modules are discovered automatically from `src/modules/*/index.jsx`.
- Shared pieces: `ResourcePage`, `DataTable`, `useUrlFilters`, `FilterSelect`, `DateRangeMenu`.
- Dashboard widgets come from the backend registries and go through `normalizeWidget`.

### Website
- Content is in `src/data/content.ts`, the Solutions menu in `src/data/solutions.ts`, and site settings in `src/config/site.ts`.

## 4. Trip sheet rules (current)

The full logic is in SOFTWARE_DETAILS §7.

### Sections
1. Driver and truck
2. Shipment (several shippers and consignees)
3. State-wise fuel and mileage
4. Truck expenses: 11 paper lines plus custom lines
5. **Repairs and breakdown**: new, optional
6. Trip and mileage (odometer)
7. Driver's signature

Revenue and driver pay are visible only with `trips.view_revenue`.

### Totals
- **TOTAL** = all expense lines (including Com Check and Advance) **+ REPAIRS**.
- **Cost per mile** = TOTAL ÷ total miles.
- **Net profit** = load rate − TOTAL − driver pay.
- **Mileage warning:** shown when state miles differ from odometer miles by more than the variance setting (default 2%).

### Workflow and phone form
- Draft → Submitted → Approved / Rejected → Settled.
- On the phone the form is a **7-step wizard**: Trip Info · Shipment · Fuel & Miles · Expenses · **Repairs** · Odometer & Route · Review & Sign.
- On desktop it is one page laid out like the paper sheet, with a live summary.
- Drafts autosave to the phone and work offline.

### Repairs (added 14 Nov)
- **Each repair records:**
  - date, city and state, odometer and downtime hours;
  - what went wrong and what was done;
  - the shop (name, phone, address) and the mechanic (name, phone), each with a tap-to-call button;
  - parts, each marked replaced / new / repaired / adjusted, with quantity × unit cost;
  - labor, who paid, invoice number and notes.
- **Totals:** parts cost = Σ quantity × unit cost (quantity defaults to 1); repair total = parts + labor.
- **Database:**
  - tables `trip_repairs` and `trip_repair_parts`;
  - column `trips.repairs_total`;
  - migration `2026_01_05_000020_create_trip_repairs_tables.php`.
- **API:**
  - optional `repairs[]` in the trip payload;
  - sending `repairs` replaces them, `[]` removes them, and leaving it out keeps them;
  - empty repair cards and parts without a name are skipped.
- **Settlements:** repairs paid in **cash or Com Check** are reimbursed automatically, with the description "Road repair · TRP-… · shop".
- **Where it shows:**
  - the form (desktop section 5 and phone step 5);
  - the trip detail **Repairs** tab (link: `/trips/{id}?tab=repairs`);
  - a REPAIRS line on the paper sheet and PDF, plus a repair details table in the PDF.
- **Duplicating a trip does not copy its repairs.**
- **Demo data:**
  - `TripSeeder::demoRepair()` adds repairs to every 9th seeded trip;
  - two live demo trips have repairs, TRP-2026-00032 and TRP-2026-00044.

**Code:**

| Part | Files |
|---|---|
| Totals | `TripCalculator`, `TripService::repairTotals()` / `syncRepairs()` |
| API output | `TripResource`, `TripController`, `TripPdfController` |
| PDF | `trips/sheet.blade.php` |
| Settlements | `SettlementService` |
| Frontend | `RepairsEditor.jsx`, `RepairsView.jsx`, `tripUtils.js`, `useTripForm.js` |

## 5. Website (Astro): design decisions

| Area | Current state |
|---|---|
| Theme colour | `--tms-gradient` is **dark navy** (`#1B2D55 → #111B33 → #0A1428`), the same as the home banner. Light page sections and white cards are unchanged. |
| Buttons | Solid buttons and selected states use `--tms-btn` `#111B33` (hover `#1E3160`), not blue. Text links stay blue. |
| Home banner | Dark navy with an animated **dotted world map** (`public/hero-map.svg`): faint dots, thin dashed truck routes, pulsing hubs, moving trucks. |
| Inner page banners, CTA band | Dark navy gradient; inner banners also show the map. |
| Hero phone mockup | Shows the app's **real 7-step wizard** with a navy app bar, progress segments, Back/Next buttons and the real tab bar. One loop is 16 s, synced with the laptop, chips and data packet. |
| Header | **Solutions** mega menu (5 groups of modules the owner already has). Top menu hover and current page are navy (current page is a solid navy pill). |
| Footer | Dark `#0B1020`. Logo, tagline and contacts, then the columns **Platform · Solutions · Company · Legal**, then the © row with Log in / Start free trial. |
| Chat (assistant + WhatsApp) | `components/ChatAssistant.astro` on every page (one button, bottom right, above the phone tab bar). The **website assistant** answers first, instantly and **without any AI service**; "Talk to a person on WhatsApp" (header button, footer link, and offered when there is no answer) opens wa.me with the visitor's question typed in. Answers + matcher download only when the chat opens (or the button is hovered); the build makes `/assistant.json` as a fallback if the API is down. Number: `PUBLIC_WHATSAPP_NUMBER`. |
| Features page | Every feature with a screenshot **plays a flow of 3–5 real app screens** (`components/ScreenFlow.astro`, list in `FLOWS` at the top of `pages/features.astro`): IFTA, expenses, settlements, fleet, dashboard & reports, team, and the phone mockup for "Made for the phone". Trip sheets keep the animated `TripSheetFlow`. **Fast page:** only the first screen of each flow is in the page (lazy); the others have `data-src` and download only when the section is ≥25% on screen (next screen just before it slides); a flow plays only when ≥60% visible, pauses on hover, no autoplay with Data Saver / reduced motion. `srcset` serves `<key>-<n>-1x.webp` (1280 / 390 px) on normal screens and `<key>-<n>.webp` (2×) on retina. Measured on the production build: page load = 2 screens / 109 KB on desktop, 0 on phones. `npm test` checks one eager screen per flow, alt text and that every file exists. |
| Paper → Digital (home) | The app phone plays the trip flow on a loop (lines typed in → totals count up → Signed / receipts → Submitted → Approved → Pay chip) with a 4-step tracker under it. Runs only while visible; reduced motion / no JS shows the finished sheet. |
| Register `/signup/` | **No site header** (a logo link instead). Dark navy panel with map; logo row + pill; steps beside the animated white trip card with chips; road with a truck; "Included in your trial". Fits one screen at 1440×900. On phones only the form shows. "Questions before you start?" (phone, email) sits under the form. |

**Map file:**
- Built by `website/scripts/build-hero-map.mjs`, a dependency-free script with hand-simplified continent outlines. Run it with `node scripts/build-hero-map.mjs`.
- The `dotted-map` npm package could not be installed (permission denied), which is why the outlines are hand-made.
- A copy is in `frontend/public/hero-map.svg`, used by the app login.

**Retaking the features page screenshots:**
- Capture each app page in headless Chrome at 1280×720 with `--force-device-scale-factor=2`.
- Log in with a `TokenService::createLoginCode` code at `/auth/callback?code=…&next=…`.
- Hide the `.banner-area` banners.
- Save the images as WebP in `website/public/screens/`.
- For the State Mileage shot, switch RanaBros (subscription 1) to Business (plan_id 3) and then **restore Professional (plan_id 2)**.
- Take **only** State Mileage while on Business: the Trucks page shows the plan name ("6 / 15 trucks on Professional").
- Dashboard shot: open `/?date_preset=this_quarter` (This Month shows mostly red arrows in the demo data).
- Flow screens (16 Nov): `/reports/state-mileage` scrolled 560 / 1120, `/reports/expenses` scrolled, `/trips/40` States and Expenses tabs, `/settlements`, `/reports/driver-pay`, `/fleet/trailers`, `/employees`, `/parties`, dashboard scrolled, `/reports`, `/settings/roles` (Driver), `/settings/users`, `/settings/trip-sheet`. Save each as `<key>-<n>.webp` (2560×1440) and `<key>-<n>-1x.webp` (1280×720).
- **18 Nov update (user: "update the website with new features, change photos if changed, video not now"):** home grid now 12 tiles (+ Live Dispatch & GPS, Compliance, Documents & Contacts, Search & Export; Fleet → Fleet & Maintenance); features page has 3 new sections with flows — `dispatch` (live map, Live tracking window), `compliance` (Driver Files, a driver's file, Company Filings, Driver applications), `documents` (Company Documents, Contacts) — and updated points (team drivers, templates / duplicate, IFTA tax, per-driver settlements grouped by trip, maintenance + truck documents, export, global search, + button, tours, push). Removed the old "every US state and Canadian province" claim. Solutions menu, footer, pricing module labels and 2 new FAQs updated (EN + ES). **Screens retaken 18 Nov** with `scratchpad/opt/webshots.cjs` (groups desktop / ifta / mobile; hides banners, tours, tooltips; 1280×720 or 390×712 at 2×): all dashboard / expenses / settlements / fleet (now trucks, maintenance, truck documents, service history) / team / mobile shots + new dispatch-1..2, compliance-1..4, documents-1..2 + ifta-4. **ifta-1..3 were kept from 16 Nov** — the report now shows "IFTA tax due $0.00" and a "no tax rate entered" notice until the Super Admin enters official IFTA rates; retake them after that. Demo data added for the shots: 6 company documents (8 small PDFs) and 6 contacts in RanaBros. mobile-5 now uses trip 40 (positive profit). Videos not changed (user: "video not now"). The website assistant's answers live in the database (Super Admin → Website assistant) and were not changed.
- **19 Nov website update (user: "implement all changes on the website… template, duplicate and other things"):** content.ts EN + ES — home tiles (trip sheets: duplicate / template / same as last time; IFTA: any quarter + return export with receipts; expenses: fuel stops + repairs), trip-sheets points (shipper/consignee search + add, cities + auto state, Load From/Destination from the shipment, "Same as last time?", fuel stop details + receipt, repair photos, templates fill shippers/consignees/states + starting miles carry on, 6 steps with "Anything else?" + review), IFTA points (any quarter, IFTA-return export PDF/Excel/one PDF with receipts/ZIP, IFTA records, fuel stops fill state gallons, qualified trucks + decal/fleet no., record checks), new FAQ "same trips every week" + IFTA FAQ (EN + ES). Solutions menu: "Trip Templates & Duplicate", "Team Drivers", "Fuel Stops & Receipts", "IFTA Return Export with Receipts" (EN + ES). **Screens retaken 19 Nov** (`scratchpad/opt/webshots2.cjs`, 1280×720 / 390×712 at 2×, PIL → WebP 2× + 1×): ifta-1 (year/quarter filter, IFTA return button, record checks), ifta-4 (States tab with highways + odometer entering), **new ifta-5** (Export IFTA return dialog); phone flow now 6: mobile-1 list, **mobile-2 Use Template**, **mobile-3 "Same as last time?"**, **mobile-4 "Anything else?"**, **mobile-5 review with Edit**, mobile-6 approved trip. While shooting, fixed the Use Template row on phones (Use button was cut off: `.tpl-list` grid column `minmax(0, 1fr)` + text column `min-width: 0`). Videos not changed.
- All 7 features page shots were retaken on 16 Nov with the new UI (sidebar with search, top search, compact dashboard banner, contained page banners, standard tabs, coloured action buttons).

## 6. Dashboard app: recent UI decisions

- **Login screen** (`AuthLayout.jsx` and the end of `app.css`):
  - dark navy panel with the map; content column centred (max 760px);
  - navy Sign in button and links;
  - phones show only the form, with a small logo link;
  - "Questions before you start?" sits under the form, using `VITE_SUPPORT_PHONE` and `VITE_SUPPORT_EMAIL` from `frontend/.env`.
- **Inside the app** the bright blue theme is unchanged. Only the website and the login screen were switched to navy.
- **Earlier UI work:**
  - dashboard cleanup and filter overlap fix;
  - segmented tabs and inline row action buttons;
  - fixed button hover colours;
  - plan pages restyled;
  - custom date range filter;
  - Super Admin Demo Requests and Test Cases pages.

### Dynamic sidebar menu (added 16 Nov)
- **Database-driven:** the sidebar comes from the tables `menu_sections` and `menu_items`. It is seeded from `App\Support\Menu\DefaultMenu`: 8 sections and 48 links across the company, driver and platform areas.
- **Delivery:** `GET /app/bootstrap` returns `menu` for the user's area. The app still applies permission and plan checks (`frontend/src/layout/menu.js`). If the server sends no menu, the app falls back to the modules' built-in `menu` lists.
- **Super Admin → System → Menu Manager** (`/platform/menu`, permission `platform.menu.manage`):
  - rename a link, change its icon, change its page, move it up or down or to another section, show or hide it;
  - add custom links, and delete them (built-in links can only be hidden);
  - rename, reorder or hide sections;
  - "Reset to defaults" (custom links are kept);
  - a live preview per area.
- **Sidebar:**
  - **search box**: filters links by name or section; Enter opens the first match, Esc clears;
  - **collapse button**: icons only with tooltips, remembered per device;
  - **section headings** fold and unfold, remembered per device.
- **Phone "More" page:** a menu search box.
- **Code:**
  - backend: `MenuService`, `DefaultMenu`, `Platform/MenuController`, `routes/platform/menu.php`, migration `2026_01_11_000001_create_menu_tables.php`;
  - frontend: `layout/Sidebar.jsx`, `layout/menu.js`, `modules/menus/`.
- **New permission or seed changes:** after adding a permission or changing `DefaultMenu`, run the `RoleSync` `syncPermissions()` and `MenuService::syncDefaults()` (`PlatformSeeder` does both).

### Database backups (added 16 Nov)
- **Page:** Super Admin → System → **Database Backups** (`/platform/backups`).
- **What a backup is:** a full gzip `mysqldump` (single transaction, with routines and triggers), stored in `backend/storage/app/private/backups/`. That folder is not reachable from the web.
- **The list survives restores:** the `db_backups` table itself is never dumped, so restoring an old backup keeps the list of backups.
- **On the page:**
  - Back up now;
  - Download;
  - Delete;
  - **Restore**: type `RESTORE` to confirm. A `pre_restore` safety backup is made first, then the file is loaded with `mysql`, then `migrate --force` runs and caches are cleared.
- **Automatic backups:**
  - settings `backup.auto_enabled`, `backup.frequency` (daily or weekly), `backup.time` (server time, UTC), and `backup.keep` (newest N automatic backups kept);
  - the scheduler runs `tms:backup --if-due` every 5 minutes, and the command decides whether a backup is due;
  - `php artisan tms:backup` makes a manual backup from the command line.
- **Tools:** `BACKUP_MYSQLDUMP` and `BACKUP_MYSQL` in `backend/.env` point to `/opt/lampp/bin/mysqldump` and `/opt/lampp/bin/mysql`.
- **Permissions:** `platform.backups.{view,create,download,delete,restore,settings}`. Platform Staff can only view.
- **Not included:** uploaded files (logos, receipts, signatures) are not part of database backups.
- **Code:**
  - backend: `Services/Platform/BackupService`, `Platform/BackupController`, `Console/Commands/BackupDatabase`, `routes/platform/backups.php`, migration `2026_01_12_000001_create_db_backups_table.php`;
  - frontend: `modules/backups/`.

### Application logs (added 16 Nov)
- **Page:** Super Admin → System → **Application Logs** (`/platform/logs`), modelled on the user's reference screenshot.
- **What it reads:** `storage/logs/laravel.log`, and `laravel-YYYY-MM-DD.log` if logging is switched to daily.
- **Left side:** days by month, each with entry count, size and per-level counts.
- **Right side:** the day's entries, newest first:
  - level chips;
  - search, which also looks inside stack traces;
  - Download (the raw lines of that day);
  - filters: Type (exception, database, HTTP, queue, message), HTTP status, Exception, Source (`app/`, `vendor/`…), and a time range;
  - each row opens to show the full message, the exception and code, file and line, context (request_id, userId…), and the stack trace with app frames highlighted.
- **How it works:** `Services/Platform/LogReader` caches its parsed summary per file until the file changes. Bump `PARSER_VERSION` whenever `parse()` changes. Full details are read on demand from each entry's byte offset.
- **Permissions:** `platform.logs.view` and `platform.logs.download`.
- **Log noise fixed at the same time:**
  - test runs no longer write to `laravel.log` (`phpunit.xml` uses `LOG_CHANNEL=null`). 513 of 723 entries were from tests;
  - `ApiException`s with a 4xx status are no longer logged as errors (`bootstrap/app.php`, `dontReportWhen`). They are normal business answers;
  - the Super Admin's notification bell kept calling `/notifications/unread-count`, which was company-only, so every call failed and was logged. The 4 personal notification routes now serve every user type (`routes/api.php`), and the announcements banner no longer calls the company feed for the Super Admin.

### Action button colours (added 16 Nov)
- **Row actions in every `ResourcePage` table**, and their "⋯" menus, are coloured by meaning. `components/actionTone.js` works out the colour from the action's label or icon; an action can override it with `tone`:
  - delete / suspend / disable / reject: **red**
  - edit / schedule: **blue**
  - open / view: **grey**
  - approve / activate / enable / mark done: **green**
  - download / print / PDF: **teal**
  - duplicate / copy: **violet**
  - reset password / restore / reopen / login as: **amber**
  - email / reply / send: **indigo**
- **Look:** a tinted button with a coloured icon, filling solid on hover; lighter shades in dark mode.
- **Hand-built small buttons** (`.btn-sm.btn-ghost`, such as in Menu Manager, Backups and Logs) get the same colours from their icon through CSS `:has()` rules at the end of `styles/app.css`.

### Global search (added 16 Nov)
- **Where:** the top bar, on every page (`layout/GlobalSearch.jsx`). Phones get a 🔍 button in the header that opens a full-screen search.
- **Results:**
  - **Pages:** sidebar links matching what you type (from the database menu, instant).
  - **Records:** `GET /search?q=` for company users and drivers, `/platform/search?q=` for the Super Admin. Backend in `Api/Core/GlobalSearchController`, 5 results per group, grouped with "See all" (the list filtered by `?q=`).
  - Only what the user may see: permissions and plan modules apply, and drivers see only their own trips, pay and tickets.
- **Keyboard:** Ctrl/⌘+K or `/` from anywhere; ↑ ↓ to move, Enter to open, Esc to close. The last 6 searches are remembered on the device.

### Blog posts + website SEO (added 16 Nov)
- **Super Admin → Communication → Blog Posts** (`/platform/posts`):
  - list with state (draft, scheduled, published), category, date and views;
  - **editor** with title, auto address (slug) and summary;
  - body with a formatting toolbar and preview (plain text or HTML; the server cleans it and keeps images and tables);
  - cover image with alt text, category and tags;
  - publish now or schedule, featured, noindex;
  - **SEO panel** with a Google preview, focus keyword, SEO title and description counters, and an SEO score checklist.
- **Backend:**
  - `posts` table, `Post` model, `Services/Platform/PostService`, `Platform/PostController` (CRUD) and `Public/PostController` (live posts only);
  - permissions `platform.posts.*` (Platform Staff can view, create and update);
  - starter articles from `PostSeeder` (5 SEO articles).
- **Website:**
  - `/blog/`: category filter, featured post, grid; `Blog` structured data;
  - `/blog/<slug>/`: `BlogPosting` and breadcrumb structured data, article Open Graph tags, a contents panel, share buttons, related posts and a view beacon;
  - `/rss.xml`;
  - a "From the blog" section on the home page, and Blog in the menu and footer;
  - posts are read from the API **at build time**, so new posts appear after the next website build. Set `TMS_WEBSITE_DEPLOY_HOOK` (backend `.env`) to the hosting build hook to rebuild automatically on publish. The dev server always shows them live.
- **SEO across the website** (`layouts/Base.astro`):
  - meta keywords (site keywords in `config/site.ts` plus each page's own);
  - author and application name;
  - canonical and `hreflang` en-US / x-default, the RSS link;
  - robots, googlebot and bingbot with max-image-preview and max-snippet;
  - full Open Graph and Twitter tags, including image alt, article times, section and tags;
  - Organization and WebSite structured data;
  - keyword-rich titles on every page.

### Website assistant (no AI) — added 16 Nov

- **Super Admin → Website Assistant** (`/platform/assistant`, permission `platform.assistant.*`, menu item in Communication). Tabs:
  - **Answers**: question, *other ways people ask* (one per line), keywords, category, answer, button link, quick-question flag, active, order. Shows times shown and 👍 / 👎.
  - **Unanswered**: visitor questions with no good answer, grouped (`times`). **Answer it** creates an answer and links them; **Ignore** / **Reopen**.
  - **Try it**: type a question and see the exact reply, match score and how it was understood.
- **Data**: tables `assistant_answers`, `assistant_questions`. Starter set: 104 answers in `backend/database/seeders/data/assistant.json` (`AssistantSeeder` only adds missing questions, never overwrites edits).
- **Placeholders** filled live by the API: `{app} {trial_days} {plans} {support_email} {support_phone} {app_url}` (e.g. links like `{app_url}/fleet`).
- **API**: `GET public/assistant` (compact knowledge base, cached 5 min) · `POST public/assistant/ask` (logs hits / unanswered) · `POST public/assistant/{id}/feedback` (both throttled `assistant`, 30/min per IP) · Super Admin `platform/assistant/answers|questions` (CRUD) and `platform/assistant/knowledge`.
- **Matcher**: `website/src/scripts/assistant-match.js` (exact copy in `frontend/src/modules/assistant/assistantMatch.js`, a test checks they are identical). Phrases → tokens, light stemming, synonyms, typo tolerance only for unknown words (swap = 1 typo), IDF weights, exact phrasing wins (partial matches are capped at 0.98).
- **Never a wrong answer (user requirement, 16 Nov):** answers directly only when **sure** = score ≥ 0.90 **and** ≥ 0.05 ahead of the next answer, or typed exactly as a stored question. Otherwise: *"I want to be sure I give you the right answer. Which one did you mean?"* with the closest questions as buttons + *None of these: ask a person* (WhatsApp).
- **Off-topic** (no trucking / FleetTruck word, or an unrelated word with only weak matches): a friendly reply that names their topic (*Sorry, I can't help with "pizza" 🙂 …*), 4 rotating wordings (never the same twice in a row), popular questions and *Ask on WhatsApp*. Logged as **Ignored**.
- **Learning loop:** a visitor's pick from "Did you mean…" is saved (status answered, linked answer). Super Admin → Unanswered → **Add as a way to ask** adds their wording to that answer → answered directly next time (`POST platform/assistant/questions/{id}/learn`).
- **Measured** (`website/tests/assistant-eval.json`, 304 questions, enforced by `npm test`): **0 wrong direct answers in every set**; answered directly 56–80%; right answer offered in the "Did you mean" list for the rest (right answer reachable 95.7–100%); fresh set written after tuning (holdout3, 50 questions): 0 wrong, 58% direct, 42% via one tap, 0 missed; off-topic recognised 20 of 23, none ever answered.

### Billing cycles: Monthly · Quarterly · Half-yearly · Yearly — added 16 Nov

- **Backend:** `App\Support\BillingCycle` is the one place for each cycle's months, label and price (`price()`, `end()` = addMonthsNoOverflow, `monthly()` for MRR, `prices()` for cards, `suggested()`). Plans have `price_quarterly` / `price_half_yearly` (nullable → monthly × 3 / × 6). `company_subscriptions.cycle` and `subscription_invoices.cycle` accept `quarterly`, `half_yearly`. Used by subscribe, invoices, payment approval (renewal extends the running period), CompanyProvisioner, Super Admin company forms, MRR.
- **Prices** filled for existing plans: quarterly −5 %, half-yearly −10 % (yearly already −15 %): Starter 29 / 83 / 157 / 296 · Professional 59 / 168 / 319 / 602 · Business 99 / 282 / 535 / 1010 · RanaBros Special 69 / 197 / 373 / 700.
- **App:** `CycleSwitch`, `priceFor`, `cycleSaving`, `cycleLabel` in `frontend/src/modules/billing/plans.jsx` (Billing page, subscribe dialog, Super Admin Plans + plan editor preview); plan editor has Quarterly + Half-yearly price fields and "Fill from monthly with discounts 5 / 10 / 15 %"; cycle labels everywhere (no raw `half_yearly`).
- **Website:** pricing toggle with 4 cycles (best saving per cycle, 2 × 2 grid on phones); each card shows the per-month price + "$168 billed every 3 months · save 5 %"; `website/src/lib/plans.ts` `CYCLES`, `cyclePrice`, `cyclePerMonth`, `cycleSaving`. Terms + pricing copy updated. Assistant: new answer "Can I pay every 3 or 6 months?".
- Tests: `tests/Feature/Billing/BillingCyclesTest.php`, `frontend/tests/unit/billing/cycles.test.jsx`.

### Export: Word, Excel, CSV everywhere — added 16 Nov

- Every **Export** button (all lists via `ResourcePage`, every report) is one shared menu `frontend/src/components/ExportMenu.jsx`, styled like the user's reference: coloured file icons **Excel (.xlsx)** green · **CSV** dark · **PDF** red · **Word (.docx)** blue (all four on every list and report), a divider, **Print this page**, and the note "Exports every row matching your search and filters, in the current sort order." (CSS `.exp-*` in `app.css`). The trip sheets list's old separate *PDF* button was removed (same file as Export → PDF). PDF (`resources/views/exports/table.blade.php`) matches the Word look: navy header repeated on each page, zebra rows, numbers right-aligned, page numbers; Letter portrait ≤6 columns, landscape 7–11, Legal landscape >11.
- API: `?export=docx|xlsx|csv|pdf` on every CrudController list and `GET reports/{key}?export=…`. Plan module `excel_pdf_export` (label now "Export (Word, Excel, CSV, PDF)") + `*.export` permissions unchanged.
- Word files are real `.docx` built without a library: `app/Support/Exports/DocxTable.php` (PHP zip) — title, company, period / filters, navy header row repeated on each page, zebra rows, numbers right-aligned; column widths from the content (water-filling: short columns never wrap, long text wraps); portrait ≤6 columns, Letter landscape 7–11, **Legal landscape >11**; 8 pt text above 8 columns. Tests: `tests/Feature/Core/ExportFormatsTest.php` (opens the .docx and validates the XML).

### Recycle Bin (both dashboards) — added 16 Nov

- **Pricing fix (16 Nov):** the website mapped API plan modules as-is, so *Driver mobile access, Excel / PDF export, Company announcements* showed "not included" on every plan. `website/src/lib/plans.ts` now maps `driver_mobile → driver_access`, `excel_pdf_export → export`, `company_announcements → announcements`; a website test fails if any module row is never included.

- **Plan module `recycle_bin`** ("Recycle Bin (restore deleted records)", Super Admin → Plans → Modules): on for Professional, Business and custom plans that have the Audit Log; off for Starter (locked menu item → upgrade page; API 403 `feature_locked`). Deletes still go to the bin on Starter, so upgrading shows them. The Super Admin bin is not plan-gated.
- **Where:** company dashboard → Account → **Recycle Bin** (`/recycle-bin`, `recycle_bin.view|restore|delete`; Manager: view + restore; Owner: all) and Super Admin → System → **Recycle Bin** (`/platform/recycle-bin`, `platform.recycle_bin.*`; Platform Staff: view).
- **What shows:** every soft-deleted record the user could delete (module delete permission + plan module):
  - company tabs Trip sheets · Settlements · Fleet (trucks, trailers) · People (employees, departments, designations, user logins) · Shippers · Communication (announcements, own support tickets);
  - platform tabs Companies · Plans & billing (plans, bank accounts) · Content (blog posts, platform announcements) · Users · Support.
- **Filters:** search, type, deleted by, date deleted (+ tab per group with counts). Bulk restore / delete forever.
- **Who deleted:** `deleted_by` on all 15 soft-delete tables (trait `App\Models\Concerns\RecordsDeleter`, cleared on restore).
- **Restore exactly as it was:** codes renamed on delete (`T-101~del7`) get their number back (409 if now used) · plan limits checked (trucks, trailers, drivers, users) · a deleted draft settlement keeps a snapshot (`driver_settlements.deleted_meta`) and gets its trips + lines back if they are still unsettled · an employee brings back the login removed with it, same roles (`users.deleted_meta`) · a login whose employee is in the bin must come back with the employee.
- **Delete forever:** blocked ("restore only", reason shown) while history points to it: trucks/trailers/drivers on trip sheets, shippers on trip stops, users who entered/approved trips, handled settlements or appear in the audit log, plans with subscriptions or invoices, non-draft settlements. Otherwise removes the record, its children (DB cascade) and its files; a company also loses its roles, tokens, sequences, notifications and storage folder. Both actions are written to the audit log (`restored`, `deleted_forever`).
- **Code:** `app/Support/RecycleBin/RecycleBin.php` (types), `app/Services/Core/RecycleBinService.php` (rules), `Api/Core/RecycleBinController` (one controller, route default `area`), `frontend/src/modules/recycle/RecycleBinPage.jsx`. Tests: `tests/Feature/Core/RecycleBinTest.php`.

### Refer & Earn + wallet points — added 16 Nov

- **Off by default.** Super Admin → Billing → **Referrals & Wallets** → Program → *Refer & Earn on/off* (`referral.enabled`). While off: company menu item hidden, `POST referrals/link` → 403 `referrals_off`, signup `ref` ignored.
- **One wallet + one link per company.** The link `/signup/?ref=CODE` is valid for `referral.link_valid_days` (60 = 2 months); then a new one is made.
- **Reward rule:**
  - B signs up with A's link → referral `pending`;
  - B buys a plan within `referral.reward_window_days`, pays, and the Super Admin **approves** the payment;
  - A gets `referral.points` (5000) plus a notification;
  - `reward_on`: first paid plan only (default), or every payment.
- **Fraud flags** (same IP as referrer logins, same company email domain, same phone, referrer not active) → status `review`; the Super Admin approves or rejects.
- **Using points:** only on plan invoices (`new` / `renewal` = buy, renew, upgrade), at most `wallet.max_redeem_pct` (50 %) of the invoice, minimum `wallet.min_redeem_points`, 1000 points = $1 (`wallet.points_per_dollar`), rounded down to whole cents. Never cash, never other charges.
  - On the invoice the company **chooses**: "Keep my points" (default, pay full) or "Use my points".
  - Amount due = total − points discount. The payment must equal the amount due (422 `amount_mismatch`).
- **Ledger:** `wallet_transactions` is append-only.
  - Signed points, `balance_after`, sha256 hash chain (`prev_hash` → `hash`).
  - Unique `idempotency_key` (`reward:{referral}:{invoice}`, `redeem:…`, `adjust:{request_key}`).
  - The model refuses update and delete.
  - Integrity check: Super Admin → Referrals & Wallets → *Check integrity* (`WalletService::verify`).
- **Code:** `app/Services/Billing/{WalletService,ReferralService}.php`, `app/Support/{ReferralSettings,BillingLog,BillingGuard}.php`, `Api/Billing/ReferralController`, `Api/Platform/{ReferralAdminController,BillingLogController}`, `frontend/src/modules/referrals/*`, `frontend/src/modules/billing/PointsPanel.jsx`, `website/src/scripts/referral.ts`.

### Billing safety (request validity + one action at a time) — added 16 Nov

- **Only expected fields:** every money endpoint calls `BillingGuard::strict($request, [allowed])`. Any other key in the query, body or files (e.g. `total`, `points_discount`, `status`, `company_id`) gets **422 `unexpected_fields`** and a `security.unexpected_fields` log line. Validation still runs after this.
  - Covered: subscribe, submit payment, referral link, points apply / remove, Super Admin approve / reject payment, record cash, wallet adjust, referral approve / reject, program settings (nested keys checked too).
- **One billing action per company at a time:** `BillingGuard::lock('company:{id}')` (cache lock in the `database` store, so it works across PHP processes). A second tab, a double click or a parallel script gets **409 `billing_busy`** plus a `security.concurrent_blocked` line. Verified live: lock held from another process → 409; once free → 200.
- **Second wall, inside the DB transaction:** `SELECT … FOR UPDATE` and a re-check of the state.
  - subscribe locks the company row;
  - submit payment locks the invoice (must still be `pending`, amount still equals due);
  - approve / reject lock the payment;
  - points apply locks the wallet and the invoice;
  - referral link / approve / reject lock their row.
- **Refused actions are logged:** any `ApiException` inside a lock → `<area>.refused` (code, status, path).
- **Throttle:** `wallet` limiter 20/min per user on link / apply / remove / adjust.

### Atomic writes — whole system (Laravel atomic lock + one DB transaction) — added 16 Nov

Every POST / PUT / PATCH / DELETE in both dashboards and the public website API goes through middleware `atomic` (`app/Http/Middleware/AtomicWrites.php`, on the public group and the authenticated group in `routes/api.php`).

1. **Laravel atomic lock (`Cache::lock`).** Key = company (or `platform` / visitor IP) + method + resolved path (e.g. `POST api/v1/trips/15/approve`).
   - **Same user, same action** (second tab, double click, script) → **409 `request_in_progress`** at once; nothing runs twice.
   - **Another user of the same company, same action** → waits for the first request (`tms.atomic.wait`, 15 s), then runs on the committed data. If still busy after the wait → **409 `write_busy`**.
   - Different actions, other companies and all reads are never blocked. A crashed request's lock expires after `tms.atomic.ttl` (120 s).
2. **One DB transaction per request.** Error response (4xx / 5xx) or exception → **rollback**: nothing half-saved. Success → commit. Deadlock / lock-wait timeout → **409 `write_conflict`** (nothing saved, safe to retry). Services keep their own `DB::transaction` / `lockForUpdate` (nested = savepoints).
3. **Locks + rate limits use their own connection `locks`** (same database; set in `AppServiceProvider::register`, cache `database` store `connection` / `lock_connection`). So a lock is visible to other requests at once and a rollback can't undo the failed-login counter.
4. **Kept after a rollback** (`App\Support\Atomic::durable`): failed-login history and billing log lines (security / refused).
5. **Not in the transaction (still locked):** `platform.backups.store|restore` (SQL import / dump) and `platform.qa.runs.store` (starts a background process that must see the new row).
6. **Browser side** (`frontend/src/api/client.js`, `dedupeWrites`): while a write is running, the same write (method + URL + body) is not sent again; both callers get the one result. Opt out with `{ allowDuplicate: true }`.
7. **Scheduled jobs:**
   - `tms:billing-daily` changes each company under the same company billing lock, in one transaction (busy → skipped until the next run; the renewal invoice is re-checked under the lock);
   - announcement publishing locks the row (scheduler + "publish now" → sent once);
   - every scheduled command has `withoutOverlapping()`.
- **Tests:**
  - `tests/Feature/Core/AtomicWritesTest.php`: rollback, durable records, second tab 409, other user waits, locks freed after errors, deadlock 409;
  - `frontend/tests/unit/api/dedupeWrites.test.js`.
- **Live check (dev server):** with the lock held by another PHP process → 409; 6 identical "create truck" requests → 1 truck.

### IP Block Management (Super Admin → System → IP Blocking) — added 16 Nov

- **Every request** passes global middleware `BlockIps` first.
  - A blocked IP or range gets **403 `ip_blocked`** ("Access from your network has been blocked until …") and nothing else runs.
  - An allow-listed IP always passes.
  - Cost: one cached rule list (60 s, cleared on every change).
- **Manual (input field):** an IP or range (`203.0.113.7`, `203.0.113.0/24`, `2001:db8::/48`), **Block** or **Always allow**, for 1 h / 24 h / 7 d / 30 d / permanently / until a date, plus a reason.
  - Ranges are normalised (`203.0.113.77/24` → `203.0.113.0/24`).
  - Refused: invalid input, ranges wider than /16 (IPv6 /32), localhost (`IP_BLOCK_PROTECTED`), anything that includes **your own IP**, and blocking an allow-listed IP.
  - Blocking the same IP again updates the rule. Unblocking keeps the row as history (`removed_at`).
- **Automatic.** Each IP collects strikes in a window: too many requests (429) 2 · failed login 3 · extra hacking fields 5 · guest 404/405 1 · attack probes (`/.env`, `/wp-login.php`, `../`, `UNION SELECT`, `etc/passwd`, phpMyAdmin…) 15.
  - Default: 30 strikes in 10 minutes → blocked for 60 minutes. The 2nd automatic block within 30 days lasts 24 h; the 3rd is permanent. All configurable on the page.
  - Only **real public IPs** are blocked automatically, never localhost or private networks.
  - Each block stores what the IP did (strikes by reason, last paths, browser / tool). One alert to Super Admins per 10 minutes.
- **Page:** summary cards, Block / allow form, Check an IP (status + current strikes), Automatic blocking settings, and the rule list (status / rule / added / reason filters, details, Unblock).
  - Permissions `platform.ip_blocks.view` (Platform Staff) and `.manage`. Manual actions and automatic blocks are in the audit log.
- **Behind a load balancer / Cloudflare:** configure trusted proxies so `$request->ip()` is the visitor, not the proxy. A network-level flood (DDoS) must also be stopped in front of the server (firewall / Cloudflare), because PHP still starts for each blocked request.
- **Code:** `app/Services/Platform/IpBlockService.php`, `app/Http/Middleware/BlockIps.php`, `Api/Platform/IpRuleController`, `frontend/src/modules/security/*`.
  - Tests: `tests/Feature/Platform/IpBlockingTest.php`, `frontend/tests/unit/security/ipBlocking.test.jsx`.

### Fixes 16 Nov (from testing Refer & Earn)

- **MariaDB hidden auto-update:** a NOT NULL `timestamp` without a default silently gets `ON UPDATE CURRENT_TIMESTAMP`. `referral_links.expires_at` reset to "now" when someone signed up with the link (the link showed "valid until today"). The same applied to `login_codes.expires_at` and `user_tours.completed_at`.
  - Fixed by migration `2026_01_18_000002` (columns made nullable; link expiry repaired to created + 60 days).
  - `tests/Feature/Core/SchemaSafetyTest.php` fails if any column other than `updated_at` auto-updates. **Always use `->nullable()` for timestamp columns.**
- **Same-IP referral flag** now only compares real public IPs. On localhost everyone is `127.0.0.1`, so every local referral was flagged and held for review.
- **The referrer** now sees "Plan bought — being checked" (status `checking`) instead of "Waiting for their first plan" while a referral is under review. Fraud flags are still hidden.

### Marketing video + social ads — added 16 Nov

- **Video:** "a complete trip sheet in about a minute" (70 s, no sound, captions). It is the real app on a phone (Rana Owner, demo data) in a navy brand stage, with intro and outro cards.
  - Masters: `doc/videos/new-trip-sheet-landscape-1080p.mp4` (1920×1080) and `doc/videos/new-trip-sheet-vertical-1080p.mp4` (1080×1920).
  - Website copies: `website/public/videos/new-trip-sheet-{landscape,vertical}.{mp4,webp}`.
- **Website:** home page section **"See it in action"** (`#video`, after Paper → Digital), component `website/src/components/ProductVideo.astro`.
  - Phones (≤ 767px) get the vertical video; larger screens get landscape. It swaps on rotate / resize.
  - Nothing downloads with the page except a lazy `<picture>` poster. The video is attached about 300px before it scrolls in, autoplays muted at ≥ 50% visible and pauses when scrolled away.
  - No autoplay with Data Saver or reduced motion. A website test guards this.
- **How it was made:** `doc/videos/source/`. `record.cjs` drives headless Chrome at phone size in slow motion (Animation playback 0.5 and screenshots, which give 30 fps). `stage.html` and `compose.cjs` build the 1080p frames and encode with ffmpeg. `cleanup.php` deletes the demo trip the recording submits.
  - Two traps: Chrome changes the page scale during a screenshot, so a tap sent at that moment lands at the wrong place (pause screenshots for input). A `#hash` change does not reload the stage page (use a query param).
- **19 Nov re-recording (user: "also update video"):** the video now follows the 6-step phone wizard — Trip info · Shipment (search + pick Lone Star Foods / Desert Retail DC #21) · **Miles & States** (Load From / Destination filled from the shipment, Ending Miles typed, **"Same as last time?" → Use these**) · Expenses · **Anything else?** (skipped) · Review & sign → Submit. `record.cjs`: app port **5174** (was 5173), truck **T-104** + trailer TR-22 (John Smith's usual truck). `compose.cjs` captions "Step x of 6" with keys list/start/info/shipment/miles/expenses/extras/review/sign/submit/done; `stage.html` STEPS = 6. Demo data: **T-104 current_odometer set to 360,873** (= its last trip's Ending Miles) so the review shows no odometer warnings — every demo truck's odometer was ~52,000 mi above its trips (seed inconsistency; others not changed). `cleanup.php` deletes the submitted demo trip (run with TRIP_ID / LOAD_NO=460215).
- **Video player line (user, 19 Nov):** the progress line is no longer baked into the video (`stage.html` `#bar` display:none); `ProductVideo.astro` draws the same blue→amber line along the bottom edge and it is the seek bar — click / drag (mouse + touch), ← → 5 s, Home / End; thicker with a handle + time on hover / drag; redrawn every animation frame while playing (smooth). New masters 19 Nov (65 s): `doc/videos/new-trip-sheet-{landscape,vertical}-1080p.mp4`; website copies re-encoded (landscape 1920×1080 crf 32 ≈ 2.7 MB, vertical 720×1280 crf 31 ≈ 1.4 MB) + posters from 6 s. Caption "About a minute". **Paper → Digital** section (`PaperDigital.astro`): new red point "same route… every week", green points template / receipt on fuel stops / IFTA return with receipts, and the phone animation starts with a "From template · Dallas → Phoenix" tag (EN + ES).
- **Social ads:** `doc/marketing/social/` (20 PNGs). Three messages (paperless / profit / paper-to-app) in feed square, feed portrait, story/reel, link ad and X post sizes, plus a YouTube thumbnail and Facebook / X / LinkedIn / YouTube covers.
  - Template `doc/marketing/source/ad.html`; see `doc/marketing/README.md` (sizes, safe zones, how to re-render).
  - Truck photos are from Unsplash (free licence, credits in the README). A photo of the company's own trucks would be better.
- **Found while recording (not changed):** the Driver role has no `trips.create` by default (owner grants it per driver). But the driver phone app still shows the orange **+** (new trip), which opens "You don't have access".

### Fleet maintenance, truck documents, fleet alerts and phone push — added 17 Nov

- **Maintenance** (Fleet → Maintenance, `/fleet/maintenance`, permissions `maintenance.view/create/update/delete`):
  - **Service schedules** (`maintenance_items`): one per truck and service, every N miles and/or N days, whichever comes first. Types: oil change, PM, annual DOT inspection, tires, brakes, other. Empty intervals in the form take the usual ones (`TYPE_DEFAULTS`: oil 15,000 mi, DOT 365 days …).
  - **Next due** = last done + interval, stored as `next_due_odometer` / `next_due_on`. Miles left = next due − `trucks.current_odometer`, which approved trip sheets keep current. Status is overdue, due soon (≤ `alerts.maintenance_miles`, default 500 mi, or ≤ `alerts.document_notice_days` days) or ok. Logic is in `App\Services\Fleet\Maintenance`.
  - **Log service** (`POST /maintenance-items/{id}/complete`): writes a `maintenance_records` row and moves the schedule forward from the service odometer and date. An older date (catching up history) doesn't move it back.
  - **Service history** (`/fleet/maintenance/history`): office service records plus the **repairs drivers entered on trip sheets**, read live from `trip_repairs` (not copied). Trip rows link to the trip.
  - MariaDB trap: odometer columns are UNSIGNED. Never write `next_due_odometer - current_odometer` in SQL (out-of-range error when negative). Compare `next_due <= odo + N`, or CAST to SIGNED for sorting.
- **Truck documents** (Fleet → Truck Documents, `/fleet/documents`, `truck_documents.*`): registration / plate, insurance, annual DOT inspection, IFTA, IRP, title, lease, permit, other. Each has a number, issue date, expiry date and a file (PDF or photo, private storage).
  - **Two-way sync:** registration and insurance documents keep `trucks.registration_expiry / insurance_expiry` in step. The latest document wins; a date typed on the truck form updates or creates the document (`App\Services\Fleet\TruckDocuments`).
  - The migration turned the existing truck dates into documents.
- **Alerts** (`php artisan tms:fleet-alerts`, scheduled daily 07:00):
  - **Truck documents:** a notification `alerts.document_notice_days` (default **10**) days before expiry, and again once it has expired.
  - **Maintenance:** a notification when a service becomes due soon, and again when it is overdue.
  - **Each alert is sent once.** Documents remember `alert_level` + `alerted_for` (a new expiry date resets them); schedules remember `alerted_key` (due point + level).
  - **Recipients:** owner + users with `truck_documents.update` / `maintenance.update`. Up to 3 items each get their own notification; more are combined into one.
  - **Channels:** in-app, email and phone push. Settings are in Trip sheet rules → Expiry alerts.
- **Menu badges / dashboard:** bootstrap `counts.maintenance_due` and `counts.documents_expiring`. Dashboard widgets: "Maintenance due" (`Support/Dashboard/maintenance.php`), and "Fleet documents expiring", which now covers every document type.
- **Phone push (Web Push, VAPID):** library `minishlink/web-push`. Keys are in `.env` (`VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY / VAPID_SUBJECT`); make new ones with `php artisan tms:push-keys`.
  - **Server:** `Notifier` queues `SendPushNotification` (after commit) for users who allow push for that type. `App\Support\WebPush` encrypts (aes128gcm), signs and removes dead devices.
  - **Dashboard:** Notification settings → "Push notifications on this device" → **Turn on / Send test / Turn off** (`src/utils/push.js`). The service worker loads `public/push-sw.js` (shows the notification; a tap opens the page). Same `tag` replaces the older one, e.g. trip rejected → approved.
  - **Trip rejected** now reads "Trip sheet rejected — please fix".
  - **Push needs HTTPS and the production build** (the dev server has no service worker). On iPhone the app must be added to the Home Screen first (iOS 16.4+). The queue worker must run.
  - **Verified locally:** a real encrypted push to a fake push service (accepted, plus a "gone" device that was removed). A phone end-to-end test needs the live HTTPS site.
- **Demo data:** `Modules/MaintenanceSeeder` (order 11) adds 11 schedules for RanaBros (T-102 oil change overdue; T-101 oil, T-102/T-105 DOT due soon), past services, and IFTA / IRP / DOT documents.
- **Tests:** backend `tests/Feature/Masters/MaintenanceTest.php` (6); frontend `tests/unit/fleet/maintenance.test.jsx` (5).

### Small changes 18 Nov (afternoon)

- **Trip form states (user):** no separate "Not on paper sheet" group and **no Canada / other countries** on the form. One list of the 48 US states in paper order with ID, MA, NE, SD, WI, WY slotted in alphabetically (ID before IL, MA before ME, NE before NV, SD before TN, WI before WV, WY last), shown in 3 equal columns on desktop and as one "States" list in the phone picker (`paperStates()` / `columns()` in `tripUtils.js`). The "Add other jurisdiction" box is gone from the phone picker (Settings → States & provinces still exists). Older trips with a Canadian row still show that row at the end. The printed sheet / PDF are unchanged (they list driven extra states only).
- **Trip form states, second change (user):** the desktop form no longer lists every state — it shows **only the states added to this trip** (rows in paper order with a remove ×, flowing in 3 / 2 / 1 columns by the box width — `useColumnCount`). Add states with the search box (type a code or name, ↑↓ Enter or click; `StateSearchAdd`) or "Pick from list" (the phone sheet). **Not in the list → "Add … as a new state"** (`NewStateForm`: code, name, country) → `POST /jurisdictions`; allowed for anyone with `trips.create` / `trips.create_any` (editing / deleting stays `jurisdictions.manage`). Company-added places are flagged `custom` in the bootstrap lookups and always show (any country), after the 48 states. The phone "Add State" sheet has the same "Not in the list?" form.
- **Repair receipts:** trip files can belong to a repair (`trip_attachments.trip_repair_id`); Trip → Repairs tab → "Add receipt photo" (camera) per repair, thumbnails, remove. Repairs now keep their id when the trip is saved again (form sends `repairs[].id`; `syncRepairs` updates in place, deletes the missing ones — their photos become ordinary trip files).
- **Repairs report** (Reports → Repairs, `GET /reports/repairs?group_by=truck|shop|state|month|driver`): repairs, trips, parts, labor, total, per repair, downtime hours, paid by drivers.
- **Website:** the "Most popular" pricing card border is navy (light blue in dark mode).

### Duplicate trip + trip templates ("general trip sheets") — added 18 Nov (user)

- **User choices:** both copy only the **repeating parts** — driver + co-drivers, truck, trailer, route, shippers / consignees, the **states driven with empty gallons / miles**, and the load rate (only when the user has `trips.view_revenue`). Never copied: load no., odometer end, numbers, expenses, repairs, signature, notes. The new draft gets today's date, a new trip number and starting miles from the truck. Templates are **company-wide only** (no personal ones). Everything is reached from the **trips list** (user's choice — no separate templates page / New Trip picker).
- **Duplicate:** row action in All Trip Sheets (inline copy icon), a "Duplicate" button on the phone trip cards, and the existing button on the trip page. Who: `trips.create_any`, or the main driver with `trips.create` (own trips). `TripService::duplicate` → `startDraft()` (shared with templates). Inactive co-drivers are left out.
- **Templates:** table `trip_templates` (name unique per company, driver_id, truck_id, trailer_id, route, `stops` json, `co_driver_ids` json, `jurisdiction_ids` json, load_rate, uses_count, last_used_at, creator_id, updater_id). Users with `trips.manage_templates` (owner by default) save one from a trip (row ⋯ → "Save as Template", name suggested from the route), rename / delete it in the "Use Template" window. Anyone with `trips.create` / `trips.create_any` opens **Trip Sheets → Use Template → Use** → new draft opens in the form. A driver entering their own sheets becomes the main driver of the new trip. If the template's driver or truck is no longer active → 422 `template_outdated` with a clear message. Services `App\Services\Trips\TripTemplates`, controller `TripTemplateController`, `TripController::fromTemplate`; migration `2026_01_25_000001`.
- Form: copied state rows (0 / 0) open empty (`tripToForm`). Unfilled states are dropped when the sheet is saved (same as before).
- Tests: `tests/Feature/Trips/TripTemplateTest.php` (shared setup moved to `TripTestSetup` trait); frontend `tripUtils.test.js`. Demo: one template "Amarillo → Kansas City" in RanaBros.

### Team drivers (several drivers on one trip) — added 18 Nov (user)

- **User choices:** a trip can have up to 4 drivers (team driving, e.g. 10 h + 10 h). The **owner / office types each driver's wage per trip** (office only — `trips.view_revenue`); an empty wage = that driver's usual rate from the driver profile (per mile × trip miles, % of load rate, or flat). The **main driver** (= `trips.driver_id`) fills in / signs the sheet and **gets all the trip's reimbursements and deductions**; a **co-driver sees the trip but only the main driver edits it**. Settlements are **grouped by trip**.
- **Data:** `trip_drivers` (company_id, trip_id, employee_id, is_main, sort_order, hours, `pay` = typed wage or null, `amount` = the wage worked out on the last save, settlement_id, creator_id, updater_id; unique trip + employee). Every trip has a main row (kept in step with `trips.driver_id` by `Trip::saved` → `TripDrivers::ensureMain`). `trips.driver_pay` = the sum of all wages (net profit uses it); `trips.driver_pay_override` = some wage was typed. `settlement_trips` is now one row per driver per trip (unique settlement + trip) with that driver's wage + hours. Migrations `2026_01_24_000001` (existing trips → one main row, typed pay + settlement kept) and `2026_01_24_000002` (`amount`).
- **API:** `POST/PUT /trips` takes `drivers: [{driver_id, hours?, pay?}]` (main first; `pay` ignored without `trips.view_revenue`; without `drivers` the old `driver_pay_override` + `driver_pay` still work for the one driver). Trip output has `drivers[]` (driver_id, name, is_main, hours, in_settlement; + `pay`, `effective_pay` with revenue rights) and `co_drivers` (count). `/trips/calculate` returns `totals.driver_wages[]` (usual + used wage per driver). `?driver_id[]=` finds trips where that person is main **or** co-driver; a driver's own list / `Access::scopeOwn` / global search / reports include co-driven trips. The driver lookup now lists all active drivers (names only) for drivers who may create their own sheets, so they can pick a co-driver.
- **Settlements:** `generate` takes every driver row of approved trips in the period that is not yet in a settlement and is owed something (main driver always; co-driver when the wage > 0) and builds one draft per driver: `settlement_trips` gets that driver's wage + hours, `trip_drivers.settlement_id` is set; only the main driver's draft sets `trips.settlement_id` and gets the auto reimbursement / deduction lines. **A trip becomes Settled only when every driver owed something is paid.** Delete / rebuild a draft frees only that driver's rows; Recycle Bin restore puts back only that driver's rows. A trip can't be reopened while any driver's row is in a settlement. `DriverSettlement::trips()` is now belongs-to-many through `settlement_trips` (pivot driver_pay, hours).
- **Screens:** Trip form → Driver → "Add a co-driver (team driving)" (main + co-driver rows with hours, remove, max 4; phone wizard too). Revenue & Pay card → one "Wage" box per driver (placeholder + hint = usual rate; the old "Override driver pay" switch is gone). Trip detail: team in the header + "Team drivers" card (hours, wage, typed / usual). Trip list / card: "+1". Paper sheet + trip PDF: co-drivers with hours under Driver; office copy lists each wage. Settlement page + PDF: per trip — wage, hours, "Team: …", then that trip's lines; "Other adjustments" = lines not tied to a trip. Live Dispatch: "Driver + 1". Driver dashboard "Estimated pay" = their own wage on trips they drove (main or co-driver). Reports Driver Performance / Driver Pay: one row per driver with their own wage and their own settlement status.
- Tests: `TripTest::test_team_trip_*`, `test_deleting_a_co_driver_settlement_releases_only_their_row`; frontend `tripUtils.test.js` (team totals / payload / tripToForm).

### Record authors: creator_id + updater_id on every table — added 18 Nov (user rule)

- **Rule (user, 18 Nov): every table has `creator_id` (who created the row) and `updater_id` (who changed it last)**, to track which user did what. New tables must have them too — `tests/Feature/Core/SchemaSafetyTest::test_every_table_has_creator_and_updater_columns` fails otherwise. No generic `status` column (the user said not needed).
- Migration `2026_01_23_000003_add_creator_and_updater_to_all_tables`: renamed `created_by` → `creator_id` (announcements, canned_replies, db_backups, driver_settlements, ip_rules, maintenance_records, referral_links, subscription_invoices, truck_trackers) and `updated_by` → `updater_id` (assistant_answers, help_articles, ifta_tax_rates); added the columns everywhere else. Tables that already name their creator keep it and only got `updater_id`: `trips.entered_by`, `trip_attachments.uploaded_by`, `driver_applications.invited_by`. Not on Laravel plumbing (migrations, cache, cache_locks, jobs, job_batches, failed_jobs, sessions, password_reset_tokens) or the role / permission link tables. Existing rows got creator / last editor from the audit log where it had them (seeded rows stay empty).
- Filled automatically by `App\Support\RecordAuthors` (listeners on `eloquent.creating: *` / `eloquent.updating: *` in AppServiceProvider) from the signed-in user. Not filled: no signed-in user (scheduler, public cab screen / application link), `saveQuietly()`, query-builder writes (`DB::table()->update`, mass `->update()`). An update with no changed field writes nothing (Laravel skips it).
- API fields named `created_by` in the IP rules, backups and announcements responses are display values (the creator's name) and were kept.

### Driver self-onboarding (online DOT application) — added 18 Nov (idea from FleetCollect)

- **Office:** Driver Files → **Invite driver** (name, phone, email) → private link `/apply/{token}` (40 chars, stored sha256, shown once, valid 30 days) with **Copy / WhatsApp / Text message / Email** buttons (client-side links, no SMS service). **Applications** page (`/employees/driver-files/applications`, button with a count on Driver Files) and detail page: answers, CDL / medical photos, signature, **PDF** (filled-in DOT application), **Show SSN** (driver_files.update, audit log `ssn_viewed`), **New link** (old one stops), **Approve & add driver** (hire date) or **Reject**. Permissions reuse `driver_files.*` (create = invite, update = approve / reject / SSN).
- **Driver (no login), phone first, 6 steps saved on every Next:** You (name, DOB, SSN, phone, email, address + addresses of 3 years) · Licence (CDL no., state, class, endorsements, expiry, other licences, medical card expiry, denied / suspended / failed-test questions) · Experience (equipment, accidents and tickets of 3 years) · Employers (3 years, 10 for CDL; FMCSR + D&A testing yes/no; or "no employment history") · Documents (CDL front required, back, medical card, other — camera on phones) · Review & sign (certification + MVR + previous-employer authorizations, finger signature). Step tabs show ✓ only when complete, "!" when something is missing.
- **Approve:** creates the employee (driver, active, code, address), CDL + medical card details, and Driver File documents: **application** (the generated PDF), **CDL** (with the photo), **medical** (with the photo). Plan driver limit checked. The rest of the DQF (MVR, previous employer inquiries, road test, drug test, Clearinghouse) is done in the Driver File.
- **SSN:** required (391.21), stored **encrypted** (`driver_applications.ssn`, Laravel `encrypted` cast), shown masked `***-**-1234` everywhere incl. the PDF.
- Code: `App\Services\Employees\DriverOnboarding`, controllers `Api\Public\DriverApplicationController` (throttle `application`, 60/min per link) and `Api\Employees\DriverApplicationController`, view `driver-files/application.blade.php`, pages `frontend/src/pages/DriverApply.jsx`, `frontend/src/modules/employees/onboarding/`. Tests: `backend/tests/Feature/Masters/DriverOnboardingTest.php`, `frontend/tests/unit/employees/driverFiles.test.jsx`.
- Demo (dev DB): a sent application from "Maria Lopez" (made-up data, sample licence picture marked DEMO) and an open invite for "Jake Miller".

### Live Dispatch (live truck map) — added 18 Nov (idea from FleetCollect's Dispatch page, own design)

- **Main → Live Dispatch** (`/dispatch`, permission `dispatch.view`; `dispatch.manage_trackers` for setup — Manager + Dispatcher), plan feature `fleet`. **The user decided: no separate loads module and no rate-con scanning — every trip sheet is the dispatch.** Trips "on the road" = draft / rejected trip sheets dated in the last 7 days (newest per truck).
- **Page:** cards Moving / Stopped / Idle-offline / Trips on the road / Waiting approval; left = trips on the road (route, driver, truck, state, open trip sheet); centre = Leaflet map (truck markers coloured by state with heading arrow, dashed pickup → delivery line, solid path driven on that trip); right = trucks (filters All / Moving / Stopped / On a trip / Free, speed, last seen). Refreshes every 30 s. Phones: map, then tabs with the two lists. Module `frontend/src/modules/dispatch/` (`liveMap.js`, `LiveDispatchPage.jsx`, `TrackingSetupModal.jsx`).
- **How trucks send their position — the owner chooses per truck (Trucks → ⋯ → Live tracking):**
  1. **Truck screen**: the tablet mounted in the cab opens `/track/{code}` (public page `frontend/src/pages/TruckScreen.jsx`, no login, code belongs to the truck). Uses the tablet's own GPS (needs an LTE / SIM model — Wi-Fi-only tablets often have no real GPS — and internet), keeps the screen on (Wake Lock), sends every 30 s, shows truck, trip and speed. Only while the page is open.
  2. **Separate GPS device / app**: hardware GPS trackers or the free **Traccar Client** app (background tracking) send the **OsmAnd protocol** to `GET|POST /api/v1/track/osmand?id=CODE&lat=&lon=&timestamp=&speed(knots)=&bearing=&accuracy=&batt=`.
  Codes: 12 characters, stored as sha256 (`truck_trackers.code_hash`), shown once; removing a device stops its code. Rate limit `tracking` 30 / min per code.
- **Data:** `truck_trackers`, `truck_positions` (path; max one every 10 s per truck; linked to the trip on the road + driver), `trucks.last_lat/last_lng/last_speed_mph/last_heading/last_position_at/last_position_source`, `geocodes`. Truck state: moving (≤ 10 min, ≥ 5 mph), stopped (≤ 10 min), idle (≤ 2 h), offline. Code: `App\Services\Tracking\{Tracking, Geocoder}`, controllers `Api\Tracking\{TrackController (public), DispatchController}`.
- **Map:** OpenStreetMap tiles (free, attribution; fine for light use — CARTO now needs a key). For many users set `VITE_MAP_TILES_URL` / `VITE_MAP_TILES_ATTRIBUTION` (e.g. MapTiler, Stadia). City → point: OpenStreetMap Nominatim, queued job `GeocodePlaces` (1 / s, generic User-Agent, only city + state + country sent), cached in `geocodes`; state centre until found or if not found. `GEOCODING_ENABLED=false` (tests) → state centres only.
- **Demo / dev DB (simulated, can be deleted):** trackers "Demo GPS (simulated)" on T-103 and T-104 and "Demo cab tablet" on T-101, with simulated positions (T-103 Amarillo → Kansas City, T-101 parked in Dallas, T-104 last seen 5 h ago near Memphis). Two "Screenshot (temporary)" trackers are already removed.
- Tests: `backend/tests/Feature/Masters/LiveDispatchTest.php`, `frontend/tests/unit/dispatch/liveDispatch.test.js`.
- Ideas not built: geofence "arrived at pickup / delivery", ETA, late alerts, ELD integrations (Samsara / Motive APIs), driver phone location from the FleetTruck app itself.

### Solo plan — added 18 Nov (idea from FleetCollect)

- **Solo** (`slug solo`, sort 0, first on the pricing page): **$15/mo**, $43/quarter, $81/half-year, $153/year (same steps as the other plans: ~5 / 10 / 15 % off — the user sets final prices himself in Platform → Plans). 1 truck, 1 driver, 1 user, 2 trailers, 1 GB. Modules: trip sheets, fleet, employees + shippers (a trip sheet needs them), driver mobile, basic reports. Migration `2026_01_22_000004_add_solo_plan` (creates it only when missing).
- The yearly discount already existed (monthly / quarterly / half-yearly / yearly prices on every plan, "save X %" on the website). The user keeps the current prices and will change them manually.
- **`PlatformSeeder` now only creates missing plans** — it no longer overwrites prices or limits changed in Platform → Plans.
- Website: Solo added to the fallback plans (`website/src/data/plans.ts`) and the Spanish plan text (`src/lib/plans.ts`); the pricing grid shows 4 plans in a row (2 × 2 between 961 and 1199 px). Tests counting 3 standard plans now count 4.
- Note: Starter's description still says "For owner-operators and very small fleets" — the user may want to change it in Platform → Plans now that Solo exists.
- Dev note: `scripts/dev.sh status` checks the saved pid only; if a service shows "running" but its port doesn't answer, delete `~/.local/share/fleet-tms/run/<name>.pid` and run `scripts/dev.sh start`.

### Company Filings (compliance calendar) — added 18 Nov (idea from FleetCollect)

- **Operations → Company Filings** (`/filings`, badge = open filings overdue or due within 30 days; dashboard card "Company filings due"). Permission `filings.view/create/update/delete` (Manager + Accountant all, Dispatcher view), plan feature `fleet`. Module `frontend/src/modules/compliance/`.
- **Auto filings** (`App\Services\Compliance\Filings`, created by `Filings::ensure()` on page load, dashboard and the daily alerts):
  - **MCS-150** every 2 years, end of a month from the USDOT number (last digit = month, 0 = October; second-to-last digit odd/even = odd/even years). Needs `companies.usdot_no` (Company Profile); a changed number moves the open one. RanaBros (1234567) → July of even years → 07/31/2028.
  - **UCR** (Dec 31, for next year), **IFTA quarterly return** (Apr 30 / Jul 31 / Oct 31 / Jan 31, link to State Mileage), **IFTA licence & decals** (Dec 31), **HVUT 2290** (Aug 31, July–June).
- **Typed-in:** IRP renewal, insurance filing (BMC-91), BOC-3, drug & alcohol program, NY HUT, KYU, NM weight-distance, Oregon weight-mile, state permit, other — each with its own recurrence (once / quarter / year / 2 years).
- **Mark done** (date, confirmation no., fee/tax paid, receipt file, notes) → the next occurrence is created. **Not needed for us** → status `skipped`; auto types stay off until "Turn back on". Tabs Upcoming (grouped by month, date badges) / Done / Not needed.
- **Alerts** (`tms:fleet-alerts`): 30 and 7 days before and when overdue, once per stage, to `filings.update`.
- Table `company_filings` (soft deletes, Recycle Bin "Company filing"). Demo `CompanyFilingSeeder` (order 12): last quarter's IFTA return and this year's UCR filed, IRP renewal due in 20 days, BOC-3 on file.
- Tests: `backend/tests/Feature/Masters/CompanyFilingsTest.php`.
- Reference dates are general federal rules; state permits/IRP depend on the base state — the user types those.

### Driver Qualification Files (DQF) — added 18 Nov (idea from FleetCollect)

- **Employees → Driver Files** (`/employees/driver-files`, menu "Driver Files (DQF)" with a badge = drivers not cleared; also a tab on the Employees pages and a "Driver file (DQF)" row action on drivers). Permission `driver_files.view/create/update/delete` (Manager all, Dispatcher view, Accountant none), plan feature `employees`.
- **Checklist** (`App\Services\Employees\DriverFiles::TYPES`, DOT audit order, 49 CFR 391.51 + Part 382): employment application, MVR at hire, previous employers inquiry, road test (or CDL), pre-employment drug test, Clearinghouse full query (once); CDL and medical certificate (expiry); yearly MVR review and yearly Clearinghouse query (every 12 months — the first is due 12 months after its at-hire item; empty "next due" = date done + 12 months); optional ELDT certificate and Other.
- **Clearance:** `not_cleared` (a required item missing / expired / overdue — the page says which), `expiring` (something runs out within 90 days) or `cleared`. Not used to block trip sheets (yet).
- **Alerts** (`tms:fleet-alerts`, daily 07:00): 90, 60 and 30 days before and on expiry / overdue, once per stage (`alert_level` + `alerted_for`); only the latest document of a type counts. Office: users with `driver_files.update`; the driver's own login gets their CDL / medical card alerts ("Your …").
- **Audit PDF** (`/driver-files/{id}/audit`, view `driver-files/audit.blade.php`): cover, clearance, checklist, then one page per document with photos printed. **Download all** (`/zip`): the PDF + every uploaded file numbered in audit order.
- **Sync:** CDL / medical documents ↔ `driver_details.cdl_expiry / medical_card_expiry` both ways (document saved → profile; driver form date changed → latest document updated or created). The migration turned existing profile dates into documents.
- Table `driver_documents` (soft deletes, Recycle Bin "Driver document"). Demo: `DriverFileSeeder` (order 21) — RanaBros: John cleared, Carlos expiring, Ray missing Clearinghouse query, Dwayne CDL expired + yearly MVR overdue.
- Tests: `backend/tests/Feature/Masters/DriverFilesTest.php`, `frontend/tests/unit/employees/driverFiles.test.jsx`.
- **Sidebar:** a parent link is no longer highlighted together with a deeper one (`/employees` vs `/employees/driver-files`).

### IFTA tax calculation — added 18 Nov (idea from FleetCollect)

- **Super Admin → System → IFTA Tax Rates** (`/platform/ifta-rates`, permission `platform.ifta_rates.view / manage`, Platform Staff can view): one set of **diesel rates per quarter for the whole platform** (table `ifta_tax_rates`: quarter `2026Q4`, jurisdiction code, rate and surcharge in US$ per US gallon). Type them, **Paste rates** (one line per state: code or name, rate, surcharge) or **Copy last quarter**; link to the official IFTA matrix. Rates are **not pre-filled on purpose**: they must come from the official matrix (wrong rates = wrong tax on a filing).
- **State Mileage report** (group by State, one quarter selected): adds Net taxable gallons, Tax rate, Surcharge and **Tax due (− = credit)** per state, the total in the KPI "IFTA tax due", the return due date (last day of the month after the quarter) and a list of states with no rate yet. Spanning more than one quarter shows a hint instead. Maths in `App\Support\Ifta` (58 members: 48 lower states + 10 provinces; AK, HI, DC, Mexico get no tax).
- Tests: `backend/tests/Feature/Reports/IftaTaxTest.php`, `frontend/tests/unit/platform/iftaRates.test.jsx`.
- The State Mileage report needs the plan feature `reports_advanced` (Business plan); the RanaBros demo plan doesn't have it.

### Users & roles: who can see and give what — added 17 Nov

One rule class: `backend/app/Support/RoleGrants.php`. Test: `backend/tests/Feature/Core/RoleAssignmentTest.php`.

- **Unrestricted:** the owner (`is_owner`) and anyone with `roles.manage` can give any role and any permission.
- **Everyone else who may add/edit users or employee logins** can only give:
  - a role whose permissions they **all** have themselves;
  - direct permissions they have themselves.
  The **Owner role only comes from the owner** (or a transfer of ownership). Nobody can change the role of someone with more access than them. Checked in `UserController::beforeSave` and `EmployeeController::saveLogin`.
- **"More access than you"** (`RoleGrants::hiddenUserIds`) = the owner, anyone with the Owner role, and (unless you have `roles.manage`) anyone holding a permission you don't have. The owner sees everyone; you always see yourself.
  - **Users page:** those people are left out of `GET /users` (list, `?all=1` pickers, search). Open / edit / disable / reset password / delete by id answer **404**. This closed a takeover hole: a manager could reset the owner's password or change the owner's email.
  - **Employees page:** the employee record stays (owner-operators drive and must stay in driver lists), but its `login` is only `{ "restricted": true }` (shown as "🔒 Higher access"), `can.manage_login` is false, and `POST/DELETE /employees/{id}/login` answer 403.
- **Role list** `GET /roles` and permission catalog `GET /permissions`: open to anyone who may view/add/edit users or employees; without `roles.manage` they list only what that person may give (so the manager's "Add User" Role dropdown works). There is no `users.manage` permission.
- Demo (RanaBros): the manager sees themselves, the dispatcher and the driver; may give Manager, Dispatcher, Driver.

### Website languages — added 17 Nov

- **English + Spanish are real pages.** English keeps the plain URLs (`/pricing/`); Spanish is `/es/…` (`/es/pricing/`). Both are built from the same file in `website/src/pages/[...lang]/` (`getStaticPaths = langPaths`).
  - Each page and component holds its own text as `pick(lang, { en: …, es: … })`. Shared words and the **Spanish style guide** (tú form, glossary, which words stay English) are in `website/src/i18n/ui.ts`. The helpers are in `website/src/i18n/index.ts`: `langFromUrl`, `localize` (internal links) and `alternates`.
  - Shared copy: `contentFor(lang)` in `data/content.ts`, `solutionsFor(lang)`, `moduleLabels(lang)`, `cyclesFor(lang)`, `planText(p, lang)`. Plans come from the API in English; the Spanish text is looked up by plan slug and falls back to English.
  - SEO: `<html lang>`, hreflang en-US / es-US / x-default on every page, `og:locale` + alternate, and the XML sitemap pairs each URL (`i18n` option in `astro.config.mjs`). Spanish titles and descriptions follow the same length rules.
  - **English only:** blog articles (`/blog/<slug>/` comes from the CMS in English; `/es/blog/` lists them with a note) and the 404 page.
  - **Chat assistant:** the answers are English. On Spanish pages the chat UI is Spanish, and the starter chips show Spanish but ask the English question.
  - **The app itself is English.** App mock-ups (HeroDevices, PaperDigital, TripSheetFlow) and screenshots keep their English UI text, and only the captions are translated. The Spanish FAQ has an extra answer saying the app is in English.
  - The forms (`api-form.ts`) send `Accept-Language`. The API does not translate its messages yet; client-side checks are in Spanish.
- **Language menu** (`components/LangSwitch.astro`): a globe button in the header (all screen sizes, sign-up page too), "Idioma / Language" in the phone menu sheet, and the footer.
  - Picking English / Español opens the same page in that language and is remembered (`localStorage site-lang`). A returning visitor who arrives from outside the site is sent to their language (inline script in `Base.astro`; crawlers keep no storage, so SEO is unaffected).
- **More languages = Google Translate** (`scripts/google-translate.ts`, list `i18n/google.ts`): 100+ languages, popular first (Punjabi, Hindi, Urdu, Russian, Ukrainian, Portuguese, French, Arabic …), searchable by native or English name.
  - Google's script loads **only after a visitor picks a language** (and on later pages while the `googtrans` cookie is set). Nothing goes to Google before that, and a website test guards it.
  - Google's own top bar and pop-ups are hidden (`styles/global.css`). The globe shows the chosen language code, and English / Español switch back to the original.
  - Right-to-left languages get `html.gt-rtl` (text right-to-left, layout unchanged). Long translations: the header hides "Book a demo" and clips the nav instead of widening the page.
  - The brand name and the language menu have `translate="no"`.
- **Flags** next to every language (header menu, phone menu, footer): `website/src/i18n/flags.ts` maps language → country; the images are 48×36 WebP in `website/public/flags/` (about 37 KB in all, made from the MIT flag-icons set, licence in that folder), loaded lazily when the menu opens. English → US, Spanish → Mexico, Portuguese → Brazil, Punjabi / Hindi → India, Urdu → Pakistan. Esperanto, Hmong, Kurdish, Uyghur and Yiddish have no country, so they show a globe. They are decorative (`alt=""` + `aria-hidden`), which the alt-text test allows. Emoji flags were not used: Windows shows them as letters.
- **Tests:** `website/tests/site.test.mjs` (26, incl. "every flag in the menu is in the build"). It checks both languages exist with lang, hreflang and the menu; that Spanish pages link to Spanish pages; that Spanish pages have no leftover English site text; that blog articles are English-only; and that Google never loads with the page.
- **To add a language as real pages:** add it to `LANGS` in `i18n/index.ts` and to every `pick(…)` (TypeScript lists the missing ones), then add it to the `i18n` locales in `astro.config.mjs`.

### Billing Log & History (Super Admin) — added 16 Nov

- **Where:** Super Admin → Billing → **Billing Log & History** (`/platform/billing-log`, permission `platform.billing_log.view`). The same list is the *Billing log* tab in Referrals & Wallets.
- **What's logged** (`billing_events`, append-only — update/delete throw):
  - invoices: created / cancelled;
  - payments: submitted / approved / rejected / cash recorded / amount mismatch;
  - subscriptions: activated / plan changed / dates changed / trial / limits / private plans (with before → after);
  - points: applied / released;
  - wallet: adjusted / verified;
  - referrals: link / signup / review / approved / rejected / rewarded / expired;
  - settings changes;
  - security events and refused attempts.
  - Every line has who, role, IP, browser, request id and the amount due before → after.
- **Page:**
  - summary cards (payments approved, points earned, points used net, refused, security);
  - filters: area, date, done by, company id, invoice id, search text / event / request id;
  - export Excel / CSV / PDF / Word;
  - row → details (all fields, JSON details, other steps of the same request);
  - **History** timeline of a company / invoice / payment / referral / request: log lines with each points-ledger line directly under the step that caused it, plus invoices and payments.

### SEO rules for the website (16 Nov)
- **Titles:** every page has a unique `<title>` of at most 65 characters. `Base.astro` adds " | FleetTruck" only when it still fits.
- **Descriptions:** 70–165 characters.
- **Images:** every image has descriptive `alt` text and a `title`.
- **Header tags:**
  - keywords, author, referrer, geo (US-TX, Fort Worth);
  - canonical, hreflang, RSS, a link to the site map page;
  - robots, googlebot and bingbot;
  - Open Graph (with image alt, secure URL and type, and article times) and Twitter;
  - structured data: Organization and WebSite on every page, plus page-specific data.
- **Site map:**
  - `/sitemap/` is a visible page linking every page, feature section, Solutions item and blog article; it's linked in the footer;
  - `/sitemap-index.xml` gives each page a priority, update frequency and last-updated date (blog dates come from the API; rules in `astro.config.mjs`);
  - `robots.txt` points to both.
- **Enforced:** `npm test` in `website/` fails if any of these rules break.

## 7. Tests (17 Nov)

| Suite | Result | Run |
|---|---|---|
| Backend (unit + feature) | **358 passed** | `cd backend && php artisan test` (not `--parallel`: ParaTest is not installed) |
| Frontend (Vitest) | **275 passed** | `cd frontend && npx vitest run` |
| Website (build + link / anchor / SEO / tab-bar / screen-flow / chat / pricing-module / language / flag checks + assistant accuracy) | **26 passed** | `cd website && npm test` |

**Full-system browser check (17 Nov):** every dashboard page as Super Admin, owner, manager, dispatcher, accountant and driver, on desktop (1366 px) and phone (390 px), opening each page's "Add" form; every GET list API as 4 users; every website page on desktop + phone. No crashes. The crawler logs in with a one-time login code (`TokenService::createLoginCode`), reads the routes from `/src/modules/registry.js` in the browser and drives headless Chrome over CDP. To repeat it, ask Claude for a "full-system crawl"; the scripts were in the session scratchpad, not in the repo.

Do not use `npx astro check`: it waits on an interactive prompt to install `@astrojs/check` and hangs. Use `astro build`.

## 8. What the user wants (preferences)

- Show everything **here as local files or screenshots, not Artifacts**.
- **Mobile first**, app-like, simple enough for non-technical drivers, attractive and fast.
- Main colour direction: **dark navy** (website banner, buttons, menu states, login and register).
- **Do not change whole pages when only a colour or one element is asked for.** The full-site dark theme was reverted at the user's request.
- The "simple state entry" trip form redesign was **reverted**. Keep the original trip form design.
- Show only real features of the system on the website (menus, footer, features).
- **Dashboard sidebar (17 Nov):** logo, company card and menu search fixed at the top; the help box fixed at the bottom as **one compact row** ("Need help? · Guides & support · Open"); only the menu scrolls. Round dark collapse button on the edge. Several menu sections can be open at once — a "one section at a time" accordion was tried and **reverted** at the user's request.
- **Website language menu shows flags** next to every language (see "Website languages").
- **Users must never see or manage people with more access than themselves** (see "Users & roles: who can see and give what").

## 9. Open items and ideas for Monday

- [ ] Real Turnstile keys and real contact details (`site.ts`, `VITE_SUPPORT_*`) before going live.
- [ ] The app inside still uses the bright blue theme. Ask if it should move to navy like the website and login.
- [ ] Production deployment plan (hosting, queue worker, scheduler).
- [x] **Done 19 Nov: fuel stops** (Fuel Stops module + optional section on the trip; see section 6). Original note: — per stop: date, truck stop, city + state, odometer, gallons, price/gal, paid by (fuel card / cash / Com Check), receipt photo. Open question for then: should stops fill the state gallons and Total Cash Fuel automatically, and show in a Fuel report / Live Dispatch map / trip PDF? Today fuel-card purchases are recorded as gallons only (no cost).
- [ ] **Deferred (user, 18 Nov): merge Truck Documents + Company Filings** — the user found them confusing (IRP / IFTA show in both) and asked to merge, then said "no need to merge now". If asked again, ask first: one page with one "what is due" calendar + Company / Trucks & Trailers tabs (recommended) vs one flat list; name (Compliance?); Driver Files in or out. Smaller idea offered, not built: when an IRP / IFTA renewal filing is marked done, offer to update every truck's matching document expiry.
- [x] **Started 19 Nov: Flutter app (`mobile/`)** — phases 1–5 built + tested (see the 19 Nov Flutter section at the end and `mobile/README.md`). Original note: user asked 18 Nov, then said "no need now". If asked again, ask first: who it is for (drivers first recommended), install Flutter + Android SDK here (not installed; iPhone builds need a Mac + Xcode, Apple $99/yr, Google Play $25), phone GPS tracking while on a trip, push via Firebase (FCM slot already reserved in `POST /push/subscribe`). The API is ready: `GET /app/bootstrap`, `/app/version`, `/lookups?since=`, offline drafts by `client_uuid` + `POST /sync/push`.
- [ ] Optional: back up uploaded files too, and copy backups off the server (S3 or another disk).
- [ ] Optional: let each company owner customise their own company's menu.
- [ ] **Ask the user:** in the demo the manager can't see the accountant on the Users page, because the accountant has `billing.view` and the manager doesn't ("more access" = any permission you don't have). If the user wants only the owner / clearly higher roles hidden, narrow `RoleGrants::hiddenUserIds` (trade-off: the manager could then reset the accountant's password and use billing access).

## 10b. Session change log (18 Nov 2026)

- **Later on 18 Nov:** Duplicate + trip templates (company-wide; `trips.manage_templates` to create, anyone with create rights to use; labels "Use Template" / "Save as Template"; help tooltip); trip form top bar Cancel removed (Use Template instead on new sheets); Delete for draft trips on the list + phone cards; row buttons light tint + dark icon, hover deeper + zoom; app-wide styled tooltips (`GlobalTip`, `data-tip`). Tests: backend 384, dashboard 289. User decided not to merge Truck Documents / Company Filings for now (see Open items).

- **Dashboard dev port 5173 → 5174:** another project on this computer ("LabCore") uses 5173. Changed in `scripts/dev.sh`, `frontend/vite.config.js`, backend `.env` / `.env.example` (`FRONTEND_APP_URL`, `FRONTEND_URLS`), `config/tms.php`, website `.env` / `site.ts`, and the docs.
- **FleetCollect review:** app.fleetcollect.net/v2 is only a sign-in page; its public site lists IFTA (GPS state miles, tax), DQF compliance, dispatch + rate-con scan + invoicing, drug testing services. The user chose to build, in this order: IFTA tax ✅, Driver Qualification Files ✅, company compliance calendar ✅, Solo plan + yearly discount ✅, driver self-onboarding ✅, live dispatch ✅ (the user dropped the separate loads module + rate-con scan: trips are the dispatch; customer invoices not started), driver self-onboarding, live truck tracking. Then **team drivers** (several drivers per trip, owner types each driver's wage, settlement grouped by trip; main driver gets all reimbursements/deductions; co-driver sees the trip, main driver edits) — **done 18 Nov** (section "Team drivers").
- **Duplicate trip + trip templates** done (see its section).
- **Trip form (desktop) top bar:** the Cancel button is gone; new sheets show **Use Template** there instead (same template window as the list; not shown when editing an existing trip).
- **Row action buttons (all lists, user):** light button in its own colour with a dark icon of that colour (dark mode: soft tint, light icon); hover = a slightly deeper tint + a little zoom (`.row-act` in `styles/app.css`; no zoom with reduced motion). The ⋯ button stays neutral.
- **Global search updated for every module (user):** company search now also finds trip templates, truck documents, truck maintenance, driver files (DQF), driver applications, company filings, users (never people with more access — RoleGrants), help articles, and trips by shipper / consignee name; type names match too ("insurance", "UCR", "oil"). New **Features** group (`frontend/src/layout/searchShortcuts.js`) for things that are not a page — Use Template, Save as Template, Duplicate, Team drivers, Live tracking setup, IFTA report, Service history, applications, filings words (MCS-150, UCR, HVUT…), DQF words (CDL, MVR…) — permission + plan gated, 3+ letters, small typo tolerance ("temple" → Use Template). `/trips?templates=1&tq=…` opens the Use Template window. **Keep `searchShortcuts.js` and `GlobalSearchController::company` up to date when a module / feature is added.** Tests: `GlobalSearchTest::test_newer_modules_are_found_too_and_a_driver_still_sees_only_own_trips`, `searchShortcuts.test.js`.
- **Export on every list (user: "export option in all tables"):** added Export (Excel / CSV / PDF / Word, same filters as the screen, all pages up to 5000 rows, explicit columns) to Invoices, Service History, Support Tickets, Audit Log, Recycle Bin (company + platform), Company Filings, Refer & Earn (referred companies + points history) and platform IP Blocking, Referrals, Wallets, Audit Log, Platform Users, Jurisdictions, Contact Messages, Canned Replies, IFTA Tax Rates. Shared helper `app/Support/Exports/TableExport.php` (CrudController uses it; unknown format → 422; dates m/d/Y, booleans Yes/No). Fixes found on the way: platform exports failed with "feature locked" (plan check needs a company — platform users skip it; company users still need `excel_pdf_export`); the default column list never includes hidden / password / token / secret / *_hash fields (platform users export now has explicit columns). Not exported on purpose: detail sub-tables (trip, invoice, settlement — they have PDFs), settings matrices, QA runner, plan comparison, dashboard widgets. Test `tests/Feature/Core/ExportEverywhereTest.php`. Tests now: backend 390, dashboard 292.
- **Favicon (user, 18 Nov):** the user saw a purple graduation-cap icon in the tab — the browser's cached icon for `localhost:5174` from another project, not ours. `frontend/index.html` now links `/favicon.svg?v=2` + a new `/favicon.ico?v=2` (16–64 px, from `icons/icon-192.png`) + `apple-touch-icon.png?v=2`; bump `?v=` if the icon changes. New navy design options were drawn (scratchpad `fav/favicon-options.png`) but not chosen — the blue truck icon stays.
- **Fuel Stops (user, 19 Nov):** new module Operations → **Fuel Stops** (`/fuel-stops`, table `fuel_stops`: name, address, city, state — US or Canada —, ZIP, phone, notes; `fuel_stops.*` — Manager / Dispatcher all, Accountant view; anyone with trips.create / create_any may also **add** a missing stop from the trip form). On the trip sheet an **optional "Fuel Stops" section like Repairs** (desktop section 6 — Trip & Mileage is now 7, Signature 8; phone step 6 of **8**): each row = a stop picked from the list (or "+ Add a new fuel stop…"), odometer, gallons, cost; price per gallon and totals shown. Table `trip_fuel_stops` (name / city / state copied so the trip keeps them). Payload `fuel_stops[]: {fuel_stop_id, odometer, gallons, cost}` (replaced on every save); output `fuel_stops[]` (+ price_per_gallon), `fuel_stops_gallons`, `fuel_stops_cost`. Fuel stops do not change the paper TOTAL; **since the IFTA work (below) they DO fill the state gallons** when a trip has fuel stops with gallons. Trip page "Fuel stops" tab, trip PDF table, global search, Recycle Bin, export, phone + sheet, tour step. Migration `2026_01_26_000001`. Test `tests/Feature/Trips/FuelStopsTest.php`. Demo: 5 fuel stops in RanaBros (one in Ontario), 2 on trip 40.
- **IFTA record keeping (user, 19 Nov: "fill all the missing things"):** after an audit against the IFTA Procedures Manual / Best Practices (R1000/P540 records), migration `2026_01_27_000001_ifta_record_keeping` added:
  - **Trips:** `end_date` (≥ trip_date; field next to Date) and `empty_miles` (deadhead, part of the total; field in Trip & Mileage). Warnings: `crosses_quarter` (start and end in different IFTA quarters → split), `odometer_gap` (truck's previous submitted/approved/settled trip ended below this start → miles on no trip sheet), empty miles > total.
  - **State rows:** `route` (highways) + `odometer_in` (odometer entering the state) → "Route of travel (IFTA)" panel under the state table (desktop section 3, phone step 3), States tab on the trip page, trip PDF table.
  - **Fuel stops on a trip:** `purchased_on` (defaults to trip date), `fuel_type` (diesel, biodiesel, gasoline, propane, cng, lng, **reefer = not IFTA**), `invoice_no`, **receipt photos** (`trip_attachments.trip_fuel_stop_id`, uploaded on the trip page Fuel stops tab — shared `Receipts` component from RepairsView). Rows keep their `id` on re-save so photos stay linked. **When a trip has fuel stops with road-fuel gallons, the gallons per state come from them** (`TripService::applyFuelToStates`, mirrored by `applyFuelToStates()` in tripUtils; state gallon inputs are then locked with a note); trips without fuel stops keep typed gallons.
  - **Trucks:** `ifta_qualified` (switch, default on), `ifta_decal_no`, `fleet_no`. **Companies:** `ifta_account_no`, `ifta_base_state` (Company profile → General).
  - **State Mileage / IFTA report:** only IFTA-qualified trucks count; for one quarter miles / gallons / taxable gallons are **whole numbers** (`Ifta::tax` rounds like the return); summary `loaded_miles` / `empty_miles`; disclaimer shows the IFTA account (or asks to add it); `meta.notices` (banners): trucks left out, trips crossing a quarter, odometer gaps per truck, fuel stops without receipt photo.
  - Not code: official IFTA tax / interest rates must still be entered by the Super Admin each quarter; a GPS-vs-trip-sheet cross-check is future work. Test `tests/Feature/Trips/IftaRecordsTest.php`. Demo trip 40 has routes, odometer-in and invoice numbers.
- **IFTA report: any quarter + IFTA return export (user, 19 Nov):** State Mileage report quarter filter = **Year select + Q1–Q4 + Whole year** (years from the company's first trip, `meta.quarter_years`; future quarters disabled; active chip = `meta.ifta.quarter`). New **"IFTA return"** button → dialog with 4 choices: Data only PDF · Data only Excel · **With receipts — one PDF** · **With receipts — ZIP** (user picked "both"). `GET /reports/ifta-return?quarter=&format=pdf|xlsx&receipts=none|pdf|zip` (`IftaReturnController` extends ReportController; same truck / driver / status filters; reports.ifta + reports_advanced + reports.export + excel_pdf_export). Content: header (licensee, IFTA account, base state, quarter, due date, fleet MPG), schedule per jurisdiction (total / taxable miles, taxable / tax-paid / net gallons, rate, tax, surcharge, total due; non-IFTA miles listed), supporting schedules: miles by vehicle and jurisdiction (VIN, plate, decal, fleet no., odometer from/to), fuel purchases, trips (odometer + route), notices. Excel = sheets IFTA return · Miles by truck · Fuel purchases · Trips · Receipts. Receipts = photos on fuel stops + receipts on Total Cash Fuel expense lines; one-PDF mode scales photos (≤1400 px, EXIF upright) and merges PDF receipts with **pdfunite** (poppler-utils — install it on the server; without it PDF receipts get a note page, and the ZIP has them); renders in segments of 40. ZIP files named `NNN_date_trip_truck_state_invoice.ext`, same names in the Excel. Temp files in `storage/app/tmp`, deleted after sending. Interest not computed (only for late returns). Tests `tests/Feature/Reports/IftaReturnExportTest.php`. Demo: 2 receipts on trip 40 (a photo + a PDF).
- **Repair photos & invoices in the trip form (user, 19 Nov):** each repair card has "Photos & invoices" — Add photo / invoice (several, images compressed, PDFs kept), previews with remove, saved ones shown; files upload after the trip saves with `trip_repair_id` (`matchSavedRepairs()` in tripUtils maps form repairs to saved ones: by id, new ones in order) and the form takes the new repair ids so a second save does not re-create them. Expense receipt buttons and trips-list buttons use styled tooltips (`data-tip`). Trips list rows: only Edit + Duplicate as buttons; Open / Save as Template / Print / Delete in ⋯.
- **City dropdown (user, 19 Nov):** Load From City / Destination are a search dropdown (`CityPicker` in TripFormParts, helpers in `trips/cities.js`): this trip's shippers (Load From) / consignees (Destination) first ("on this trip"), then the company's cities (`lookups.cities` from `app/Support/Lookups/cities.php`: trips, trip stops, repairs, shippers/consignees, fuel stops — most used first, max 1000; "used before"), then ~200 built-in major US + Canadian freight cities. Picking fills City + ST; **ST is read-only** (always from the city — user); "Add “Waco” as a new city" (or type "Waco, TX") keeps the typed city and asks "Which state is Waco in?" (state list: US / Canada / company-added); leaving the box with a typed city takes the exact match from the list, or asks the state for a new one; it is saved with the trip and offered next time (no separate cities table). Test `tests/Feature/Trips/CityLookupTest.php`, `tests/unit/trips/cities.test.js`.
- **Faster trip form (user, 19 Nov):** End date defaults to today (and moves with Date when Date goes past it). Shipper / Consignee name = search dropdown of Shippers & Consignees (`SearchSelect.jsx`, shared) + the city dropdown (`CityCombo`, ST read-only); a new name is **added to Shippers & Consignees when the trip saves** (`TripService::stopParty`: matches name + city case-insensitive first, sets the shipper/consignee mark, only this company's party ids — fixes a cross-company id hole; lookups `parties` up to 1000). Fuel stop picker = search dropdown ("Add “…” as a new fuel stop" opens the add form with the name). A new fuel stop's odometer starts from the previous stop (or Starting Miles); hint shows the trip's odometer range, red when outside. Ending Miles: one-tap "Use 413,545" (Starting + state miles) when empty — not filled silently, so the odometer check stays honest. Duplicate / template start at the truck's last trip Ending Miles (`Truck::lastOdometerFor`, same as `/trucks/{id}/last-odometer`). Every date box opens its calendar on click (`utils/datePickerOnClick.js`, installed in main.jsx). Test `tests/Feature/Trips/QuickFillTest.php`.
- **Faster trip form, part 2 (user, 19 Nov — "do 1, 2, 3 + phone wizard"):** (1) **"Same as last time?"** — `GET /trips/lane?from_city&from_state&to_city&to_state&exclude` (TripController::lane: latest non-draft trip on that Load From → Destination with state miles, case-insensitive; drivers only their own trips) → `LaneSuggestion` above the states (desktop + phone) with the states/miles chips, "Use these" (`applyLane`: miles + highways into the state rows, gallons kept) / "No thanks"; hidden once any state has miles. (2) **Miles left** — when Ending − Starting is known and exactly one state has no miles, "Fill NM with 415 mi" (`MilesLeft`); Ending Miles keeps its one-tap "Use …" (not silent). (3) **Load From / Destination follow the shipment** (first shipper city / last consignee city) while empty or auto-filled (`_from_auto` / `_to_auto`, `withRoute` in useTripForm); picking a city by hand stops it; hint "From the first shipper — change it if…". **Phone wizard 6 steps** (`PHONE_STEPS` in tripUtils): Trip Info · Shipment · Miles & States (odometer + states + route) · Expenses · **Anything else?** (`ExtrasStep`: both buttons "Add a repair" / "Add a fuel stop" always shown, their editors below when used; Next skips) · Review & Sign (`ReviewStep`: whole sheet in parts with **Edit** → jumps to that step). `stepForField` updated. Website "6 simple steps". Test `tests/Feature/Trips/LaneSuggestionTest.php`.
- **Refresh button (user, 19 Nov):** ↻ in the desktop top bar (before the tour signpost) and the phone header (`layout/PageRefresh.jsx`). Reloads the open page without reloading the app: `<Outlet key={refreshKey}>` in AppLayout mounts the page again (its useFetch calls run again) + `auth.refresh()` (bootstrap: menus, badges, lookups). Pages with unsaved changes register `useUnsavedChanges(isDirty, keepCopy)` → "Refresh this page?" confirm; the trip form registers (dirty since the last save) and saves its device copy first, so "Restore" is offered after the refresh. Other forms (modal forms) are not registered yet.
- **Prices $7 under FleetCollect (user, 19 Nov — first "$5 less", then "7 dollar less"; chose "only lower, never raise"):** FleetCollect (fleetcollect.net — the user wrote "fleetcollection.net", which does not exist) lists Solo $19 / Starter $39 (2–5 drivers) / Growth $59 (6–10) / Professional $7 per driver (11+), 7-day trial, yearly −20% (read from their site's pricing code, 19 Nov). Ours now: **Solo $12** (q 34 · h 65 · y 122), Starter $29 (unchanged), **Professional $52** (q 148 · h 281 · y 530), Business $99 (unchanged); 3/6/12 months keep 5 % / 10 % / 15 % off. Migration `2026_01_28_000001_lower_plan_prices` (only plans still at the old price), PlatformSeeder, website fallback `website/src/data/plans.ts`; billing tests updated. Existing subscriptions keep their invoiced amount. Website home: "NEW · Trip sheets from templates" badge + "⚡ Fill a trip sheet fast" line under the hero text; hero phone animation now the app's 6 steps (Miles & States with odometer, "Anything else?").
- **Truck change bug fixed (found while recording, 19 Nov):** picking a driver auto-picks their usual truck and fills Starting Miles / trailer; changing the truck afterwards kept the old truck's Starting Miles (Starting Miles only filled when empty) → wrong odometer + "below the truck odometer" warning. Now values filled from a truck carry `_start_auto` / `_trailer_auto` and follow a truck change; typed / hand-picked values are kept (`setField` clears the flags); a slower answer for an earlier truck is ignored (`truckReq` counter in `chooseTruck`).
- **Pricing cards compact (user, 19 Nov: "remove extra space… small size, not remove anything"):** `website/src/components/PricingCards.astro` — smaller padding, icon, title, price (34px), limit boxes, feature rows and gaps; all content kept.
- **Row buttons smaller (user, 19 Nov):** `.row-act` 28 px (icon 12.5 px) with a mouse, 32 px on touch screens.
- **No Vite error box (user, 19 Nov):** `server.hmr.overlay: false` in `frontend/vite.config.js`; errors show the app's ErrorBoundary card. Production builds never had the box.
- **Canada back on the trip form (user, 19 Nov):** `paperStates()` now returns the 48 US states (paper order) → the 10 Canadian provinces A–Z → company-added places; the phone picker shows groups "US states" / "Canada" / "Added by your company". (On 18 Nov the user had asked to remove Canada — reversed today.)
- **Company Documents + Contacts (user, 18 Nov):** Operations → **Company Documents** (`/company-documents`): name (required), category (optional — type or pick; suggestions = standard list + categories already used, `GET /company-documents/categories`), optional expiry (reminders 30 and 7 days before + when expired — `tms:fleet-alerts`, every plan, `company_documents.update`), notes, **several files** (`company_document_files`; form sends `new_files[]` / `remove_files[]`; PDF, photos, Word, Excel… up to 20 MB each; private storage). Each file has a view link and a **download link with its own name** (`Files::downloadUrl` → `files.show?download=`). Office only: `company_documents.*` (Manager all, Accountant view/create/update, Dispatcher view, owner gives more). **Contacts** (`/contacts`): name, phone, email, notes (user chose "simple"); office manages (`contacts.*`), **drivers can read** (`contacts.view`, also in the driver menu); call / email buttons. Both: Recycle Bin (group "Documents & contacts"), export, global search + Features shortcuts, phone "+" sheet. Tables `company_documents`, `company_document_files`, `contacts` (migration `2026_01_25_000004`). Test `tests/Feature/Masters/CompanyDocumentsContactsTest.php`. FormField `type: 'custom'` is used for the category box and the files list.
- **Page tours (user, 18 Nov):** own tour engine `frontend/src/components/Tour.jsx` (no library): spotlight + card (Back · Next · Skip tour, "3 of 9", dots, ← → Esc); phone: card docked at the bottom/top; tall parts (side menu): card beside them. Steps whose part is not on screen are skipped (permission, phone vs desktop, no data) — one list serves owner / office / driver and phone / desktop. Tours in `frontend/src/layout/tours.js`: `dashboard.company`, `dashboard.driver`, `trips.list`, `trips.form` (desktop sections + phone wizard), `trips.detail`; pages call `usePageTour(key, TOURS[key], { ready })`. **User rules:** each tour starts by itself only the first time (per user, server `GET /tours`, `POST /tours/{key}/complete`); **Skip tour (or Esc) turns automatic tours off on every page** (key `_skipped`); replay any time via the signpost button in the top bar or profile menu → "Take the tour of this page". Auto-start waits while a window is open (e.g. an announcement to read). Targets use `data-tour="…"` markers (menu, tabbar, fab, new-trip, use-template, new-trip-sheet, save-draft, submit, trip-s1…s7, revenue, team, trip-tabs, driver-new) and `data-wtype` on dashboard widgets. **Add a tour (tours.js + usePageTour) for new main pages.** Test `tests/unit/core/tour.test.jsx`.
- **Phone "+" → Create new (user):** the amber + in the phone tab bar opens a "Create new" sheet (3-column tiles) with only the actions the user may do (permission + plan): New trip sheet, Use Template, Add truck / trailer / driver-employee, Invite driver to apply, Add shipper / consignee, Log service, Add service schedule, Add truck document, Add company filing, New settlement, New announcement, New support ticket. List in `frontend/src/layout/createActions.js` — **add new modules with an Add form there too.** Pages open straight into their Add form via `?create=1` (any ResourcePage — its Add form or a header action marked `create: true` — and Company Filings) or `?invite=1` (driver applications). Super Admin keeps "Add Company". Test `tests/unit/core/createActions.test.js`.
- **Actions column title (user):** the row-button column in every list is titled "Actions".
- **Live tracking (user):** Trucks row: Live tracking is its own button (+ a button on phone truck cards); "Service history" row button removed — Maintenance page tabs (Service schedules / Service history) now keep the truck. Tracking window: each device shows its type (Truck screen / Separate GPS device), option cards show "In use" and the window opens on the type in use; devices can be edited (name + type, `PUT /trackers/{id}`) and get a **new code** (`POST /trackers/{id}/new-code` — the old code stops; codes are stored hashed so a lost one can't be shown again). Test `LiveDispatchTest::test_a_device_can_be_renamed_switched_and_given_a_new_code`. **Add Truck → Live tracking (user):** the Add Truck form (new trucks only, users with `dispatch.manage_trackers`) has a "Live tracking" section — Not now / Truck screen / Separate GPS device + device name; the link / code (screen link, or GPS server URL + device ID, with Copy) is shown **in the form before saving** (`GET /trackers/setup-preview` — nothing stored; `TrackingPreview`), and after the truck is saved the device is created with that same code (`POST /trucks/{id}/trackers {code}` — must be 12 valid characters and unused, else 422) and the Live tracking window confirms it. FormField has `type: 'custom'` with `render({ values, value, onChange })`. **Device in use (user: "select which one selected"):** one device per truck is in use (`truck_trackers.in_use`, radio + green "In use" in the window, "Use this" on the others = backups). Only the device in use moves the truck on the map; backups still check in (last seen / battery) and their cab screen shows "Backup device". A new device becomes the one in use; removing the one in use hands over to the newest remaining one. `POST /trackers/{id}/use`. Migration `2026_01_25_000003` (existing trucks: the device that reported last). Test `test_only_the_device_in_use_moves_the_truck`.
- **Use Template help (user):** the Use Template buttons (Trip Sheets list + New Trip Sheet form) show a help tooltip ("Start a new trip sheet from a saved template: driver, truck, trailer, route, shippers / consignees and states are filled in. You only type this trip's numbers." — `USE_TEMPLATE_TIP` in `TripTemplates.jsx`). Header actions in ResourcePage accept `tip`. Long tooltips wrap (max 280px) and stay on screen with the arrow on the button.
- **Tooltips (user):** every row button shows its name in a styled tooltip on hover / keyboard focus — `components/GlobalTip.jsx` (mounted once in AppLayout) shows any `[data-tip]` element's text, fixed on <body> so tables never cut it off; hidden on touch screens (hover: none + coarse pointer). Row buttons use `data-tip` instead of `title`. Areas that draw their own tooltips are marked `data-own-tips` and skipped (the sidebar — its tooltip sits to the right of the link; fixed a double tooltip there).
- **Delete on the trips list (user):** draft trip sheets have a red Delete button on the row (and a trash button on phone cards) — confirm → `DELETE /trips/{id}` → Recycle Bin. Shown only when `can.delete` (draft + trips.delete + own sheet or update_any). ResourcePage row actions accept `inline: true` (always a button, never in ⋯); `renderCard(row, ctx)` now gets ctx.
- **Trip templates permission (user):** new `trips.manage_templates` ("Manage trip templates") — only it can save / rename / delete templates; the Owner role has it (owners get every permission) and gives it to others in Roles & Permissions. Using a template still needs only trips.create / trips.create_any. Migration `2026_01_25_000002`.
- **Team drivers** done (see its section). Trip form state grid: the "ST" header is centred over the state chips (user: "title not align").
- **IFTA tax calculation**, **Driver Qualification Files**, **Company Filings**, the **Solo plan**, **Live Dispatch** and **driver self-onboarding** (see the sections above).
- The user also wants **live truck tracking like FleetCollect's Dispatch page** (screenshot: load board To dispatch / All loads, live truck map with routes and late loads, drivers panel Available / On load, Scan rate con, money cards). Build it with the loads/dispatch item, in FleetTruck's own design — features, not a copy of their page.

## 10a. Session change log (17 Nov 2026)

- **Website languages:** English + Spanish pages and a Google Translate "More languages" list (see "Website languages" above).
- **Blog:** new first post "How to Fill In a Trip Sheet in FleetTruck: Step-by-Step Guide" (`how-to-fill-in-a-trip-sheet-step-by-step`). It is featured and the newest, so it shows first on /blog/ and on the home page. Its source is the first entry in `PostSeeder` (the seeder skips posts that already exist). It follows the real 7 wizard steps of `TripForm.jsx`; update it if the form changes.
- **Header:** FAQ is removed from the website header menu (desktop and phone sheet). It stays in the footer, the site map and the home/pricing FAQ blocks.
- **Brand renamed "Fleet TMS" → "FleetTruck"** everywhere a person sees it:
  - **Name settings:** website `site.name` / `legalName` (FleetTruck LLC), dashboard `APP_NAME` (`frontend/src/config.js`, PWA name in `vite.config.js`, `index.html`), backend `APP_NAME` (.env, which also sets the email sender name), and `branding.product_name` (the default in `PlatformSettings`).
  - **Database:** migration `2026_01_19_000001_rename_brand_to_fleettruck` updates the welcome announcement and its notifications, the platform bank account titles and a saved product-name setting. History (audit, login, backups, billing log) is not rewritten.
  - **Contact placeholders:** `support@` / `sales@` / `no-reply@` now use `fleettruck.example` / `fleettruck.test`. Backup files are now named `fleettruck-….sql.gz`.
  - **Pictures:**
    - the website screenshots in `public/screens` had the sidebar logo swapped for the live one (the data in them is unchanged);
    - `public/og-image.png` has the new name;
    - the ads in `doc/marketing/social` were re-rendered;
    - the marketing videos were re-recorded.
  - **Kept on purpose** (invisible or login-related): the Super Admin login `admin@fleettms.test`, the database names `fleet_tms*`, the dev data folder `~/.local/share/fleet-tms`, the npm package names and the cache keys.
  - To change the name again: the settings listed under "Name settings" plus the migration pattern. Pictures need the same treatment.
- **Sidebar:** logo, company card and menu search are fixed at the top and the help box (now one compact row) at the bottom; only the menu scrolls. Round collapse button. Menu label "Truck Maintenance" (migration `2026_01_20_000002`).
- **Website language menu has flags** (`website/src/i18n/flags.ts`, files in `website/public/flags/`, 48×36 WebP from MIT flag-icons). English → US, Spanish → Mexico, Portuguese → Brazil; languages with no country (Esperanto, Hmong, Kurdish, Uyghur, Yiddish) show a globe.
- **Full-system check (crawl of every dashboard page as Super Admin, owner, manager, dispatcher, accountant and driver, desktop + phone, opening each "Add" form; every GET list API as 4 users; every website page).** No page crashed. Fixed what it found:
  - **Security — role escalation:** anyone who could add or edit users (e.g. Manager) could create an Owner, move themselves to Owner, or hand out any permission directly (also via employee logins). Now `App\Support\RoleGrants`: you can only give roles whose permissions you all hold and permissions you hold; the Owner role only from the owner; you can't change the role of someone with more access. Owner and `roles.manage` keep full freedom. Test: `tests/Feature/Core/RoleAssignmentTest.php`.
  - **Manager's "Add User" / employee login form had an empty Role list** (`GET /roles` and `/permissions` needed `roles.manage` or a non-existent `users.manage`). Now open to anyone who may view/add/edit users or employees; it lists only the roles (and permissions) they may give.
  - **Super Admin got 403** on Saved views (every platform list) and on Notification settings: `saved-filters`, `tours`, `notification-preferences` and `push/*` moved from the company-only routes (`routes/api/core.php`) to the signed-in-any-user group in `routes/api.php`. Same URLs.
  - **Broken links → "Page not found":** dashboard "Driver documents expiring" (`/employees/{id}`), the trailer expiry in "Fleet expiring" (`/fleet/trailers/{id}`) and the platform "Payments to verify" card (`/platform/payments/{id}`) linked to pages that don't exist. They now open the list searched for that person / trailer / invoice.
  - **List search matches word by word** (`CrudController::applySearch`): "John Smith" finds first name John + last name Smith. Before, a full name found nothing, so global search → employee opened an empty list.
  - **Blog view counter shared the website forms' limit** (`throttle:public-form`, 10 / hour per IP): reading ~10 posts blocked the contact, demo and forgot-password forms for an hour. It has its own limiter `post-views` (30 / minute).
  - **Driver:** Trips and Reports no longer show Truck / Trailer / Driver / Shipper filters to people who can't read those lists (they loaded an empty list with a 403).
- **People with more access are hidden** from the Users page and their logins from the Employees page; they can't be opened, edited, disabled, reset or deleted by lower users (see "Users & roles: who can see and give what").

## 10. Session change log (16 Nov 2026)

1. **Dynamic sidebar menu:**
   - database tables, seeded defaults, `menu` in bootstrap;
   - Super Admin Menu Manager.
2. **Sidebar:** menu search, collapse to icons, folding section headings; search on the phone "More" page.
3. **Database Backups module (Super Admin):**
   - back up now, automatic daily or weekly backups with a retention count;
   - download, delete, and restore with a typed confirmation plus a safety backup.
4. **Application Logs module (Super Admin):** days, filters, entry details, download.
5. **Log noise fixes:** tests no longer log to `laravel.log`; 4xx `ApiException`s are not logged; notification routes now serve every user type.
6. **Tests:**
   - menu: 6 backend + 8 frontend;
   - backups: 6 backend (including a real mysqldump run) + 4 frontend;
   - logs: 4 backend + 2 frontend.

## 11. Session change log (14 Nov 2026)

1. **Trip repairs and breakdown, end to end:**
   - database, API, calculator, PDF and settlements;
   - phone step, desktop section and Repairs tab;
   - tests, docs and demo data.
2. **Website:**
   - animated dotted world map hero, made small and faint, on dark navy;
   - real 7-step wizard in the phone mockup.
3. **Website colours:**
   - the theme gradient became dark navy;
   - buttons and selected states became navy;
   - top menu hover and current page became navy.
4. **Features page:**
   - text updated to the latest rules;
   - new 2× screenshots;
   - browser bar and tilt removed;
   - home feature cards take their icon colour on hover.
5. **Header and footer:** Solutions mega menu; new footer columns, kept dark.
6. **Register and login:**
   - dark navy theme and map;
   - no header on register;
   - compact layout that fits one screen;
   - centred content columns;
   - the trip card animation added to register;
   - form only on phones;
   - support contact line under both forms.

### 19 Nov (later) — mobile app logs, security sweep, Flutter toolchain
- Super Admin → Application Logs has a **Server (Laravel) / Mobile app** switch; the app sends crashes, uncaught errors and server 5xx (user chose "errors only") to `POST /app/logs` → `storage/logs/mobile-*.log`; platform dashboard card "Mobile app errors (24 h)".
- Security: automatic sweep over every API route (`tests/Feature/Security/RouteAuthorizationTest.php`) + independent review; 11 findings fixed (see API_SPEC "Mobile app logs + security sweep"); regression tests in `SecurityReviewTest.php`. Known open: ReportRateLimitTest (user: leave it).
- Live Dispatch: trips on the road now carry truck_id / truck_no (were hidden by a `//` comment); drivers' phones share the truck position (`POST /portal/position`).
- Flutter installed in ~/dev-tools (3.50.0); app in `mobile/` compiles and its 182 tests pass. Tests: backend 436 (+1 known failure), dashboard 310.

### 19 Nov (end of day) — Flutter app phases 1–5 (`mobile/`)
- User decisions: full native rewrite with the same look + flow as the website's **phone view**; one app for everyone (company / driver / Super Admin by `user_type`); app id `org.fleettruck.app`; built in phases, report after each and ask what's next; unit tests for every screen + action; never crash; security check every phase (`mobile/SECURITY.md`, checks 1–52).
- Built: 1 sign in / sign up / forgot password / captcha · 2 shell (header, tabs, amber +, More menu) + dashboards · 3 trip sheets (list, Pending Approval, detail actions, 6-step form, templates) · 3b Live Dispatch + drivers must turn location on, phone sends the truck position (also in background) · 4 Operations: Trucks, Trailers, Maintenance, Truck Documents, Employees & Drivers, Driver Files (DQF), Company Filings · 5 Company Documents, Shippers & Consignees, Fuel Stops, Contacts, Reports (8 reports + export + IFTA return export).
- Shared engine: `lib/widgets/resource/` (ResourceList, FieldSpec forms, RecordLoader detail). Torture tests open every screen with 6 kinds of broken server data (`test/screens/robustness_test.dart`).
- Tests: **449 app tests pass**, `flutter analyze` has no errors. Backend 436 (+ known ReportRateLimitTest failure, user: leave it), dashboard 310.
- Debug APK: `flutter build apk --debug --dart-define=API_URL=http://10.0.2.2:8010/api/v1` → `mobile/build/app/outputs/flutter-apk/app-debug.apk` (first build slow: Gradle download ~1.7 GB cached in ~/.gradle).
- Next (user to choose): Settlements / driver pay, Settings, Notifications, Super Admin pages. Nothing committed — push only when the user says "push".
- Later 19 Nov (user): fuel stops in the trip form take a receipt / invoice (photo or PDF, several) — uploaded to that fuel stop when the trip is saved (website + app), so the IFTA return export finds it; the desktop form's title row with Use Template / Save Draft / Submit stays visible while scrolling; "Pick from list" (states) always shown in its hover colour. Tests: dashboard 314, app 452.

### 20 Nov — renamed to FleetTruck360 (user bought fleettruck360.com)
- Name everywhere: **FleetTruck360** (one word) — website, dashboard, API texts and emails, phone app name, docs, design mockups.
- Addresses: website `https://fleettruck360.com`, dashboard `https://app.fleettruck360.com`, API `https://api.fleettruck360.com/api/v1`; emails `support@` / `sales@` / `no-reply@fleettruck360.com` (production values noted in each `.env.example`; local stays localhost).
- Phone app ID **com.fleettruck360.app** (Android applicationId + iOS bundle id; was org.fleettruck.app, never published). Internal code names unchanged: Dart package `fleettruck`, Kotlin namespace, database `fleet_tms`, storage keys (`fleettruck.token`), `admin@fleettms.test`.
- Database: migration `2026_01_29_000001_rename_brand_to_fleettruck360` (announcements + notifications, posts, platform bank account title, platform settings; history left as it was; safe to run twice).
- Images: `website/public/og-image.png` remade from the new template `doc/marketing/source/og-image.html` (`node doc/marketing/source/render-og.cjs <cdpPort> website/public/og-image.png`); all marketing images in `doc/marketing/social` re-rendered; the 32 desktop website screenshots got the new sidebar logo line from the live app (same pages and data; the 6 phone shots never showed the name). Videos not changed (they show the old name).
- Tests after the rename: backend 436 (+ known ReportRateLimitTest), dashboard 314, website 26, app 452.

### 20 Nov — FleetTruck360 logo + trip form changes
- **Logo** (user chose: concept D + E's semi truck, "round the truck circle", option 1): blue gradient tile, white ring around a white semi truck, amber "360" pill on the ring; name Fleet (navy) · Truck (blue) · 360 (amber). Files in `doc/brand/logo/` (SVG icon / square / small / maskable / Android adaptive layers, horizontal logo light + dark, wordmarks, PNGs); regenerate with `node doc/brand/gen-logo.cjs <opentype.js>` and `node doc/brand/export-png.cjs <cdpPort> in.svg out.png <size>`. Concept boards: `doc/brand/logo-concepts*.png`, `d2-test.png`, `d3-test.png`. Used on the website (header, footer, sign-up, hero mock, favicon = small truck-only version, apple-touch-icon, logo-512.png for search engines), dashboard (`components/Brand.jsx`: sidebar, phone header, sign-in, loading; favicon.svg/.ico, PWA icons incl. maskable) and the phone app (`assets/brand/logo.png` 1×/2×/3×, launcher icons Android + adaptive + iOS). Not yet: og-image/ads still show the old truck tile icon (name already FleetTruck360); website screenshots still show the old icon tile in the sidebar.
- **Trip form** (website + app): Scales, Tires and Misc. expense lines hidden (list `HIDDEN_EXPENSE_CODES` / `kHiddenExpenseCodes`; older sheets with an amount still show it). Repair: Odometer, Downtime, Notes removed (old values kept); Where = searchable city with ST from the city; shop address fills "City, ST" from Where until edited; Labor on the "Add part" line; repair icons theme blue.
- Tests: dashboard 315, app 453.
- Later 20 Nov (trip form, user): fuel stops have no Odometer; "+" beside the fuel-stop and shipper/consignee search opens a popup form, saves to the list and picks it; receipt / photo buttons full row; repair: one "What went wrong & what was done" box, Parts & labor then Photos second last; only the Repairs and Fuel Stops section boxes fold (click the header; folded = "Optional · summary"). Driver's Signature section commented out; signature rule off by default and only the Super Admin can turn it on per company (`PUT /platform/companies/{id}/trip-rules`; switch "Trip sheet rules" on the Super Admin company page; read-only on the company's own Trip sheet rules page). Tests: backend 437 (+ known ReportRateLimitTest), dashboard 319, app 455.
- Required trip-sheet fields now marked with a red * (website + app): Date, Driver, Truck No., Starting Miles, Ending Miles, State-wise Fuel & Mileage (at least one state); popup Name fields. The signature box / "Review & Sign" appears only for companies where the Super Admin turned the signature on.
- Shipper and consignee (each with its city) are compulsory to submit (server check + red *); Repairs and Fuel Stops sections start folded (+) unless the sheet already has some. Tests: backend 438 (+ known ReportRateLimitTest), dashboard 319, app 455.
- Trip form: "+" joined to Driver / Truck No. / Trailer No. opens a short popup (new driver / truck / trailer) → saved to the list and picked (website; only with the create permission). Dashboard tests 322.
- Add-truck form: Live tracking section removed (website + app) — trucks are tracked by the driver's phone app; the per-truck "Live tracking" button for cab tablets / GPS devices remains.
- Live tracking setup offers only "Separate GPS device / Traccar app"; the "Truck screen" (cab tablet /track link) choice is hidden for now — already set-up tablets keep working. Live tracking = driver's phone app (+ optional GPS device).
- Live tracking settings in Super Admin → Platform settings → Live tracking (GPS every 15 s, send every 30 s on a trip, check every 300 s without one, first send 5 s, 500 positions offline, website sharing on/off). Drivers signed in on the website now share their location while the page is open (same rules as the app). Tests: backend 439 (+ known ReportRateLimitTest), dashboard 326, app 456.
- App caught up with all 20 Nov trip-sheet / truck changes: "+" quick add for Driver, Truck No., Trailer No., Shipper and Consignee (trip_quick_add.dart). App tests 459.
- Reports: every report covers at most 1 year (any older year can be opened, one year at a time; longer custom ranges get a clear message; no dates = last 12 months). Repairs report shows Downtime only when the period has some. IFTA tax unaffected by today's trip-form changes. Tests: backend 441 (+ known ReportRateLimitTest), dashboard 326, app 459.

- App: no internet → full page "No internet connection" with "Turn on internet" (opens the phone's internet panel / settings) and "Try again"; it closes by itself when the connection is back (lib/core/network.dart, features/home/no_internet_gate.dart).
- App: shimmer loading (grey boxes with a moving light band) instead of spinning circles on lists, forms, reports, trip templates and tracking devices (widgets/ui.dart SkeletonBox / SkeletonCard / SkeletonForm; still when the phone asks for less motion; off in tests via flutter_test_config.dart). Small spinners inside buttons, the splash and the location check stay. App tests 464.

### 20 Nov — website caught up with today's changes (user: "all today changes also implement in the website … dashboard image … add sheet scrolls … content … video")
- **Copy** (`website/src/data/content.ts`, EN + ES): trip sheets (red * required fields; shipper/consignee need name + city to submit; "+" pop-ups for Driver / Truck No. / Trailer No. / Shipper / Consignee / Fuel stop; fuel stops without odometer; the 8 expense lines on the form; one "what went wrong & what was done" repair box with city search; repairs / fuel stops optional + folded; Review instead of signing; signature only when switched on for the company), live tracking = driver's phone (app + website while signed in, positions kept on a weak signal; GPS device / Traccar optional; nothing to set up on add truck), reports up to 1 year at a time, no-internet page in the app. New FAQ "How far back can I run reports?". Steps/home/sign-up/demo texts no longer promise a signature. Hero phone mock (`HeroDevices.astro`): last step "Review" with parts ticking off (no signature pad); `PaperDigital` chip "Signed" → "Reviewed".
- **Features page**: new block **"See the whole trip sheet"** right after Trip sheets (`components/SheetScroll.astro`): the real New Trip Sheet (filled) scrolls top→bottom in a laptop window and the phone Review step in a phone frame; plays only while ≥40% visible, stops while the visitor hovers / touches / scrolls inside (they can scroll it themselves), none with reduced motion / Data Saver; phones (≤600px) show only the phone frame. Files `public/screens/sheet-desktop(.webp|-1x.webp)` 1016×3947 and `sheet-phone…` 390×2040.
- **Screenshots retaken (all 38 + 2 sheet)** with the new logo: `doc/marketing/source/webshots.cjs` (CDP, Chrome headless on its own port; login code from `TokenService::createLoginCode`). Rules: **never click "Use" on a template or Duplicate** (both save a server draft) — the filled sheet is a browser-only local draft built from approved trip 40 (`tripToForm` via Vite import, `saveLocalDraft('new')`, then "Restore"), shifted to continue from T-104's odometer 360,873 so no warnings show. Demo company was on the custom plan "RanaBros Special" (sub 14, plan 4): switched to **Business (3) only during the shots, then back to 4**. Fresh T-103 positions for Live Dispatch: `doc/marketing/source/demo-positions.php` (trip 51; T-106 is inactive so Dispatch hides it). PNG → WebP q80 2× + q82 1×.
- **Legal pages rewritten (EN + ES), dated 20 Nov**: Privacy — location tracking section (drivers only, kept only during a trip on the road, background indicator, who sees it, GPS devices), driver files / encrypted SSN, billing receipts, assistant questions, app error logs, push, providers (hosting/email, Cloudflare Turnstile, OpenStreetMap tiles + Nominatim city+state, browser push services, Google Translate only when picked, WhatsApp only when used), browser storage, retention (read-only after expiry; deleted on the owner's request; backups roll over, ~2 weeks by default), rights, under-18. Terms — plan limits + read-only, Refer & Earn points, drivers/staff & live-tracking consent is the company's job, reports ≤ 1 year at a time, check exports before use. **Open:** there is no automatic deletion job for expired/closed companies or old positions — the policy only promises deletion on request.
- **Language menu hidden** (user: "for now hide language and not work on it"): `site.showLanguages = false` in `website/src/config/site.ts` hides the header / phone menu / footer / sign-up menus and the remembered-language redirect; Spanish pages still build (not updated further). Tests skip the 3 menu tests while hidden. Decorative logo images got `aria-hidden` (alt test). Website tests: 23 pass + 3 skipped.
- **Video re-recorded** (fork, 20 Nov): new logo/name in intro, brand corner and outro; steps 1 "+" for new driver/truck/trailer, 2 "New one? Tap +", 4 Toll/Lumper/Truck Wash (no Scales), 5 **"Fuel stops & repairs"** adds Pilot Travel Center #421 (118.4 gal), 6 **"Review & submit"** (no signature); outro chips "Fuel stops & receipts", "IFTA-ready records" + fleettruck360.com. `record.cjs` clears old drafts first; `compose.cjs` waits for the stage page. Masters 64 s in doc/videos/, website copies 2.8 MB / 1.4 MB + posters. Demo trip deleted with cleanup.php (counter back to 48). ProductVideo alt text updated.
- **3D hero** (user: "add 3D like modern websites" → chose "3D hero devices"): `HeroDevices.astro` — scene in CSS 3D (perspective 1500px): laptop at the back, phone `translate: 0 0 90px`, wire/packet/chips 110–150px out; back plates (thickness), glare sliding with the tilt, floor shadow. A small script eases `--tx/--ty` toward the pointer (fine pointers; slow sway when resting / on phones) and `--sc` (lean back while scrolling away); runs only while visible; nothing with reduced motion. Uses the individual `translate` property so the chip/packet transform animations still work.

### 20 Nov — database indexes + partitions (user: "check all possible index in db and add partitions")
- **Index audit** (every table vs the queries the code runs): migration `2026_01_30_000001_add_query_indexes` adds trips (company_id, status, trip_date) [replaces (company_id, status)] and (trip_date, company_id) [Super Admin dashboard], user_notifications (user_id, created_at), truck_positions (trip_id, recorded_at) [replaces (trip_id)], driver_settlements (company_id, driver_id, period_end) [replaces (driver_id)], login_histories (company_id, ip, created_at) [replaces (company_id)], truck_documents (truck_id, type, expires_on) [replaces the FK index], subscription_invoices (status, paid_at), support_tickets (status, resolved_at); drops Spatie's left-prefix duplicates (company_id on model_has_permissions / model_has_roles / roles).
- **`whereDate()` never used an index** (Laravel sends `date(col) >= ?`). All 59 calls in app/ now use **`whereDateIndexed()` / `orWhereDateIndexed()`** (`App\Support\DayQuery`, registered in AppServiceProvider): same meaning, sent as a plain range (`<= d` → `< d+1`, `= d` → `d <= col < d+1`), correct for DATE and DATETIME; non-dates fall back to whereDate. ⚠ Not named whereDay — Laravel's whereDay() is day-of-month. Use whereDateIndexed in new code.
- **Partitions** (user chose: big log tables, keep everything): `truck_positions` (recorded_at), `audit_logs` (created_at), `login_histories` (created_at) — `PARTITION BY RANGE (UNIX_TIMESTAMP(col))` monthly: p_old · pYYYY_MM · p_future (MAXVALUE). Migration `2026_01_30_000002_partition_log_tables`: drops their foreign keys (MariaDB forbids FKs on partitioned tables), time column NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id, time). Cascades now in `RecycleBinService` (truck purge → its positions; company purge → its positions deleted, its audit rows company_id → NULL). `php artisan tms:partitions` (daily 02:15) splits p_future so this month + 3 ahead exist; **nothing is ever dropped**. Helper `App\Support\Partitions`. Tests: `tests/Feature/Core/PartitionsAndIndexesTest.php` (no DDL inside tests — it would commit the test transaction). Backend 445 pass (+ known ReportRateLimitTest). Backup taken before migrating the dev DB.
- Not done (found by the audit, optional): nothing cleans up truck_positions / user_notifications / login_codes / audit_logs and `sanctum:prune-expired` is not scheduled; `TripDrivers::scopeForDriver` uses `driver_id = X OR EXISTS(...)` (driver's trip lists can't use the index); dashboard employees query scans driver_details without a tenant filter; `Notifier::toPlatform` lacks `whereNull('company_id')`.
- `vendor/bin/pint --dirty` reformatted every uncommitted backend file (imports / spacing only).

### 20 Nov — live deployment kit (cPanel) + mobile app out of git
- **Server:** cPanel shared hosting, home `/home/fleepylw` (Terminal available). API → `/home/fleepylw/fleettruck360/api` (subdomain api. → its `public`), dashboard → `/home/fleepylw/app.fleettruck360.com`, website → `public_html`. Phone app not deployed now.
- **Kit in `deploy/`:** `README.md` (step-by-step: PHP 8.3 + extensions, MySQL `fleepylw_fleettruck360` / user `fleepylw_ft360`, subdomains, email no-reply@, AutoSSL, upload/extract, Terminal commands, 2 cron jobs: schedule:run + queue:work --stop-when-empty, checks, updates, troubleshooting), `build-release.sh api|app|website|all` → `deploy/release/*.zip` (git-ignored; API zip = production vendor, no .env/tests/storage contents; app/website built with `deploy/env/app.env` / `website.env` + `.htaccess` from `deploy/htaccess/`), `env/api.env` (production .env template with CHANGE_ME placeholders, shipped inside the API zip as `.env.production.example`).
- **Website build reads the LIVE API** (`BUILD_API_URL`, new `site.buildApiUrl` for plans / posts / assistant at build time; browsers still use PUBLIC_API_URL) → build the website after the API is live; `ALLOW_LOCAL_API=1` = local fallback for a try. Blog posts need a website rebuild + upload (no build hook on cPanel).
- **Live data (user: "Clean + demo company"):** `php artisan db:seed --class=ProductionSeeder --force` = PlatformSeeder + RanaBros demo + modules + posts + assistant, without DemoPlatformSeeder; refuses until SUPER_ADMIN_EMAIL / SUPER_ADMIN_PASSWORD / DEMO_PASSWORD are real (≥10 chars, not CHANGE_ME / .test). Demo logins use `DEMO_PASSWORD` (config `tms.demo_password`; empty → Password@123 locally/tests). Dry-run on the test DB: 1 company, plans, 6 posts, 105 answers, partitions OK.
- Email: cPanel SMTP (no-reply@, port 465 smtps). Captcha: Cloudflare test keys until real Turnstile keys are added (API .env + both env files, then rebuild). QA runner off in production.
- **Git:** `/mobile/` added to .gitignore and untracked (`git rm -r --cached mobile`, 189 files staged as deleted; files stay on disk). The next push removes mobile/ from the remote's latest commit. `/deploy/release/` ignored.
- **Git deploy (user, 20 Nov: "attach git with the hosting" → manual cPanel button, builds made here and kept in git):** GitLab `sameerlatif1997/fleet-truck` cloned on the server by cPanel Git Version Control (read-only deploy key `~/.ssh/gitlab_deploy`, repo path `~/repositories/fleet-truck`). "Update from Remote" + "Deploy HEAD Commit" → `.cpanel.yml` → `deploy/cpanel-deploy.sh`: rsync backend → ~/fleettruck360/api (keeps .env / storage / vendor / .well-known; composer only when composer.lock changed; key:generate if empty; down → migrate → caches → storage:link → tms:partitions → queue:restart → up; stops before artisan when .env is missing), `deploy/build/app` → ~/app.fleettruck360.com (rsync --delete, keeps .well-known), `deploy/build/website` → public_html (overwrite; only /_astro replaced as a whole; deletes parking-page.shtml). Log `~/fleettruck360/deploy.log`; optional `~/fleettruck360/deploy.conf` (PHP=, COMPOSER=). **`deploy/build/` is committed** — run `deploy/build-release.sh app` / `website` before pushing dashboard/website changes. Rehearsed locally with a fake HOME + test DB (first deploy without .env, full deploy, repeat deploy skips composer; deployed API served /public/plans 200).
- First website build was made from the local API (`ALLOW_LOCAL_API=1`): local standard plans = seeder plans, same 6 blog posts.
- **Total Cash Fuel compulsory (user, 20 Nov):** an amount above $0.00 is needed to SUBMIT (drafts may leave it empty). Server: TripService::submit → `errors.expenses` "Enter the Total Cash Fuel amount before submitting." Website: red * on the Total Cash Fuel line (computer + phone layouts), amount outlined red on that error (message in the form's error banner). App: same red * (`label-cash_fuel`), outline, the submit error opens the Expenses step. Tests: backend TripTest (446 + known), dashboard cashFuelRequired.test.jsx (328), app trip_form_test (465). deploy/build/app rebuilt.
- Mailboxes created on the server: no-reply@, support@, sales@fleettruck360.com.
