---
feature: Cancellations, refunds and cancellation rules
slug: cancellations-refunds
surface: admin
consumer: react
version: 2.1.0
status: ready
brd_version: "1.3"
brd_ids: [ADMIN-018, CUST-020, PROV-016]
business_rules: [BR-19, BR-20, BR-24, BR-25, BR-26, BR-29]
decisions: [DEC-10, DEC-24, TD-19, TD-27, TD-95, TD-151, TD-152, TD-153, TD-154, TD-155, TD-156, TD-157]
schema_tables: [cancellation_rules, cancellation_rule_translations, orders, refunds, payments, wallets, wallet_transactions, earnings, trips, idempotency_keys]
related_docs: [orders.md, ../client/cancellation.md, ../provider/cancellation.md, ../client/orders.md]
last_updated: 2026-11-10
---

# Cancellations, refunds and cancellation rules — React Dashboard Integration Guide

> **Base URL:** `{HOST}/api/v1/admin` · Shared rules (headers, envelope, errors,
> pagination, axios setup, TS types): [API_CONVENTIONS.md](../API_CONVENTIONS.md)

> **DEC-10 is partly open.** Every refund goes to the customer wallet (TD-152). `original_method`
> exists in the data but nothing writes it until the client says when it applies.

## Version history

Newest first. Never edit an old row.

| Version | Date | Type | Summary | Dashboard action required |
|---------|------|------|---------|---------------------------|
| 2.1.0 | 2026-11-10 | MINOR | Customer references in admin cancellation and refund rows now also carry `customer.user_id`, the **user** uuid that opens the customer at `GET /admin/users/{id}`; `customer.id` is unchanged (the customer-profile uuid, still what `filters[customer_id]` takes). Fixes the order → customer link that returned 404 (QA-03). The cancellation-rule form also returns Arabic field names in validation messages (QA-NEW-01). | Link to `/users/{customer.user_id}` instead of `/users/{customer.id}`; ignore the field if absent. |
| 2.0.0 | 2026-11-02 | MAJOR | A wallet refund never calls the payment gateway, so it is always `completed`: `POST /refunds/{refund}/retry`, `can_retry` and `REFUND_NOT_RETRYABLE` are removed, and `POST /refunds` requires an `Idempotency-Key` header (TD-152, TD-156). | Drop the Retry button and `can_retry`; send a fresh `Idempotency-Key` per refund; treat 409 `IDEMPOTENCY_KEY_REUSED` as a key clash. |
| 1.0.0 | 2026-11-01 | Initial | Cancellation rule CRUD, a read-only cancellations monitor, the refunds list with an admin-initiated refund to the wallet and a retry of failed refunds. | Build the three pages and the refund dialog; gate by `cancellations_refunds.*`. |

## Changelog

### 2.1.0 — 2026-11-10

- **Added:** Customer references in admin cancellation and refund rows now also carry `customer.user_id`, the **user** uuid that opens the customer at `GET /admin/users/{id}`; `customer.id` is unchanged (the customer-profile uuid, still what `filters[customer_id]` takes). Fixes the order → customer link that returned 404 (QA-03). The cancellation-rule form also returns Arabic field names in validation messages (QA-NEW-01).
- **Note:** the JSON examples in this guide were captured before `customer.user_id` existed and do not show it; the current captured responses are in the Postman collection.
- **Breaking:** No. **App action required:** Link to `/users/{customer.user_id}` instead of `/users/{customer.id}`; ignore the field if absent.

### 2.0.0 — 2026-11-02
- **Added:** required `Idempotency-Key` header on `POST /refunds` (same key and body replays the first refund with the same 201; same key with another body is 409 `IDEMPOTENCY_KEY_REUSED`; a missing or over-long key is 422 `VALIDATION_FAILED`).
- **Changed:** a new admin refund is always `status: completed` — it is credited to the wallet in the same transaction and the payment gateway is not called (TD-152).
- **Removed / Deprecated:** `POST /refunds/{refund}/retry` (`admin.refunds.retry`), the `can_retry` field on refund rows and on `refunds[]` in cancellation details, and the error `REFUND_NOT_RETRYABLE`. The `failed` status value stays in the enum for a future `original_method` refund; nothing produces it today.
- **Breaking:** Yes — the route and two fields are removed and the header is required.
- **Endpoints affected:** `POST /refunds`, `POST /refunds/{refund}/retry` (removed), `GET /refunds`, `GET /refunds/{refund}`, `GET /cancellations/{cancellation}`.
- **Dashboard action required:** Remove the Retry button and `can_retry`; generate a new UUID `Idempotency-Key` per intended refund and keep it on retries of the same request.
- **BRD / decisions:** ADMIN-018; DEC-10; TD-152, TD-156, TD-157.

