# SPay4 SYSTEM_NOTIFICATION_HISTORY：通知歷史、人工背景批次與完整 FCM

> **現況：#332／#339 已實作並啟用。** `SYSTEM_NOTIFICATION_HISTORY` 與 hidden `SYSTEM_NOTIFICATION_SEND` 已翻 READY，routes 見 [BO 菜單 API 參考](../concepts/backoffice-menu-api-reference.md#hidden-resource-路由)。以下保留規劃時原文；「沒有已確認 history API」「不開始實作」等敘述是當時狀態，不代表現況。

## Problem Statement

Superadmin 需要查詢 SPay4 Supply Cardholder 的通知歷史，區分站內信已讀狀態與 FCM 投遞結果，並能人工向指定 Supplier、Gateway 或持卡人發送通知。目前菜單只有未啟用的 identity／VIEW 宣告，沒有已確認 history API；部分 producer／entity 存在不代表完整 device registration、sender、recovery 或 provider 接線已完成。

參考 BO demo 可了解分類、篩選及頁籤，但 demo 的發送操作不是 SPay4 persistence 或 authorization authority。原有 spay-bo 人工公告只同步建立 IN_APP，不執行 FCM；其動態重算收件人與同 key 直接 skip 的行為也不符合本輪已確認的首次 snapshot 與 SPay4 immutable conflict 規則。

## Solution

提供 Superadmin-only、唯讀的通知歷史 API，以 IN_APP／FCM 分頁籤所需的 channel-specific 資料呈現全部來源；提供獨立權限的人工發送 API，沿用 Legacy 的內容驗證、使用 target-native recipients／owner／idempotency，非同步建立不限總人數的背景批次並完成 FCM sender／recovery 接線。

首次受理固定完整收件人集合與內容。通知建立與 FCM 投遞分開追蹤，單項失敗不回滾其他成功項目。此次不設計或實作畫面；Backend 不因 spec、DDL 或隔離測試通過而自動開啟菜單、release 或 production adapter。

## User Stories

