---
id: spay4-target-schema-foundation-contract
status: accepted
audience:
  - backend
  - dba
  - qa
source_documents:
  - spay4-rebuild-consolidated-spec.md
  - ../../adr/spay4-target-architecture.md#adr-0386
  - ../../adr/authentication-and-credentials.md#adr-0387
  - ../../adr/spay4-target-architecture.md#adr-0388
  - ../../adr/authentication-and-credentials.md#adr-0395
  - ../../adr/hourly-financial-aggregate.md#adr-0389
---

# SPay4 Target Schema Foundation Contract

## Scope and exclusions

> **版本化 foundation 與 exact overlays：** 下列 relation／逐欄 mapping 保留 **14 Core＋38 Domain＝52 relations** 的 foundation baseline；Overview exact 2 為 `payment_account_identity_guard`／`payment_account_overview_command`，以 [Overview readiness](cardholder-overview-readiness.md) 核對新增欄位／兩表及未完成 gate；Withdrawal exact 1 為 `supply_withdrawal_operation`，以 [Withdrawal target contract](withdrawal-target-native-contract.md)／[Withdrawal schema inventory](schema-orders.md#2-d1-w1-relation-inventory) 核對責任與證據。Notification exact 2 為 `supply_notification_batch`／`supply_notification_batch_recipient`，依 ADR-0406（此參考僅供內部環境使用，公開版本未提供） 核對首次受理凍結 recipient／owner／channel manifest、exact request key replay 與獨立短 transaction 建立工作；不取代 notification provider lifecycle。HOUSE balance exact 1 為 `house_card_balance_log`，依 #419 與 SQL README（此參考僅供內部環境使用，公開版本未提供） 核對 HOUSE Card 帳面餘額 append-only ledger，不是 Withdrawal authority。BO alert exact 1 為 `bo_alert`，依 #428 與 SQL README 核對 Agent 範圍 BO 告警收件匣；#472 起另以 `recipient_scope=SUPERADMIN` 與 projection queue／失敗序號承載 hourly projection park 告警（#457）。Payment Account limit exact 1 為 `payment_account_currency_limit`，依 #421 與 SQL README 核對 CH Payment Account 幣別預設限額，只供 Deposit routing。依 SQL README／validator，Notification 後聯集為 57 relations（14 Core＋43 Domain），HOUSE balance 後為 58（14 Core＋44 Domain），BO alert 後為 59（14 Core＋45 Domain），其後再加 Supply Channel、Supply Channel daily quota、Supply Channel transaction 與 Channel report overlays，並經 #546 移除 `supply_withdrawal_recovery_case`、#697 新增 Payment Account identity history exact 1（`payment_account_identity_history`），目前 fresh DDL 聯集為 **69 relations（14 Core＋55 Domain）**，以 SQL README（此參考僅供內部環境使用，公開版本未提供） 的 Core／Domain inventory 與各 overlay inventory 為準（#617 以 `SchemaFoundationFreshInventoryIntegrationTest` 於本機 fresh DDL 驗證），exact baseline／各 overlays 分別核對、缺表／未知／重複仍拒絕；不代表57逐欄詳審，也不代表57之後任何聯集逐欄詳審。不能從 baseline 圖表、表數或 source inventory 推定 API ready、runtime／target SQL 執行、migration 或部署已驗證。

本contract描述 SPay4 target relation 的 identity、owner／snapshot authority、required field group 與 query-shaped index intent，供#197審閱。#197 審閱時的完整候選 inventory 為 `ddl.sql` 的 14 Core 加 38 Domain，合計 52 relations（含 Deposit-only `supply_deposit_operation`，不恢復已撤回六表），此數為歷史 baseline；#546 後現行 foundation 為 14 Core＋37 Domain＝51，加 overlay 後現行聯集為 69 relations（14 Core＋55 Domain），以 SQL README（此參考僅供內部環境使用，公開版本未提供） 的表名清單為準；逐表結果與文件/HTML finding 請見 [表格完整性審核](table-completeness-audit.md)，完整 nullable/cardinality 請見 [Target ER 審核](target-er-model-review.md)。每張表的 DDL 必須有 table／column `COMMENT`；關聯由 service transaction 驗證，不建立 DB foreign key。本文件不是DDL、seed、migration、database connection或runtime implementation授權。

SPay3 table、`supply_actor_account`、Legacy credential／session／routing／financial／reporting persistence都不是target authority。`realm`不能取代`agent_id`、`supplier_id`或`supply_gateway_id`。

Supplier offset 依 ADR-0402（此參考僅供內部環境使用，公開版本未提供） 與 [Supplier Setting contract](supplier-setting-api-contract.md) §4 為 creation-only：建立後任何 actor（包括 Superadmin）不可修改；Update 傳 `timezone`／`businessUtcOffset` 同值也拒絕。合法 name、operational/lifecycle/version 更新仍依專責 contract 的 fresh authority／scope／version guards。不回寫、搬移或重算既有 business date、counter、order、assignment、reservation、ledger、PT／Commission snapshot 或 report。`business_utc_offset` 保留 `CHAR(6) NOT NULL`、無 DB default；Create 未傳／null 的 application default 與 canonical fixed-offset 驗證以專責 contract 為準。COMMENT、ADR 或 source 存在不代表 runtime／MySQL／部署已驗證。

## Target relation matrix

| Relation | Identity／required field group | Authority與owner scope | Query-shaped index intent |
| --- | --- | --- | --- |
| `agent` | `id`；immutable Currency、Prefix 與 `business_utc_offset CHAR(6) NOT NULL` | Agent 固定 `±HH:MM` offset 是 House 日界與 Agent–Gateway effective-binding time authority；Create 明確提供、無 default、建立後 immutable | unique `prefix`；(`currency_id`, status, `id`) |
| `notification_provider_source` | `id`；source type、implementation vendor、display name、parser profile | LINE webhook provider registry；不保存 credential material | unique (`source_type`, `implementation_vendor`)；active source lookup |
| `credential_reference` | `id`；`agent_id`、kind、scope、LINE provider source、lifecycle/version | Agent OGP／LINE integration 的 non-secret metadata；OGP scope 固定 `DEFAULT` | unique (`agent_id`, kind, scope)；Agent lifecycle 與 LINE provider lookup |
| `credential_secret` | `id`；credential reference、API key/fingerprint、AES-GCM cipher、key version、rotation/version | `credential_reference` 的一對一 current OGP／LINE secret；唯一可保存 integration ciphertext | unique reference、API key、fingerprint |
| `supplier` | `id`；immutable `code=login_id`、business UTC offset（creation-only）；可更新 name、operational/lifecycle/version | Supply root；Supplier是Gateway唯一owner | unique `code`、unique `login_id`；owner/detail by `id` |
| `supply_gateway` | `id`；`supplier_id`、immutable currency／code；name、operational status、version | Gateway Currency與operational authority；不保存Agent owner或offset | unique (`code`，全系統唯一)；(`supplier_id`, currency, operational status, `id`) |
| `supply_account` | `id`；immutable `owner_type`／`owner_id`；global unique `account`；BCrypt password hash、TOTP AES-GCM cipher、single pending password-change challenge、session epoch、fixed profile、account lifecycle、version | Supplier或Gateway登入principal；直接保存 own credential/session state，不保存 Agent integration key | unique `account`；(`owner_type`, `owner_id`, account lifecycle, `id`) |
| `domain_audit_log` | append-only `id`；actor、stable `action_type`、aggregate-root target、owner keys、non-secret before／after／effect-object array、risk、request／trace | committed successful BO mutation evidence；audit write與mutation同transaction | (`supplier_id`, create time)、(`supply_gateway_id`, create time)、(`agent_id`, create time)、target lookup、(`action_type`, create time) |
| `supply_pt_policy` | `id`；immutable `owner_type`／`owner_id`；共享 immediate-change state、aggregate version | Supplier／Gateway／Cardholder owner-level PT aggregate | unique (`owner_type`, `owner_id`) |
| `supply_pt_revision` | `id`；policy、CURRENT／PENDING／HISTORICAL、effective month、active slot、version | 原子化兩方向 desired-state revision；history 永久唯讀 | unique (`policy_id`, active slot)；policy/status/month rollover lookup |
| `supply_pt_revision_line` | `id`；revision／direction、rate、base fee、threshold | revision 的唯一 Deposit/Withdrawal line；Cardholder 才使用 fee/threshold | unique (`revision_id`, direction) |
| `supply_gateway_direction_config` | `id`；`supply_gateway_id`／direction；min／max per-order limit、version | Gateway direction current config；不保存direction enable或daily limit | unique (`supply_gateway_id`, direction) |
| `supply_gateway_agent_allocation` | `id`；`supply_gateway_id`／`agent_id`；enabled、priority、version | Agent與Gateway N:M availability，不改變 Gateway owner、也不保存 Supplier key；Supplier 必由 Gateway owner chain 解析 | unique (`supply_gateway_id`, `agent_id`)；(`agent_id`, enabled, priority, `supply_gateway_id`) 支援 Agent-first enabled-binding read |
| `supply_eligible_fact` | immutable `id`；canonical source identity、occurrence instant、owner type＋owner keys（CH 帶 Gateway／Cardholder；Supply Channel 為 Supplier-only，Gateway／Cardholder 為 NULL，#512）、currency、direction、amount、offset snapshot | canonical accepted financial evidence | unique canonical source identity；canonical-hour／owner query |
| `supply_eligible_fact_correction` | immutable `id`；original fact reference、correction identity、signed delta | correction永遠屬原fact canonical hour／month | unique correction identity；original fact lookup |
| `supply_eligible_fact_projection_queue` | `id`；fact／correction work identity、current retry state、next eligibility、人工重排次數（#472／#457） | durable unfinished projection work；不是financial authority | unique work identity；(retry state, next eligibility, `id`) |
| `supply_eligible_fact_projection_failure_attempt` | immutable `id`；queue identity、committed failure sequence、classification／sanitized diagnostic | operations evidence；不表示投影完成 | unique (queue identity, failure sequence) |
| `supply_aggregate_projection_watermark` | `id`；logical source／partition、contiguous source cursor | projector progress only；不是report completeness gate | unique (logical source, partition) |
| `supply_financial_hourly_aggregate` | `id`；UTC hour、Commission Accounting Month、owner type＋owner keys（Supplier-only 列的 Gateway／Cardholder 為 NULL）、currency、direction、eligible amount／fact count、published revision | Report／Commission唯一共用read model；Commission為query-time derived | unique aggregate grain（owner 以 null-safe `owner_grain_key` 參與，#512）；owner＋hour／month report queries |

## Onboarding, report and seed boundaries

Supplier onboarding同一transaction建立Supplier、直接保存 credential state 的 Supplier initial `supply_account`、Supplier PT policy 與 current zero-value revision pair、DEFAULT Gateway、直接保存 credential state 的 Gateway initial `supply_account`、Gateway PT policy 與 current zero-value revision pair、兩筆Gateway direction config與一筆 required `CREATE_SUPPLIER` aggregate audit；Cardholder onboarding 同樣建立其 PT policy 與 current zero-value revision pair。任一失敗都rollback。audit target 為 Supplier，effect-object array 列出全部子資源的 non-secret committed effects。`user` 與 `supply_account` 分別保存 own TOTP/session state；Agent OGP／LINE integration credential 不屬於 onboarding aggregate。

Report以per-fact projection更新aggregate，並保留每分鐘recovery。Hourly Report Reconciliation只隔離重建已結束UTC hour，完整驗證後原子發布；可重跑但不得double count，不持久化Commission result。

本Issue不提供可執行seed。`system_method`／`role_method`的versioned idempotent BO_USER seed由Authorization child擁有；每份future seed或DDL package都須先對本contract取得獨立人工批准，再取得Operator／target approval。

## Table／column comment matrix

| Relation | Future table `COMMENT` | Required column `COMMENT` intent |
| --- | --- | --- |
| `agent` | Agent／Prefix master | `business_utc_offset` 是建立時明確設定、immutable、無 default 的 canonical `±HH:MM` time authority |
| `supplier` | Supply owner root | `code`／`login_id` canonical identity；`business_utc_offset` current owner time authority |
| `supply_gateway` | Supplier-owned Supply Gateway | `supplier_id` immutable owner；`currency_id` immutable Gateway currency；operational status current state |
| `notification_provider_source` | LINE webhook provider registry | source type/vendor 是 provider identity；parser profile 是穩定 routing metadata |
| `credential_reference` | Agent integration credential metadata | `agent_id` 是 owner；OGP `DEFAULT` scope、LINE provider source/scope 與 lifecycle 都是 non-secret metadata |
| `credential_secret` | Current integration ciphertext | reference 一對一；僅 `api_secret_cipher` 保存 OGP／LINE AES-GCM ciphertext |
| `supply_account` | Supply actor login principal | `owner_type`／`owner_id` immutable owner binding；`account` global login identity；password/TOTP/challenge/session epoch 與 profile/lifecycle 都是 current principal state |
| `domain_audit_log` | Append-only committed successful BO mutation audit | actor／`action_type`／aggregate-root target／owner keys are scope snapshots; before／after／effect-object array must be non-secret |
| `supply_pt_policy` | Supply owner PT aggregate | immutable owner binding, shared immediate-change entitlement and aggregate version |
| `supply_pt_revision` | Supply PT revision header | active slot permits one current/pending revision while immutable history remains append-only |
| `supply_pt_revision_line` | Supply PT direction line | revision/direction is unique; service always writes a complete Deposit/Withdrawal pair |
| `supply_gateway_direction_config` | Gateway per-direction current limit | Gateway reference and direction form unique grain; min/max are per-order current limits |
| `supply_gateway_agent_allocation` | Agent-to-Gateway availability mapping | both relation IDs define mapping; enabled／priority are current availability, not ownership；Supplier scope is resolved only through Gateway owner chain |
| `supply_eligible_fact` | Immutable accepted financial evidence | source identity is idempotency authority; owner keys／offset are immutable snapshots |
| `supply_eligible_fact_correction` | Immutable delta for original eligible fact | original fact reference and correction identity are immutable; signed delta stays in original bucket |
| `supply_eligible_fact_projection_queue` | Current unfinished projection work | work identity is unique; retry state／next eligibility are operational current state only |
| `supply_eligible_fact_projection_failure_attempt` | Immutable projection failure evidence | queue identity plus committed sequence is unique; diagnostic must be sanitized |
| `supply_aggregate_projection_watermark` | Per-source partition projection progress | source／partition identity is unique; cursor is contiguous progress, not report completeness |
| `supply_financial_hourly_aggregate` | Shared hourly Report and Commission read model | UTC hour／Commission month／owner keys form aggregate grain; amount and fact count are latest published values |

## Naming and owner-key trace

| Contract surface | Required name／authority |
| --- | --- |
| schema／relation | `supply_account` only; never `supply_actor_account` |
| API DTO／JWT principal | future principal identity is `supplyAccountId`; fixed profile and owner scope resolve server-side from the same `supply_account` identity |
| credential mapping／audit target | `credential_reference.agent_id` 僅綁定 Agent OGP／LINE integration；`user` 與 `supply_account` 各自直接保存 own password/TOTP/challenge/session state；audit actor／`action_type`／aggregate-root target 只保存非 secret snapshot，effect 必為安全 object array |
| owner chain | Supplier → Supply Gateway → Supply Cardholder → Payment Account; Agent allocation is availability only，且可跨 Supplier，不保存或推導 Agent-owned Supplier scope |
| report scope | applicable `agent_id`、`supplier_id`、`supply_gateway_id` are indexed keys; `realm` only classifies authenticated principal and cannot supply owner scope |

## Legacy-authority exclusion review

- target schema不讀取、匯入、fallback或dual-store Legacy raw secret、ciphertext、credential reference或configuration。
- `credential_secret` 僅保存 Agent integration AES-GCM ciphertext；`user` 與 `supply_account` 各自直接保存 own TOTP AES-GCM ciphertext。metadata、audit、log、telemetry、seed 與 Frontend persistent state 均不得保存 secret material。
- OGP callback URL 設定 authority 只可取 `agent.callback_url`；Deposit terminal event 的 `agent_callback_outbox.callback_url_snapshot` 僅保存由該 authority 驗證後凍結的 immutable destination，不是第二個設定來源。credential relation、Legacy pending URL 或 request payload 都不得提供 callback URL；outbox 不保存 signing material。
- 不以SPay3 table、DAO、entity、session、routing、financial或reporting persistence作target authority；`supply_actor_account`與Supply role table不建立。
- queue、failure attempt與watermark只承載projection operations state；只有accepted fact、correction與published aggregate形成financial read authority。
- 本Issue沒有可執行seed或DDL。未來每份seed／DDL package都必須先取得本contract的獨立人工審核，再取得Operator／target approval。

## Review evidence

本 relation matrix、table／column comment matrix、naming／owner-key trace、Legacy-authority exclusion review 與 [表格完整性審核](table-completeness-audit.md) 共同覆蓋#197的 documentary acceptance criteria。表格完整性審核不採納任何 DDL 修正；nullable system-scope `user` uniqueness（DEC-01）已由 #501 的 `uk_user_system_account`（generated `system_account`）與 #489 的服務 409 轉換結案。