### 1.0.0 — 2026-11-01
- **Added:** `GET/POST /cancellation-rules`, `GET/PUT/DELETE /cancellation-rules/{cancellation_rule}`; `GET /cancellations`, `GET /cancellations/{cancellation}`; `GET /refunds`, `POST /refunds`, `GET /refunds/{refund}`, `POST /refunds/{refund}/retry`.
- **Changed:** —
- **Fixed:** —
- **Removed / Deprecated:** —
- **Breaking:** No
- **Endpoints affected:** all of the above.
- **Dashboard action required:** Build the pages in §2. Never send a refund destination.
- **BRD / decisions:** ADMIN-018, CUST-020, PROV-016; BR-19, BR-20; DEC-10, DEC-24; TD-152…156.

---

## 1. Business summary

Admins watch every cancelled order and every refund, and maintain the **cancellation rules** that decide
whether a customer or a provider may cancel at a stage and what the customer keeps paying.

- A **cancellation** is an order with status `cancelled`. The monitor shows who cancelled
  (customer, provider, admin or system), the reason, the fee kept, how much went back to the wallet
  and the state of that refund. A permitted pre-execution cancellation has a full refund and
  `earnings_due: 0` — no provider and no driver amount is owed (BR-20).
- A **rule** is `who cancels × booking type × stage → allowed? fee %`. Stages: `before_window` and
  `within_window` (the two timed tiers, split by `window_minutes`), `after_departure`, `after_arrival`.
  DEC-24's defaults allow `before_window` for free and deny the other two, for both parties.
- A **refund** is always credited to the customer's wallet (TD-152). An admin can also refund part
  or all of a paid order on its own; it is credited at once, because no payment gateway is involved.
- Cancelling or fully refunding an order **reverses** the provider's earning of it, and the driver's
  earning of a completed trip unless the rule kept the delivery fee (TD-155).

## 2. Pages and permissions

All routes belong to the **`cancellations_refunds`** section (`config/rbac.php`).

| Page / component | Purpose | Endpoint(s) | RBAC permission (route name) | Section · action |
|------------------|---------|-------------|------------------------------|------------------|
| CancellationRulesPage | Rules table | `GET /cancellation-rules` | `admin.cancellation-rules.index` | cancellations_refunds · view |
| CancellationRuleForm (edit) load | One rule with both locales | `GET /cancellation-rules/{rule}` | `admin.cancellation-rules.show` | cancellations_refunds · view |
| CancellationRuleForm (create) | New rule | `POST /cancellation-rules` | `admin.cancellation-rules.store` | cancellations_refunds · create |
| CancellationRuleForm (edit) / active switch | Partial update | `PUT /cancellation-rules/{rule}` | `admin.cancellation-rules.update` | cancellations_refunds · update |
| DeleteRuleDialog | Remove an unused rule | `DELETE /cancellation-rules/{rule}` | `admin.cancellation-rules.destroy` | cancellations_refunds · delete |
| CancellationsPage | Cancelled orders | `GET /cancellations` | `admin.cancellations.index` | cancellations_refunds · view |
| CancellationDetailsPage | One cancellation with refunds and amounts due | `GET /cancellations/{order}` | `admin.cancellations.show` | cancellations_refunds · view |
| RefundsPage | Refunds table | `GET /refunds` | `admin.refunds.index` | cancellations_refunds · view |
| RefundDetailsDrawer | One refund with its payment and wallet credit | `GET /refunds/{refund}` | `admin.refunds.show` | cancellations_refunds · view |
| NewRefundDialog | Refund part or all of a paid order | `POST /refunds` | `admin.refunds.store` | cancellations_refunds · create |

Sidebar entry: Cancellations & refunds → Cancellations / Refunds / Rules. Hide each when the admin lacks its `index`
permission. Show "Refund" on an order only when the admin has `admin.refunds.store`.

## 3. List / table

### 3.1 Cancellation rules — `GET /cancellation-rules`

List key in `data`: `cancellation_rules` (standard paginated shape, API conventions §2.2).

| Column | Field | Sortable (`sort[...]`) | Filter (`filters[...]`) | Notes |
|--------|-------|------------------------|-------------------------|-------|
| Party | `cancelled_by.label` | yes | `filters[cancelled_by]=customer\|provider` | |
| Booking | `booking_type.label` | yes | `filters[booking_type]=instant\|scheduled\|any` | |
| Stage | `stage.label` | yes | `filters[stage]=before_window\|within_window\|after_departure\|after_arrival` | |
| Window | `window_minutes` | no | — | `null` = no timed tier |
| Allowed | `is_allowed` | yes | `filters[is_allowed]=0\|1` | |
| Fee | `fee_percent_of_service`, `charge_delivery_fee` | no | — | Percent of the services amount; delivery fee kept when true |
| Active | `is_active` | yes | `filters[is_active]=0\|1` | |
| Used | `orders_count` | no | — | Orders this rule was applied to |
| Description | `description` | no | — | Request locale, Arabic fallback |

`search` matches `description`. Default order: newest first.

Postman: `admin.cancellation-rules.index` › "200 Cancellation Rule List".

