> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Wallet API — Flutter

Source: `modules/Wallet/Routes/api.php` on `main` of `alalmiyalhura/outlet`.

**Verified route inventory:** 7 method/path entries. Route names and permissions are sourced from GitLab.

> **Contract completeness:** All seven controller actions and `WalletViews` were source-reviewed on `main`. AmountRule, WalletQueries filter enum, shared HTTP envelopes, and runtime responses remain to be independently verified. Routes below omit the common `/api/v1` prefix.

## `GET /wallet`

- Access: `auth`.

**Request:** no body or endpoint-specific query. Authenticated user wallet only.

| `data` field | Type | Description |
|---|---|---|
| `balances.available` | money + `label` | Withdrawable balance |
| `balances.pending` | money + `label`, `note`, `breakdown` | Held earnings and settling refunds |
| `balances.pending.breakdown.earnings` | money + `label` | Pending sale earnings |
| `balances.pending.breakdown.settling_refunds` | money + `label` | Refunds awaiting settlement |
| `balances.reserved` | money + `label`, `note` | Reserved amount |
| `balances.total` | money | Aggregate balance |
| `can_withdraw` | boolean | Server-authoritative eligibility |
| `withdraw_blocked` | `{code:string,message:string}` or null | Reason withdrawal is unavailable |
| `withdrawals` | `{count:int,pending_count:int,label:string}` | Withdrawal counters |
| `payout_account` | object or null | Masked bank details (see below) |
| `recent_transactions` | array of history rows | At most 4 rows |
| `texts` | object | Localized `footer`, `account_pending_note`, `sheet` |

`money` is a JSON object with decimal amount and currency (do not parse as float for calculations). `payout_account`: `bank_code`, `bank_name`, `iban_masked`, `iban_last4`, `holder_name`, `label`, `short_label`. `sheet` has `title`, `status_label`, `date_label`, `close`.

## `GET /wallet/transactions`

- Access: `auth`.

**Query validation:**

| Name | Type | Rules | Default |
|---|---|---|---|
| `filter` | string | Nullable; one of `WalletQueries::HISTORY_FILTERS` keys (enum values not yet independently extracted) | `all` |
| `per_page` | integer | 1–50 | 20 |
| `page` | integer | Laravel paginator parameter; validation not explicitly declared in controller | 1 |

**Response:** Top-level `data` (array of history rows), `months` (array of `{key,label,count}` for **this page only**), `filters` (array of `{key,label,selected}`), `texts` (`empty`, `footer`, `sheet`), `links` (`first`, `last`, `prev`, `next`) and `meta` (`current_page`, `from`, `last_page`, `per_page`, `to`, `total`). Unlike `/wallet`, this endpoint returns the paginator directly, **not** `data` wrapped in the standard `ApiResponse::ok` envelope.

**History row:** `id:int`, `kind:string`, `label:string`, `icon:string`, `direction:'in'|'out'|'none'`, `amount:money`, `signed_amount:string`, `struck:boolean`, `status:{code,label,tone}`, `reference:string|null`, `reference_kind:'withdrawal'|'order'|null`, `reference_label:string|null`, `withdrawal_id:int|null`, `reason_code:string|null`, `reason:string|null`, `note:string`, `posted_at:ISO8601`, `date_label:string`, `month:{key:'YYYY-MM',label:string}`, `tone:string`. `kind` includes `earning_pending`, `earning_available`, `earning_reduced`, `refund`, `withdrawal`, `reserved_returned`, `correction`; `status.code` may be `pending`, `processing`, `settling`, `done`, `completed`, `rejected`, `cancelled`.

## `GET /wallet/withdrawals`

- Access: `auth`.

**Query:** `per_page` optional integer 1–50, default 20; `page` paginator parameter. Records are sorted by `requested_at DESC`, then `id DESC`, and restricted to authenticated owner.

**Response:** Top-level `data: Withdrawal[]`, `texts:{empty,footer}`, `links:{first,last,prev,next}`, `meta:{current_page,from,last_page,per_page,to,total}`. No standard `ApiResponse::ok` wrapper on this paginated endpoint. `Withdrawal` schema is specified below under detail.

## `GET /wallet/withdrawals/form`

- Access: `auth`.

**Request:** no body/query required. Returns the server-calculated withdrawal form.

| `data` field | Type | Notes |
|---|---|---|
| `available`, `pending`, `max_amount`, `min_amount` | money | Available balance, held amount and limits |
| `quick_amounts` | `{key,label,amount:money}[]` | `half` and `all`; half rounded down to whole currency units |
| `fee` | `{type,value,label,display}` | Fee policy, including percentage or fixed amount |
| `payout_account` | masked payout object or null | Destination bank |
| `pending_withdrawals`, `max_pending` | integer | Pending count and policy maximum |
| `can_withdraw` | boolean | Authoritative eligibility |
| `blocked` | `{code,message}` or null | Localized block reason |
| `texts` | object | Localized form labels and confirmation texts |

`texts` keys: `title`, `amount_label`, `hint`, `hint_over`, `min_note` (nullable), `destination_label`, `change`, `sum_label`, `fee_label`, `net_label`, `info`, `submit`.

## `GET /wallet/withdrawals/quote`

- Access: `auth`.

**Query:** `amount` **required** and validated by `AmountRule::rules()`; its exact lexical/range constraints need a separate rule-file check. No body is read by this controller.

