---
id: spay4-reporting-timezones
type: concept
status: proposed
audience:
  - backend
  - accounting
  - qa
source_documents:
  - ../../../spay-bo/src/main/java/com/sit/spay2/model/db/Agent.java
  - ../../../spay-bo/src/main/java/com/sit/spay2/task/service/impl/BusinessPeriodServiceImpl.java
  - ../../adr/supply-routing.md#adr-0055
  - ../../adr/commission-and-reports.md#adr-0180
  - ../../adr/commission-and-reports.md#adr-0181
  - ../../adr/commission-and-reports.md#adr-0182
  - ../../adr/commission-and-reports.md#adr-0183
  - ../../adr/commission-and-reports.md#adr-0184
  - ../../adr/commission-and-reports.md#adr-0185
  - ../../adr/commission-and-reports.md#adr-0186
  - ADR-0187（已移除，見 git c8fb32936）
  - ../../adr/commission-and-reports.md#adr-0188
  - ../../adr/commission-and-reports.md#adr-0189
  - ADR-0190（已移除，見 git c8fb32936）
  - ../../adr/hourly-financial-aggregate.md#adr-0191
  - ../../adr/prefix-gateway-allocation.md#adr-0192
  - ../../adr/agent-integration.md#adr-0230
  - ../../adr/commission-and-reports.md#adr-0193
  - ../../adr/commission-and-reports.md#adr-0194
  - ../../adr/hourly-financial-aggregate.md#adr-0195
  - ADR-0196（已移除，見 git c8fb32936）
  - ../../adr/hourly-financial-aggregate.md#adr-0197
  - ../../adr/hourly-financial-aggregate.md#adr-0198
  - ../../adr/hourly-financial-aggregate.md#adr-0199
  - ADR-0200（已移除，見 git c8fb32936）
  - ADR-0201（已移除，見 git c8fb32936）
  - ADR-0202（已移除，見 git c8fb32936）
  - ADR-0203（已移除，見 git c8fb32936）
  - ADR-0204（已移除，見 git c8fb32936）
  - ADR-0205（已移除，見 git c8fb32936）
  - ADR-0206（已移除，見 git c8fb32936）
  - ../../adr/hourly-financial-aggregate.md#adr-0207
  - ../../adr/hourly-financial-aggregate.md#adr-0208
  - ../../adr/commission-and-reports.md#adr-0209
  - ../../adr/commission-and-reports.md#adr-0210
  - ADR-0211（已移除，見 git c8fb32936）
  - ADR-0212（已移除，見 git c8fb32936）
  - ../../adr/commission-and-reports.md#adr-0213
  - ../../adr/commission-and-reports.md#adr-0214
  - ../../adr/commission-and-reports.md#adr-0430
  - ../../adr/hourly-financial-aggregate.md#adr-0215
  - ../../adr/hourly-financial-aggregate.md#adr-0216
  - ../../adr/hourly-financial-aggregate.md#adr-0217
  - ../../adr/hourly-financial-aggregate.md#adr-0218
  - ../../adr/hourly-financial-aggregate.md#adr-0219
  - ../../adr/hourly-financial-aggregate.md#adr-0220
  - ../../adr/hourly-financial-aggregate.md#adr-0221
  - ../../adr/hourly-financial-aggregate.md#adr-0222
  - order-workspace-contract.md
---

# Configured-zone Commission and UTC Hourly Report Boundary

## Canonical Time Model

- DB event timestamps一律UTC `DATETIME(6)`。
- Supplier／Supply Gateway／Cardholder的Commission Accounting Month，將UTC occurrence依Agent與Gateway owner Supplier已匹配的configured Business Zone offset換算為`YearMonth`；沒有全域`+08:00`fallback。
- 此configured-zone boundary控制rule `effectiveMonth`、`PENDING_NEXT_MONTH` target、各方向eligible monthly volume與query-time Direction Monthly Commission Result；Agent–Supply Gateway Allocation必須Currency與Business Zone同時相同。
- Report canonical period固定為UTC `+00:00` hourly half-open window，且不建立Prefix／Supplier／Superadmin三張actor-specific physical tables。
- Eligible terminal facts先投影到persisted Hourly Financial Aggregate；一般Report讀它做filter／mask／aggregation，Commission Report query則依Commission Accounting Month＋owner＋currency＋direction加總eligible amount後套一次完整月公式。不得逐UTC hour、viewer timezone或current owner zone計算Commission。

## Commission Month Example

同一筆`completed_time = 2026-08-31T16:30:00Z`會依保存的configured offset得到不同Commission月份，但Report hour固定不變：