### 3.2 Cancellations — `GET /cancellations`

List key: `cancellations`. Only orders with status `cancelled`.

| Column | Field | Sortable (`sort[...]`) | Filter (`filters[...]`) | Notes |
|--------|-------|------------------------|-------------------------|-------|
| Order | `code` | no | `search` (partial code) | `id` is the order uuid |
| Customer / Provider | `customer.full_name`, `customer.user_id` (opens `/users/{id}`), `provider.display_name` | no | `filters[customer_id]`, `filters[provider_id]` (uuids) | |
| Cancelled by | `cancelled_by.label` | no | `filters[cancelled_by]=customer\|provider\|admin\|system` | |
| Booking | `booking_type.label` | no | `filters[booking_type]=instant\|scheduled` | |
| Cancelled at | `cancelled_at` | yes | `filters[cancelled_from]`, `filters[cancelled_to]` (`YYYY-MM-DD`) | |
| Total / Fee | `total_amount`, `cancellation_fee` | yes, yes | — | SAR strings |
| Refunded | `refunded_amount` | no | — | Sum of `completed` refunds |
| Refund | `refund_status` | no | `filters[refund_status]=pending\|completed\|failed` | `null` when nothing was refunded |
| Payment | `payment_status.label` | no | `filters[payment_status]` | |

Postman: `admin.cancellations.index` › "200 Cancellations List", "422 Cancellations Unknown Filter Value".

### 3.3 Refunds — `GET /refunds`

List key: `refunds`.

| Column | Field | Sortable (`sort[...]`) | Filter (`filters[...]`) | Notes |
|--------|-------|------------------------|-------------------------|-------|
| Order | `order.code` | no | `search` (partial code), `filters[order_id]` (uuid) | |
| Customer | `customer.full_name`, `customer.user_id` (opens `/users/{id}`) | no | `filters[customer_id]` (uuid) | |
| Amount | `amount` | yes | — | SAR string |
| Reason | `reason.label` | no | `filters[reason]` | `customer_cancel`, `provider_cancel`, `provider_rejected`, `provider_timeout`, `admin`, `package_refund`, `other` |
| Destination | `destination.label` | no | `filters[destination]` | Always `wallet` for now (TD-152) |
| Status | `status.label` | no | `filters[status]=pending\|completed\|failed` | New refunds are always `completed` |
| Processed | `processed_by.name`, `processed_at` | no | — | `processed_by` is `null` for automatic refunds |
| Created | `created_at` | yes | `filters[created_from]`, `filters[created_to]` | |

Postman: `admin.refunds.index` › "200 Refunds List".

## 4. Details view

### 4.1 Cancellation — `GET /cancellations/{order}` (`{order}` = order uuid; a live order or an integer id is a 404)

Adds to the list row: `amounts`, `order_status_at_cancel` (the status it was cancelled from), every refund with its
`wallet_credit` (amount and `balance_after`), `earnings_due` (rows still owed — AC-ADMIN-018 expects `0`)
and the `earnings` of both parties with their status (`reversed` when cancelled).