1. 作為 Superadmin，我希望查詢全域 Supply Cardholder 通知，以便監督 SPay4 原生通知而不混入 Legacy 資料。
2. 作為 Superadmin，我希望 IN_APP 與 FCM 分開呈現，以便不把已讀狀態與投遞結果混為一談。
3. 作為 Superadmin，我希望同一事件的兩種 channel 保留獨立資料，以便查明兩者各自的處理結果。
4. 作為 Superadmin，我希望查詢 ORDERS、CARDS、SECURITY、SYSTEM 四種 category，以便按業務分類檢視。
5. 作為 Superadmin，我希望人工、BO 自動與 App 自動事件預設全部可見，以便不誤以為歷史缺漏。
6. 作為 Superadmin，我希望按通知 origin 篩選，以便分辨人工操作與自動產生的事件。
7. 作為 Superadmin，我希望來源無法可靠分類時仍看見未分類紀錄，以便保留真實歷史而不猜測來源。
8. 作為 Superadmin，我希望 origin 與業務 source provenance 分開，以便人工／自動分類不取代 domain event identity。
9. 作為 Superadmin，我希望按 Supplier 與 Gateway 篩選，以便定位歷史通知的組織範圍。
10. 作為 Superadmin，我希望按 Cardholder 篩選，以便追查指定收件人的紀錄。
11. 作為 Superadmin，我希望按 category 與 notification type 篩選，以便定位特定事件。
12. 作為 Superadmin，我希望按建立時間及標題／內文文字篩選，以便快速找到需要的通知。
13. 作為 Superadmin，我希望預設查最近 30 天且能查更早資料，以便兼顧日常使用與歷史追查。
14. 作為 Superadmin，我希望最新優先且穩定分頁，以便相同時間的紀錄不亂序或遺漏。
15. 作為 Superadmin，我希望 IN_APP 可篩選已讀／未讀並查看已讀時間，以便了解站內信閱讀情況。
16. 作為 Superadmin，我希望 FCM 可篩選 dispatch status，以便區分待派送、等待裝置、重試與 terminal 結果。
17. 作為 Superadmin，我希望詳情顯示完整標題／內文與可讀的關聯 display，以便不自行連查 master API。
18. 作為 Superadmin，我希望歷史歸屬保留建立時 owner snapshot，以便後續組織變動不改寫原來紀錄。
19. 作為 Superadmin，我希望 FCM 詳情提供 attempt count、retry、sent/end time 及 sanitized diagnostic，以便進行基本故障診斷。
20. 作為 Superadmin，我希望 FCM 成功不被顯示為持卡人已讀，以便不誤解 provider acknowledgement。
21. 作為 Prefix、Supplier 或 Gateway，我希望無權限的歷史／發送／批次查詢被拒絕，以便只開放已確認的 Superadmin 權限。
22. 作為 Superadmin，我希望歷史查詢與人工發送分開授權，以便 VIEW 不隱含發送權。
23. 作為 Superadmin，我希望按多個 Supplier 選擇旗下持卡人，以便發送組織公告。
24. 作為 Superadmin，我希望按多個 Gateway 選擇旗下持卡人，以便發送指定 Gateway 公告。
25. 作為 Superadmin，我希望直接選多位 Cardholder，以便發送精確的人工通知。
26. 作為 Superadmin，我希望每次只用一種 selector 並去除重複 ID，以便不產生重複收件人。
27. 作為 Superadmin，我希望只納入 ACTIVE 持卡人，以便不向不合資格帳號建立新的人工通知。
28. 作為 Superadmin，我希望直接指定不存在或不合資格者時在受理前被拒絕，以便不偷偷忽略錯誤目標。
29. 作為 Superadmin，我希望人工通知固定 SYSTEM category 且只接受三種人工公告 type，以便不偽造自動事件。
30. 作為 Superadmin，我希望必填標題／內文分別限制 120／2000 字元，以便沿用原有人工公告內容 contract。
31. 作為 Superadmin，我希望每次送出都填寫操作原因並寫入受理 audit，以便追溯每次人工通知的目的（#486 取代 #221 的固定 audit reason）。
32. 作為 Superadmin，我希望能指定 IN_APP、FCM 或兩者且預設兩者，以便按需要選擇投遞方式。
33. 作為 Superadmin，我希望提交後取得受理 receipt 與 batch identity，以便不等待所有持卡人處理完成。
34. 作為 Superadmin，我希望沒有總收件人 cap 而使用背景批次，以便大規模發送仍可持續處理。
35. 作為 Superadmin，我希望首次受理即固定完整 recipient／owner／channel manifest，以便 queue 延遲不改變收件人。
36. 作為 Superadmin，我希望以相同 requestKey 重試得到同一批次，以便網路 timeout 不建立第二次發送。
37. 作為 Superadmin，我希望相同 key 重試不納入後來新增者，以便第一次選定名單維持穩定。
38. 作為 Superadmin，我希望相同 key 不同 immutable 內容得到 conflict，以便錯誤重用 key 不靜默遺失通知。
39. 作為 Superadmin，我希望省略 requestKey 時由 Backend 產生並回傳，以便保留原有便利性及後續重試 identity。
40. 作為 Superadmin，我希望查詢每個 channel 的通知建立 counts，以便分辨新建、replay、pending 與 failed。
41. 作為 Superadmin，我希望通知建立完成與 FCM 投遞進度分開，以便等待裝置不讓整批看似一直建立中。
42. 作為 Superadmin，我希望某個 recipient／channel 失敗時其他工作繼續，以便不因單項問題停止整批。
43. 作為 Superadmin，我希望成功項目不因批次 recovery 被重新建立或 dispatch，以便減少重複操作。
44. 作為維運者，我希望受理與工作具備 durable persistence，以便程序重啟不遺失已接受的批次。
45. 作為維運者，我希望每次 worker 掃描及 transaction 有界，以便無總人數 cap 不造成無界記憶體或長 provider transaction。
46. 作為維運者，我希望 claim／crash／concurrency recovery 可核對，以便不只靠記憶體 queue 或 pre-read 保證安全。
47. 作為持卡人，我希望登入或裝置尚未註冊不阻止 IN_APP 建立，以便站內信不依賴推播裝置。
48. 作為持卡人，我希望 FCM 無 eligible current-session registration 時等待而不消耗 provider attempt，以便後續註冊仍有合法派送機會。
49. 作為持卡人，我希望 Android 裝置以本人 verified native session 註冊，以便其他人不能指定我的 owner 或 provider。
50. 作為持卡人，我希望新 registration 使用新 generation 並原子取代舊 active slots，以便 token rotation 與 account switch 不混用裝置。
51. 作為持卡人，我希望 terminal registration 清空 ciphertext 且不復活，以便失效 delivery material 不繼續保存或使用。
52. 作為持卡人，我希望取消 registration 僅影響本人 installation，以便相同 device ID 不跨帳號撤銷。
53. 作為持卡人，我希望成功 registration commit 後喚醒合法等待通知，以便遺漏喚醒仍能由 recovery 恢復。
54. 作為持卡人，我希望每次 claim 僅選 current active session 最新 eligible generation，以便不 fan-out 至舊裝置。
55. 作為維運者，我希望 provider success、permanent invalid token、transient failure 與 unknown outcome 分開，以便不偽造 delivery 成功或永久失效。
56. 作為維運者，我希望遵循固定投遞窗口、lease、retry 與 admission budgets，以便大批次不繞過既有保護。
57. 作為持卡人，我希望 App 只讀／mark-read 本人的 IN_APP，以便 FCM outbox 不成為第二個可讀 inbox。
58. 作為持卡人，我希望已讀站內信不取消 FCM，以便兩種 channel 的 lifecycle 不互相覆寫。
59. 作為稽核者，我希望受理與 committed mutation 保留真實 actor、request identity 及非秘密 audit，以便失敗不被記成成功。
60. 作為稽核者，我希望 BO response、audit、log 及 error 不包含 token、credential 或 raw provider payload，以便查詢不洩漏 delivery secret。
61. 作為 Operator，我希望先取得經靜態驗證的 DDL，再人工確認 target／執行／read-back，以便 agent 不自行執行 schema 變更。
62. 作為 Operator，我希望 existing target 不被 fresh DDL 重建，以便已存在資料與 credential 不被 DROP 或盲目轉換。
63. 作為開發者，我希望 backend、frontend、release readiness 分別核對，以便 schema／spec 存在不被當成 runtime ready。