| Boundary | Interpreted time／bucket | Result |
| --- | --- | --- |
| Configured Business Zone `+07:00` | `2026-08-31 23:30 +07:00` | Commission month `2026-08` |
| Configured Business Zone `+08:00` | `2026-09-01 00:30 +08:00` | Commission month `2026-09` |
| Canonical Report UTC hour | `[2026-08-31T16:00:00Z, 2026-08-31T17:00:00Z)` | Report hour `2026-08-31T16:00:00Z` |

Hourly Financial Aggregate同時保存UTC hour與Commission Accounting Month dimensions；若canonical `±HH:MM` offset使同一UTC hour跨月界，必須依Commission month拆row。Report可以用其他timezone呈現label，但不得改變已依offset snapshot歸屬的Commission month。

## Available-facts Interval Example

查詢`+07:00`的`2026-08` Commission month時，若目前Hourly Financial Aggregate只有`08-15`的100與`08-20`的200，Report先顯示300。`08-01..08-14`沒有facts或某source尚未追上都不阻擋Report、不補zero facts，也不標示partial。之後`08-25`的50完成投影，下一次相同query顯示350。月份仍依各fact保存的configured offset與canonical occurrence判定；計算不需要owner activation timestamp。

## Accepted Boundary

- Business Zone是canonical fixed offset `±HH:MM`，有效範圍 `-14:00..+14:00`，不接受 IANA region ID、`Z` 或省略格式，也沒有DST。
- Agent Create 仍明確提交 canonical `businessUtcOffset`；Supplier Create 接受 optional 固定 `timezone` 或舊 `businessUtcOffset`，皆未傳或 null 時僅由 application service 預設 `+07:00`。非 null 先 trim 並驗證，空白或無效值不 fallback；雙欄各自驗證且不同值拒絕。DB 與 snapshots 沒有 offset default，六個 business offset／snapshot 欄位統一 `CHAR(6)`。Agent offset建立後immutable，是 House daily boundary 與 Agent 營業日的 time authority；Agent–Gateway effective binding 不再要求兩方 offset 相同（ADR-0449（此參考僅供內部環境使用，公開版本未提供））。Supplier 的較晚 mutation reinstatement 已由 ADR-0402（此參考僅供內部環境使用，公開版本未提供） creation-only 目標取代；任何 actor 不可 Update offset，歷史 counts／facts／snapshots 不搬移。階段 A 只有 schema COMMENT／靜態交付，應用 guard 尚未切換。
- Deposit與Withdrawal分開累計，但同一effective Agent–Supply Gateway chain共用已匹配的Commission month offset。
- 第一筆Supply Order成功claim／routing先驗證Agent與Gateway Currency相同（Agent與Gateway owner Supplier的Business UTC Offset可以不同），再保存收款方offset快照（Supplier；HOUSE為House Card所屬Agent）與Agent offset快照，Commission month使用收款方快照（ADR-0449（此參考僅供內部環境使用，公開版本未提供））；Canonical fact需保存UTC occurrence、Commission Accounting Month、Currency、direction、owner chain、該routing offset snapshot與rule revision／inputs identity。Month仍以terminal eligible occurrence換算，不使用claim time當month occurrence。
- 一般Report與Commission Report共同讀取authoritative Hourly Financial Aggregate。它保存eligible inputs，不保存hourly Commission result；Commission Report先彙總整月eligible amount，才套threshold／base fee／rate一次。
- Hourly Financial Aggregate的`eligible_amount`固定使用`DECIMAL(38,10)`；source fact與受控rebuild只做exact decimal addition，不在hour boundary套Currency display rounding。無法無損表示時fail closed，不clamp／truncate／round。
- Supply Channel 結算的 eligible fact 是 Supplier-only owner（`owner_type = SUPPLY_CHANNEL`）：只保存 Supplier 與 Supply Channel，Gateway／Cardholder 為 NULL、不捏造；Commission month 依 Order 首次 assignment 保存的 Supplier Business Zone 快照換算。Hourly Financial Aggregate 以 null-safe owner grain（`owner_grain_key`）分開 CH 列與各 Supply Channel 列；Commission Report 的 Supplier 層加總兩者，Gateway／Cardholder 層只讀 CH 列，CH 結果不變（#512、ADR-0431（此參考僅供內部環境使用，公開版本未提供））。
- UTC hour boundary只決定bucket，不是acceptance cutoff。Late-arriving且此前未投影的全新eligible fact依canonical source identity恰好一次更新原hour row；duplicate delivery不得再次增加`eligible_amount`或`fact_count`，arrival time不得改分桶。
- 已投影fact的amount correction保留原fact，追加source-linked immutable signed delta，並沿用原fact的canonical occurrence與offset snapshot恰好一次修正原UTC hour／Commission month。原amount 100更正為90時原bucket exact減10；correction arrival time不建立新bucket，後續Commission Report query反映latest value。
- 每筆成功claim的projection work以per-fact transaction共同commit fact／correction identity、aggregate delta、applied identity與queue `PROCESSED`。互相獨立且signed delta已確定的facts可不依queue ID或claim time套用；final total由exact addition與exactly-once application保證，cursor仍不得越過pending／failed gap。
- Source transaction commit durable queue row後，best-effort targeted attempt與Scheduler bounded recovery共用同一per-fact projector。Recovery每輪最多admit 50 IDs並使用固定30秒soft execution budget，但candidate仍逐筆commit；budget從第一次candidate query前以monotonic elapsed time起算，active per-fact／failure-record transaction不hard-cancel；batch commit、`SKIP LOCKED`與claim-token／lease不作baseline，只有G6具體證據成立後才逐項評估。
- Commission Report使用available-facts semantics：target interval內目前已接受facts都參與計算；資料缺漏、尚未抵達或coverage未知只是不計入，不阻擋Report、不標partial，也不合成zero fact。Later fact／correction完成投影後由下一次query反映，不需要activation boundary。Pt Snapshot（#407）另回僅供參考的`dataUpdatedThrough`（篩選結果內最新aggregate `utc_hour`的結束時刻，以查看者offset呈現）與每列`inProgress`（查看者月份尚未結束），兩者不形成completeness gate（ADR-0430（此參考僅供內部環境使用，公開版本未提供））；volume／count依查看者offset以`utc_hour`起點歸月，PT仍依aggregate的Commission Accounting Month計算，不因查看者時區改變。
- Per-source／partition contiguous cursor只描述projector progress／resume／operations，不是Report completeness gate；normal historical projection不等待所有source full-scope coverage。Controlled rebuild仍從immutable original facts與accepted corrections在隔離shadow result重建明確bounded scope，但只用於原子替換已上線scope；validation失敗保留舊live scope，Report query只看完整舊版或完整新版。
- 每個owner＋currency＋direction整月只在Direction Monthly Commission Result round一次。Commission Report query即時計算`DECIMAL(38,16)` exact與`DECIMAL(38,10)` final representable values，Final使用`Currency.decimalNumber`／`HALF_UP`，scale只接受`0..10`且使用後immutable；result不保存成pair、snapshot或Current Result。只有invalid Currency metadata、numeric overflow或missing applicable PT rule等真正計算錯誤才fail closed，不得回commission 0或previous cached value；任何requested target有這類錯誤時整份Report不回傳Commission amounts、partial rows、summaries或totals。Spay4 backend不管理paid／unpaid、settlement、outstanding、recovery或disposition。
- Historical retry／recovery／re-dispatch／rebuild必須重用first successful claim／routing保存的immutable offset snapshot，不得讀current master重新分月。