| `data` field | Type | Meaning |
|---|---|---|
| `amount`, `fee`, `net` | money | Server-calculated quote |
| `valid` | boolean | Whether request is eligible |
| `error` | `{code,message,field}` or null | Form-level eligibility error |
| `confirmation` | `{title,body,confirm,cancel}` or null | Present only when valid and payout account exists |

**Important:** A successfully validated quote can return HTTP 200 with `valid:false`; do not treat that as a successful withdrawal. Rate limit `120/min`.

## `GET /wallet/withdrawals/{id}`

- Access: `auth`.

**Path:** `id` numeric withdrawal ID. Another user's ID is indistinguishable from a nonexistent withdrawal (404).

**Response:** `ApiResponse::ok(Withdrawal)`. `Withdrawal` fields: `id:int`, `reference:string`, `amount:money`, `fee:money`, `net:money`, `status:{code,label,tone}`, `requested_at:ISO8601`, `requested_at_label:string`, `bank:{name:string|null,iban_last4:string,iban_masked:string,holder_name:string,label:string}`, `note:string|null`, `transferred_at:'YYYY-MM-DD'|null`, `rejection:{reason,label,note,bank_details_issue:boolean,bank_edit_label:string|null}|null`. `status.code` is `processing`, `completed` or `rejected`.

## `POST /wallet/withdrawals`

- Access: `auth; idempotent`.

**Request:** JSON `{ "amount": "100" }` (illustrative). `amount` is required and checked by `AmountRule::rules()`; the exact rule is pending review. `Idempotency-Key` is handled by the shared `idempotent` middleware (exact header validation/replay semantics pending middleware review). Rate limit `30/min`.

**HTTP 201 response (direct JSON, not `ApiResponse::ok`):**

```json
{
  "data": {"id": 123, "reference": "EXAMPLE", "amount": {"amount": "100.00", "currency": "SAR"}, "fee": {"amount": "0.00", "currency": "SAR"}, "net": {"amount": "100.00", "currency": "SAR"}, "status": {"code": "processing", "label": "localized", "tone": "warning"}},
  "message": "localized submission message",
  "balances": {"available": {"amount": "0.00", "currency": "SAR"}, "pending": {"amount": "0.00", "currency": "SAR"}, "reserved": {"amount": "100.00", "currency": "SAR"}}
}
```

*Example is illustrative and intentionally omits required additional `data` fields: use the full Withdrawal schema above.* The service enforces balance, bank destination, and pending-withdrawal policy. Re-quote immediately before submitting; do not calculate fees client-side.

## Verified precision: withdrawal amount, history filters and business errors

Source: `modules/Wallet/Interfaces/Http/Requests/AmountRule.php`, `modules/Wallet/Infrastructure/ReadModel/WalletQueries.php`, `modules/Wallet/Interfaces/Http/Middleware/LocalizeWalletErrors.php` (GitLab `main`, reviewed 2026-11-22).

### Amount field: `GET /wallet/withdrawals/quote` and `POST /wallet/withdrawals`

| Field | Location | Type | Required | Exact validation |
|---|---|---|---|---|
| `amount` | Query for quote; JSON body for POST | Decimal **string** | Yes | Regex `^\d{1,9}(\.\d{1,2})?$`; 1–9 integer digits, optionally 1–2 decimal digits; no sign, commas or exponent |

**Examples:** `"100"`, `"100.5"`, `"100.50"` pass the syntax rule. `"100.555"`, `"-1"`, `"1e3"` do not. Syntax passing **does not** mean the amount is withdrawable: the quote service checks minimum, available balance, payout account and pending-withdrawal policy. Use decimal strings, not floating-point arithmetic.

### Transaction history filters: `GET /wallet/transactions`

| Query | Type | Allowed / bounds | Default |
|---|---|---|---|
| `filter` | string or null | `all`, `earnings`, `refunds`, `withdrawals` | `all` |
| `per_page` | integer or null | 1–50 | 20 |
| `page` | pagination query | Laravel paginator | 1 |

The server orders rows by `posted_at DESC`, then transaction `id DESC`. `earnings` includes sale holds, released sales and some seller-side refund reductions; `refunds` includes refunds affecting available or settling balances; `withdrawals` includes requests and rejections. **Do not treat these as a raw ledger feed:** the query deliberately hides intermediate settlement, reversal and replaced hold rows. Use returned `kind`, `status`, `struck`, `signed_amount`, `direction` and `month` to render each row. `months[]` describes months **in the current page**, not all historical months.

### Error handling contract

The `LocalizeWalletErrors` middleware rewrites the existing `error.message` using the request language for Wallet business exceptions. It preserves the surrounding Core error envelope; the exact Core envelope and HTTP status for every Wallet exception require separate verification.

| Exception class | `error.details` shape | Flutter handling |
|---|---|---|
| `WithdrawalRuleViolation` with a non-null `field` | `{ "<field>": ["localized message"] }` | Display beneath the named form field |
| `InsufficientFunds` | `{ "amount": ["localized message"] }` | Display under amount and refresh wallet/quote |
| Other Wallet business exceptions | Middleware adds no field-specific details | Use stable `error.code` and localized `error.message` |

**Illustrative partial error payload:**

```json
{
  "error": {
    "code": "<actual-wallet-error-code>",
    "message": "Localized explanation",
    "details": { "amount": ["Localized amount error"] }
  }
}
```

`<actual-wallet-error-code>` is a placeholder, not a real code. The middleware itself does **not** define the error codes or status codes. Also distinguish a successful quote with `valid: false` and its inline `error: {code,message,field}` from a failed HTTP request.