## Implementation Decisions

### Authority、module 與政策

- Runtime owner 為 spay4-bo 的 supply vertical slice；auth 提供 fresh principal/session 與 policy，audit 提供參與式 target audit。Controller 與跨 concept collaborator 只依賴 service interface／DTO；不以 Legacy DAO、entity、RoleSet、DB 或 fallback 作 target authority。
- 既有 SYSTEM_NOTIFICATION_HISTORY 僅 SUPERADMIN／VIEW。人工發送使用獨立 SYSTEM_NOTIFICATION_SEND resource，SUPERADMIN／INSERT；batch progress 使用此 resource 的 VIEW。本期不新增畫面或 materialize menu seed；後續 code 可用既有 hidden policy entry pattern 接線，但所有 B/F/R／production transport 在未驗收前維持 fail closed。
- 首次受理及每次 HTTP read／replay 都需 fresh authority，不由 client owner ID、JWT claim、menu visibility 或已存在 requestKey 授予權限。Background work 只能使用已 commit 且有 audit 的 target-native accepted command，不 impersonate client session、不從自由文字 selector 取得新權限。
- Native Cardholder 裝置入口只接受由現有 registered verifier 簽發的 verified context；decoded claims、BO principal、裸 Cardholder ID 或 Legacy session 不得替代。只補本功能必要的 registration／unregister／wake-up 及 notification consumer isolation，不擴張其他 App 功能。

### BO API contract

| Method | Canonical endpoint | Resource／action | 成功結果 |
| --- | --- | --- | --- |
| GET | `/bo/v2/notificationHistory/page` | SYSTEM_NOTIFICATION_HISTORY／VIEW | HTTP 200，raw PageVo |
| GET | `/bo/v2/notificationHistory/{id}` | SYSTEM_NOTIFICATION_HISTORY／VIEW | HTTP 200，raw channel-specific detail VO |
| POST | `/bo/v2/notificationBatches` | SYSTEM_NOTIFICATION_SEND／INSERT | HTTP 202，raw acceptance receipt |
| GET | `/bo/v2/notificationBatches/{batchId}` | SYSTEM_NOTIFICATION_SEND／VIEW | HTTP 200，raw batch progress VO |