## Remaining Report／Reconciliation Decisions

原列於本段的未決項已依下列來源定案；本期只剩三組列為「本期不做」，各附觸發條件，不在本期建立對應實作。

已定案（附來源）：

- Hourly Financial Aggregate exact columns／unique key、canonical source／correction identity columns、attempt technical primary key／columns／index、per-source／partition watermark（cursor type／state placement）：`sql/V4/ddl.sql` 的 `supply_eligible_fact`、`supply_eligible_fact_correction`、`supply_eligible_fact_projection_queue`、`supply_eligible_fact_projection_failure_attempt`、`supply_aggregate_projection_watermark` 與 `supply_financial_hourly_aggregate`（#406）。
- Producer 與 after-commit projection signal：#406；Supply Channel Supplier-only producer：#512。
- Lock／conditional SQL、failure-attempt 與 queue retry persistence：#426。
- Operator endpoint／role／error：#457。
- Hourly publication 的 overlap／non-reentry 與 hourly scope shadow storage／atomic replacement：#427、ADR-0389（此參考僅供內部環境使用，公開版本未提供）。
- Queue 完成紀錄與 failure attempt 的 retention：永久保留，不做清理或 compaction（ADR-0438（此參考僅供內部環境使用，公開版本未提供））。
- R1 report fields、API、actors、scope／masking／authority，以及 Pt Snapshot 的 table／API／VO 與 export contract：#407 專責契約（[SUPPLY_COMMISSION_REPORT](backoffice-menu-api-reference.md#v2-clientoperation-map)）。Deposit／Withdrawal 營運工作台的 list、detail、CSV、Action、viewer display offset 與日期 filter 已由 [Order Workspace Contract](order-workspace-contract.md) 定義，且不得演變成新的 summary report。
- Reconciliation：排除的是 Payment Account `reconciliation_run`／`reconciliation_item`（ADR-0380（此參考僅供內部環境使用，公開版本未提供））；既有 Hourly Report Reconciliation（每小時 shadow rebuild 後原子發布，ADR-0389（此參考僅供內部環境使用，公開版本未提供））保留。
- Commission Report HTTP／error fields 與 historical display：真正計算錯誤時整份 HTTP 409／40054、available-facts、`HALF_UP` 每月 round 一次（ADR-0430（此參考僅供內部環境使用，公開版本未提供））；ADR-0209 已排除 result／payment／recovery schema，ADR-0210 經 ADR-0213 縮限為真正計算錯誤的 Report-level all-or-nothing failure，ADR-0213 固定 available-facts 與 amounts-only response semantics 並 supersede ADR-0211／0212，ADR-0214 固定 per-target latest committed reads 且不保證 request-wide snapshot，歷史月份因此顯示 query 當下的 latest value。

