1.4.0: show-roster-sync-failure — the HR roster sync status on /admin/settings shows why the latest run failed
CI / build (push) Successful in 11m11s
CI / build (push) Successful in 11m11s
- The failure is shown after 「失敗」 as a Chinese explanation of the stage and reason, e.g. 「2026/11/01 名冊查詢:HTTP 400(日期超出 HR 可查範圍或參數錯誤)」. It comes only from the recorded codes (`rosterSyncFailureText`, src/lib/hr-sync-failure.ts); no HR response content, token or personal data. Unknown codes are shown as is; old rows without a stage show only 「失敗」. - hr_roster_syncs gains failure_date (migration 0026): the 1st-of-month roster / organization queries (this month and last month share one stage) record which date failed. HrSyncError carries an optional date. - Sync behavior is unchanged (user decision 2026-11-01: the error must be known before the data can be trusted). - E2E: insertRosterSync takes stage / reason / date; the headcount adjustment test uses 9 (the demo department's computed count for last month is already 3, which was refused as 人數未變更). - CLAUDE.md: roster sync failure record and display. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -105,7 +105,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
|
||||
- Creates or updates snapshots with `syncSnapshotsFromHr(tx, audit, cardMonth, rosterOnBaseDate, tree)`: ACTIVE on the base date, unit resolved to the department through that day's tree (group members count toward their 部). Locked or manually adjusted snapshots are never overwritten. Departments without a code in that roster are skipped. The earlier card month is processed first.
|
||||
- It also stores the 1-day member list in `headcount_snapshot_members` (same conditions as the count; a DB trigger rejects writes for a locked snapshot): `counted` (== the count; every ACTIVE person), `excluded` (old lists only: ACTIVE, not full-time; shown without a reason), `suspended`, `offboarded` (only `leaveDate` ≥ the 1st of the card month). Non-ACTIVE people without a unit fall back to last month's list. A list-only change records `headcount.snapshot_members_updated` (counts only, no names). `listMonthSnapshots` returns `members` (local snapshots list `departmentMembersAt` live; an HR snapshot without a list is null → 「此快照沒有名單紀錄」).
|
||||
- Employment status step (`syncEmploymentStatus`, `src/server/hr-sync/employment-status.ts`, stage `employment_status`, after snapshots, current roster): stores `users.hr_status` / `hr_status_since` for existing accounts. SUSPENDED / OFFBOARDED + active → `deactivateUser(…, hrDeactivated=true)` (sessions deleted, department history null from `suspendedSince` / `leaveDate`, clamped to [last history date, today]) and `account.hr_deactivated`. ACTIVE + inactive + `hr_deactivated` → `activateUser` (original department from today) and `account.hr_reactivated`. Manually deactivated accounts are never re-enabled; `setAccountActive` refuses to enable an account whose HR status is SUSPENDED / OFFBOARDED (`HR_INACTIVE_ACCOUNT_ERROR`). `/admin/accounts` shows HR 狀態 and 「由 HR 停用」.
|
||||
- Each step is its own transaction. A failure stops the run and is recorded in the row (stage + reason). Success writes one `hr_sync.roster_synced` summary audit, not one per person.
|
||||
- Each step is its own transaction. A failure stops the run (finished steps are kept) and is recorded in the row (stage + reason, plus `failure_date` for the 1st-of-month roster / tree queries, which share one stage). `/admin/settings` (headcount tab) shows it via `rosterSyncFailureText` (`src/lib/hr-sync-failure.ts`; codes only, never HR response content). Failures write no audit. Success writes one `hr_sync.roster_synced` summary audit, not one per person.
|
||||
- Per-person full-time status is never shown on any page (and is currently not used for headcounts).
|
||||
- HR wins:
|
||||
- HR name over the ID token name.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-01
|
||||
@@ -0,0 +1,41 @@
|
||||
## Context
|
||||
|
||||
- 名冊同步(`runRosterSyncIfDue` → `run`,`src/server/hr-sync/roster.ts`)一次送出 6 個查詢:現況名冊、現況組織結構,以及本月 1 日、上月 1 日的名冊與組織結構。查詢失敗以 `HrSyncError(stage, reason)` 表示(`errors.ts`),最後寫進 `hr_roster_syncs.failure_stage` / `failure_reason`;寫入步驟的例外由 `step()` 轉成 `write_failed`,執行超過 10 分鐘被視為中斷時寫 `run` / `abandoned`(`claimRosterSync`)。
|
||||
- `stage` 有 `roster_on_date` / `organizations_on_date`,但兩個日期共用同一個 stage,紀錄分不出是本月 1 日還是上月 1 日查不到。
|
||||
- 設定頁(`admin/settings/page.tsx`,人數快照分頁)以 `latestRosterSyncs(db)` 取最近一次與最近成功,只顯示 `ROSTER_SYNC_LABEL[status]`。
|
||||
- `reason` 的可能值:`http_<狀態碼>`、`timeout`、`invalid_response`、`network`、`exchange_failed`、`write_failed`、`abandoned`(token 交換失敗不會進名冊同步:名冊同步只在登入取得 token 後執行)。
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- 失敗時在現有狀態行內顯示「哪一步、什麼原因、(哪一天)」,管理者據此判斷要等 HR 重建、按重新同步,或找人看 log。
|
||||
- 說明文字集中在一個純函式,未知的階段或原因也有可讀的退路(顯示原始代碼)。
|
||||
|
||||
**Non-Goals:**
|
||||
- 不改同步流程、不做部分成功、不重試(使用者決定 2026-11-01)。
|
||||
- 不保存或顯示 HR 錯誤回應內容(例如 400 回應附的 `coverageFrom` / `coverageTo`):hr-sync 規定紀錄 MUST NOT 含 HR 回應內容,要放寬需另開 change。
|
||||
- 不為名冊同步失敗新增操作紀錄或通知。
|
||||
- 登入同步的 `hr_sync.failed` 操作紀錄顯示方式不變。
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **查詢日期另存欄位 `hr_roster_syncs.failure_date`(`YYYY-MM-DD`,可為空)**,`HrSyncError` 加一個選填的 `date`。
|
||||
- 替代方案:把日期編進 `reason`(`http_400@2026-11-01`)或拆出 `roster_on_month_start` / `roster_on_prev_month_start` 等 stage。前者讓 reason 不再是固定代碼,後者的 stage 名稱依「今天」而變,事後看紀錄反而難懂。另存欄位最直白,舊紀錄自然為空。
|
||||
- 只有 `roster_on_date` / `organizations_on_date` 會帶日期;`run()` 的 `onFirst(i)` 已知道 `months[i]`,在丟出錯誤時帶上 `${months[i]}-01`。
|
||||
2. **說明文字放在 `src/lib/hr-sync-failure.ts`:`rosterSyncFailureText({ stage, reason, date })`**,回傳例如「2026/11/01 名冊查詢:HTTP 400(日期超出 HR 可查範圍或參數錯誤)」。
|
||||
- 放 `src/lib`(不 import `@/server/*`)而非 server:純字串對應,可單元測試,也不會讓 `src/app` 多 import `@/server/hr-sync/*`(設定頁已被允許 import,但不必擴大)。stage 型別在 lib 以字串接收,避免 lib 依賴 server 的型別。
|
||||
- 階段說明:現況名冊查詢、現況組織結構查詢、`<日期>` 名冊查詢、`<日期>` 組織結構查詢、部門同步、正職身分寫入、人數快照寫入、在職狀態寫入、執行中斷(`run`)。
|
||||
- 原因說明:`http_400` 日期超出 HR 可查範圍或參數錯誤;`http_401` / `http_403` 權杖無效或沒有權限;`http_404` 查無資料;`http_503` HR 歷史資料尚未建置;其他 `http_N` 只顯示「HTTP N」;`timeout` 逾時(30 秒內未完成);`network` 連線失敗;`invalid_response` 回應格式不符;`write_failed` 寫入本系統失敗;`abandoned` 超過 10 分鐘未完成,視為中斷。400、503 的說明依 HR Sync API 手冊(`mason/skills/hr-sync/references/api-contract.md`「日期與時間」「錯誤」)。
|
||||
- 未知代碼原樣顯示(例如「步驟 foo:bar」),不丟錯。
|
||||
3. **顯示位置**:沿用 `roster-sync-status` 那一行,「失敗」後面接「(<說明>)」,再接原本的「;最近成功 …」。不新增區塊或 Alert,避免設定頁更擠;`data-testid="roster-sync-failure"` 包住說明供 e2e 檢查。
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [說明是推測而非 HR 回傳的確切原因,例如 400 也可能是參數錯誤] → 文字寫「日期超出 HR 可查範圍**或**參數錯誤」,不下定論;確切原因仍以 log 為準。
|
||||
- [手冊改版、狀態碼語意改變] → 說明集中在一個檔案,有單元測試列出每個代碼,改版時一起更新。
|
||||
- [新增欄位需要 migration] → 只新增可為空欄位,啟動時自動 migrate,無資料轉換。
|
||||
|
||||
## Migration Plan
|
||||
|
||||
- `npm run db:generate` 產生新增 `failure_date` 的 migration 並 commit;部署後啟動時自動套用。
|
||||
- 回滾:舊版程式不讀這個欄位,可直接回到前一版映像;欄位留著無害。
|
||||
@@ -0,0 +1,29 @@
|
||||
## Why
|
||||
|
||||
2026/11/01 19:15 的 HR 名冊同步失敗,後台設定頁只顯示「失敗」與最近成功時間。失敗階段與原因其實已寫在 `hr_roster_syncs`(`failure_stage`、`failure_reason`),但畫面不顯示,名冊同步失敗也不寫操作紀錄,管理者只能請人翻伺服器 log 才知道原因。使用者決定(2026-11-01):同步行為不改,1 日名冊查不到仍整次失敗,因為要先知道錯誤才能保證快照資料正確;但失敗原因要直接在後台看得到。
|
||||
|
||||
## What Changes
|
||||
|
||||
- 後台設定頁人數快照分頁的「HR 名冊同步」狀態,在最近一次同步失敗時顯示**失敗階段與原因的中文說明**,例如「失敗(2026/11/01 名冊查詢:HTTP 400,日期超出 HR 可查範圍或參數錯誤)」。
|
||||
- 名冊同步失敗在查詢某一天的名冊或組織結構時(1 日名冊、1 日組織結構),紀錄 SHALL 同時保存**查詢的日期**,畫面上顯示是哪一天查不到(本月 1 日與上月 1 日兩次查詢分得出來)。
|
||||
- 失敗說明只來自本系統的階段與原因代碼(HTTP 狀態碼、逾時、回應格式不符、連線失敗、寫入失敗、中斷),MUST NOT 顯示 HR 回應內容、token 或任何個資。
|
||||
- 不改名冊同步本身的行為:哪一步失敗就整次失敗、下一位登入者重試,都照舊。
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
(無)
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `headcount-snapshot`:「快照檢視」的名冊同步狀態在失敗時顯示失敗階段、原因與查詢日期。
|
||||
- `hr-sync`:「每日名冊同步」的執行紀錄另保存失敗查詢的日期(只限查詢某一天的名冊與組織結構時)。
|
||||
|
||||
## Impact
|
||||
|
||||
- 資料庫:`hr_roster_syncs` 新增可為空的 `failure_date` 欄位(migration);既有紀錄為空,照常顯示階段與原因。
|
||||
- 程式:`src/server/hr-sync/errors.ts`(`HrSyncError` 可帶查詢日期)、`src/server/hr-sync/roster.ts`(1 日查詢失敗時帶日期、寫入 `failure_date`)、新增 `src/lib/hr-sync-failure.ts`(階段與原因的中文說明,純函式)、`src/app/(app)/admin/settings/page.tsx`(顯示)。
|
||||
- 測試:`roster.test.ts`(失敗時記錄日期)、說明文字的單元測試、e2e `settings.spec.ts`(失敗紀錄顯示說明;`insertRosterSync` 可帶階段與原因)。
|
||||
- 文件:CLAUDE.md 的 HR Sync 段落、`/help` 管理端說明(若有提到名冊同步狀態)。
|
||||
- 權限不變:設定頁人數快照分頁本來就只有管理者與系統管理員能看。
|
||||
@@ -0,0 +1,24 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: 快照檢視
|
||||
管理者 SHALL 可在後台設定頁依月份檢視所有部門的快照人數、部門類型、算出的月上限、鎖定狀態、來源(HR 名冊或系統計算)與調整紀錄,並看到最近一次名冊同步的時間與結果;最近一次失敗時 SHALL 同時顯示失敗的階段與原因(中文說明;查詢某一天的名冊或組織結構失敗時含該日期),說明 MUST 只由本系統記錄的階段與原因代碼產生,MUST NOT 含 HR 回應內容、token 或個資。其他角色 MUST NOT 修改快照。
|
||||
|
||||
#### Scenario: 依月份檢視
|
||||
- **WHEN** 管理者在後台設定頁選擇 2026/10
|
||||
- **THEN** 列出每個部門的快照人數、類型、月上限、是否鎖定與來源,可展開查看調整紀錄
|
||||
|
||||
#### Scenario: 名冊同步失敗
|
||||
- **WHEN** 今天的名冊同步失敗,管理者開啟後台設定頁
|
||||
- **THEN** 快照區塊顯示最近一次名冊同步的時間與「失敗」、失敗的階段與原因,以及最近一次成功的時間
|
||||
|
||||
#### Scenario: 查詢某一天的名冊被 HR 拒絕
|
||||
- **WHEN** 2026/11/01 的名冊同步查詢 2026/11/01 的名冊時 HR Sync 回應 HTTP 400,管理者開啟後台設定頁
|
||||
- **THEN** 快照區塊顯示失敗發生在 2026/11/01 名冊查詢、原因為 HTTP 400,並說明 400 代表日期超出 HR 可查範圍或參數錯誤
|
||||
|
||||
#### Scenario: 同步逾時
|
||||
- **WHEN** 最近一次名冊同步因 HR Sync 逾時失敗
|
||||
- **THEN** 快照區塊顯示失敗原因為逾時,不顯示查詢日期以外的任何 HR 資料
|
||||
|
||||
#### Scenario: 舊的失敗紀錄沒有日期
|
||||
- **WHEN** 最近一次失敗的紀錄建立於本功能上線前,沒有保存查詢日期
|
||||
- **THEN** 快照區塊照常顯示失敗的階段與原因,不顯示日期
|
||||
@@ -0,0 +1,20 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: 每日名冊同步
|
||||
HR Sync 已設定時,每天(Asia/Taipei)第一次成功完成公司帳號登入後,系統 SHALL 以該次登入換得的 HR Sync token 在背景同步全公司名冊與組織結構:依序同步部門與主管(見「HR 部門對應與自動建立」「由 HR 組織結構同步部門主管」「清理組級部門」)、正職身分與人數快照(見各需求)。名冊同步 MUST NOT 延遲或影響登入結果;同一天已有一次成功的名冊同步時 MUST NOT 再執行,同一時間 MUST 只有一個名冊同步在執行。名冊同步失敗時,下一位登入者 SHALL 重試。每次執行 SHALL 留存紀錄(開始與結束時間、觸發的登入者員工編號、結果、處理筆數、失敗階段與原因;查詢某一天的名冊或組織結構失敗時另含該查詢日期),MUST NOT 包含 token 或 HR 回應內容。HR Sync token MUST 只存在伺服器記憶體中,名冊同步結束即丟棄。開發登入 MUST NOT 觸發名冊同步。
|
||||
|
||||
#### Scenario: 當天第一位登入者觸發
|
||||
- **WHEN** 2026/11/03 第一位員工以公司帳號登入
|
||||
- **THEN** 該員工照常進入首頁,系統在背景完成一次名冊同步並留存成功紀錄
|
||||
|
||||
#### Scenario: 當天已同步
|
||||
- **WHEN** 2026/11/03 已有一次成功的名冊同步,又有員工登入
|
||||
- **THEN** 系統不再同步名冊
|
||||
|
||||
#### Scenario: 同步失敗後重試
|
||||
- **WHEN** 2026/11/03 第一次名冊同步因 HR Sync 逾時失敗,之後另一位員工登入
|
||||
- **THEN** 系統再試一次名冊同步,兩次執行都有紀錄
|
||||
|
||||
#### Scenario: 某一天的名冊查詢失敗
|
||||
- **WHEN** 2026/11/01 的名冊同步查詢 2026/11/01 名冊時 HR Sync 回應 HTTP 400
|
||||
- **THEN** 該次名冊同步記為失敗,紀錄的失敗階段為該日名冊查詢、原因為 HTTP 400、查詢日期為 2026/11/01;之前已完成的步驟保留(部門與主管、正職身分、以 2026/10/01 名冊計算的 2026/09 快照),2026/10 快照與帳號在職狀態不更新,下一位登入者重試
|
||||
@@ -0,0 +1,16 @@
|
||||
# Tasks
|
||||
|
||||
## 1. 記錄失敗的查詢日期
|
||||
|
||||
- [x] 1.1 `hr_roster_syncs` 新增可為空的 `failure_date`(`src/server/db/schema/hr-sync.ts`),`npm run db:generate` 產生 migration 並 commit;`createTestDatabase()` 的整合測試能讀寫該欄位。
|
||||
- [x] 1.2 `HrSyncError` 加選填 `date`(`errors.ts`);`run()` 的 `onFirst(i)` 對 `roster_on_date` / `organizations_on_date` 帶上 `${months[i]}-01`;結束時寫入 `failureDate`。`roster.test.ts`:本月 1 日名冊回 400 → 紀錄 stage `roster_on_date`、reason `http_400`、`failure_date` 為本月 1 日;上月 1 日組織結構失敗 → 日期為上月 1 日;現況名冊失敗與寫入失敗 → `failure_date` 為空。既有失敗測試不變。
|
||||
|
||||
## 2. 失敗說明與顯示
|
||||
|
||||
- [x] 2.1 新增 `src/lib/hr-sync-failure.ts`:`rosterSyncFailureText({ stage, reason, date })`,依 design 決策 2 的階段與原因說明組字串,未知代碼原樣顯示。單元測試涵蓋每個階段、`http_400`/`401`/`403`/`404`/`503`/其他狀態碼、`timeout`、`network`、`invalid_response`、`write_failed`、`abandoned`,以及有日期與沒有日期。
|
||||
- [x] 2.2 設定頁人數快照分頁(`admin/settings/page.tsx`):最近一次為失敗時,在「失敗」後顯示「(<說明>)」(`data-testid="roster-sync-failure"`),其餘文字不變。e2e `settings.spec.ts`「人數快照顯示來源與最近一次 HR 名冊同步」:`insertRosterSync` 可帶 stage/reason/date,檢查顯示「2026/MM/01 名冊查詢:HTTP 400」與說明;沒有階段的舊紀錄只顯示「失敗」。
|
||||
- [x] 2.3 CLAUDE.md HR Sync 的 Daily roster sync 段落補上:失敗紀錄含 `failure_date`(只限 1 日查詢),設定頁顯示 `rosterSyncFailureText`;若 `/help` 管理端說明提到名冊同步狀態,一併更新。
|
||||
|
||||
## 3. 驗證
|
||||
|
||||
- [x] 3.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `settings.spec.ts` 與 `visibility.spec.ts` 通過。
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ai-subsidy-system",
|
||||
"version": "1.3.1",
|
||||
"version": "1.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ai-subsidy-system",
|
||||
"version": "1.3.1",
|
||||
"version": "1.4.0",
|
||||
"dependencies": {
|
||||
"@radix-ui/react-dialog": "^1.2.0",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.25",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ai-subsidy-system",
|
||||
"version": "1.3.1",
|
||||
"version": "1.4.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -14,6 +14,7 @@ import { MoneyDisplay } from "@/components/ui/money-display";
|
||||
import { ToneBadge } from "@/components/ui/status-badge";
|
||||
import { DEPARTMENT_TYPE_LABELS } from "@/lib/department-types";
|
||||
import { formatDate, formatDateTime, formatMonth } from "@/lib/format";
|
||||
import { rosterSyncFailureText } from "@/lib/hr-sync-failure";
|
||||
import {
|
||||
ATTACHMENT_FORMAT_LABELS,
|
||||
ROUNDING_LABELS,
|
||||
@@ -303,6 +304,14 @@ async function HeadcountTab({
|
||||
const rows = listMonthSnapshots(db, month, timeZone);
|
||||
const missing = rows.some((r) => r.snapshotId === null);
|
||||
const roster = latestRosterSyncs(db);
|
||||
const failureText =
|
||||
roster.latest?.status === "failed"
|
||||
? rosterSyncFailureText({
|
||||
stage: roster.latest.failureStage,
|
||||
reason: roster.latest.failureReason,
|
||||
date: roster.latest.failureDate,
|
||||
})
|
||||
: null;
|
||||
const resync = rosterResyncStatus(db);
|
||||
|
||||
return (
|
||||
@@ -331,6 +340,7 @@ async function HeadcountTab({
|
||||
<p className="mb-4 text-sm text-muted" data-testid="roster-sync-status">
|
||||
HR 名冊同步:最近一次 {formatDateTime(roster.latest.startedAt, timeZone)}{" "}
|
||||
{ROSTER_SYNC_LABEL[roster.latest.status]}
|
||||
{failureText && <span data-testid="roster-sync-failure">({failureText})</span>}
|
||||
{roster.latest.status !== "succeeded" &&
|
||||
`;最近成功 ${
|
||||
roster.lastSuccess ? formatDateTime(roster.lastSuccess.startedAt, timeZone) : "尚無"
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { rosterSyncFailureText } from "./hr-sync-failure";
|
||||
|
||||
const text = (stage: string | null, reason: string | null, date?: string | null) =>
|
||||
rosterSyncFailureText({ stage, reason, date });
|
||||
|
||||
describe("rosterSyncFailureText", () => {
|
||||
it("1 日名冊查詢被拒:日期、階段與 400 的說明", () => {
|
||||
expect(text("roster_on_date", "http_400", "2026-11-01")).toBe(
|
||||
"2026/11/01 名冊查詢:HTTP 400(日期超出 HR 可查範圍或參數錯誤)",
|
||||
);
|
||||
expect(text("organizations_on_date", "http_503", "2026-10-01")).toBe(
|
||||
"2026/10/01 組織結構查詢:HTTP 503(HR 歷史資料尚未建置)",
|
||||
);
|
||||
});
|
||||
|
||||
it("每個階段都有中文名稱", () => {
|
||||
expect(
|
||||
[
|
||||
"roster",
|
||||
"organizations",
|
||||
"roster_on_date",
|
||||
"organizations_on_date",
|
||||
"departments",
|
||||
"employment",
|
||||
"snapshots",
|
||||
"employment_status",
|
||||
"run",
|
||||
].map((stage) => text(stage, "network")),
|
||||
).toEqual([
|
||||
"現況名冊查詢:連線失敗",
|
||||
"現況組織結構查詢:連線失敗",
|
||||
"名冊查詢:連線失敗",
|
||||
"組織結構查詢:連線失敗",
|
||||
"部門同步:連線失敗",
|
||||
"正職身分寫入:連線失敗",
|
||||
"人數快照寫入:連線失敗",
|
||||
"在職狀態寫入:連線失敗",
|
||||
"執行:連線失敗",
|
||||
]);
|
||||
});
|
||||
|
||||
it("HTTP 狀態碼:常見的附說明,其他只顯示代碼", () => {
|
||||
expect(text("roster", "http_401")).toBe("現況名冊查詢:HTTP 401(權杖無效或沒有權限)");
|
||||
expect(text("roster", "http_403")).toBe("現況名冊查詢:HTTP 403(權杖無效或沒有權限)");
|
||||
expect(text("roster", "http_404")).toBe("現況名冊查詢:HTTP 404(查無資料)");
|
||||
expect(text("roster", "http_500")).toBe("現況名冊查詢:HTTP 500");
|
||||
});
|
||||
|
||||
it("其他原因", () => {
|
||||
expect(text("roster", "timeout")).toBe("現況名冊查詢:逾時(30 秒內未完成)");
|
||||
expect(text("roster", "invalid_response")).toBe("現況名冊查詢:回應格式不符");
|
||||
expect(text("snapshots", "write_failed")).toBe("人數快照寫入:寫入本系統失敗");
|
||||
expect(text("run", "abandoned")).toBe("執行:超過 10 分鐘未完成,視為中斷");
|
||||
expect(text("departments", "no_division_level")).toBe(
|
||||
"部門同步:HR 組織結構中沒有層級為「部」的單位",
|
||||
);
|
||||
});
|
||||
|
||||
it("未知的代碼原樣顯示;沒有日期就不顯示日期", () => {
|
||||
expect(text("foo", "bar")).toBe("步驟 foo:bar");
|
||||
expect(text("roster_on_date", "http_400", null)).toBe(
|
||||
"名冊查詢:HTTP 400(日期超出 HR 可查範圍或參數錯誤)",
|
||||
);
|
||||
});
|
||||
|
||||
it("沒有階段與原因(例如執行中或舊紀錄)時沒有說明", () => {
|
||||
expect(text(null, null)).toBeNull();
|
||||
expect(text(null, "timeout")).toBe("逾時(30 秒內未完成)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { formatDate } from "./format";
|
||||
|
||||
/**
|
||||
* 名冊同步失敗的中文說明(show-roster-sync-failure):只由本系統記錄的階段、原因代碼與查詢日期組成,
|
||||
* 不含 HR 回應內容。400、503 的含義依 HR Sync API 手冊(mason skills/hr-sync「日期與時間」「錯誤」)。
|
||||
* 未知的代碼原樣顯示。
|
||||
*/
|
||||
|
||||
const STAGE_LABELS: Record<string, string> = {
|
||||
roster: "現況名冊查詢",
|
||||
organizations: "現況組織結構查詢",
|
||||
roster_on_date: "名冊查詢",
|
||||
organizations_on_date: "組織結構查詢",
|
||||
departments: "部門同步",
|
||||
employment: "正職身分寫入",
|
||||
snapshots: "人數快照寫入",
|
||||
employment_status: "在職狀態寫入",
|
||||
run: "執行",
|
||||
};
|
||||
|
||||
const HTTP_NOTES: Record<string, string> = {
|
||||
"400": "日期超出 HR 可查範圍或參數錯誤",
|
||||
"401": "權杖無效或沒有權限",
|
||||
"403": "權杖無效或沒有權限",
|
||||
"404": "查無資料",
|
||||
"503": "HR 歷史資料尚未建置",
|
||||
};
|
||||
|
||||
const REASON_LABELS: Record<string, string> = {
|
||||
timeout: "逾時(30 秒內未完成)",
|
||||
network: "連線失敗",
|
||||
invalid_response: "回應格式不符",
|
||||
write_failed: "寫入本系統失敗",
|
||||
abandoned: "超過 10 分鐘未完成,視為中斷",
|
||||
no_division_level: "HR 組織結構中沒有層級為「部」的單位",
|
||||
};
|
||||
|
||||
function reasonText(reason: string): string {
|
||||
const http = reason.match(/^http_(\d{3})$/);
|
||||
if (http) {
|
||||
const note = HTTP_NOTES[http[1]];
|
||||
return note ? `HTTP ${http[1]}(${note})` : `HTTP ${http[1]}`;
|
||||
}
|
||||
return REASON_LABELS[reason] ?? reason;
|
||||
}
|
||||
|
||||
/** 例:「2026/11/01 名冊查詢:HTTP 400(日期超出 HR 可查範圍或參數錯誤)」。 */
|
||||
export function rosterSyncFailureText({
|
||||
stage,
|
||||
reason,
|
||||
date,
|
||||
}: {
|
||||
stage: string | null;
|
||||
reason: string | null;
|
||||
date?: string | null;
|
||||
}): string | null {
|
||||
if (!stage && !reason) return null;
|
||||
const stageText = stage ? (STAGE_LABELS[stage] ?? `步驟 ${stage}`) : "";
|
||||
const where = [date ? formatDate(date) : "", stageText].filter(Boolean).join(" ");
|
||||
const why = reason ? reasonText(reason) : "";
|
||||
return where && why ? `${where}:${why}` : where || why;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `hr_roster_syncs` ADD `failure_date` text;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -183,6 +183,13 @@
|
||||
"when": 1793355487357,
|
||||
"tag": "0025_reflective_dagger",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 26,
|
||||
"version": "6",
|
||||
"when": 1793534658268,
|
||||
"tag": "0026_kind_wendigo",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -46,6 +46,8 @@ export const hrRosterSyncs = sqliteTable(
|
||||
snapshotChanges: integer("snapshot_changes"),
|
||||
failureStage: text("failure_stage"),
|
||||
failureReason: text("failure_reason"),
|
||||
/** 失敗的查詢日期 `YYYY-MM-DD`:只有查詢某一天的名冊或組織結構失敗時有值。 */
|
||||
failureDate: text("failure_date"),
|
||||
},
|
||||
(t) => [index("hr_roster_syncs_date_idx").on(t.syncDate, t.id)],
|
||||
);
|
||||
|
||||
@@ -26,17 +26,26 @@ export class HrSyncError extends Error {
|
||||
readonly stage: HrSyncStage,
|
||||
/** `http_<狀態碼>`、`timeout`、`invalid_response`、`network`、`exchange_failed`、`write_failed`。 */
|
||||
readonly reason: string,
|
||||
/** 查詢某一天的資料失敗時的查詢日期 `YYYY-MM-DD`(名冊同步的 1 日名冊與組織結構)。 */
|
||||
readonly date?: string,
|
||||
) {
|
||||
super(`HR 同步失敗(${stage}:${reason})`);
|
||||
super(`HR 同步失敗(${stage}:${reason}${date ? `,${date}` : ""})`);
|
||||
this.name = "HrSyncError";
|
||||
}
|
||||
}
|
||||
|
||||
/** 把任意例外轉成 HrSyncError,不保留原始訊息(可能含上游回應)。 */
|
||||
export function toHrSyncError(stage: HrSyncStage, error: unknown, fallback: string): HrSyncError {
|
||||
if (error instanceof HrSyncError) return error;
|
||||
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
||||
return new HrSyncError(stage, "timeout");
|
||||
export function toHrSyncError(
|
||||
stage: HrSyncStage,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
date?: string,
|
||||
): HrSyncError {
|
||||
if (error instanceof HrSyncError) {
|
||||
return date && !error.date ? new HrSyncError(error.stage, error.reason, date) : error;
|
||||
}
|
||||
return new HrSyncError(stage, fallback);
|
||||
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
||||
return new HrSyncError(stage, "timeout", date);
|
||||
}
|
||||
return new HrSyncError(stage, fallback, date);
|
||||
}
|
||||
|
||||
@@ -217,6 +217,52 @@ describe("名冊同步", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("失敗紀錄的查詢日期", () => {
|
||||
it("本月 1 日名冊回 400:紀錄階段、原因與查詢日期(本月 1 日)", async () => {
|
||||
const outcome = await runRosterSyncIfDue(
|
||||
t.db,
|
||||
source({ "2026-11-01": new HrSyncError("roster_on_date", "http_400") }).hr,
|
||||
options(),
|
||||
);
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
failure: { stage: "roster_on_date", reason: "http_400", date: "2026-11-01" },
|
||||
});
|
||||
expect(syncs()[0]).toMatchObject({
|
||||
status: "failed",
|
||||
failureStage: "roster_on_date",
|
||||
failureReason: "http_400",
|
||||
failureDate: "2026-11-01",
|
||||
});
|
||||
});
|
||||
|
||||
it("上月 1 日組織結構逾時:查詢日期為上月 1 日", async () => {
|
||||
const timeout = Object.assign(new Error("timed out"), { name: "TimeoutError" });
|
||||
await runRosterSyncIfDue(t.db, source({ "tree:2026-10-01": timeout }).hr, options());
|
||||
expect(syncs()[0]).toMatchObject({
|
||||
failureStage: "organizations_on_date",
|
||||
failureReason: "timeout",
|
||||
failureDate: "2026-10-01",
|
||||
});
|
||||
});
|
||||
|
||||
it("現況名冊失敗與寫入失敗不帶日期", async () => {
|
||||
await runRosterSyncIfDue(
|
||||
t.db,
|
||||
source({ current: new HrSyncError("roster", "http_503") }).hr,
|
||||
options(),
|
||||
);
|
||||
expect(syncs()[0]).toMatchObject({ failureStage: "roster", failureDate: null });
|
||||
|
||||
await runRosterSyncIfDue(
|
||||
t.db,
|
||||
source({ "tree:current": [unit("G1", "前端組", "組")] }).hr,
|
||||
options(new Date("2026-11-03T03:00:00.000Z")),
|
||||
);
|
||||
expect(syncs()[1]).toMatchObject({ failureStage: "departments", failureDate: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("要求重新同步名冊", () => {
|
||||
const admin = (now: Date) => ({ actor: null, actorLabel: "林人資(A0001)", ip: null, now });
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ export type RosterSyncOutcome =
|
||||
employmentChanges?: number;
|
||||
snapshotChanges?: number;
|
||||
employmentStatus?: EmploymentStatusResult;
|
||||
failure?: { stage: string; reason: string };
|
||||
failure?: { stage: string; reason: string; date?: string };
|
||||
};
|
||||
|
||||
/** 「下次登入時重新同步名冊」的要求(`_meta` 的鍵)。 */
|
||||
@@ -215,13 +215,15 @@ async function run(
|
||||
throw toHrSyncError("organizations", currentTree.reason, "network");
|
||||
}
|
||||
// 1 日的名冊與組織結構到快照那一步才要求成功;部門清理只拿查到的組織結構輔助判斷。
|
||||
// 失敗紀錄帶查詢日期:本月 1 日與上月 1 日共用同一個階段,要分得出是哪一天查不到。
|
||||
const onFirst = (i: number) => {
|
||||
const [roster, tree] = [dated[i * 2], dated[i * 2 + 1]];
|
||||
const date = `${months[i]}-01`;
|
||||
if (roster.status === "rejected") {
|
||||
throw toHrSyncError("roster_on_date", roster.reason, "network");
|
||||
throw toHrSyncError("roster_on_date", roster.reason, "network", date);
|
||||
}
|
||||
if (tree.status === "rejected") {
|
||||
throw toHrSyncError("organizations_on_date", tree.reason, "network");
|
||||
throw toHrSyncError("organizations_on_date", tree.reason, "network", date);
|
||||
}
|
||||
return {
|
||||
roster: roster.value as HrRosterEntry[],
|
||||
@@ -262,8 +264,8 @@ async function run(
|
||||
result.ok = true;
|
||||
} catch (error) {
|
||||
const failure = toHrSyncError("roster", error, "network");
|
||||
result.failure = { stage: failure.stage, reason: failure.reason };
|
||||
console.warn(`HR 名冊同步失敗(${failure.stage}:${failure.reason})`);
|
||||
result.failure = { stage: failure.stage, reason: failure.reason, date: failure.date };
|
||||
console.warn(failure.message.replace("HR 同步失敗", "HR 名冊同步失敗"));
|
||||
}
|
||||
|
||||
withTransaction(db, (tx) => {
|
||||
@@ -276,6 +278,7 @@ async function run(
|
||||
snapshotChanges: result.snapshotChanges ?? null,
|
||||
failureStage: result.failure?.stage ?? null,
|
||||
failureReason: result.failure?.reason ?? null,
|
||||
failureDate: result.failure?.date ?? null,
|
||||
})
|
||||
.where(eq(hrRosterSyncs.id, syncId))
|
||||
.run();
|
||||
|
||||
+11
-3
@@ -333,16 +333,24 @@ export function setHrStatus(
|
||||
* 新增一筆名冊同步紀錄(模擬每日名冊同步的結果)。不寫正職身分歷程:
|
||||
* 共用的 e2e 資料庫一旦有正職資料,所有本系統計算的快照都會改計正職。
|
||||
*/
|
||||
export function insertRosterSync(status: "succeeded" | "failed", startedAt: Date): void {
|
||||
export function insertRosterSync(
|
||||
status: "succeeded" | "failed",
|
||||
startedAt: Date,
|
||||
failure: { stage?: string; reason?: string; date?: string } = {},
|
||||
): void {
|
||||
withDb((db) => {
|
||||
db.prepare(
|
||||
`insert into hr_roster_syncs (triggered_by, sync_date, status, started_at, finished_at)
|
||||
values ('E2E', ?, ?, ?, ?)`,
|
||||
`insert into hr_roster_syncs (triggered_by, sync_date, status, started_at, finished_at,
|
||||
failure_stage, failure_reason, failure_date)
|
||||
values ('E2E', ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
startedAt.toISOString().slice(0, 10),
|
||||
status,
|
||||
startedAt.toISOString(),
|
||||
startedAt.toISOString(),
|
||||
failure.stage ?? null,
|
||||
failure.reason ?? null,
|
||||
failure.date ?? null,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -88,21 +88,21 @@ test("人數快照:調整需填原因、保留紀錄;鎖定後拒絕調整",
|
||||
|
||||
// 未填原因
|
||||
await row.locator("summary").click();
|
||||
await row.getByLabel("調整後人數").fill("3");
|
||||
await row.getByLabel("調整後人數").fill("9");
|
||||
await row.getByRole("button", { name: "儲存調整" }).click();
|
||||
// 不用 getByRole("alert"):Next.js 的路由播報元素也是 role="alert"
|
||||
await expect(page.getByText("請填寫調整原因")).toBeVisible();
|
||||
|
||||
// 正常調整
|
||||
// 正常調整(9 與示範部門的計算人數不同;相同人數會被拒絕「人數未變更」)
|
||||
const row2 = page.locator("table").getByTestId("adjust-設計部(示範)");
|
||||
await row2.locator("summary").click();
|
||||
await row2.getByLabel("調整後人數").fill("3");
|
||||
await row2.getByLabel("調整後人數").fill("9");
|
||||
await row2.getByLabel("調整原因").fill("到職者系統晚建檔(e2e)");
|
||||
await row2.getByRole("button", { name: "儲存調整" }).click();
|
||||
const after = page.locator("table").getByTestId("adjust-設計部(示範)");
|
||||
await expect(after.locator("summary")).toContainText("筆紀錄");
|
||||
await after.locator("summary").click();
|
||||
await expect(after).toContainText(/→ 3(到職者系統晚建檔(e2e))/);
|
||||
await expect(after).toContainText(/→ 9(到職者系統晚建檔(e2e))/);
|
||||
|
||||
// 模擬部長已提交月結(鎖定由 add-department-settlement 呼叫 setSnapshotLocked)
|
||||
const db = new Database(e2eEnv.DATABASE_PATH);
|
||||
@@ -135,6 +135,20 @@ test("人數快照顯示來源與最近一次 HR 名冊同步", async ({ page })
|
||||
await expect(page.locator("table tr", { hasText: "設計部(示範)" })).toContainText("系統計算");
|
||||
await expect(page.getByTestId("roster-sync-status")).toContainText("失敗");
|
||||
await expect(page.getByTestId("roster-sync-status")).toContainText("最近成功");
|
||||
// 舊紀錄沒有失敗階段與原因:只顯示「失敗」
|
||||
await expect(page.getByTestId("roster-sync-failure")).toHaveCount(0);
|
||||
|
||||
// 失敗紀錄有階段、原因與查詢日期時顯示說明(show-roster-sync-failure)
|
||||
const firstOfMonth = `${monthsAgo(0)}-01`;
|
||||
insertRosterSync("failed", new Date(), {
|
||||
stage: "roster_on_date",
|
||||
reason: "http_400",
|
||||
date: firstOfMonth,
|
||||
});
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("roster-sync-failure")).toHaveText(
|
||||
`(${firstOfMonth.replaceAll("-", "/")} 名冊查詢:HTTP 400(日期超出 HR 可查範圍或參數錯誤))`,
|
||||
);
|
||||
});
|
||||
|
||||
test("未設定 HR Sync 時「下次登入時重新同步名冊」停用並說明原因", async ({ page }) => {
|
||||
|
||||
Reference in New Issue
Block a user