> **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.

# Dashboard Wallet API — Source-verified handoff

**Repository:** `alalmiyalhura/outlet`, branch `main`. **Base:** `/api/v1`. All routes require `auth:sanctum` and use `LocalizeWalletErrors`. This document describes source contracts, not observed live responses. Do not treat examples as staging test evidence.

## Shared contract

| Field | Type | Meaning |
|---|---|---|
| `Authorization` | Header | `Bearer <token>` (Sanctum) |
| `Accept` | Header | `application/json` |
| `per_page` | query integer | 1–100; list default 15 except ledger list/accounts default 25, audit default 25 |
| `sort` | query string | Whitelisted field, prefix `-` for descending |
| `filter.search` | query string | Max 100 characters on range-filtered lists |
| Money object | JSON object | `{ "amount": "12.50", "currency": "SAR" }`; decimal **string**, never float |
| Paginated result | JSON object | `data: []`, `links: {first,last,prev,next}`, `meta: {current_page,from,last_page,per_page,to,total}`; optional `summary`, `meta.filters` |
| Audit row | JSON object | `id,event,subject,subject_id,old_values,new_values,actor_id,actor:{id,name}|null,tags,at` |

**Filters:** amount range `filter.<name>_min` / `_max` uses decimal regex `^\d{1,9}(\.\d{1,2})?$`; date range `filter.<name>_from` / `_to` is inclusive of whole days. Enum filters accept comma-separated strings or arrays. Boolean filters accept `0,1,true,false`. Validation failures are 422. Unknown records raise module not-found errors; permissions are enforced by route middleware. Exact error JSON envelope should be confirmed against Core exception renderer before generating a typed client error parser.

## Wallets

### GET `/admin/wallet/wallets` — `wallets.view`

| Query | Type / validation | Description |
|---|---|---|
| `per_page` | integer 1–100, default 15 | Page size |
| `sort` | `available,pending,reserved,settling,total,created_at,last_activity,name`, optional `-` | Default `-total` |
| `filter.available_min/max` | decimal | Available balance range |
| `filter.pending_min/max` | decimal | Pending range |
| `filter.reserved_min/max` | decimal | Reserved range |
| `filter.settling_min/max` | decimal | Settling range |
| `filter.total_min/max` | decimal | Total range |
| `filter.activity_from/to` | date | Last activity range |
| `filter.user_id` | positive integer | Exact user |
| `filter.user_status` | enum list | Values from Identity `AccountStatus` (also returned in `meta.filters.user_status`) |
| `filter.has_pending_withdrawal` | boolean | Pending withdrawal exists |
| `filter.non_empty` | boolean | Total balance >0 vs =0 |
| `filter.search` | string max 100 | Matches wallet holder using server user search |

**`data[]` response fields:**

| Field | Type | Notes |
|---|---|---|
| `user` | object | `id:int,name:string|null,phone:string|null,status:string|null` |
| `available,pending,reserved,settling,total` | Money object | Five separate balance pots |
| `pending_withdrawals` | object | `count:int,amount:Money` |
| `last_activity_at,created_at` | ISO datetime or null | |
| `links.self` | string | `/api/v1/admin/wallet/wallets/{userId}` |

**Additional response:** `meta.filters.user_status[]` each `{value,label:{locale:text}}`.

### GET `/admin/wallet/wallets/{userId}` — `wallets.view`

| Path | Type | Validation |
|---|---|---|
| `userId` | integer | Numeric route; must refer to an existing user |

**`data` fields:** `user:{id,name,phone,status}`, `balances:{available,pending,reserved,settling,total}` (Money), `created_at:datetime|null`, `accounts:Account[]`, `totals_by_type:{transaction_type:Money}`, `payout_account:object|null`, `withdrawals:{by_status:{status:{count,amount}},recent:Withdrawal[]}` (10 latest), `recent_ledger:Transaction[]` (20 latest), `integrity:object` (LedgerVerifier result), `links:{ledger,withdrawals,account}`. `payout_account` comes from Accounts `SellerDirectory` and its nested shape is defined by that module, not invented here.