本期不做：

1. **Correction 執行／ordering 與 cursor 推進。** `supply_eligible_fact_correction` 與 `supply_aggregate_projection_watermark` 只有 schema，沒有 writer：projector 不讀 watermark、不推進 cursor，hourly shadow rebuild 只重建 `PROCESSED` facts（`spay4-bo/src/main/java/com/sit/spay4/supply/service/impl/SupplyHourlyScopePublisherImpl.java` 的 `publish`／`validatedShadow`），上方 Accepted Boundary 的 correction signed delta 與 contiguous cursor 屬未實作範圍。開單觸發條件：出現需更正已投影 fact 金額的業務來源，或 operator 需要查 projector 進度／從 cursor 續跑。
2. **歷史 catch-up、coverage／checksum、並行 catch-up 與 G6 最佳化。** Controlled rebuild 只以 hourly scope 執行（ADR-0389）；超出單一 hour 的 bounded historical rebuild、coverage／checksum fields、並行 catch-up，以及 `SKIP LOCKED`／claim-token／lease 等 G6 最佳化都不建立。開單觸發條件：需回補超過 hourly reconciliation 範圍的歷史 scope（新 producer 上線補歷史 facts 或資料修復），或 G6 量測證據顯示 bounded recovery（每 fire 50 IDs／30 秒）追不上 backlog。
3. **Commission Report query plan、timeout、cache／materialized fallback。** 現行每次 query 即時彙總，不設 cache 或 materialized fallback。開單觸發條件：Commission Report／Pt Snapshot 的實測查詢時間或 DB 負載超出營運可接受範圍，或 requested target 數量成長使 page／export 逾時。