Postman: "200 Cancellation Details"

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": {
    "id": "01a19b41-b5bf-70bb-adda-3ab5d091da84",
    "code": "JSH-mtzl28816332",
    "customer": {
      "id": "01a19b41-b5c4-7050-b09f-5e475310c95d",
      "full_name": "Ms. Josianne Ankunding III"
    },
    "provider": {
      "id": "01a19b41-b5c7-711e-84f8-47db835ea9ec",
      "display_name": "Jaquan Murazik"
    },
    "booking_type": {
      "value": "instant",
      "label": "Instant"
    },
    "cancelled_by": {
      "value": "customer",
      "label": "Customer"
    },
    "reason": "Plans changed",
    "cancelled_at": "2026-11-02T07:55:37+00:00",
    "payment_status": {
      "value": "refunded",
      "label": "Refunded"
    },
    "total_amount": "150.00",
    "cancellation_fee": "0.00",
    "refunded_amount": "150.00",
    "refund_status": {
      "value": "completed",
      "label": "Completed"
    },
    "rule": null,
    "amounts": {
      "services_amount": "130.00",
      "package_amount": "0.00",
      "delivery_fee": "20.00",
      "discount_amount": "0.00",
      "vat_amount": "0.00",
      "total_amount": "150.00"
    },
    "order_status_at_cancel": null,
    "refunds": [
      {
        "id": "01a19b41-b5d2-7106-a521-ac48e6c385e3",
        "amount": "150.00",
        "status": {
          "value": "completed",
          "label": "Completed"
        },
        "destination": {
          "value": "wallet",
          "label": "Wallet"
        },
        "reason": {
          "value": "customer_cancel",
          "label": "Customer cancelled"
        },
        "wallet_credit": {
          "id": "01a19b41-b5d3-72b7-bb3d-0b00e70d1d88",
          "amount": "150.00",
          "balance_after": "150.00",
          "at": "2026-11-02T07:55:37+00:00"
        },
        "processed_by": null,
        "processed_at": "2026-11-02T07:55:37+00:00"
      }
    ],
    "earnings_due": 0,
    "earnings": []
  }
}
```



| Field | Type | Nullable | Description |
|-------|------|----------|-------------|
| `cancelled_by` | `{value,label}` | yes | `customer`, `provider`, `admin`, `system` |
| `cancellation_fee` | money string | no | Kept from the customer (customer cancellations only) |
| `refunded_amount` | money string | no | Sum of `completed` refunds |
| `refund_status` | `{value,label}` | yes | Status of the newest refund |
| `rule` | `{id, stage}` | yes | Rule the cancellation resolved against; `null` for an unpaid package purchase |
| `order_status_at_cancel` | `{value,label}` | yes | From the status history |
| `refunds[].wallet_credit` | object | yes | `null` unless the refund is `completed` |
| `earnings_due` | int | no | Earnings not `reversed` |
| `earnings[]` | list | no | `role`, `source`, `net_amount`, `status` per earning row |

### 4.2 Refund — `GET /refunds/{refund}`

Adds the `payment` the money comes from, the order's `order_payment_status` / `order_total_amount` and the
`wallet_transaction` the credit produced (`null` unless `completed`).

Postman: "200 Refund Details"

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": {
    "id": "01a19b41-d430-73ba-9fdd-2f685b571770",
    "order": {
      "id": "01a19b41-d41a-73ee-aea9-302a3b7ca802",
      "code": "JSH-aspt08902724"
    },
    "customer": {
      "id": "01a19b41-d41f-719e-91de-5fe676020174",
      "full_name": "Asia Zboncak"
    },
    "amount": "30.00",
    "destination": {
      "value": "wallet",
      "label": "Wallet"
    },
    "reason": {
      "value": "admin",
      "label": "Admin refund"
    },
    "status": {
      "value": "completed",
      "label": "Completed"
    },
    "processed_by": {
      "id": "01a19b41-d416-7247-b98f-51e210df4e51",
      "name": "Dr. Cristopher Windler Sr."
    },
    "processed_at": "2026-11-02T07:55:45+00:00",
    "created_at": "2026-11-02T07:55:45+00:00",
    "order_payment_status": {
      "value": "partially_refunded",
      "label": "Partially refunded"
    },
    "order_total_amount": "150.00",
    "payment": {
      "id": "01a19b41-d427-728b-a4f7-e1e1c1ae1a92",
      "amount": "150.00",
      "method": {
        "value": "card",
        "label": "Bank card"
      },
      "status": {
        "value": "partially_refunded",
        "label": "Partially refunded"
      }
    },
    "wallet_transaction": {
      "id": "01a19b41-d432-7067-89bf-1713ecc948a2",
      "amount": "30.00",
      "balance_after": "30.00",
      "created_at": "2026-11-02T07:55:45+00:00"
    }
  }
}
```



### 4.3 Rule — `GET /cancellation-rules/{rule}`

Same fields as the list row plus `ar` / `en` objects (`{ "description": … }` or `null`).

## 5. Forms (create / edit)

### 5.1 Cancellation rule

`POST /api/v1/admin/cancellation-rules` · `PUT /api/v1/admin/cancellation-rules/{rule}`
(update takes any subset; business checks run on the **merged** values)

| Field | Input type | Required on create | Validation (mirror in zod/yup) | Notes |
|-------|-----------|--------------------|-------------------------------|-------|
| `cancelled_by` | select | yes | `customer` \| `provider` | |
| `booking_type` | select | yes | `instant` \| `scheduled` \| `any` | An exact type beats `any`, then `sort_order` |
| `stage` | select | yes | `before_window` \| `within_window` \| `after_departure` \| `after_arrival` | Execution starts at `on_the_way` (BR-19) |
| `window_minutes` | number | no | integer 1–525600, nullable | Scheduled: minutes before the visit; instant: minutes after confirmation. **Only on `before_window` / `within_window`** |
| `is_allowed` | switch | no | boolean (default true) | A denying rule cannot carry a fee |
| `fee_percent_of_service` | number | no | numeric 0–100, 2 decimals (default 0) | Kept from the refund. **Provider rules must be 0** |
| `charge_delivery_fee` | switch | no | boolean (default false) | Keeps the delivery fee too. **Provider rules must be false** |
| `provider_share_percent` | number | no | numeric 0–100, 2 decimals (default 100) | Recorded only; paying it out is a payouts feature (TD-155) |
| `affects_provider_ranking` | switch | no | boolean (default false) | Not applied yet (DEC-24: no penalty) |
| `is_active` | switch | no | boolean (default true) | |
| `sort_order` | number | no | integer (default 0) | Lower wins among equal matches |
| `ar.description`, `en.description` | text | no | string 1–500 | Both optional; `ar` / `en` may be omitted entirely |