- 不另建 aliases 或一律套 Legacy ResponseVo advice；測試核對 actual JSON shape。沿用 target error handler／SystemCode，validation、denied、not-found、conflict 與 dependency-not-ready 分開，不回 raw input／exception／secret。
- History required deliveryChannel 為 IN_APP 或 FCM；每個頁籤單獨查詢，不以 logical event 合併 row。共用 optional filters：supplierId、gatewayId、cardholderId、category、type、origin、from、to、search；IN_APP 額外 read，FCM 額外 dispatchStatus。另一 channel 專用 filter 在錯誤頁籤拒絕，不偷偷忽略。
- Categories 為 ORDERS／CARDS／SECURITY／SYSTEM；origin 為 BO_MANUAL／BO_AUTO／APP_AUTO，UNKNOWN 僅用來查詢無法分類的既有 null origin。Origin 預設不篩選，全部來源可見；新 producer 必須從 Backend catalog 提供明確 origin，不能依 sourceType 字面或 idempotency key 猜測。
- pageNumber zero-based 預設 0，pageSize 預設 20、範圍 1..500；invalid 拒絕、不 cap。排序 createTime／id DESC。from／to 為 UTC ISO LocalDateTime inclusive；兩者缺省時為受查詢 serverNow 前 30 天至 serverNow，單缺 to 用 serverNow、單缺 from 用 to 前 30 天。from 大於 to 拒絕；不限制可查更早時間、不引入 retention/delete policy。
- Owner filters 使用 immutable Supplier／Gateway snapshots，不透過 current Cardholder owner 改寫歷史。Response 同時提供 identity 與可讀 display，清楚標示 owner ID 為 historical snapshot；display 是 current lookup 或缺失時 null，不偽造 historical name snapshot，不授予新的 scope。
- Detail 共用 identity／historical owner／recipient display／category／type／origin／sourceType／sourceId／createTime／title／body；IN_APP 提供 read/readTime，FCM 提供 dispatchStatus、attemptCount、nextRetryTime、sentTime、dispatchEndedTime、dispatchEndReason、lastErrorCode／sanitized message／time。FCM 沒有 read state；detail 不回 payloadJson、device identity/material、provider raw payload、idempotency key、lease 或 version。
- 不存在或無合法 authority 的 detail／batch 使用 target 既有 secret-safe not-found／denied 語意；本期不向 Supplier／Gateway 開放 scoped history。

### 人工內容、recipients 與首次受理

- Request 為 targetType、對應 selector ID list、eventType、title、body、必填 reason、optional requestKey、optional deliveryChannels。不接受 category、origin、source、actor、owner、auditReason 等 reason 以外的 audit 欄位、payload、ciphertext、status、version 或 server-derived fields；unknown／duplicate JSON properties、wrong types、空 channel set、非法 enum／ID／mixed selector input fail closed。
- targetType 為 SUPPLIER／GATEWAY／CARDHOLDER；每次僅一種，ID positive，去重並排序形成 request identity。不存在的 explicit selector 在受理前拒絕；group resolution 僅包含 row lifecycle 與 cardholderStatus 都 ACTIVE、owner chain 合法的 native Cardholders。Direct Cardholder 任一不存在／非 ACTIVE／owner 不合法時整個 request 受理前拒絕，不產生部分 batch。
- 非空且有效的組織 selector 沒有 eligible recipients 時，沿 Legacy zero-target 行為回受理 receipt／targetCount=0，建立進度已完成，沒有 notification／FCM work；這不是 request 格式錯誤。不得因沒有 device registration 排除其他合法 recipients。
- 沿 Legacy 內容規則：eventType 僅 ANNOUNCEMENT／MAINTENANCE／ALERT；category 固定 SYSTEM，origin/sourceType 固定 BO_MANUAL，sourceId／payload 為 null。title/body 原始輸入先驗非空及長度 120／2000，再沿原有 edge trim 保存，不截斷超長內容。reason 必填，以共用 `OrderReasonPolicy.requiredStrictUnicode` 驗證（原文不得含控制字元或 malformed UTF-16，strip 後 1～500 code points），保存 strip 後的值；缺少、null、空白、非字串或超長回 400／40005，錯誤與 log 不回顯 reason。requestKey optional、最長 120，提供時須通過中央 ASCII segment grammar，不 trim/case-fold；省略則 Backend UUID 並回傳。
- deliveryChannels 缺省為 IN_APP＋FCM，可顯式選單一或兩者；null／unknown／重複 channel input 不使用隱含 fallback。Channel set 的排序不改變 request identity。
- 首次受理在單一一致 transaction 固定 request、完整 distinct recipient 集合、Supplier/Gateway snapshot、所選 channel manifest 與 audit，commit 後才回 202。不等待全部 notification 建立或 provider send，但不能先回受理再用較晚資料選人。Freeze failure 不留下 accepted receipt／半套 manifest。
- 不限制總收件人數或偷偷截取部分人；manifest 以可證明一致性的 set-oriented／bounded persistence 形成，不將全量 JPA entities 或 target IDs 載入 JVM。若需 native SQL bulk adapter，限此有證據的 snapshot 目的，不能演變為通用 SQL runner。
- Immutable owner chain 若在 notification insert 時不合法或與首次 snapshot 不一致，該 work 記錄失敗、不轉給目前其他 owner、不修改 manifest；其他工作仍繼續。

### Persistence 與建立工作

