# Restaurant app

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

Error `message`s are in the language of the `Locale` header (`en` / `ar` / `pl` / `uk`), validation errors included. Show `message` as it is. Never compare it with a fixed string: decide by HTTP status. Always send `Locale`; without it, messages are in English.

On **Add / edit product**, Price and Discount placeholders must use the platform currency from `GET /settings?domain=BUSINESS` (`generalCurrencyName*` / `generalCurrencySymbol`). Do not hardcode "Saudi Riyal".

### Add product (`POST /product`)

Multipart/form-data. Required: `nameAr`, `descriptionAr`, `descriptionEn` (or fill via `nameDefault` / `descriptionDefault`), `categoryId`, `subCategoryId`, `maxPurchase`, `price`, `thumbnail` (image file). Optional: `nameEn`, `stock`, `discount`, `discountType` (`PERCENTAGE` | `AMOUNT` | `NONE`), `calories`, `allergens` (string or repeated fields), `addon` (ids), `image` (up to 6), `translations`.

Do **not** send empty strings for optional selects/numbers (`discountType=`, `discount=`, `unitId=`). Omit the field, or send a real value — empty `discountType` used to fail the request. Show the API `message` on failure (do not replace it with a generic "unexpected error").

## 1. Register and login

Registering a store has its own reference: [store-registration.md](store-registration.md). It covers the form (country and NIP first, labels above the inputs), the NIP and company lookup for Poland, the request and its errors, the phone verification, what happens after, and editing a registered store. In short:

- One store name (`nameDefault`) and a three-part address (`street`, `buildingNumber`, `postalCode`).
- A **NIP is required when the store is in Poland** (country `phoneCode` `48`). `GET /company/lookup?nip=` can pre-fill the form; the details it finds are read-only, and the server takes them from the registry when the store is saved.
- Older app builds cannot register a store in Poland.

Login: `POST /authentication/login` with role `VENDOR`, email and password. What the app shows when the login is refused (`412`, `401`) is in [store-registration.md](store-registration.md#after-verification).

## 2. Home delivery orders

The restaurant chooses who delivers each order; the API picks the driver. Do not show a driver list and do not send `deliveryManId`.

1. Accept: `PATCH /order/{id}` `{ "status": "ACCEPTED" }`. The stored status becomes `HANDED_OVER`. Drivers do not see the order yet.
2. Ready for a driver, with who delivers it, in one call:

```json
{ "status": "WAITING_DELIVERY_ACCEPTANCE", "deliverySource": "PLATFORM" }
```

```json
{ "status": "WAITING_DELIVERY_ACCEPTANCE", "deliverySource": "STORE_FLEET" }
```

   From this moment drivers of that kind see the order, the nearest get a push, and one of them can accept it. `deliverySource` is required in this call: without it the API returns `400` and the order stays where it is. Show the two choices before the "Ready for driver" button, with the order's current `deliverySource` (the restaurant's default) pre-selected, and send the one the restaurant picks. The push goes out right away, to drivers of the chosen kind.
3. Optional, to assign a driver now instead of waiting for one to accept: `POST /order/{id}/auto-assign` with the same `{ "deliverySource": ... }` body.

| `deliverySource` | Who can get the order |
| --- | --- |
| `PLATFORM` | Platform drivers |
| `STORE_FLEET` | Drivers of the fleet company linked to the restaurant, while that company is active |

Enable the "Company fleet" (label was "Store fleet") choice only when the order's `Store.FleetCompany` is present with `status: "ACTIVE"` and `deletedAt: null` (in `GET /order?id={id}`). Otherwise disable it and show that admin must link an active fleet company.

Among those, the API picks a driver who is free, available, has shared a location in the last 10 minutes and, when the restaurant is in an admin-drawn zone, is inside it. It takes the nearest one (in 2 km bands), then the highest rated in that band.

On success the order is `WAITING_DELIVERY` with `deliveryManId` set. Show the driver from the order. The driver continues it (`ON_THE_WAY`, `DRIVER_ARRIVED`, `DELIVERED`); the restaurant cannot set `DELIVERED` on a home-delivery order.

Errors (`400` or `403`):