```json
{ "cancelled_by": "customer", "booking_type": "any", "stage": "within_window", "window_minutes": 120,
  "fee_percent_of_service": "50.00", "charge_delivery_fee": true,
  "ar": { "description": "رسوم نصف قيمة الخدمة" }, "en": { "description": "Half the service value is kept" } }
```

Postman: "201 Cancellation Rule Created"

```json
{
  "status": "success",
  "message": "Data saved successfully",
  "data": {
    "id": "01a19b41-a368-7396-9c3c-43002c7c9ce2",
    "cancelled_by": {
      "value": "customer",
      "label": "Customer"
    },
    "booking_type": {
      "value": "any",
      "label": "Any"
    },
    "stage": {
      "value": "within_window",
      "label": "Within the window"
    },
    "window_minutes": 120,
    "is_allowed": true,
    "fee_percent_of_service": "50.00",
    "charge_delivery_fee": true,
    "provider_share_percent": "100.00",
    "affects_provider_ranking": false,
    "is_active": true,
    "sort_order": 0,
    "description": "Half the service value is kept",
    "orders_count": 0,
    "ar": {
      "description": "رسوم نصف قيمة الخدمة"
    },
    "en": {
      "description": "Half the service value is kept"
    }
  }
}
```



### Validation errors

Field-keyed 422 (`data.errors`, API conventions §3.1). The merged-value rules answer in the same shape:

- `window_minutes` — a window on `after_departure` / `after_arrival`.
- `fee_percent_of_service` — a fee or a kept delivery fee on a `provider` rule.
- `is_allowed` — a fee on a rule that does not allow cancelling.

Postman: "422 Cancellation Rule Window On Untimed Stage"

```json
{
  "status": "fail",
  "message": "A window applies only to the before-window and within-window stages.",
  "data": {
    "errors": {
      "window_minutes": [
        "A window applies only to the before-window and within-window stages."
      ]
    }
  }
}
```



Postman: `admin.cancellation-rules.store` › "422 Cancellation Rule Missing Fields", "422 Cancellation Rule Provider With Fee".

## 6. Actions (non-CRUD)

### 6.1 Delete a rule

`DELETE /api/v1/admin/cancellation-rules/{rule}` · Permission: `admin.cancellation-rules.destroy`

| HTTP | `error_code` | When | Dashboard behavior |
|------|--------------|------|--------------------|
| 403 | — | Missing permission | Hide/disable the action |
| 409 | `CANCELLATION_RULE_IN_USE` | An order was cancelled under this rule | Toast `message`; offer "Deactivate" (`PUT { is_active: false }`) |

Postman: "409 Cancellation Rule In Use"

```json
{
  "status": "fail",
  "message": "This rule was applied to orders. Deactivate it instead of deleting it.",
  "data": {
    "error_code": "CANCELLATION_RULE_IN_USE",
    "correlation_id": "ab04bf47-fbcd-46da-afce-de7a27395a60"
  }
}
```



Editing a rule never rewrites history: an order keeps the rule id and the fee it was charged.

### 6.2 Refund part or all of a paid order

`POST /api/v1/admin/refunds` · Permission: `admin.refunds.store`

| Field | Input type | Required | Validation | Notes |
|-------|-----------|----------|-----------|-------|
| `order_id` | hidden / picker | yes | uuid of an existing order | Any order status, while paid money is left |
| `amount` | number | yes | numeric > 0, max 2 decimals | At most the amount still refundable (`REFUND_NOT_AVAILABLE` / 422 on `amount` otherwise) |

There is **no destination field**: the money is credited to the customer's wallet (TD-152). The refund is
taken from the order's newest `paid` / `partially_refunded` payment that still has money. Amounts already
refunded count as spent.

**Header `Idempotency-Key`** (required, 1–100 characters): use one new key per intended refund and keep it when
the same request is retried (a double click, a timeout). The first call refunds; a later call with the same key
and the same body answers the first refund again (201, same `id`, no second wallet credit). The same key with a
different body is **409 `IDEMPOTENCY_KEY_REUSED`**. Keys belong to the admin who sent them and are kept 7 days.

The answer is **201 with the completed refund**: `status.value` is `completed` and the wallet is credited in the
same transaction; the payment gateway is never called (TD-152). The response adds `earnings`: `reversed`
(provider earnings reversed because the order is now **fully** refunded) and `not_reversible` (rows already
`in_payout` / `paid`, to adjust by hand).

Postman: "201 Refund Created Partial"