- 既有 notification relation 增加 nullable immutable notification_origin 及 deliveryChannel／createTime／id 的 global-history index。新 producer 必填 origin，舊資料無可靠 mapping 時保持 null，不自動回填 UNKNOWN token；filter/display 將 null 表達為 UNKNOWN。
- 新增 supply_notification_batch：保存 exact ASCII binary unique requestKey、真實 actor、canonical selector snapshot、type/content、channel flags、distinct targetCount、snapshot/create time。無 request hash、mutable content 或 FCM counters 複本。
- 新增 supply_notification_batch_recipient：每個 batch／Cardholder／channel 一筆，保存 immutable owner/channel manifest 與獨立 notification 建立工作。Unique tuple 防重；notification reference unique 且成功後不重綁，並有 batch progress、PENDING、RETRY、stale PROCESSING lanes 的 indexes。
- Creation work 狀態為 PENDING／PROCESSING／RETRY／CREATED／DUPLICATE／FAILED；不是 notification dispatchStatus。Worker 每次 bounded discovery、每項短 transaction、持久 claim／lease／CAS 與 crash recovery；retry budget/backoff 必須由 Backend 明確有界設定並測試，不能以永久 busy-loop 取代恢復。不因內部 page/admission budget 限制總 recipients。
- 同 requestKey 先驗 authority，再比較 canonical selector、type、title/body 與 channels，回同一 batch、固定名單及最新進度；不同 immutable request conflict。reason 不參與比對（ADR-0406）：同 key 不同 reason 回首次結果，不新增 audit 或發送，保留首次 reason。不存在 committed batch 的首次失敗可用原 key 重試；省略 key 的第二次提交是新 request，不能承諾自動去重。
- Notification key 由中央 factory 產生並含 recipient/channel，全表 ASCII binary unique；只有完整 immutable identity／owner／source／content 相同才 replay。Unique race 以 DB 最終防線與 conflict reload 正確處理，不能只以 pre-read 宣稱安全。BO_MANUAL sourceId 維持 null，batch ID 不冒充 entity source ID。
- 每個 channel 的 notification insert/replay、manifest reference、工作 terminal result 與必要 target audit 同 transaction；audit failure rollback 該項但不回滾其他已 commit 項目。成功及合法 replay 不再 insert／dispatch；transient creation failure 與 permanent conflict 明確區分。
- Batch counts 使用 long／BIGINT 等可容納大量資料的型別，從 committed manifest／notification 推導。Receipt 回 requestKey、batchId、targetCount、所選 channels、acceptedTime、creationStatus；不回全量 recipient array。Progress 回每 channel 的 expected／pending／processing／retry／created／duplicate／failed counts，以及 FCM 各 dispatch state counts。
- CreationStatus 由工作推導為 QUEUED／PROCESSING／COMPLETED／PARTIAL_FAILED／FAILED；zero-target 為 COMPLETED。中途有 FAILED 不使其他工作停止；所有工作 terminal 後才形成建立終態。FCM progress 另列，不要求 creation batch 等到所有 provider outcomes terminal。

### 完整 device／FCM lifecycle

