# Gomi API Reference

Garbage collection platform API. Multi-tenant — all data is scoped to a company.

## Base URL

`https://getgomi.xyz`

## Authentication

Three methods:

1. **Session cookie**: set by signing in with Google at `GET /auth/login` (the console uses it; it lasts 30 days)
2. **JWT**: from `POST /auth/token` or `GET /auth/me` with a session; it lasts 24hr and `POST /auth/refresh` renews it
3. **API key**: `gomi_` and 64 hex characters, for the driver API. `POST /auth/token` makes one the first time a person with no key asks; a person makes their own with `POST /api/keys`; an admin makes one for a member with `POST /api/admin/users/{id}/create-key`

Send a JWT or an API key as `Authorization: Bearer <value>`, or as `?key=<value>` where a header can't be set (`EventSource`). The server tries the value as a JWT, then as an API key, then reads the session cookie.

Which method each group of routes accepts:

| Routes | Session | JWT | API key |
|--------|---------|-----|---------|
| `/api/driver/*` (driver role) | Yes | Yes | Yes |
| `GET /auth/me`, `GET /api/me/companies`, `/auth/logout` | Yes | Yes | Yes |
| `/api/profile`, `/api/keys` | Yes | Yes | No |
| `/api/dispatch/*`, `/api/geo/*` (admin or dispatcher) | Yes | Yes | No |
| `/api/admin/*` (admin) | Yes | Yes | No |
| `/api/super/*` (super admin) | Yes | Yes | No |
| `POST /auth/token` | Yes | Yes | No |
| `POST /auth/refresh` | No | Yes | No |
| `GET /health`, `GET /api/waste-types`, `GET /api/`, `GET /api/docs.md` | No sign-in needed | | |

An API key on a route that refuses it: 403 `"JWT or session authentication required (API keys not accepted for this endpoint)"`. Live positions for a dashboard come from `GET /api/dispatch/trips/live` with a session or JWT: no API key is needed or accepted.

### Company Context (X-Company-ID)

`X-Company-ID` was a late addition to the API, and the endpoints it applies to did not document it until November 2026.

A user can belong to more than 1 company (a driver can drive for 2). Every request acts in 1 of them, with the user's role in that company, picked in this order:

1. Header `X-Company-ID: <company_id>`: must be a company the user belongs to; any other gives the request no company (and no role)
2. Cookie `gomi_company=<company_id>` (browser page loads): a company the user has left falls through to 3
3. Neither: the user's **first company by name**, which for a driver of 2 companies need not be the company of the job in hand

An API key acts in its own company only. `GET /api/me/companies` lists the user's companies; a job's company is `job.company_id` in `GET /api/driver/jobs/{id}`. Data is scoped to the company: you cannot reach a company you are not a member of.

| Driver calls | X-Company-ID |
|--------------|--------------|
| The route job calls: `POST /api/driver/trips/start`, `GET /api/driver/trips?job_id=`, `POST /api/driver/jobs/{id}/stops/{stopId}`, `/api/driver/trips/{id}` and its `/photos` | Not needed: they answer for a job assigned to the driver, in any company |
| The collection point photo calls: `GET /api/driver/collection-points/{id}/photos`, `.../photo-gallery`, `.../job-photos` and `GET /api/driver/jobs/{id}/collection-point-photos` | Not needed: they answer for a point in any company the driver belongs to (until November 2026 they answered only for the company the request acts in: 404 `"collection point not found"` or 403 `"collection point not in your company"` otherwise) |
| `GET /api/driver/nearby-jobs` | Lists the jobs of the company the request acts in only: send `X-Company-ID` to pick it |
| `POST /api/driver/jobs/{id}/photos` | Needed: the job's company. For pickup photos use `POST /api/driver/trips/{stop id}/photos`, which does not need it |

---

## Health

| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/health` | None | Health check (returns `{"status": "ok"}`) |

---

## Auth

| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/auth/login` | None | Redirect to Google OAuth |
| GET | `/auth/callback` | None | OAuth callback (internal) |
| GET | `/auth/me` | Any | Current user; a JWT too when signed in with a session |
| POST | `/auth/token` | Session/JWT | A JWT, and an API key the first time (driver mobile flow) |
| POST | `/auth/refresh` | JWT | Refresh an expiring JWT |
| GET/POST | `/auth/logout` | Any | Clear session |

### GET /auth/me
```json
// Response
{
  "user": {
    "id": "usr_a1b2c3d4",
    "email": "kenji@example.com",
    "first_name": "Kenji",
    "last_name": "Yamada",
    "avatar_url": "https://lh3.googleusercontent.com/a/...",
    "role": "admin",
    "status": "online",
    "is_super_admin": false
  },
  "auth_method": "session",
  "token": "eyJhbGciOiJIUzI1NiIs..."
}
```
`auth_method` is `session`, `jwt` or `apikey`. `token` (a JWT, 24hr) is present only with a session. `role` is the role in the company the request acts in.

### POST /auth/token

Returns a JWT. A person with no active API key also gets one, made now and shown only here (driver mobile flow; it is named `auto-mobile`).

```json
// Response
{
  "token": "eyJhbG...",
  "expires_in": 86400,
  "token_type": "Bearer",
  "api_key": "gomi_3f9a...(64 hex)",
  "api_key_note": "Auto-generated API key for /api/driver/* endpoints. Save it ..."
}
```
An API key is refused: 403 `"session or JWT authentication required"`.

### POST /auth/refresh
```json
// Response
{
  "token": "eyJhbGciOiJIUzI1NiIs...",
  "expires_in": 86400,
  "token_type": "Bearer"
}
```
Only a JWT is accepted: anything else gets 403 `"JWT required for refresh"`.

### GET or POST /auth/logout
Ends the session. With `Accept: application/json` or `?json=1` the answer is `{"message": "logged out"}`; otherwise the signed-out page.

---

## Profile

Manage the authenticated user's own profile.

| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/api/profile` | Session/JWT | Get current user profile |
| PUT | `/api/profile` | Session/JWT | Update profile |

### GET /api/profile
```json
// Response
{
  "user": {
    "id": "usr_a1b2c3d4",
    "email": "kenji@example.com",
    "first_name": "Kenji",
    "last_name": "Yamada",
    "avatar_url": "https://lh3.googleusercontent.com/a/...",
    "role": "admin",
    "status": "online",
    "is_super_admin": false,
    "name_set_in_gomi": false,
    "last_active_at": "2026-09-15T08:00:00Z",
    ...
  }
}
```

### PUT /api/profile
```json
// Request
{"first_name": "Kenji", "last_name": "Yamada"}
```
```json
// Response
{"user": {"id": "usr_a1b2c3d4", "first_name": "Kenji", "last_name": "Yamada", ...}, "message": "profile updated"}
```
`first_name` is required.

---

## Companies (Super Admin)

Only `is_super_admin` users can manage companies, signed in with a session or JWT. An API key is refused: 403 `"JWT or session authentication required (API keys not accepted for this endpoint)"` (until November 2026 a super admin's API key was accepted here).

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/super/companies` | Create company |
| GET | `/api/super/companies` | List all companies |
| GET | `/api/super/companies/{id}` | Get company details + members |
| PUT | `/api/super/companies/{id}` | Update company name/color/logo |
| DELETE | `/api/super/companies/{id}` | Delete company |
| POST | `/api/super/companies/{id}/members` | Add user to company |
| DELETE | `/api/super/companies/{id}/members/{userId}` | Remove user from company |

