# Driver app

How the driver app works with the API today. Shared rules (headers, errors, phone format, image compression) are in [common.md](common.md).

## Platform driver or company driver

Every driver is one of two kinds. The app never chooses it; it is set on the account.

| Kind | How to tell | Gets orders with `deliverySource` |
| --- | --- | --- |
| Platform driver | `Delivery.companyId` is `null` | `PLATFORM` |
| Company driver | `Delivery.companyId` is set | `STORE_FLEET`, only from restaurants linked to the same company |

## 1. Register

`POST /delivery` as `multipart/form-data`. No token.

| Field | Required | What to send |
| --- | --- | --- |
| `firstName`, `lastName` | yes | At least 2 characters each |
| `phone` | yes | `+{phoneCode} {nationalNumber}` ([common.md](common.md#phone-format)) |
| `email` | yes | Email |
| `password` | yes | At least 8 characters with upper case, lower case, a number and a symbol |
| `gender` | yes | `MALE` or `FEMALE` |
| `vehicle` | yes | `CAR` or `BICYCLE` |
| `identifyNumber` | yes | National ID or residence number |
| `licenseNumber` | yes | Driving licence number |
| `licenseExpiry`, `idExpiry` | yes | `YYYY-MM-DD`, today or later |
| `image` | yes | Driver photo (file) |
| `idFrontImage`, `idBackImage` | yes | ID photos (files) |
| `licenseFrontImage`, `licenseBackImage` | yes | Licence photos (files) |
| `transportCardImage` | yes | Transport Authority card (file) |
| `passportImage` | no | Passport photo (file). Optional; can be added later through a profile edit (section 4). |

- `cityId` is optional.
- There is no nationality. Remove the nationality dropdown from the register screen and do not call `GET /nationality`; that endpoint no longer exists. A `nationalityId` sent by an older version is ignored.
- Do not send `tierId`, `commissionType` or `commissionValue`; the API ignores them. Every new driver starts at the lowest tier.
- A missing photo returns `Missing required files: ...`. A past date returns `{field} must be today or a future date`.

The new driver is `PENDING` and not verified. The API sends an OTP to `phone`. Verify with:

```
POST /delivery/verify/{id}
{ "id": 1, "phone": "+966 512345678", "otp": "1234" }
```

## 2. Login

`POST /authentication/login`. The login field accepts an email or a phone; send only one of them.

```json
{ "role": "DELIVERY", "email": "driver@example.com", "password": "..." }
```

```json
{ "role": "DELIVERY", "phone": "+966 512345678", "password": "..." }
```

Decide on the device before calling the API:

| User typed | App does |
| --- | --- |
| Contains `@` and is a valid email | Send `email` only |
| Contains `@` but is not a valid email | Do not call the API. Show "Enter a valid email" / "أدخل بريداً إلكترونياً صحيحاً" |
| No `@`, matches `+{code} {8–10 digits}` | Send `phone` only |
| Anything else | Do not call the API. Show "Enter a valid email or phone number" / "أدخل بريداً إلكترونياً أو رقم جوال صحيح" |

Never put email text in `phone`. If the app still sends an email (value with `@`) in `phone`, the API moves it to `email`. A value that is neither a valid phone nor a valid email returns `400` `Enter a valid email or phone number` — not `email must be an email` and not the phone-format hint. Prefer validating on the device and not calling the API (table above). Sending both keys returns `400` `You can only login with email or mobile phone`.

Login results:

| Response | Meaning | Screen |
| --- | --- | --- |
| `200` and `data.user.accountNotice` is `null` | Logged in | Home |
| `200` and `data.user.accountNotice.action` is `"UPDATE_DOCUMENTS"` | Logged in, but suspended because a document expired (section 9) | Profile, with the notice on top |
| `412` with `data.deliveryId`, `data.phone` | Phone not verified | OTP step |
| `401` with `data.status: "PENDING"` | Not approved by admin yet | Waiting screen |
| `401` with `data.status: "DENIED"` | Inactive for another reason | Show `message` |

Choose the screen from the status code and the fields, never from the message text.

## 3. Profile

`GET /user/profile` with the driver token. Account fields are on the root; driver fields are on `data.Delivery`.

| Screen | Read from |
| --- | --- |
| Photo, first name, last name, email, phone | `image`, `firstName`, `lastName`, `email`, `phone` |
| Gender | `Delivery.gender` (`MALE` / `FEMALE`) |
| ID number, licence number | `Delivery.identifyNumber`, `Delivery.licenseNumber` |
| Licence expiry, ID expiry | `Delivery.licenseExpiry`, `Delivery.idExpiry` |
| Vehicle type | `Delivery.vehicle` (`CAR` / `BICYCLE`) |
| Document photos | `Delivery.idFrontImage`, `idBackImage`, `licenseFrontImage`, `licenseBackImage`, `transportCardImage`, `passportImage` |
| Account status | `Delivery.status`, `Delivery.suspendReason` |
| Available switch | `Delivery.readyToReceiveOrders` |

### Tier and rating (read-only)

The app does not know the tiers and does not calculate one. Admin can rename a tier or change the rating it needs. `GET /user/profile` returns the current result on `data.Delivery`:

```json
{
  "ratingAvg": 4.6,
  "ratingQuality": 4.8,
  "ratingCommitment": 4.5,
  "ratingCommunication": 4.5,
  "companyId": null,
  "DriverTier": {
    "id": 3, "code": "...", "nameEn": "...", "nameAr": "...", "namePl": "...", "nameUk": "...",
    "freelancePlatformCommissionType": "PERCENTAGE",
    "freelancePlatformCommissionValue": 15,
    "companyDriverEarningType": "PERCENTAGE",
    "companyDriverEarningValue": 60
  }
}
```

- Badge: the name in the app language (`nameAr`, `nameEn`, `namePl`, `nameUk`). Do not branch on `code`.
- Hide the badge when `DriverTier` is `null`.
- Rating: `ratingAvg` with 1 decimal. The three others are an optional breakdown (service quality, punctuality, communication). Hide a row that is `null`.
- The driver cannot change the rating or the tier. The tier moves up and down with the rating, and admin or the company can also set it. The next `GET /user/profile` is what the app shows.

### Tier terms (read-only)

The tier sets how the delivery fee is split (section 8). Which pair of fields applies depends on `Delivery.companyId`:

| Driver | Fields | Meaning |
| --- | --- | --- |
| `companyId` is `null` (platform driver) | `freelancePlatformCommissionType`, `freelancePlatformCommissionValue` | What the platform takes from each delivery fee |
| `companyId` is set (company driver) | `companyDriverEarningType`, `companyDriverEarningValue` | The driver's share of the fee left after the company's platform commission |

Show one line under the tier badge. Hide it when the pair's `Type` or `Value` is `null`.

| Driver | `Type` | Line |
| --- | --- | --- |
| Platform | `PERCENTAGE` | "Platform commission: {value}% of each delivery fee" |
| Platform | `FIXED` | "Platform commission: {value} per order" |
| Company | `PERCENTAGE` | "Your share: {value}% of the delivery fee after your company's commission" |
| Company | `FIXED` | "Your share: {value} per order" |

The company's own commission is not on the driver's profile. Do not work out a final amount.

### Tier change notification

Every change of the driver's tier, and every change of the tier's commission, adds an in-app notification (`GET /app-notification`, in the `Locale` language) and sends a push with `data: { "type": "DRIVER_TIER_CHANGED" }`. The push title and body are always in English. A new driver's first tier sends nothing. The change applies to new orders only.

On a push with `data.type === "DRIVER_TIER_CHANGED"`, reload `GET /user/profile` so the badge and the terms line are current.

### Assigned vehicle (read-only)

A company assigns one of its vehicles to a driver from its dashboard:

```json
{
  "AssignedCompanyVehicle": {
    "id": 4, "brand": "Toyota", "model": "Hilux", "year": 2022, "color": "White",
    "plate": "ABC 1234", "seats": 2, "photo": "...", "status": "ACTIVE"
  }
}
```

Show brand, model, year, colour, plate and the photo when present. It is `null` for platform drivers and for company drivers without a vehicle; then show `Delivery.vehicle`.

### Document expiry warning

Use `licenseExpiry` and `idExpiry` to warn before the date, e.g. "Your licence expires on 2026-11-02". See section 9.

## 4. Edit profile (sent for review)

Changes to the profile are reviewed before they apply. Fill the form from section 3; every row is editable, including empty ones. Tier, rating, commission and vehicle assignment are not in the form.

```
POST /delivery/profile-edit-request      (multipart/form-data)
```

Send only the changed fields, with the names from section 3. Photos are file parts. Dates are `YYYY-MM-DD`, today or later.

| Driver | `data.status` after sending | Who reviews |
| --- | --- | --- |
| Company driver | `PENDING_COMPANY` | The company only |
| Platform driver | `PENDING_ADMIN` | Admin only |

```json
{ "message": "Profile edit sent for review", "data": { "id": 1, "status": "PENDING_COMPANY", "rejectionReason": null } }
```

- The profile does not change until the reviewer approves (`APPROVED`). Then reload `GET /user/profile`.
- A company driver's request can still turn into `PENDING_ADMIN` if the company is suspended or the driver leaves it before it reviews.
- `REJECTED` comes with `rejectionReason`. Show it.
- Load the latest request when the screen opens: `GET /delivery/profile-edit-request` (`data` is `null` if there is none).
- While the status is `PENDING_COMPANY` or `PENDING_ADMIN`, keep the form read-only.

| `message` (`en`) | `message` (`ar`) | Show |
| --- | --- | --- |
| Empty edit payload | بيانات التعديل فارغة | Nothing changed |
| A profile edit is already waiting for review | في طلب تعديل مستني المراجعة | The waiting state |
| Phone already in use | رقم الجوال مستخدم بالفعل | That phone |
| Email already in use | البريد الإلكتروني مستخدم بالفعل | That email |
| licenseExpiry / idExpiry must be today or a future date | same English text | That date |
| Your driving licence or ID has expired. Send the renewed expiry date and photos first, then you can edit the rest of your profile. | رخصة القيادة أو الهوية منتهية. أرسل تاريخ الانتهاء الجديد والصور المجددة أولاً، وبعدها تقدر تعدل باقي بياناتك. | Highlight the expired document rows (section 9) |

`PATCH /user/profile` and `PATCH /delivery` cannot change the driver's profile. For a driver they create the same review request (even if the body also sends `readyToReceiveOrders` — availability is updated separately; profile fields still go to review). Only a password change through `PATCH /user/profile` applies at once. Company drivers' requests show under the company portal **Edit requests** and trigger an in-app notice.

## 5. Availability and location

### Available switch

```
PATCH /delivery
{ "readyToReceiveOrders": true }
```

Only `readyToReceiveOrders` is used. `PATCH /delivery/{id}` for another driver returns `403`.

### Sharing the location

Orders go to the nearest drivers first, then the highest rated among them. The API only uses a location received in the last **10 minutes** (admin setting). Without a recent location the driver gets no assigned orders and cannot accept orders.

While the driver is available, send the location at least every **2 minutes**, and when they move more than about 200 m:

```
namespace: /location
header:     Authorization: Bearer {token}
event:      update_location
payload:    { "lat": 24.713552, "lng": 46.675296 }
```

The socket is not under `/api/v1`. It is the API host on `SOCKET_PORT`, namespace `/location`.

| Environment | URL |
| --- | --- |
| Production | `wss://api-back.deliverus.pl:1234/location` |
| Dev server | `ws://<server>:1234/location` |

- Send full decimals. Do not round.
- Every `GET /order` with `lat` and `lng` also counts as a location update.
- Stop sending when the driver switches off "available" or logs out.
- Keep sending while the app is in the background or the screen is off: an Android foreground service (with its visible notification) and the iOS background location mode. If the phone stops the updates, the location is stale after 10 minutes and the driver silently stops getting orders.
- Only driver accounts can send `update_location`. The socket sends no locations back to the driver app.

## 6. Available orders

```
GET /order?status=DELIVERY&lat={lat}&lng={lng}&page=1
```

`lat` and `lng` are required (the driver's real location, full decimals). Without them: `Delivery man must provide location`.

The list contains unassigned home-delivery orders the driver may take:

- Only orders the restaurant marked ready for a driver (`WAITING_DELIVERY_ACCEPTANCE`). Orders still being prepared are not shown.
- Platform drivers see `PLATFORM` orders; company drivers see `STORE_FLEET` orders of restaurants linked to their company.
- When the restaurant is in a zone drawn by admin, only drivers currently inside that zone see the order.
- Sorted nearest restaurant first. Each order has `Store.lat` and `Store.lng` for showing the distance. Parcel orders have no restaurant and come after them (see "Parcel orders" below).
- No tier delay. An eligible driver sees the order at once, whatever their tier. The push goes to the 20 nearest, then highest `ratingAvg`. The app does not hide or postpone an order.
- Orders the driver rejected before are not shown.
- A card order (`paymentMethod: "VISA"`) appears only once it is paid. This includes card parcels.
- Empty when the "available" switch is off, when the driver already has an order in progress, when the account is not active or not verified, when the driver's company is not active, or when the driver's tier (or company) has no commission set (section 8). Show the normal empty state.

### What to collect

Every order in `GET /order` and `GET /order?id={id}` (driver token) carries the amount to collect, ready to show:

```json
"paymentMode": "COLLECT_CASH",
"collectAmount": 70
```

| Order | `paymentMode` | `collectAmount` | Show on the order card and the delivery screen |
| --- | --- | --- | --- |
| Cash, 120 | `COLLECT_CASH` | `120` | **"Collect cash: 120"**, large and in the main colour |
| 120, customer paid 50 from the wallet, rest cash | `COLLECT_CASH` | `70` | **"Collect cash: 70"** |
| Card paid, or paid fully from the wallet | `PAID` | `0` | **"Paid — collect nothing"** |

- Show `collectAmount` as it is. Do not work it out from `paymentMethod`, `paymentStatus`, `totalPrice` or `finalPrice`.
- The driver never pays the restaurant at pickup, for any order, cash orders included. The platform settles with the restaurant. Do not show any "pay the restaurant" amount.
- Restaurant order: collect on delivery, from the customer. Parcel: collect at pickup, from the sender.

### Parcel orders

A customer can send a parcel. The customer picks a parcel size; the delivery fee is the fixed fee of that size, not the distance. Parcel orders are platform orders (`deliverySource: "PLATFORM"`), so only platform drivers get them.

On a parcel order `Store` is `null` and `ParcelOrder` holds the two points as `"lat,lng"` strings:

```json
"ParcelOrder": { "senderPoint": "24.7136,46.6753", "receiverPoint": "24.7743,46.7386" }
```

- Show the distance and the route from `senderPoint` (pickup) and `receiverPoint` (drop-off).
- Cash parcel: "Collect cash: {collectAmount}" at pickup, from the sender.
- Accept, reject and the status steps are the same as for restaurant orders.

### New order alert

When a restaurant marks an order ready for a driver (or a card order gets paid after that), the API sends a push to the 20 best-placed drivers who may take it (zone, distance, then rating). It skips drivers with the "available" switch off, drivers who already have an order in progress, drivers who rejected the order, and, for a cash order, drivers above the debt limit (section 8).

| Push event | On tap |
| --- | --- |
| `ORDER.DELIVERY.AVAILABLE` | Open the available orders list and reload it |

### Accept or reject

```
PATCH /order/{id}
{ "status": "ACCEPTED" }        or        { "status": "REJECTED" }
```

Accepting sets the driver on the order. A `WAITING_DELIVERY_ACCEPTANCE` order becomes `WAITING_DELIVERY`. Rejecting hides the order from this driver only.

Accepting runs the same checks as the list. Errors (`400`):

| `message` (`en`) | `message` (`ar`) | When |
| --- | --- | --- |
| This driver account is not active | حساب السائق ده مش مفعّل | Account not active or not verified |
| This driver is not available to receive orders | السائق ده مش متاح لاستقبال الطلبات | The "available" switch is off |
| This driver's company is not active | شركة السائق ده مش نشطة | Company suspended or removed |
| This order needs a platform driver | الطلب ده محتاج سائق من المنصة | Company driver on a `PLATFORM` order |
| This driver is not in the store's fleet company | السائق ده مش تبع شركة أسطول المطعم | Driver from another company |
| This store has no active fleet company | المطعم مش مربوط بشركة أسطول نشطة | Fleet order, restaurant has no active company |
| This driver's current location is unknown. ... | موقع السائق الحالي مش معروف. ... | No location in the last 10 minutes |
| This driver is outside the store's delivery zone | السائق ده برة زون التوصيل بتاعة المطعم | Driver left the zone |
| This order was already assigned to another driver | الطلب ده اتسند لسائق تاني بالفعل | Another driver accepted first, or the API assigned it at the same moment |
| This driver's tier has no commission set, so the driver can't take orders yet | شريحة السائق ده مالهاش عمولة متحددة، فمش هيقدر يستلم طلبات لسه | The tier has no commission (admin setup) |
| This driver's company has no platform commission set, so its drivers can't take orders yet | شركة السائق ده مالهاش عمولة منصة متحددة، فسواقينها مش هيقدروا يستلموا طلبات لسه | The company has no platform commission (admin setup, rare) |
| Your debt is over the allowed limit. Top up your wallet to take cash orders | مديونيتك تخطت الحد المسموح. اشحن محفظتك لتستلم طلبات الدفع النقدي | Cash order, and the driver's debt is above the debt limit (section 8) |

The API also refuses an order that already has a driver, and a driver who still has an order in progress. After any error, show `message` as returned and reload the list. Never compare `message` with a fixed string: it is translated by `Locale`. The tier and company cases are an admin setup issue; the driver cannot fix them.

## 7. My orders

Orders assigned to the driver (by accepting, or assigned by the restaurant or admin) are not in the available list. The Orders tab loads every in-progress status:

```
GET /order?status=WAITING_DELIVERY&status=HANDED_OVER&status=ON_THE_WAY&status=DRIVER_ARRIVED&lat={lat}&lng={lng}&page=1
```

- Repeat the `status` key per value. `status=A,B` returns `400`.
- Do not add `onGoing=true`; it drops `WAITING_DELIVERY`.

History: `GET /order?status=DELIVERED&lat={lat}&lng={lng}`. It returns only this driver's orders. `GET /order?id={id}` returns nothing for another driver's order.

Search: `GET /order?name={text}` (alias `search`). Digits match the order id as a prefix (`150` finds `1501`). Also matches customer/driver/store/product names, phone, note, and status/payment words.

Move the order forward, one step at a time (only the assigned driver can):

```
PATCH /order/{id}   { "status": "ON_THE_WAY" }  →  { "status": "DRIVER_ARRIVED" }  →  { "status": "DELIVERED" }
```

An order assigned by the restaurant arrives as `WAITING_DELIVERY`. Do not send `ACCEPTED` for it.

Marking an order `DELIVERED` settles the wallet exactly once, even if two requests arrive at the same time. If `PATCH /order/{id}` with `"status": "DELIVERED"` times out, send it again.

### Automatic assignment

If no driver accepts an order within **3 minutes** (admin setting), the API assigns the best available driver itself: free, available, recent location, in the zone, nearest, then highest rated. The driver does not accept it; it is already theirs.

| Push event | On arrival |
| --- | --- |
| `ORDER.DELIVERY.ASSIGN` | Reload the Orders tab and open the order |

The same push is sent when the restaurant or admin assigns the driver.

## 8. Wallet

### Earnings

The driver earns a share of the order's delivery fee. The split is fixed **when the driver takes the order** (accepts it, or is assigned), with the tier and company terms in force at that moment. Later changes only affect new orders.

**Platform driver (no company):** the tier sets the platform's commission.

```
platform commission = tier commission on the delivery fee
driver earning      = delivery fee − platform commission
```

**Company driver:** the company sets the platform's commission, and the tier sets the driver's share of what is left.

```
platform commission = company commission on the delivery fee
rest                = delivery fee − platform commission
driver earning      = tier share of the rest
company share       = rest − driver earning
```

Each commission is a percentage (`PERCENTAGE`) or a fixed amount per order (`FIXED`). A fixed amount larger than what it is taken from is capped, so nobody gets a negative amount. The customer never pays a commission on top of the fee. On a parcel the delivery fee is the parcel size's fee.

Example (fee 100, company commission 20%, tier share 60%): platform 20, driver 48 (60% of 80), company 32.

Two drivers can earn different amounts for the same order. Read earnings only from the wallet and its history. Never work them out from the order's `shipping` or from the tier.

### Balance and debt

The wallet has one balance, `currentBalance`. On a cash order the driver collects the cash from the customer (or the sender of a parcel), and only their earning is theirs. So after cash orders `currentBalance` is usually negative:

```
cash order 120, driver earning 17  →  balance −103  (debt 103)
```

−103 means the driver holds 103 that belongs to the platform. It is not an error and not money lost. New earnings and top-ups cover the debt first.

`GET /delivery/wallet` returns the wallet columns plus:

```json
{
  "currentBalance": 24,
  "available": 24,
  "debt": 0,
  "held": 0,
  "totalEarning": 340,
  "totalWithdrawn": 100,
  "collectedCash": 1200,
  "debtLimit": 500,
  "overDebtLimit": false
}
```

| Field | Meaning |
| --- | --- |
| `available` | Can be withdrawn: the balance when above 0, else `0` |
| `debt` | Owed to the platform: the balance below 0, as a positive number, else `0` |
| `held` | In open withdraw requests (already taken off the balance) |
| `debtLimit` | The most debt the driver may carry. `null` = no limit |
| `overDebtLimit` | `true` when `debt` is above `debtLimit` |

Show available, debt and held separately:

| State | Show |
| --- | --- |
| `debt` above 0 | مستحق عليك للمنصة / You owe the platform: `debt`, in a warning colour, with the "Top up wallet" button |
| `available` above 0 | الرصيد المتاح / Available balance: `available`, with the "Withdraw" button enabled |
| both 0 | Available balance 0.00, "Withdraw" disabled |
| `held` above 0 | "In withdraw requests: {held}" |
| `overDebtLimit` is `true` | A notice: "Top up to take cash orders" |

### Debt limit

The admin sets the most debt a driver may carry (`debtLimit`; 500 on staging). While the driver's debt is above it:

- The driver gets no push and no automatic assignment for cash orders.
- Accepting a cash order returns `400` with "Your debt is over the allowed limit. Top up your wallet to take cash orders" (translated by `Locale`). Show `message`.
- Paid orders (`paymentMode: "PAID"`) work as usual.

A top-up brings the driver back under the limit at once.

### Top up

The driver can top up any amount above 0. Take the payment through Moyasar for the amount the driver types, then send:

```
POST /delivery/wallet/topup
{ "paymentId": "<paid Moyasar payment id>" }
```

- The amount added is what Moyasar confirms was paid. It covers the debt first; the rest becomes available balance.
- Each payment id works **once**.
- Optional: put `metadata.deliveryManId` on the Moyasar payment. If it is set and is not this driver's id, the top-up is refused.
- `POST /delivery/payroll` is the same call (same body, same result), kept for older builds. New builds use `/delivery/wallet/topup`.

Example: balance −103. Top up 50 → −53. A card order with earning 17 → −36. Top up 60 → +24 available.

| Result | Status | `message` (`en`, translated by `Locale`) |
| --- | --- | --- |
| Paid | `200` | `payment successfully`; `data` is the wallet (same shape as `GET /delivery/wallet`) |
| Payment id already used, not paid, or for another driver | `400` | `Payment failed, please try again` |

After `200`, show the returned wallet. On `400`, show `message` and start a **new** payment. Never retry with the same `paymentId`.

A debt the driver paid by bank transfer is recorded by admin; it shows in the history as `DEBT_PAYMENT`.

### History

```
GET /ledger?page=1&limit=20
```

```json
{
  "data": [
    { "id": 121, "type": "CASH_COLLECTED", "amount": "-120", "balanceAfter": "-103", "orderId": 91, "reason": null, "reference": null, "createdAt": "2026-11-18T12:00:00.000Z" },
    { "id": 120, "type": "DRIVER_NET", "amount": "17", "balanceAfter": "17", "orderId": 91, "reason": null, "reference": null, "createdAt": "2026-11-18T12:00:00.000Z" }
  ],
  "total": 2
}
```

The driver only gets their own rows (`ownerType` / `ownerId` are ignored for drivers). Newest first; `limit` is at most 100. `amount` and `balanceAfter` are decimal strings.

| `type` | Show as | Sign |
| --- | --- | --- |
| `OPENING_BALANCE` | Opening balance | ± |
| `DRIVER_NET` | Earning – order #{orderId} | + |
| `CASH_COLLECTED` | Cash collected – order #{orderId} | − |
| `TOPUP` | Wallet top-up (`reference` = Moyasar payment id) | + |
| `DEBT_PAYMENT` | Debt payment (`reference` = bank transfer number) | + |
| `WITHDRAW_HOLD` | Withdraw requested | − |
| `WITHDRAW_RELEASE` | Withdraw rejected (returned) | + |
| `WITHDRAW_PAID` | Withdraw transferred | 0 |
| `ADJUSTMENT` | Adjustment by admin – {reason} | ± |

Show it as a "History" list under the wallet card. Take the sign and colour from `amount`.

### Bank accounts

The driver's accounts for withdrawals (`deliveryAccountId`). Driver token only; each driver sees and changes only their own.

| Call | Body / result |
| --- | --- |
| `GET /bank` | The bank list (names in the `Locale` language) for the picker |
| `GET /delivery-bank` | The driver's accounts |
| `POST /delivery-bank` | `{ "name", "bankId", "ownerName", "iban", "phone" }`, all required. The same IBAN twice returns `409` |
| `PATCH /delivery-bank/{id}` | Any of the fields above |
| `DELETE /delivery-bank/{id}` | Removes the account. Requests already sent keep their copy of it |

### Withdraw

```
POST /withdraw
{ "amount": 50, "deliveryAccountId": 3 }
```

- `amount` must fit the **available** balance. A driver with debt cannot withdraw. Do not send a request above `available`.
- The amount is held at once (`WITHDRAW_HOLD`, shown in `held`). Several open requests are allowed while their total fits.
- There is no automatic payout. Admin reviews the request and sends a bank transfer outside the app.
- Each request keeps a copy of the bank account at request time (`bankName`, `accountName`, `accountOwnerName`, `accountIban`, `accountPhone`).

| Result | Status | `message` (`en`, translated by `Locale`) |
| --- | --- | --- |
| Created | `201` | Decide by the status. Reload `GET /delivery/wallet` and the list |
| Above the available balance | `400` | `Not enough balance` |
| `deliveryAccountId` is not the driver's account | `400` | `Bank account not found` |

List the driver's requests with `GET /withdraw` (or `GET /withdraw/{id}`); only their own are returned.

| `status` | Show | Extra fields |
| --- | --- | --- |
| `PENDING_REVIEW` | Waiting for review | — |
| `APPROVED_AWAITING_TRANSFER` | Approved, bank transfer coming | — |
| `TRANSFERRED` | Transferred | `transferReference`, `transferredAt`: show both |
| `REJECTED` | Rejected; the amount is back in the available balance | `rejectReason`: show it |

Each status change after the request adds an in-app notification (`GET /app-notification`, in the `Locale` language) and sends a push with:

```json
{ "type": "WITHDRAW_STATUS", "withdrawId": "12", "status": "TRANSFERRED" }
```

The push title and body are in English. On a `WITHDRAW_STATUS` push, reload `GET /delivery/wallet` and the request.

### Push data

Two driver pushes carry a `data` field: `DRIVER_TIER_CHANGED` (section 3) and `WITHDRAW_STATUS` (above). Every other push has none.

## 9. Expired documents

Every day the API checks the licence and ID expiry dates of every driver.

| When | What happens |
| --- | --- |
| 30 days before the earliest expiry | One reminder email to the driver (and the company for a company driver) |
| A document has expired | Status `DENIED`, `suspendReason: "DOCUMENTS_EXPIRED"`, and the driver is logged out |
| A renewed date is saved (company, admin, or an approved edit request) | Status `ACTIVE` again at once |

The suspended driver can still log in, only to send the renewed documents. Login returns `accountNotice` in `data.user.accountNotice`, and `GET /user/profile` in `data.accountNotice`:

```json
{
  "accountNotice": {
    "reason": "DOCUMENTS_EXPIRED",
    "action": "UPDATE_DOCUMENTS",
    "expiredDocuments": ["licenseExpiry"],
    "message": "Your driving licence or ID has expired, so you can't receive orders. Send the renewed document from your profile; you can work again once it is approved."
  }
}
```

| Field | Use |
| --- | --- |
| `action` | `"UPDATE_DOCUMENTS"`: open the profile (edit screen) instead of home |
| `message` | Show as a note on top of the profile, in the `Locale` language |
| `expiredDocuments` | `licenseExpiry` and/or `idExpiry`. Highlight those rows and their photos (`licenseFrontImage`/`licenseBackImage`, `idFrontImage`/`idBackImage`) |

`accountNotice.reason` has one value: `DOCUMENTS_EXPIRED`. Which document expired is `expiredDocuments` (`licenseExpiry` and/or `idExpiry`), not a separate reason. `accountNotice` is `null` for every other driver, including a suspension that is not an expired document.

While suspended:

- The available list is empty and accepting returns `This driver account is not active`. Keep the driver on the profile; hide or disable the orders and the available switch.
- The renewal is a normal edit request (section 4): new expiry date plus new front and back photos for every expired document (`licenseExpiry` + `licenseFrontImage` + `licenseBackImage`, and/or `idExpiry` + `idFrontImage` + `idBackImage`). The API rejects any edit that does not include them (`400`, "Your driving licence or ID has expired…"), so the app should also keep Update disabled until they are filled. Other fields can be sent in the same request. It goes to the company first for a company driver, then admin.
- When admin approves, the account is `ACTIVE` again at once and `accountNotice` becomes `null`. Reload `GET /user/profile` when the app returns to the foreground.

When the suspension happens while the driver is logged in, the API ends the session: the next request returns `401`, the app logs out, and the next login shows the notice.

## 10. Uploads

Compress every image ([common.md](common.md#images)). Image fields: `image`, `identifyImage`, `DrivingLicense`, `VehicleLicense`, `idFrontImage`, `idBackImage`, `licenseFrontImage`, `licenseBackImage`, `transportCardImage`, `passportImage`.

## Checklist

- [ ] Register sends every required field and file; no nationality, tier or commission
- [ ] The register screen has no nationality dropdown and does not call `GET /nationality`
- [ ] The register screen has an optional passport photo (`passportImage`); submit works without it
- [ ] Register verifies the phone with `POST /delivery/verify/{id}`
- [ ] Login decides email vs phone on the device and sends only one
- [ ] Login screens come from the status code and `data` (`412`, `PENDING`, `DENIED`)
- [ ] `accountNotice.action: "UPDATE_DOCUMENTS"` opens the profile with `message` on top and the expired documents highlighted
- [ ] Any `401` after login logs the driver out
- [ ] Profile shows tier, rating and assigned vehicle read-only
- [ ] Edit profile sends `POST /delivery/profile-edit-request` and shows `PENDING_COMPANY` or `PENDING_ADMIN`
- [ ] Available switch sends only `readyToReceiveOrders`
- [ ] Location is sent over the socket at least every 2 minutes while available, with full decimals
- [ ] Location keeps being sent in the background (Android foreground service, iOS background location)
- [ ] `ORDER.DELIVERY.AVAILABLE` push opens and reloads the available list
- [ ] `ORDER.DELIVERY.ASSIGN` push reloads the Orders tab and opens the order
- [ ] Available list shows distance from `Store.lat` / `Store.lng`; empty list shows the empty state
- [ ] A failed accept shows `message` and reloads the list
- [ ] Orders tab sends the four in-progress statuses
- [ ] Profile shows the tier terms line (platform or company pair), hidden when `Type` or `Value` is `null`
- [ ] `DRIVER_TIER_CHANGED` push reloads `GET /user/profile`
- [ ] Order card and delivery screen show `collectAmount` from `paymentMode` / `collectAmount`; never a "pay the restaurant" amount
- [ ] Parcel orders (`Store` is `null`) show pickup and drop-off from `ParcelOrder.senderPoint` / `receiverPoint`; cash is collected at pickup
- [ ] Accept errors (tier/company commission missing, debt limit) show `message` as returned; no string comparison on `message`
- [ ] Retrying "Delivered" after a timeout does not change the wallet twice
- [ ] Wallet shows `available`, `debt` and `held` separately; "Withdraw" only when `available` is above 0
- [ ] `overDebtLimit: true` shows "Top up to take cash orders"
- [ ] Top up takes any amount through Moyasar and sends `POST /delivery/wallet/topup`; shows the returned wallet; a failed top-up starts a new payment
- [ ] Wallet "History" lists `GET /ledger` rows with the right label and sign, including `TOPUP` and `DEBT_PAYMENT`
- [ ] Withdraw sends `POST /withdraw` with `amount` within `available` and `deliveryAccountId`
- [ ] Withdraw list maps `PENDING_REVIEW`, `APPROVED_AWAITING_TRANSFER`, `TRANSFERRED` (with `transferReference`) and `REJECTED` (with `rejectReason`)
- [ ] `WITHDRAW_STATUS` push reloads the wallet and the request