| `message` (`en`) | `message` (`ar`) | When |
| --- | --- | --- |
| Choose platform drivers or the company fleet before marking the order ready for a driver | اختار سائقين المنصة أو أسطول الشركة قبل ما تعلّم الطلب جاهز للسائق | `WAITING_DELIVERY_ACCEPTANCE` sent without `deliverySource` |
| Assign a driver only after the order is accepted and marked ready for a driver | تعيين السائق يتم بعد قبول الطلب وتعليمه جاهزاً للسائق | Order is not `WAITING_DELIVERY_ACCEPTANCE` |
| No available driver for this delivery source | لا يوجد سائق متاح لمصدر التوصيل ده | No free driver of that kind |
| No available driver in the store's zone right now | مفيش سائق متاح في زون المطعم دلوقتي | Free drivers exist, but none nearby with a recent location |
| This store has no active fleet company | المطعم مش مربوط بشركة أسطول نشطة | `STORE_FLEET`, but no active fleet company |
| This order is paid by card and the payment is not complete yet | الطلب ده بالبطاقة ولسه الدفع ما اكتملش | Card order (`VISA`) not paid yet |

A card order that is not paid yet does not reach drivers. Once it is paid, drivers see it and get the push, without another call from the restaurant.

`PATCH /order/{id}` with `deliverySource: "STORE_FLEET"` follows the same fleet rule. The source cannot change after a driver is assigned.

### When no driver accepts

If the order is still without a driver **3 minutes** after step 2 (admin setting), the API assigns the best driver itself, the same way as step 3. A `STORE_FLEET` order whose fleet company is no longer active goes to platform drivers. The API tries again every minute until a driver is free.

So a driver can be set on the order at any moment after step 2, by a driver accepting or by the API:

- The restaurant gets an `ORDER.UPDATE` push. Reload the order and show the driver.
- An assign that comes too late returns `400` with `This order was already assigned to another driver` / `الطلب ده اتسند لسائق تاني بالفعل`. Reload the order.

## 3. Store profile and delivery source

`defaultDeliverySource` (`PLATFORM` or `STORE_FLEET`) is copied onto new orders. Saving `STORE_FLEET` without an active fleet company returns:

| `message` (`en`) | `message` (`ar`) |
| --- | --- |
| Company fleet needs an active fleet company | أسطول الشركة محتاج شركة أسطول نشطة |