### POST /api/super/companies
```json
// Request
{"name": "ekPro", "color": "#1a5276", "admin_email": "admin@ekpro.example"}
```
```json
// Response (201)
{"company": {"id": "comp_a1b2c3", "name": "ekPro", "slug": "ekpro", "color": "#1a5276", "logo_url": "", "created_by": "usr_a1b2c3d4", "created_at": "2026-09-15T08:00:00Z", "updated_at": "2026-09-15T08:00:00Z"}, "invite": {"id": "inv_d4e5f6", "email": "admin@ekpro.example", "role": "admin", "company_id": "comp_a1b2c3", "created_at": "2026-09-15T08:00:00Z"}, "invite_url": "https://getgomi.xyz/auth/login?invite=..."}
```
`name` and `admin_email` are required; `color` defaults to `#2d5a2d`. The slug is made from the name (lower case, runs of other characters become `-`), and must be unique: 409 `"failed to create company (slug may already exist)"`. The company is created with an Admin invite for `admin_email` (emailed, open for 7 days, recorded as `invite_sent` in the new company's audit log), or not at all. The super admin who creates the company does not become a member of it.

### GET /api/super/companies
Query params: `limit`, `offset`
```json
// Response
{"companies": [{"id": "comp_a1b2c3", "name": "ekPro", "slug": "ekpro", "color": "#1a5276", "logo_url": "", ...}]}
```

### GET /api/super/companies/{id}
```json
// Response
{
  "company": {"id": "comp_a1b2c3", "name": "ekPro", "slug": "ekpro", "color": "#1a5276", ...},
  "members": [
    {"company_id": "comp_a1b2c3", "user_id": "usr_a1b2c3d4", "role": "admin", "created_at": "...", "email": "kenji@example.com", "first_name": "Kenji", "last_name": "Yamada", "avatar_url": "", "status": "online", "is_super_admin": false}
  ],
  "member_count": 1
}
```
`is_super_admin` is true for a member of the Gomi team; the console labels them "Gomi team" instead of their role.

### PUT /api/super/companies/{id}
Replaces the name, colour and logo address: send all 3 (a field left out is saved empty). The slug is made again from the name.
```json
// Request
{"name": "ekPro Updated", "color": "#2e86c1", "logo_url": ""}
```
```json
// Response
{"company": {"id": "comp_a1b2c3", "name": "ekPro Updated", "slug": "ekpro-updated", "color": "#2e86c1", ...}}
```

### DELETE /api/super/companies/{id}
```json
// Response
{"message": "company deleted"}
```

### POST /api/super/companies/{id}/members
Adds the person, or changes their role if they are a member.
```json
// Request
{"user_id": "usr_d001", "role": "driver"}
```
```json
// Response
{"message": "member added"}
```
Roles: `admin`, `dispatcher`, `driver`; any other: 400 `"role must be 'admin', 'dispatcher', or 'driver'"`.

### DELETE /api/super/companies/{id}/members/{userId}
```json
// Response
{"message": "member removed"}
```

### POST /api/super/users/{id}/disable
Disables the account in every company: its sessions end, its API keys are revoked, its trips end and its open jobs go back to `pending`, unassigned. Signing in is then refused. You cannot disable yourself (409).
```json
// Response
{"user": {"id": "usr_d001", "disabled_at": "2026-11-13T09:00:00Z", ...}}
```

### POST /api/super/users/{id}/enable
```json
// Response
{"user": {"id": "usr_d001", "disabled_at": null, ...}}
```

### GET /api/me/companies
Returns every company the signed-in person belongs to, by name, with their role in each (`member_role`). Any sign-in method; with an API key it still lists all of the person's companies.
```json
// Response
{"companies": [{"id": "comp_a1b2c3", "name": "ekPro", "slug": "ekpro", "color": "#1a5276", "logo_url": "", "member_role": "admin", ...}]}
```

---

## Users (Admin)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/admin/users` | List users in current company |
| GET | `/api/admin/users/{id}` | Get user details |
| PATCH | `/api/admin/users/{id}/status` | Set user status |
| PATCH | `/api/admin/users/{id}/role` | Set user role in this company |
| PATCH | `/api/admin/users/{id}/name` | Set the name shown in Gomi |
| DELETE | `/api/admin/users/{id}/membership` | Remove from this company |

`{id}` must be a member of the company the request acts in: anyone else is 404 `"user not found"`.

### GET /api/admin/users
Query params: `search`, `role`, `limit`, `offset`

Returns the members of the active company. `company_role` is the role in this company; `total` counts all members.
```json
// GET /api/admin/users?role=driver&limit=10
// Response
{
  "users": [
    {
      "id": "usr_d001",
      "email": "kenji@example.com",
      "first_name": "Kenji",
      "last_name": "Yamada",
      "avatar_url": "https://lh3.googleusercontent.com/a/...",
      "role": "driver",
      "company_role": "driver",
      "status": "online",
      "last_known_lat": 35.6762,
      "last_known_lng": 139.6503,
      "last_active_at": "2026-09-15T08:00:00Z",
      "disabled_at": null
    }
  ],
  "total": 12
}
```

### GET /api/admin/users/{id}
`role` is the person's role in the active company.
```json
// Response
{"user": {"id": "usr_d001", "email": "kenji@example.com", "first_name": "Kenji", "last_name": "Yamada", "role": "driver", "status": "online", ...}}
```

### PATCH /api/admin/users/{id}/status
```json
// Request
{"status": "online"}
```
```json
// Response
{"user": {"id": "usr_d001", "status": "online", ...}, "message": "status updated"}
```
Valid statuses: `online`, `offline`, `on_job`

### PATCH /api/admin/users/{id}/role
Sets the role in the active company only; the person's roles in other companies stay.
```json
// Request
{"role": "dispatcher"}
```
```json
// Response
{"user": {"id": "usr_d001", "role": "dispatcher", ...}, "message": "role updated"}
```
Valid roles: `admin`, `dispatcher`, `driver`. With no company chosen: 400 `"choose a company first: a role is set per company"`.

### PATCH /api/admin/users/{id}/name
The name shown in Gomi; signing in with Google no longer changes it.
```json
// Request
{"first_name": "Kenji", "last_name": "Yamada"}
```
```json
// Response
{"user": {"id": "usr_d001", "first_name": "Kenji", "last_name": "Yamada", "name_set_in_gomi": true, ...}, "message": "name updated"}
```
`first_name` is required; each name is at most 100 characters.

### DELETE /api/admin/users/{id}/membership
Removes the person from the active company: their API keys for it are revoked, their trips there end and their open jobs there go back to `pending`, unassigned. Their other companies are untouched.
```json
// Response
{"message": "removed from the company"}
```
409 for yourself (`"you cannot remove yourself"`), a super admin (`"a global admin has access to every company"`) and the last admin (`"a company needs at least 1 admin"`).

---

## Invites (Admin)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/admin/invites` | Create invite (sends email) |
| GET | `/api/admin/invites` | List invites for current company |
| DELETE | `/api/admin/invites/{id}` | Delete invite |

### POST /api/admin/invites
```json
// Request
{"email": "driver@example.com", "role": "driver"}
```
The invite is automatically scoped to the current company. When accepted, the user is added to that company. Someone who already has a Gomi account is invited the same way: they join when they sign in through the invite, and the reply never carries their account. A new invite replaces this company's earlier open invites to the same email; other companies' invites stay. Inviting a current member of the company: 409 `"this person is already a member of this company: change their role on the Users page"`. Signing in accepts every pending invite to the email, 1 per company.

### GET /api/admin/invites
```json
// Response
{
  "invites": [
    {"id": "inv_001", "email": "newdriver@example.com", "role": "driver", "company_id": "comp_a1b2c3", "created_at": "2026-09-15T08:00:00Z"}
  ]
}
```

### DELETE /api/admin/invites/{id}
```json
// Response
{"message": "invite deleted"}
```

---

## Jobs (Admin/Dispatcher)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/dispatch/jobs` | Create job |
| GET | `/api/dispatch/jobs` | List/search jobs |
| GET | `/api/dispatch/jobs/{id}` | Get job with waste type info |
| PUT | `/api/dispatch/jobs/{id}` | Update job |
| POST | `/api/dispatch/jobs/{id}/assign` | Assign to driver |
| POST | `/api/dispatch/jobs/{id}/reassign` | Reassign driver |
| POST | `/api/dispatch/jobs/{id}/cancel` | Cancel job |
| POST | `/api/dispatch/jobs/{id}/reschedule` | Reschedule job |
| GET | `/api/dispatch/jobs/{id}/events` | Job event history |
| GET | `/api/dispatch/jobs/{id}/photos` | Photos uploaded by driver |
| POST | `/api/dispatch/jobs/auto-assign` | Auto-assign unassigned jobs |
| GET | `/api/dispatch/drivers` | The company's drivers, to assign |

### GET /api/dispatch/jobs
Query params: `status`, `priority`, `search`, `hide_old`, `limit`, `offset`

- `status`: `pending`, `assigned`, `in_progress`, `completed`, `cancelled`
- `priority`: `low`, `normal`, `high`, `urgent`
- `search`: searches title, address, area, driver name (ILIKE)
- `hide_old`: non-empty = hide completed/cancelled older than 30 days

```json
// GET /api/dispatch/jobs?status=pending&limit=5
// Response
{
  "jobs": [
    {
      "id": "job_001",
      "title": "Pickup at Shibuya Station",
      "status": "pending",
      "address": "1-24-12 Shibuya",
      "latitude": 35.6580,
      "longitude": 139.7016,
      "priority": "normal",
      "scheduled_at": "2026-09-15T09:00:00Z",
      "waste_type_name": "Burnable",
      "waste_type_icon": "🔥",
      "driver_first_name": null,
      "driver_last_name": null,
      "no_photo_count": 0
    }
  ],
  "total": 42
}
```

`no_photo_count`: how many of the job's pickups were completed with no after photo, which drivers may skip; the console shows them **No photo**. A pickup is a stop of the job when it has stops, else the job itself. It is worked out from the photos, so an after photo uploaded later clears it.

### POST /api/dispatch/jobs
```json
// Request
{
  "title": "Pickup at Shibuya Station",
  "description": "Regular morning pickup",
  "address": "1-24-12 Shibuya",
  "latitude": 35.6580,
  "longitude": 139.7016,
  "scheduled_at": "2026-09-15T09:00:00Z",
  "priority": "normal",
  "country_code": "JP",
  "waste_type_id": "wt_001",
  "collection_point_id": "cp_001",
  "driver_id": "usr_d001",
  "contact_name": "Tanaka",
  "contact_phone": "+81-3-1234-5678",
  "estimated_volume": "3 bags",
  "area_name": "Shibuya",
  "notes": "Gate opens at 8:00",
  "pickup_window_start": "2026-09-15T08:30:00Z",
  "pickup_window_end": "2026-09-15T10:00:00Z",
  "route_id": "rt_001"
}
```
```json
// Response (201)
{"job": {"id": "job_001", "title": "Pickup at Shibuya Station", "status": "pending", ...}}
```

`title` and `collection_point_id` are required: every job is at a collection point, under which the driver's photos are filed. To pick up somewhere new, add the collection point first. `country_code` is `JP` (the default) or `UG`; `priority` defaults to `normal`. The job's address and coordinates are what you send: they are not copied from the collection point. A job made with a `driver_id` is `pending` with that driver recorded; `POST /api/dispatch/jobs/{id}/assign` makes it `assigned`. A `route_id` makes it a route job: its stops are the route's, made the first time the driver app asks for them.

### GET /api/dispatch/jobs/{id}
```json
// Response
{
  "job": {
    "id": "job_001",
    "title": "Pickup at Shibuya Station",
    "status": "pending",
    "address": "1-24-12 Shibuya",
    "latitude": 35.6580,
    "longitude": 139.7016,
    "priority": "normal",
    "waste_type_name": "Burnable",
    "waste_type_icon": "🔥",
    "contact_name": "Tanaka",
    "contact_phone": "+81-3-1234-5678",
    "scheduled_at": "2026-09-15T09:00:00Z",
    "created_at": "2026-09-14T20:00:00Z",
    "driver_id": "usr_d001",
    "driver_first_name": "Yuki",
    "driver_last_name": "Tanaka"
  },
  "events": [],
  "stops": [],
  "no_photo_count": 0
}
```

`stops` holds the job's stops in the admin's order (empty for a job with none), each with `id`, `collection_point_id`, `stop_order`, `status`, `arrived_at` (the first arrival), `completed_at`, `departed_at` (when a completed stop was completed: completing a stop is departing it; a skipped stop has none), `point_name`, `before_photos`, `after_photos`, `no_photo` (completed with no after photo, which drivers may skip; the console shows it **No photo**), `reference_photos` (the admin's photos of the stop's point: `id`, `public_url`, `caption`) and `photos` (the driver's at the stop on this job, oldest first: `id`, `public_url`, `phase`, `uploaded_at`). A stop since taken off the route is listed last. `no_photo_count` is as in the jobs list.

### PUT /api/dispatch/jobs/{id}
Replaces the job's details with the request: send every field, as read from `GET /api/dispatch/jobs/{id}`. A field left out is saved empty (an address, coordinates, a scheduled time or a route left out is cleared). The fields are those of `POST /api/dispatch/jobs` except `driver_id`, `collection_point_id`, `recurring`, `recurrence_rule` and `route_assignment_id`, which this call does not change.
```json
// Request
{
  "title": "Pickup at Shibuya Station",
  "description": "Regular morning pickup",
  "address": "1-24-12 Shibuya",
  "latitude": 35.6580,
  "longitude": 139.7016,
  "scheduled_at": "2026-09-15T09:00:00Z",
  "notes": "Customer requested early pickup",
  "country_code": "JP",
  "waste_type_id": "wt_001",
  "priority": "high",
  "estimated_volume": "3 bags",
  "contact_name": "Tanaka",
  "contact_phone": "+81-3-1234-5678",
  "area_name": "Shibuya",
  "pickup_window_start": null,
  "pickup_window_end": null,
  "route_id": null
}
```
```json
// Response
{"job": {"id": "job_001", "title": "Pickup at Shibuya Station", "priority": "high", ...}}
```

Only an open job (`pending`, `assigned` or `in_progress`) can be edited. A completed or cancelled job keeps its record: 409 `"this job is completed: a completed or cancelled job can't be edited"`.

### POST /api/dispatch/jobs/{id}/assign
```json
// Request
{"driver_id": "usr_d001"}
```
```json
// Response
{"job": {"id": "job_001", "status": "assigned", "driver_id": "usr_d001", ...}, "message": "job assigned"}
```

Only a job not started yet (`pending` or `assigned`) can be assigned. A job in progress keeps its driver, and a completed or cancelled job keeps its record: 409 `"this job is in progress: only a pending or assigned job can be assigned"`. The driver must be a driver of the job's company, and not offline: 400 `"driver is currently offline"`.

### GET /api/dispatch/drivers
The drivers of the company you act in, by first name, for choosing whom to assign. Admins and dispatchers. A disabled account is left out. `status` is `online`, `on_job` or `offline`; assigning an offline driver is refused.
```json
// Response
{"drivers": [{"id": "usr_d001", "first_name": "Yuki", "last_name": "Tanaka", "email": "yuki@example.com", "status": "online"}]}
```

### POST /api/dispatch/jobs/{id}/reassign
```json
// Request
{"driver_id": "usr_d002"}
```
```json
// Response
{"job": {"id": "job_001", "driver_id": "usr_d002", ...}, "message": "job reassigned"}
```
Changes the driver of a `pending` or `assigned` job (an offline driver is accepted here); any other: 400 `"job not found or cannot be reassigned (must be pending or assigned)"`.

### POST /api/dispatch/jobs/{id}/cancel
```json
// Request
{"notes": "Customer not available"}
```
```json
// Response
{"job": {"id": "job_001", "status": "cancelled", ...}, "message": "job cancelled"}
```
The reason (`notes`, or `reason`) is recorded in the job's history as the `cancelled` event's details; the job's own notes stay as they are. Only an open job can be cancelled: 409 `"this job is already completed"`.

### POST /api/dispatch/jobs/{id}/reschedule
```json
// Request
{"scheduled_at": "2026-09-16T10:00:00Z", "notes": "Moved to next day per customer request"}
```
```json
// Response
{"job": {"id": "job_001", "scheduled_at": "2026-09-16T10:00:00Z", ...}, "message": "job rescheduled"}
```
Only works on `pending` or `assigned` jobs. `notes` is recorded in the job's history as the `rescheduled` event's details; the job's own notes stay as they are. The pickup window moves with the job, by as much as the scheduled time moves, unless the request gives `pickup_window_start` or `pickup_window_end`; a job that had no scheduled time keeps its window.

### GET /api/dispatch/jobs/{id}/events
```json
// Response
{
  "events": [
    {
      "id": "evt_001",
      "job_id": "job_001",
      "event_type": "arrived",
      "actor_id": "usr_d001",
      "old_value": "en_route",
      "new_value": "arrived",
      "details": "Collection Point A",
      "created_at": "2026-11-04T08:25:00Z",
      "actor_first_name": "...",
      "actor_last_name": "..."
    }
  ]
}
```
Oldest first; the same list is `events` in `GET /api/dispatch/jobs/{id}`. Job event types: `created`, `updated`, `assigned`, `auto_assigned`, `reassigned`, `started`, `completed`, `cancelled`, `rescheduled`, `aborted`.

The driver's events (`old_value` / `new_value`, `details`):

| event_type | When | old_value / new_value | details |
|------------|------|-----------------------|---------|
| `trip_started` | The driver starts a trip on the job | / the trip id | |
| `arrived` | The driver sets a stop `arrived` | the stop's status before / `arrived` | the point's name |
| `in_progress` | A stop set `in_progress` | before / `in_progress` | the point's name |
| `departed` | A stop set `completed`: completing a stop is departing it | before / `completed` | the point's name |
| `skipped` | A stop set `cancelled` | before / `cancelled` | the point's name |
| `en_route` | A stop set back to `en_route` | before / `en_route` | the point's name |
| `photo_uploaded` | A photo through `POST /api/driver/trips/{id}/photos` (the older `POST /api/driver/jobs/{id}/photos` logs one too, with the phase as `new_value`) | / the photo id | `before photo, <point>` or `after photo, <point>` |
| `trip_completed`, `trip_cancelled` | The trip ends | the trip's status before / after | |

A stop status sent again (the same as the stop has) is not a new event. These are logged from November 2026 on; for earlier stops, `arrived_at` and `departed_at` on the stops of `GET /api/dispatch/jobs/{id}` have the times.

### GET /api/dispatch/jobs/{id}/photos
```json
// Response
{
  "photos": [
    {
      "id": "ph_001",
      "job_id": "job_001",
      "driver_id": "usr_d001",
      "collection_point_id": "cp_001",
      "phase": "before",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/...",
      "content_type": "image/jpeg",
      "size_bytes": 245000,
      "latitude": 35.6580,
      "longitude": 139.7016,
      "exif_taken_at": "2026-09-15T09:15:00Z",
      "exif_lat": 35.6581,
      "exif_lng": 139.7015,
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro",
      "image_width": 4032,
      "image_height": 3024,
      "uploaded_at": "2026-09-15T09:16:00Z",
      ...
    }
  ]
}
```
The driver's photos on the job, `after` before `before`, each oldest first. `latitude`/`longitude` are where the app said it was; the `exif_` fields come from the image.

### POST /api/dispatch/jobs/auto-assign
Plans which online driver takes which unassigned job, nearest first, and assigns the plan only when `commit` is true. Drivers: the company's drivers who are `online` with a known location. Jobs: `pending`, no driver, with coordinates. In turns, each driver takes the unassigned job nearest to them (after the first, nearest to their last job) until the jobs run out.
```json
// Request (all optional)
{"driver_ids": ["usr_d001"], "job_ids": ["job_001", "job_002"], "commit": false}
```
```json
// Response
{
  "assignments": [
    {
      "driver_id": "usr_d001", "driver_name": "Kenji Yamada", "start_lat": 35.68, "start_lng": 139.76,
      "jobs": [{"job_id": "job_001", "title": "...", "address": "...", "latitude": 35.66, "longitude": 139.70, "distance_km": 5.2, "order": 1}],
      "total_km": 5.2
    }
  ],
  "total_jobs": 2,
  "total_drivers": 1,
  "assigned_count": 0,
  "dry_run": true,
  "message": "Preview only. Set commit=true to apply assignments."
}
```
With `commit` true the plan is worked out again from the current data and assigned: each job becomes `assigned`, with an `auto_assigned` event. No driver to plan for: 400 `"no available drivers with known location"`.

---

## Collection Points (Admin/Dispatcher)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/dispatch/collection-points` | Create collection point |
| GET | `/api/dispatch/collection-points` | List/search points |
| GET | `/api/dispatch/collection-points/{id}` | Get point details |
| PUT | `/api/dispatch/collection-points/{id}` | Update point |
| DELETE | `/api/dispatch/collection-points/{id}` | Delete point |

### POST /api/dispatch/collection-points
```json
// Request
{
  "name": "Shibuya Station East Exit",
  "address": "1-24-12 Shibuya, Shibuya-ku, Tokyo",
  "area_name": "Shibuya",
  "latitude": 35.6580,
  "longitude": 139.7016,
  "contact_name": "Tanaka",
  "contact_phone": "+81-3-1234-5678",
  "waste_type_id": "wt_001",
  "notes": "Near the east exit, behind the flower shop"
}
```
```json
// Response (201)
{"collection_point": {"id": "cp_001", "name": "Shibuya Station East Exit", "address": "1-24-12 Shibuya, Shibuya-ku, Tokyo", "country_code": "JP", ...}}
```
`name`, `latitude` and `longitude` are required. The point must be in Japan or Uganda: elsewhere is 400 (for example `"point is in KR, outside Japan and Uganda"`).

### GET /api/dispatch/collection-points
Query params: `search` (name, address or area), `limit`, `offset`. Most used first, then by name.
```json
// GET /api/dispatch/collection-points?search=shibuya&limit=10
// Response
{
  "collection_points": [
    {
      "id": "cp_001",
      "name": "Shibuya Station East Exit",
      "address": "1-24-12 Shibuya, Shibuya-ku, Tokyo",
      "area_name": "Shibuya",
      "latitude": 35.6580,
      "longitude": 139.7016,
      "notes": "Near the east exit",
      "use_count": 12,
      ...
    }
  ]
}
```

### GET /api/dispatch/collection-points/{id}
```json
// Response
{"collection_point": {"id": "cp_001", "name": "Shibuya Station East Exit", "address": "1-24-12 Shibuya, Shibuya-ku, Tokyo", ...}}
```

### PUT /api/dispatch/collection-points/{id}
Replaces the point's details: send every field of `POST`, as read from `GET`; a field left out is saved empty. `latitude` and `longitude` are required.
```json
// Request
{"name": "Shibuya East Updated", "address": "1-24-12 Shibuya, Shibuya-ku, Tokyo", "area_name": "Shibuya", "latitude": 35.6580, "longitude": 139.7016, "contact_name": "", "contact_phone": "", "waste_type_id": null, "notes": "Gate code: 1234"}
```
```json
// Response
{"collection_point": {"id": "cp_001", "name": "Shibuya East Updated", ...}}
```

### DELETE /api/dispatch/collection-points/{id}
Deletes the point and its site photos.
```json
// Response
{"message": "collection point deleted"}
```
A point that is a stop on a route, or that any job uses, is kept: 409 with the reason, the routes' names and the number of jobs.
```json
{"error": "This point is a stop on Morning route. Remove it from that route first.", "routes": ["Morning route"], "jobs": 0}
```

### Site Photos (Reference photos for drivers)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/dispatch/collection-points/{id}/photos` | Upload photo (multipart) |
| GET | `/api/dispatch/collection-points/{id}/photos` | List site photos |
| PATCH | `/api/dispatch/collection-points/{id}/photos/{photoId}` | Update caption |
| DELETE | `/api/dispatch/collection-points/{id}/photos/{photoId}` | Delete single photo |
| POST | `/api/dispatch/collection-points/{id}/photos/batch-delete` | Delete multiple photos |

### POST /api/dispatch/collection-points/{id}/photos
Multipart form: `file` (image), `caption` (optional text). Admins and dispatchers.

- Max **20 photos** per collection point: another is 409 `"maximum 20 site photos reached for this collection point"`
- Max **50MB** per file (413 `"file too large (max 50MB)"`)
- Formats: JPEG, PNG, WebP, HEIC
- **Duplicate detection**: the same image (MD5 of the file) already at this collection point is 409:
```json
{"error": "duplicate photo: this image has already been uploaded"}
```
```json
// Response (201)
{"photo": {"id": "sph_001", "collection_point_id": "cp_001", "uploaded_by": "usr_a1b2c3d4", "public_url": "https://storage.googleapis.com/gomi_storage_public/sites/...", "caption": "Blue gate on left side", "content_type": "image/jpeg", "size_bytes": 245000, "md5_hash": "5200db9b...", "sort_order": 0, "created_at": "2026-09-15T11:08:08Z", ...}}
```

### POST /api/dispatch/collection-points/{id}/photos/batch-delete
```json
// Request
{"ids": ["photo_id_1", "photo_id_2", "photo_id_3"]}
```
```json
// Response
{"message": "batch delete completed", "deleted_count": 3}
```
Every id must be a photo of this collection point: one that is not is 404, and nothing is deleted.

### PATCH /api/dispatch/collection-points/{id}/photos/{photoId}
```json
// Request
{"caption": "Look for the blue gate on the left"}
```
```json
// Response
{"photo": {"id": "sph_001", "caption": "Look for the blue gate on the left", ...}}
```

### DELETE /api/dispatch/collection-points/{id}/photos/{photoId}
```json
// Response
{"message": "photo deleted"}
```

### GET /api/dispatch/collection-points/{id}/photos
Returns all site photos for a collection point, by `sort_order` then upload time.
```json
// Response
{
  "photos": [
    {
      "id": "sph_001",
      "collection_point_id": "cp_001",
      "uploaded_by": "usr_a1b2c3d4",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/sites/...",
      "caption": "Blue gate on left side",
      "content_type": "image/jpeg",
      "size_bytes": 245000,
      "md5_hash": "5200db9b77199d5a...",
      "sort_order": 0,
      "created_at": "2026-09-15T11:08:08Z",
      "company_id": "comp_a1b2c3",
      ...
    }
  ]
}
```

---

## Routes (Admin/Dispatcher)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/dispatch/routes` | Create route |
| GET | `/api/dispatch/routes` | List routes with stop count |
| GET | `/api/dispatch/routes-with-stops` | List routes, each with its stops |
| GET | `/api/dispatch/routes/{id}` | Get route + stops |
| PUT | `/api/dispatch/routes/{id}` | Update route |
| DELETE | `/api/dispatch/routes/{id}` | Delete route |
| PUT | `/api/dispatch/routes/{id}/stops` | Set route stops (replace all) |
| POST | `/api/dispatch/routes/{id}/clone` | Clone route with stops |
| POST | `/api/dispatch/routes/{id}/optimize` | Plan the stop order from a position |

### POST /api/dispatch/routes
```json
// Request
{
  "name": "Shibuya Morning",
  "description": "Morning route covering Shibuya ward",
  "area_name": "Shibuya",
  "schedule_days": "mon,tue,wed,thu,fri",
  "color": "#e74c3c"
}
```
```json
// Response (201)
{"route": {"id": "rt_001", "name": "Shibuya Morning", "schedule_days": "mon,tue,wed,thu,fri", "color": "#e74c3c", "is_active": true, ...}}
```
`name` is required; `color` defaults to `#2d5a2d`. `schedule_days` names the days the route runs, as `mon`, `tue`, `wed`, `thu`, `fri`, `sat`, `sun` joined by commas; `POST /api/dispatch/routes/generate-schedule` reads it. `estimated_duration_min` and `estimated_distance_km` may be sent; saving the stops sets them.

### GET /api/dispatch/routes
Query params: `limit`, `offset`. By name.
```json
// Response
{
  "routes": [
    {
      "id": "rt_001",
      "name": "Shibuya Morning",
      "description": "Morning route covering Shibuya ward",
      "area_name": "Shibuya",
      "schedule_days": "mon,tue,wed,thu,fri",
      "color": "#e74c3c",
      "estimated_duration_min": 95,
      "estimated_distance_km": 14.2,
      "is_active": true,
      "stop_count": 8,
      ...
    }
  ]
}
```

### GET /api/dispatch/routes-with-stops
Query params: `limit`, `offset`. Each route as in `GET /api/dispatch/routes`, with its stops as in `GET /api/dispatch/routes/{id}`.
```json
// Response
{"routes": [{"route": {"id": "rt_001", "name": "Shibuya Morning", ...}, "stops": [...], "stop_count": 8}]}
```

### GET /api/dispatch/routes/{id}
```json
// Response
{
  "route": {"id": "rt_001", "name": "Shibuya Morning", "schedule_days": "mon,tue,wed,thu,fri", "color": "#e74c3c", ...},
  "stops": [
    {
      "id": "rs_001",
      "route_id": "rt_001",
      "collection_point_id": "cp_001",
      "stop_order": 0,
      "estimated_arrival_min": 0,
      "estimated_service_min": 5,
      "notes": "",
      "point_name": "Shibuya Station East Exit",
      "point_address": "1-24-12 Shibuya",
      "point_area": "Shibuya",
      "point_lat": 35.6580,
      "point_lng": 139.7016,
      "point_contact_name": "",
      "point_contact_phone": "",
      "point_country_code": "JP",
      "waste_type_name": "Burnable",
      ...
    }
  ]
}
```

### PUT /api/dispatch/routes/{id}
Every field is optional: a field left out keeps its value. Fields: `name`, `description`, `area_name`, `schedule_days`, `color`, `estimated_duration_min`, `estimated_distance_km`, `is_active`.
```json
// Request
{"name": "Shibuya Morning Updated", "color": "#3498db"}
```
```json
// Response
{"route": {"id": "rt_001", "name": "Shibuya Morning Updated", "color": "#3498db", ...}}
```

### DELETE /api/dispatch/routes/{id}
Also clears the route's stops, deletes its schedule entries (route assignments) and takes the route off its jobs (`route_id` empty; the jobs stay). The collection points stay.
```json
// Response
{"message": "route deleted"}
```

### PUT /api/dispatch/routes/{id}/stops
```json
// Request
{
  "stops": [
    {"collection_point_id": "cp_001", "estimated_service_min": 5},
    {"collection_point_id": "cp_002", "estimated_service_min": 10, "estimated_arrival_min": 12, "notes": "Back gate"},
    {"collection_point_id": "cp_003", "estimated_service_min": 5}
  ]
}
```
```json
// Response
{"stops": [{"id": "rs_001", "stop_order": 0, ...}, {"id": "rs_002", "stop_order": 1, ...}, ...], "distance_km": 14.2}
```
Replaces all the route's stops, in array order. Every point must be a point of the route's company.

### POST /api/dispatch/routes/{id}/clone
```json
// Request (optional)
{"name": "Shibuya Morning B"}
```
```json
// Response (201)
{
  "route": {"id": "rt_002", "name": "Shibuya Morning B", ...},
  "stops": [{"id": "rs_010", "stop_order": 0, ...}, ...],
  "message": "Cloned 'Shibuya Morning' → 'Shibuya Morning B' with 8 stops"
}
```
With no name the copy is named `<name> (copy)`.

### POST /api/dispatch/routes/{id}/optimize
Plans an order for the route's stops starting from a position, with directions when the server has a Google Maps key and nearest first otherwise. Nothing is saved: to keep the order, send it to `PUT /api/dispatch/routes/{id}/stops`.
```json
// Request
{"driver_lat": 35.6812, "driver_lng": 139.7671}
```
```json
// Response
{
  "route": {"id": "rt_001", ...},
  "optimized_stops": [{"collection_point_id": "cp_003", "name": "...", "address": "...", "lat": 35.66, "lng": 139.70, "order": 0, ...}],
  "polyline": "u{~vFvyys@fS]...",
  "total_distance_m": 14200,
  "total_duration_s": 2700,
  "legs": [{"distance_m": 1800, "duration_s": 420, "start_address": "...", "end_address": "...", ...}]
}
```
`polyline` is Google's encoded polyline format. Missing `driver_lat`/`driver_lng`: 400 `"driver_lat and driver_lng are required"`.

---

## Route Assignments (Admin/Dispatcher)

A route assignment is an entry on the daily schedule: a route on a date, with or without a driver.

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/dispatch/route-assignments` | Put a route on a date |
| GET | `/api/dispatch/route-assignments` | List a date's entries |
| PUT | `/api/dispatch/route-assignments/{id}` | Update an entry |
| DELETE | `/api/dispatch/route-assignments/{id}` | Delete an entry |
| POST | `/api/dispatch/route-assignments/{id}/create-jobs` | Create pickup jobs from the route's stops |
| POST | `/api/dispatch/routes/generate-schedule` | Put every route that runs on a date on it |
| POST | `/api/dispatch/routes/auto-assign` | Give a date's entries with no driver to drivers |

### POST /api/dispatch/route-assignments
```json
// Request
{"route_id": "rt_001", "driver_id": "usr_d001", "date": "2026-09-15", "notes": ""}
```
```json
// Response (201)
{"assignment": {"id": "ra_001", "route_id": "rt_001", "driver_id": "usr_d001", "date": "2026-09-15T00:00:00Z", "status": "assigned", ...}, "message": "route assigned"}
```
`route_id` and `date` are required. With a driver the status is `assigned`, without one `scheduled`. A route once per date: a second is 409 `"failed to create assignment (may already exist for this date)"`.

### GET /api/dispatch/route-assignments
Query param: `date` (`YYYY-MM-DD`; default today on the server's clock, UTC)
```json
// GET /api/dispatch/route-assignments?date=2026-09-15
// Response
{
  "assignments": [
    {
      "id": "ra_001",
      "route_id": "rt_001",
      "driver_id": "usr_d001",
      "date": "2026-09-15T00:00:00Z",
      "status": "assigned",
      "notes": "",
      "route_name": "Shibuya Morning",
      "route_area": "Shibuya",
      "route_color": "#e74c3c",
      "driver_first_name": "Kenji",
      "driver_last_name": "Yamada",
      "stop_count": 8,
      ...
    }
  ],
  "date": "2026-09-15"
}
```

### PUT /api/dispatch/route-assignments/{id}
Replaces the driver, status and notes: a field left out is saved empty (no `driver_id` takes the driver off), and `status` defaults to `assigned`.
```json
// Request
{"driver_id": "usr_d002", "status": "assigned", "notes": ""}
```
```json
// Response
{"assignment": {"id": "ra_001", "driver_id": "usr_d002", "status": "assigned", ...}}
```
Statuses: `scheduled`, `assigned`, `in_progress`, `completed`, `cancelled`

### DELETE /api/dispatch/route-assignments/{id}
```json
// Response
{"message": "assignment deleted"}
```

### POST /api/dispatch/route-assignments/{id}/create-jobs
Creates 1 job per stop of the route, no request body. Each job is titled `<route> — Stop <n>: <point>`, at its stop's point, address and coordinates, with the entry's driver (`pending`, the driver recorded), the route and the entry. The first is scheduled at 08:00 UTC on the entry's date (17:00 in Japan), each next one 5 minutes later. With a driver, the entry becomes `assigned` and its notes become `Jobs created: <n>`.
```json
// Response (201)
{
  "created": 8,
  "jobs": [
    {"id": "job_020", "title": "Shibuya Morning — Stop 1: Shibuya Station East Exit", "status": "pending", "route_id": "rt_001", "route_assignment_id": "ra_001", ...}
  ],
  "message": "Created 8 jobs from route Shibuya Morning"
}
```
An entry that already has jobs: 409 `"8 jobs already exist for this assignment"`.

### POST /api/dispatch/routes/generate-schedule
Puts every active route whose `schedule_days` has the date's day on the date, with no driver (`scheduled`). A route already on the date is skipped. A past date: 400 `"cannot generate schedule for a past date"`.
```json
// Request
{"date": "2026-09-15"}
```
```json
// Response
{
  "created": 2,
  "date": "2026-09-15",
  "assignments": [{"id": "ra_001", "route_id": "rt_001", "status": "scheduled", ...}],
  "message": "Generated 2 assignments for 2026-09-15 (Tue)"
}
```
`assignments` lists all of the date's entries.

### POST /api/dispatch/routes/auto-assign
Plans which online driver (with a known location) takes which of a date's entries with no driver, each driver the nearest route by its first stop, and saves it only when `commit` is true. A past date: 400.
```json
// Request
{"date": "2026-09-15", "commit": false}
```
```json
// Response
{
  "assignments": [
    {"assignment_id": "ra_001", "route_name": "Shibuya Morning", "driver_id": "usr_d001", "driver_name": "Kenji Yamada", "distance_to_start_km": 2.4, "stop_count": 8}
  ],
  "date": "2026-09-15",
  "committed": 0,
  "dry_run": true,
  "message": "Preview only. Set commit=true to apply."
}
```

---

## Driver: A Route Job, Step by Step

How the driver app runs a job on a route, from start to finish. Every call here works with the driver's JWT alone: **no `X-Company-ID` header is needed**, whichever company the job is in.

```
1. Start the trip       POST /api/driver/trips/start                  -> keep trip.id
2. Get the stops        GET  /api/driver/trips?job_id={job id}        -> 1 entry per stop, in the admin's order
3. At each stop         POST /api/driver/jobs/{job id}/stops/{stop id}   {"status": "arrived"}
                        POST /api/driver/trips/{stop id}/photos          phase=before (optional, up to 5)
                        POST /api/driver/trips/{stop id}/photos          phase=after  (optional, up to 5)
                        POST /api/driver/jobs/{job id}/stops/{stop id}   {"status": "completed"}
4. Complete the trip    POST /api/driver/trips/{trip id}/complete
5. Complete the job     POST /api/driver/jobs/{job id}/complete
```

**Two kinds of id: keep them apart.**

| id | Where it comes from | What it is used for |
|----|---------------------|---------------------|
| trip id | `trip.id` in the answer of step 1 | GPS pings, arrive, completing or cancelling the trip (step 4). 1 trip covers the whole route job |
| stop id | each entry's `id` in `GET /api/driver/trips?job_id=` (step 2) | Everything at a stop: its photos (`/api/driver/trips/{stop id}/photos`) and its status (`/api/driver/jobs/{job id}/stops/{stop id}`) |

For a route job, the entries of the `trips` array in step 2 are the job's **stops**, not trips, even though the field is called `trips`.

### 1. Start the trip

```json
// POST /api/driver/trips/start
{"job_id": "job_01", "latitude": 35.6812, "longitude": 139.7671}

// 201 Created
{"trip": {"id": "trip_01", "job_id": "job_01", "status": "en_route", "started_at": "2026-10-31T08:00:00Z"}, "next_ping_ms": 3000}
```

Keep `trip.id`. Starting the trip also puts the job `in_progress`. With another trip still live the answer is 409 `"You already have an active trip"`, with that trip in `active_trip`: complete or cancel it first. A live trip started more than 12hr ago is cancelled instead, and the new trip starts. Start the trip before anything else: photos need a live trip on the job.

### 2. Get the stops, in the admin's order

```json
// GET /api/driver/trips?job_id=job_01  ->  200 OK
{
  "trips": [
    {
      "id": "stop_a",
      "job_id": "job_01",
      "route_id": "route_01",
      "collection_point_id": "cp_01",
      "stop_order": 0,
      "status": "en_route",
      "arrived_at": null,
      "completed_at": null,
      "estimated_service_min": 10,
      "point_name": "Collection Point A",
      "point_address": "1-2-3 Shibuya, Tokyo",
      "point_area": "Shibuya",
      "point_lat": 35.6580,
      "point_lng": 139.7016,
      "point_contact_name": "...",
      "point_contact_phone": "...",
      "point_waste_type_id": "wt_01",
      "waste_type_name": "Burnable",
      "waste_type_icon": "...",
      "updated_at": "2026-10-31T08:00:00Z"
    },
    {"id": "stop_b", "stop_order": 1, "status": "en_route"},
    {"id": "stop_c", "stop_order": 2, "status": "en_route"}
  ]
}
```

- **Order:** already the admin's order (`stop_order` 0 to n-1). Run the stops in that order; do not sort them again.
- **Fresh slate per job:** each job gets its own copy of the route's stops, all `en_route`. Statuses and photos of one job never show on another job of the same route.
- **Refresh any time:** call it again to see what is done and what is left.
- A job not on a route has no stops: there `trips` holds the job's trips (see the single-point job below).

### 3. At each stop: photos, then status

| Step | Call | Notes |
|------|------|-------|
| a. Arrived | `POST /api/driver/jobs/{job id}/stops/{stop id}` `{"status": "arrived"}` | Sets `arrived_at` (the first arrival is kept) |
| b. Before photos | `POST /api/driver/trips/{stop id}/photos`, form: `photo` = the image, `phase` = `before` | Optional, up to 5 per stop |
| c. After photos | `POST /api/driver/trips/{stop id}/photos`, form: `photo` = the image, `phase` = `after` | Optional, up to 5 per stop. `phase` defaults to `after` |
| d. Completed | `POST /api/driver/jobs/{job id}/stops/{stop id}` `{"status": "completed"}` | Photos are optional: the stop completes with none. With no after photo it shows **No photo** to dispatch |

A stop's status is one of `en_route` (not reached yet), `arrived`, `in_progress`, `completed` or `cancelled` (skipped). The status call answers with the stop: `{"stop": {"id": "stop_a", "status": "completed", "arrived_at": "...", "completed_at": "..."}}`.

```js
// React Native: upload a photo of a stop
const form = new FormData();
form.append('phase', 'after');                 // 'before' or 'after'
form.append('photo', { uri: image.uri, name: 'pickup.jpg', type: 'image/jpeg' });

const res = await fetch(`${BASE}/api/driver/trips/${stop.id}/photos`, {
  method: 'POST',
  // Only the token: do NOT set Content-Type, fetch sets multipart/form-data with its boundary
  headers: { Authorization: `Bearer ${token}` },
  body: form,
});
// 201 Created
// {"photo_id": "ph_01",
//  "photo": {"id": "ph_01", "job_id": "job_01", "phase": "after", "collection_point_id": "cp_01", "public_url": "https://storage.googleapis.com/..."},
//  "remaining": 4}                              // after photos this stop can still take
```

Photo upload checklist:
- The path takes the **stop id**. The trip id works too, with the stop id in a `stop_id` form field; both file the photo under that stop.
- The file field is named `photo`. (The older `POST /api/driver/jobs/{id}/photos` takes `file`, counts photos per job rather than per stop, and needs `X-Company-ID`: do not use it for pickups.)
- JPEG, PNG, WebP or HEIC, up to 50MB. EXIF (time, GPS, camera) is kept.
- Upload while the trip is live: before step 4.

To show a stop with its photos:
- `GET /api/driver/trips/{stop id}`: `trip` (the job's trip), `stop`, `collection_point_name`, `collection_point_address`, `reference_photos` (the admin's guidance photos of the point) and `proof_photos` (this stop's before and after photos on this job).
- `GET /api/driver/trips/{stop id}/photos`: `{"photos": [...]}`, this stop's before and after photos on this job, each with its `phase`.

### 4. Next stop, then complete the trip

Repeat step 3 for each stop, in `stop_order`. A stop the driver skips is set `cancelled`. After the last stop, `POST /api/driver/trips/{trip id}/complete` with `{"latitude": ..., "longitude": ...}`. This takes the **trip id**, not a stop id. Once the trip is completed, photo uploads on the job answer 409 `"this trip has ended (completed)"`, so take every photo first.

### 5. Complete the job

```json
// POST /api/driver/jobs/job_01/complete
{"notes": "", "next_status": "online"}

// 200 OK
{"job": {"id": "job_01", "status": "completed"}, "message": "job completed", "status": "online"}
```

After this the job's stops can no longer change (409 `"this job is completed"`). The next job, even on the same route, starts again from step 1 with its own stops and photos.

### A single-point job (no route)

The same steps without stops: start the trip, then upload to `POST /api/driver/trips/{trip id}/photos` (no `stop_id`), up to 5 before and 5 after. Photos are optional: `POST /api/driver/trips/{trip id}/complete` and `POST /api/driver/jobs/{job id}/complete` work with none, and a job completed with no after photo shows **No photo** to dispatch.

### Errors and what to do

| Status | `error` | Cause | Fix |
|--------|---------|-------|-----|
| 404 | `trip not found` | The id in `/api/driver/trips/{id}/...` is neither a trip nor a stop | Use `trip.id` from step 1 or a stop's `id` from step 2 |
| 404 | `no trip of yours on this stop's job: start one first` | A stop id, but the driver has no trip on its job | Step 1: `POST /api/driver/trips/start` with the job's id |
| 404 | `stop not found on this job` | The stop id is of another job, or the job is not the driver's | Take the stop ids from `GET /api/driver/trips?job_id=` of this job |
| 404 | `stop not found on this trip's job` | A trip id in the path with a `stop_id` of another job | Send the stop id of this trip's job, or put the stop id in the path |
| 400 | `stop_id is required on a job with a route: ...` | A trip id in the path on a route job, without `stop_id` | Put the stop id in the path instead of the trip id |
| 400 | `phase must be 'before' or 'after'` | Any other `phase`, such as `proof` | Send `before` or `after`, or leave it out for `after` |
| 400 | `missing 'photo' field` | The image was sent under another field name (such as `file`), or the body is not multipart | Name the field `photo`; do not set `Content-Type` yourself |
| 403 | `unauthorized` / `trip does not belong to you` | Another driver's trip | Use the trip started by this driver |
| 409 | `maximum 5 after photos reached for this pickup` | The stop already has 5 photos of that phase | Nothing to do: 5 is the limit per phase per stop |
| 409 | `this trip has ended (completed)` | Uploading after the trip was completed or cancelled | Upload before step 4; for more photos, start a new trip on the job |
| 409 | `this job is completed` / `this job is cancelled` | The job is closed | Nothing to change on it; the next job starts fresh |
| 409 | `this job has ended: ongoing for more than 3 days` | The job was started more than 3 days ago, so it was cancelled automatically | Ask dispatch for a new job |
| 409 | `You already have an active trip` | Starting a trip with another one live and started less than 12hr ago | Complete or cancel `active_trip` first |

---

## Driver API

Session, JWT or API key; the driver role in the company the request acts in.

### Dashboard & Status

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/driver/dashboard` | Driver overview (active/upcoming jobs) |
| PUT | `/api/driver/clock-in` | Clock in with location |
| PUT | `/api/driver/clock-out` | Clock out |
| PUT | `/api/driver/location` | Update current location |
| PUT | `/api/driver/status` | Set status (online/offline) |
| GET | `/api/driver/stats` | Job counts |
| GET | `/api/driver/shifts` | Clock in and out history |

### GET /api/driver/dashboard
```json
// Response
{
  "user": {"id": "usr_d001", "email": "kenji@example.com", "first_name": "Kenji", "status": "online", ...},
  "status": "online",
  "active_shift": {
    "id": "sh_001",
    "driver_id": "usr_d001",
    "event_type": "clock_in",
    "latitude": 35.6762,
    "longitude": 139.6503,
    "created_at": "2026-09-15T08:00:00Z"
  },
  "active_jobs": [
    {"id": "job_010", "title": "Pickup at Roppongi Hills", "status": "in_progress", "address": "6-10-1 Roppongi", ...}
  ],
  "upcoming_jobs": [
    {"id": "job_011", "title": "Pickup at Tokyo Tower", "status": "assigned", "address": "4-2-8 Shiba-koen", ...}
  ],
  "stats": {
    "active": 1,
    "upcoming": 5,
    "completed_today": 3,
    "total": 142
  }
}
```

### PUT /api/driver/clock-in
```json
// Request (all optional)
{"latitude": 35.6762, "longitude": 139.6503, "notes": "Starting morning shift"}
```
```json
// Response
{"user": {"id": "usr_d001", "status": "online", "last_known_lat": 35.6762, ...}, "message": "clocked in"}
```
Already `online` or `on_job`: 409 `"already clocked in (status: online)"`.

### PUT /api/driver/clock-out
```json
// Request (optional)
{"notes": "End of shift"}
```
```json
// Response
{"user": {"id": "usr_d001", "status": "offline", ...}, "message": "clocked out"}
```
409 with a job in progress (`"cannot clock out with active jobs in progress — complete or hand off first"`) or when already offline (`"already clocked out"`).

### PUT /api/driver/location
```json
// Request
{"latitude": 35.6810, "longitude": 139.6900}
```
```json
// Response
{"user": {"id": "usr_d001", "last_known_lat": 35.6810, "last_known_lng": 139.6900, ...}, "message": "location updated"}
```
Both are required. During a trip, its pings update the location too.

### PUT /api/driver/status
```json
// Request
{"status": "online"}
```
```json
// Response
{"user": {"id": "usr_d001", "status": "online", ...}, "message": "status updated"}
```
Valid statuses: `online`, `offline`

### GET /api/driver/stats
```json
// Response
{
  "stats": {
    "total": 142,
    "pending": 4,
    "assigned": 6,
    "in_progress": 2,
    "completed": 130,
    "completed_today": 3
  }
}
```

### GET /api/driver/shifts
Query params: `from`, `to` (RFC3339 or `YYYY-MM-DD`; both or neither). With neither, the latest events.
```json
// GET /api/driver/shifts?from=2026-09-15&to=2026-09-16
// Response
{
  "events": [
    {
      "id": "sh_001",
      "driver_id": "usr_d001",
      "event_type": "clock_in",
      "latitude": 35.6762,
      "longitude": 139.6503,
      "notes": "Starting morning shift",
      "created_at": "2026-09-15T08:00:00Z"
    }
  ]
}
```

### Jobs

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/driver/jobs` | List driver's jobs |### Jobs

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/driver/jobs` | List driver's jobs |
| GET | `/api/driver/jobs/{id}` | Get job detail + site photos |
| POST | `/api/driver/jobs/{id}/start` | Start working on job |
| POST | `/api/driver/jobs/{id}/complete` | Complete job |
| POST | `/api/driver/jobs/{id}/abort` | Abort a job with reason |
| GET | `/api/driver/nearby-jobs` | Find nearby jobs (own assigned by default) |

### GET /api/driver/jobs
Query params: `status`, `limit`, `offset`. `total` counts all of the driver's jobs, before the status filter.
```json
// GET /api/driver/jobs?status=assigned&limit=10
// Response
{
  "jobs": [
    {
      "id": "job_011",
      "title": "Pickup at Tokyo Tower",
      "status": "assigned",
      "address": "4-2-8 Shiba-koen",
      "latitude": 35.6586,
      "longitude": 139.7454,
      "scheduled_at": "2026-09-15T10:00:00Z"
    }
  ],
  "total": 25
}
```

### GET /api/driver/nearby-jobs
Returns jobs near the driver's current location, sorted by proximity (closest first).
Requires the driver to be online with a known location.

**Query parameters:**

| Param | Default | Description |
|-------|---------|-------------|
| `scope` | *(assigned)* | `unassigned` to find unassigned pending jobs available for pickup. Default returns the driver's own pending/assigned/in_progress jobs. |
| `limit` | `10` | Max results (1–100) |

```json
// GET /api/driver/nearby-jobs
// Response (default — driver's own assigned jobs, nearest first)
{
  "jobs": [
    {
      "id": "job_011",
      "title": "Pickup at Tokyo Tower",
      "status": "assigned",
      "address": "4-2-8 Shiba-koen",
      "latitude": 35.6586,
      "longitude": 139.7454,
      "distance_sq": 0.00012,
      "waste_type_name": "Burnable",
      "waste_type_icon": "🔥"
    },
    {
      "id": "job_012",
      "title": "Pickup at Roppongi Hills",
      "status": "pending",
      "address": "6-10-1 Roppongi",
      "latitude": 35.6604,
      "longitude": 139.7292,
      "distance_sq": 0.00089
    }
  ],
  "scope": "assigned"
}
```
```json
// GET /api/driver/nearby-jobs?scope=unassigned&limit=5
// Response (unassigned jobs available for pickup)
{
  "jobs": [
    {
      "id": "job_050",
      "title": "Unassigned pickup at Meguro",
      "status": "pending",
      "driver_id": null,
      "distance_sq": 0.00034
    }
  ],
  "scope": "unassigned"
}
```
The `distance_sq` field is the squared Euclidean distance in degrees — useful for relative ordering, not absolute distance.

### GET /api/driver/jobs/{id}
Returns job detail. If the job is linked to a collection point that has admin-uploaded site photos, they are included automatically:
```json
// Response
{
  "job": {
    "id": "job_011",
    "title": "Pickup at Tokyo Tower",
    "status": "assigned",
    "address": "4-2-8 Shiba-koen",
    "collection_point_id": "cp_003",
    "waste_type_name": "Burnable",
    "waste_type_icon": "🔥",
    "contact_name": "Suzuki",
    "contact_phone": "+81-3-9876-5432"
  },
  "site_photos": [
    {
      "id": "sph_005",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/sites/...",
      "caption": "Blue gate entrance — ring bell"
    }
  ]
}
```
The `site_photos` field is omitted if no collection point is linked or no photos exist. A job that is not the driver's: 404 `"job not found"`.

### POST /api/driver/jobs/{id}/start
Request (optional): `{"latitude": ..., "longitude": ...}`, saved as the driver's location. The driver becomes `on_job`. A job that is not open: 409 `"this job is <status>"`; not the driver's: 404.
```json
// Response
{"job": {"id": "job_011", "status": "in_progress", "started_at": "2026-09-15T10:05:00Z", ...}, "message": "job started"}
```

### POST /api/driver/jobs/{id}/complete
```json
// Request (all optional)
{"actual_volume": "2 bags", "notes": "Left area clean", "photo_url_after": "", "next_status": "offline"}
```
```json
// Response
{"job": {"id": "job_011", "status": "completed", "completed_at": "2026-09-15T10:25:00Z", "actual_volume": "2 bags", ...}, "message": "job completed", "status": "online"}
```
`notes` is the `completed` event's details in the job's history; the job's own notes stay. `status` is the driver's status now: `on_job` with another job in progress, else `offline` if `next_status` asked for it, else `online`. A job that is not open: 409 `"this job is <status>"`.


### POST /api/driver/jobs/{id}/abort
Cancels a job of the driver's that is `pending`, `assigned` or `in_progress`, with a reason. The reason is the `aborted` event's details in the job's history; the job's notes stay. A live trip on the job is cancelled too, and the driver becomes `online`.

```json
// Request
{"reason": "Blocked road, unable to proceed"}
```
```json
// Response
{"job": {"id": "job_011", "status": "cancelled", ...}, "message": "job aborted"}
```
With a live trip on the job, the response adds `"trip_status": "cancelled"` and `"note": "Active trip for this job was also cancelled"`.

Errors: 404 `"job not found"`; 403 `"job is not assigned to you"`; 400 `"cannot abort a completed job"` (or `cancelled`).

### Photos: site photos and driver photos

A collection point has 2 kinds of photos:

| | Site photos (also called reference photos) | Driver photos |
|---|---|---|
| What | An admin's or dispatcher's photos of the point, showing drivers where to go | Before and after photos a driver takes at a pickup |
| Upload | Admins and dispatchers: `POST /api/dispatch/collection-points/{id}/photos`; admins also through `POST /api/admin/collection-points/{id}/reference-photos`, the same upload | Drivers: `POST /api/driver/trips/{stop id}/photos` on a route job (see Driver: A Route Job), or `POST /api/driver/jobs/{id}/photos` |
| Limit | 20 per point | 5 per phase per pickup |
| Change or delete | Caption and delete: admins and dispatchers | No API call changes or deletes them |
| Filed under | The point | The job and the job's collection point |
| Drivers read them | `GET /api/driver/collection-points/{id}/photos` and the views below | The views below |

Site photos have no location or camera data. Driver photos keep where the app said it was (`latitude`, `longitude`) and what the image says (`exif_taken_at`, `exif_lat`, `exif_lng`, `exif_make`, `exif_model`, `image_width`, `image_height`).

### Job Photos (driver)

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/driver/jobs/{id}/photos` | Upload a photo for this job |
| GET | `/api/driver/jobs/{id}/photos` | List photos for this job |

On a route job, upload with `POST /api/driver/trips/{stop id}/photos` instead: it files the photo under the stop.

### POST /api/driver/jobs/{id}/photos
Multipart form: `file` (required), `collection_point_id` (required: a point of the company the request acts in), `phase` (`before` or `after`, default `after`), `latitude`, `longitude` (optional). Needs `X-Company-ID` for a driver of more than 1 company (see Company Context).

- The job must be the driver's and `in_progress`, or `completed` less than 48hr ago: otherwise 409 (`"photos can only be uploaded for in-progress or completed jobs"`, `"upload window closed (48 hours after completion)"`)
- Max **5 photos per phase** per job: 409 `"maximum 5 after photos reached"`
- Max **50MB** per file; JPEG, PNG, WebP, HEIC
- The same image (MD5) twice in the same phase of the job: 409 `"duplicate photo — this image has already been uploaded"`
- The job's history gets a `photo_uploaded` event

### GET /api/driver/jobs/{id}/photos
The job's photos, `after` before `before`, each oldest first; fields as in `GET /api/dispatch/jobs/{id}/photos`.
```json
// Response
{
  "photos": [
    {
      "id": "ph_001",
      "job_id": "job_011",
      "phase": "before",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/...",
      "content_type": "image/jpeg",
      "size_bytes": 245000,
      "latitude": 35.6586,
      "longitude": 139.7454,
      "exif_taken_at": "2026-09-15T10:06:00Z",
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro",
      ...
    }
  ]
}
```

### Collection point photos for drivers

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/driver/collection-points/{id}/photos` | The point's site photos |
| GET | `/api/driver/collection-points/{id}/photo-gallery` | The point, its site photos and every driver photo filed under it |
| GET | `/api/driver/collection-points/{id}/job-photos` | The same, with the full point record |
| GET | `/api/driver/jobs/{id}/collection-point-photos` | The same for the point of one of the driver's jobs |

They answer for a point in any company the driver belongs to: no `X-Company-ID` is needed (see Company Context); a point of another company answers 404 `"collection point not found"`. On a route job, `GET /api/driver/trips/{stop id}` has the stop's site photos in `reference_photos`. Driver photos here are every driver's at the point, on any job.

### GET /api/driver/collection-points/{id}/photos
```json
// Response
{"photos": [{"id": "sph_001", "collection_point_id": "cp_001", "public_url": "https://storage.googleapis.com/.../sites/...", "caption": "Blue gate on left side", "sort_order": 0, "created_at": "2026-08-01T10:00:00Z", ...}]}
```

### GET /api/driver/collection-points/{id}/photo-gallery
```json
// Response
{
  "collection_point": {"id": "cp_001", "name": "Downtown Depot", "address": "...", "area_name": "...", "latitude": 35.68, "longitude": 139.76},
  "reference_photos": [{"id": "sph_001", "public_url": "...", "caption": "Entrance", "uploaded_at": "2026-08-01T10:00:00Z", "uploaded_by": "usr_a1b2c3d4"}],
  "work_photos": [{"id": "ph_001", "job_id": "job_011", "phase": "after", "public_url": "...", "uploaded_at": "2026-09-15T10:06:00Z", "latitude": 35.68, "longitude": 139.76}],
  "work_photo_count": 1
}
```
Work photos are `after` before `before`, each newest first. `GET /api/driver/jobs/{id}/collection-point-photos` answers the same, with a `job` (`id`, `title`, `status`, `collection_point_id`) and the point's `id`, `name`, `address` and `area_name`; a job with no point answers `{"message": "job not linked to a collection point", "reference_photos": [], "work_photos": [], "work_photo_count": 0}`. `GET /api/driver/collection-points/{id}/job-photos` answers `collection_point` (the full record), `photos` (the driver photos, full records) and `reference_photos` (the site photos).

### Site photos for admins

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/admin/collection-points/{id}/reference-photos` | Upload a site photo (the same as `POST /api/dispatch/collection-points/{id}/photos`) |
| DELETE | `/api/admin/collection-points/{id}/reference-photos/{photoId}` | Delete a site photo (the same as the dispatch delete) |
| GET | `/api/admin/collection-points/{id}/reference-photos` | The point (`id`, `name`, `address`), its site photos and their `count` |

To delete several at once, use `POST /api/dispatch/collection-points/{id}/photos/batch-delete`.

---

### Trip Tracking

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/driver/trips/start` | Start GPS trip |
| GET | `/api/driver/trips` | List trips |
| GET | `/api/driver/trips/{id}` | Get trip detail |
| POST | `/api/driver/trips/{id}/ping` | Send location ping |
| POST | `/api/driver/trips/{id}/ping/batch` | Batch send pings |
| POST | `/api/driver/trips/{id}/arrive` | Mark arrival |
| POST | `/api/driver/trips/{id}/complete` | Complete trip |
| POST | `/api/driver/trips/{id}/cancel` | Cancel trip |
| GET | `/api/driver/trips/{id}/pings` | Get all pings for trip |
| POST | `/api/driver/trips/{id}/photos` | Upload a before or after photo of a pickup (`{id}`: trip or stop id) |
| GET | `/api/driver/trips/{id}/photos` | List a pickup's photos (`{id}`: trip or stop id) |
| POST | `/api/driver/jobs/{id}/stops/{stopId}` | Set a stop's status on a route job |

For a job on a route, follow [A Route Job, Step by Step](#driver-a-route-job-step-by-step).

### POST /api/driver/trips/start
```json
// Request
{"job_id": "job_011", "latitude": 35.6762, "longitude": 139.6503}
```
```json
// Response (201)
{"trip": {"id": "trp_001", "driver_id": "usr_d001", "job_id": "job_011", "status": "en_route", "started_at": "2026-09-15T09:00:00Z", ...}, "next_ping_ms": 3000}
```
`job_id` is required (400 without it), and the job must be assigned to the driver (403) and open (409 `"this job is completed"`). It puts the job `in_progress` and the driver `on_job`. A second live trip: see A Route Job, step 1.

### GET /api/driver/trips
List all trips for the driver, with optional filters and enrichment.

**Query Parameters:**

| Param | Type | Description |
|-------|------|-------------|
| `status` | string | Filter by trip status: `en_route`, `arrived`, `in_progress`, `completed`, `cancelled` |
| `job_id` | string | Filter by job ID. For a job on a route, `trips` holds the job's stops instead, 1 per stop in the admin's order, each with its own `id` and `status`: see A Route Job, Step by Step |
| `limit` | integer | Results per page (default 20, max 500) |
| `offset` | integer | Pagination offset (default 0) |

Both filters can be combined: `?status=completed&job_id=job_011`

**Response includes:**
- Trip details (id, status, timestamps, coordinates, distance)
- Job information (title, address)
- Collection point information (id, name, address)
- **Photos** (before/after) — all photos the driver uploaded at this collection point for this specific trip, organized by collection point with accumulated history

```json
// GET /api/driver/trips?status=completed&limit=10
// Response
{
  "trips": [
    {
      "id": "trp_001",
      "driver_id": "usr_d001",
      "job_id": "job_011",
      "status": "completed",
      "started_at": "2026-09-15T09:00:00Z",
      "arrived_at": "2026-09-15T09:15:00Z",
      "completed_at": "2026-09-15T09:45:00Z",
      "start_lat": 35.6762,
      "start_lng": 139.6503,
      "end_lat": 35.6586,
      "end_lng": 139.7454,
      "distance_meters": 9500,
      "duration_seconds": 2700,
      "job_title": "Pickup at Tokyo Tower",
      "job_address": "4-2-8 Shiba-koen",
      "photos": [
        {
          "id": "ph_001",
          "job_id": "job_011",
          "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/...",
          "phase": "before",
          "content_type": "image/jpeg",
          "size_bytes": 245000,
          "latitude": 35.6586,
          "longitude": 139.7454,
          "exif_taken_at": "2026-09-15T09:06:00Z",
          "exif_make": "Apple",
          "exif_model": "iPhone 15 Pro",
          ...
        }
      ],
      "collection_point_id": "cp_003",
      "collection_point_name": "Tokyo Tower North",
      "collection_point_address": "4-2-8 Shiba-koen"
    }
  ]
}
```

### GET /api/driver/trips/{id}
Get details for a specific trip with full enrichment. `{id}` may also be a stop's id from `GET /api/driver/trips?job_id=`: the answer is then about that stop (with `stop`), on the driver's latest trip on its job.

**Response includes:**
- `trip`; for a stop's id also `stop`
- `job_title`, `job_address`, `collection_point_name`, `collection_point_address`
- `reference_photos`: the point's site photos
- `proof_photos`: the driver's photos on the job (for a stop: at the stop)
- `stats`: `ping_count`, `first_ping`, `last_ping`, `avg_speed`, `max_speed` (m/s)

```json
// Response
{
  "trip": {
    "id": "trp_001",
    "driver_id": "usr_d001",
    "job_id": "job_011",
    "status": "en_route",
    "started_at": "2026-09-15T09:00:00Z",
    "arrived_at": null,
    "completed_at": null,
    "start_lat": 35.6762,
    "start_lng": 139.6503,
    ...
  },
  "job_title": "Pickup at Tokyo Tower",
  "job_address": "4-2-8 Shiba-koen",
  "collection_point_name": "Tokyo Tower North",
  "collection_point_address": "4-2-8 Shiba-koen",
  "reference_photos": [{"id": "sph_005", "public_url": "...", "caption": "Blue gate", ...}],
  "proof_photos": [{"id": "ph_001", "phase": "before", "public_url": "...", "exif_taken_at": "2026-09-15T09:06:00Z", ...}],
  "stats": {"trip_id": "trp_001", "ping_count": 42, "first_ping": "2026-09-15T09:00:05Z", "last_ping": "2026-09-15T09:30:00Z", "avg_speed": 5.3, "max_speed": 11.2}
}
```

### POST /api/driver/trips/{id}/ping
Short keys save bytes; the long names (`latitude`, `longitude`, `accuracy`, `speed`, `heading`, `altitude`, `battery_level`, `timestamp`) are read too. `spd` is in m/s. The body may be gzipped (`Content-Encoding: gzip`).
```json
// Request
{"lat": 35.6762, "lng": 139.6503, "acc": 10.5, "spd": 8.3, "hdg": 180, "alt": 40, "batt": 85, "ts": "2026-09-15T09:30:00Z"}
```
```json
// Response
{"ok": true, "ping_count": 42, "stored": true, "next_ping_ms": 5000}
```
A ping less than 3m from the last one and within 30 seconds of it is not stored (`stored` false), but still moves the driver on the live map. `next_ping_ms` is when to send the next: 15000 when stopped, 10000 under 3m/s, 5000 under 8m/s, 3000 under 16m/s, else 2000. A trip that has ended: 409 `"this trip has ended (completed)"`.

### POST /api/driver/trips/{id}/ping/batch
Pings saved while offline, oldest first, in the same form; may be gzipped.
```json
// Request
{
  "pings": [
    {"lat": 35.6762, "lng": 139.6503, "spd": 8.3, "ts": "2026-09-15T09:30:00Z"},
    {"lat": 35.6770, "lng": 139.6510, "spd": 7.9, "ts": "2026-09-15T09:30:05Z"}
  ]
}
```
```json
// Response
{"ok": true, "ping_count": 44, "stored": 2, "skipped": 0, "next_ping_ms": 5000}
```

### POST /api/driver/trips/{id}/arrive
Request (optional): `{"latitude": ..., "longitude": ...}`.
```json
// Response
{"trip": {"id": "trp_001", "status": "arrived", "arrived_at": "2026-09-15T09:45:00Z", ...}}
```

### POST /api/driver/trips/{id}/complete
```json
// Request (all optional)
{"latitude": 35.6586, "longitude": 139.7454, "notes": "Collected all bags"}
```
```json
// Response
{"trip": {"id": "trp_001", "status": "completed", "completed_at": "2026-09-15T10:00:00Z", ...}, "stats": {"trip_id": "trp_001", "ping_count": 42, ...}}
```
The driver becomes `online`.

### POST /api/driver/trips/{id}/cancel
No request body.
```json
// Response
{"trip": {"id": "trp_001", "status": "cancelled", ...}}
```
The driver becomes `online`.

### GET /api/driver/trips/{id}/pings
Query param: `after` (RFC3339: only later pings). Also `GET /api/dispatch/trips/{id}/pings` for admins and dispatchers.
```json
// Response
{
  "pings": [
    {
      "id": "png_001",
      "trip_id": "trp_001",
      "driver_id": "usr_d001",
      "latitude": 35.6762,
      "longitude": 139.6503,
      "accuracy": 5.0,
      "speed": 8.3,
      "heading": 180,
      "altitude": 40,
      "battery_level": 85,
      "timestamp": "2026-09-15T09:30:00Z",
      "created_at": "2026-09-15T09:30:01Z",
      ...
    }
  ],
  "trip": {"id": "trp_001", ...}
}
```

---

## Live Tracking (Admin/Dispatcher)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/dispatch/trips` | List all trips (filterable) |
| GET | `/api/dispatch/trips/active` | All active trips with driver info |
| GET | `/api/dispatch/trips/live` | SSE stream of live location updates |
| GET | `/api/dispatch/trips/{id}/pings` | Ping history for a trip |

### GET /api/dispatch/trips

List trips with optional filters.

**Query parameters:**

| Param | Type | Description |
|-------|------|-------------|
| `status` | string | Filter by trip status: `en_route`, `arrived`, `in_progress`, `completed`, `cancelled` |
| `job_id` | string | Filter by job ID — returns all trips for a specific job |
| `limit` | int | Max results (default 20, max 500) |
| `offset` | int | Pagination offset |

**Trip statuses:**

| Status | Description |
|--------|-------------|
| `en_route` | Driver is traveling to the collection point |
| `arrived` | Driver has arrived at the collection point |
| `in_progress` | Collection is actively being performed |
| `completed` | Trip finished successfully |
| `cancelled` | Trip was cancelled |

```json
// GET /api/dispatch/trips?status=en_route
{
  "trips": [
    {
      "id": "12882dcad73c...",
      "driver_id": "abc...",
      "job_id": "def...",
      "status": "en_route",
      "started_at": "2026-09-29T08:00:00Z",
      "start_lat": 35.6762,
      "start_lng": 139.6503,
      "driver_first_name": "Tanaka",
      "driver_last_name": "Yuki",
      "driver_email": "yuki@example.com",
      "job_title": "Shibuya Ward Collection",
      "job_address": "1-24-12 Shibuya",
      ...
    }
  ]
}
```

### GET /api/dispatch/trips/active
The company's live trips (`en_route`, `arrived`, `in_progress`), newest first, with the driver and the job. The same list is the live stream's `init` event.
```json
// Response
{
  "trips": [
    {
      "id": "trp_001",
      "driver_id": "usr_d001",
      "job_id": "job_011",
      "status": "en_route",
      "started_at": "2026-09-15T09:00:00Z",
      "first_name": "Kenji",
      "last_name": "Yamada",
      "email": "kenji@example.com",
      "avatar_url": "",
      "last_known_lat": 35.6810,
      "last_known_lng": 139.6900,
      "last_location_at": "2026-09-15T09:35:00Z",
      "job_title": "Pickup at Tokyo Tower",
      "job_address": "4-2-8 Shiba-koen",
      "job_lat": 35.6586,
      "job_lng": 139.7454,
      "job_route_id": "rt_001",
      ...
    }
  ]
}
```

### GET /api/dispatch/trips/live
Server-Sent Events: the live positions of the company's drivers, as the Live page shows them. Sign in with the console session (a browser's `EventSource` sends the cookie) or a JWT as `?key=<JWT>` (`EventSource` cannot send headers) or `Authorization: Bearer <JWT>`. An API key is refused (403): see Authentication.

Each event's `data` is `{"type": "<event>", "data": {...}}`. A comment line `: keepalive` comes every 15 seconds.

| Event | When | `data` |
|-------|------|--------|
| `init` | On connecting | The live trips, as `GET /api/dispatch/trips/active` |
| `trip_start` | A driver starts a trip | `trip`, `driver_id`, `driver_name`, `job_title`, `job_address`, `job_lat`, `job_lng`, `route_id` |
| `ping` | A driver's position | `trip_id`, `driver_id`, `lat`, `lng`, `spd` (m/s), `ts`; a single ping adds `hdg`, `batt`, `stored`; a batch adds `batch` true and `batch_size` |
| `trip_arrive` | A trip is marked arrived | the trip |
| `trip_complete` | A trip is completed | `trip`, `driver_id` |
| `trip_cancel` | A trip is cancelled, or ended by the server (a job ongoing for more than 3 days; a driver removed or disabled) | `trip`, `driver_id` |

```
event: ping
data: {"type":"ping","data":{"trip_id":"trp_001","driver_id":"usr_d001","lat":35.6810,"lng":139.6900,"spd":6.9,"hdg":180,"batt":85,"ts":"2026-09-15T09:35:00Z","stored":true}}
```
```js
const es = new EventSource('/api/dispatch/trips/live'); // in the console, with its session
es.addEventListener('ping', (e) => { const p = JSON.parse(e.data).data; /* move p.driver_id to p.lat, p.lng */ });
```

### GET /api/dispatch/trips/{id}/pings
Query params: `limit` (default 1000)
```json
// Response
{
  "pings": [
    {"id": "png_001", "latitude": 35.6762, "longitude": 139.6503, "speed": 25.0, "heading": 180, "recorded_at": "2026-09-15T09:30:00Z"},
    {"id": "png_002", "latitude": 35.6770, "longitude": 139.6510, "speed": 28.5, "heading": 178, "recorded_at": "2026-09-15T09:30:05Z"}
  ]
}
```

---

## Geo (Admin/Dispatcher)

Map services through the server: OSRM for routes and distance tables, Nominatim (OpenStreetMap) for addresses. Each is called at most once a second, and answers are cached for 24hr. The upstream answer is passed through as it comes. When the service does not answer: 502 `"the map service did not answer"`.

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/geo/route` | Driving route through points (OSRM `route`) |
| GET | `/api/geo/table` | Driving times and distances between points (OSRM `table`) |
| GET | `/api/geo/reverse` | The address at a point (Nominatim `reverse`) |
| GET | `/api/geo/search` | The point of an address (Nominatim `search`, top hit) |

### GET /api/geo/route and /api/geo/table
Query param: `coords`, 2 to 100 points as `lng,lat` separated by `;` (longitude first)
```
GET /api/geo/route?coords=139.7016,35.6580;139.6917,35.6895
```

### GET /api/geo/reverse
Query params: `lat`, `lon`
```
GET /api/geo/reverse?lat=35.658&lon=139.701
```

### GET /api/geo/search
Query param: `q`, 4 to 300 characters
```
GET /api/geo/search?q=1-24-12+Shibuya,+Tokyo
```

---

## API Keys

| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/api/keys` | Session/JWT | Create API key |
| GET | `/api/keys` | Session/JWT | List your API keys |
| DELETE | `/api/keys/{id}` | Session/JWT | Revoke API key |
| GET | `/api/admin/keys` | Admin | List all API keys |
| DELETE | `/api/admin/keys/{id}` | Admin | Revoke any API key |
| POST | `/api/admin/users/{id}/create-key` | Admin | Create key for a user |

A person has at most 10 active keys: another is 409 `"maximum API keys reached (revoke an existing key first)"`. A key acts only in the company it was made in (the company the request acted in). Keys are for the driver API: see the table under Authentication.

### POST /api/keys
```json
// Request (both optional)
{"name": "Mobile App", "expires_in": "90d"}
```
`name` defaults to `default`. `expires_in`: `7d`, `30d`, `90d`, `1y`, or leave it out for a key that does not expire; anything else is 400.
```json
// Response (201)
{
  "key": "gomi_3f9a...(64 hex)",
  "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
  "name": "Mobile App",
  "prefix": "gomi_3f9a1c2b",
  "expires": "2026-12-14T10:00:00Z",
  "message": "Save this key now. It will not be shown again."
}
```
The full `key` is returned only here; the server keeps only its hash.

### GET /api/keys
Your own keys, newest first, revoked ones included (`revoked` 1).
```json
// Response
{
  "keys": [
    {"id": "a1b2...", "user_id": "usr_d001", "name": "Mobile App", "key_prefix": "gomi_3f9a1c2b", "last_used_at": "2026-09-15T14:30:00Z", "expires_at": null, "revoked": 0, "created_at": "2026-09-15T10:00:00Z"}
  ]
}
```

### DELETE /api/keys/{id}
Revokes one of your own keys. Any other id: 404 `"key not found"`.
```json
// Response
{"message": "key revoked"}
```

### GET /api/admin/keys
The keys made in the active company, newest first, with their owner. Query params: `limit`, `offset`.
```json
// Response
{
  "keys": [
    {"id": "a1b2...", "user_id": "usr_d001", "name": "Mobile App", "key_prefix": "gomi_3f9a1c2b", "last_used_at": null, "expires_at": null, "revoked": 0, "created_at": "2026-09-15T10:00:00Z", "user_email": "kenji@example.com", "user_first_name": "Kenji", "user_last_name": "Yamada", "user_avatar_url": ""}
  ]
}
```

### DELETE /api/admin/keys/{id}
Revokes a key made in the active company (any other: 404).
```json
// Response
{"message": "key revoked"}
```

### POST /api/admin/users/{id}/create-key
A key for a member of the active company, shown once. The body is optional and reads as `POST /api/keys`: `name` (default `admin-generated`) and `expires_in`. The 10-key limit applies, and the audit log records `api_key_created_admin` under the admin, naming the member.
```json
// Request (optional)
{"name": "Driver tablet", "expires_in": "30d"}
```
```json
// Response (201)
{
  "key": "gomi_9c1e...(64 hex)",
  "id": "f0e1d2c3...",
  "name": "Driver tablet",
  "prefix": "gomi_9c1e7a0b",
  "expires": "2026-12-13T11:00:00Z",
  "user_id": "usr_d001",
  "user_name": "Kenji Yamada"
}
```

---

## Waste Types

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/waste-types` | List waste types |
| GET | `/api/waste-types?country=JP` | Filter by country |

### GET /api/waste-types
```json
// GET /api/waste-types?country=JP
// Response
{
  "waste_types": [
    {"id": "wt_001", "name": "Burnable", "name_local": "燃えるゴミ", "color": "#e74c3c", "icon": "🔥", "country_code": "JP"},
    {"id": "wt_002", "name": "Non-burnable", "name_local": "燃えないゴミ", "color": "#3498db", "icon": "🧊", "country_code": "JP"},
    {"id": "wt_003", "name": "Recyclable", "name_local": "リサイクル", "color": "#27ae60", "icon": "♻️", "country_code": "JP"},
    {"id": "wt_004", "name": "Oversized", "name_local": "粗大ゴミ", "color": "#f39c12", "icon": "📦", "country_code": "JP"}
  ]
}
```

---

## Admin Photos Search

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/admin/photos` | Search photos across all jobs |

### GET /api/admin/photos
Query params: `job_id`, `driver_id`, `phase`, `taken_after`, `taken_before`, `limit`, `offset`

The active company's driver photos, newest upload first. All filters are optional. `taken_after` and `taken_before` (RFC3339) compare the time in the image (`exif_taken_at`): a photo with none is left out when either is set.
```
GET /api/admin/photos?driver_id=usr_d001&phase=after&taken_after=2026-09-01T00:00:00Z&limit=50
```
```json
// Response
{
  "photos": [
    {
      "id": "ph_001",
      "job_id": "job_011",
      "job_title": "Pickup at Tokyo Tower",
      "driver_id": "usr_d001",
      "driver_first_name": "Kenji",
      "driver_last_name": "Yamada",
      "driver_email": "kenji@example.com",
      "phase": "after",
      "public_url": "https://storage.googleapis.com/gomi_storage_public/jobs/...",
      "content_type": "image/jpeg",
      "size_bytes": 245000,
      "latitude": 35.6586,
      "longitude": 139.7454,
      "exif_taken_at": "2026-09-15T10:30:00Z",
      "exif_make": "Apple",
      "exif_model": "iPhone 15 Pro",
      "collection_point_id": "cp_003",
      "uploaded_at": "2026-09-15T10:31:00Z",
      ...
    }
  ]
}
```

---

## Audit Log (Admin)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/admin/audit/auth` | Auth event log (logins, logouts, etc.) |

### GET /api/admin/audit/auth
Query params: `limit`, `offset`, `event_type`, `status` (`success` or `error`), `user_id`

The active company's events, newest first. `user_id` and `email` are the person who acted. `total` counts all of the company's events, before filters; `event_types` lists the types found in the company's log.
```json
// GET /api/admin/audit/auth?limit=5
// Response
{
  "events": [
    {
      "id": "ae_001",
      "event_type": "login",
      "email": "kenji@example.com",
      "user_id": "usr_a1b2c3d4",
      "ip_address": "203.0.113.42",
      "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)...",
      "details": "",
      "location": "Tokyo, JP",
      "status": "success",
      "company_id": "comp_a1b2c3",
      "created_at": "2026-09-15T08:00:00Z"
    }
  ],
  "total": 500,
  "event_types": ["login", "jwt_issued", "job_created"]
}
```
Event types:
- Sign-in: `login`, `logout`, `login_failed` (status `error`), `jwt_issued`, `invite_sent`, `invite_accepted`
- Keys: `api_key_created`, `api_key_auto_created`, `api_key_created_admin`, `api_key_revoked`, `api_key_revoked_admin`
- People: `user_renamed`, `user_role_changed`, `user_status_changed`, `member_removed`, `user_disabled`, `user_enabled`
- Drivers: `clock_in`, `clock_out`
- Jobs: `job_created`, `job_updated`, `job_assigned`, `job_reassigned`, `job_rescheduled`, `job_cancelled`, `job_auto_cancelled`
- Collection points: `cp_created`, `cp_updated`, `cp_deleted`
- Routes: `route_created`, `route_updated`, `route_deleted`

Events with no company (signing in is not in a company: `login`, `login_failed`, and `logout` or `jwt_issued` sent with none) show in the log of every company the person is a member of. `invite_accepted` carries the inviting company and shows in its log only (rows from before 13 November 2026 carry none and show like sign-ins). A super admin with no company chosen sees every company's events.

---

## Common Patterns

### Pagination
List endpoints take `limit` (default 20; above 500 is read as 500; 0 or not a number is read as 20) and `offset` (default 0), unless the endpoint says otherwise (`GET /api/driver/nearby-jobs`: 1 to 100, default 10). `GET /api/keys`, `GET /api/me/companies`, `GET /api/dispatch/drivers`, `GET /api/dispatch/jobs/{id}/events`, `GET /api/dispatch/trips/active` and `GET /api/dispatch/route-assignments` return everything.
```
GET /api/dispatch/jobs?limit=10&offset=20
```

### Error Responses
```json
{"error": "description of what went wrong"}
```
HTTP status codes: 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (not found), 409 (conflict), 500 (server error).

### Status Values
- **Job status**: `pending`, `assigned`, `in_progress`, `completed`, `cancelled`
- **User status**: `online`, `offline`, `on_job`
- **Trip status**: `en_route`, `arrived`, `in_progress`, `completed`, `cancelled`
- **Route assignment status**: `scheduled`, `assigned`, `in_progress`, `completed`, `cancelled`
- **User roles**: `admin`, `dispatcher`, `driver`

