---
feature: Trip execution
slug: trip-execution
surface: delivery
consumer: flutter
version: 1.4.0
status: ready
brd_version: "1.3"
brd_ids: [DRIV-010, DRIV-011, DRIV-012, DRIV-013, DRIV-014, DRIV-015]
business_rules: [BR-19, BR-21, BR-22, BR-23, BR-24, BR-25, BR-26]
decisions: [DEC-07, DEC-08, TD-132, TD-139, TD-147, TD-149, TD-158]
schema_tables: [trips, trip_status_history, orders, order_status_history, earnings, commission_rules]
screens: "Not captured"
last_updated: 2026-11-09
---

# Trip execution — Flutter integration guide

## Version history

| Version | Date | Type | Summary | App action required |
|---------|------|------|---------|---------------------|
| 1.4.0 | 2026-11-09 | MINOR | `order.tracking.location` and the customer's tracking block now carry `freshness`, `distance_km`, `eta_minutes`, `calculated_at` and `source`, computed on the server from the driver's position (R06, R07, TD-183). Your request and response are unchanged. | None for the driver app. |

| 1.3.2 | 2026-11-02 | PATCH | Docs only: `POST /trips/{trip}/location` gets its own section with the real response and errors; the status table is filled; §2/§6 no longer say the earning is `pending` (it is `available` since 1.3.1); `trip.*` event `status` is a plain string. | None. |
| 1.3.1 | 2026-11-02 | PATCH | The driver's earning is written `available` (not `pending`) at arrival confirmation (DEC-11 answer, TD-158); she asks for the transfer in [earnings](earnings.md). | None: `amount_due_status` now reads `available`; do not special-case `pending`. |
| 1.3.0 | 2026-11-01 | MINOR | Arrival confirmation (DRIV-015): `POST /trips/{trip}/confirm-arrival` completes an arrived trip and records the driver's amount due; trip payloads add `arrival_confirmed_by`, `can_confirm_arrival`, `completed_at` and now fill `amount_due_status` / `net_earning`. | Show a confirm button while `can_confirm_arrival` is true; read the earning fields after completion. |
| 1.2.0 | 2026-11-01 | MINOR | A position sent on `PATCH /availability` during a live trip also reaches the customer's tracking preview. | None mandatory; either endpoint may carry the position. |
| 1.1.0 | 2026-10-29 | MINOR | Adds live trip location update for customer preview tracking. | Send authenticated coordinates during live trip stages and honor shared 429 budget. |
| 1.0.0 | 2026-10-28 | Initial | Cycle F contract. | Implement this flow. |

## Changelog

### 1.3.2 — 2026-11-02

- **Fixed (docs):** §2 and §6 still said the arrival earning is `pending` and that `pending → available` belongs to a later feature. Since 1.3.1 it is written `available` at once (TD-158).
- **Added (docs):** a full section for `POST /trips/{trip}/location` (request, real response, errors), the trip status table in §4, and the payload of `trip.updated` / `trip.offer` in §7: their `status` is the **plain trip status string** (`"to_provider"`), not a `{value,label}` object; refetch the trip for the label.
- **Breaking:** No. **App action required:** None.
- **Registry:** the guide was already `ready`; the registry row said `in-progress (tracking verification)` and is corrected.

### 1.3.1 — 2026-11-02

- **Changed:** the earning written by `confirm-arrival` is `available` straight away (`available_at` set); previously `pending`. Existing `pending` earnings of completed trips were migrated to `available`. `amount_due_status` and the trip payloads are otherwise unchanged.
- **Breaking:** No.
- **App action required:** None. The earnings screen and the transfer request are in [earnings](earnings.md).
- **BRD / decisions:** DRIV-017, DEC-11 (answered 2026-11-02), TD-158.

### 1.3.0 — 2026-11-01

- **Added:** `POST /api/v1/delivery/trips/{trip}/confirm-arrival` (`delivery.trips.confirm-arrival`, TD-149, resolves DEC-08). The driver, the provider or the customer may confirm an `arrived` trip; the first confirmation moves it to `completed` and writes the driver's earning. Repeats are 200 no-ops. Postman: `delivery.trips.confirm-arrival` › "200 Driver confirms arrival and the trip completes".
- **Added:** `arrival_confirmed_by` (`{value,label}` or null: `driver`, `provider`, `customer`), `can_confirm_arrival` (bool) and `completed_at` on the trip card and the trip details. `amount_due_status` (`{value,label}`: `pending`, `available`, `in_payout`, `paid`, `reversed`) and `net_earning` (SAR string) are no longer always null: they are set once the trip is completed.
- **App action required:** show "Confirm arrival" while `can_confirm_arrival` is true, refresh on `trip.updated` with `reason: arrival_confirmed` (another party may confirm first), and show the net earning on completed trips.

