---
feature: Customer order cancellation
slug: cancellation
surface: client
consumer: flutter
version: 1.2.1
status: ready
brd_version: "1.3"
brd_ids: [CUST-020]
business_rules: [BR-19, BR-20, BR-21, BR-22]
decisions: [D3, DEC-10, DEC-24, TD-105, TD-106]
schema_tables: [cancellation_rules, cancellation_rule_translations, orders, order_status_history, payments, refunds, wallets, wallet_transactions, notifications]
screens: [customer--orders--05-*, customer--orders--06-*]
related_docs: [orders.md, ../provider/orders.md]
last_updated: 2026-11-02
---

# Customer order cancellation — Flutter Integration Guide (client)

> **Base URL:** `{HOST}/api/v1/client` · [Shared API conventions](../API_CONVENTIONS.md).

## Version history

| Version | Date | Type | Summary | App action required |
|---------|------|------|---------|---------------------|
| 1.2.1 | 2026-11-02 | PATCH | The refund is credited to the wallet in the cancelling transaction and never calls the payment gateway (TD-152); no contract change. | None |
| 1.2.0 | 2026-11-01 | MINOR | `cancellation.cancelled_by` tells who cancelled; an order the provider cancelled arrives with a full wallet refund ([provider cancellation](../provider/cancellation.md)). | Word the cancelled screen from `cancelled_by`. |
| 1.1.0 | 2026-10-27 | MINOR | Unpaid package purchases cancel; paid purchases are refused and session cancellation releases the hold. | Handle `PACKAGE_PURCHASE_CANCELLATION_UNAVAILABLE` and refresh the package balance. |
| 1.0.0 | 2026-10-26 | Initial | Customer cancellation, policy gate, wallet refund and both-app notice. | Show Cancel from `can_cancel`, send the optional reason, and refetch on `order.updated` (`cancelled`). |

## Changelog

### 1.2.1 — 2026-11-02

- **Changed:** The wallet refund is created and completed in the same transaction as the cancellation and does not call the payment gateway, so `refund.status` is `completed` as soon as the cancel call returns. No field changes.
- **Breaking:** No. **App action required:** None.
- **BRD / decisions:** DEC-10; TD-152.

### 1.2.0 — 2026-11-01

- **Added:** `cancellation.cancelled_by` (`{value,label}`) in the order details; the settlement of a cancelled order also cancels every live trip and reverses earnings (TD-155).
- **Breaking:** No. **App action required:** Use `cancelled_by` to tell "you cancelled" from "the provider cancelled".
- **BRD / decisions:** PROV-016, BR-20; TD-153, TD-155.

### 1.1.0 — 2026-10-27

- **Added / changed:** Unpaid package purchases cancel; paid purchases are refused and session cancellation releases the hold.
- **Fixed / removed:** None.
- **Breaking:** No.
- **Endpoints affected:** Existing order or package reads and actions described below.
- **App action required:** Handle `PACKAGE_PURCHASE_CANCELLATION_UNAVAILABLE` and refresh the package balance.
- **BRD / decisions:** D1, TD-123–128.


### 1.0.0 — 2026-10-26
- **Added:** `POST /orders/{order}/cancel`; real `can_cancel`; always-present `cancellation` object in customer details; `order_cancelled` inbox rows and `order.updated` with `reason: cancelled` for both apps.
- **Changed:** Customer orders in `cancelled` now show the refund returned to her wallet when paid.
- **Fixed / Removed:** None. **Breaking:** No.
- **Endpoints affected:** `POST /orders/{order}/cancel`, `GET /orders/{order}` and shared create/pay details responses.
- **App action required:** enable Cancel only when `can_cancel` is true; keep the action hidden from `on_the_way` onward and all final statuses; show the cancellation reason, time, fee and refund; refetch after a cancellation event.
- **BRD / decisions:** CUST-020, BR-19/20/21/22, DEC-10/24, TD-105/106.

---

## 1. Business summary

An unpaid package purchase cancels without a refund; a paid purchase returns 422 `PACKAGE_PURCHASE_CANCELLATION_UNAVAILABLE` pending a refund decision. Cancelling a session releases its hold and applies the normal delivery policy. See [my packages](my-packages.md).