## Withdrawals

### GET `/admin/wallet/withdrawals` — `wallets.view`

| Query | Type / validation | Description |
|---|---|---|
| `per_page` | integer 1–100, default 15 | |
| `sort` | `requested_at,amount,processed_at,reference`, optional `-` | Pending-only default oldest first; otherwise newest first |
| `filter.status` | enum list | Values returned by `meta.filters.status` |
| `filter.user_id` | positive integer | |
| `filter.bank_code` | string list | |
| `filter.bank_details_issue` | boolean | |
| `filter.amount_min/max` | decimal | |
| `filter.requested_from/to` | date | |
| `filter.processed_from/to` | date | |
| `filter.search` | string max 100 | Reference, holder name, transfer reference, user |

**Response:** paginated `data: Withdrawal[]`, `summary:{status:{count:int,amount:Money}}`, `meta.filters.status[]`.

### Withdrawal response schema (`Withdrawal`)

| Field | Type | Notes |
|---|---|---|
| `id` | integer | |
| `reference` | string | |
| `user` | object | `id,name,phone,status` |
| `amount,fee,net` | Money | |
| `fee_rule` | object | `type,value` |
| `status` | string | Enum from WithdrawalStatus |
| `status_label` | localized map | Enabled locales, e.g. `ar`, `en` |
| `payout_account` | object | `bank_code,bank_name,iban_masked,iban_last4,holder_name` |
| `requested_at` | ISO datetime | |
| `waiting_hours` | integer or null | Present only for pending |
| `processed_at` | ISO datetime or null | |
| `processed_by` | object or null | Actor details |
| `transfer_reference` | string or null | |
| `transferred_at` | `YYYY-MM-DD` or null | |
| `rejection_reason` | string or null | |
| `bank_details_issue` | boolean | |
| `payout_reveal` | object | `method,url,permission,must_match_last4` |
| `links` | object | `self,complete,reject,history,wallet,reveal_payout_account` |

### GET `/admin/wallet/withdrawals/{id}` — `wallets.view`

Path `id`: positive numeric ID. Response `data` contains all Withdrawal fields plus `current_payout_account:object|null`, `payout_changed_since_request:boolean`, `payout_account_removed:boolean`, `user_balances:{available,pending,reserved,settling}` Money, `other_pending:int`, `ledger:Transaction[]`, `can_process:boolean`, `can_reveal_payout_account:boolean`. **Security:** revealing the full IBAN requires a separate audited Accounts endpoint with `users.view_sensitive`; check `iban_last4` against the withdrawal snapshot before transferring.

### GET `/admin/wallet/withdrawals/{id}/history` — `wallets.view`

| Query | Type | Default |
|---|---|---|
| `per_page` | integer 1–100 | 25 |

Response: paginated Audit rows. Unknown withdrawal returns not-found error.

### POST `/admin/wallet/withdrawals/{id}/complete` — `withdrawals.process`

| JSON field | Type | Validation |
|---|---|---|
| `transfer_reference` | string | Required, length 1–`Withdrawal::TRANSFER_REF_MAX` |
| `transferred_at` | string | Required `YYYY-MM-DD` |

```json
{"transfer_reference":"BANK-2026-001","transferred_at":"2026-11-22"}
```

Response `data:{changed:boolean, ...Withdrawal}`. Repeated completion is idempotent (`changed:false`); the service audits and notifies the user. Transfer reference maximum is defined by the Withdrawal domain constant (do not hardcode until checked).

### POST `/admin/wallet/withdrawals/{id}/reject` — `withdrawals.process`

| JSON field | Type | Validation |
|---|---|---|
| `reason` | string | Required, `Withdrawal::REASON_MIN`–`Withdrawal::REASON_MAX` characters |
| `bank_details_issue` | boolean | Optional, default false |