- Fresh device schema 依 accepted ADR 使用 Backend-owned FCM、required ANDROID、case-sensitive opaque deviceId、algorithm-tagged tokenHash、version-tagged AES-GCM ciphertext、ACTIVE／INVALIDATED／DEAD 與 immutable endedTime／reason。移除獨立 key-version authority、全歷史 fingerprint unique 與 LINE provider-source binding。
- ACTIVE-only installation slot 在 Cardholder/provider scope 唯一，ACTIVE token identity 跨 Cardholder 唯一；terminal 可保留相同 hash，但 ciphertext 必須同 transaction 清空。Registration 每次建立新 generation，原子替換命中的全部舊 ACTIVE rows，禁止復活 terminal。
- 使用既有 external device-token family 的 register/unregister facade，接線至 verified native context；provider／Cardholder ID／ciphertext／hash／key version／end reason 由 Backend 決定。Raw token 不 trim／case-fold／normalize；ANDROID 限制不因共用 enum 存在其他平台而放寬。Unregister 無 active target 是不產生 mutation audit 的 idempotent no-op。
- Registration commit 後 best-effort wake-up；漏掉的通知由 durable recovery 恢復。登入、logout、密碼重設、session termination 與 account/gateway deactivation 的 token invalidation 必須保持既有 source-session lifecycle，不借 Legacy token/session 作 fallback。
- IN_APP 建立即 SENT、attemptCount=0，只有該 channel 可有 readTime。FCM 初始 PENDING、readTime 永遠 null，使用 PENDING／WAITING_FOR_DEVICE／PROCESSING／RETRY／SENT／SKIPPED／EXPIRED／DEAD；修正現有 entity 的 CREATED／category/type/readTime 不一致，不放寬已接受 catalog。
- 每次 FCM claim 選 current ACTIVE formal session 最新 eligible active generation，不 fan-out。無 eligible registration 進 WAITING_FOR_DEVICE、不耗 provider attempt；已 commit claim 不被稍後 login 撤回，後續 attempt 才重新選 token。
- 每筆 FCM 的 deadline 為 immutable notification createTime＋24 小時，不使用 batch request/snapshot time，不因 login／registration／retry 重設。到期未 claim 為 EXPIRED／DELIVERY_WINDOW_EXPIRED；無法確認已 claim outcome 且無 retry window 時為 DEAD／DELIVERY_OUTCOME_UNKNOWN，不偽稱 provider 已拒絕。
- 遵循固定五分鐘不可續租 lease、最多五 committed claims、同 claim 短 retry 1／2／4 秒及 durable retry 1／5／15／60 分鐘。UTC recovery 每十分鐘、四條 state-specific lanes（stale lease、due retry、PENDING、WAITING_FOR_DEVICE，依 ADR-0411（此參考僅供內部環境使用，公開版本未提供））各 100、wake-up 最多 100；這些是 admission budgets，不是 batch 總收件人限制。單筆建立（`create(...)`）新插入的 FCM row 在建立交易 commit 後立即派送一次（ADR-0460（此參考僅供內部環境使用，公開版本未提供））；人工通知批次的首次派送、立即派送失敗或漏接的補送仍走上述 recovery。
- Provider I/O 在 claim commit 後、短 DB transaction 外執行；finalize 必須核對 exact claim/version/target generation。成功需要 provider message ID。永久 token failure 與 notification finalization 同 transaction；較晚已 terminal token 的原 tuple 不覆寫、不把結果套到最新另一 generation。
- Sender／recovery／Firebase adapter 與 deployment readiness 完整接線；secret 僅由 operator-managed target configuration 提供，不能 import/read/fallback Legacy credential 或把 LINE credential_secret 當 FCM authority。未 provisioned／無法解密／未知 provider result fail closed 並回可診斷的安全狀態，不假裝成功。
- FCM 是 at-least-once；batch replay 不重建成功 row、不主動再次派送 SENT，但 stale claim／未知 outcome recovery 可能重複 provider delivery，不承諾 exactly-once。
- Native App list／mark-read 僅 authenticated Cardholder 的 IN_APP；read 不取消 FCM，也不自動補 sibling。IN_APP／FCM row 可獨立成功或失敗，不新增跨-channel transaction 保證。

### Query、audit 與 schema 安全

- 可選條件採 dynamic predicate，不使用 nullable OR 或對 indexed column 包 function 作主要篩選；title/body contains search 不宣稱 B-tree acceleration。以真 MySQL query semantics／EXPLAIN 驗 owner/channel/time pagination 及 candidate lanes，不先加 category/type 專用 index。
- 受理 audit 的 `after_summary.reason` 為首次受理 request 的正規化 reason；背景 work lifecycle audit 維持固定 reason manual announcement。背景讀取已 commit 受理 audit 時接受任何符合共用 reason 規則且已正規化的值，含歷史固定值 manual announcement。Audit 使用真實提交 actor／accepted command identity、batch／work/channel 與安全 counts；不複製全文、raw provider message、token、ciphertext、key material 或 raw payload 至 generic audit/log/error。Denied、validation、rollback、replay/no-op 不製造新的 committed mutation audit。
- 所有新 relation／column 有具體 COMMENT，InnoDB／utf8mb4／utf8mb4_unicode_ci，exact identities 採適用 binary comparison；不建 DB foreign key 或 runtime catalog CRUD。Service 驗證 channel/status/read-time、owner、source、claim 及 terminal tuple。
- SQL 是先行的 fresh schema review artifact，不代表已執行。Existing target 即使 empty 也不可重跑 fresh DDL，需經 target classification 另審 upgrade artifact；本期不盲目產生 ALTER、backfill、Legacy import、data repair 或 seed。

## Testing Decisions