### 1.2.0 — 2026-11-01

- `PATCH /api/v1/delivery/availability` with `lat` and `lng` while the driver has a live trip (`accepted` to `to_customer`) publishes the same customer `order.tracking.location` event as `POST /trips/{trip}/location`. Without coordinates, or with no live trip, nothing is published. Both endpoints share the `dispatch-availability` 429 budget (TD-147). Trip status changes that also move the order (`to_provider`, `arrived`) now produce two identical customer stage events; clients ignore repeats. App action required: none mandatory.

### 1.1.0 — 2026-10-29

- Added `POST /api/v1/delivery/trips/{trip}/location` (`delivery.trips.location`): approved driver JWT, own live trip, required numeric `lat` -90..90 and `lng` -180..180, returns the persisted `recorded_at`. Postman: `delivery.trips.location` › "200 Driver location recorded". 404 hides foreign trip, 422 rejects invalid coordinates or inactive stage, 429 `RATE_LIMITED` shares the `dispatch-availability` budget with availability updates. App action required: send while the trip is live and use `Retry-After` to slow both update types. Location is not a history trail.

### 1.0.0 — 2026-10-28

- Added cycle F endpoints. App action required: integrate the flow and handle documented errors.

## 1. Business summary

An accepted driver advances sequentially to_provider → at_provider → picked_up → to_customer → arrived. Repeating the current status is an idempotent success; skipping or reversing is refused.

## 2. User flow and screens

Driver departure moves the order to on_the_way and arrival moves it to arrived. The driver becomes available for new offers on arrival (TD-132). Arrival confirmation (DRIV-015, TD-149): any one of driver, provider or customer confirms an `arrived` trip; the first completes it, records `arrival_confirmed_by` and creates one driver earning (`earnings.source_type = trip`, net = delivery fee − driver commission, BR-24/25). The earning is `available` at once (TD-158) and is never paid automatically (BR-26): she asks for the transfer in [earnings](earnings.md).

While the trip is live (`accepted` → `to_customer`) the app sends her position with `POST /trips/{trip}/location` (or with `PATCH /availability`); the customer sees it on the order's tracking preview.

## 3. Endpoints

Use an approved driver account and a bearer token for that app. Public record IDs are UUID strings (TD-19).

### POST /api/v1/delivery/trips/{trip}/status

status is required and must be to_provider, at_provider, picked_up, to_customer or arrived. Optional lat and lng must be provided together.

Postman: `delivery.trips.status` › "200 Driver starts trip to provider".

```json
{
    "status": "success",
    "message": "",
    "data": {
        "id": "01a19791-2d75-7049-b986-65234a97c0ff",
        "code": "TRP-xfuq83096338",
        "order_id": "01a19791-2d67-73f3-8009-a667cdedb6d1",
        "status": {
            "value": "to_provider",
            "label": "Driver on the way to provider"
        },
        "next_status": {
            "value": "at_provider",
            "label": "Driver arrived at provider"
        },
        "can_advance": true,
        "pickup": {
            "address": "Al Olaya Street, Riyadh",
            "lat": 24.7136,
            "lng": 46.6753,
            "provider": {
                "id": "01a19791-2d48-73a8-8226-80ea9c8fd2c1",
                "name": "Dr. Bertha Windler"
            }
        },
        "dropoff": {
            "address": "Al Nakheel Dist, Riyadh",
            "lat": 24.7743,
            "lng": 46.7386
        },
        "distance_km": "8.50",
        "est_duration_min": 22,
        "delivery_fee": "25.00",
        "arrival_confirmed_by": null,
        "can_confirm_arrival": false,
        "amount_due_status": null,
        "net_earning": null,
        "completed_at": null,
        "vehicle": {
            "id": "01a19791-2d70-72fc-b718-15c3288b110d",
            "make_model": "Toyota Yaris",
            "plate_number": "CAR-pmxw05092074",
            "vehicle_type": "car"
        },
        "timeline": [
            {
                "status": {
                    "value": "to_provider",
                    "label": "Driver on the way to provider"
                },
                "at": "2026-11-01T14:43:56+00:00"
            }
        ],
        "cancel_reason": null
    }
}
```

| HTTP | error_code | Meaning |
|------|------------|---------|
| 401 | `UNAUTHENTICATED` | Missing or expired token |
| 403 | `PERMISSION_DENIED` | Token issued by another app |
| 403 | `ACCOUNT_INACTIVE` | Account is not approved; inspect account_status and complete review. |
| 404 | `ENTITY_NOT_FOUND` | Trip not found |
| 422 | `—` | Invalid trip status |
| 422 | `INVALID_STATE_TRANSITION` | Invalid trip transition |
| 429 | `RATE_LIMITED` | Too many trip status transitions |