```json
{"reason":"Bank account details could not be verified","bank_details_issue":true}
```

Response `data:{changed:boolean, ...Withdrawal}`; repeats return `changed:false`. The action is audited and notifies the user.

## Ledger

### GET `/admin/wallet/ledger` — `ledger.view`

| Query | Type / validation | Notes |
|---|---|---|
| `per_page` | 1–100, default 25 | |
| `sort` | `posted_at,amount,reference,id`, optional `-` | Default `-posted_at` |
| `filter.type` | enum list | TransactionType |
| `filter.account` | string max 64 | Exact account code |
| `filter.account_kind` | enum list | AccountKind |
| `filter.user_id` | positive integer | Account owner |
| `filter.reference` | string max 120 | Exact; ending `:` or `*` means prefix |
| `filter.order_ref` | string max 64 | |
| `filter.withdrawal_ref` | string max 64 | |
| `filter.reversed` | boolean | Whether a reversal exists |
| `filter.reason_code` | enum list | RefundReason |
| `filter.amount_min/max` | decimal | |
| `filter.posted_from/to` | date | |
| `filter.search` | string max 100 | Reference, order, withdrawal, memo |

Response: paginated `data:Transaction[]`, `summary:{amount:Money}`, `meta.filters:{type,account_kind,reason_code}`.

### Ledger transaction schema (`Transaction`)

| Field | Type | Notes |
|---|---|---|
| `id` | integer | |
| `reference,type` | string | |
| `type_label` | localized map | |
| `amount` | Money | |
| `memo,reason_code,order_ref,withdrawal_ref,reverses_reference` | string or null | |
| `reason_label` | localized map or null | |
| `reversed` | boolean | |
| `reversed_by_reference` | string or null | |
| `settlement` | object or null | `code,label` for settling refunds |
| `user` | object or null | `id,name,phone,status` |
| `actor_id` | integer or null | |
| `posted_at` | ISO datetime | |
| `entries` | array | Each `{id,account,kind,kind_label,user_id,side,amount,balance_effect}` |

Entry `side` is `debit|credit`; `amount` and `balance_effect` are Money objects; `kind_label` is localized map.

### GET `/admin/wallet/ledger/{id}` — `ledger.view`

Numeric transaction ID. Response `data:{...Transaction,reversed_by:{id,reference}|null,reverses:{id,reference}|null,related:[{id,reference,type,posted_at}]}`.

### GET `/admin/wallet/accounts` — `ledger.view`

| Query | Type | Notes |
|---|---|---|
| `per_page` | integer 1–100 | Default 25 |
| `sort` | `code,balance,updated_at`, optional `-` | Default `code` |
| `filter.kind` | AccountKind list | |
| `filter.user_id` | positive integer | |
| `filter.scope` | `platform|user` | |
| `filter.balance_min/max` | decimal | |
| `filter.search` | string max 100 | Account code |

`data[]` Account fields: `id,code,kind,kind_label,user_id,balance:Money,updated_at`. Additional `summary:{platform:{kind:Money},users:{kind:Money}}` and `meta.filters:{kind,scope}`.

### GET `/admin/wallet/ledger/{id}/history` — `ledger.view`

`per_page` integer 1–100, default 25. Response: paginated Audit rows for transaction correction history.

### POST `/admin/wallet/ledger/{id}/reverse` — `ledger.correct`

| JSON field | Type | Validation |
|---|---|---|
| `reason` | string | Required, 5–500 chars |

```json
{"reason":"Reversing a duplicate ledger posting after reconciliation"}
```

Response `data:{changed:boolean,...Transaction}`, HTTP **201** when newly posted, **200** when already reversed. Creates a *new* mirror transaction with reference `admin:reversal:{id}`; original ledger transaction is never edited or deleted. Withdrawal movements must be handled through withdrawal business actions.