- 測試只斷言外部可觀察行為、JSON contract、persisted facts、transaction results 及 provider adapter outcomes，不鎖定 private helper、mock call order 或內部 class 拆分。
- 主要最高 seam 為既有 BO MVC/security/session boundary → target-native persistence → controlled background ticks → history/batch progress。Device registration 在既有 verified native Cardholder application boundary 驗證，必要 facade 也需真 session／epoch／owner assertions；不新增低階 production testing hooks。
- Provider 邊界採受控 FCM transport／clock／故障注入，使用合成 token/credential fixture，不使用 Legacy／target secret、不連真 provider 作常態 tests。Actual adapter wiring 需驗格式、project binding、timeouts、provider mapping 及 secret-safe outcomes；真 sandbox smoke 必須另外取得 operator 授權與安全 evidence，未執行不可宣稱 live ready。
- Prior art 為 target Domain Audit query／policy integration、Overview native HTTP／audit rollback／command concurrency、Withdrawal bounded per-item transaction batch，以及 Legacy manual announcement 的內容／zero-target／500 discovery tests。只重用測試模式，不把 Legacy authority／mock success 當 target acceptance。
- History matrix 覆蓋四 category、三 origin＋UNKNOWN、兩個 channel、read/status 專用 filter拒絕、UTC date bounds/default、30 天外查詢、tie-break、page count、search、missing display、historical owner與 raw/sanitized response；至少含 duplicate createTime 跨頁穩定性。
- Policy matrix 覆蓋 Superadmin allow、Prefix/Supplier/Gateway/CH/anonymous deny、revoked/expired/epoch mismatch、authority-before-replay、guessed batch/detail ID 與 closed readiness。不能僅測 menu visibility。
- Request matrix 覆蓋三 selector、mixed/empty/invalid IDs、duplicate IDs、active/locked/inactive、group filtering與直接指定拒絕、owner-chain fail closed、zero recipients、type/category/origin spoof、title/body boundary與先驗長度再 trim、strict JSON、optional/invalid key、channel default/單選/雙選。
- Snapshot／acceptance 使用 disposable MySQL：大量 recipients 大於 500 及 worker page size仍全數處理、無 int overflow；一萬人也不全量 entities 入記憶體。Concurrent selector membership／eligibility changes、接受提交後新增者、程序重啟與 freeze rollback 都不得改變首次 accepted 集合或留下半套 receipt。
- Batch idempotency／unique race 覆蓋同 key same request、同 key改 selector/content/channel conflict、順序與去重 canonical equivalence、兩個 concurrent first submits、audit failure、insert-conflict reload、crash在 claim/insert/reference/finalize 間，驗 notification/work/audit 原子性與 counts 可重算。
- Partial matrix 至少有一位一個 channel永久失敗、另一 channel成功、其他 recipients繼續、temporary dependency恢復、成功 replay不重建、全部失敗及零目標；creationStatus與FCM長時間WAITING/RETRY互不混淆。
- Device matrix 覆蓋 genuine native session、ANDROID/provider/owner spoof拒絕、deviceId exact比較、raw token no normalization、active slots並發、相同token的新 terminal history generation、跨CH installation isolation、rotation rollback、terminal ciphertext removal、source-session reasons、unregister no-op及 commit後 wake-up。
- FCM matrix 使用可控制時間：no token不耗attempt、new registration／login race cutoff、latest generation/no fanout、24h boundary、五分鐘 stale lease、五 claims、短/durable retry、三lane budgets、provider ID required、permanent invalidation原子性、較晚token terminal優先、DEAD unknown outcome與EXPIRED區分、read不取消FCM及不補IN_APP sibling。
- True schema／transaction／locking／rollback／unique race／query semantics 必須用隔離 MySQL，不用 H2 或 mock 替代。SQL static guards 與 negative text fixtures 不執行 SQL、不連 DB，涵蓋 exact two-table overlay、origin/global index、Device partial uniqueness／ciphertext／forbidden old fields、COMMENT／charset/no FK。
- 實作完成後依 module/consumer 執行 compile、targeted behavior及隔離 integration；有 source/build 變動後重新跑固定 native SPay4 validation，不沿用舊 GREEN／counts。Setup、skipped、launch receipt、fixture success、source-only tests與 runtime acceptance 分開報告；dirty worktree/native provider不可用時記錄 BLOCKED，不改用自由 full CLI。

## Out of Scope

新 BO／App 畫面、前端頁籤實作；Supplier/Gateway/Prefix 通知權限；Legacy notification_outbox/session/credential import、read fallback或dual-write；BO inbox、Email、SMS、LINE history；公告主檔CRUD、草稿、排程、附件或撤回；歷史刪除、人工重送、代標已讀、CSV/export；逐次 immutable FCM attempt timeline；iOS/Web或其他provider；自動補channel sibling、跨channel atomicity及 exactly-once；自動SQL/migration/seed/grant/backfill、production/cutover啟用、secret provisioning、未授權 target/Legacy DB或真provider連線。