A customer can cancel her own service order while it is `pending_provider`, `awaiting_payment`, `confirmed` or `preparing`, if the active policy allows it. Execution starts at `on_the_way`; delays never reopen cancellation. DEC-24's default policy charges no fee and refunds the full paid amount to her wallet. An unpaid order creates no refund.

## 2. User flow and screens

| Step | Screen / widget | Endpoint | Notes |
|------|-----------------|----------|-------|
| 1 | Order details | `GET /orders/{order}` | Show Cancel only from `can_cancel`. |
| 2 | Cancellation confirmation | `POST /orders/{order}/cancel` | Optional `reason`; disable the button while sending. A same-customer replay returns 200 unchanged. |
| 3 | Cancelled details / wallet line | `GET /orders/{order}` | Read `cancellation` and `refund`; `refund` is null for an unpaid or fully fee-withheld order. |

## 3. Endpoints

### 3.1 Cancel an order

`POST /api/v1/client/orders/{order}/cancel` · customer bearer token · JSON body · no `Idempotency-Key` required. `{order}` is the order UUID; a foreign, unknown or integer ID returns 404.

| Field | Type | Required | Validation | Meaning |
|-------|------|----------|------------|---------|
| `reason` | string or null | no | Max 500 characters | The customer's own cancellation reason. |

Postman: `client.orders.cancel` › "200 Paid order cancelled with DEC-24 full wallet refund", "200 Unpaid customer order cancelled", "200 Customer cancellation replay".

**Success — 200**, selected fields copied from the recorded DEC-24 response (the response also includes the normal order details):

```json
{
  "status": "success",
  "message": "",
  "data": {
    "id": "01a1779b-331d-718b-9aaa-fde9459a41fb",
    "status": {"value": "cancelled", "label": "Cancelled"},
    "payment_status": {"value": "refunded", "label": "Refunded"},
    "can_cancel": false,
    "cancellation": {"reason": null, "at": "2026-10-25T07:00:00+00:00", "fee": "0.00", "rule_id": "01a1779b-32f9-7082-9006-e5431cf82126"},
    "refund": {"id": "01a1779b-36fe-7001-b60f-3e2c6a43b1bb", "amount": "150.00", "status": {"value": "completed", "label": "Refunded"}, "destination": {"value": "wallet", "label": "Wallet"}, "returned_to_wallet": true, "refunded_at": "2026-10-25T07:00:00+00:00"}
  }
}
```

`cancellation` is always present, with `reason` and `at` null before cancellation, `fee` as a two-decimal money string, and `rule_id` as the matching rule UUID or null. `refund` keeps the [order details](orders.md) shape. The order status and payment status remain `{value,label}`.

| HTTP | `error_code` | When | App action | Recorded example |
|------|--------------|------|------------|------------------|
| 401 / 403 | `UNAUTHENTICATED` / `PERMISSION_DENIED` | Missing token or token for another app. | Sign in with the customer app. | Shared Postman examples |
| 404 | — (`data: null`) | Unknown, integer or another customer's order ID. | Return to her own order list. | "404 Another customer order is not found" |
| 422 | — (validation) | `reason` is not a string or exceeds 500 characters; `data.errors.reason` explains it. | Correct the text. | "422 Cancellation reason too long" |
| 422 | `ORDER_CANCELLATION_LOCKED` | Execution reached `on_the_way` (BR-19). | Hide Cancel and refetch status. | "422 Cancellation locked after departure" |
| 422 | `ORDER_CANCELLATION_NOT_ALLOWED` | No active allowing rule matches the booking type and resolved stage. | Hide Cancel and show the localized message. | "422 No active cancellation rule matches" |
| 422 | `INVALID_STATE_TRANSITION` | Rejected, expired, completed or cancelled by another party. | Refetch; this order is final. | "422 Already cancelled by provider" |

## 4. Statuses and enums

| Status | `can_cancel` | Meaning |
|--------|--------------|---------|
| `pending_provider`, `awaiting_payment`, `confirmed`, `preparing` | Policy-dependent | Pre-execution; DEC-24 defaults allow cancellation. |
| `on_the_way`, `arrived`, `in_progress` | false | Execution has begun; BR-19 lock applies despite delay alerts. |
| `cancelled`, `rejected`, `expired`, `completed` | false | Final; a repeat by the cancelling customer is the only 200 replay. |