### POST `/admin/wallet/ledger/adjustments` — `ledger.correct`

| JSON field | Type | Validation |
|---|---|---|
| `reference` | string | Required; regex `^[A-Za-z0-9][A-Za-z0-9_.-]{2,80}$` |
| `reason` | string | Required, 5–500 chars |
| `order_ref` | string or null | Max 64 |
| `withdrawal_ref` | string or null | Max 64 |
| `lines` | array | Required, 2–20 items |
| `lines[].account` | string | Required, max 64 |
| `lines[].side` | string | Required `debit|credit` |
| `lines[].amount` | decimal string | Required, regex `^\d{1,9}(\.\d{1,2})?$` |

```json
{"reference":"RECON-20261122-01","reason":"Manual reconciliation of an identified balance discrepancy","lines":[{"account":"ACCOUNT_CODE_A","side":"debit","amount":"12.50"},{"account":"ACCOUNT_CODE_B","side":"credit","amount":"12.50"}]}
```

**Note:** `ACCOUNT_CODE_A/B` are placeholders, not confirmed valid account codes. The ledger requires valid balanced lines. Result `data:{changed:boolean,...Transaction}`; HTTP 201 newly posted, 200 replay; idempotency key is internally `adjustment:{reference}`.

## Integrity

### GET `/admin/wallet/integrity` — `ledger.view`

Response `data:{latest:<LedgerVerifier latest result>}`. Exact nested verifier fields require inspection of `LedgerVerifier`.

### GET `/admin/wallet/integrity/runs` — `ledger.view`

| Query | Type | Default |
|---|---|---|
| `per_page` | integer 1–100 | 25 |
| `filter.ok` | boolean (`0,1,true,false`) | None |

Response: `{data: IntegrityRun[], links: {first,last,prev,next}, meta: {current_page,from,last_page,per_page,to,total}}`. Each run has the exact `IntegrityRun` fields defined below.

### POST `/admin/wallet/integrity/run` — `ledger.view`

No request body; `throttle:6,1`. Response `data: IntegrityRun` (including the newly created `id`). Initiates and stores a fresh integrity check; does not change ledger balances.

## Settings

### GET `/admin/wallet/settings` — `settings.manage`

Response `data` is the flat union of `WithdrawSettings::toArray()` and `{refund_settlement_minutes:int,alert_recipients:int[]}`. Configurable fields: `fee_type,fee_value,min_amount,max_pending,refund_settlement_minutes,alert_recipients`. Source: `WalletSettingsController::view()`.

### PATCH `/admin/wallet/settings` — `settings.manage`

| JSON field | Type | Validation |
|---|---|---|
| `fee_type` | string | Optional `fixed|percent` (WithdrawalFee constants) |
| `fee_value` | decimal string | Optional regex `^\d{1,9}(\.\d{1,2})?$`; percent must be ≤50% |
| `min_amount` | decimal string | Optional same regex |
| `max_pending` | integer | Optional 1–20 |
| `refund_settlement_minutes` | integer | Optional 0–43200 |
| `alert_recipients` | integer[] | Optional max 50; distinct existing user IDs |

```json
{"max_pending":3,"refund_settlement_minutes":1440,"alert_recipients":[12,24]}
```

Response: same flat settings object as GET. Changes audited old→new; they affect **new** withdrawal requests, not the fee on existing pending withdrawals.

### GET `/admin/wallet/settings/history` — `settings.manage`

`per_page` integer 1–100, default 25. Response paginated Audit rows for both `withdraw` and `wallet` settings groups.

## Implementation notes / remaining external dependencies