## Further Notes

- 此 spec 已由使用者逐項確認後要求發布，無需再次訪談。Demo：[notifications](https://spay-bov2.web.app/notifications)，只參考 history 分類／互動；人工內容沿 Legacy，資料與 authority 完全 target-native。Canonical token 是 SYSTEM，不是對話中的 SYSTE 拼字。
- 設計 authority：ADR-0406（此參考僅供內部環境使用，公開版本未提供）、channel/owner ADR-0414（此參考僅供內部環境使用，公開版本未提供）、idempotency ADR-0364（此參考僅供內部環境使用，公開版本未提供）、source ADR-0365（此參考僅供內部環境使用，公開版本未提供）。FCM/device沿 ADR-0329至0339、0341至0363、0373至0374，受ADR-0414明示 supersession 的舊 read/combined-row 內容不可回復。Credential沿ADR-0387→0395→0396 direct-principal chain，不能誤認為FCM provisioning contract。
- 歷史設計 Issues #143／#145／#148／#152 已 closed，不宣稱其 schema、fixture或token entity即已完成本功能。Discovery未找到通知batch/manifest、完整target registration/sender/recovery；本ticket須補齊，不能用NativeCallback或金融receipt替代。
- 現有bo-menu/API progress、reader／API-table-impact及部分entity仍有舊語意；此spec不把它們標成ready。Runtime實作時同步consumer contract與相關readiness文件，不為本期先行SQL改寫所有歷史圖表。

### Blocking prerequisite：SQL 前置 ticket 與人工 schema gate（body）

> **歷史紀錄：** 本段是開工前的 SQL gate。SQL #220（此參考僅供內部環境使用，公開版本未提供） 已結案，#332／#339 已實作並啟用；下列 BLOCKED／不開始實作的敘述不代表現況。

- SQL 前置 Issue：SQL #220（此參考僅供內部環境使用，公開版本未提供）；本功能 ticket 必須等待該 ticket 的 Operator 執行／read-back evidence，不能只依 closed state 判定完成。SQL scope 與 artifact 已分拆至 [SQL prerequisite spec](spay4-notification-sql-prerequisite.md)。

- 已先行準備 sql/V4/ddl.sql（此參考僅供內部環境使用，公開版本未提供）；完整聯集為57 relations（14 Core／43 Domain），新增supply_notification_batch與supply_notification_batch_recipient，並更新notification origin/global history index及Device generation schema。審核步驟以 SQL README（此參考僅供內部環境使用，公開版本未提供） 為準。
- **Gate狀態：BLOCKED／等待Operator手動執行與read-back。SQL已生成不等於已執行。**在Operator提供合規schema completion evidence前，本功能ticket不開始實作、不執行依賴schema的runtime/target驗證，也不把此gate標成通過。先行SQL／spec工作只在獨立worktree，不修改使用者本地分支。
- Operator須記錄不含credential的target alias/schema identity、DBA/target approval、exact artifact SHA-256、手動執行結果及columns/indexes/nullability/57-table inventory的read-back evidence。發佈時記錄DDL SHA-256：`684ac4f635af1f0344c8a85e4ed2043a8c0f07f9924dae497c9f21f56c7559df`；target identity尚未提供，不猜測database或環境。
- **Fresh DDL包含DROP；只依README對fresh candidate審核。Existing target（即使empty）必須停止，另案經target classification準備手動upgrade artifact，不可拿整份ddl.sql升級。**本spec/DDL preparation不授權清庫、修正資料、讀secret或自動執行。
- Repository現有prerequisite resolver只支援BO V2，不能verify此V4 gate；本Issue不產生unsupported machine declaration、不改resolver、不以fixture代替manual target read-back。人工completion以Issue comment/approved evidence解除body gate。
- DDL目前是本地worktreeartifact，未自動commit/push；執行者必須先確認artifact已納入其source baseline且hash相符，缺失或版本不同一律BLOCKED，不從spec重造猜測SQL。此功能Issue保持opened，手動SQL完成只解除schema前置，不代表Backend/FCM完成。
- Provider/project/target encryption key provisioning與sandbox smoke evidence由Operator依安全配置另行提供；absence必須fail closed，不能偷偷借Legacy credential。功能隔離 acceptance 與 live/deployment readiness 分開記錄。完整 docs/Postman gates 的既有 baseline 漂移不得被本 ticket 忽略；SQL artifact 的 24 個 focused schema tests 通過不代表 full gate GREEN。
