---
id: spay4-backoffice-menu-api-reference
status: current
audience: [bo-frontend, backend, qa]
source_documents: [backoffice-menu-catalog.md, authorization-menu-contract.md, authorization-menu-verification-matrix.md]
---

# SPay4 BO 菜單－API－前端參考（V2）

> **Withdrawal wire 更新：** [Withdrawal target contract](withdrawal-target-native-contract.md#2-bo-http-矩陣) 固定 `/bo/v2/withdrawalOrders` 的 method／suffix／query／body／response／error 及 authority 矩陣；同型 BO wire 沿 Deposit，Action 五欄 `orderId,targetAttemptId,status,actual,version`，Evidence acceptance 一欄，raw VO／PageVo 成功，不新增 aliases／wrapper。Agent／callback 保留 `orderStatus,actualAmount`。Withdrawal handlers 已啟用，`SUPPLY_WITHDRAWAL_WORKSPACE` 的 B/F/R 為 `READY/READY/ENABLED`；各動作仍依角色與 scope 驗證。

> **Deposit 前端交接更新：** exact 目標 route、role、error、App 差異與 readiness 以 [Target-native Deposit contract](deposit-target-native-contract.md#5-api-freeze目標不代表-handler-已發布) 為準。依最新 ADR-0397／Deposit 契約，唯一 base path 為 `/bo/v2/depositOrders`，取代先前 `/backoffice/v2/depositOrders` 提案；不搬移其他 `/bo/v2` route、不新增 fallback alias。工作樹 handler 與 namespace 一致，但仍受 readiness gate 控制；契約或 namespace 一致不能開啟 menu/release。HOUSE 現有 workspace 保留既有 namespace。

> **Overview／Activity 目標契約：** [22-route API contract](cardholder-overview-api-contract.md) 與 [驗證矩陣](cardholder-overview-verification-matrix.md) 固定三角色 scope、Application review／dev 自審例外、完整帳號、獨立 Freeze、原日 Usage 與 native Activity／CSV。Accepted 不代表已實作、已註冊或 B/F/R-ready；hidden direct create 不能作 Application bypass。

> **時間格式（ADR-0409（此參考僅供內部環境使用，公開版本未提供））：** response 與 CSV 的時間點一律帶時區：UTC 時間點為 ISO-8601 帶 `Z`（小數秒依 `ISO_INSTANT`），Workspace `displayTime` 帶 viewer `businessUtcOffset`（例 `+07:00`）。Query 時間參數接受不帶 offset（視為 UTC）、`Z` 或 `+00:00`，非 UTC offset 回 400。

## 結論

本文件只使用 `SPAY4_BO_MENU_CATALOG_V2` 的 26 code。`AGENT_MANAGEMENT`、`ACCESS_ROLE_MANAGEMENT`、`ACCESS_USER_MANAGEMENT`、`SUPPLIER_ACCOUNT_LIST`、`GATEWAY_ACCOUNT_LIST`、`BANK_MANAGEMENT`、`NOTIFICATION_PROVIDER_SOURCE`、`SUPPLY_CARDHOLDER_OVERVIEW`、`SUPPLY_CARDHOLDER_MANAGEMENT`、`HOUSE_TRANSACTION_WORKSPACE`、`SUPPLY_TRANSACTION_WORKSPACE`、`SUPPLY_DEPOSIT_WORKSPACE`、`DEPOSIT_WORKSPACE`、`SUPPLY_WITHDRAWAL_WORKSPACE`、`SUPPLIER_SETTING`、`SUPPLY_GATEWAY`、`SUPPLY_HOUSE_CARD`、`SUPPLY_PT_RULE`、`SUPPLY_COMMISSION_REPORT`、`CHANNEL_ANALYTICS`、`CHANNEL_DEPOSIT_REPORT`、`SYSTEM_CONFIGURATION`、`DOMAIN_AUDIT_LOG`、`SYSTEM_NOTIFICATION_HISTORY`、`SYSTEM_HOURLY_PROJECTION`、`RESET_PASSWORD` 共 26 項（Prefix 專用的 `COMMISSION_REPORT` 已於 #517 移除，ADR-0451（此參考僅供內部環境使用，公開版本未提供）），與本文件明列的密碼／帳號 recovery resource 已啟用（與 `BackofficePolicyCatalog#ENTRIES` 一致）；唯一 `NOT_READY/NOT_READY/NOT_ENABLED` 的 menu entry 是 #516 新增的 `SUPPLY_TRANSACTION_WORKSPACE`（不投影、無路由，由 #513 開啟）。完整 catalog metadata 可由獨立 SQL materialize，但不構成 production menu、route、grant 或 endpoint acceptance 的授權。前端只能以 `GET /bo/v2/menu` response 的 `method.code` 註冊 route；route/menu/JWT claim 都不是 API authorization。

**A1/A2 接線更新：**本人入口、16 條 additive projections、metadata 與可信登入 IP 的精確 contract／驗證狀態見 [BO UI foundation](bo-ui-foundation-contract.md)。本次不更動其他批次、readiness 或 Department。

**Response 包裝依既有 runtime 保留，不是一律 `ResponseVo<T>`：**Auth login／menu／新 me 等已包裝端點回單層 `ResponseVo`；本次 16 條管理 reads 維持 raw VO／PageVo，Access Role／User 的 create／update 與 `permission-resources`、`role-assignments` 亦回 raw root（#605，User TOTP reset 維持 envelope），Supplier/Gateway options 與 allocation 使用各自既有 advice，[Transaction Records API](#transaction-records-api) 的 JSON 成功回應包單層 `ResponseVo`（#892）。page 為 zero-based `pageNumber` 與 `pageSize=1..500`。409 `RESOURCE_VERSION_CONFLICT(40051)` 必須 reload、重確認且不可自動 retry。一時性 password/TOTP setup secret 僅在建立成功 response 交付一次；持久化 credential 僅保存 hash 或 ciphertext。既有需登入後台管理 API（含 Config 與 Domain Audit）使用 `/bo/v2/**`；Deposit 使用同一 `/bo/v2/depositOrders` namespace，獨立 readiness／release 邊界以上方 notice 為準，不新增 alias、redirect、fallback；已部署 frontend、API client 與 proxy 規則須同步切換，repository 變更不代表外部部署已完成；登入／一次性改密碼與 external HMAC API 使用各自 namespace。新增 `/bo/v2/**` handler 前，必須在 `BackofficePolicyCatalog#ENTRIES` 或同 catalog hidden entry 定義 resource/action/B/F/R、加上 `@RequireBackofficePolicy`、完成 service owner/business guard、OpenAPI/route registry 與 negative tests。

## Runtime menu shape

```json
{"code":2000,"message":"","data":[{"name":"Order Management","methods":[{"code":"DEPOSIT_WORKSPACE","name":"Agent Deposit"}]}]}
```

未回傳 code 不顯示 placeholder、不註冊 route。公開 login type 為 `GATEWAY`；內部 `SUPPLY_GATEWAY` 是 resource identity，不是 public principal identity。

## 需登入、免 resource-action grant API

下列 API 都必須帶有效 Bearer JWT／formal session；它們不是匿名公開 API，但不要求對應的 application-level resource-action grant：route 宣告 hidden `AUTH_MENU_BOOTSTRAP:VIEW`，catalog 對四種 principal 直接授權、不經 role grant（ADR-0422（此參考僅供內部環境使用，公開版本未提供）），沒有 `checkPermission` 開關。

| Method | Path | Grant requirement | 行為 |
| --- | --- | --- | --- |
| `GET` | `/bo/v2/auth/me` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | 四種有效 formal principal 本人安全 projection、本人 CAS version；單層 `ResponseVo<PrincipalSelfVo>`、`Cache-Control: no-store`；未知 query 回 400，不接受他人 selector。 |
| `POST` | `/bo/v2/auth/logout` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | Superadmin／Prefix／Supplier／Gateway 本人 formal logout，無 request body，成功 HTTP 204。依 ADR-0094（此參考僅供內部環境使用，公開版本未提供） principal-level revoke-all：本人 `session_epoch` 原子 +1，同 principal 所有裝置的 formal token 之後呼叫任何 protected API（含再次 logout）皆 401，需重新登入；其他 principal 不受影響。成功寫一筆 LOW audit `LOGOUT_AUTH_PRINCIPAL`；併發重送於鎖後發現已撤銷時回 204、不寫 audit（#392）。 |
| `GET` | `/bo/v2/menu` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | 每次由 fresh server-side authorization 或 fixed Supply profile 重新解析目前 principal 的 menu projection，回傳 `ResponseVo<List<SystemGroupVo>>`；menu 不是 endpoint authorization。 |
| `GET` | `/bo/v2/agents/options` | 需登入（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `AGENT_MANAGEMENT:VIEW`），範圍依 principal | Superadmin 全部 active Agent；Prefix 只回自己的 ACTIVE Agent（0 或 1 筆，INACTIVE 回空陣列，#1019）；Supplier（Admin／User 相同，自己底下全部 Gateway）與 Gateway（自己）只回傳有啟用中且 ACTIVE 的 allocation、Gateway 與 Supplier 皆 ACTIVE、Agent 幣別相符（offset 可不同，ADR-0449（此參考僅供內部環境使用，公開版本未提供））、Agent ACTIVE 者，不依餘額、金額或派單候選資格過濾（#466）。只回傳 identity 與 Prefix display option，固定依 `id ASC` 排序。 |
| `GET` | `/bo/v2/banks/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `BANK_MANAGEMENT:VIEW`） | 只回傳 active Bank 的安全 selector projection，固定依 code ASC 排序。 |
| `GET` | `/bo/v2/currencies/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | System Admin 與 Supplier 回傳全部 ACTIVE Currency；Agent 與 Gateway 僅回傳自身綁定且為 ACTIVE 的 Currency。 |
| `GET` | `/bo/v2/suppliers/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `SUPPLIER_SETTING:VIEW`） | Superadmin 全域、Supplier 自己、Gateway 所屬 Supplier、Prefix 空清單；固定 `supplierName ASC, supplierId ASC`。 |
| `GET` | `/bo/v2/supplyGateways/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `SUPPLY_GATEWAY:VIEW`） | Superadmin 全域、Supplier 自己底下、Gateway 自己、Prefix 空清單；固定 `supplierLoginId ASC, gatewayName ASC, gatewayId ASC`。 |
| `GET` | `/bo/v2/access/roles/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `ACCESS_ROLE_MANAGEMENT:VIEW`） | Superadmin 過 fresh guard 後回可指派的 ACTIVE Role；Prefix、Supplier、Gateway 空清單。逐條見 [Access Role Management API](#access-role-management-api)。 |
| `GET` | `/bo/v2/notificationProviderSources/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `NOTIFICATION_PROVIDER_SOURCE:VIEW`） | Supplier Setting 與 Agent 發行 LINE credential 時的 `notificationProviderSourceId` 下拉（#1097）：四種 principal 相同，只回 ACTIVE 的 `LINE_WEBHOOK` 來源，固定 `id ASC`，不分頁、不收參數；每筆只有 `id`、`displayName`、`status`，不回 vendor、parser profile 或建立／修改者；單層 `ResponseVo`。`/page`、`/{sourceId}` 仍只限 Superadmin。 |
| `GET` | `/bo/v2/config/definitions` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant；不需 `SYSTEM_CONFIGURATION:VIEW`） | 只回傳受管理設定的 `key`、`description` 與 `globalOnly`，不回傳設定值或覆寫；`globalOnly=true` 表示只能由 Superadmin 設定全域值，Prefix 不能建立或刪除 Agent 覆寫（寫入回 403／40001），值唯一來源為 `SystemConfigKey.globalOnly()`（#1096）。 |
| `GET` | `/bo/v2/alerts/page` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | BO 收件匣分頁，見下方「BO 收件匣與 SSE」。 |
| `GET` | `/bo/v2/alerts/unreadCount` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | 收件範圍內未讀數；前端以此為權威。 |
| `PUT` | `/bo/v2/alerts/{alertId}/read` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | 標記單筆已讀（範圍內共享）。 |
| `PUT` | `/bo/v2/alerts/readAll` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | 標記收件範圍內全部未讀為已讀。 |
| `GET` | `/bo/v2/alerts/stream` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`，不經 role grant） | SSE 即時推送新告警（best-effort）。 |

### BO 收件匣與 SSE

收件範圍一律由 server 依 session 決定，request 不能擴大範圍：

| 告警 `recipientScope` | 可見者 |
| --- | --- |
| `AGENT` | 該 Agent 的 Prefix 使用者與 Superadmin |
| `SUPERADMIN` | 只有 Superadmin |
| `SUPPLY_GATEWAY` | 該 Supply Gateway 帳號（依 `supplyGatewayId`）與 Superadmin |
| `SUPPLIER` | 該 Supplier 的 Admin／User（依 `supplierId`）與 Superadmin |

- **Page**（`GET /bo/v2/alerts/page`）：query `agentId`（可空，僅 Superadmin 用來縮小到單一 Agent；Prefix 指定他 Agent、Supply Gateway／Supplier 帶 `agentId` 皆回 not-found）、`read`（可空；`true` 只回已讀、`false` 只回未讀）、`pageNumber`、`pageSize`。排序固定 `createTime DESC, id DESC`，回 `PageVo<BoAlertVo>`。
- **Unread count**（`GET /bo/v2/alerts/unreadCount`）：回 `{ "unreadCount": <long> }`，範圍與 page 相同。SSE 可能漏送，未讀 badge 以本值為準。
- **已讀是共享的**：每筆告警只有一份已讀狀態，可見它的任一使用者標記後，同範圍所有使用者與 Superadmin 都看到已讀（`read=true`、同一 `readTime`）。`PUT /{alertId}/read` 無 request body；已讀者重送為 no-op；範圍外與不存在都回 not-found 並寫 WARN log。實際變更時寫一筆 LOW audit `MARK_BO_ALERT_READ`。`PUT /readAll` 無 request body，Prefix、Supply Gateway、Supplier 標記 own 範圍，Superadmin 標記全部；每個實際變更的 Agent、Supply Gateway、Supplier 範圍各寫一筆 LOW audit `MARK_ALL_BO_ALERTS_READ`，`SUPERADMIN` 範圍另寫一筆。
- **SSE**（`GET /bo/v2/alerts/stream`，`text/event-stream`）：事件名 `bo-alert`，`data` 為一筆 `BoAlertVo`，範圍與 page 相同。這是 best-effort 推送：
  - **instance-local**：只推給同一個 BO instance 上的連線；多 instance 時，連到其他 instance 的使用者收不到。
  - **不補送**：斷線期間的告警不會重送，重連後以 page 與 unreadCount 補齊。
  - **30 分鐘逾時**：連線 30 分鐘後由 server 結束，前端須重連。
  - 登記失敗只寫 WARN log。
- **`BoAlertVo` 欄位**（page 與 SSE 相同）：
  - 識別與種類：`alertId`、`alertType`（`UNMATCHED_TRANSACTION`、`HOURLY_PROJECTION_PARKED`、`SUPPLY_CHANNEL_UNMATCHED_TRANSACTION`、`ORDER_ESCALATION`）、`recipientScope`（上表四種）。
  - 內容：`title`、`message`，都是建立時的 snapshot，不含帳號、付款人姓名或 exception 訊息。
  - 已讀與時間：`read`、`readTime`（未讀為 null）、`createTime`，皆為 UTC 帶 `Z`。
  - 範圍：`agentId`、`agentPrefix`（Agent 已不存在時為 null）、`supplierId`、`supplyGatewayId`。
  - 導向：`houseCardTransactionId`（`UNMATCHED_TRANSACTION`）；`projectionQueueId`、`projectionFailureSequence`（`HOURLY_PROJECTION_PARKED`，導向 parked fact 列表與重排）；`depositOrderId`、`withdrawalOrderId`（訂單升級告警）；`transactionNo`（交易告警）。
  - 升級：`escalationTier`（`SUPPLY_GATEWAY`、`SUPPLIER`、`SUPERADMIN`）。
  - 不適用的欄位為 null。

## Hidden resource 路由

下列 route 的 resource 是 catalog `hidden(...)` 宣告的非 menu resource：不出現在 `/bo/v2/menu`、不能經 role grant 授權，只由 catalog 直接授權給所列 principal；它們不是 menu code，不列入 [API 進度表](../backoffice-menu-api-progress.json) 的 menu entries。

| Method | Path | Resource:action | 授權 principal | 行為 |
| --- | --- | --- | --- | --- |
| `PUT` | `/bo/v2/auth/principals/{principalType}/{principalId}/unlock` | `AUTH_PRINCIPAL_UNLOCK:UPDATE` | Superadmin | 解除 principal 登入鎖定；實際 mutation 撤銷 target formal session 並寫入 audit。 |
| `POST` | `/bo/v2/notificationBatches` | `SYSTEM_NOTIFICATION_SEND:INSERT` | Superadmin | 受理人工通知批次（`202 Accepted`）；必填 `reason`（strip 後 1～500 code points、無控制字元，不合法回 400／40005）寫入受理 audit；同交易固定收件人、channel 與內容並寫 audit，同 requestKey 同內容回原批次（reason 不參與比對，保留首次 reason）、不同內容回 conflict，派送於背景進行。 |
| `GET` | `/bo/v2/notificationBatches/{batchId}` | `SYSTEM_NOTIFICATION_SEND:VIEW` | Superadmin | 查詢人工通知批次進度；不存在回 404。 |

## V2 client/operation map

| Code | Allowed caller and derived scope | API family / UI restriction |
| --- | --- | --- |
| `AGENT_MANAGEMENT` | Superadmin all；具 active `VIEW` grant 的 Prefix 僅 own Agent | 已啟用的 Prefix/Agent V2 management resource；詳細 route 與限制見下節。 |
| `ACCESS_ROLE_MANAGEMENT` | Superadmin global | 已啟用的 Role、grant、lifecycle、刪除與安全 User Role assignment full action set。 |
| `ACCESS_USER_MANAGEMENT` | Superadmin global | 已啟用的 BO User 查詢、建立、profile／Role 更新、status、軟刪除、強制密碼重設與 TOTP 重設；完整 action set 為 `VIEW/INSERT/UPDATE/DELETE`。 |
| `SUPPLIER_ACCOUNT_LIST` | Superadmin global；Supplier Admin 僅 own Supplier | 已啟用 Supplier account read/create/status/delete/recovery；Supplier Admin 僅可管理 `SUPPLIER_USER`，Supplier User 無帳號管理能力：`GET /bo/v2/menu` 對 Supplier User 不投影此 code，直接呼叫 API 仍回 403（#520）。 |
| `GATEWAY_ACCOUNT_LIST` | Superadmin、Supplier、Gateway Admin | Gateway account list/create/update、temporary-password reset 與 TOTP reset resource；Supplier Admin 與 Supplier User 同權，可對 own Supplier 旗下 Gateway 帳號 create／status／delete／password reset／TOTP reset，跨 Supplier 404（#950，ADR-0480（此參考僅供內部環境使用，公開版本未提供））。Gateway Admin 固定 own Gateway，只可 mutation own `GATEWAY_USER`：其他 `GATEWAY_ADMIN` 可讀不可改（403）、改自己 400、跨 owner 404，只能建立 `GATEWAY_USER`；`GATEWAY_USER` 與 role 為 null 的 Gateway 帳號不顯示選單，所有帳號管理 API 含查詢回 403。`POST` 選填 `role`（未帶為 `GATEWAY_USER`，無效值 400），建立後不可修改。 |
| `BANK_MANAGEMENT` | Superadmin global | Bank page／by-currency／create／update／status；mutation 必填 audit `reason`，見 [Bank Management API](#bank-management-api)。 |
| `NOTIFICATION_PROVIDER_SOURCE` | Superadmin global | 已啟用的 LINE provider source 管理；完整 action set 為 `VIEW/INSERT/UPDATE/DELETE`，secret 僅能走 Agent credential rotation。 |
| `SUPPLY_CARDHOLDER_OVERVIEW` | Superadmin 全域、Supplier own descendants、Gateway own descendants | 已啟用（#368）[26 條契約](cardholder-overview-api-contract.md) routes：runtime catalog/B/F/R 為 `READY/READY/ENABLED`，conditional gate 隨 canonical catalog 註冊剛好 26 條 mapping（#411 擴充 R23／R24 帳戶限額，#698 擴充 R25 修改戶名與展示名稱）。Application action 為 VIEW/INSERT/UPDATE；Account status 三者皆可在 scope 內切換（ADR-0461）；Account direction／unfreeze、Adjust 與帳戶限額 R23／R24 三者皆可在 scope 內操作（ADR-0481，#955），由 `OverviewAuthorityService` 依 owner chain 判定，scope 外 404；Prefix 沒有 grant。`PUT /bo/v2/paymentAccounts/{id}/profile`（`UPDATE`，Superadmin、Supplier、Gateway 的 owner chain；#698、#699）修改銀行、帳號、戶名與展示名稱（銀行、帳號、戶名僅 `editScope=FULL`，保存 identity 歷史並通知 Cardholder）：列表與明細的 `editScope`（`FULL`／`DISPLAY_NAME_ONLY`／`NONE`，Application 為 null）提示可改範圍，卡片展示名稱以 `paymentAccountDisplayName` 回傳，`displayName` 仍是 Cardholder 名稱；細節見 [R25](cardholder-overview-api-contract.md)。`POST /bo/v2/paymentAccounts` mapping 不存在，不能作 Application bypass。`PaymentAccountController` 的 create／approve 委派 `OverviewCommandService`；own-resource／browse／Activity reads 分別由 `OverviewAccountReadController`、`OverviewBrowseController`、`OverviewActivityController` 負責。Target 啟用仍須 Operator 完成 migration（#367）、部署與 smoke。 |
| `SUPPLY_CARDHOLDER_MANAGEMENT` | Superadmin 全域；Supplier 僅 own Gateway descendants；Gateway 僅 own Gateway read | 已啟用 Cardholder master read/create/profile/status command（含 Unlock）與 force logout；catalog action 為 `VIEW/INSERT/UPDATE`，Gateway fixed profile 僅允許 `VIEW`。 |
| `SUPPLY_TRANSACTION_WORKSPACE` | Superadmin、Supplier；Supplier 固定 own Supplier；Prefix 經 `prefixVia` 轉查 `HOUSE_TRANSACTION_WORKSPACE` | Supplier Transaction Record（#513 開啟，ADR-0455（此參考僅供內部環境使用，公開版本未提供））：runtime catalog/B/F/R 為 `READY/READY/ENABLED`，六條 [Transaction Records API](#transaction-records-api) 路由都宣告此 resource；Superadmin、Supplier 皆為 VIEW／UPDATE，Gateway 沒有格子（403）。Supplier 只看 own `supplier_id` 的 Supply Channel 交易，`VIEW` 讀取與匯出（export 寫 export audit），`UPDATE` 僅可人工匹配。 |
| `HOUSE_TRANSACTION_WORKSPACE` | Superadmin、Prefix；Prefix 固定 own Agent | Agent Transaction Record（#516 改名）。#513 起沒有宣告此 resource 的 controller route：六條 [Transaction Records API](#transaction-records-api) 路由宣告 `SUPPLY_TRANSACTION_WORKSPACE`，Prefix 經 catalog `prefixVia` 以此 resource 的 role grant 通過守衛，service 限 own Agent 的 House Card 交易；page／export 帶 `methodCode=HOUSE_TRANSACTION_WORKSPACE` 時只查 House Card 交易。`VIEW` 僅讀取與匯出（export 寫 export audit），`UPDATE` 僅可人工匹配，raw content 必須 no-store。 |
| `SUPPLY_DEPOSIT_WORKSPACE` | Superadmin、Supplier、Gateway | Deposit List（#516，ADR-0450（此參考僅供內部環境使用，公開版本未提供））：收款方為 Cardholder 或 Supply Channel 的單；page／stats／export 帶 `methodCode=SUPPLY_DEPOSIT_WORKSPACE` 時 Superadmin 只看此範圍，Prefix 帶此值 403。已啟用（#381，與 `DEPOSIT_WORKSPACE` 一起）：runtime catalog/B/F/R 為 `READY/READY/ENABLED`，conditional gate 隨 canonical catalog 註冊 13 條 BO mappings（含 #435 `GET /stats` 統計列）；`spay4.cardholder.native-enabled=true` 且已設定 `spay4.internal.cardholder-key` 時另註冊 6 條 `/internal/cardholder/depositOrders` internal CH routes（只供 `spay4-cardholder` edge 呼叫，#423），callback 排程改為 Deposit／Withdrawal 兩方向皆派送（#375）。Superadmin、Supplier、Gateway 皆為 VIEW／UPDATE（#412）：Supplier／Gateway 只對 own-scope CH Deposit 執行 settle（含差額裁決）／close／redispatch／evidence／remarks，初派 `assign` 限 Superadmin、其他 principal 與跨 owner 一律 404，Gateway 重派目標須為 own-Gateway Account（否則 409）；Prefix 經 catalog `prefixVia` 共用同一組守衛 route。重派後 CH confirm 因 attempt history 不唯一只進 review，須 BO 對舊 attempt 登記無入款後引用同一 receipt settle。三角色＋Prefix 權限、重派後舊 attempt 拒絕與 Freeze overlay 由真登入 HTTP 的 `DepositMenuAuthorizationHttpIntegrationTest`、`NativeCardholderDepositReadyHttpIntegrationTest` 驗證。Agent v1 Deposit 與 HouseIngress 不受 catalog 控制。不增加 menu alias；target 啟用仍須 Operator 執行 `menu-catalog.sql` 與 grant（含 Prefix `role_method`）、provision `spay4.deposit.proof-root` 並部署。`/bo/v2/depositOrders/page` 與 `/export` 另接受 `currencyId`、`bankCode`（`payer_bank_code`）、`account`（`payer_account` exact only）、`name`（`payer_name` contains），規則見 [Order Workspace filter 規則](order-workspace-contract.md#付款方與收款方查詢-filters)（#394）；page／export／stats 另接受 `receivingType`（`HOUSE`／`CARDHOLDER`／`SUPPLY_CHANNEL`）（依 current receiver 指標，未指派不命中，#485）；page／stats／export 另接受 `methodCode`（`DEPOSIT_WORKSPACE`／`SUPPLY_DEPOSIT_WORKSPACE`，menu bootstrap 的 `methodCode`；server 重驗 caller 直接持有該選單 VIEW，否則 403；Superadmin 未帶時為兩選單聯集，#516）。`GET /bo/v2/depositOrders/page` 與 `/{id}` 回 `proofs` 陣列（#777）：每個元素含 `proofId`、`attemptId`、`mimeType`、`proofStatus`、`createTime`，依 `proofId` 由新到舊，不回 `fileId`、`relativePath`、`contentHash`、驗證 digest 與上傳者身分；`REGISTER_RECEIPT` 取用其中 `proofId`，`targetAttemptId` 須等於該元素的 `attemptId`。可見範圍與 `proofs/{proofId}/content` 相同：Gateway 只列自己 attempt 的 proof，Prefix 列與僅歷史可見的 Gateway 列回 `[]`，沒有 proof 也回 `[]`；每次 page 或 detail 最多多一次 proof 查詢，不讀 storage bytes；stats 與 export（CSV 欄位與內容）不變。Deposit `status` 列舉、`routeCode` 篩選、evidence／settle body 必填與 `actual` 比對、proof content MIME 見 [Order Workspace 契約](order-workspace-contract.md#現行工作台規則)（#778）。 |
| `SUPPLY_WITHDRAWAL_WORKSPACE` | Superadmin、Supplier、Gateway；Prefix own Agent 安全 VIEW 與 own Agent 建單（INSERT，#1019） | 已啟用（#377）：runtime catalog/B/F/R 為 `READY/READY/ENABLED`，conditional gate 隨 canonical catalog 註冊 18 條 BO mappings（含 #983 `GET /stats` 頁籤筆數）；`spay4.cardholder.native-enabled=true` 且已設定 `spay4.internal.cardholder-key` 時另註冊 7 條 `/internal/cardholder/withdrawalOrders` internal CH routes（只供 `spay4-cardholder` edge 呼叫，#423），callback 與 assignment expiry 排程隨之註冊（Deposit 關閉時只派送 Withdrawal，#375）。同一 resource 宣告 VIEW／INSERT／UPDATE；catalog per-principal map 的 `prefix(VIEW, INSERT)` 限 Prefix VIEW 與建單（#1019：`agentId` 可省略、只能是 own Agent，他 Agent 404／40002，帶 `supplierId`／`gatewayId` 400／40005；沒有 UPDATE，不能核准自己建的單）。WithdrawalInitialAssignmentServiceImpl#assign（此參考僅供內部環境使用，公開版本未提供） 初派與 WithdrawalRedispatchWriterImpl#replace（此參考僅供內部環境使用，公開版本未提供） 重派呼叫 `admission.reserve`，WithdrawalPaymentAdmissionServiceImpl#reserve（此參考僅供內部環境使用，公開版本未提供） 寫入原日WITHDRAWAL Account obligation／shared fairness。#211 CH 單次提交與 BO optional actual 規則不變；三角色＋Prefix 權限與重派後舊 attempt 拒絕由真登入 HTTP 的 `WithdrawalMenuAuthorizationHttpIntegrationTest`、`NativeCardholderWithdrawalRedispatchHttpIntegrationTest` 驗證。不增加 menu alias；target 啟用仍須 Operator 執行 `menu-catalog.sql` 與 grant、provision `spay4.withdrawal.proof-root` 並部署。`/bo/v2/withdrawalOrders/page` 與 `/export` 另接受 `currencyId`、`bankCode`（`receiver_bank_code`）、`account`（`receiver_account` exact only）、`name`（`receiver_name` contains），規則見 [Order Workspace filter 規則](order-workspace-contract.md#付款方與收款方查詢-filters)（#394）；另接受 `originType`（`BO`／`AGENT_API`）（畫面 MANUAL／AUTO）與 `rejectSource`（`CARDHOLDER`／`SYSTEM`／`UPPER`）（依 Order 目前狀態判定，#485）。page／export／stats 另接受頁籤 `bucket`（`PENDING_APPROVAL`／`AWAITING_DISPATCH`／`PENDING_CH_ACTION`／`PENDING_BO_REVIEW`／`COMPLETED`，與 `status` AND）；`GET /bo/v2/withdrawalOrders/stats` 與 page 同 parser／scope，回 `all` 與五個 bucket 筆數，對應表見 [Withdrawal target contract](withdrawal-target-native-contract.md#2-1-1-頁籤-bucket-與-stats)（#983）。`GET /bo/v2/withdrawalOrders/page` 與 `/{id}` 回 `proofs` 陣列（#777）：元素欄位、排序與不回傳的欄位同 Deposit；可見範圍與 `proofs/{proofId}/content` 相同，Prefix 列與僅歷史可見的 Gateway 列回 `[]`，沒有 proof 也回 `[]`；提款 proof 主要供查看，同一 proof 不可再被另一筆 evidence 使用；每次 page 或 detail 最多多一次 proof 查詢，不讀 storage bytes；export（CSV 欄位與內容）不變。 |
| `DEPOSIT_WORKSPACE` | Superadmin 全域；Prefix own Agent | Agent Deposit（#516，ADR-0450（此參考僅供內部環境使用，公開版本未提供））：收款方為 HOUSE、`AGENT_ACCOUNT`（#992）或從未分派的單，Superadmin 帶 `methodCode=DEPOSIT_WORKSPACE` 只看此範圍並在此初次分派（從未分派且 `PENDING_REVIEW` 的單回傳 `ASSIGN` action）；Superadmin 為新增授權，既有 Prefix 角色授權不自動補。已啟用（#381）：BO routes 宣告 `SUPPLY_DEPOSIT_WORKSPACE`，Prefix 由 catalog `prefixVia` 轉查本 resource 的 `role_method`（VIEW／UPDATE）；service 限 own Agent 的全部單，只有 HOUSE current 單與 `AGENT_ACCOUNT` 單（#992，唯讀：actions 至多 `REPORT`）為完整投影，其餘遮罩 Supplier／Gateway／Cardholder／Account／attempt／version／備註、無 actions，證明檔、evidence 與 mutation 404，不接受跨 owner selector。唯一例外是 Prefix 回報（#542，ADR-0453（此參考僅供內部環境使用，公開版本未提供））：`POST /bo/v2/depositOrders/{orderId}/reports` 直接宣告本 resource 的 UPDATE（Supplier／Gateway 無此 grant 回 403，Superadmin 由 service 回 403），只限 Prefix 對 own Agent、current 分派給 Cardholder 的單；body `reasonCategory`（`PAID_NOT_CREDITED`／`AMOUNT_MISMATCH`／`OTHER`）與 `description`（strip 後 1..200 code points），raw `{reportId, orderId, orderNo, reasonCategory, createTime}`；回報即建立 `PREFIX_REPORT` 告警給該單 current Supply Gateway（不可營運改 Supplier，再無則 Superadmin），自回報時間依升級門檻通知 Supplier、Superadmin；不寫 `bo_remark`、不改訂單。訂單仍停在回報時的分派、狀態與進入時間即為未處理：同內容重送回原結果，不同內容 409／40003；House Card、別的 Agent、未分派與不存在 404／40002；內容不合法 400／40005；拒絕寫 WARN（orderId、agentId、原因類別，不含說明）。`GET /bo/v2/depositOrders/page`、`/{id}` 與 `/export` 在 `houseCardId` 後回 nullable `houseCardName`（#873）：HOUSE current 單的 House Card 目前 displayName（不是指派當時的快照，同頁一次批次查詢，比照 `supplierName`／`gatewayName`）；非 HOUSE 單、僅歷史可見的列、Prefix 遮罩列與卡片已不存在時為 null；CSV 欄位緊接 `houseCardId`。 |
| `SUPPLIER_SETTING` | Superadmin global；Supplier（Admin 與 User）只限 own Supplier（其他 Supplier 404），key／LINE credential 寫入限 Supplier Admin，營運狀態、建立、刪除、列表、匯出限 Superadmin（#958，ADR-0482（此參考僅供內部環境使用，公開版本未提供）） | 已啟用 Supplier page/detail/onboarding/basic update/status/soft delete/CSV，以及 Online Cardholders／New Cards 只讀 projection；完整 action set 為 `VIEW/INSERT/UPDATE/DELETE`。 |
| `SUPPLY_GATEWAY` | Superadmin global；Supplier own Gateway；Gateway self Gateway | 已啟用 Gateway setting；Superadmin 與 Supplier 為 `VIEW/INSERT/UPDATE/DELETE`，Gateway 只有 `VIEW/UPDATE`（#959，ADR-0486（此參考僅供內部環境使用，公開版本未提供））。 |
| `SUPPLY_HOUSE_CARD` | Superadmin、Prefix | 已啟用 HOUSE Card CRUD，以及帳面餘額調帳與 balance log（#420，ADR-0428（此參考僅供內部環境使用，公開版本未提供）：`PUT {houseCardId}/bookBalance` 用 UPDATE，`balanceLogs/page`、`balanceLogs/{logId}` 用 VIEW）；Prefix 固定 own Agent，System Admin 可指定 target Agent，action 為 VIEW/INSERT/UPDATE/DELETE。`GET /bo/v2/houseCard/page` 接受 `agentId`、`cardStatus`、`bankId`、`displayName` 與 `limitSource`（`CUSTOM`／`DEFAULT`）（#485：`CUSTOM` 為兩項 configured 限額任一非 NULL，數值等於預設也算；`DEFAULT` 為兩者皆 NULL；未知、重複或空值回 400 `FIELD_VALIDATE_FAILED`（data `limitSource`／`invalid`）並寫不含原始值的 WARN）；無 export。 |
| `SUPPLY_PT_RULE` | Superadmin 全域；Supplier 僅 own Gateway/Cardholder descendants；Gateway 僅 own Cardholder descendants | 已啟用 PT tree、current/pending/history revision page 與完整 desired-state update；service 拒絕 Supplier/Gateway self mutation。 |
| `SUPPLY_COMMISSION_REPORT` | Superadmin 全部；Supplier own Supplier、旗下 Gateway 與其 Cardholder；Gateway self 與旗下 Cardholder | 已啟用（#407）：runtime catalog/B/F/R 為 `READY/READY/ENABLED`。`SUPPLY_COMMISSION_REPORT` 註冊 `GET /bo/v2/supplyCommissionReports/page`、`/detail`、`/orders`、`/export`。讀 hourly aggregate 於查詢時計算 PT：volume／count 依查看者時區月份（Superadmin `+08:00`，Supplier／Gateway 用 Supplier offset），PT 依同名 Commission month，Cardholder 套 threshold／base fee、Supplier／Gateway 為 volume×rate/100，整月 `HALF_UP` round 一次；期間最多 6 個月；任一列缺規則、Currency metadata 無效或 overflow 整份 409（ADR-0430（此參考僅供內部環境使用，公開版本未提供））。未帶 `level` 時預設查看者頂層（Superadmin、Supplier 為 `SUPPLIER`，Supply Gateway 為 `GATEWAY`；帶 `gatewayId` 時為 `GATEWAY`），往下看以明確 `level` 加上層列的 `ownerId` 作 `supplierId`／`gatewayId`；`SUPPLIER` 層每列為月份 × Supplier × 幣別 × 方向、套 Supplier 自己的 PT，各層不得跨層加總（ADR-0446（此參考僅供內部環境使用，公開版本未提供），#518）。Superadmin 可帶 `supplierId`／`gatewayId`，Supplier 只可帶自己鏈內的 `gatewayId`，不存在或不相符 not-found（WARN log），Supplier 帶 `supplierId` 或 Supply Gateway 帶任何 selector 回 400。export 寫 HIGH `EXPORT_SUPPLY_COMMISSION_REPORT` audit。`/detail` 只回每日 count／volume，不算每日 PT；逐筆訂單用 `/orders`（#957）：以列的 `level`、`ownerId`、`currencyId`、`direction` 加查看者時區 `fromDate`..`toDate`（含頭尾最多 31 天）與 `pageNumber`／`pageSize` 分頁，每筆回 orderNo、成功時間（UTC 與查看者時間）、commissionMonth、所屬 Gateway（id／code／name）與 CH（id／username）（Supply Channel 為 null）、計入金額（fact 加 correction）與該筆 PT，依 (成功時間, fact id) 排序；日期依 fact 的 UTC hour 加查看者 offset 歸日，筆數與金額和 `/detail` 對應日期一致。每筆 PT 為參考值（`ptReferenceOnly=true`）：同 owner、currency、direction、commission month 內從該月第一筆累計，round(F(累計到本筆)) − round(F(累計到前一筆))，與 CH App（#431）同法，同月全部訂單加總等於月 PT（ADR-0172（此參考僅供內部環境使用，公開版本未提供）、ADR-0181（此參考僅供內部環境使用，公開版本未提供））；範圍錯誤 400、越權 not-found、有訂單的月份缺規則或 Currency metadata 無效 409，三者皆寫 WARN（actorType、actorId、level、ownerId、reason）；純讀取，不寫 audit、不提供 CSV。target 啟用仍須 Operator 執行 `menu-catalog.sql` 並部署。原 Prefix 專用的 `COMMISSION_REPORT`（`/bo/v2/commissionReports/page`、`/export`）已於 #517 移除（ADR-0451（此參考僅供內部環境使用，公開版本未提供）），歷史 `EXPORT_COMMISSION_REPORT` audit 仍可查詢。 |
| `CHANNEL_ANALYTICS` | Superadmin 指定一個 Agent；Prefix 僅 own Agent；Supplier／Gateway 403 | 已啟用 Channel Analytics（#529，ADR-0454（此參考僅供內部環境使用，公開版本未提供））：`GET /bo/v2/channelAnalytics/options`、`/page`、`/detail` 皆要求 VIEW、唯讀、不提供 CSV；Prefix 只看收款路線代號，不見 Supply Gateway／Supply Channel／Supplier 真實身分。完整語意見 [Channel Analytics API](#channel-analytics-api)。 |
| `CHANNEL_DEPOSIT_REPORT` | Superadmin 指定一個 Agent；Prefix 僅 own Agent；Supplier／Gateway 403 | 已啟用 Channel Deposit Report（#530，ADR-0454（此參考僅供內部環境使用，公開版本未提供））：`GET /bo/v2/depositOrders/report/options`、`/page`、`/subtotals`、`/export` 皆要求 VIEW；明細與「Agent × 收款路線」小計，歸屬同 Channel Analytics；會員帳號遮罩，Prefix 只看收款路線代號、非 House Card 且非 `AGENT_ACCOUNT` 單備註為 null；export 寫 HIGH `EXPORT_CHANNEL_DEPOSIT_REPORT` audit。完整語意見 [Channel Deposit Report API](#channel-deposit-report-api)。 |
| `SYSTEM_CONFIGURATION` | Superadmin global；具 active grant 的 Prefix 僅 own Agent override | 已啟用的 System Configuration；`/bo/v2/config` 的 GET/PUT/DELETE 分別要求 VIEW/UPDATE/DELETE；Global-only key 不可 Agent 覆寫。 |
| `DOMAIN_AUDIT_LOG` | Superadmin 全域；具 active VIEW grant 的 Prefix own Agent；Supplier own Supplier；Gateway self Gateway | 已啟用 `/bo/v2/domainAudit/page`、`/bo/v2/domainAudit/{id}`、`/bo/v2/domainAudit/actions`；Supply realm 使用 fixed-profile VIEW baseline，detail 跨 scope 回 not-found。page／detail／export 帶目前顯示值 `agentPrefix`、`supplierName`、`gatewayName`（非 snapshot）；Prefix 的 `supplierName`／`gatewayName` 一律 null（#878）；Prefix 另看到 null 的 `supplierId`／`gatewayId`、Supply 操作者的 `actorId`／`actorAccount`，detail 摘要中的 Supply 身分 ID 為 null，`supplierId`／`gatewayId` 篩選忽略、`actorAccount`／`actorId` 篩選不命中 Supply 操作者（#884，[Domain Audit 契約](domain-audit-contract.md)）。 |
| `SYSTEM_NOTIFICATION_HISTORY` | System Admin global | 已啟用 Notification history（`/bo/v2/notificationHistory/page`、`/bo/v2/notificationHistory/{id}`，#332／#339）與 type 選項 `GET /bo/v2/notificationHistory/options`（#875，VIEW、唯讀、不寫 audit）：raw root 陣列，每組 `{category, types}`，category 依 `ORDERS`、`CARDS`、`SECURITY`、`SYSTEM`，types 依 `NotificationEventType` 宣告順序，所有 types 聯集即 page `type` filter 的全部可用值；回應由 Backend enum 與 `NotificationCatalog` 產生，新增 type 時自動出現，對應見 [通知 type 與 category](#通知-type-與-category)。非 Superadmin 403，policy guard 寫 WARN 請求摘要（actor id 與 `authFailure` 分類）。人工通知送出走 hidden `SYSTEM_NOTIFICATION_SEND`，見 [Hidden resource 路由](#hidden-resource-路由)。 |
| `SYSTEM_HOURLY_PROJECTION` | Superadmin global | 已啟用 parked hourly projection fact 列表與人工重排（#457，ADR-0218（此參考僅供內部環境使用，公開版本未提供））：`GET /bo/v2/hourlyProjectionFacts/page`（VIEW）只列 `NEEDS_ATTENTION`，回 `queueId`／`version`、來源與 owner（id 加 `agentPrefix`、`supplierName`、`supplyGatewayName` 顯示欄位）、attempt／人工重排次數、去敏 `lastClassification`／`lastErrorCode` 與 `lastFailureTime`，可依 `agentId`、`errorCode`、`failedFrom`／`failedUntil` 篩選，依最後失敗時間、queue id 遞減；`POST /bo/v2/hourlyProjectionFacts/{queueId}/requeue`（UPDATE）必帶 `expectedVersion` 與 `reason`（strip 後 1..500 code points），CAS 改回 `RETRYING` 立即到期、不在 request 內投影，版本過期 409 `RESOURCE_VERSION_CONFLICT`、非 parked 409 `RESOURCE_STATE_CONFLICT`、不存在 404；`POST /bo/v2/hourlyProjectionFacts/requeueBatch`（UPDATE）1..50 筆不重複共用 reason，格式不合法整批 400，每筆各自 transaction 依序回報 `REQUEUED`／`VERSION_CONFLICT`／`NOT_PARKED`／`NOT_FOUND`，該筆非預期失敗時整筆 rollback 並回 `FAILED`、其他筆照常處理。每筆成功寫 HIGH `REQUEUE_HOURLY_PROJECTION_FACT` audit；人工重排只多給一次嘗試，再失敗立即重新 park；重排前已開始、晚到才記錄的失敗照實計次但不消耗新授予的嘗試。Park 時另寫 SUPERADMIN 範圍 `bo_alert`（`HOURLY_PROJECTION_PARKED`），經 `/bo/v2/alerts/**` 與 SSE 只給 Superadmin。target 啟用須先套用 #472 菜單 seed 再部署。 |
| `RESET_PASSWORD` | Superadmin、Prefix、Supplier、Gateway | My Profile self-service password change；所有 caller 只可更新自己。 |

<a id="通知-type-與-category"></a>
### 通知 type 與 category

`NotificationEventType` 每個值固定屬於一個 category（`NotificationCatalog`，ADR-0414（此參考僅供內部環境使用，公開版本未提供））；`GET /bo/v2/notificationHistory/options` 的回應與本表一致，順序同 API。

| category | type |
| --- | --- |
| `ORDERS` | `NEW_DEPOSIT`、`NEW_WITHDRAWAL`、`DEPOSIT_ASSIGNMENT_ENDED`、`DEPOSIT_SETTLED`、`DEPOSIT_CLOSED`、`WITHDRAWAL_ASSIGNMENT_ENDED`、`WITHDRAWAL_SETTLED`、`WITHDRAWAL_CLOSED` |
| `CARDS` | `CARD_FROZEN`、`CARD_PAUSED`、`CARD_UPDATED`、`CARD_DELETED`、`CARD_APPLICATION_APPROVED`、`CARD_APPLICATION_REJECTED` |
| `SECURITY` | `PASSWORD_RESET`、`LOGIN_NEW_DEVICE` |
| `SYSTEM` | `ANNOUNCEMENT`、`MAINTENANCE`、`ALERT`、`BALANCE_ADJUSTED` |

## Supply PT Rule API

`SUPPLY_PT_RULE` 的 tree、revision 與 update 皆從 authenticated principal immutable owner chain 推導 scope。`GET /bo/v2/supplyPtRules/tree` 回傳 current/pending 與非敏感 owner display fields；`GET /bo/v2/supplyPtRules/revisions` 必須以可重複或 comma-separated `statuses` 指定 `CURRENT`、`PENDING_NEXT_MONTH` 或 `HISTORICAL`；`PUT /bo/v2/supplyPtRules/{ownerType}/{ownerId}` 為完整 desired-state mutation，先驗證 aggregate `expectedVersion`。成功回應與 revisions 的 `SupplyPtRevisionVo` 帶 `policyVersion`（policy aggregate version）：下一次 Save 的 `expectedVersion` 直接用它；`revisionVersion` 是 revision row 的 version，不能當 `expectedVersion`（ADR-0439（此參考僅供內部環境使用，公開版本未提供））。Supplier/Gateway 雙方向 rate 必填，Cardholder 另要求兩方向 base fee/threshold；rate 為 `0..100`、最多四位小數的 canonical plain decimal string（只收字串，ADR-0170）；base fee／threshold 為非負 plain decimal，JSON number 或 string 皆可（ADR-0489（此參考僅供內部環境使用，公開版本未提供））。首次實際變更消耗 owner-level immediate entitlement，後續實際變更 upsert pending；numeric no-op 不改版、不寫 audit，也不改 `modifier`。`SupplyPtRevisionVo` 另回 revision 的 nullable `creator`／`modifier`：bootstrap 沿用上層 Supplier／Gateway／Cardholder 建立者，BO Save 寫操作者 account，排程升版寫 `PT_ROLLOVER`；歷史資料為 null（#549）。子節點同一生效期間 rate 不得高於 parent，父節點下修若使任何後代超限即 fail closed。

## Supply Cardholder Management API

`SUPPLY_CARDHOLDER_MANAGEMENT` 的每條 route 都要求對應 policy action，並由 service 以 `Cardholder → Gateway → Supplier` immutable owner chain 重新驗證 scope。Superadmin 可查看及管理全域；Supplier 可查看及管理 own Gateway descendants；Gateway 可查看及管理 own Gateway Cardholder（建立、改名、狀態、強制登出、重設密碼；`GATEWAY_ADMIN` 與 `GATEWAY_USER` 相同，ADR-0473（此參考僅供內部環境使用，公開版本未提供））。Prefix 不可見且不授權。跨 scope、缺失或不一致 owner chain 一律回 not-found。

| 類型 | Method | Path | 行為 |
| --- | --- | --- | --- |
| Read | `GET` | `/bo/v2/supplyCardholders`、`/{cardholderId}` | `VIEW`；page 可用 gatewayId、supplierId、cardholderId exact、cardholderStatus、username exact、displayName contains 與 `createdFrom`／`createdUntil`（UTC half-open），全部與 server scope AND，固定 `gatewayId ASC, id ASC`，完整回傳非機密 master projection；`creator`／`modifier` 為建立者與最近管理異動者（BO 操作者 account，App 本人改密碼為 `cardholder:<username>`），登入簿記不改寫，歷史資料為 null（#549）。 |
| Create | `POST` | `/bo/v2/supplyCardholders` | `INSERT`；只接受 gatewayId、username、displayName、reason（Gateway 不可帶 gatewayId，由 server 綁定 own Gateway，帶了回 400）；原子建立 Cardholder、PT policy 與 current zero-value revision pair，temporary password 僅成功 response 一次性回傳。 |
| Profile | `PUT` | `/bo/v2/supplyCardholders/{cardholderId}` | `UPDATE`；只可變更 displayName，要求 expectedVersion 與 audit reason；canonical 同值為 no-op。 |
| Status | `PUT` | `/bo/v2/supplyCardholders/{cardholderId}/status` | `UPDATE`；action 為 `LOCK/UNLOCK/ACTIVATE/DEACTIVATE`。僅 LOCK 帶 `ADMIN_LOCKED/RISK_REVIEW` lockReason；`FAILED_LOGIN_LIMIT` 拒絕。先驗證 scope/version，進入 LOCKED/INACTIVE 時同 transaction 撤銷全部 active session 與寫 audit。 |
| Force logout | `POST` | `/bo/v2/supplyCardholders/{cardholderId}/forceLogout` | `UPDATE`；body 只接受 `expectedVersion`。同 transaction 結束全部 active session（`end_reason=ADMIN_FORCE_LOGOUT`），refresh token 與該 session 註冊的推播裝置一併失效；帳號狀態不變，進行中訂單不取消、不改派。有撤銷時寫一筆 audit，沒有 active session 時成功且不寫 audit（ADR-0418（此參考僅供內部環境使用，公開版本未提供））。 |
| Password reset | `POST` | `/bo/v2/supplyCardholders/{cardholderId}/password/reset` | `UPDATE`；限 Superadmin、own Supplier 的 Supplier 帳號（`SUPPLIER_ADMIN` 與 `SUPPLIER_USER`，ADR-0480（此參考僅供內部環境使用，公開版本未提供））與 own Gateway 的 Gateway 帳號（不分 `supplyRole`，ADR-0473（此參考僅供內部環境使用，公開版本未提供））。body 為必填 `expectedVersion` 與可選 `newPassword`：有帶則依 Unified Login Password Policy 驗證後使用，response 不回傳 credential；未帶則 Backend 產生 temporary password，只在成功 response 交付一次。同 transaction 設 `mustChangePassword=true`、清 `failedLoginCount`、只解除 `FAILED_LOGIN_LIMIT` lock、撤銷全部 active session（`end_reason=PASSWORD_RESET`）與其推播裝置，並寫一筆 HIGH audit（ADR-0040（此參考僅供內部環境使用，公開版本未提供）、#390）。 |

Gateway 可解除 Supplier 或 Superadmin 設下的 `RISK_REVIEW`、`ADMIN_LOCKED` 與 `INACTIVE`；系統不記鎖定來源，由 Domain Audit 的 actor 追溯。拒絕（4xx）時 service 記 WARN `supply cardholder command rejected`，含 operation、status、原因分類、actorType／actorId 與 cardholderId，不含 username 或 credential。

除 Create 與未帶 `newPassword` 的 Password reset 一次性交付 `temporaryPassword` 外，所有 response 都不含 password、hash、token、ciphertext 或任何 credential secret，且不嵌入 Payment Account、交易統計或 PT detail。status current-version no-op 不升 version、不寫 audit、不撤銷 session；但 stale version 永遠回 `409 RESOURCE_VERSION_CONFLICT(40051)`。

### Cardholder 強制登出、解除鎖定與重設密碼（前端串接）

三支 API 的契約與實作入口如下，Supplier Setting 的 Online Cardholders 與 Cardholder User Mgmt 直接呼叫本節路徑，不另開 Supplier 路徑入口。成功回應為未包裝的 JSON 物件；錯誤回應為 `{ "code", "message", "data" }` envelope。時間欄位為 UTC 時間點，依 ADR-0409（此參考僅供內部環境使用，公開版本未提供） 輸出 ISO-8601 帶 `Z`（例 `2026-10-14T08:00:00Z`，0 秒不帶小數）。

**409 處理原則：** 收到 `409` 時，前端提示「資料已被其他人更新」，重新載入 Cardholder detail 取得最新 `version` 與狀態，由使用者確認後再操作；不得自動以新 version 重送。

#### 強制登出 Cardholder

- Method／Path：`POST /bo/v2/supplyCardholders/{cardholderId}/forceLogout`
- 權限：`SUPPLY_CARDHOLDER_MANAGEMENT:UPDATE`；Superadmin 全域、Supplier 限 own Gateway descendants；Gateway 帳號不可執行。
- Request body（strict JSON，只允許此欄位）：

```json
{ "expectedVersion": 4 }
```

- 成功 `200`：`invalidatedSessionCount` 為實際結束的 session 數；有撤銷時 `cardholder.version` 前進、`activeSessionCount` 變 0、`sessionsRevokedAt` 更新，`cardholderStatus` 不變。沒有 active session 時同樣回 `200`，`invalidatedSessionCount=0` 且 version 不變。

```json
{
  "cardholder": {
    "cardholderId": 30, "username": "alice_01", "displayName": "Alice",
    "gatewayId": 20, "gatewayCode": "GW", "gatewayName": "Gateway", "supplierId": 10,
    "supplierLoginId": "SUP", "supplierName": "Supplier", "currencyId": 3, "currencyCode": "THB",
    "cardholderStatus": "ACTIVE", "lockReason": null, "lockedTime": null,
    "mustChangePassword": false, "failedLoginCount": 0, "passwordPolicyVersion": 1,
    "activeSessionCount": 0, "lastSessionIssuedAt": "2026-10-14T08:00:00Z", "sessionsRevokedAt": "2026-10-14T09:30:00Z",
    "version": 5, "createTime": "2026-10-01T00:00:00Z", "modifyTime": "2026-10-14T09:30:00Z",
    "creator": "root", "modifier": "root"
  },
  "invalidatedSessionCount": 1
}
```

| HTTP | SystemCode | 情境 | 前端處理 |
| --- | --- | --- | --- |
| `400` | `FIELD_VALIDATE_FAILED(40005)` | 缺少、null、非數字或負數 `expectedVersion`；未知欄位；空 body | 視為前端 bug，修正 request，不重送相同內容 |
| `401` | `NO_AUTHENTICATION(40000)` | BO 登入失效 | 導回登入 |
| `403` | `NO_PERMISSION(40001)` | 無 `UPDATE` 權限或 Gateway 帳號 | 隱藏／停用按鈕並提示無權限 |
| `404` | `DATA_NOT_EXISTS(40002)` | Cardholder 不存在或不在 scope | 提示資料不存在並重新整理列表 |
| `409` | `RESOURCE_VERSION_CONFLICT(40051)` | `expectedVersion` 過期 | 依上方 409 原則重新載入，不自動重送 |

#### 解除鎖定 Cardholder（Unlock）

- Method／Path：`PUT /bo/v2/supplyCardholders/{cardholderId}/status`，`action=UNLOCK`
- 權限：`SUPPLY_CARDHOLDER_MANAGEMENT:UPDATE`；scope 同強制登出。
- Request body（strict JSON；`UNLOCK` 不可帶 `lockReason`，`reason` 為必填 audit 原因，trim 後最多 500 字）：

```json
{ "action": "UNLOCK", "expectedVersion": 4, "reason": "客服確認後解除鎖定" }
```

- 成功 `200`：`LOCKED → ACTIVE`，清除 `lockReason`／`lockedTime`、`failedLoginCount` 歸零並寫 audit；不恢復已撤銷 session，Cardholder 需重新登入。已是 `ACTIVE` 時為 no-op：`stateChanged=false`、version 不變、不寫 audit。

```json
{
  "cardholder": {
    "cardholderId": 30, "username": "alice_01", "displayName": "Alice",
    "gatewayId": 20, "gatewayCode": "GW", "gatewayName": "Gateway", "supplierId": 10,
    "supplierLoginId": "SUP", "supplierName": "Supplier", "currencyId": 3, "currencyCode": "THB",
    "cardholderStatus": "ACTIVE", "lockReason": null, "lockedTime": null,
    "mustChangePassword": false, "failedLoginCount": 0, "passwordPolicyVersion": 1,
    "activeSessionCount": 0, "lastSessionIssuedAt": "2026-10-14T08:00:00Z", "sessionsRevokedAt": "2026-10-14T09:00:00Z",
    "version": 5, "createTime": "2026-10-01T00:00:00Z", "modifyTime": "2026-10-14T09:30:00Z",
    "creator": "root", "modifier": "root"
  },
  "stateChanged": true,
  "invalidatedSessionCount": 0
}
```

| HTTP | SystemCode | 情境 | 前端處理 |
| --- | --- | --- | --- |
| `400` | `FIELD_VALIDATE_FAILED(40005)` | 缺少 `action`／`expectedVersion`／`reason`、帶 `lockReason`、未知欄位、`reason` 空白或超過 500 字 | 修正表單或 request，不重送相同內容 |
| `401` | `NO_AUTHENTICATION(40000)` | BO 登入失效 | 導回登入 |
| `403` | `NO_PERMISSION(40001)` | 無 `UPDATE` 權限或 Gateway 帳號 | 隱藏／停用按鈕並提示無權限 |
| `404` | `DATA_NOT_EXISTS(40002)` | Cardholder 不存在或不在 scope | 提示資料不存在並重新整理列表 |
| `409` | `RESOURCE_VERSION_CONFLICT(40051)` | `expectedVersion` 過期 | 依上方 409 原則重新載入，不自動重送 |
| `409` | `FIELD_VALIDATE_FAILED(40005)`，`data=["status","state conflict"]` | Cardholder 為 `INACTIVE`，不能 Unlock | 重新載入；需要時改用 `ACTIVATE` |

#### 重設 Cardholder 密碼（Password reset）

- Method／Path：`POST /bo/v2/supplyCardholders/{cardholderId}/password/reset`
- 權限：`SUPPLY_CARDHOLDER_MANAGEMENT:UPDATE`；Superadmin 全域，Supplier（`SUPPLIER_ADMIN` 與 `SUPPLIER_USER`，ADR-0480（此參考僅供內部環境使用，公開版本未提供））限 own Gateway descendants，Gateway 帳號限 own Gateway（ADR-0473（此參考僅供內部環境使用，公開版本未提供））。
- Request body（strict JSON；`expectedVersion` 必填，`newPassword` 可省略或 `null`）：

```json
{ "newPassword": "Reset-pass-456", "expectedVersion": 4 }
```

- `newPassword` 有值：依 Unified Login Password Policy（8–20 字、至少 1 個英文字母與 1 個數字、只接受英數與 `! @ # $ % & * _ - ?`、不得含自身 username）驗證，原樣保存為 hash，不 trim；成功 response 的 `temporaryPassword` 為 `null`。
- `newPassword` 省略或 `null`：Backend 產生符合同一政策的 temporary password，只在本次成功 response 的 `temporaryPassword` 交付一次；前端只顯示一次，不得保存或寫入 log。
- 成功 `200`：`cardholder.mustChangePassword=true`、`failedLoginCount=0`；`LOCKED／FAILED_LOGIN_LIMIT` 轉回 `ACTIVE`，`ADMIN_LOCKED`、`RISK_REVIEW` 與 `INACTIVE` 維持原狀。全部 active session 以 `PASSWORD_RESET` 結束，refresh token 與推播裝置失效；Cardholder 以新密碼登入後只能進入受限 change-password flow。

```json
{
  "cardholder": {
    "cardholderId": 30, "username": "alice_01", "displayName": "Alice",
    "gatewayId": 20, "gatewayCode": "GW", "gatewayName": "Gateway", "supplierId": 10,
    "supplierLoginId": "SUP", "supplierName": "Supplier", "currencyId": 3, "currencyCode": "THB",
    "cardholderStatus": "ACTIVE", "lockReason": null, "lockedTime": null,
    "mustChangePassword": true, "failedLoginCount": 0, "passwordPolicyVersion": 1,
    "activeSessionCount": 0, "lastSessionIssuedAt": "2026-10-14T08:00:00Z", "sessionsRevokedAt": "2026-10-19T09:30:00Z",
    "version": 5, "createTime": "2026-10-01T00:00:00Z", "modifyTime": "2026-10-19T09:30:00Z",
    "creator": "root", "modifier": "root"
  },
  "temporaryPassword": null,
  "invalidatedSessionCount": 1
}
```

| HTTP | SystemCode | 情境 | 前端處理 |
| --- | --- | --- | --- |
| `400` | `FIELD_VALIDATE_FAILED(40005)` | 缺少、null、非數字或負數 `expectedVersion`；`newPassword` 非字串；未知欄位；空 body | 視為前端 bug，修正 request，不重送相同內容 |
| `400` | `PASSWORD_FORMAT_ERROR(40011)` | `newPassword` 不符密碼政策 | 提示密碼規則，讓使用者重新輸入 |
| `401` | `NO_AUTHENTICATION(40000)` | BO 登入失效 | 導回登入 |
| `403` | `NO_PERMISSION(40001)` | 無 `UPDATE` 權限（例如 Prefix） | 隱藏／停用按鈕並提示無權限 |
| `404` | `DATA_NOT_EXISTS(40002)` | Cardholder 不存在或不在 scope（含他 Supplier） | 提示資料不存在並重新整理列表 |
| `409` | `RESOURCE_VERSION_CONFLICT(40051)` | `expectedVersion` 過期 | 依上方 409 原則重新載入，不自動重送 |
| `409` | `FIELD_VALIDATE_FAILED(40005)`，`data=["status","state conflict"]` | 帳號 status／lock tuple 不一致（fail closed） | 重新載入；持續發生時回報後端 |

Audit：每次成功重設寫一筆 `RESET_SUPPLY_CARDHOLDER_PASSWORD`（target `SUPPLY_CARDHOLDER`），risk `HIGH`、effect `PASSWORD_CHANGED`。before／after summary 皆含 `cardholderStatus`、`lockReason`、`lockedTime`、`failedLoginCount`、`mustChangePassword`、`sessionEpoch`；after 另含 `credentialSource`（`ADMIN_PROVIDED` 或 `SERVER_GENERATED`）、`endReason`（`PASSWORD_RESET`）與 `invalidatedSessionCount`。summary 不含任何 password、hash 或 temporary password；stale version、密碼政策拒絕與 scope／角色拒絕都不寫 audit。

#### Cardholder 列表篩選

`GET /bo/v2/supplyCardholders` 新增 query：`supplierId`（Superadmin 用於指定 Supplier；不存在或 scope 外的 Supplier 回 `404`，與 `gatewayId` 現行表示一致）、`cardholderId`（exact，scope 外得到空頁）、`createdFrom`（含）與 `createdUntil`（不含）。時間為 ISO-8601 UTC，可帶 `Z`、`+00:00` 或不帶 offset；非 UTC offset、`createdFrom >= createdUntil`、非正數 `supplierId`／`cardholderId` 回 `400 FIELD_VALIDATE_FAILED(40005)`。

`POST /bo/v2/paymentAccounts` direct-create mapping 已移除。正式 Account 目標只能由 scoped Application approval 建立，初始 `ACTIVE/UNFROZEN`、兩方向 disabled、金融值為零；`PaymentAccountController` 已將 create／approve 委派 `OverviewCommandService`，相關八項 commands 與十四項 reads 都已有 source；完整驗收尚未完成，不以既有 internal creator、parser inventory 或 source handlers 冒充 acceptance。Overview 的 22 routes 的 accepted contract 與實作來源須各自核對，conditional gate 關閉時不註冊；B/F/R 維持 `NOT_READY/NOT_READY/NOT_ENABLED`；不得因 foundation 測試或文件通過而開啟 runtime catalog、grants 或前端 menu route。

## Transaction Records API

Agent Transaction Record（`HOUSE_TRANSACTION_WORKSPACE`）與 Supplier Transaction Record（`SUPPLY_TRANSACTION_WORKSPACE`）兩個選單共用同一組路由與同一頁面元件（#513，ADR-0455（此參考僅供內部環境使用，公開版本未提供））。六條路由都宣告 `SUPPLY_TRANSACTION_WORKSPACE`：Superadmin 與 Supplier 直接授權；Prefix 經 catalog `prefixVia` 轉查 `HOUSE_TRANSACTION_WORKSPACE` 的 role grant；Gateway 沒有格子，一律 403。

**路徑名稱限制**：路徑沿用 `/bo/v2/houseCardTransactions` 以維持相容，實際涵蓋 House Card 交易（`house_card_transaction`，屬 Agent）與 Supply Channel 交易（`supply_channel_transaction`，屬 Supplier）兩張分開的表；路徑名稱不代表只回 House Card 交易，請以每列的 `sourceType`（`HOUSE`／`SUPPLY_CHANNEL`）判讀來源。

**身分範圍**：Prefix 只看 own Agent 的 House Card 交易；Supplier 只看 own `supplier_id` 的 Supply Channel 交易；Superadmin 看全部。所有 target identity 的可見性由 server-derived scope 判定，跨 scope 與不存在均為相同 not-found。page／detail 回傳遮罩帳號；raw response 固定為 `text/plain; charset=UTF-8` 並帶 `Cache-Control: no-store`。

**回應包裝**（#892）：controller 類別層宣告 `@Envelope`，page、detail、manualMatch candidates 與 PUT manualMatch 的成功回應為單層 `ResponseVo`：`{"code":2000,"message":"","data":...}`，`data` 為原 `PageVo`（`records`、`total`、`size`、`number`）或 `HouseCardTransactionVo`；BO 前端讀成功回應須改由 `data` 取值（page 為 `data.records` 等）。export（CSV 串流）與 raw-content（`text/plain`）不包裝，內容與 header 不變；錯誤回應維持既有 `{code, message, data}` envelope 與 HTTP status。

**`transactionNo` 路徑參數**：四條 id 路由使用 `{transactionNo}`（opaque string）。新資料 House Card 交易為 `HC-<uuid>`、Supply Channel 交易為 `SC-<uuid>`，回應一律輸出大寫前綴（舊 House Card 資料無前綴者輸出 `HC-`＋原值）。選表規則：`HC-` 前綴（大小寫不拘）只查 House Card 表，比對 `HC-<rest>` 或 `<rest>`；`SC-` 前綴只查 Supply Channel 表；無前綴者查 House Card 表，比對原值或 `HC-`＋原值；純數字暫視為舊 House Card 交易 id（相容，待前端改完另單移除）。找到後再套身分範圍；不存在、前綴不符或範圍外一律回相同 404。`transactionId` 欄位只供 House Card 列相容，Supply Channel 列為 null；告警以 `BoAlertVo.transactionNo` 開啟詳情。

**page 與 export 共用 filters**：

- `methodCode`：`HOUSE_TRANSACTION_WORKSPACE`（只查 House Card 交易）或 `SUPPLY_TRANSACTION_WORKSPACE`（只查 Supply Channel 交易），即 menu bootstrap 的 `methodCode`；server 以 catalog 重驗 caller 直接持有該選單 VIEW（delegate 不算），否則 403。未帶時 Superadmin 為兩表總覽、Prefix 為 own Agent House Card、Supplier 為 own Supplier Supply Channel。
- `agentId`：僅 Superadmin 可選，只查 House Card 表；Prefix 帶非 own Agent、Supplier 帶入均回同一 not-found。
- `supplierId`：僅 Superadmin 可選，只查 Supply Channel 表；Supplier 帶非 own、Prefix 帶入均回同一 not-found。
- `supplyChannelId`：只查 Supply Channel 表（Prefix 帶入回空頁）。
- `matchStatus`：兩種來源皆套用。
- `bankId`、`currencyId`：House Card 交易比對已解析 HOUSE Card 的 immutable Bank／Currency（未解析 HOUSE 的交易不命中）；Supply Channel 交易比對 receiver Bank 與交易 Currency。
- `orderNo`：matched Deposit order number 精確比對，strip 後最多 100 code points。
- `from`／`until`：UTC half-open，ISO-8601 須帶 `Z` 或 `+00:00`；`until` 缺省為 server 現在時間，`from` 缺省為 `until` − 1 天；`from` ≥ `until` 或跨度超過 31 天回 400。三種身分、page 與 export 都套用。

只屬一種來源的篩選（`agentId`、`supplierId`、`supplyChannelId`、`methodCode`）只查該表，含 COUNT。非正數 identity 回 400 `FIELD_VALIDATE_FAILED`。

**排序與分頁**：固定 `transactionTime DESC`、`sourceType`（`HOUSE` 先於 `SUPPLY_CHANNEL`）、`id DESC`，單表查詢也用同一排序。總覽兩表各取排序後前 offset＋pageSize 筆在程式內合併；(`pageNumber`＋1)×`pageSize` 最多 10,000，超過回 400 請縮小區間；`total` 為區間內兩表 COUNT 相加。前端頁碼分頁不變。

**回應欄位**（`HouseCardTransactionVo`，page／detail／manualMatch 共用）：`transactionId`（僅 House Card 相容）、`transactionNo`、`sourceType`、`agentId`（House Card）、`houseCardId`（House Card）、`houseCardName`（House Card；已解析卡片目前的 displayName，不是交易當時的快照；未解析、卡片已不存在與 Supply Channel 交易為 null，#873）、`supplierId`、`supplyChannelId`（Supply Channel；未解析時為 null）、`supplyChannelCode`、`supplyChannelName`（Supply Channel；已解析 Channel 的 code 與目前名稱，不是交易當時的快照，Channel 已刪除仍回；未解析、Channel 已不存在與 House Card 交易為 null；Prefix 只看得到 House Card 交易，這兩欄恆為 null，#874）、`currencyId`、`bankId`、`payerAccountMasked`、`receiverAccountMasked`、`amount`、`transactionTime`、`matchStatus`、`matchMode`、`matchedDepositOrderId`、`matchedOrderNo`、`matchedAssignmentAttemptId`、`matchedTime`。`amount` 為 plain decimal string（不使用科學記號，保留資料庫 scale；#876 起，ADR-0477（此參考僅供內部環境使用，公開版本未提供）），CSV 的 `amount` 與 JSON 逐字相同；manualMatch candidates 的 `requestedAmount` 同為 plain decimal string。

**export**：`GET /bo/v2/houseCardTransactions/export` 匯出與 page 同 scope、filters、時間區間與排序的全部列（忽略 `pageNumber`／`pageSize`）。先 COUNT，超過 100,000 筆回 400（寫 WARN，不寫 audit）。兩表各一個 keyset 游標每批 500 筆交錯合併，寫入加密暫存檔，不整份留在記憶體。欄位與順序為 `transactionId,transactionNo,sourceType,agentId,houseCardId,houseCardName,supplyChannelId,supplyChannelCode,supplyChannelName,payerAccountMasked,receiverAccountMasked,amount,transactionTime,matchStatus,matchMode,matchedDepositOrderId,matchedTime`；帳號只輸出遮罩值、不含 raw notification；`text/csv; charset=UTF-8` without BOM、CRLF、每格加引號並 formula escape（同 Deposit workspace CSV），帶 `Cache-Control: no-store`、`X-Content-Type-Options: nosniff` 與 attachment filename `house-card-transactions.csv`。CSV 完整寫入暫存檔後，依查詢涵蓋的表各於同交易寫一筆 export audit：House Card 表寫 `EXPORT_HOUSE_TRANSACTION_WORKSPACE`（target `HOUSE_TRANSACTION_WORKSPACE`）、Supply Channel 表寫 `EXPORT_SUPPLY_TRANSACTION_WORKSPACE`（target `SUPPLY_TRANSACTION_WORKSPACE`）；target id 為 actor principal id，effect `EXPORTED`，summary 只含該表 `rowCount` 與 `maskedProjection`，risk `HIGH`；`agentId` 與 `supplierId` 互斥而不涵蓋任何表時仍寫一筆 House Card export audit（`rowCount` 0）。交易提交後才交付 bytes；驗證、scope 失敗不寫 audit。

**人工匹配**：House Card 與 Supply Channel 交易的 candidate 不以 amount／payer mismatch 排除（未解析到 HOUSE 卡的交易例外，見下），也不套用自動配對時間窗。House Card 交易只列同 Agent、同已解析 HOUSE、`ASSIGNED` 且未被 HOUSE transaction 結案的 Deposit order；未解析到 HOUSE 卡的交易（#992）只列同 Agent、申請金額與交易金額完全相同、未被配對的 `AGENT_ACCOUNT` 單（`ASSIGNED` 期限內，或到期轉 `PENDING_REVIEW`），以金額不同的單配對回 404；Supply Channel 交易只列同 Supplier、同 Supply Channel、同幣別、`ASSIGNED`、current attempt 未逾期且未被任何 Supply Channel 交易匹配的 Deposit order。request 的 `reason` 必填、清理後保存，且不在 response／audit 回顯。先鎖 target Deposit order 再鎖交易，持鎖重驗後原子結案；Supply Channel 交易與自動匹配共用同一結算（結算、扣 Supply Channel 保留、Supplier PT、callback 同一 transaction，失敗整筆 rollback），寫 `MANUAL_MATCH_SUPPLY_CHANNEL_TRANSACTION`，持鎖重驗失敗回 409 `TRANSACTION_MATCH_CONFLICT`。House Card 交易持鎖重驗失敗（交易已被並發匹配、order 已結案或結算 guard 拒絕）也回 409 `TRANSACTION_MATCH_CONFLICT`，整筆 rollback、不寫 `MANUAL_MATCH_HOUSE_CARD_TRANSACTION`（#881）。可匹配狀態（candidates 與 manualMatch 相同，#872）：`matchStatus` 為 `UNMATCHED`、`PENDING_REVIEW` 或 `MATCH_FAILED`，且交易已對應 House Card 或 Supply Channel，或是未解析到 HOUSE 卡的 Agent 交易（只可配 `AGENT_ACCOUNT` 單，#992）；`MATCHED` 回 404，範圍外、候選不合格也回 404；409 只出現在 manualMatch 持鎖重驗（House Card 與 Supply Channel）。交易回應不另帶可匹配旗標。人工匹配不把告警標為已讀。

**失敗 log**：人工匹配被拒與查詢範圍超限各寫一行 WARN：`transactionNo`、`sourceType`、`supplierId` 或 `agentId` 與原因類別（`STATUS_CONFLICT`、`CANDIDATE_INELIGIBLE`、`OUT_OF_SCOPE`、`CONCURRENT_CONFLICT`、`AMOUNT_MISMATCH`、`RANGE_EXCEEDED`），House Card 人工匹配另記 request 的 `orderId`（#992），不含帳號、戶名與原始通知。

**Supply Channel 選項**（#874）：`GET /bo/v2/supplyChannels/options` 供 `supplyChannelId` 篩選的下拉選單。宣告 `AUTH_MENU_BOOTSTRAP:VIEW`（比照 `GET /bo/v2/supplyGateways/options`，登入即可）；Superadmin 與 Supplier 由 service 以 fresh guard 重驗 `SUPPLY_TRANSACTION_WORKSPACE:VIEW`，不通過 403（filter 與 service 之間被撤銷時，請求摘要 WARN 帶 actor id 與 `authFailure` 分類、不含帳號；已撤銷 token 由 filter 先回 401）。範圍：Superadmin 全部、Supplier 只看 own `supplier_id`、Prefix 與 Gateway 一律 `[]`；排除已刪除的 Channel。raw root 陣列，每筆 `id`、`code`、`name`、`supplierId`、`currencyId`、`bankId`、`status`（營運狀態 `ACTIVE`／`INACTIVE`）、`accountNoMasked`（遮罩規則同 `payerAccountMasked`，只留最後四碼），以及顯示欄位 `supplierName`（所屬 Supplier 目前名稱）、`currencyCode`（Channel Currency 的 code）、`bankName`（收款 Bank 名稱），三者各自在 Supplier／Currency／Bank 參照不存在時為 null，其他欄位照常（#885）；不回完整帳號。固定 `code ASC`、`id ASC`，不分頁、不接受參數；純讀取，不寫 audit。沒有 `/bo/v2/supplyChannels/{id}` 路由，字面 `options` 不會被 id 路由吃掉。

時間區間預設、31 天、10,000 與 100,000 筆上限為起點值，沒有量測依據，以實測修正；兩表時間排序索引由 #535 交付。

| Method | Path | Required action |
| --- | --- | --- |
| `GET` | `/bo/v2/houseCardTransactions/page` | `VIEW` |
| `GET` | `/bo/v2/houseCardTransactions/export` | `VIEW` |
| `GET` | `/bo/v2/houseCardTransactions/{transactionNo}` | `VIEW` |
| `GET` | `/bo/v2/houseCardTransactions/{transactionNo}/raw-content` | `VIEW` |
| `GET` | `/bo/v2/houseCardTransactions/{transactionNo}/manualMatch/candidates` | `VIEW` |
| `PUT` | `/bo/v2/houseCardTransactions/{transactionNo}/manualMatch` | `UPDATE` |
| `GET` | `/bo/v2/supplyChannels/options` | 登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`）；service 重驗 `SUPPLY_TRANSACTION_WORKSPACE:VIEW` |

此 workspace 不提供 provider payload CRUD、raw notification CSV、dismiss/reject、Withdrawal candidate 或 Legacy transaction fallback。LINE ingress、D1 routing/reservation 與 callback outbox 仍依 Deposit／Withdrawal flow contract 由各自 runtime use case 負責，workspace 不建立 Legacy fallback 或 dual-write。

## Agent Management API

`AGENT_MANAGEMENT` 使用既有 `/bo/v2/agents/**` target-only contract，不新增或保留平行 legacy route。除前節登入即可（`AUTH_MENU_BOOTSTRAP:VIEW`）的 `options` 外，Superadmin 可使用所有下列操作；Prefix 必須具 active 嚴格 JSON `AGENT_MANAGEMENT:VIEW` grant，僅可讀取 `/me`、own `/{agentId}` 與 own LINE credential metadata，不能 list/page、跨 Agent id 或執行任何 mutation／credential rotation。

`GET /bo/v2/agents/page` 每列（`AgentPageItem`）帶 `externalOrderApiCredential` 與 `lineCredentials[]`，欄位與值同 detail 的 `CredentialMetadata`，前端不必另打 detail 即可輪替 key（ADR-0439（此參考僅供內部環境使用，公開版本未提供））：`externalOrderApiCredential.credentialVersion` 是 `PUT /{agentId}/credentials/externalOrderApi` 的 `expectedVersion`；`lineCredentials[].credentialVersion` 是 `PUT /{agentId}/credentials/line/{notificationProviderSourceId}` 的 `expectedVersion`（`secretKeyVersion` 是加密 key 版本，只供顯示）。page 與 detail（含 `/me`）只列 `ACTIVE`／`CURRENT` 且已有 secret 的 credential：未配置或非 `ACTIVE`／`CURRENT` 的 externalOrderApi 為 null；LINE 只列已存在者，首次建立時前端以 `GET /bo/v2/notificationProviderSources/options`（登入即可）取 `ACTIVE` `LINE_WEBHOOK` sources，缺的 source 送 `expectedVersion: null`。`expectedVersion: null` 只在 reference 確實不存在時建立成功；既有但非 `ACTIVE`／`CURRENT` 的 reference 同樣不列出，對它輪替一律 `409 RESOURCE_VERSION_CONFLICT(40051)`。source 非 `ACTIVE` 的 LINE credential 照常列出，前端以 source 清單的 status 停用輪替按鈕。credential 以批次查詢組裝，查詢數不隨列數成長；`/agents/list` 仍回 `AgentListItem`，不含 credential。`CredentialMetadata` 另帶 nullable `creator`／`modifier`（#548）：首次輪替的操作者帳號與最近一次輪替的操作者帳號，取自 credential reference；#548 前建立的 credential 為 null，不回填。

| 類型 | Method | Path |
| --- | --- | --- |
| Read | `GET` | `/bo/v2/agents/me`、`/{agentId}`、`/{agentId}/credentials/line` |
| Superadmin list | `GET` | `/bo/v2/agents/list`、`/page` |
| Management | `POST` | `/bo/v2/agents` |
| Management | `PUT` | `/{agentId}/status`、`/callback-url`、`/banks` |
| Credential rotation | `PUT` | `/{agentId}/credentials/externalOrderApi`、`/credentials/line/{notificationProviderSourceId}` |

`POST /bo/v2/agents` 的 optional `callbackUrl` 與 `PUT /{agentId}/callback-url` 只接受 absolute `https`、最長 500 字元；`http`、無 scheme、超長或無法解析回 `400`，data 為 `invalid callbackUrl`，不寫入、不寫 audit，只記 WARN（原因分類，不含 URL）。`null` 清除、no-op、授權與成功 audit 不變；response 形狀不變（#630）。

既有 Prefix role 不會因 release 自動取得 grant；System Admin 必須顯式授與 active `VIEW`。新建 Prefix 的 onboarding role 會寫入唯一 `["VIEW"]` grant。legacy `PUT /agent` 的 mutable `businessZone`、custom channel sort 與 Agent channel update 不在 SPay4 contract；deprecated `/agent/{agentId}/token` 不提供替代，external order API 請使用一次性回傳的 credential rotation API。

### Agent–Supply Gateway availability binding API（backend-only 增補）

以下四條 handler 使用既有 `AGENT_MANAGEMENT`，service 每次透過 `AuthService.guard` 重驗 active User／Role／session，僅允許 system-scope Superadmin。Prefix 即使具有 VIEW grant 也不可呼叫；Supplier／Gateway 同樣拒絕。不新增 menu、grant 或 legacy `/supplyGatewayAllocation/**` alias。此增補不代表 Frontend 已接線、target 已升級或已部署；既有 resource 的 B/F/R 狀態不是新功能 acceptance 證據。

Base：`/bo/v2/agents/{agentId}/supplyGatewayAllocations`，Agent／Gateway IDs 必須為正整數；不存在 Agent 回 `404 DATA_NOT_EXISTS`。所有 success 由局部 response advice 包為單層 `ResponseVo<T>`，不影響其他 API。

| Method | Path suffix | Policy action | Request／結果 |
| --- | --- | --- | --- |
| `GET` | base | `VIEW` | 只接受 zero-based `pageNumber`（預設 0）、`pageSize=1..500`（預設 20）；回 `allocationVersion, enabledCount, records, total, size, number`。 |
| `PUT` | `/{gatewayId}` | `UPDATE` | body 必填 JSON boolean `enabled`、`reason`、non-negative integer `expectedVersion`；回 version／affectedCount／enabledCount／total／受操作 `row`。 |
| `POST` | `/enableAll` | `UPDATE` | body 只接受必填 `expectedVersion`、`reason`；回 version／counts，不回 rows。 |
| `POST` | `/disableAll` | `UPDATE` | body 同上；停用全部既有 enabled flags，`affectedCount` 可大於 eligible `total`。 |

未知 query／body 欄位（含已移除的 `priority`，ADR-0466（此參考僅供內部環境使用，公開版本未提供））、缺值、非法型別與範圍回 `400 FIELD_VALIDATE_FAILED`；不接受 owner 或 external channel 設定。`reason` 規則比照 Supply Channel：strip 後 1..500 code points、不可含控制字元，只寫入 domain audit。Row 欄位為 `gatewayId, gatewayCode, gatewayName, supplierId, supplierCode, supplierName, enabled`；missing mapping 顯示 false。固定排序 `gatewayName ASC, gatewayId ASC`；total／enabledCount 計完整 eligible scope，越界頁仍保留 summary。

Eligible 僅要求 Supplier row／operational ACTIVE、Gateway row／operational ACTIVE、Agent Currency＝Gateway Currency；Agent 與 Supplier 的 business UTC offset 可以不同（ADR-0449（此參考僅供內部環境使用，公開版本未提供））；不要求已有 mapping、direction config、Account、Cardholder 或 routing admission。Agent 與 Gateway 是跨 Supplier 可綁的 N:M，Supplier 只經 Gateway owner chain 解析；不參與 routing 順序、不改 Gateway owner 或歷史訂單／reservation／financial facts。

Active Agent 可首次 enable 或設定完整單列。Missing mapping 的 `enabled=false` 是不建 row 的 no-op。Inactive Agent 仍可查詢、停用及 disableAll，不可 enable。Existing binding 即使 Supplier／Gateway inactive、deleted、失配或 master 缺失，仍可安全停用；不恢復 lifecycle，缺失 master 顯示欄位為 null。Cleanup row 可不在 eligible page，summary 仍只計 eligible scope。

`expectedVersion` 比對獨立 `agent.allocation_version`；stale no-op 也回 `409 RESOURCE_VERSION_CONFLICT(40051)`，不得自動 retry。真正 single／bulk change 最多推進 root 一次，每列 JPA version 仍屬內部 concurrency。Fresh no-op 仍驗證 `reason`，但不改 version／metadata／audit。GET 使用同一 read-only repeatable-read snapshot；commands 先鎖 Agent，再穩定鎖 Supplier → Gateway → allocation；enableAll 凍結 candidates 後重驗，失配整批 409／rollback，並行新建 Gateway 不納入。DB `priority` 欄位保留但不對外：新列固定 1、既有值不改寫；disableAll 不受 eligible 或 master lifecycle 限制。

每個實際變更 mapping 一筆 `UPDATE_AGENT_GATEWAY_ALLOCATION`／`ENABLE_ALL_AGENT_GATEWAY_ALLOCATIONS`／`DISABLE_ALL_AGENT_GATEWAY_ALLOCATIONS` audit，含 actor、owner scope、mapping identity、before／after enabled／row version／time，after summary 另記 `reason`；bulk structured summary 共用 server-generated operationId，每列記同一個 `reason`。拒絕分支記 WARN（operation、actorId、agentId、gatewayId、原因分類），不含 reason 全文或原始 payload。Recorder 與 bindings／root version 同交易，audit failure 完整 rollback。

Schema：fresh target 初始化使用 V4 DDL（此參考僅供內部環境使用，公開版本未提供），依 SQL README（此參考僅供內部環境使用，公開版本未提供） 審核與 read-back；allocationVersion default 0、enabled default false、priority default 1、pair unique 與 availability index 均已整合。#216 source 核對後已退休舊 manual migration 及其 preflight tests，現行測試直接核對 V4 初始化契約。Existing target 升級須另案準備並審核 artifact，不得重跑 fresh DDL、清庫或 backfill；pair duplicates、priority≤0 與 owner-reference 異常不得自動修復，**不自動將既有 priority=0 改成 1**。Operator 仍須確認 target identity、備份、停止相關 writers，遇錯立即停止。Source 核對不代表 target 已初始化、升級或部署。

驗證入口：`SupplyGatewayAllocationServiceImplTest`、`SupplyGatewayAllocationControllerTest`、`SupplyGatewayAllocationIntegrationTest` 與既有 `DepositPaymentAdmissionIntegrationTest`。MySQL integration 必須以 `SPAY4_TESTCONTAINERS_ENABLED=true` 實跑，skipped 不算通過。

### Agent–Supply Channel 分配 API（#442）

Prefix List Agent 編輯管理哪些 Supply Channel 可承接該 Agent 的訂單（ADR-0431（此參考僅供內部環境使用，公開版本未提供））。四條 handler 沿用 `AGENT_MANAGEMENT`，service 以 `AuthService.guard` 重驗後只允許 system-scope Superadmin；Prefix 即使具 grant、Supplier／Gateway 一律 403，不新增 menu 或 grant。成功回 raw VO／`PageVo`（不包 `ResponseVo`）；Agent 不存在回 `404 DATA_NOT_EXISTS`。實作：SupplyChannelAllocationController（此參考僅供內部環境使用，公開版本未提供）、SupplyChannelAllocationServiceImpl（此參考僅供內部環境使用，公開版本未提供）。

Base：`/bo/v2/agents/{agentId}/supplyChannelAllocations`

| Method | Path suffix | Policy action | Request／結果 |
| --- | --- | --- | --- |
| `GET` | base | `VIEW` | `pageNumber`／`pageSize`；此 Agent 既有分配，固定 id ASC，含 Channel 已停用或已刪除（`channelDeleted=true`）的分配。 |
| `GET` | `/candidates` | `VIEW` | `pageNumber`／`pageSize`；Currency 與 Agent 相同且未刪除的 Supply Channel（含 INACTIVE），固定 id ASC，`allocated` 標示已分配。 |
| `POST` | base | `INSERT` | body `supplyChannelId`、`enabled`、`customPriority`、`reason`；回分配。 |
| `PUT` | `/{supplyChannelId}` | `UPDATE` | body `enabled`、`customPriority`、`expectedVersion`、`reason`；回分配，無此分配 404。 |

- 分配 row 欄位：`agentId, supplyChannelId, supplyChannelCode, supplyChannelName, supplierId, supplierCode, supplierName, channelStatus, channelDeleted, enabled, customPriority, version, creator, createTime, modifier, modifyTime`；不含帳號或戶名。
- 驗證：`enabled` 必填 boolean；`customPriority` 必填非負整數（小數 400）；`reason` strip 後 1..500 code points、不含控制字元。失敗回 `400 FIELD_VALIDATE_FAILED` 與 `[field, reason]`。
- 拒絕：Channel 不存在或已刪除 `[supplyChannelId, invalid]`；Channel 與 Agent Currency 不一致 `[supplyChannelId, currency mismatch]`；同一 `(agentId, supplyChannelId)` 已有分配 `409 UNIQUE_KEY_EXISTS(40007)`（unique key 保證並行建立只有一筆）。
- Channel 停用或刪除不 cascade 分配；已刪除 Channel 的分配仍可停用或改 `customPriority`，但不可由停用改為啟用（`[enabled, invalid]`）。不提供刪除分配，停止承接以 `enabled=false` 表達。
- `expectedVersion` 比對分配 row version，缺少或過期回 `409 RESOURCE_VERSION_CONFLICT(40051)`；current-version 同值為 no-op，不升 version、不寫 audit。
- `enabled` 本期只保存，下一期 routing 生效；`customPriority` 只供顯示；不提供 `routingMode`、`merchantRate`、`feeBearing`。
- Audit：每筆實際變更同交易一筆 `CREATE_AGENT_SUPPLY_CHANNEL_ALLOCATION`／`UPDATE_AGENT_SUPPLY_CHANNEL_ALLOCATION`（target `AGENT_SUPPLY_CHANNEL_ALLOCATION`，risk `HIGH`），owner scope 一律 null，只有 Superadmin 查得到（#438 追加決策）；summary 含 `agentId`、`supplyChannelId`、`enabled`、`customPriority`、`version`，after 另含 `reason` 與 Update 的 `changedFields`。Audit 失敗整筆 rollback。
- Schema：#445 的 `supply_channel_agent_allocation`。驗證入口：`SupplyChannelAllocationIntegrationTest`（`SPAY4_TESTCONTAINERS_ENABLED=true` 實跑，skipped 不算通過）。

### Agent callback outbox 列表、明細與 DEAD 人工補送（#455，backend-only 增補）

以下三條 handler 使用既有 `AGENT_MANAGEMENT`，不新增 catalog code、menu 或 grant；service 每次經 `AuthService.require` 重驗 active User／Role／session 與 grant 後，再以程式只允許 Superadmin。Prefix 即使具有 `VIEW`／`UPDATE` grant 也回 `403 NO_PERMISSION`；Supplier／Gateway 同樣拒絕。Success 不包 `ResponseVo`；此增補不代表 Frontend 已接線、target 已升級或已部署。

Base：`/bo/v2/agentCallbackOutbox`，outbox id 必須為正整數，不存在回 `404 DATA_NOT_EXISTS`。

| Method | Path suffix | Policy action | Request／結果 |
| --- | --- | --- | --- |
| `GET` | `/page` | `VIEW` | 可選 `agentId`（正整數）、`dispatchStatus`（`PENDING`／`PROCESSING`／`RETRY`／`SENT`／`DEAD`）、`from`／`to`（outbox `createTime` 的 UTC 半開區間 `[from, to)`，非 UTC offset 或 `from` 晚於 `to` 回 400）、zero-based `pageNumber`（預設 0）、`pageSize=1..500`（預設 20）；固定 `createTime DESC, id DESC`，回 `PageVo`。 |
| `GET` | `/{id}` | `VIEW` | 回安全 lifecycle 欄位與 immutable `payloadJson`。 |
| `POST` | `/{id}/manualResend` | `UPDATE` | body 必填 `expectedVersion`（non-negative integer）與 `reason`（strip 後 1..500 code points、不可含控制字元，只寫入 audit）；成功回 `202` 與 `id, dispatchStatus=PENDING, dispatchVersion`。 |

列表 row 為 `id, dispatchVersion, agentId, agentPrefix, orderType, orderId, eventType, eventId, dispatchStatus, attemptCount, dispatchEndReason, nextRetryTime, createTime, modifyTime`；明細另含 `claimLeaseExpiresTime, lastErrorCode, lastErrorTime, providerResponseCode, sentTime, dispatchEndedTime, payloadJson`。`agentPrefix` 為目前 Agent display，缺失時為 null；兩者都不回 URL snapshot、credential reference、key 或簽章材料。不提供逐次嘗試歷史 API；`lastErrorCode` 只保留最近一次的安全 code。

補送只接受 `DEAD`，各種結束原因皆可（`CALLBACK_URL_UNAVAILABLE`、`CALLBACK_CREDENTIAL_UNAVAILABLE`、`CALLBACK_CURRENCY_UNAVAILABLE`、`UNSAFE_TARGET`、`CREDENTIAL_UNAVAILABLE`、`HTTP_REJECTED`、`ATTEMPTS_EXHAUSTED`）。Service 先依 Order→outbox 鎖序鎖定，再依序驗：`expectedVersion` 不符回 `409 RESOURCE_VERSION_CONFLICT(40051)`；非 DEAD 回 `409 RESOURCE_STATE_CONFLICT(40054)`（data `NOT_DEAD`）；Agent 目前 callback URL 或 current EXTERNAL_ORDER_API credential 缺失回同一 409（data `CALLBACK_URL_UNAVAILABLE`／`CALLBACK_CREDENTIAL_UNAVAILABLE`），修好後才可補送。並行補送同一 version 只有一筆成功，其餘 409。

成功時同一 transaction 將 outbox `DEAD→PENDING`、`attempt_count` 歸零、`dispatch_version` +1、清除 sent／end／lease／retry 欄位，target snapshot 改為 Agent 目前 URL／credential reference，並把 Order `callback_status` 投影改回 `PENDING`；`payload_json`、`idempotency_key`（event id）與 Order 金融狀態不變。既有 native worker 之後依原 5 次 committed claim 與 1／5／30／60 分鐘 backoff 重送；每次 attempt 照常 fresh 讀 Agent current URL／key、重做 HTTPS／DNS／public IP 安全檢查，並產生新的 nonce 與 `X-Spay-Callback-Id`。換 key（ADR-0013）不會自動重排仍在送的 callback。補送前已發出的 lease 一律被 stale finalize 拒絕。

同交易寫一筆 `MANUAL_RESEND_AGENT_CALLBACK` audit（見 [Domain audit](domain-audit-contract.md#4-bo-endpoint-catalog)）；audit 失敗整筆 rollback。列表與明細不寫 audit。

驗證入口：`AgentCallbackOutboxManualResendTest`（DB-free lifecycle）與 `AgentCallbackOutboxManagementHttpIntegrationTest`（隔離 MySQL→HTTP，含本地 HTTPS receiver），後者必須以 `SPAY4_TESTCONTAINERS_ENABLED=true` 實跑，skipped 不算通過。

## Bank Management API

`BANK_MANAGEMENT` 的 page、by-currency、create、update 與 status handler 都要求對應 policy action（`VIEW`／`INSERT`／`UPDATE`），並在 service 再次確認 `SUPERADMIN`；`GET /bo/v2/banks/options` 見上方「需登入、免 resource-action grant API」節。Bank 沒有 `expectedVersion`；same-value update 與 same-status 切換不寫入、不寫 audit。

| 類型 | Method | Path | Authority 與資料範圍 |
| --- | --- | --- | --- |
| Read | `GET` | `/bo/v2/banks/page`、`/currency/{currencyId}` | `VIEW`；page 固定 code ASC，by-currency 不依 status 過濾。 |
| Create | `POST` | `/bo/v2/banks` | `INSERT`；驗證 ACTIVE Currency 與 code／codeId uniqueness，201 回 Bank。 |
| Update | `PUT` | `/{bankId}` | `UPDATE`；只改 name／localeName／keyword／decimalFuzzing／amountCooldownTime。 |
| Status | `PUT` | `/{bankId}/status` | `UPDATE`；只接受 `ACTIVE`／`INACTIVE`，204，不修改既有 Agent-Bank 關聯。 |

三種 mutation request 皆必填 `reason`（#395）：strip 後 1..500 code points（`DepositOperationPolicy.REASON_MAX_CODE_POINTS`）且不可含控制字元；缺漏、空白、超長或含控制字元回 400 `FIELD_VALIDATE_FAILED`、error data `["reason"]`，Bank 與 audit 皆不寫入。reason 只寫入 `CREATE_BANK`／`UPDATE_BANK`／`UPDATE_BANK_STATUS` audit after summary 的 `reason` key，不存 Bank 欄位、不在 response 回顯，也不計入 update 的 `changedFields`。

## Notification Provider Source API

`NOTIFICATION_PROVIDER_SOURCE` 的 page、detail、parser profile 選項、create、update、status 與 delete handler 都要求對應 policy action，並在 service 再次 fresh-check active `SUPERADMIN`。建立 source 固定為 `LINE_WEBHOOK`／`INACTIVE`；source type 與 implementation vendor 不可變。更新／status／delete 必須提供 current `expectedVersion`，409 `RESOURCE_VERSION_CONFLICT(40051)` 必須 reload 後重確認，same-value/status request 不寫 metadata 或 audit。

| 類型 | Method | Path | Authority 與資料範圍 |
| --- | --- | --- | --- |
| Read | `GET` | `/bo/v2/notificationProviderSources/page`、`/{sourceId}` | `VIEW`；page 可選 vendor/profile/status/display name filter，固定 `implementationVendor ASC, id ASC`，只回傳非機密 detail。 |
| Options | `GET` | `/bo/v2/notificationProviderSources/parserProfiles` | `VIEW`；新增／編輯表單的 parser profile 下拉，raw root 字串陣列、依字母排序、不分頁，只回正式 profile（目前 `["LINE_VENDOR"]`）；測試用 profile 不列出但仍可送出（#877）。 |
| Create | `POST` | `/bo/v2/notificationProviderSources` | `INSERT`；只接受已註冊 parser profile，source 固定 `LINE_WEBHOOK`／`INACTIVE`。 |
| Update/lifecycle | `PUT` | `/{sourceId}`、`/{sourceId}/status` | `UPDATE`；只可在 `INACTIVE` 時更新 display name/profile；啟用時重新驗證 parser registry。 |
| Delete | `DELETE` | `/{sourceId}`，JSON body `{"expectedVersion"}` | `DELETE`；僅 physical delete 未被任何 credential reference 引用的 `INACTIVE` source；version 省略或 null 回 409（ADR-0421，不接受 query string）。 |

Provider source 不保存或回傳 API key、secret、fingerprint、ciphertext 或 callback URL。`PUT /bo/v2/agents/{agentId}/credentials/line/{notificationProviderSourceId}` 是唯一 LINE secret lifecycle endpoint，且只接受 active `LINE_WEBHOOK` source。

## Access Role Management API

`ACCESS_ROLE_MANAGEMENT` 的所有 endpoint 都受同一 resource/action policy guard 與 fresh active `SUPERADMIN` service guard 保護；例外是下表的 `GET /bo/v2/access/roles/options`，它宣告 `AUTH_MENU_BOOTSTRAP:VIEW`，登入即可，只有 Superadmin 才走 fresh guard。既有 Role list/detail、permission resource、create、grant replacement、status、delete 共七條 route 保持原 contract；新增 User Role assignment 不新增一般後台帳號 CRUD、credential、TOTP、session 或 password API。

| 類型 | Method | Path | Authority 與資料範圍 | Response 包裝（[契約例外](authorization-menu-contract.md#通用規則與專責契約的適用順序)） |
| --- | --- | --- | --- | --- |
| Role read | `GET` | `/bo/v2/access/roles`、`/roles/{roleId}`、`/permission-resources` | `VIEW`；管理 system 與 Agent-owned Role、canonical grants 與可指派 B/F/R-ready resource。 | 皆 raw root：list `PageVo<RoleSummary>`、detail `RoleDetail`（16 條 reads）、`permission-resources` 為 `PermissionResource` 陣列（#605）；`allowedActions` 是所有 principal 的聯集，`prefixAllowedActions` 是 Agent Role 可授予的 catalog Prefix 上限，不開放給 Prefix 或以 `prefixVia` 委派的 resource 為空陣列（#706）。 |
| Role options | `GET` | `/bo/v2/access/roles/options` | `AUTH_MENU_BOOTSTRAP:VIEW`（#717）；Superadmin 過 fresh guard，不通過 `403 NO_PERMISSION`；Prefix、Supplier、Gateway 一律回 `[]`，忽略 `agentId`、不查 Role。`agentId` 選填，不帶回 system 與所有 Agent，帶了只回該 Agent，查無此 Agent 回 `[]`，非數字 `400`。只回 `status=ACTIVE`，排除 `isAdmin=false` 的 system Role，不依 Agent 狀態過濾；固定 `agentId ASC`（system 在前）、`name ASC`、`id ASC`；不分頁。已撤銷的 token 由 Bearer filter 先回 `401`，`403` 只出現在 filter 通過後才被撤銷的窗口。 | raw root `RoleOption` 陣列：`id`、`name`、`agentId`、`agentPrefix`、`isAdmin`（system 的 `agentId`、`agentPrefix` 為 null）。 |
| Role mutation | `POST` / `PUT` / `DELETE` | `/bo/v2/access/roles`、`/roles/{roleId}`、`/roles/{roleId}/status`、`/roles/{roleId}` | `INSERT`／`UPDATE`／`DELETE`；grant/status 變更依既有規則撤銷引用 User session。`agentId` 非 null 的 Role，create／update 的每個 grant 須在該 resource 的 Prefix 上限內（ADR-0422（此參考僅供內部環境使用，公開版本未提供）），超過時整筆 `400 FIELD_VALIDATE_FAILED(40005)` 不寫入；system scope Role 不套用。既有資料不動，Role 已存的無效 grant 在 update 送出同一項時同樣被拒絕，須先移除（#706）。 | create `201`、update `200` 皆 raw root `RoleDetail`，不包 `ResponseVo`（#605）；status、delete 為 `204` 無 body。 |
| Assignment read | `GET` | `/bo/v2/access/role-assignments` | `VIEW`；以 `agentId`、`account`、`statuses`、zero-based `pageNumber`／`pageSize=1..500` filter，僅回傳 User identity/display、status/version 與 Role identity/name/status。 | raw root `PageVo<RoleAssignmentSummary>`（#605）。 |
| Assignment mutation | `PUT` | `/bo/v2/access/role-assignments/{userId}` | `UPDATE`；body 提供 `roleId`、target User `expectedVersion`。Role 先鎖定、再鎖定 User；兩者必須 ACTIVE 且 `agentId`（含 system `null`）完全一致；system User（`agentId` 為 null）的 target Role 另須 `isAdmin=true`，否則 `400 FIELD_VALIDATE_FAILED(40005)` 不寫入，此檢查先於版本驗證與 same Role no-op，既有非法綁定可改綁回 admin Role 修復（#718）。實際變更會撤銷 target session 並寫入 `ASSIGN_USER_PRINCIPAL_ROLE`／`ROLE_ASSIGNED` audit；same Role 在 version 驗證後為 no-op。 | `204` 無 body。 |

找不到、inactive、cross-owner 或 stale assignment 一律拒絕且不寫 audit；409 `RESOURCE_VERSION_CONFLICT(40051)` 必須 reload、重確認且不可自動 retry。

Role detail（含 create／update response）的每筆 `grants[]`（`RoleGrant`）另帶 nullable `creator`／`modifier`（#548）：建立該 grant 的帳號，以及最近一次實際改變該 grant actions 或啟停的帳號；grant replacement 中 actions 不變的 grant 與 no-op update 不改 `modifier`，Role 的 rename／status／delete 也不改 grant 的 `modifier`。#548 前建立的 grant 為 null，不回填。

## Access User Management API

`ACCESS_USER_MANAGEMENT` 的所有 endpoint 都受同一 resource/action policy guard 與 fresh active `SUPERADMIN` service guard 保護。此 resource 管理 system 與 Agent scope BO User；所有 read projection 與 audit/log/error 都不得包含 password、password hash、TOTP secret/code/ciphertext、lock/replay 或 session state。

| 類型 | Method | Path | Authority 與資料範圍 | Response 包裝（[契約例外](authorization-menu-contract.md#通用規則與專責契約的適用順序)） |
| --- | --- | --- | --- | --- |
| User read | `GET` | `/bo/v2/access/users`、`/users/{userId}` | `VIEW`；list 以 `agentId`、`account`、`name`、`roleName`、`statuses`、`lastLoginIp` 與 zero-based `pageNumber`／`pageSize=1..500` filter，固定依 `agentId, account, id`；回傳 account、Agent Prefix、Role display、status、version、metadata 與 nullable lastLoginIp。IP filter 為 trim 後最多45字元 literal contains，wildcards escape、空白忽略，不支援 CIDR。 | 皆 raw root：list `PageVo`、detail `UserDetail`（16 條 reads）。 |
| User create | `POST` | `/bo/v2/access/users` | `INSERT`；account 為 1..25 個 Unicode code points（對齊 `user.account VARCHAR(25)`），前後不可有空白，超長於寫入前回 400／`FIELD_VALIDATE_FAILED (40005)` `invalid account`（#502）；管理員提供 policy-compliant password；後端產生 Base32 TOTP secret、加密保存並只在 `201` response 交付一次 setup secret，沒有 QR code。system User 必須為 system `isAdmin=true` ACTIVE Role；Agent User 的 Agent 與 Role 必須 ACTIVE 且 owner scope 相同。 | `201` raw root `{user, totpSetupSecret}`，不包 `ResponseVo`（#605）。 |
| User update | `PUT` | `/bo/v2/access/users/{userId}` | `UPDATE`；只可更新 name、description、Role 與 expectedVersion；account、owner 不可變。實際 Role 改綁撤銷目標所有 session；same payload 為 no-op。 | `200` raw root `UserDetail`，不包 `ResponseVo`（#605）。 |
| User lifecycle | `PUT` / `DELETE` | `/bo/v2/access/users/{userId}/status`、`/users/{userId}` | `UPDATE`／`DELETE`；status 僅接受 `ACTIVE/INACTIVE` 並在實際變更撤銷 session。Superadmin 不可停用自己：本人送 `INACTIVE` 在取鎖與版本檢查前回 400／`FIELD_VALIDATE_FAILED (40005)` `cannot disable own account`，不寫入；本人送 `ACTIVE` 維持版本檢查後 no-op。停用 system User 時依 id 順序鎖 actor 與 target 並鎖後重驗（ADR-0464（此參考僅供內部環境使用，公開版本未提供）），互相停用的輸家回 403／`NO_PERMISSION (40001)`。delete 為不可還原的 User-local `DELETED`，拒絕 admin Role User，成功撤銷 session；已刪除 User 不可再 mutation。 | `204` 無 body。 |
| User TOTP reset | `POST` | `/bo/v2/access/users/{userId}/totp/reset` | `UPDATE`（#468）；Superadmin 可重設 Prefix User 與其他 Superadmin，不可重設本人（403），非 Superadmin 403。request 只收 required `expectedVersion`（缺少、負數或過期 409 `RESOURCE_VERSION_CONFLICT`）；不存在或已 `DELETED` 404。立即換新 encrypted TOTP secret，清除防重放 time step、失敗次數與 lock，撤銷所有 session，version 與 session epoch +1；password 與 status 不變，inactive User 或 inactive 上層仍可重設且不因此啟用。response 為單層 envelope `{totpSetupSecret, version}`，新 Base32 setup secret 僅本次揭露，由 Superadmin 以安全管道轉交；不新增登入分支。HIGH `RESET_USER_PRINCIPAL_TOTP` audit 不含 secret。 | 單層 envelope `ResponseVo<{totpSetupSecret, version}>`。 |

system-scope account 唯一由 DB 保障（DEC-01，#489）：`user.system_account`（`agent_id` 為 null 時等於 `account`）上的 `uk_user_system_account` 與既有 `uk_user_agent_account` 並存，沿用 `utf8mb4_unicode_ci` 不分大小寫、含所有 status（已刪除與停用帳號仍佔用）。服務保留同 scope 查詢預檢；預檢後併發建立被 `uk_user_system_account` 擋下時同樣回 409 `DATA_ALREADY_EXISTS`（40003）、不寫 audit，其他 integrity 錯誤維持全域 409 `UNIQUE_KEY_EXISTS`。

## Supplier Account 與 Supplier onboarding API

**Supplier Setting：** [專責 contract](supplier-setting-api-contract.md) 對應完整 Supplier＋DEFAULT Gateway Create、creation-only offset、原子 optional name/status Update、全條件 CSV，以及 Online Cardholders／New Cards 只讀 projection（ADR-0417（此參考僅供內部環境使用，公開版本未提供））；每條 endpoint 的 request／response 範例與錯誤處置見該契約。下表、OpenAPI annotations／Postman 與 source contract 同步；breaking Create／Update 不提供舊 payload 或 flat response fallback。

`SUPPLIER_ACCOUNT_LIST` 的 list/detail 預設排除 soft-deleted account。Superadmin 可跨 Supplier 管理；Supplier Admin 的 `supplierId` request input 一律忽略並由 fresh principal 導出 own Supplier scope，且只能操作 `SUPPLIER_USER`。登入 ID 與 role 均 immutable，不提供 generic update endpoint。狀態變更、soft delete 與 credential recovery 都要求 `expectedVersion`；使帳號不可登入的 mutation 會撤銷既有 session。

| 類型 | Method | Path | Authority 與資料範圍 |
| --- | --- | --- | --- |
| Supplier read | `GET` | `/bo/v2/suppliers`、`/{supplierId}` | `SUPPLIER_SETTING:VIEW`；page 僅 Superadmin，detail 另開放 own Supplier（其他 Supplier 404）。page 固定 `id ASC`、`pageNumber` zero-based、`pageSize=1..500`，可用 code/loginId exact、supplierName contains、supplierStatus filter，預設排除 `DELETED`。 |
| Supplier onboarding | `POST` | `/bo/v2/suppliers` | `SUPPLIER_SETTING:INSERT`；fresh Superadmin。單一 canonical uppercase Login ID、required ACTIVE `defaultGatewayCurrencyId`，原子建立 Supplier＋DEFAULT Gateway、兩個帳號、兩份 PT 與十四個 effects 的一筆 audit；HTTP 200 raw 四個 roots，一次性交付兩組獨立 credentials。optional 固定 offset 皆缺失／null 才預設 +07:00；不接受 code/name alias，禁止 POST auto retry。 |
| Supplier update | `PUT` | `/bo/v2/suppliers/{supplierId}`、`/{supplierId}/status` | `SUPPLIER_SETTING:UPDATE`；`/status` 僅 Superadmin；own Supplier 只能改名稱，`supplierStatus` 有傳須等於現值否則 403；required `expectedVersion`，optional `supplierName/supplierStatus` 有傳才更新且不可 null；ACTIVE/INACTIVE。同交易只推進一次 version／audit；current no-op 不改 metadata/audit，stale no-op 仍 409。identity／offset（含同值）一律拒絕，status-only 委派同一規則。 |
| Supplier external provider | `GET`／`PUT` | `/bo/v2/suppliers/{supplierId}/externalProvider` | `SUPPLIER_SETTING:VIEW`／`UPDATE`；GET 為 fresh Superadmin 與 own Supplier，PUT 為 Superadmin 與 own Supplier Admin（Supplier User 403）。只配置不對接：保存 apiUrl 與 write-only key／iv（`CredentialCrypto` 加密存 `supplier_external_provider_secret`），read 只回 `keyConfigured`／`ivConfigured`；PUT 必填 `expectedVersion`／`reason`，key／iv 同時提供才替換；audit 沿用 `UPDATE_SUPPLIER`（`setting=externalProvider`）、owner scope null、不含 secret（[§4.1](supplier-setting-api-contract.md#41-外部支付商設定bov2supplierssupplieridexternalprovider)）。 |
| Supplier CSV | `GET` | `/bo/v2/suppliers/export` | `SUPPLIER_SETTING:VIEW`；僅 fresh Superadmin（Supplier 403），僅四個業務 filters，拒絕 pagination／owner／unknown／duplicate keys。與 list 共用 safe projection，全符合條件 id ASC、單一 repeatable-read snapshot；UTF-8 無 BOM／CRLF／formula 防護，no-store／nosniff，不產生 audit；中途失敗終止下載。 |
| Supplier delete | `DELETE` | `/bo/v2/suppliers/{supplierId}` | `SUPPLIER_SETTING:DELETE`；僅 Superadmin（Supplier 對 own Supplier 403、其他 Supplier 404）；必須帶 `expectedVersion`。鎖定 root 並驗證 version 後一次檢查所有 blocker，任一存在回 409＋`DATA_ALREADY_EXISTS (40003)`，`data: {blockers:[{blockerType,count}]}` 只列 count>0、依固定順序：`GATEWAY`（未刪除，含 DEFAULT）、`SUPPLY_CHANNEL`（未刪除，含 `INACTIVE`）、`SUPPLIER_LINE_CREDENTIAL`（`CURRENT`；`REVOKED` 不擋）。成功 soft delete 不可復原、同交易清除外部支付商密鑰、撤銷所有 retained Supplier Account formal session，保留歷史 Channel、分配與憑證 metadata；`DELETE_SUPPLIER` audit owner scope 為 null（#519）。 |
| Supplier online cardholders | `GET` | `/bo/v2/suppliers/{supplierId}/onlineCardholders` | `SUPPLIER_SETTING:VIEW`；fresh Superadmin 與 own Supplier，Supplier 不存在／DELETED／其他 Supplier 404。委派 Overview 判定，只回 `loginStatus` 為 `LOGGED_IN`／`LOGOUT_PENDING` 的 Cardholder；query 只接受 `gatewayId/username/displayName/loginStatus/pageNumber/pageSize`，其他或重複 key 400。固定 gatewayId、cardholderId ASC；raw PageVo、no-store，不含金額與 `availableActions`。每列帶 Cardholder `version`（同一 read snapshot）：force logout／unlock 走 Cardholder resource API，`expectedVersion` 直接用它。 |
| Supplier new cards | `GET` | `/bo/v2/suppliers/{supplierId}/newCards` | `SUPPLIER_SETTING:VIEW`；fresh Superadmin 與 own Supplier，Supplier 不存在／DELETED／其他 Supplier 404。委派 Overview，只回 PENDING Payment Account Application（狀態不開放篩選）；query 只接受 `gatewayId/bankId/pageNumber/pageSize`，其他或重複 key 400。固定 gatewayId、cardholderId、applicationId ASC；raw PageVo、no-store，含完整帳號，不含金額與 `availableActions`。每列帶 `applicationVersion`：approve／reject／cancel 的 `expectedVersion` 直接用它。 |
| Supplier LINE credential | `GET`／`POST`／`PUT`／`DELETE` | `/bo/v2/suppliers/{supplierId}/lineCredentials`、`/{credentialId}` | `SUPPLIER_SETTING:VIEW`／`INSERT`／`UPDATE`／`DELETE`；GET 為 fresh Superadmin 與 own Supplier，發行／輪替／撤銷為 Superadmin 與 own Supplier Admin（Supplier User 403），其他 Supplier 404。Supplier＋Currency＋LINE_WEBHOOK provider source 最多一筆 `CURRENT`；發行與輪替 response 一次性揭露完整 apiKey／apiSecret，GET 只回遮罩 metadata；輪替／撤銷必填 `expectedVersion`，三種 mutation 必填 `reason`；audit 沿用 `UPDATE_SUPPLIER`（`setting=lineCredential`）、owner scope null、不含 secret；本期無 ingress（[§12](supplier-setting-api-contract.md#12-supplier-line-credentialbov2supplierssupplieridlinecredentials)）。 |
| Account read | `GET` | `/bo/v2/supplierAccounts`、`/{accountId}` | `VIEW`；Superadmin 可選 `supplierId`，Supplier Admin 固定 own Supplier scope。cross-scope、deleted 或不存在 target 一律 not-found。 |
| Account create | `POST` | `/bo/v2/supplierAccounts` | `INSERT`；固定建立 `SUPPLIER_USER`。request 帶 `supplierId`、`account` 與必填 write-only `password`（建立時雜湊保存、不回傳）；建立時不生成也不回傳 TOTP credential。Supplier Admin 忽略 request 的 `supplierId`。 |
| TOTP reset | `POST` | `/bo/v2/supplierAccounts/{accountId}/totp/reset` | `UPDATE`；必須帶 `expectedVersion`。生成或覆蓋 TOTP secret、撤銷 target 全部 session，新 secret 只在本次 response 交付一次。 |
| Lifecycle | `PUT` / `DELETE` | `/bo/v2/supplierAccounts/{accountId}/status`、`/{accountId}` | `UPDATE`／`DELETE`；禁止 self disable/delete 與移除最後有效 `SUPPLIER_ADMIN`。 |

Supplier projection 回傳 `supplierId`、`code`、`loginId`、`supplierName`、`businessUtcOffset`、`supplierStatus`、`version` 與 `creator/createTime/modifier/modifyTime`。Supplier Account list/detail 另回 `gaReady` 與 nullable ISO-8601 UTC `lastLoginTime`，只取 formal session 簽發時間、不計 temporary challenge。Supplier Account 與 Gateway Account 的 list/detail 另回 nullable `creator`／`modifier`：建立者與最近管理異動者的 account snapshot（BO／Supplier 操作者 account；本人改密碼、登出寫本人 account），登入失敗、批次撤銷等系統簿記不改寫，本欄上線前的歷史資料為 null（#549）。deleted／不存在 target 一律 not-found；stale version 一律 HTTP 409，前端 reload 後由使用者重確認，禁止自動 retry。`INACTIVE` Supplier 不可作新 Deposit／Withdrawal 分配候選；實際轉為 INACTIVE 時同交易撤銷 Supplier 帳號、旗下 Gateway 帳號與 Cardholder 的 session 及推播註冊，INACTIVE 期間不能登入，重新 ACTIVE 後依其他 eligibility 恢復但舊 session 不恢復（ADR-0104／0328，#449）。

## Supply Gateway API

`SUPPLY_GATEWAY` 已完成完整 B/F/R，所有 route 都要求對應 policy action，並由 service 以 authenticated actor 導出 scope。Superadmin 可跨 Supplier 操作完整 CRUD；Supplier 對 own Gateway 有完整 CRUD（#959，ADR-0486（此參考僅供內部環境使用，公開版本未提供））；Gateway 僅能讀取與更新 self Gateway，`SupplyActorPolicy` 拒絕其 `INSERT`／`DELETE`，Prefix 一律拒絕。越權（catalog 403、Gateway 改自己狀態 403）與跨 scope（404）各記一行 WARN `supply gateway <操作> rejected`（actorType、actorId、gatewayId、supplierId、reason；route policy 擋下者由請求摘要 WARN `authFailure=POLICY_DENIED` 記錄）；path、request owner selector 與 menu projection 都不能放寬 server-derived scope。

| 類型 | Method | Path | Authority 與資料範圍 |
| --- | --- | --- | --- |
| Read | `GET` | `/bo/v2/supplyGateways`、`/{gatewayId}` | `VIEW`；Superadmin 可跨 owner，Supplier 僅 own Gateway，Gateway 僅 self Gateway；列表新增 positive `supplierId/currencyId`，與 server scope AND，跨 scope 回空頁。page/detail 另回 metadata；deleted、cross-scope 或不存在 target 一律 not-found。四個 limits（`depositMinAmount`、`depositMaxAmount`、`withdrawalMinAmount`、`withdrawalMaxAmount`）在 page、detail 與回傳 Gateway projection 的 command 皆為 canonical plain decimal string（移除多餘尾零、零為 `"0"`；#876 起，ADR-0145（此參考僅供內部環境使用，公開版本未提供）、ADR-0477（此參考僅供內部環境使用，公開版本未提供））；request wire 開關不變。 |
| Create | `POST` | `/bo/v2/supplyGateways` | `INSERT`；Superadmin 或 Supplier（Admin 與 User），建立 Gateway 與兩方向 initial config，成功回 200。Supplier 的 `supplierId` 必須是自己的 Supplier，否則回 404 `40002` 且不建立，並記 WARN `reason=SUPPLIER_OUT_OF_SCOPE`（#959）。選填 `supplyGatewayStatus`（`ACTIVE`／`INACTIVE`，省略或 null 為 `ACTIVE`，其他值 400 且不建立任何資料）與 `changeReason`（trim 後空白視為未提供；有值時寫入 `CREATE_SUPPLY_GATEWAY` audit after summary）；`INACTIVE` 建立時 initial PT 與兩方向 config 照常建立（#434）。某方向兩值皆正且 min > max 時回 400 `40005`，`data` 為 `["depositMinAmount", "must not exceed depositMaxAmount"]` 或 `["withdrawalMinAmount", "must not exceed withdrawalMaxAmount"]`（兩方向皆倒置回 Deposit），並記 WARN `reason=DEPOSIT_RANGE_INVERTED`／`WITHDRAWAL_RANGE_INVERTED`（含 actorId、supplierId，不含金額；#951）。 |
| Update | `PUT` | `/{gatewayId}` | `UPDATE`；Superadmin、owning Supplier 或 self Gateway（Gateway Admin 與 Gateway User）。名稱與營運設定合併為單一完整取代（#997，ADR-0492（此參考僅供內部環境使用，公開版本未提供）；舊 `/{gatewayId}/name` 與 `/{gatewayId}/operationalConfig` 已移除，呼叫回 404）：strict JSON，八欄必填 `gatewayName`（trim 後 1～100，不檢查唯一性）、`supplyGatewayStatus`、四個 limits（request 接受 JSON number 或 plain decimal string，文法不符回 `[field, "invalid format"]`，ADR-0489（此參考僅供內部環境使用，公開版本未提供））、`changeReason`（只改名稱與同值 no-op 亦必填）、`expectedVersion`；缺少或 null 回 400 `40005`，未宣告欄位（如 `supplierId`）回 400。欄位檢查在鎖定前；鎖定後依序驗權、驗 version（缺 `expectedVersion` 回 400 `40005`，不符 409 `40051`）。Gateway 可改名稱與四個 limits，`supplyGatewayStatus` 必須等於現值，否則 403 `40001` 並記 WARN `supply gateway update rejected … reason=GATEWAY_STATUS_SELF_CHANGE`；他人 Gateway 404 並記 WARN `reason=OUT_OF_SCOPE`（#959，ADR-0486）。回完整 Gateway projection；名稱、狀態與四個 limits 全部相同為成功 no-op，不升 version、不寫 audit。名稱有變記 `UPDATE_SUPPLY_GATEWAY_NAME`、狀態或 limits 有變記 `UPDATE_SUPPLY_GATEWAY_OPERATIONAL_CONFIG`，兩者都變同交易兩列，兩列 after 都帶 trim 後的 `changeReason`。status 實際由 `ACTIVE` 轉為 `INACTIVE` 時，同交易撤銷該 Gateway 全部帳號 session 與旗下 Cardholder session／推播註冊（`GATEWAY_DEACTIVATED`），audit after 記撤銷計數；INACTIVE 期間不能登入，重新 ACTIVE 不恢復舊 session（ADR-0111／0328，#449）。limits 倒置的 400 `data` 與 WARN reason 同 Create，在鎖定與讀取 Gateway 前拒絕，WARN 記 path `gatewayId`、`supplierId=null`（#951）。 |
| Soft delete | `DELETE` | `/{gatewayId}` | `DELETE`；Superadmin 或 owning Supplier（Admin 與 User，#959）；必須帶 `expectedVersion`，Gateway 須先 `INACTIVE`（不隱式停用）。鎖定 root 並驗證 version 後一次檢查所有 blocker，任一存在回 409＋`SUPPLY_GATEWAY_DELETE_BLOCKED (40050)`，`data: {blockers:[{blockerType,count}]}` 只列 count>0、依下列固定順序：`GATEWAY_NOT_INACTIVE`（count 1）、`ENABLED_ALLOCATION`（enabled 且未刪除 allocation）、`GATEWAY_ACCOUNT`（未刪除 Gateway BO 帳號）、`CARDHOLDER`（未刪除）、`PAYMENT_ACCOUNT`（未刪除，含營運停用）、`PENDING_APPLICATION`（`PENDING`）、`OPEN_DEPOSIT_ORDER`（current Gateway 且 `PENDING_ROUTING`／`ASSIGNED`／`PENDING_REVIEW`）、`OPEN_WITHDRAWAL_ORDER`（current Gateway 或 BO 建單 created Gateway，含未派出，`SETTLED`／`REJECTED_NO_TRANSFER` 以外，同單只計一次）、`ACTIVE_RESERVATION`（`RESERVED`）。不回 child IDs；終局訂單、已釋放／已消耗 reservation 與其他歷史不阻擋。無 blocker 時 soft delete 並寫 `DELETE_SUPPLY_GATEWAY` audit（#467，ADR-0031／0033）。 |

Gateway兩方向min/max皆required；依ADR-0398合法`0/0`表示無上下限，單bound為0表示該bound不限制，negative／missing／不完整回 `["invalid limits"]`，兩值positive且min>max回該方向欄位 `[<dir>MinAmount, must not exceed <dir>MaxAmount]`（#951）。不能套HOUSE positive quota或要求max>0；Supplier無direction/daily配置、Gateway無daily quota。此amount guard與allocation enabled/fresh lifecycle/Currency/offset同時成立；allocation不對外提供priority，也不參與routing（ADR-0466）。

## Password reset API

接線鏈：login → `GET /bo/v2/auth/me` → 以其本人 `version` 手動呼叫既有本人改密碼。me 不替代 `RESET_PASSWORD:UPDATE` grant，不取 owner version／JWT epoch，不自動 retry 409；成功後必須重新登入。

下列 password mutation 皆由 server-side `PrincipalSession`、target lock 與 `expectedVersion` 決定；request 不得帶 principal、owner、Supplier 或 Gateway selector。stale version 一律回 HTTP 409／`RESOURCE_VERSION_CONFLICT(40051)`，前端必須重新取得 authoritative state 並由使用者重確認，禁止自動 retry。

| Method | Path | Authority | 成功結果 |
| --- | --- | --- | --- |
| `PUT` | `/bo/v2/auth/password` | 具 `RESET_PASSWORD:UPDATE` 的 Superadmin、Prefix、Supplier 或 Gateway；僅本人 | 驗證 `currentPassword`、更新 hash、清除 lock／challenge、撤銷 formal session；HTTP 204，不簽發 replacement JWT，必須重新登入。 |
| `POST` | `/bo/v2/auth/users/{userId}/password/reset` | 僅具 `ACCESS_USER_MANAGEMENT:UPDATE` 的 Superadmin | 以 `newPassword` 強制更新未刪除 BO User，撤銷 target session；HTTP 204，絕不產生 temporary password。 |
| `POST` | `/bo/v2/supplierAccounts/{accountId}/password/reset` | Superadmin；Supplier Admin 僅 own `SUPPLIER_USER` | 每次產生 policy-compliant temporary password，清除 lock／challenge、設 `mustChangePassword=false`、撤銷所有 session，temporary password 下次登入直接取得 formal session（ADR-0471（此參考僅供內部環境使用，公開版本未提供））；不輪替 TOTP secret、不清除 replay step，GA 只由 `POST /bo/v2/supplierAccounts/{accountId}/totp/reset` 重設。success response 只有 `{temporaryPassword, version}`，temporary password 只揭露一次。 |
| `POST` | `/bo/v2/gatewayAccounts/{accountId}/password/reset` | Superadmin、owning Supplier（Supplier Admin 與 Supplier User，ADR-0480）或 Gateway Admin（只限 own Gateway 的 `GATEWAY_USER`：其他 admin 403、本人 400、跨 owner 404） | 與 Supplier account reset 相同；跨 Supplier owner scope、missing 或已刪除 target 一律視為不存在。 |
| `POST` | `/bo/v2/gatewayAccounts/{accountId}/totp/reset` | Superadmin、owning Supplier（Supplier Admin 與 Supplier User，ADR-0480）或 Gateway Admin（只限 own Gateway 的 `GATEWAY_USER`：其他 admin 403、本人 400、跨 owner 404） | 必須帶 non-negative `expectedVersion`（缺少 400）。只輪替 encrypted TOTP secret：清除 replay step、失敗次數、lock 與 pending password-change challenge，撤銷所有 session、version +1；不改 password 與 `mustChangePassword`。inactive account 或 inactive Gateway 仍可重設。單層 envelope 回 `{totpSetupSecret, version}`，新 secret 只交付一次；Gateway User、Prefix 回 403；跨 Supplier owner scope、missing 或已刪除 target 一律視為不存在；寫一筆 HIGH `ROTATE_GATEWAY_ACCOUNT_TOTP` audit（#433）。 |

所有新密碼依 `AuthenticationPolicy` 檢查；temporary password、password、hash、TOTP secret／code、token 與 challenge hash 不得進入 OpenAPI 範例、audit、log 或 error response。Supplier 與 Gateway password reset 都可處理 inactive account／owner，都不旋轉 TOTP secret 或 replay step；密碼與 GA 都遺失時，管理者分別呼叫 password reset 與 totp reset。

## System Config API

`SYSTEM_CONFIGURATION` 已啟用，`GET /bo/v2/config`、`PUT /bo/v2/config/{key}`、`DELETE /bo/v2/config/{key}` 分別要求 `VIEW`、`UPDATE`、`DELETE`。System Admin 操作 global `system_config`；具 active `SYSTEM_CONFIGURATION` grant 的 Prefix 只操作 session 導出的 own Agent `agent_system_config` override，request 不收 `agentId`，Global-only key 的 PUT／DELETE 回 403 `NO_PERMISSION`；成功且實際變更的設定 mutation 與 non-secret `domain_audit_log` 同一 transaction 提交；同值 no-op、拒絕與 rollback 不寫 audit，audit 記變更前後值。GET 每筆 `ConfigVo` 另帶 nullable `creator`／`modifier`，與 `value` 同來源：`source=AGENT_OVERRIDE` 時為該 Agent override 的建立者與最近實際變更者帳號（#548）；`source=SYSTEM_DEFAULT`（含 System Admin 的 global page 與 Agent 未覆寫列）為 `system_config` 的建立者與最近實際變更者帳號（#555：System Admin 建立時兩者皆寫操作者、更新與停用只寫 modifier，同值 no-op 不改；未經 BO 改過的 seed 列為 `SPAY4_DATA_SEED`）。完整 contract 與 DBA unique-index preflight 請見 [System Config API Contract](system-config-api-contract.md)。

## Payment Account 限額 API（#411）

CH Payment Account 的每日金額、每日筆數與 Balance Ceiling 只影響 Deposit routing，不影響 HOUSE 與 Withdrawal（ADR-0427（此參考僅供內部環境使用，公開版本未提供））。四支 API 的 service 都以 fresh principal 重驗，成功回單層 `ResponseVo` 與 `Cache-Control: no-store`。幣別預設兩支掛 `SYSTEM_CONFIGURATION`：GET 限 **Superadmin** 與有 VIEW grant 的 **Prefix**（唯讀，兩者看到同一份全域預設，ADR-0495（此參考僅供內部環境使用，公開版本未提供）），PUT 只限 **Superadmin**；Supplier、Gateway 讀寫與 Prefix 寫入回 403 `NO_PERMISSION (40001)`，錯誤沿用一般 BO 格式（`data` 為欄位名稱陣列）。帳戶限額兩支是 [Overview 契約](cardholder-overview-api-contract.md#66-account-limits2324) R23／R24，採 Overview 錯誤 wire（`data` 為 `{field, reasonCode}`）：Superadmin 全域，Supplier／Gateway 限 own scope（ADR-0481（此參考僅供內部環境使用，公開版本未提供），#955），scope 外 404；VIEW-only principal 可讀不可覆寫。

| Method／Route | Policy | 說明 |
| --- | --- | --- |
| `GET /bo/v2/paymentAccountCurrencyLimits` | `SYSTEM_CONFIGURATION:VIEW` | Superadmin、Prefix（唯讀）。已設定的幣別預設（`currencyId`、`currencyCode`、`dailyAmountLimit`、`dailyTxLimit`、`balanceCeiling`、`systemMaxCeiling`、`version`）；沒有列的幣別新卡不設限。 |
| `PUT /bo/v2/paymentAccountCurrencyLimits/{currencyId}` | `SYSTEM_CONFIGURATION:UPDATE` | body 五欄皆必須出現：三項限額與 `systemMaxCeiling`（null 不限制）、`applyMode`（`NEW_ACCOUNTS_ONLY`／`BACKFILL`）。整列取代；`systemMaxCeiling` 只限制單一帳戶覆寫的 `balanceCeiling`，不限制幣別預設本身。`BACKFILL` 同交易把同幣別 `limitOverridden = false` 的帳戶改為新預設，response `backfilledAccountCount` 為實際變更數。Currency 不存在 404。 |
| `GET /bo/v2/paymentAccounts/{id}/limits` | `SUPPLY_CARDHOLDER_OVERVIEW:VIEW` | 帳戶目前三項限額、`currencyCode`、`limitOverridden`、該幣別 `systemMaxCeiling` 與 `version`。 |
| `DELETE /bo/v2/paymentAccounts/{id}` | `SUPPLY_CARDHOLDER_OVERVIEW:DELETE` | Superadmin、Supplier、Gateway 限 owner chain：INACTIVE、餘額與 reserved 皆零、無未解除 obligation 才可刪，FROZEN 可刪；不可恢復，歷史保留，同帳號可重新申請取得新 id（ADR-0462（此參考僅供內部環境使用，公開版本未提供））。不屬於限額，放此處僅因同為單一 Account 操作。 |
| `PUT /bo/v2/paymentAccounts/{id}/limits` | `SUPPLY_CARDHOLDER_OVERVIEW:UPDATE` | body 四欄皆必須出現：三項限額（null 不限制）與 `expectedVersion`。整組覆寫並設 `limitOverridden = true`；幣別設有 `systemMaxCeiling` 時 `balanceCeiling` 必填且不得超過（400 field `balanceCeiling`／`INVALID_FIELD`，等於可設）；stale version 409 `40051 VERSION_CONFLICT`；current-version 同值且已覆寫為 no-op。 |

- 金額為正數 plain decimal，request 可送 JSON number 或 string（ADR-0489（此參考僅供內部環境使用，公開版本未提供）；最多 20 位整數、10 位小數，不 rounding），回應為去尾零的 string；筆數為 `1..2147483647` 整數；0 與負數回 400。
- 「只套用新卡」：Application 核准建立 Account 時複製當下幣別預設；之後改預設不影響既有帳戶，除非 `BACKFILL`。
- `creator`／`modifier`（#550）：帳戶覆寫與 `BACKFILL` 實際改到帳戶限額時，`payment_account.modifier` 寫該 Superadmin account；同值 no-op 與已覆寫而略過的帳戶不改。Overview 列表與明細（`OverviewCardRow`、PaymentAccountDetail、ApplicationDetail）另回 nullable `creator`／`modifier`：Account 為核准建立者與最近實際異動者（status、direction、unfreeze、餘額調整、限額；App 本人改接單開關為 `cardholder:<username>`），Application 為申請者（BO 操作者 account 或 App 本人 `cardholder:<username>`）與最近 approve／reject／cancel 操作者；replay、no-op 與金流 reserve／credit／debit／release 不改，本欄上線前的歷史資料為 null。
- 判斷點：Deposit admission 持鎖後，原 business date `used + reserved + 本筆` 金額或筆數任一超過，或 `currentBalance + 未結 Deposit 占用 + 本筆 > balanceCeiling`，即跳過該帳戶改派其他候選，全部不合格時照既有規則轉待覆核。
- 實際異動寫 HIGH audit `UPDATE_PAYMENT_ACCOUNT_CURRENCY_LIMIT`／`OVERRIDE_PAYMENT_ACCOUNT_LIMIT`，同值 no-op 不寫（[Domain Audit](domain-audit-contract.md)）。尚無取消覆寫的入口。

## Channel Analytics API

`CHANNEL_ANALYTICS`（#529，Payment Management，sort 70）讓 Agent 比較各收款路線的建立、成功、耗時與使用率（ADR-0454（此參考僅供內部環境使用，公開版本未提供））。三支路由都是 `GET`、要求 `CHANNEL_ANALYTICS:VIEW`、Domain Audit 分類為 `READ_ONLY`，回應為未包裝的 VO；本頁不提供 CSV。營運分析直接讀 Deposit／Withdraw Order 與 Assignment Attempt，不讀 hourly aggregate。

| Method／Route | 說明 |
| --- | --- |
| `GET /bo/v2/channelAnalytics/options` | 只接受 `agentId`。回 `agentId`、`agentBusinessUtcOffset`（±HH:MM）、`currencyCode`（Agent 預設幣別，master 缺失時 null）、`today`（目前 Agent 營業日）、`routes`、`routeTypes`、`directions`、`periods` 與 `maxCustomDays`（31）。`routes` 列出 Agent 全部 House Card（含停用、刪除）、已有代號的 Supply Gateway／Supply Channel（含停用、刪除的收款方），最後為 `UNASSIGNED`，依類型、編號排序；不回 `SG-UNCODED`／`SC-UNCODED`，這兩個值只能直接帶入列表或 Channel 查詢的 `routeCode` 篩選；每筆含 `routeCode`、`routeType`、`displayName`、`supplierName`。Agent 清單另由 `/bo/v2/agents/options` 取得。 |
| `GET /bo/v2/channelAnalytics/page` | 必填 `direction`（`DEPOSIT`／`WITHDRAWAL`）與 `period`；可選 `fromDate`／`toDate`、`routeType`、`routeCode`、`pageNumber`（預設 0）、`pageSize`（預設 20，1..500）。回整段期間內至少有一筆計入訂單的路線，依類型、編號排序；外層含 `agentId`、`direction`、`fromDate`、`toDate`、`agentBusinessUtcOffset`、`currencyCode`、`records`、`total`、`size`、`number`。 |
| `GET /bo/v2/channelAnalytics/detail` | 必填 `direction`、`period`、`routeCode`；可選 `fromDate`／`toDate`。回該路線的 `routeCode`、`routeType`、`displayName`、`supplierName`、期間內每個 Agent 營業日一筆的 `days`（由舊到新；沒有訂單的日期計數為 0、其他指標為 null）與 `totals`。`totals` 與同條件 `page` 的該列相同，計數與金額等於 `days` 加總。 |

**範圍與遮罩：**

- Superadmin 必帶 `agentId`（未帶 400，不存在 404），一次只看一個 Agent。Prefix 固定看自己的 Agent，可不帶 `agentId`；帶入其他 Agent 回 404。Supplier／Gateway 一律 403（catalog 不授權）。
- Prefix 的 Supply Gateway／Supply Channel 路線 `displayName` 為代號、`supplierName` 為 null，回應不含真實 Supply Gateway、Supply Channel 或 Supplier 名稱與識別碼，也不能以 Supplier 名稱篩選。Superadmin 的 `displayName` 為真實名稱，並回 `supplierName`。House Card 屬 Agent 自身，兩者都看得到卡片 display name。
- 參數不合法回 400 `FIELD_VALIDATE_FAILED`；`routeCode` 格式正確但不屬於該 Agent 回 404。越權、跨 Agent、非法參數與代號不存在都寫 WARN `channel analytics rejected`（含 HTTP status、原因類別、欄位名稱、actorId、agentId），不記參數原值，也不含收款方身分或付款人資料。Supplier／Gateway 的 403 由既有請求摘要 WARN 記錄（`authFailure=POLICY_DENIED`）。

**收款路線代號（`routeCode`）：**大小寫須完全相同，每條路線只有一種寫法。

| 代號 | `routeType` | 說明 |
| --- | --- | --- |
| `HC-<houseCardId>` | `HOUSE_CARD` | House Card id，正整數、不補零。House Card 屬 Agent 自身，不是隱藏身分。 |
| `SG-NN` | `SUPPLY_GATEWAY` | 該 Agent 的 Supply Gateway 代號，序號至少兩位補零（`SG-01`、`SG-123`），`SG-1`、`SG-001` 皆不合法。Payment Account（Cardholder）的單依其 Supply Gateway 合併為一列。 |
| `SC-NN` | `SUPPLY_CHANNEL` | 該 Agent 的 Supply Channel 代號，格式同上。 |
| `SG-UNCODED`／`SC-UNCODED` | `SUPPLY_GATEWAY`／`SUPPLY_CHANNEL` | 已分派但收款方尚無代號（#531 upgrade 後、本版部署前寫入的分派，下次分派時補上代號），不揭露身分。 |
| `UNASSIGNED` | `UNASSIGNED` | 從未分派的訂單。 |

代號在該 Agent 的單第一次分派給該收款方時，於同一分派交易內產生；永不重編、不重用，收款方停用或刪除後仍保留。SG／SC 代號只在同一 Agent 內有意義，所以 Superadmin 使用代號時必須同時指定 `agentId`。

**期間：**日期皆為 Agent 營業日，依 Agent 主檔 `business_utc_offset` 換算。`TODAY` 為今日；`LAST_7_DAYS`、`LAST_30_DAYS` 為含今日往前 7／30 天；`CUSTOM` 必帶 `fromDate`／`toDate`（`YYYY-MM-DD`，含頭含尾），`fromDate` ≤ `toDate`、最多 31 天、`toDate` 不得晚於 Agent 今日。非 `CUSTOM` 帶日期回 400。

**計入訂單與歸屬：**

- Deposit 與 Withdraw 分開統計，只算 Agent 發出的單：Deposit 為該 Agent 全部 Deposit Order，但 `CANCELLED` 完全不計（不入建立筆數）；Withdraw 只取 `originType=AGENT_API`，BO 建立的單不計。
- 每單只算一次，依建單時間的 Agent 營業日歸入期間與日期。
- 路線歸屬：已結算的單歸給被選中結算的 attempt 的收款方；其他歸給目前 attempt，沒有目前 attempt 則歸給最後一個 attempt；從未分派列為 `UNASSIGNED`。attempt 有 House Card 為 `HOUSE_CARD`，有 Supply Channel 為 `SUPPLY_CHANNEL`，否則依 Supply Gateway 為 `SUPPLY_GATEWAY`。

**指標定義（`records[]`、`days[]`、`totals`）：**金額與比率皆為 decimal string。

| 欄位 | 定義 | null 規則 |
| --- | --- | --- |
| `createdCount` | 計入的訂單數 | 不為 null（無訂單為 0） |
| `successCount` | `SETTLED` 筆數 | 不為 null |
| `failedCount` | Deposit `REJECTED`、`EXPIRED`；Withdraw `REJECTED_NO_TRANSFER` | 不為 null |
| `processingCount` | 其餘狀態（含 Withdraw `PENDING_REVIEW`、`ROUTING_FAILED`） | 不為 null |
| `successRate` | 成功 ÷（成功＋失敗），處理中不計；4 位小數 HALF_UP | 分母為 0 時 null |
| `settledAmount` | `SETTLED` 訂單實際金額加總（Agent 幣別，plain decimal） | 沒有成功單時 null |
| `medianSettleSeconds` | `SETTLED` 訂單建單到結算秒數的中位數，偶數筆取中間兩筆平均；3 位小數 HALF_UP | 沒有成功單時 null |
| `p90SettleSeconds` | 同上的 P90，nearest-rank（第 ⌈0.9n⌉ 小）；3 位小數 HALF_UP | 沒有成功單時 null |
| `utilization` | 見下方使用率規則；4 位小數 HALF_UP | 不適用時 null |

**使用率：**只對 Deposit 的 House Card 與 Supply Channel 計算，是比較指標，不是歷史占用。分子為該 Agent 期間內的 `SETTLED` Deposit 實際金額，條件是被選中結算的 attempt 在該收款方，且該 attempt 的收款方配額日落在期間日期內（House Card 用 Agent 營業日，Supply Channel 用 Supplier 營業日）；分母為期間天數 × 目前生效的每日金額上限。`detail` 每日列以單日（天數 1）計算。有上限但期間內沒有結算時回 `0.0000`。以下情況回 null：Supply Gateway、`UNASSIGNED`、`SG-UNCODED`／`SC-UNCODED`、所有 Withdraw 列、不限額（House Card 沒有生效上限；Supply Channel `daily_amount_limit = 0`），以及 House Card 上限設定錯誤。

**列表跳轉：**`detail` 每日列的 `listFilter` 可原樣作為列表 query：`path`（`/bo/v2/depositOrders/page` 或 `/bo/v2/withdrawalOrders/page`）、`agentId`、`routeCode`、`from`（該 Agent 營業日 00:00 的 UTC 時點，含）、`until`（翌日 00:00 的 UTC 時點，不含），Withdraw 另帶 `originType=AGENT_API`（Deposit 為 null）。

**Deposit／Withdraw 列表的 `routeCode` 篩選：**`/bo/v2/depositOrders` 的 page／stats／export 與 `/bo/v2/withdrawalOrders` 的 page／export／stats 接受同一組代號，歸屬規則與本報表完全一致，詳見 [Order workspace 契約](order-workspace-contract.md#付款方與收款方查詢-filters)。帶代號時 Deposit 排除 `CANCELLED`（同時帶 `status=CANCELLED` 回 200 空頁）、Withdraw 只含 `AGENT_API`，與報表計數一致；Superadmin 必須同時帶 `agentId`，Supplier／Gateway 不可使用，兩者皆回 400 並寫 WARN `workspace routeCode rejected`（不含代號原值）；格式錯誤回 400；代號在該 Agent 不存在時回空頁。

## Channel Deposit Report API

`CHANNEL_DEPOSIT_REPORT`（#530，Payment Management，sort 80）讓 Agent 依收款路線查看 Deposit 明細與小計（ADR-0454（此參考僅供內部環境使用，公開版本未提供））。四支路由都是 `GET`、要求 `CHANNEL_DEPOSIT_REPORT:VIEW`；options／page／subtotals 的 Domain Audit 分類為 `READ_ONLY`，export 為 `MUTATION`（`EXPORT_CHANNEL_DEPOSIT_REPORT`）。回應為未包裝的 VO。本期不做 Fee、Net Amount、Player Credited、Prefix Cost。

範圍沿用 Deposit 列表（#516）的查詢元件：Prefix 為 own Agent 全部單、Superadmin 以 `agentId` 指定一個 Agent；收款路線歸屬與代號同 [Channel Analytics](#channel-analytics-api)（已結算看被選中結算的 attempt，其他看目前 attempt，沒有則看最後一個 attempt，從未分派為 `UNASSIGNED`）。與 Channel Analytics 相同，`CANCELLED` 不列入。

| Method／Route | 說明 |
| --- | --- |
| `GET /bo/v2/depositOrders/report/options` | 只接受 `agentId`。回 `agentId`、`agentBusinessUtcOffset`、`today`、`defaultFromDate`／`defaultToDate`（今天加前 29 個 Agent 營業日）、`routes`（同 Channel Analytics options，含停用、刪除的收款方與歷史代號，最後為 `UNASSIGNED`）、`currencies`（Agent 主檔幣別的 `currencyId`、`currencyCode`）、`statuses`（Deposit 狀態，不含 `CANCELLED`）、`periods` 與 `maxCustomDays`（31）。 |
| `GET /bo/v2/depositOrders/report/page` | 篩選見下；`pageNumber`（預設 0）、`pageSize`（預設 20，1..500）。依建單時間、id 由新到舊；外層含 `agentId`、`fromDate`、`toDate`、`agentBusinessUtcOffset`、`records`、`total`、`size`、`number`。 |
| `GET /bo/v2/depositOrders/report/subtotals` | 與 page 相同篩選（分頁欄位只驗證格式）。`rows` 為「Agent × 收款路線」小計（`agentId`、`agentPrefix`、`routeCode`、`routeType`、`routeName`、`orderCount`、`requestedAmount`、`actualAmount`），依路線類型、編號排序；另回 `totalCount`、`totalRequestedAmount`、`totalActualAmount`。實際金額無值以 0 加總。`totalCount` 等於同條件 page 的 `total`，各列 `routeCode` 帶回 page 的 `total` 等於該列 `orderCount`。 |
| `GET /bo/v2/depositOrders/report/export` | 與 page 相同篩選、欄位與排序的全部明細 CSV（不只當頁）：`id,orderNo,agentOrderId,agentId,agentPrefix,createTime,businessUtcOffset,displayTime,payerAccount,payerName,routeCode,routeType,routeName,currencyCode,amount,actual,status,boRemark`。每批 500 筆 keyset 讀取，UTF-8 without BOM、CRLF、一律加引號並防公式（`CsvCellPolicy.DEPOSIT`）；完成後同交易寫 HIGH `EXPORT_CHANNEL_DEPOSIT_REPORT` audit（target `CHANNEL_DEPOSIT_REPORT`＝actor principal id，summary 含 `rowCount`、`agentId`），audit 寫入失敗時整筆失敗、不回傳檔案。`Cache-Control: no-store`、`X-Content-Type-Options: nosniff`。 |

**篩選：**皆可省略；未列出的參數（例如 `supplierId`、`gatewayId`、`receivingType`）不綁定、不生效，所以 Prefix 無法以 Supplier 或其他收款方身分篩選。

- 期間：`period` 預設 `LAST_30_DAYS`（今天加前 29 個 Agent 營業日），亦可 `TODAY`、`LAST_7_DAYS` 或 `CUSTOM`（必帶 `fromDate`／`toDate`，規則同 Channel Analytics，最多 31 天）；依 Agent 主檔 offset 換算為 UTC 半開區間比對建單時間。
- `currencyId`：完全相同。`routeCode`：options 的代號或 `SG-UNCODED`／`SC-UNCODED`；格式不符 400，不屬於該 Agent 404。`status`：`statuses` 的值（帶 `CANCELLED` 為 400）。
- `orderNo`：32 位小寫 hex，或匯入的 Legacy 單號 `DEP`／`WDR` 加 15 位數字（可帶 `S2` 前綴），完全相同；其他格式 400。`agentOrderId`：逐字完全相同（區分大小寫），1..100 字。
- `account`：會員帳號完全相同（沿用 Deposit 列表，不做部分比對），最多 100 字。`name`：會員姓名部分比對（`%`、`_` 為字面），最多 255 字。

**明細欄位（`records[]` 與 CSV）：**`id`、`orderNo`、`agentOrderId`、`agentId`、`agentPrefix`、`createTime`（UTC）、`businessUtcOffset` 與 `displayTime`（Agent offset）、`payerAccount`（只露末四碼，四碼以下為 `****`；Superadmin 亦同）、`payerName`、`routeCode`、`routeType`、`routeName`（House Card display name；Supply Gateway／Supply Channel 對 Superadmin 為真實名稱、對 Prefix 為代號；未編號／未分派為固定中文名稱）、`currencyCode`、`amount`（申請金額）、`actual`（實際金額，無值為 null）、`status`、`boRemark`。金額為 plain decimal，保留原小數精度、去除尾端 0。

**範圍與遮罩：**

- Superadmin 必帶 `agentId`（未帶 400，不存在 404），一次只看一個 Agent。Prefix 固定看自己的 Agent，可不帶 `agentId`；帶入其他 Agent 回 404。Supplier／Gateway 一律 403（catalog 不授權）。
- Prefix 回應不含 Supply Gateway、Supply Channel 或 Supplier 的真實名稱與識別碼；`boRemark` 只在目前收款方為 own House Card 的單與 own `AGENT_ACCOUNT` 單（#992）有值（與 #516 Deposit 列表的遮罩列相同），分派給 Cardholder 等其他單為 null。Superadmin 看得到全部備註。
- 參數不合法回 400 `FIELD_VALIDATE_FAILED`，跨 Agent、Agent 不存在與代號不屬於該 Agent 回 404。越權、跨 Agent、非法參數、代號不存在與匯出失敗都寫 WARN `channel deposit report rejected`（含 HTTP status、原因類別、欄位名稱、actorId、agentId），不記參數原值，也不含付款人帳號、姓名或收款方真實身分。Supplier／Gateway 的 403 由既有請求摘要 WARN 記錄（`authFailure=POLICY_DENIED`）。

## HOUSE Master Contract

HOUSE master 的仍有效條款集中於此，供 Reader／[HOUSE 功能](../pages/backoffice-menu-api-progress.html#feature-house-config)／收款流程共用。[Schema Foundation](schema-foundation.md#house-card)保留 persistence 字典；[Deposit 契約](deposit-target-native-contract.md)管金融作業。ADR-0397 只取代適用 Deposit disposition，未撤銷 Delete／required fallback guards；ADR-0398 不改 HOUSE limits/quota。以下是 accepted contract，不是 runtime 驗收、grant 或 SQL authority。

### HOUSE Scope Identity and Lifecycle

- current target-native HOUSE **只參與 Deposit**；歷史 `withdrawal_enabled`／shared Tx 定義不授權 HOUSE Withdrawal routing 或外部 balance override。HOUSE 無 local authoritative balance／reserved amount（#420 的帳面餘額只供記帳、顯示與人工調帳，見下方「HOUSE Book Balance」，不是 authoritative），與 Payment Account 分表、entity／repository／aggregate；不能 generic card CRUD 依 owner-type 分支，最多共用 pure helper／read-only candidate。Order／Attempt 的 `payment_account_id`／`house_card_id` 及 current pointer 必須互斥。
- Admin 以 authorized target `agentId` 協助，Prefix 只限 authenticated own Agent；Supplier／Gateway 無 HOUSE authority。`agentPrefix` 是 display，不使用 `prefixId`。Currency 由 owning Agent 在 Create transaction 複製；Agent／Currency／Bank／canonical account identity immutable，換 identity 須建立新卡。
- Bank Create/new-routing 同時要求存在、非 DELETED、ACTIVE、配置給 owning Agent、同 immutable Currency。derived `bankEligible` 不替代 status／方向或全部 routing guards；reason 順序固定 `BANK_REFERENCE_MISSING` → `BANK_DELETED` → `BANK_INACTIVE` → `BANK_AGENT_MAPPING_MISSING` → `BANK_CURRENCY_MISMATCH`。eligible reason 必為 null；scope 通過才回 reason，routing 用 fresh predicates 不是 cached reason。
- Bank 失效不 cascade HOUSE status／cancel／redispatch／release 既有 Attempt；Bank 恢復後其他 current guards 通過即恢復新 routing 資格，不須重存卡。既有 LINE／settlement／reconciliation 依 persisted immutable references 收斂；missing Bank 進人工核對，不猜 identity、不建立新 candidate。
- `cardStatus` 只有 ACTIVE／INACTIVE，與 BaseEntity DELETED、方向、Bank 分開。Create 不接受 status，明確建立 ACTIVE（無 DB default）。INACTIVE 可在有 active／review-held obligation 時設定，但只阻止新 Attempt；status／方向變更不得取消或阻斷既有 Order／LINE／settlement。沒有 PAUSING／PAUSED／FROZEN。
- financial tuple 為 `(agent_id, currency_id, bank_id, canonical account_no)`，non-deleted 且 ACTIVE 才產生 nullable generated `active_identity_key` UQ；允許多筆 INACTIVE／DELETED，不用 status＋identity composite UQ。Create／Activate ACTIVE collision 回 HTTP 409／`UNIQUE_KEY_EXISTS (40007)`，不回 existing ID／account，完整 rollback，operator reload，禁止 auto-switch／retry。
- Activate 只改明確 target ID＋version，no-cascade：其他卡／flags／歷史不動。DELETED 沒有 Restore；同 identity 僅 INACTIVE／DELETED 不阻擋一般 Create，新 ID 重新驗 current guards，不繼承 mutable settings／version／audit、不搬歷史，不將舊 LINE 跨 generation rebind。quota 按 `houseCardId`；同 ID 停啟用不 reset。
- canonical account 共用 normalizer：raw 只准 ASCII letters/digits、space/tab、hyphen/underscore；拒絕其他 control、Unicode letter/digit/symbol；移除 ASCII space/tab/`-`/`_`、Locale.ROOT uppercase，結果 `[A-Z0-9]{1,100}`，保留 leading zeros。完整 authorized account 不能進 URL／log／analytics／audit metadata／error／真實 Swagger example，沒有 raw 或 masked alias。LINE 完整帳號先 canonical exact，無唯一結果才依 Agent/provider-scoped fuzzy；partial 不放寬 scope。

### HOUSE Exact Requests and Responses

歷史相對 `/houseCard` 對應 source 所見 `/bo/v2/houseCard`；這是 source mapping，不宣告兩條可執行 alias 或已通過 wire parity，也不呼叫產品 HTTP。

| 動作 | exact request／boundary |
| --- | --- |
| Create | 單一 POST；十個 flat fields 依序 `agentId`, `displayName`, `bankId`, `accountNumber`, `accountName`, `depositEnabled`, `dailyAmountLimit`, `dailyTxLimit`, `depositMin`, `depositMax`（後兩欄 #956，ADR-0483（此參考僅供內部環境使用，公開版本未提供））。Admin required positive agentId；Prefix **omitted/null**，任何 non-null 即使 own ID 也 `must be omitted`，不忽略、不覆寫、不作 target probe。五個 business fields required，兩 limits required-present nullable，explicit null 繼承、omitted 拒絕。不能傳 status／Currency／owner alias、nested account/availability/limits 或 response fields。BO 不接受 `withdrawalEnabled`（唯讀，ADR-0452（此參考僅供內部環境使用，公開版本未提供））：Create 一律保存 false、Update 保留現值；request 只要出現此欄（true／false／null）即在 lookup 前回 HTTP 400＋40005＋exact `["withdrawalEnabled", "must be omitted"]`（多個錯誤時依 ADR-0478：型別錯誤先回，語意錯誤中排在 `depositEnabled` 之後），不寫入、不寫 audit，並記一筆 WARN log（actorId、houseCardId（Create 為 null）、reason `READ_ONLY_FIELD`，不含帳號／戶名）；response 仍回 current `withdrawalEnabled`。 |
| General Update | PUT `{houseCardId}`；八欄 full replacement 依序 `displayName`, `accountName`, `depositEnabled`, `dailyAmountLimit`, `dailyTxLimit`, `depositMin`, `depositMax`, `expectedVersion`。不能傳 identity／cardStatus／derived／audit 或 `withdrawalEnabled`（同 Create 回 400 `must be omitted`、保留現值），不能當 patch；limits required-present nullable。 |
| Status | 唯一 PUT `{houseCardId}/status`，兩欄 required `cardStatus`, `expectedVersion>=0`；無 activate/inactivate/query/path-state/PATCH alias。authorized lock → version comparison → same-state；stale same-state HTTP 409／`RESOURCE_VERSION_CONFLICT (40051)`，不回 current data/version、不自動重送。current-version same-state 回200 full VO，zero-write／zero-audit，不改 version／modifier／modifyTime。real transition version 恰增一次。 |
| Delete | JSON body required current `expectedVersion`（ADR-0421，不接受 query string；省略或 null 回 409）、先由 operator 完成 INACTIVE，再依下節 blockers；不隱式停用。 |
| Book Balance | PUT `{houseCardId}/bookBalance`；四欄 required-present `targetBalance`, `reason`, `expectedVersion`, `idempotencyKey`，見下方「HOUSE Book Balance」。 |

- `displayName` 是 non-unique BO label，`accountName` 是銀行戶名；各自 required mutable，非 identity/matching/routing。Create／Update 共用各自 pure validator：presence → 拒絕 raw `Character.CONTROL`（含 edge tab/CR/LF/NUL）→ Unicode `isWhitespace || isSpaceChar` edge trim → 1..100 code points；內部一般空白／Thai／emoji／combining marks／大小寫原樣保留，不 normalize/collapse。缺失/null/raw empty/trim-empty 回 `required`，raw control 優先回 `contains control characters`，超100回 `must contain between 1 and 100 code points`。
- House-local strict Create transport：missing/empty/null/nonobject/malformed、known-field wrong token type、unknown/case-variant/alias/nested field，一律 HTTP 400／`FIELD_VALIDATE_FAILED (40005)`／exact `["request", "invalid request"]`。金額欄位 `dailyAmountLimit`、`depositMin`、`depositMax` 接受 JSON number 或 plain decimal string，字串或 number 文法不符（科學記號、逗號、空白、正負號字串）為 `[field, "invalid format"]`（ADR-0489（此參考僅供內部環境使用，公開版本未提供））。duplicate top-level JSON property 在 semantic 前拒絕（與 unknown 等其他綁定錯誤同時存在時回讀到的第一個，ADR-0478），即使 same value，不採 first/last/merge；不反射 unknown/duplicate name、parser path/exception/raw input，不全域改 Legacy mapper。
- semantic HTTP400／40005／exact `[field, reason]` 一次一錯；十一欄按表順序（含唯讀 `withdrawalEnabled`）；型別錯誤與缺 required 欄位（例如數字欄位送字串、省略 limit）先於語意錯誤回報（ADR-0478），**全部在 Agent/Bank lookup／mutation/Audit 前**。八個 exact lowercase reasons 只有 `required`、`must be positive`、`must be omitted`、`contains control characters`、`must contain between 1 and 100 code points`、`invalid format`，以及單筆上下限專用的 `must not be negative`、`must not exceed depositMax`（#956），無 punctuation/localization/raw value，Frontend 不解析 message。逐欄：Admin agentId missing/null→required、非正→must be positive；Prefix non-null 永遠 must be omitted；bankId 同 presence/positive；accountNumber missing/null/raw empty→required、non-empty canonicalization 失敗→invalid format；兩 Boolean missing/null→required、false 合法；兩 names 依上列 precedence。lookup 後 domain/authorization/not-found 不折疊成 semantic error。
- limits omitted→`[field, "required"]`、present null 合法、非 number token→`["request", "invalid request"]`、zero/negative→`[field, "must be positive"]`、positive 但不可 lossless 表示→`[field, "invalid format"]`，Create/Update 相同。number lexical category 的 representation failure 不能先被 DTO binding 改為 transport error；Amount 為 positive `DECIMAL(30,10)`/BigDecimal（最多20整數＋10小數），Tx為 `1..2147483647` integer。禁止 rounding/truncate/clamp，HOUSE 的0不是 Gateway unlimited，不套 `@NotNull` 擋 explicit null；兩 limits 都錯先 Amount。
- **單筆 Deposit 上下限**（#956，ADR-0483（此參考僅供內部環境使用，公開版本未提供））：`depositMin`、`depositMax` Create／Update 皆必填，JSON number 或 plain decimal string（ADR-0489（此參考僅供內部環境使用，公開版本未提供）），非負且可無損保存為 DECIMAL(30,10)，**0 表示該邊不限制**（與日限額不同）。omitted 或 null→`[field, "required"]`、非 number／string token→`["request", "invalid request"]`、負數→`[field, "must not be negative"]`、不可 lossless 或文法不符（科學記號、逗號、空白、正負號字串）→`[field, "invalid format"]`；兩者皆非 0 且 `depositMin` 大於 `depositMax`→`["depositMin", "must not exceed depositMax"]`，排在所有欄位錯誤之後，並記一行 WARN（actorId、actor 的 Agent scope（System Admin 為 null）、houseCardId（Create 為 null）、reason `DEPOSIT_RANGE_INVERTED`，不含金額與帳號）。0/0、min=max、單邊 0 皆合法。派單判斷閉區間且 0 不限制：BO 人工派單候選不列範圍外的卡，OGP 指定卡範圍外回 409／40054（[Deposit 契約](deposit-target-native-contract.md#3-routing重派與金融-transaction)）。回應照存值，未設定為 0（ADR-0488（此參考僅供內部環境使用，公開版本未提供），#1015）。
- General Update 固定 authentication/route-role → local strict transport/allow-list → 完整九欄 semantic（含唯讀 `withdrawalEnabled`）→ scoped target lookup/authorization → version comparison → target-dependent guards/mutation。invalid request 遮蔽 missing/out-of-scope/stale target，不作 target lookup、不洩漏資料；非 limit Update 與未被 ADR 凍結的 wire errors仍待專責契約，不從 Create 自行推導。
- Create 成功 HTTP200，沒有 Location／201；Controller full VO 經 ApiAdvice **單次**包 `ResponseVo<HouseCardVo>`，`code=2000`、`message=""`，transaction/Audit commit 後才 success。重送 ACTIVE identity 仍409/40007，不變成 idempotent replay。
- page/detail/create/update/status 同一 exact **34-field** VO：`houseCardId`, `agentId`, `agentPrefix`, `currencyId`, `currencyCode`, `currencyName`, `displayName`, `bankId`, `bankCode`, `bankName`, `accountNumber`, `accountName`, `cardStatus`, `depositEnabled`, `withdrawalEnabled`, `bankEligible`, `bankEligibilityReason`, `version`, `depositMin`, `depositMax`, `dailyAmountLimit`, `effectiveDailyAmountLimit`, `dailyTxLimit`, `effectiveDailyTxLimit`, `dailyAmountLimitSource`, `dailyTxLimitSource`, `todayUsedAmount`, `todayUsedTxCount`, `todayBusinessDate`, `bookBalance`, `bankReportedBalance`, `bankReportedTime`, `bookBankDifference`, `agentCardId`。18→22→24→27→31→32→34 是明示擴充（#393 加當日用量，#420 加帳面／銀行回報餘額，#436 加 OGP 卡片識別碼，#956 加單筆上下限），不保留 partial success。金額欄位 `depositMin`、`depositMax`、`dailyAmountLimit`、`effectiveDailyAmountLimit`、`todayUsedAmount`、`bookBalance`、`bankReportedBalance`、`bookBankDifference` 為 plain decimal string（不使用科學記號，保留資料庫 scale；null 維持 null；#876 起，ADR-0477（此參考僅供內部環境使用，公開版本未提供））。僅兩 configured limits、missing Bank 的 bankCode/bankName、eligible 的 reason、BO 建立的卡的 `agentCardId`，以及從未回報銀行餘額時的 `bankReportedBalance`／`bankReportedTime`／`bookBankDifference` nullable（`bookBalance` 必有值，可為負數）；Agent/Currency missing fail closed，其餘 required。沒有 row-status／audit metadata／masked alias／stateChanged；effective/source 只讀不持久化、不進 request，source逐欄 HOUSE/AGENT/GLOBAL且與 effective 同次 resolution，mixed sources 合法。`todayUsed*` 直接讀 routing admission 同一 `house_card_daily_counter`（非鎖 snapshot）：`todayBusinessDate` 為 owning Agent business UTC offset 下的 server 當日，`todayUsedAmount` 為該日 reserved requested 加已確認 actual（僅 Deposit，可超過 effective limit），`todayUsedTxCount` 為 reserved 加 consumed 筆數；兩者即 admission 比對 effective limit 的已占用量，無 counter 時為 0，跨 business date 自動歸零；只讀、不進 request、不授予 admission authority。

- **OGP 管理的卡**（`agentCardId` 非 null，ADR-0429（此參考僅供內部環境使用，公開版本未提供））：BO 只能改兩個日限額與單筆上下限（#956）。Frontend 將 `displayName`、`accountName`、`depositEnabled`、`withdrawalEnabled` 設為唯讀，並隱藏 status 與 delete 操作。後端同樣 fail closed，皆不寫入、不寫 audit：
  - General Update：先完成 transport、semantic、scope 與 `expectedVersion` 檢查；`displayName`、`accountName` 或 `depositEnabled` 與現值不同時回 HTTP 409／`RESOURCE_STATE_CONFLICT (40054)`。三欄維持現值、只改 limits 或單筆上下限照常成功。
  - Status（`PUT {houseCardId}/status`）與 Delete：scope 鎖定後、version 比對前即回 HTTP 409／`RESOURCE_STATE_CONFLICT (40054)`，所以 stale version 也回 40054。
  - `withdrawalEnabled`：依 #517（ADR-0452（此參考僅供內部環境使用，公開版本未提供））對所有卡都在 lookup 前回 400／40005 `["withdrawalEnabled", "must be omitted"]`，不再是 OGP 卡專屬的 409；多個錯誤時依 ADR-0478，型別錯誤先回，語意錯誤中排在 `depositEnabled` 之後。

### HOUSE Book Balance

ADR-0428（此參考僅供內部環境使用，公開版本未提供）（#420）：帳面餘額以 SPAY4 內部 append-only ledger `house_card_balance_log` 記帳，`house_card.book_balance` 為 projection；只供記帳、顯示與人工調帳，不作 House Withdrawal authority，Withdrawal pool 維持 disabled。

- **入帳**：只有 HOUSE Deposit 結算成功（LINE auto match、BO manual match／settle）以 actual 入帳，寫一筆 `DEPOSIT_CREDIT`（每張 Deposit order 唯一，late／duplicate／redispatch 不重複入帳）；與 settlement effects 同交易、在 HOUSE row lock 之後，rollback 時餘額與 ledger 一併回復。未配對入帳與出帳不計入。入帳會升 HOUSE `version`。入帳後為負數照常入帳，負數 `bookBalance` 即為標示。
- **調帳**：`PUT /bo/v2/houseCard/{houseCardId}/bookBalance`（`UPDATE`）。strict JSON 四欄皆須出現（omitted 回 `[field, "required"]`，型別錯或未知欄位回 `["request", "invalid request"]`）；`targetBalance` 為 JSON number 或 plain decimal string（ADR-0489（此參考僅供內部環境使用，公開版本未提供））、≥ 0、最多 20 整數＋10 小數（負數 `must not be negative`、超出或文法不符 `invalid format`）；`reason` 去除前後空白後 1..500 code points、不得含控制字元；`idempotencyKey` 為 1..128 位 ASCII 英數或 `.` `_` `:` `-`，大小寫視為不同。順序：欄位驗證 → scope 鎖定（跨 scope 與不存在皆 404）→ 同卡同 key：同 `targetBalance`／`reason` 回首次結果（即使 version 已前進），不同回 409／`IDEMPOTENCY_KEY_CONFLICT (40045)` → `expectedVersion` 為 null 或過期回 409／`RESOURCE_VERSION_CONFLICT (40051)`（省略欄位已在 transport 回 400 `["expectedVersion", "required"]`） → 目標值等於目前帳面為 no-op（`balanceLogId=null`、不寫 log／audit、不升 version）→ 設為目標值、寫 `MANUAL_ADJUSTMENT` log（before／delta／after／reason／operator）與 HIGH audit `ADJUST_HOUSE_CARD_BOOK_BALANCE`（summary 只含 `agentId`、`bookBalance`、`version`、`balanceLogId`，不含 reason）並升 version。回應 `HouseCardBookBalanceAdjustmentVo`：`houseCardId`, `balanceBefore`, `balanceDelta`, `balanceAfter`, `balanceLogId`, `operationTime`；三個 balance 欄位為 plain decimal string（#876）。request 的 `targetBalance` 接受 JSON number 或 plain decimal string（#961）。單步生效、不做 maker-checker、無通知。
- **Balance log**：`GET /bo/v2/houseCard/{houseCardId}/balanceLogs/page`（`VIEW`，`pageNumber` zero-based、`pageSize` 1..500，排序固定 `createTime DESC, id DESC`）與 `GET /bo/v2/houseCard/{houseCardId}/balanceLogs/{logId}`（`VIEW`，`logId` 不屬於該卡回 404）。`HouseCardBalanceLogVo`：`balanceLogId`, `houseCardId`, `entryType`（`DEPOSIT_CREDIT`／`MANUAL_ADJUSTMENT`）, `balanceBefore`, `balanceDelta`, `balanceAfter`, `depositOrderId`, `depositOrderNo`, `reason`, `operatorType`, `operatorAccount`, `createTime`；`balanceBefore`／`balanceDelta`／`balanceAfter` 為 plain decimal string（#876）；Deposit 入帳的 reason／operator 為 null，人工調帳的 order 欄位為 null。無 CSV 匯出。
- **投影**：`HouseCardVo.bookBalance` 為帳面餘額（新卡與既有卡初始 0，首次人工調帳填實際餘額）；`bankReportedBalance`／`bankReportedTime` 為該卡最新一筆非 null 的 `house_card_transaction.balance_after` 與其 transaction time（同時間取 id 較大者），從未回報時兩者與 `bookBankDifference` 皆為 null；`bookBankDifference = bookBalance − bankReportedBalance`。銀行回報只供對帳，不覆寫帳面。
- **可見性**：Superadmin 全部、Prefix 僅 own Agent；Supplier／Gateway 沒有 `SUPPLY_HOUSE_CARD` grant，service 亦回 403。

### HOUSE Delete Safety

ADR-0241（此參考僅供內部環境使用，公開版本未提供）仍有效：authorized non-deleted HOUSE lock＋expectedVersion，必須已 **INACTIVE**，檢查 current Order、nonterminal／unsettled Attempt、active／review-held reservation obligation、open reconciliation／recovery 四類 unresolved references。**不得自動處理 blocker**：不能取消/expire/redispatch Order、settle/release/consume obligation 或自動結案；任一成立整個 Delete fail closed。Terminal／closed history 不阻擋，仍保留原 ID/audit/ledger，不 cascade。blocker檢查、final INACTIVE/version recheck、soft-delete與 Audit 同交易，status/new-routing/delete共用 row/version race boundary。一般讀排除DELETED，authorized persisted-ID歷史讀仍可達，不讓 LINE 使舊卡重新成 candidate。

- **Delete blocker exact error**（#667 定案，凍結現行回應）：檢查順序為授權與 scope 鎖定 → OGP 管理卡拒絕 → `expectedVersion` → 必須 INACTIVE → 四類 blocker；任一 blocker 成立回 HTTP 409／`REFERENCE_DATA_EXISTS (40006)`，envelope 固定為 `{"code":40006,"message":"reference data exists","data":[]}`，`data` 必須存在且恰為空陣列，不帶 blocker 類別、數量或 houseCardId；不套 40053、不新增 safe payload。前端以 code 判斷，message 只作診斷。
- 被擋時整筆不寫入：HOUSE `version`／metadata 與四類金融參照不變，不寫 domain audit。失敗 log 只用既有請求摘要（`requestId`、`errorCode=40006`、`reason=REFERENCE_DATA_EXISTS`，4xx WARN），不含 request body，不另記 houseCardId 或 blocker 類別。

### HOUSE Limits Fail Closed

ADR-0260（此參考僅供內部環境使用，公開版本未提供）／0273（此參考僅供內部環境使用，公開版本未提供）／0274（此參考僅供內部環境使用，公開版本未提供）：amount/tx各自 valid non-null House → owning Agent override → Global；**Agent row 不存在**才 fallback，present null/blank/invalid 不得用 Global 掩蓋。required Global missing/invalid fail closed，不是 unlimited/zero capacity/hard-coded default。只讀實際 required chain，未使用的較低順位 invalid config 不阻擋有效 override。

- current requested page all-or-nothing：任一 required row/dimension failure 整頁失敗，不回 PageVo／partial rows／total／successful subset／configured-only／null、zero、stale、cached placeholders；detail同樣整份失敗，頁外不必額外解析。
- Create／Update／status 按 **post-command** configured state 在任何 persistent mutation/Audit前解析 required effective/source；失敗 **零 DB 寫入**（master/其他row/方向/limits/status/version/modify metadata/Audit/outbox/alert，即使 REQUIRES_NEW也不得寫）。same-state no-op VO 不能解析仍失敗，不假回success；不能先保存再組VO失敗，也不能用最終rollback代替 pre-write precedence。
- BO page/detail/Create/Update/status 固定 **HTTP 500／40053／HOUSE_LIMIT_CONFIGURATION_INVALID／data=[]**，data必須存在且exact空array，單筆/多筆/多dimension一致，不帶 source/reason/identity/value，不重用40005/40044/40048/5000。Frontend code→i18n，message diagnostic-only不解析、不凍結文案；其他 endpoints不由本段推導。
- config reader（不是 JSON request parser）：raw null→BLANK；Java21 `String.strip()`後空→BLANK，非空兩欄共用精確 `BigDecimal(String)`，再檢 positive/lossless DECIMAL/INT。Tx `100.0`／`1e2`／`+100`／`00100`／` 100 `接受為100；fraction/overflow/zero/negative拒絕，不 rewrite DB字串。
- secret-safe server log/metric，不建立 persistent BO alert/incident/list/SSE/scanner。根因實際 config scope＋key，Agent由 immutable owning Agent定位（僅 log，不是登入actor），Global不按受影響House另造根因。exact reasons `MISSING`（required Global absent）、`BLANK`（present null/strip-empty）、`INVALID_NUMERIC`（parse/nonpositive/representation合一）；Agent absent正常fallback。reason不進response data、不回raw config/secret；metric只固定有限分類、不放Agent/House/request/trace ID及hash/encoding變體。完整欄位/頻率/dedup/telemetry-failure policy依ADR-0282由owning implementation slice定案，不臆造方案。
- HOUSE persisted Global defaults `spay.house.daily.amount.limit=500000`、`spay.house.daily.tx.limit=100000`，不預建 Agent overrides、不作 compile-time fallback。Global UQ(`key`)、Agent UQ(`agent_id`,`key`)不帶status/version；唯一性非存在性、Optional非DB guard，duplicates不能任意取第一筆/修復。artifact不代表 operator已套用，不授權SQL。

### HOUSE Quota and Successors

- 原 shared Tx master wording仍保留歷史identity，current HOUSE只Deposit：original assignment owning Agent immutable fixed offset下 `[當地00:00,次日00:00)`，不以server/actor/Supplier或DST取代。成功 assignment同交易取得完整已驗證 requested Amount＋Tx1（不扣fee/猜actual/部分占用）；rollback無占用，in-flight也扣當日capacity。Amount/Tx使用同一記錄assignment事件時間，不用建單日或commit clock。
- 午夜不釋放/搬移前日占用，今日不計前日in-flight：上限1000、前日600仍進行、新日無占用可再承接1000，跨日1600合法，不宣稱銀行實際入帳日或全部outstanding上限。不同House IDs不合併/繼承：舊A used800、新B可1000，同帳戶1800；同ID停啟用不reset。
- 合法成功且actual已確認，原日Amount requested→完整actual與成功原子生效，不提前釋放差額、不先success留較小counter。上限1000、原預留600＋其他300、actual800→1100超額仍不僅因quota阻success，不能clamp為700；不由raw LINE/partial付款推導成功。Tx持續保留原1，不再加/釋放，原日9仍9，不出現中間0/2，也不搬完成日。
- 合法limit改變新admission立即fresh新值，既有counter/assignment不reset/取消；General Update允許低於當日occupancy（800→600，或clear override繼承600），不新增Update rejection，之後新派無capacity；再升1200可400，其餘gates仍須通過。
- 只有合法新assignment才能取得fresh requested＋Tx1及新事件日期；此quota約束不授權同House/跨House/跨fulfillment重派。尚未終止原承接的合法替換失敗，原attempt/current association/quota/deadline全原狀，新目標無新占用；不覆寫獨立expiry/settlement、不復活已終止、不撤銷已commit disposition/release。
- 已確認沒有該次資金交易＋assignment正式終止首次俱備時，原Amount＋Tx完整release同次原子生效，不能先放或背景再放，兩條件可不同順序抵達；歸原日不轉贈今日。expiry/未收到通知/待判定/失敗重派不是無資金證明，Tx不變成派發次數反濫用上限；HOUSE assignment到期另依ADR-0405即拒絕並同交易釋放原quota，仍不視為無資金證明。
- ADR-0397後 HOUSE不可逆EXPIRED＋唯一失敗terminal callback intent，仍保留待款責任；舊review不授權重開成功。合法 Deposit 舊入款裁決／zero-candidate matching依 [Deposit contract](deposit-target-native-contract.md) current transaction/operation，並保留本節master/financial拒絕。Withdrawal依ADR-0403 BO-only success／單次CH submission／Admin disposition／atomic close/release/terminal intent；retained recovery schema不是Withdrawal writer authority。

### HOUSE Unresolved Evidence

仍未決：Agent/Global config writer policy、overage diagnostic比較版本、telemetry exact技術契約、未被accepted ADR凍結的 master wire errors／migration collision policy；不得由較新ADR／runtime實作自行選方案。ADR-0300移交actual/no-funds/合法重派責任，適用金融後繼已由Deposit/Withdrawal專責contract收斂，不能反向用quota結果新增權限。#399 已修正 Create／Update request-first ordering、固定reason／canonicalization與config Tx parser／pre-write resolution 的 source 差異並驗收；Delete blocker exact error 由 #667 定案（見 [HOUSE Delete Safety](#house-delete-safety)），`house-master-gap` 已結案。

## Forbidden legacy identity

`SUPPLY_GATEWAY_ALLOCATION` and `PAYMENT_ACCOUNT_APPLICATION` are not menu, route, grant or API resources. A direct legacy route must be rejected. `SUPPLY_GATEWAY_ALLOCATION` functionality is Superadmin-only under `AGENT_MANAGEMENT`；不另建 menu/grant。

## 新增 protected API checklist

1. 選擇既有 catalog resource；可見功能新增 `ENTRIES`，非菜單功能新增同 catalog hidden entry。
2. 定義 principal、canonical action、server-derived owner scope 與 B/F/R，未 ready 一律拒絕 request。
3. handler 加唯一 `@RequireBackofficePolicy`；service 保留 lifecycle、owner、optimistic version 與 business guard。
4. 更新 OpenAPI/route registry，並新增 wrong-realm、missing-action、cross-scope 與 direct-route negative tests。

## Pre-enable checklist

每個 code 都需要 OpenAPI tag/operation、backend typed resource-action、realm/scope guard、route、正反向測試與 B/F/R approval。完整 metadata seed 不會取代任何 runtime evidence。