### POST /api/v1/delivery/trips/{trip}/location

Approved driver token; her own trip (`delivery.trips.location`). Shares the `dispatch-availability` rate limit with `PATCH /availability`.

| Field | Rules | Meaning |
|-------|-------|---------|
| `lat` | required, numeric, -90..90 | Current latitude in degrees |
| `lng` | required, numeric, -180..180 | Current longitude in degrees |

Accepted only while the trip is `accepted`, `at_provider`, `to_provider`, `picked_up` or `to_customer`. The position is stored on her driver profile (the latest one only, no history trail) and published to the customer's tracking room as `order.tracking.location` `{order_id, lat, lng, recorded_at, freshness, distance_km, eta_minutes, calculated_at, source}` after commit. The last five keys are calculated by the server (R06, R07, TD-183) and need nothing from the driver app; your request and response are unchanged. The budget is `dispatch_availability_per_minute` (default 60 a minute, dashboard setting) for location **and** availability together, so one position every 5–10 s leaves room. Stop sending at `arrived`.

Postman: `delivery.trips.location` › "200 Driver location recorded".

```json
{
    "status": "success",
    "message": "",
    "data": {
        "recorded_at": "2026-11-01T07:53:40.283+00:00"
    }
}
```

| HTTP | error_code | Meaning |
|------|------------|---------|
| 401 | `UNAUTHENTICATED` | Missing or expired token |
| 403 | `PERMISSION_DENIED` | Token issued by another app |
| 403 | `ACCOUNT_INACTIVE` | Account is not approved |
| 404 | `ENTITY_NOT_FOUND` | Unknown trip or another driver's (Postman: "404 Trip not found") |
| 422 | — (`data.errors`) | `lat` / `lng` missing or out of range (Postman: "422 Invalid coordinates") |
| 422 | `INVALID_STATE_TRANSITION` | The trip is not live (arrived, completed, cancelled…): stop sending (Postman: "422 Trip is not active") |
| 429 | `RATE_LIMITED` | Location + availability updates over budget; honor `Retry-After` and slow both (Postman: "429 Too many location updates") |

### POST /api/v1/delivery/trips/{trip}/confirm-arrival