- The fleet company is chosen at registration ([store-registration.md](store-registration.md#delivery-settings)); after that only admin changes it. Do not send `fleetCompanyId` on `PATCH /store`; the API ignores it.
- New orders of a `STORE_FLEET` restaurant without an active company are created as `PLATFORM`, so they still reach a driver.

### Free delivery

`freeDeliveryOver` (`PATCH /store`, optional, number ≥ 0): free delivery when the products reach this amount, and **the restaurant pays the delivery fee** on those orders. Empty or `0` = off (saved as `null`). It applies to all branches; the admin can change it too.

The restaurant does **not** set a delivery price: the platform prices every order by distance from the branch. `deliveryFee` is no longer used (still accepted and ignored; stop sending it). Show under the field: "The delivery fee is calculated by the platform. If the platform's own free-delivery amount is lower, it applies first and the platform pays."

### Fields only admin sets

`tax`, `commissionType` and `commissionValue` are read only for the restaurant. Show them; do not put them in any edit form.

| Sent in `PATCH /store` | Response |
| --- | --- |
| `tax` (any value, `0` included) | `403` "Only an admin can set the store tax" (translated) |
| `commissionType` or `commissionValue` | `403` `Only an admin can set the store commission` / `عمولة المتجر يحددها الأدمن فقط` |

The commission the restaurant pays is in [section 9](#9-platform-commission).

## 4. Table bookings

The API returns only this restaurant's bookings.

```
GET /table-reservation?page=1&limit=20&status={status}&search={text}
GET /table-reservation/{id}
```

- `status` (optional): `PENDING`, `CONFIRMED`, `CANCELLED`, `COMPLETED` or `NO_SHOW`.
- `search` matches the guest name or phone. Newest booking time first.

| Field | Show |
| --- | --- |
| `guestName`, `guestPhone`, `guestCount` | Guest |
| `reservedAt` | Date and time. It is an exact moment (UTC). Show it in the **store's timezone** (`Store.timezone`), not the phone's, so it matches the store hours ([section 7](#7-store-hours)) |
| `notes` | Customer notes, may be `null` |
| `status`, `translated_status` | Status badge (`translated_status` is Arabic or English) |
| `storeFeeAmount` | The restaurant's share of the booking fee. Display only; the API does not deduct a wallet |
| `cancelReason` | When cancelled |

### Status

```
PATCH /table-reservation/{id}/status
{ "status": "CONFIRMED" }
```

| Current status | Buttons (`status` to send) |
| --- | --- |
| `PENDING` | Confirm (`CONFIRMED`), Cancel (`CANCELLED`) |
| `CONFIRMED` | Completed (`COMPLETED`), No show (`NO_SHOW`), Cancel (`CANCELLED`) |
| `CANCELLED`, `COMPLETED`, `NO_SHOW` | None (final) |

Send `cancelReason` when cancelling; the customer sees it. Any other change returns `400` `This status change is not allowed for this reservation` / `تغيير الحالة ده مش مسموح للحجز ده`. The customer cancellation window does not limit the restaurant.

### Settings

```
PATCH /table-reservation/store/settings
{ "reservationsEnabled": true, "reservationCancelHours": 2 }
```

| Field | Screen |
| --- | --- |
| `reservationsEnabled` | Switch "Accept table bookings" |
| `reservationCancelHours` | "Customers can cancel up to {n} hours before" (whole number, 0 or more) |

Send either field or both. Fill both fields from `GET /store/{id}` (or `GET /store?id=`). Do not assume a cancel-hours number; admin and the restaurant can change it. That response includes `lat` and `lng` for the vendor too.

A new booking and a customer cancellation do not send a push. Reload the list when the screen opens.

## 5. Uploads

Compress every image ([common.md](common.md#images)):

| Request | Image fields |
| --- | --- |
| `POST /store`, `PATCH /store`, `PATCH /store/{id}` | `logo`, `cover`, `commercialRegistryOrSelfEmploymentDocument`, `commercialRegistryOrSelfEmploymentCertificate` |
| `POST /product`, `PATCH /product/{id}` | `thumbnail`, `image` (up to 6) |
| `POST`/`PATCH` `/category`, `/brand`, `/banner`, `/campaign`, `/item-campaign`, `/notification` | `image` |
| `POST /advertisement`, `PATCH /advertisement/{id}` | `image`, `cover` (not `video`) |
| `PATCH /user/profile` | `image` |

## 6. Car pickup orders

An order with `deliveryStatus: "CAR_DELIVERY"`: the customer waits in their car at the restaurant and staff bring the order out. No driver.

In `GET /order?id={id}`:

| Field | Use |
| --- | --- |
| `Car` | `car`, `model`, `color`, `plate`, `license`: show them so staff find the car |
| `customerArrived` | `true` once the customer tapped "I've arrived" |

1. Accept: `PATCH /order/{id}` `{ "status": "ACCEPTED" }`.
2. The customer arrives: the restaurant gets the `CUSTOMER.ARRIVE` push. Reload the order and show the car.
3. Hand it over: `PATCH /order/{id}` `{ "status": "DELIVERED" }`.

`DELIVERED` before the customer arrived returns `400`:

| `message` (`en`) | `message` (`ar`) |
| --- | --- |
| customer not arrived | العميل لم يصل |

Enable "Delivered" only when `customerArrived` is `true`.

## 7. Store hours

The days and hours the restaurant is open. Customers can book a table, and the store shows as open, only inside these hours.

### Read

`GET /store/{id}` (or `GET /store?id=`) returns:

| Field | Use |
| --- | --- |
| `StoreSchedule` | List of `{ id, day, openingTime, closingTime }`. A day can have more than one slot. |
| `timezone` | Where the hours apply, an IANA name such as `Europe/Warsaw`. It comes from the store's country (a branch returns its main store's); show it under the hours ("Hours are in Warsaw time") and do not let the vendor edit it. The same field is on `Store` inside every booking. |

`day` is one of `SUNDAY`, `MONDAY`, `TUESDAY`, `WEDNESDAY`, `THURSDAY`, `FRIDAY`, `SATURDAY`. A branch shows its main store's hours.

`openingTime` and `closingTime` look like `1970-01-01T09:00:00.000Z`. The date is meaningless; the clock is the **UTC part**: this is 09:00. Show the hour and minute of the UTC value exactly. **Do not convert to the phone's timezone** (no `toLocal()` or equivalent), or the hour is wrong by the phone's offset. The restaurant staff are at the store, so the stored clock is already their clock.

### Add a slot

```
POST /store/schedule
{ "day": "TUESDAY", "openingTime": "09:00", "closingTime": "17:00" }
```

- Send `openingTime` and `closingTime` as 24-hour `HH:MM`, exactly as the vendor picked them. Do not convert and do not send a date or a `Z`.
- `closingTime` must be later than `openingTime`. A slot that crosses midnight (for example 20:00 to 02:00) is not supported: save two slots, or end at 23:59.
- To close a day, delete its slots; a day with no slot is closed.

| `message` (`en`) | `message` (`ar`) | When |
| --- | --- | --- |
| Closing Time must be greater than Opening Time | وقت الاغلاق يجب ان يكون اكبر من وقت البدء | Closing is not after opening |
| Overlapping schedule | مواعد متعددة | The slot overlaps one already saved for that day |

Show the API `message`.

### Delete a slot

```
DELETE /store/schedule/{id}
```

`{id}` is the slot `id` from `StoreSchedule`. There is no edit call: to change a slot, delete it and add the new one.

### Saved before the fix (b091)

Hours saved before this fix can be 1 to 2 hours early, because the server used its own timezone. Tell the vendor to check each day once; correcting one means deleting the slot and adding it again with the right time. New saves are exact. See the [changelog](CHANGELOG.md).

## 8. Order money

`GET /order` and `GET /order?id={id}` return what the customer pays and what the restaurant earns. Some names don't match their meaning: **`finalPrice` is not the amount to pay**. Never compute totals in the app.

### What the customer pays

| Field | Meaning | Show it as |
| --- | --- | --- |
| `price` | Products total (item offers already taken off) | "Products" |
| `productDiscount` | What item offers saved. Already inside `price` | Optional "Saved" line. Do not subtract it again |
| `discountAmount` | Coupon discount, on the products only | "Coupon" as a negative line. `0` = hide |
| `tax` | Tax: store tax rate × (products − coupon). Delivery is not taxed | "Tax" |
| `shipping` | Delivery fee the customer pays (`0` when free) | "Delivery" |
| `paidWithWallet` | Part the customer paid from their wallet | "Paid from wallet" as a negative line. `0` = hide |
| `finalPrice` | `price + tax + shipping`, before coupon and wallet | Not an amount to pay |
| `totalPrice` | **Still to pay** by cash or card: `finalPrice − discountAmount − paidWithWallet`, never below 0 | "Total" / "To collect" |

The customer never pays a commission: it is taken from the restaurant's share.

On a cash **car pickup** order the staff collect `totalPrice`. On a home-delivery order the driver collects it; the driver never pays the restaurant at pickup.

### What the restaurant earns

| Field | Meaning |
| --- | --- |
| `storeNet` | The restaurant's earning on the order. Added to its wallet when the order is delivered |
| `adminCommission` | The platform commission taken from it ([section 9](#9-platform-commission)) |
| `storeCouponShare` | The part of the coupon the restaurant pays |
| `platformCouponShare` | The part of the coupon the platform pays (the restaurant is not charged for it) |
| `deliveryFee` | Full delivery fee; the driver is paid from it |
| `waivedShipping` | Delivery fee covered on a free-delivery order |
| `waivedShippingByStore` | `true`: the restaurant paid it (its `freeDeliveryOver`), taken off `storeNet` as its own line. `false`: the platform paid it |
| `storeCommissionType` | `PERCENTAGE` or `FIXED`: the commission the order was placed with |
| `storeCommissionValue` | The percentage, or the fixed amount per order |
| `storeCommissionSource` | `STORE` (the restaurant's own commission) or `PLAN` (its package's, while the subscription ran) |
| `subscriptionId` | The subscription when the source is `PLAN`, else `null` |
| `storeCommissionRate` | Old field: the percentage, `0` when the commission is fixed. Read the two fields above instead |
| `financialsVersion` | `1`: the fields above are set. `0`: an old order, settled before this split existed; hide the earning lines |

```
storeNet = price − storeCouponShare + tax − adminCommission − (waivedShippingByStore ? waivedShipping : 0)
```

Example: products 100, coupon 10 (the restaurant's own), tax 15%, commission 10%:

```
price               100.00
discountAmount       10.00
tax                  13.50   (15% of 90)
adminCommission       9.00   (10% of 90)
storeCouponShare     10.00
storeNet             94.50   (100 − 10 + 13.50 − 9)
```

Read the earning from `storeNet` and the wallet ([section 11](#11-wallet-and-settlements)). Do not work it out in the app.

## 9. Platform commission

Each store pays the platform a commission on every order. Only admin sets it. While a package subscription runs ([section 10](#10-subscription-packages)), the package's commission replaces the store's own.

`GET /store` (own store; or `GET /store/{id}`) returns:

```json
"commissionType": "PERCENTAGE",
"commissionValue": 10,
"currentCommission": {
  "type": "PERCENTAGE",
  "value": 10,
  "source": "STORE",
  "subscriptionId": null
}
```

| Field | Meaning |
| --- | --- |
| `commissionType`, `commissionValue` | The store's own terms (the main store's for a branch). `PERCENTAGE` or `FIXED` |
| `currentCommission` | What an order placed now gets. `source` is `STORE` (own terms) or `PLAN` (the running subscription, `subscriptionId`). `null` when nothing is set |

- `PERCENTAGE`: that percent of the products after discounts (tax and delivery not included).
- `FIXED`: that amount, once per order. Never more than the products after discounts.

Show `currentCommission` read only, for example "10% (store commission)" or "5 per order (subscription package)".

Each order keeps the commission it was placed with. A later change, or a subscription that ends, does not change old orders.

When admin changes the commission, the restaurant gets an in-app notification ("Platform commission updated") in `GET /app-notification`, in the `Locale` language.

A store with no commission set can't take orders: customers get `400` `This store can't take orders yet` on cart and checkout. That is an admin setup issue.

## 10. Subscription packages

A package gives the store its own platform commission and a listing priority while it runs. It doesn't switch any feature on or off: chat, reviews and POS are open to every store, and there's no limit on orders or products. A store keeps taking orders when its package ends.

### List

```
GET /plan
```

Only active packages that can be bought are listed (a package without a commission is hidden; the default package is always listed). Each plan:

| Field | Show |
| --- | --- |
| `id`, `name`, `info` (in the `Locale` language) | Title and description |
| `price` | Price |
| `durationValue`, `durationUnit` (`DAYS` / `MONTHS` / `YEARS`) | "30 days", "3 months", "1 year". A month is a calendar month. `days` is an old field |
| `commissionType`, `commissionValue` | "10% commission" or "5 per order" |
| `priority` | Optional: lower = shown first to customers among subscribed stores |
| `default` | `true` for the default package: it is only the "no package" marker and can't be bought |

Under every price, show: **"Non-refundable. If you cancel before the end, the benefits stop at once with no refund."**

### My subscription

```
GET /plan/my-subscription
```

Vendor token; a branch gets its main store's.

```json
{
  "current": {                       // null = no package running: the store's own commission applies
    "id": 12,
    "status": "ACTIVE",              // ACTIVE, EXPIRE_SOON (last 3 days)
    "startDate": "2026-11-19T10:00:00.000Z",
    "expireDate": "2026-12-19T10:00:00.000Z",
    "daysLeft": 30,
    "planPrice": 299,
    "paymentId": "…",
    "commissionType": "PERCENTAGE",
    "commissionValue": 8,
    "priority": 2,
    "durationValue": 30,
    "durationUnit": "DAYS",
    "Plan": { "id": 2, "name": "Basic Package" }
  },
  "renewal": null,                   // a bought renewal (status SCHEDULED) waiting to start
  "canRenew": false,                 // true in the last 3 days, when no renewal is bought yet
  "renewFrom": "2026-12-16T10:00:00.000Z",
  "canSubscribe": false,             // false while a subscription runs
  "history": [ /* every period, newest first, same fields + cancelledAt */ ]
}
```

History statuses: `ACTIVE`, `EXPIRE_SOON`, `SCHEDULED`, `EXPIRED`, `CANCELLED`, `INACTIVE` (old rows). Each purchase or renewal is its own row with its payment.

Show the package name, status, end date, days left and its commission. Show a renewal when there is one, and the date from which renewing opens.

### Subscribe

Only when `canSubscribe` is `true`: **no new package while one runs**. To change package, cancel first.

1. Take a Moyasar payment for exactly the plan `price`, in minor units (`round(price * 100)`), with `metadata.planId` = the plan `id`.
2. Send:

```
POST /plan/{id}/subscribe
{ "paymentId": "<moyasar payment id>" }
```

On `201` the package runs at once, for its duration, for the main store and all its branches. Reload `GET /plan/my-subscription` and `GET /store` (`currentCommission.source` is now `PLAN`).

The period keeps the package's price, commission, priority and duration as they were when it was bought. A later change to the package applies to new subscriptions and renewals only.

### Renew

Only the running package, and only in its **last 3 days** (`canRenew`). The new period starts when the running one ends, so there's no day without the package.

```
POST /plan/{id}/renew
{ "paymentId": "<moyasar payment id>" }
```

Same payment rules. Until it starts, the renewal shows as `renewal` (`SCHEDULED`). With nothing running, renew works like subscribe. There's no automatic renewal: the store gets a notification when the last 3 days start.

### Cancel

Before cancelling, show this full warning (with the real values):

> **Cancel your {package} subscription?**
> If you cancel now:
> - The subscription stops **right away**, not on its end date ({expireDate}).
> - The **{daysLeft} days** left are lost, and **the amount you paid is not refunded**, in full or in part.
> - The platform commission on your new orders goes back from **{package commission}** to your regular **{store commission}** (`commissionType` / `commissionValue` on `GET /store`).
> - Your store no longer appears first in customer lists and search results.
> - Orders placed before you cancel keep the package commission.
>
> You can subscribe again at any time; a new subscription is paid in full.
>
> [Keep subscription] [Cancel subscription]

Only on the confirm button:

```
POST /plan/my-subscription/cancel
{ "confirm": true }
```

Without `confirm: true` the API refuses. A bought renewal is cancelled too. The store gets an in-app notification. Reload `GET /plan/my-subscription` and `GET /store`.

### Errors

| Status | `message` (`en`) | When |
| --- | --- | --- |
| `400` | Payment failed, please try again | No `paymentId`, payment not paid, amount not the plan price, `metadata.planId` is another plan, or the payment id was already used |
| `400` | You have a subscription running until {date}. You can subscribe to another package after it ends | Subscribe while one runs |
| `400` | Renewal opens in the last 3 days of the subscription, from {date} | Renew too early |
| `400` | The renewal is already bought | Renew twice |
| `400` | you can't renew this plan | Renew a package that isn't the running one |
| `400` | This package has no commission set yet, so it can't be bought | Package without commission |
| `400` | you can't subscribe to this plan | The default package |
| `400` | Confirm the cancellation: the subscription stops at once, with no refund | Cancel without `confirm: true` |
| `400` | There is no running subscription | Cancel with nothing running |
| `404` | (not found) | Package stopped or deleted |

On a payment error, take a **new** payment; never retry the same `paymentId`.

### End of a subscription

Checked every hour. In the last 3 days the subscription is `EXPIRE_SOON` and the store gets a notification. When it runs out it is `EXPIRED`: the store's own commission and the normal listing order come back, and a bought renewal starts. The commission follows the dates exactly, without waiting for the hourly check.

## 11. Wallet and settlements

Since 2026-11-19 the restaurant is paid by **settlements**: one bank transfer per cycle. There are no withdraw requests any more ([handoff](update-2026-11-19-settlements.md)).

### How a settlement works

1. **Daily, weekly or monthly**, as the admin sets. The admin can set a restaurant its own cycle. A weekly cycle ends on **Sunday 00:00** (Asia/Riyadh).
2. **At the end of the cycle**, every money row not settled yet becomes one settlement in status `DRAFT`. Rows that go in:
   - Earnings: `STORE_NET`.
   - Takeaway cash the restaurant kept: `CASH_COLLECTED`.
   - Refunds: `REFUND`.
   - Admin adjustments.

   The amount is held at once, so `currentBalance` goes down and `pendingWithdraw` goes up.
3. **The admin transfers** the money to the restaurant's **default bank account** outside the app. The admin records the reference and a proof file, and the status becomes `TRANSFERRED`. The restaurant gets an in-app notification.
4. **A main restaurant is settled together with its branches:** one transfer, with one line per branch. A branch user sees only the branch's own line.
5. **Net of 0 or below** (the restaurant kept more cash than it earned): no settlement is made. The debt is deducted from the next one. The admin can also record a bank payment of the debt (`DEBT_PAYMENT`).
6. **No bank account:** no settlement is made, and the restaurant gets a notification to add one.

### Wallet

```
GET /store/wallet
```

| Field | Show |
| --- | --- |
| `currentBalance` | "Not settled yet". Can be below 0 when the restaurant kept more takeaway cash than it earned |
| `pendingWithdraw` | "Waiting for transfer" (settlements in `DRAFT`, and old withdraw requests) |
| `totalWithdrawn` | "Paid to you" |
| `totalEarning` | "Total earned" |
| `collectedCash` | "Cash collected" (takeaway / car pickup cash orders) |

Amounts are decimal strings (for example `"512.3"`).

### Settlement summary

```
GET /settlements/summary
```

```json
{
  "due": 640.5,
  "owed": 129.45,
  "net": 511.05,
  "held": 0,
  "paid": 1200,
  "cycle": "WEEKLY",
  "cycleIsCustom": false,
  "payoutAccount": { "id": 1, "name": "Main", "iban": "SA03…", "ownerName": "…", "isDefault": true, "Bank": { "nameAr": "…", "nameEn": "…" } }
}
```

| Field | Show |
| --- | --- |
| `due` | Owed to you (not settled yet) |
| `owed` | You owe (not settled yet) |
| `net` | Net for the next settlement |
| `held` | Waiting for transfer |
| `paid` | Paid to you |
| `cycle` | Settlement cycle: `DAILY` / `WEEKLY` / `MONTHLY` |
| `payoutAccount` | Where settlements are paid. When `null`, show "Add a bank account" |

### Settlements list

```
GET /settlements?status={DRAFT|TRANSFERRED}&page=1&limit=20
GET /settlements/{id}
GET /settlements/{id}/entries?page=1&limit=50
```

Fields:
- `periodStart`, `periodEnd`, `dueTotal`, `owedTotal`, `amount`, `ordersCount`, `status`.
- The bank copy: `bankName`, `accountOwnerName`, `accountIban`.
- When transferred: `transferReference`, `transferProofPath`, `transferredAt`.

The detail has `Lines`, one per branch. `entries` lists the money rows the settlement covers, each with its order (`Order`).

| `status` | Show |
| --- | --- |
| `DRAFT` | Waiting for transfer |
| `TRANSFERRED` | Transferred: show the reference and the proof |

### Bank accounts

Use `GET /store-bank`, `POST /store-bank`, `PATCH /store-bank/{id}` and `DELETE /store-bank/{id}`.
- Each account has `isDefault`.
- `PATCH /store-bank/{id}/default` makes an account the one settlements are paid to.
- The first account added becomes the default. With only one account, that account is used.

### History

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

Only the restaurant's own rows (a branch sees its own). Newest first. `amount` and `balanceAfter` are decimal strings; `amount` is `+` in, `−` out. `reference` is an outside reference when there is one.

```json
{
  "data": [
    { "id": 130, "type": "STORE_NET", "amount": "94.5", "balanceAfter": "512.3", "orderId": 91, "reason": null, "reference": null, "createdAt": "2026-11-18T12:00:00.000Z" }
  ],
  "total": 1
}
```

| `type` | Show as | Sign |
| --- | --- | --- |
| `OPENING_BALANCE` | Opening balance | ± |
| `STORE_NET` | Earning – order #{orderId} | + |
| `CASH_COLLECTED` | Cash collected – order #{orderId} (takeaway / car pickup cash) | − |
| `REFUND` | Refund to the customer – order #{orderId} | − |
| `SETTLEMENT_HOLD` | Settlement #{settlementId}: waiting for transfer | − |
| `SETTLEMENT_PAID` | Settlement transferred – {reference} | 0 |
| `DEBT_PAYMENT` | Debt paid by bank transfer – {reference} | + |
| `WITHDRAW_HOLD` | Withdraw requested (old) | − |
| `WITHDRAW_RELEASE` | Withdraw rejected (returned) (old) | + |
| `WITHDRAW_PAID` | Withdraw transferred (old) | 0 |
| `ADJUSTMENT` | Adjustment by admin – {reason} | ± |

### Old withdraw requests

`POST /withdraw` now returns `403` ("Withdraw requests are closed for stores…"), so remove the withdraw button. Old requests can still be read:

```
GET /withdraw?page=1&limit=20&status={status}
GET /withdraw/{id}
```

| `status` | Show |
| --- | --- |
| `PENDING_REVIEW` | Waiting for review |
| `APPROVED_AWAITING_TRANSFER` | Approved, transfer coming |
| `TRANSFERRED` | Transferred (`transferReference`) |
| `REJECTED` | Rejected (`rejectReason`) |

### Refunds

When the admin refunds a delivered order, the restaurant's share comes off its balance (`REFUND`), and the restaurant gets an in-app notification. If that order's settlement was already transferred, the share is deducted from the next settlement.

## 12. Coupons

The restaurant app has no coupon screens; stores manage coupons in the store panel. What the app should know:

- A coupon is a percentage or a fixed amount on the **products** only. There are no free-delivery coupons.
- The order shows the coupon as `discountAmount`. Who pays it is split on the order ([section 8](#8-order-money)): `storeCouponShare` comes off the restaurant's earning, `platformCouponShare` is paid by the platform. A coupon the restaurant made is all `storeCouponShare`; a platform coupon is all `platformCouponShare` unless it is shared.
- A customer can use one coupon per order.

## Checklist

- [ ] Store registration validates the phone before uploading the four files
- [ ] Orders: accept, then mark ready with `deliverySource` in the same call; `POST /order/{id}/auto-assign` only to assign at once
- [ ] No driver list and no `deliveryManId`
- [ ] Failed assign or profile save shows `message`
- [ ] `ORDER.UPDATE` push reloads the order, so a driver set by the API shows up
- [ ] `fleetCompanyId` is never sent
- [ ] Bookings list with status filter and search
- [ ] Booking buttons follow the status table
- [ ] Booking time (`reservedAt`) is shown in `Store.timezone`, not the phone's timezone
- [ ] Booking settings save `reservationsEnabled` and `reservationCancelHours`
- [ ] Car pickup orders show `Car`; `CUSTOMER.ARRIVE` push reloads the order; "Delivered" only after `customerArrived`
- [ ] Store hours: send `HH:MM` as typed; show the UTC part of `openingTime` / `closingTime` without converting to the phone's timezone; show `timezone` under the hours; to change a slot, delete and add
- [ ] Error `message` shown as returned, with the `Locale` header; never compared with a fixed string
- [ ] Order money: "Total" / "To collect" is `totalPrice`, never `finalPrice`; earning is `storeNet`; nothing computed in the app
- [ ] `tax`, `commissionType`, `commissionValue` are never sent on `PATCH /store`
- [ ] Store profile shows `currentCommission` read only (store or package)
- [ ] Package cards show price, days and commission; subscribe / renew send a new paid Moyasar `paymentId` (`metadata.planId`, exact price)
- [ ] Subscribe only when `canSubscribe`; renew only when `canRenew`; after either, reload `GET /plan/my-subscription` and `GET /store`
- [ ] Cancel shows the full warning, then sends `{ "confirm": true }`
- [ ] Plan cards show duration, commission and the no-refund note
- [ ] Subscription screen shows status, end date, days left and the package commission from `GET /plan/my-subscription`
- [ ] No "new withdraw" button; old withdraw requests shown as history
- [ ] Settlements screen: summary from `GET /settlements/summary`, list and detail with reference + proof
- [ ] Bank accounts show the default one; "make default" calls `PATCH /store-bank/{id}/default`; warn when `payoutAccount` is `null`
- [ ] History maps `REFUND`, `SETTLEMENT_HOLD`, `SETTLEMENT_PAID`, `DEBT_PAYMENT`
- [ ] No free-delivery coupon handling