**Policy windows (TD-105):** scheduled orders resolve `before_window` while `now <= scheduled_at - window_minutes`, otherwise `within_window`. Instant orders resolve `before_window` while `confirmed_at` is null or `now <= confirmed_at + window_minutes`, otherwise `within_window`. Without an active timed `within_window` rule, the pre-execution stage is `before_window`; DEC-24 uses `window_minutes = null`, so no 2-hour or 5-minute fee tier exists. `on_the_way` resolves `after_departure`; `arrived` and later resolve `after_arrival`. A missing rule for the resolved stage refuses cancellation.

## Data model

| Table | Read / write | Purpose |
|-------|--------------|---------|
| `cancellation_rules`, `cancellation_rule_translations` | read; default policy migration writes | Active customer policy and Arabic/English descriptions. |
| `orders`, `order_status_history` | write | Cancellation fields and trigger-written status history. |
| `payments`, `refunds`, `wallets`, `wallet_transactions` | write for paid orders | Refund and one wallet credit; no earning row. |
| `notifications` | write | One inbox row per app. |

## 5. Dart models

```dart
class CancellationInfo {
  final String? reason;
  final DateTime? at;
  final String fee; // SAR, two decimal places
  final String? ruleId; // uuid
}
```

Keep `canCancel` as a boolean. Reuse the order details' existing `refund` model. Parse money as decimal, not `double`, for accounting displays.

## 6. Business rules enforced by the backend

| Rule | Backend result | App behavior |
|------|----------------|--------------|
| BR-19/21 | `on_the_way` locks cancellation permanently. | Refetch status; never reopen Cancel on delay. |
| BR-20 / DEC-24 | Active rule determines outcome. Default: full refund before departure, no earnings. | Follow `can_cancel` and show wallet refund. |
| DEC-10 | Refund destination is the customer wallet. | No withdrawal or top-up action. |
| TD-106 | Unpaid fee 0; paid fee capped at paid amount; zero refundable amount leaves `payment_status=paid`, `refund=null`; no earning. | Show fee and refund separately. |

## 7. Notifications and real-time events

Both customer and provider receive an `order_cancelled` inbox row (`data.order_id` is the order UUID) and `order.updated` with `payload.reason = cancelled`, `payload.status.value = cancelled` ([API conventions §9.1](../API_CONVENTIONS.md#91-order-events-customer-and-provider-apps)). Refetch the order on receipt; the socket payload does not contain money or address. Delivery is best effort; refetch on reconnect.

## 8. Localization and UI notes

Use API enum labels and localized error `message`; do not branch on translated text. Render the UTC `cancellation.at` in the device's local timezone; show SAR with two decimals. The DEC-24 design has no 20%/50% fee tiers or after-departure Cancel button, even if old prototype screens show them.

## 9. Integration checklist

- [ ] Show Cancel only when `can_cancel` is true; disable it during the POST.
- [ ] Send optional `reason` and handle each error code in §3.
- [ ] Parse `cancellation` and `refund`, including null refund and unchanged replay.
- [ ] Refetch on `order.updated` `cancelled` and reconnect; test Arabic RTL and English.

## 10. Acceptance scenarios

| AC ID | Scenario | Expected |
|-------|----------|----------|
| AC-CUST-020 | Cancel before provider or driver departure | Order cancelled; paid amount returned to wallet by DEC-24 default; customer and provider notified. |
| AC-CUST-020 | Try to cancel after departure | 422 `ORDER_CANCELLATION_LOCKED`, `can_cancel=false`, no refund. |

## 11. Open decisions and known limitations

Provider cancellation (PROV-016), admin rule screens/refund management (ADMIN-018), driver trips, package sessions, earnings/fee share, chat and delay alerts remain in their later cycles. Production payment still needs the real gateway integration (TD-94 / DEC-06); the refund is a wallet credit written in the cancelling transaction and never calls a gateway (TD-152). The suspended-provider mid-order gap remains TD-103.