Approved driver token; her own trip (another driver's trip or an integer id is 404). No body. Shares the `dispatch-status-transitions` rate limit with `POST /status`.

The trip must be `arrived` (she reported arrival with `POST /status`). The first confirmation from any party (driver, provider or customer) moves it to `completed`, sets `arrival_confirmed_by` and `completed_at`, and writes her earning: gross = the trip `delivery_fee`, minus the driver platform commission active at that moment (percent of the fee or a fixed amount, never more than the fee), status `available`. Payout is never automatic: the driver asks for a transfer ([earnings](earnings.md)) and an admin sends it by hand. The order stays `arrived`; the provider then starts the service. If the provider starts the service before anyone confirms, that counts as her confirmation.

Postman: `delivery.trips.confirm-arrival` › "200 Driver confirms arrival and the trip completes".

```json
{
    "status": "success",
    "message": "Arrival confirmed. The trip is complete.",
    "data": {
        "id": "01a19790-ba16-72f3-ac46-0cc477090952",
        "code": "TRP-dbgv62732121",
        "order_id": "01a19790-ba05-73dc-b90a-eeb214e60f54",
        "status": {
            "value": "completed",
            "label": "Completed"
        },
        "next_status": null,
        "can_advance": false,
        "pickup": {
            "address": "9831 Rozella Locks Apt. 604\nHannahhaven, ME 55556-0307",
            "lat": null,
            "lng": null,
            "provider": {
                "id": "01a19790-b9e1-713d-a89a-62841c686bc4",
                "name": "Pearlie Jones"
            }
        },
        "dropoff": {
            "address": "69744 Davis Square Suite 020\nLydiaborough, AL 24826",
            "lat": null,
            "lng": null
        },
        "distance_km": null,
        "est_duration_min": null,
        "delivery_fee": "25.00",
        "arrival_confirmed_by": {
            "value": "driver",
            "label": "Driver"
        },
        "can_confirm_arrival": false,
        "amount_due_status": {
            "value": "available",
            "label": "Available"
        },
        "net_earning": "22.50",
        "completed_at": "2026-11-01T14:43:26+00:00",
        "vehicle": {
            "id": "01a19790-ba03-711d-b1cd-c847965b2ebe",
            "make_model": "Toyota Yaris",
            "plate_number": "CAR-sagy44654754",
            "vehicle_type": "car"
        },
        "timeline": [
            {
                "status": {
                    "value": "completed",
                    "label": "Completed"
                },
                "at": "2026-11-01T14:43:26+00:00"
            }
        ],
        "cancel_reason": null
    }
}
```

| HTTP | error_code | Meaning |
|------|------------|---------|
| 200 | — | Already completed (by her or another party): the trip is returned unchanged (Postman: "200 Repeat confirmation returns the completed trip") |
| 401 | `UNAUTHENTICATED` | Missing or expired token |
| 403 | `PERMISSION_DENIED` | Token issued by another app |
| 403 | `ACCOUNT_INACTIVE` | Account is not approved |
| 404 | `ENTITY_NOT_FOUND` | Unknown trip or another driver's (Postman: "404 Another driver trip is hidden") |
| 422 | `INVALID_STATE_TRANSITION` | The trip has not reached `arrived` yet (Postman: "422 Driver has not reported arrival yet") |
| 429 | `RATE_LIMITED` | Too many confirmations; honor `Retry-After` (Postman: "429 Too many arrival confirmations") |

## 4. Statuses and enums

Trip `status` in HTTP responses is `{value, label}`; branch on `value` (schema `trips.status`).

| `status.value` | Meaning | Driver action | Order status it sets |
|----------------|---------|---------------|----------------------|
| `accepted` | She won the offer | Send `to_provider`; send location | — |
| `to_provider` | Driving to the provider | Send `at_provider`; send location | `on_the_way` |
| `at_provider` | At the provider's place | Send `picked_up`; send location | — |
| `picked_up` | Provider is in the car | Send `to_customer`; send location | — |
| `to_customer` | Driving to the customer | Send `arrived`; send location | — |
| `arrived` | At the customer's address | Confirm arrival while `can_confirm_arrival` | `arrived` |
| `completed` | Arrival confirmed by someone; earning written | Show `net_earning` | — (provider starts the service) |
| `cancelled` | Order cancelled or trip withdrawn | Leave the trip screen | — |

`searching` and `no_driver` exist only before a driver is assigned ([trip requests](trip-requests.md)). `next_status` is the one status `POST /status` accepts next, and `can_advance` says whether there is one.

## Data model

Tables: trips, trip_status_history, orders, order_status_history.

## 5. Dart models

Parse UUIDs as strings, monetary values as decimal strings, timestamps as ISO 8601, and nullable fields as nullable.

## 6. Business rules enforced by the backend

Driver departure moves the order to on_the_way and arrival moves it to arrived. The driver becomes available for new offers on arrival (TD-132). Arrival confirmation (DRIV-015, TD-149): any one of driver, provider or customer confirms an `arrived` trip; the first completes it, records `arrival_confirmed_by` and creates one driver earning (`earnings.source_type = trip`, net = delivery fee − driver commission, BR-24/25). The earning is `available` at once (TD-158) and is never paid automatically (BR-26). Location is accepted only on a live trip, and the customer sees only the position recorded after `accepted_at`.

## 7. Notifications and real-time events

`trip.updated` with `reason: arrival_confirmed` reaches the driver and the provider when anyone confirms arrival; the customer's tracking room gets `order.tracking.stage` with `transport.can_confirm_arrival: false`. Provider inbox notifications: trip_driver_approaching, trip_driver_arrived_provider, trip_provider_picked_up and trip_driver_arrived_customer. Customer also receives trip_provider_picked_up. Inbox data contains trip_id, order_id, status. `trip.updated` payload: `{trip_id, order_id, status, reason}`, where `status` is the **plain trip status string** (e.g. `"to_provider"`, not `{value,label}`) and `reason` is the status or `arrival_confirmed`; refetch `GET /trips/{trip}` for labels and flags. order.updated communicates order stage changes.

## 8. Localization and UI notes

Use localized labels and test Arabic RTL and English.

## 9. Integration checklist

- Handle loading, empty and error states and refresh after realtime events.
- Handle the documented errors and nullable fields.

## 10. Acceptance scenarios

DRIV-010, DRIV-011, DRIV-012, DRIV-013, DRIV-014: see the corresponding cycle F feature tests. AC-DRIV-015: `TripArrivalConfirmationTest` (driver, provider and customer confirmation, repeat no-op, refusal before arrival, implicit confirmation on service start, commission percent / fixed / none).

## 11. Open decisions and known limitations

DEC-07 is partly resolved: what happens when a driver cancels or does not show up after accepting is open. DEC-08 is resolved by TD-149. Open under TD-147: no stale-location age limit, no ETA / distance to the customer, and no self-travel live position for providers. DEC-11 is answered for earnings becoming `available` (immediately, TD-158); the payout cycle length stays a manual request-and-review flow. FCM push for arrival confirmation is not sent; apps refresh on `trip.updated`.