1. **Do not confuse authorization:** `wallets.view` permits wallet/withdrawal viewing; `withdrawals.process` is required for completion/rejection; `ledger.correct` for reversals/adjustments; `settings.manage` for settings.
2. **Never store money as floating point.** Money JSON carries decimal strings and currency.
3. **Withdrawal bank account snapshot matters:** compare `iban_last4` and holder name; full IBAN reveal is a separately authorized audited Accounts action.
4. **Response envelopes:** `ApiResponse::ok()` is used on detail/actions; `AdminPage::respond()` for lists/audits. `LedgerVerifier` fields are verified below. The exact Core error envelope still requires separate verification.
5. **Tests:** Source review completed for routes, five admin controllers, AdminViews, AdminPage, ListQuery, MoneyJson and AmountRule. No staging execution, permission tests, or error-code verification performed. This is **source-verified, not runtime-certified**.

### Source map

- `modules/Wallet/Routes/api.php`
- `modules/Wallet/Interfaces/Http/Controllers/Admin/{WalletAdminController,WithdrawalAdminController,LedgerAdminController,LedgerCorrectionController,WalletSettingsController,ListQuery}.php`
- `modules/Wallet/Interfaces/Http/Presenters/{AdminViews,AdminPage,MoneyJson}.php`
- `modules/Wallet/Interfaces/Http/Requests/AmountRule.php`

## Integrity verification — exact nested response contract

**Source:** `modules/Wallet/Infrastructure/Integrity/LedgerVerifier.php`. The `GET /admin/wallet/integrity` endpoint returns `data: {latest: IntegrityRun|null}`. A fresh `POST /admin/wallet/integrity/run` returns `data: IntegrityRun`; history returns an array of these records in the paginated `data` field.

| `IntegrityRun` field | Type | Meaning |
|---|---|---|
| `id` | integer | Stored run identifier |
| `ok` | boolean | All checks passed |
| `accounts_checked` | integer | Number of ledger accounts scanned |
| `transactions_checked` | integer | Number of ledger transactions |
| `drift` | array | Up to 200 `{account,cached,computed,difference}` records; amounts are decimal strings |
| `unbalanced` | array | Up to 200 `{transaction_id,reference,sum_minor,lines,reason}` records |
| `negative` | array | Up to 200 `{account,balance}` records; balance is a decimal string |
| `entries_sum_minor` | integer | Signed sum of all entry amounts in minor units |
| `triggered_by` | string | `admin` for manually initiated runs |
| `actor_id` | integer or null | Admin actor, if any |
| `duration_ms` | integer | Verification duration |
| `ran_at` | ISO 8601 datetime | Run time |

`unbalanced[].reason` is one of `no_entries`, `unbalanced`, `too_few_lines`, `total_mismatch`. A run is **read-only** with respect to ledger money, but writes a verification history row. `GET /admin/wallet/wallets/{userId}` additionally returns `integrity: {ok:boolean,accounts:[{account:string,cached:string,computed:string,in_sync:boolean}]}`; this is an on-demand per-user comparison, not a stored full run.

### Withdrawal transition contract and edge cases

**Source:** `modules/Wallet/Domain/Withdrawal/Withdrawal.php`. Completing a pending withdrawal requires `transfer_reference` (1–100 chars) and `transferred_at` (`YYYY-MM-DD`); the date must be between the request day and today. Completing again with the **same** transfer reference returns `changed:false`; using a different reference after completion conflicts. Rejecting an already rejected withdrawal returns `changed:false`; completing a rejected withdrawal or rejecting a completed withdrawal conflicts. Rejection reason is 3–500 characters. Completion transfers the reserved amount into platform payout plus fee; rejection returns the reserved amount to the available pot.

### Error localization

**Source:** `modules/Wallet/Interfaces/Http/Middleware/LocalizeWalletErrors.php`. Wallet business errors use localized `error.message`; `WithdrawalRuleViolation` adds `error.details[<field>] = [message]` when a field is known; `InsufficientFunds` adds `error.details.amount = [message]`. Validation errors use localized field names via `WalletValidation`. Do not assume every error has `details`.