```json
{
  "status": "success",
  "message": "Refund credited to the customer wallet.",
  "data": {
    "id": "01a19b41-bbb8-70e7-bf76-de380986085e",
    "order": {
      "id": "01a19b41-bb9c-716b-86fd-ac1b1f906704",
      "code": "JSH-jusd15170658"
    },
    "customer": {
      "id": "01a19b41-bba2-733d-9c48-a39d6bdc022f",
      "full_name": "Dr. Trycia Beahan Jr."
    },
    "amount": "50.00",
    "destination": {
      "value": "wallet",
      "label": "Wallet"
    },
    "reason": {
      "value": "admin",
      "label": "Admin refund"
    },
    "status": {
      "value": "completed",
      "label": "Completed"
    },
    "processed_by": {
      "id": "01a19b41-bb99-712b-b716-6ee8a2971e2e",
      "name": "Virgie Nicolas"
    },
    "processed_at": "2026-11-02T07:55:38+00:00",
    "created_at": "2026-11-02T07:55:38+00:00",
    "order_payment_status": {
      "value": "partially_refunded",
      "label": "Partially refunded"
    },
    "order_total_amount": "150.00",
    "payment": {
      "id": "01a19b41-bbaa-73d5-a49b-bf7594786cfe",
      "amount": "150.00",
      "method": {
        "value": "card",
        "label": "Bank card"
      },
      "status": {
        "value": "partially_refunded",
        "label": "Partially refunded"
      }
    },
    "wallet_transaction": {
      "id": "01a19b41-bbba-73bf-a17e-dcc305cbbdbe",
      "amount": "50.00",
      "balance_after": "50.00",
      "created_at": "2026-11-02T07:55:38+00:00"
    },
    "earnings": {
      "reversed": 0,
      "not_reversible": 0
    }
  }
}
```



| HTTP | `error_code` | When | Dashboard behavior |
|------|--------------|------|--------------------|
| 403 | — | Missing permission | Hide the action |
| 404 | — | Unknown order | |
| 409 | `IDEMPOTENCY_KEY_REUSED` | The key was already used with another `order_id` / `amount` | Generate a new key for a new refund |
| 422 | `VALIDATION_FAILED` | `Idempotency-Key` missing or longer than 100 characters | Fix the header |
| 422 | `REFUND_NOT_AVAILABLE` | Order unpaid, or nothing left to refund | Show `message`, disable the button |
| 422 | — (`data.errors.amount`) | Amount above what is refundable, or not a valid money value | Mark the field |

Postman: "201 Refund Replayed With Same Key"

```json
{
  "status": "success",
  "message": "Refund credited to the customer wallet.",
  "data": {
    "id": "01a19b41-ca07-7010-9357-d5a3ce1d21ef",
    "order": {
      "id": "01a19b41-c9eb-738e-b06b-7ee4bee672be",
      "code": "JSH-xraw12984611"
    },
    "customer": {
      "id": "01a19b41-c9f3-7390-af77-68681aa3a412",
      "full_name": "Prof. Heath Jacobson PhD"
    },
    "amount": "40.00",
    "destination": {
      "value": "wallet",
      "label": "Wallet"
    },
    "reason": {
      "value": "admin",
      "label": "Admin refund"
    },
    "status": {
      "value": "completed",
      "label": "Completed"
    },
    "processed_by": {
      "id": "01a19b41-c9e5-72d4-be0b-128df0f23dc6",
      "name": "Nella Medhurst"
    },
    "processed_at": "2026-11-02T07:55:42+00:00",
    "created_at": "2026-11-02T07:55:42+00:00",
    "order_payment_status": {
      "value": "partially_refunded",
      "label": "Partially refunded"
    },
    "order_total_amount": "150.00",
    "payment": {
      "id": "01a19b41-c9fc-71c1-945b-07ec86d3a647",
      "amount": "150.00",
      "method": {
        "value": "card",
        "label": "Bank card"
      },
      "status": {
        "value": "partially_refunded",
        "label": "Partially refunded"
      }
    },
    "wallet_transaction": {
      "id": "01a19b41-ca0a-7205-9be2-222a947d63fa",
      "amount": "40.00",
      "balance_after": "40.00",
      "created_at": "2026-11-02T07:55:42+00:00"
    },
    "earnings": {
      "reversed": 0,
      "not_reversible": 0
    }
  }
}
```

Postman: "409 Refund Key Reused With Another Body"

```json
{
  "status": "fail",
  "message": "The Idempotency-Key was already used with a different request.",
  "data": {
    "error_code": "IDEMPOTENCY_KEY_REUSED",
    "correlation_id": "7e631ea5-aee3-4adf-9dad-887eac2ae74a"
  }
}
```

Postman: "422 Refund Missing Idempotency Key"

```json
{
  "status": "fail",
  "message": "A valid Idempotency-Key header is required.",
  "data": {
    "error_code": "VALIDATION_FAILED",
    "correlation_id": "3c4de8c6-46e4-4ecd-ad9c-761066221f05"
  }
}
```

Postman: "422 Refund Nothing Left"

```json
{
  "status": "fail",
  "message": "This order has no paid money left to refund.",
  "data": {
    "error_code": "REFUND_NOT_AVAILABLE",
    "correlation_id": "7f079a8f-c22d-4f50-b461-bf5e610a160b"
  }
}
```


Postman: "422 Refund Amount Exceeds Remaining"