Shared Hourly Financial Aggregate topology、`eligible_amount DECIMAL(38,10)` no-hourly-rounding、late-arriving new fact exactly-once inclusion、existing eligible fact immutable correction delta回投原canonical bucket、controlled rebuild、per-source／partition projector cursor、per-fact atomic application、after-commit targeted attempt＋Scheduler bounded recovery、same-transaction claim／apply、rollback後separate failure attempt、Java-only 5-total-attempt retry schedule、explicit deterministic early-park classification、separate immutable attempt table＋queue current state、queue-local committed failure sequence、retry exhaustion park＋audited operator requeue與available-facts query-time latest Commission已選定；ADR-0209排除result／payment／recovery persistence，ADR-0210經ADR-0213縮限為真正計算錯誤的all-or-nothing failure，ADR-0213固定normal history不等full-scope coverage、Commission不需要activation boundary，且business response只回amounts或真正calculation failure；ADR-0214固定各target可讀取實際query時的latest committed aggregate，同一request不保證單一point-in-time snapshot且不強迫N+1 query；ADR-0215固定每筆identity／delta／applied evidence／queue completion共同commit、獨立delta不保證application order且cursor不得skip gap；ADR-0216固定兩條trigger共用projector、bounded candidate ID fetch／execution budget不形成batch commit，`SKIP LOCKED`／claim-token／lease只由G6 evidence gate；ADR-0217固定同一transaction取得ownership／status guard並apply，failure metadata不得標記applied或推進cursor；ADR-0218固定達門檻後park為`NEEDS_ATTENTION`，audited BO operator command只requeue同一row並等待Scheduler，保留history、再失敗立即re-park，SQL只作break-glass；ADR-0219固定initial execution包含在5 total attempts內，只有guard winner實際進入projector才消耗attempt，failures 1／2／3／4後分別等待1／5／15／60分鐘，failure 5直接park且沒有180-minute fallback；operator requeue不重設exhausted history，只提供一次額外執行機會；ADR-0220固定retry values由projector-owned Java domain policy提供，不新增Global／tenant／property／environment runtime override；ADR-0221固定三個explicit deterministic domain categories可在attempt 1至4直接park且不排next time，deadlock／timeout／temporary infrastructure、mutable reference暫時缺少、unexpected runtime exception、unknown code與classifier failure仍retry，classification不得解析exception／SQL message；ADR-0222固定attempt insert與queue current-state update同transaction commit，Scheduler不join history、operator不修改attempt rows且不使用queue JSON history；ADR-0223固定`queue identity + committed failure sequence` queue-local unique ordinal，未commit不占用durable sequence且不得使用未受guard保護的`MAX + 1`；ADR-0224固定Scheduler bounded recovery每1分鐘於UTC整分鐘第0秒觸發，`nextRetryTime`到期後可能再等不到60秒，HTTP delivery retry不增加projector attempt count；ADR-0225固定automatic-selectable due rows依logical eligibility time ASC、queue identity ASC admit，queue identity只作tie-break且order不保證targeted／application／completion順序；ADR-0226固定每個logical fire最多admit 50個candidate IDs，no-op／loser不退回slot且same-fire delivery retry不取得新budget；ADR-0227固定從第一次candidate query前起算的30秒soft execution budget，active per-fact／failure-record transaction不hard-cancel。DDL／API已由#406、#426、#427、#457建立；測試至少覆蓋configured offset兩側月界、同UTC hour跨Commission month時拆row、Prefix／Supplier mismatch fail-closed、offset snapshot retry一致性、requested interval只有08-15與08-20 facts時只加總現有資料、later 08-25 fact在下一次query加入、missing interval不阻擋Report、response不含freshness／completeness／partial／projector progress、UTC hourly half-open boundary、scale-10 exact addition／overflow fail-closed、late first-delivery updates original bucket、duplicate no-op、source commit後targeted success、targeted未執行後下一個UTC整分Scheduler recovery、UTC `10:02:20`到期row不早於`10:03:00` fire取得、HTTP delivery retry不增加projector attempt count、initial／retry／operator-requeue eligibility來源、earliest-time-first與same-time queue identity tie-break、低ID較晚due不得插隊、candidate query無nullable OR／indexed-column `COALESCE`／function、candidate order不保證application order、兩條trigger競爭single winner且loser不計attempt、fetch-only candidate不計attempt、每fire最多admit 50 IDs、no-op／loser不退回slot、same-fire delivery retry不取得新budget、budget在candidate query前起算、query耗盡budget時零筆開始、elapsed等於30秒不開始下一筆、active transaction跨deadline仍完成且仍逐筆commit、同transaction ownership／status guard與四項atomic write共同rollback、attempt insert與queue current-state update共同commit／rollback、queue-local sequence從1遞增且duplicate ordinal被拒絕、failure-record rollback不消耗durable sequence、Scheduler candidate query不join history、operator requeue不修改attempt rows、failure-record transaction失敗仍可重試、failures 1／2／3／4各自排定1／5／15／60分鐘、failure 5 park且不排180分鐘、Java-only policy且沒有runtime fallback、三個allow-list category各自在attempt 1後直接park且`nextRetryTime = null`、deadlock／timeout／temporary infrastructure／unknown／classifier failure仍retry、exception message變更不影響classification、diagnostic不含secret／raw payload、parked row不自動選取、operator requeue保留exhausted history且只增加一次執行機會、不inline投影、Scheduler取得due row、額外嘗試失敗append新row並立即re-park、failure metadata不標記applied、commit後crash replay no-op、controlled rebuild中途失敗保持舊live scope、normal historical projection可逐步供Report使用、每次query由latest hourly inputs彙總後只套一次target公式、並行projection commit不鎖住Report且後續target／query可見latest committed state、rebuild後歷史月份顯示latest value、invalid metadata／overflow／missing rule不回0或stale result，以及100個requested targets中1個真正計算錯誤時不回傳其餘99個amounts。Correction與cursor相關項（既有fact 100以linked delta -10修正原bucket為90且arrival period不變、correction後歷史月份顯示latest value、cursor gap不阻擋Report、parked row與failure metadata不推進cursor、獨立gap後fact先完成但cursor不skip、gap補齊後cursor前進）屬上方「本期不做」第1組的未實作範圍，不列入本期測試。
