# Fleet Module

The fleet module manages company vehicles, maintenance records and driver trips. It follows the MVC structure outlined in `AGENTS.md`.

## Features

- **Vehicles**: register make, model, registration details and fitness expiry.
- **Service Types**: define common maintenance tasks.
- **Vehicle Services**: log completed maintenance for each vehicle.
- **Vehicle Services `cost`**: each service entry includes a `cost` DECIMAL(10,2) value for tracking expenses.
- **Vehicle Report Parts `repair_cost`**: parts can optionally record their individual repair cost.
- **Vehicle Trips**: track usage including driver, purpose and mileage.
- **Trip Logs modal**: lists trip records with a "Map View" button and opens details on row click using Google Maps.
- **Fleet Calendar**: dashboard card showing trip and service schedules.
- **Repair Workflow**: approving a Goods Receipt linked to a vehicle report
  automatically sets the report status to `repaired` and ends any open
  downtime for that vehicle.

### Trip Logs Modal

The modal configuration stored in `ui_modals` renders a searchable table of trip records and provides quick access to a map view.

```json
{
  "title": "Trip Logs",
  "header": [{ "type": "button", "label": "Map View", "onClick": "openTripMapView" }],
  "body": [{
    "type": "table",
    "options": {
      "tableName": "vehicle_trips",
      "addButton": false,
      "showGlobalSearch": true
    }
  }],
  "footer": [{ "type": "button", "label": "Close", "onClick": "closeModal" }]
}
```

## Fleet Calendar

The **Fleet Calendar** card is defined in the `ui_modals` table. Clicking the
card loads the modal via `ModuleLoader` without any manual entry in
`Dashboard.php` or `router.js`. The modal consists of a single `calendar`
component whose `source` option is `fleet`, displaying upcoming trips and
maintenance events. Closing the modal returns to the dashboard.

## Trip GPS Tracking

Vehicle trips can collect GPS coordinates at regular intervals. The mobile
application records a point approximately every two minutes and posts it to the
server.

### `vehicle_trip_points`
- `id` SERIAL primary key
- `trip_id` references `vehicle_trips`
- `latitude` DECIMAL(10,6)
- `longitude` DECIMAL(10,6)
- `recorded_at` TIMESTAMP default current time
- `tenant_id`, `branch_id`, `isDeleted`, `updatedAt`

### API Endpoints
- `GET /api/vehicle_trip_points`
- `GET /api/vehicle_trip_points/{id}`
- `POST /api/vehicle_trip_points`
- `PUT /api/vehicle_trip_points/{id}`
- `DELETE /api/vehicle_trip_points/{id}`
- `GET /api/vehicle_trip_points/by-trip/{tripId}` – list points for a trip in
  chronological order

Clicking a row in the Trip Logs table highlights it automatically and stores the
trip ID. The **Map View** button then fetches that trip's GPS
points from `/api/vehicle_trip_points/by-trip/{id}` and displays them on a map.
The mapping features rely on the Google Maps JavaScript API.

## Lookup Tables

Two lookup tables provide options for the Vehicle Registration form and the Service Type form:

### vehicle_makes
- `id` SERIAL primary key
- `name` VARCHAR(100)
- `tenant_id`, `branch_id`, `isDeleted`, `updatedAt`

### vehicle_models
- `id` SERIAL primary key
- `make_id` references `vehicle_makes`
- `name` VARCHAR(100)
- same tenant and audit columns as `vehicle_makes`

These lookup tables supply the make and model dropdowns in both the Vehicle Registration and Service Type forms.

The **Make** and **Model** fields are `select-addable` so new entries can be
added directly from either form. Because both forms reference the same lookup
tables, a new make or model entered in one will immediately appear in the other.

APIs use standard CRUD endpoints such as `/api/vehicles` and `/api/vehicle_services`. Drivers are typically assigned the `Driver` role described in `FleetPermissionsMigration.md`.

## Front-End Usage

Two JavaScript modules provide management UIs:

```javascript
import { mount as mountServices } from '../FrontEnd/JsLibs2/modules/Property/SourceDeductions.js';
import { mount as mountRules } from '../FrontEnd/JsLibs2/modules/HR/DeductionSettings.js';

await mountServices('#work-area');
await mountRules('#work-area');
```

Call `unmount()` on each module to stop syncing when leaving the page.

## Database Changes

The schema adds two cost-related fields:

- `vehicle_services.cost` DECIMAL(10,2) records the expense of each service.
- `vehicle_report_parts.repair_cost` DECIMAL(10,2) stores the optional cost of a part.

## Driver and Fleet Engineer Workflows

Personnel are now stored directly in the `users` table. Submitting the Driver or
Fleet Engineer form triggers a workflow that creates the user and assigns them
to the appropriate group. The legacy `drivers` and `fleet_engineers` tables have
been removed.

## Configuration

Load the default data in `sql/defaults.sql` and assign permissions using the SQL snippet in `FleetPermissionsMigration.md`.
Run the module tests before committing:

```bash
./test_setup.sh
phpunit -c api/phpunit.xml
npm test
```