```json
{
  "status": "fail",
  "message": "The amount is more than what can still be refunded (50.00 SAR).",
  "data": {
    "errors": {
      "amount": [
        "The amount is more than what can still be refunded (50.00 SAR)."
      ]
    }
  }
}
```



## 7. Statuses and enums

| Enum | `value` | Label (en) | Badge color | Actions allowed |
|------|---------|------------|-------------|-----------------|
| refund `status` | `pending` | Pending | grey | transient; only exists inside the refund transaction |
| refund `status` | `completed` | Completed | green | none |
| refund `status` | `failed` | Failed | red | never produced today; kept for a future `original_method` refund (TD-157) |
| refund `reason` | `customer_cancel` / `provider_cancel` / `provider_rejected` / `provider_timeout` / `admin` / `package_refund` / `other` | Customer cancelled / Provider cancelled / Provider rejected / Provider did not answer / Admin refund / Package refund / Other | — | — |
| refund `destination` | `wallet` | Wallet | — | `original_method` is never written (TD-152) |
| `cancelled_by` | `customer` / `provider` / `admin` / `system` | Customer / Provider / Admin / System | — | — |
| rule `stage` | `before_window` / `within_window` / `after_departure` / `after_arrival` | Before the window / Within the window / After departure / After arrival | — | — |
| rule `booking_type` | `instant` / `scheduled` / `any` | Instant / Scheduled / Any | — | — |
| earning `status` | `pending` / `available` / `in_payout` / `paid` / `reversed` | Pending / Available / In payout / Paid / Reversed | — | read-only here |

## Data model

| Table (`db-schema.sql`) | Read / write | Notes |
|-------------------------|--------------|-------|
| `cancellation_rules` (+ translations) | read + write | Rules are applied by the customer and provider cancellation endpoints |
| `orders` | read | `cancelled_by`, `cancellation_reason`, `cancellation_fee`, `cancellation_rule_id`, `payment_status` |
| `refunds` | read + write | One row per refund; `processed_by` is the admin |
| `payments` | write | `status` follows the completed refunds |
| `wallets`, `wallet_transactions` | write | The balance moves only through a `refund_credit` row (trigger-owned balance) |
| `earnings` | write | `status` → `reversed` |
| `trips` | write | Live trips are cancelled with the order |

## 8. TypeScript types

```ts
export interface CancellationRule {
  id: string; // uuid (TD-19)
  cancelled_by: EnumValue<'customer' | 'provider'>;
  booking_type: EnumValue<'instant' | 'scheduled' | 'any'>;
  stage: EnumValue<'before_window' | 'within_window' | 'after_departure' | 'after_arrival'>;
  window_minutes: number | null;
  is_allowed: boolean;
  fee_percent_of_service: string;
  charge_delivery_fee: boolean;
  provider_share_percent: string;
  affects_provider_ranking: boolean;
  is_active: boolean;
  sort_order: number;
  description: string | null;
  orders_count: number;
}
export interface CancellationRuleDetails extends CancellationRule {
  ar: { description: string } | null;
  en: { description: string } | null;
}

export interface Cancellation {
  id: string; // order uuid
  code: string;
  customer: { id: string; user_id: string; full_name: string };
  provider: { id: string; display_name: string };
  booking_type: EnumValue<'instant' | 'scheduled'>;
  cancelled_by: EnumValue<'customer' | 'provider' | 'admin' | 'system'> | null;
  reason: string | null;
  cancelled_at: string | null; // ISO 8601
  payment_status: EnumValue<string>;
  total_amount: Money;
  cancellation_fee: Money | null;
  refunded_amount: Money;
  refund_status: EnumValue<'pending' | 'completed' | 'failed'> | null;
  rule: { id: string; stage: EnumValue<string> } | null;
}
export interface CancellationDetails extends Cancellation {
  amounts: Record<'services_amount' | 'package_amount' | 'delivery_fee' | 'discount_amount' | 'vat_amount' | 'total_amount', Money>;
  order_status_at_cancel: EnumValue<string> | null;
  refunds: RefundSummary[];
  earnings_due: number;
  earnings: { id: string; role: EnumValue<'provider' | 'driver'>; source: EnumValue<string>; net_amount: Money; status: EnumValue<'pending' | 'available' | 'in_payout' | 'paid' | 'reversed'> }[];
}

export interface Refund {
  id: string;
  order: { id: string; code: string };
  customer: { id: string; user_id: string; full_name: string };
  amount: Money;
  destination: EnumValue<'wallet' | 'original_method'>;
  reason: EnumValue<string>;
  status: EnumValue<'pending' | 'completed' | 'failed'>;
  processed_by: { id: string; name: string } | null;
  processed_at: string | null;
  created_at: string;
}
export interface RefundDetails extends Refund {
  order_payment_status: EnumValue<string>;
  order_total_amount: Money;
  payment: { id: string; amount: Money; method: EnumValue<string>; status: EnumValue<string> } | null;
  wallet_transaction: { id: string; amount: Money; balance_after: Money; created_at: string } | null;
}
export interface RefundResult extends RefundDetails {
  earnings: { reversed: number; not_reversible: number };
}
```

## 9. Business rules enforced by the backend

| Rule | What the backend does | What the admin sees |
|------|-----------------------|---------------------|
| BR-29 | Route name is the permission (`cancellations_refunds`) | `403` otherwise |
| BR-20 | Pre-execution cancellation refunds the paid amount to the wallet and leaves no provider or driver amount due | `earnings_due: 0` |
| BR-19 | Customers and providers cannot cancel from `on_the_way` onward, whatever the rules say | Not a refund concern |
| TD-152 | Refunds go to the wallet only | `destination` is always `wallet` |
| TD-153 | A provider cancellation refunds the whole paid amount, fee `0.00` | `cancelled_by: provider`, `cancellation_fee: "0.00"` |
| TD-154 | A rule used by an order is deactivated, not deleted; provider and denying rules carry no fee; a window only on timed stages | 409 / field 422 |
| TD-155 | Live trips are cancelled; a completed trip's driver earning is kept only if the rule kept the delivery fee, else `reversed`; provider earnings are `reversed`; `in_payout` / `paid` rows are left | `earnings[].status` |
| TD-152 | A wallet refund never calls the payment gateway; it is created and completed in one transaction | `status: completed` |
| TD-156 | Refundable = payment minus `completed` and `pending` refunds; a full refund reverses the provider earning; `Idempotency-Key` makes a double click one refund | `earnings.reversed`, replayed 201 |
| Concurrency | The order and the payment are locked before the refundable amount is read; the wallet balance moves only by a `wallet_transactions` row | Two admins cannot refund the same money twice |

## 10. Notifications triggered

An admin refund sends no notification. Customer and provider cancellations send `order_cancelled`
(inbox + `order.updated` with `reason: cancelled`) — see [client/cancellation](../client/cancellation.md) and
[provider/cancellation](../provider/cancellation.md).

## 11. Integration checklist

- [ ] Types match the real responses above
- [ ] Menu items/buttons gated by the listed permissions
- [ ] Filters, search and pagination wired to the documented params
- [ ] The refund dialog sends only `order_id` and `amount`, with a fresh `Idempotency-Key` per intended refund (kept on a retry of the same request)
- [ ] Rule form blocks fee fields on provider rules and a window on untimed stages (the backend also refuses them)
- [ ] `CANCELLATION_RULE_IN_USE` offers "Deactivate"
- [ ] RTL (`ar`) and `en` verified

## 12. Acceptance scenarios

| AC ID | Scenario | Expected |
|-------|----------|----------|
| AC-ADMIN-018 | A permitted pre-execution customer cancellation | Monitor shows `cancelled_by: customer`, full `refunded_amount`, wallet credit with `balance_after`, `earnings_due: 0` |
| AC-ADMIN-018 | Admin refunds 50.00 of 150.00 | 201 `completed`, wallet 50.00, payment and order `partially_refunded` |
| AC-ADMIN-018 | Admin refunds more than what is left | 422 on `amount`; nothing left → 422 `REFUND_NOT_AVAILABLE` |
| AC-ADMIN-018 | Refund while the payment simulator is off | 201 `completed`: a wallet refund does not use the gateway |
| AC-ADMIN-018 | Double click: two calls with one key | One refund, one wallet credit; the second call returns the first refund |
| AC-ADMIN-018 | Same key, different amount | 409 `IDEMPOTENCY_KEY_REUSED` |
| AC-ADMIN-018 | No `Idempotency-Key` | 422 `VALIDATION_FAILED`, nothing refunded |
| AC-ADMIN-018 | Full refund of an order with a pending provider earning | `earnings.reversed: 1`; an `in_payout` earning stays and counts in `not_reversible` |
| AC-ADMIN-018 | Cancellation with a completed trip | Driver earning `reversed`, or kept when the rule kept the delivery fee |
| AC-ADMIN-018 | Delete a used rule | 409 `CANCELLATION_RULE_IN_USE` |
| AC-ADMIN-018 | Provider rule with a fee, window on `after_arrival`, denying rule with a fee | 422 on the named field |

## 13. Open decisions and known limitations

| ID | Impact on this feature | Current behavior |
|----|------------------------|------------------|
| DEC-10 | When `original_method` applies | Never: wallet only (TD-152). A future gateway refund must be called outside any DB transaction and row lock (TD-157) |
| DEC-11 | Payout cycle | An `in_payout` / `paid` earning is not reversed by a refund; adjust it by hand |
| TD-155 | Fee shares | `provider_share_percent` is stored but no `cancellation_fee` earning is written yet |
| BR-19 | Cancelling after execution | Still blocked for customers and providers; there is no admin cancel action |
| DEC-24 | Provider ranking penalty | None; `affects_provider_ranking` is not applied |
