24 Commits
Author SHA1 Message Date
pkgsp50777_楊舒諠andClaude Opus 5.5 9a37c273ca add-approved-count: the settlement allocation table's total row now starts with 「核准人數 N 人」 (user request 2026-11-18), followed by 支付金額合計, 個人上限合計, 最終補助合計 and 占月上限合計. The count is the number of allocation rows, i.e. people with approved cases that month (several cases count once); new applicants still shown as 「待重新計算」 are included. Shown on the department settlement page and the admin settlement detail (shared component). Calculation, the quota card's 計算人數 (headcount snapshot), the CSV preview and the approved-list export are unchanged. Component test and e2e added; CLAUDE.md updated; change archived into department-settlement
CI / build (push) Successful in 5m17s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 16:13:54 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 bb8cd422aa record-token-exchange-error: when Authentik rejects the HR Sync token exchange, 「HR 同步失敗」 also records the OAuth error code next to stage and http_<status> (e.g. {"stage":"token","reason":"http_400","code":"invalid_grant"}), so the HR Sync manual's cases can be told apart: invalid_grant = user in hr-sync-deny (no token, not even self data), invalid_target = provider not registered. Only RFC 6749 / 8693 standard codes are kept as-is, anything else is "other", and error_description is never read. Reason format and old records unchanged. Prompted by employee 20260105 whose failure only showed http_400. CLAUDE.md updated; change archived into hr-sync
CI / build (push) Successful in 5m8s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 18:35:02 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 b5b90881f8 record-hr-sync-gaps: when the login HR sync queries succeed but return data that cannot be applied, record 「HR 同步資料不完整」 (hr_sync.incomplete, actor 系統(HR 同步)) on the account with reason codes only: name_missing, not_active (+ HR status such as NOT_YET_HIRED), no_organization, unit_not_in_tree (+ unit code), plus the assignment's data date (HR Sync coverageTo). Department reasons are judged only when both the assignment and the organization tree were fetched; failures stay in 「HR 同步失敗」 and are not duplicated; complete data records nothing. Sync behavior is unchanged. Prompted by a new hire (2026-11-16) who logged in fine but stayed on 待指派部門 with no audit trail explaining why. CLAUDE.md updated; change archived into hr-sync
CI / build (push) Successful in 11m9s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 18:24:50 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 0bfea35d97 clarify-edit-after-submit: make it obvious that a submitted case can still be edited before review (user report 2026-11-13: colleagues thought it could not). The detail header button 「撤回申請」 becomes 「撤回並修改」 and the 「我的申請」 row action 「撤回」 becomes 「撤回修改」; the confirm dialog explains the case returns to draft, opens the edit page and must be submitted again; a successful withdraw now goes straight to the edit page with a 「修改後請再按「送出」」 toast. The submitted notice and the detail hint name the button, and the help page gets 「送出後還能修改嗎?」 by status. Withdraw rules, audit and timeline labels are unchanged. CLAUDE.md updated; change archived into application-lifecycle
CI / build (push) Successful in 5m9s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 15:12:04 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 5f7dc1618e storage-monthly-chart: the sysadmin storage card replaces the 3-month average and yearly estimate with a 「每月新增附件」 bar chart for this month so far plus the 5 months before (user decision 2026-11-13: no averages). Each month sums attachments by Taipei upload month, including files later superseded, deleted or purged by retention, and empty months show 0; bars are labelled with size and file count, the current month is lighter and marked 「至今」. Server-rendered with design tokens (no chart library), with an aria-label and a visually hidden table. CLAUDE.md notes the storage usage and low-disk check; change archived into data-reset
CI / build (push) Successful in 5m4s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:15:13 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 ec5e018920 shorten-purpose-hint: the 工作用途說明 hint no longer reads like a 20-character minimum (user decision 2026-11-12): it now says 「請具體說明與工作的關聯」 with no number and shows only while 1–9 characters are entered (threshold 20 → 10). Still never blocks submit; empty is still rejected and the 500-character limit is unchanged. Change archived into subsidy-application
CI / build (push) Successful in 5m11s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:16:33 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 124108ca71 attachment-retention: attachment files are deleted automatically (startup + hourly, idempotent, real time so system clock adjustments never purge early) for every case of a department-month once its settlement has been final-approved (or legacy paid) for 3 months (Taipei date, month-end clamped); months with no settleable case and no submitted-or-later settlement go on the 1st of card month + 5; open / submitted settlements and pending cases block it. Includes returned, rejected, withdrawn, drafts and superseded files (user decision 2026-11-12). Rows stay with attachments.purged_at (sha256 kept for duplicate detection), files are removed after the commit, one attachment.retention_purged audit per department-month. Purged attachments return 404, the UI shows 「附件已依保存期限刪除(日期)」, storage usage lists them separately. Help page and CLAUDE.md updated; change archived into application-attachments and data-reset
CI / build (push) Successful in 11m44s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:23:18 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 64374d931f storage-usage-overview: the sysadmin maintenance tab shows storage usage (disk free/total via statfs, database + WAL size, active vs stale attachments from recorded sizes, average monthly new attachments over the last 3 full months, and pre-clear backups with sizes, newest first, warning when disk free is below 15%); a sysadmin can delete a single pre-clear backup with a required reason (data.backup_deleted audit, name validated and kept inside the backups directory). Change archived into data-reset
CI / build (push) Successful in 4m49s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 20:35:57 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 21e10cfdda zulip-reject-and-settlement-reminder: 不核准 notifications (manager, expired or overdue rejections) are also sent as Zulip DMs with the full comment, merged per recipient; new reminder.settlement_open on the day after the employee deadline (default the 21st, from params) tells managers of unsubmitted departments that have submitted cases to submit the settlement by the manager deadline, with pending / needs-revision / approved counts, in-app and on Zulip (one line per department). The 3/1-day manager deadline reminders stay in-app only. Help and CLAUDE.md updated; change archived into notifications
CI / build (push) Successful in 4m47s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 17:20:29 +08:00
pkgsp50777_楊舒諠 5c662aa9f8 ci: 依 mason 範本重新產生 CI 設定
CI / build (push) Successful in 4m40s
2026-11-11 17:02:42 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 e600048c3d zulip-notifications: 待審 (incl. resubmits) and 退回補件 notifications are also sent as Zulip direct messages to the recipient's account email via an incoming-webhook bot (user decision 2026-11-11: only these two). notifications gets chat_status / chat_attempts / chat_at as the outbox; a per-minute dispatcher (after the business transaction) merges each recipient's pending rows into one message: reviews list applicant + case number (first 10), returns include the full manager comment with @ mentions neutralized; no amounts. Already-reviewed cases, recipients without email or inactive, and rows older than 24 h are skipped; transient failures retry 3 times, failures only log. ZULIP_SITE / ZULIP_BOT_EMAIL / ZULIP_API_KEY added to vibe.yaml (values in .env.deploy); missing config keeps the site running with in-app notifications only; ZULIP_DELIVERY=dry-run for local use. Help page and CLAUDE.md updated; change archived into notifications
CI / build (push) Successful in 4m53s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 16:51:29 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 622dcbbf79 CLAUDE.md: Gitea push now uses a per-machine personal access token in wincred (set up with /mason:gitea-access) instead of the git-credential-oauth browser login
CI / build (push) Successful in 11m27s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 16:25:04 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 5a9dc0fd55 CLAUDE.md: deployment skills moved from vibe-deploy (moonshine-skills, no longer maintained) to mason; containerize / deploy-site references now use the mason: prefix
CI / build (push) Successful in 12m5s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 16:10:36 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 54860cdc2e notification-unread-dot: the bell dropdown marks unread notifications with the same blue dot and light-blue background as the notification list (it only used bold before). Shared UnreadDot component (aria-hidden; the sr-only 未讀 text stays), read items keep the empty slot so titles don't shift; bold titles kept. Change archived into notifications
CI / build (push) Successful in 4m56s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 18:22:57 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 9427ff9530 Audit log pager: 回第一頁 / 上一頁 / 下一頁 are separate buttons (they ran together as one link), with 上一頁 added. The query pages backwards with the same keyset (before: rows newer than the cursor, ascending, reversed) and returns prevCursor; unavailable buttons show disabled. Opening and closing a detail keeps the current page. E2E inserts 120 rows under a unique actor (insertAuditLogs) to page forward and back
CI / build (push) Successful in 5m3s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 18:05:32 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 4b732b949a search-accounts: /admin/accounts gets a search box (employee number, name or email, case-insensitive substring; LIKE wildcards matched literally) and department / role / HR status filters, combined with the existing all / pending / inactive tabs. Conditions live in the URL, so row actions return to the same results; the list shows 「共 N 筆」 and 「清除條件」. The form is keyed by the query so clearing resets its fields. Change archived into org-directory
CI / build (push) Successful in 5m30s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 17:26:38 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 4a424230e5 exclude-part-time-from-headcount: headcount snapshots count only people full-time on the base date again (user decision 2026-11-02: interns and part-timers don't count). The base-date status comes from the app's own hr_employment_history (recorded by the daily roster sync since 2026-10-15), not the roster's employeeGroupCode, which is the group at query time. With no history at all (dev, e2e, never synced) nobody is excluded. Excluded people show as plain 「不計入」 with no reason; locked or adjusted snapshots are untouched, others update on the next roster sync. Help, settings text and CLAUDE.md updated; change archived into headcount-snapshot
CI / build (push) Successful in 5m4s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 16:40:05 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 bc102ef866 friendly-not-found-page: Chinese 404 page. notFound() inside the app frame (case missing or out of scope, etc.) and unmatched URLs now say 「找不到這個頁面。可能是網址有誤、資料已刪除,或您沒有權限查看。」 with 回首頁 instead of the English Next.js default; still HTTP 404 and no hint whether the case exists. Change archived into app-shell
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 16:28:06 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 4332b7e528 Admin settlements overview: department names read as links (accent colour, underline, chevron) so it is clear they open the department detail. Quota card title wraps long unbroken names at 360px instead of pushing the 查看說明 link out of the card
CI / build (push) Successful in 5m6s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 14:36:29 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 c42cd686ad Archive unify-settlement-sheet, force-submit-overdue-settlement, rebase-headcount-snapshot and show-roster-sync-failure; delta specs merged into the main specs
CI / build (push) Successful in 45s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 12:03:30 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 2f1a54db6c rebase-headcount-snapshot: e2e follow-ups. The headcount settings tab now opens on last month (the current month has no snapshot until its base date); the estimate/final/preview tag of MoneyDisplay wraps on narrow cards (the admin 360px dashboard overflowed). E2E: duplicates use the same last-month card date, review and settings expect last month; CLAUDE.md notes the Chrome close hang after failed tests
CI / build (push) Successful in 11m16s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 11:36:39 +08:00
shaune.janandClaude Opus 5.5 00f1741dd7 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
- 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]>
2026-11-01 20:20:51 +08:00
shaune.janandClaude Opus 5.5 47b7d5f50f 1.3.1: review comment survives typing before hydration; e2e follows the next-month base date
CI / build (push) Successful in 11m40s
- Review panel: the comment textarea is uncontrolled (defaultValue + ref) and read on submit, like the application form, so a comment typed before hydration (e.g. right after a notification's full-page redirect to the review page) is no longer cleared and 退回補件 no longer fails with 「必須填寫意見」. Fixes the flaky notifications e2e.
- E2E for rebase-headcount-snapshot (task 4.1): the review flow expects the claim month (last month), the duplicate test uses the same card date as the form (claimDate()), and the headcount-snapshot settings tests open the last card month (this month's base date has not arrived).
- Tick rebase-headcount-snapshot 4.1/4.2 and force-submit-overdue-settlement 6.1/6.2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 19:44:41 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 191bd3a276 rebase-headcount-snapshot: headcount snapshots and application attribution use the 1st of the month after the card month (user decision 2026-10-30: employees apply in the following month, so people who left by the end of the card month no longer count). No current-month claims: card month M can be submitted from the 1st of M+1 to the 20th (drafts any time; the form shows the submission window). Everyone active on the base date counts (no full-time filter until HR Sync provides dated employee groups; issue opened in MoonShineVFX/mason). Before the base date no snapshot is created and caps show 「YYYY/MM/01 名冊確定後計算」; the daily roster sync maps this month's 1st roster to last card month; the dashboard quota cards show the previous card month. A one-time startup step removes unlocked, unadjusted snapshots whose base date has not arrived. E2E pins the system clock to the 10th of the current month (pin-clock setup project)
CI / build (push) Successful in 4m58s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 21:28:31 +08:00
230 changed files with 15728 additions and 514 deletions
+8
View File
@@ -21,3 +21,11 @@ APP_URL=
BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS=
# OIDC_ISSUER、OIDC_CLIENT_ID、OIDC_CLIENT_SECRET 由 vibe 平台部署時注入(保留字),
# 不要寫在這裡或任何進版控的檔案。
# Zulip 機器人(chat.moonshine.tw 的傳入 webhook bot):待審與退回通知同時私訊本人。
# 三個都有(且有 APP_URL)才發送;正式環境的值放 .env.deploy,由 /mason:deploy-site 交給平台。
ZULIP_SITE=
ZULIP_BOT_EMAIL=
ZULIP_API_KEY=
# 本機測試不想真的發給同事時設 dry-run(只寫 log)。不要列進 vibe.yaml。
# ZULIP_DELIVERY=dry-run
+65 -14
View File
@@ -1,4 +1,4 @@
# 由 vibe-deploy 的 containerize skill 產生。
# 由 mason 的 containerize skill 產生。
#
# 這份 workflow 不含任何 Secret,也不含任何基礎設施位址(除了下方的
# DEPLOYMENT_API)。Registry 位址、帳號與 image 名稱都由 Deployment API 在驗證
@@ -113,22 +113,73 @@ jobs:
docker logout "$registry" >/dev/null 2>&1 || true
rm -f /tmp/registry-credentials.json
# API 可能要等同一個應用程式的其他請求(最多 60 秒),再花最多 45 秒設定公司登入
# 與物件儲存,所以單次等 135 秒。只有三個錯誤碼代表「稍後重送就會成功」,依 API
# 給的 Retry-After 重試:最多三次請求,從第一次起算共 6 分鐘。其他錯誤一次就停。
# 重送同一個 commit 是安全的:API 會沿用既有的部署紀錄。
- name: 建立部署
if: gitea.event_name == 'push' && gitea.ref == format('refs/heads/{0}', gitea.event.repository.default_branch)
env:
DEPLOY_TOKEN: ${{ secrets.GITEA_TOKEN }}
DEPLOY_REPOSITORY: ${{ gitea.repository }}
DEPLOY_COMMIT: ${{ gitea.sha }}
run: |
set -eu
code=$(curl -sS -m 20 -o /tmp/deployment.json -w '%{http_code}' \
-X POST "${DEPLOYMENT_API}/v1/deployments" \
-H "Authorization: Bearer ${{ secrets.GITEA_TOKEN }}" \
-H 'Content-Type: application/json' \
-d "{\"repository\":\"${{ gitea.repository }}\",\"commitSha\":\"${{ gitea.sha }}\"}")
cat /tmp/deployment.json
echo
# 201 建立、200 表示同一個 SHA 已經有部署紀錄,兩者都算成功。
case "$code" in
200|201) ;;
*) echo "建立部署失敗:HTTP $code"; exit 1 ;;
esac
python3 - <<'PY'
import json, os, re, socket, sys, time, urllib.error, urllib.request
RETRYABLE = {"application_busy", "s3_credential_change_blocked", "application_provisioning_timeout"}
TIMEOUT = float(os.environ.get("DEPLOY_REQUEST_TIMEOUT", "135"))
BUDGET = float(os.environ.get("DEPLOY_RETRY_BUDGET", "360"))
MAX_REQUESTS = 3
url = os.environ["DEPLOYMENT_API"].rstrip("/") + "/v1/deployments"
body = json.dumps({"repository": os.environ["DEPLOY_REPOSITORY"],
"commitSha": os.environ["DEPLOY_COMMIT"]}).encode()
timeouts = (TimeoutError, socket.timeout)
# 內網位址是明文 HTTP:環境變數裡的 proxy 會看到 token,所以不用 proxy。
# HTTPS 時 proxy 只轉送加密的通道,照環境設定走。
handlers = [] if url.startswith("https://") else [urllib.request.ProxyHandler({})]
opener = urllib.request.build_opener(*handlers)
started = time.monotonic()
for attempt in range(1, MAX_REQUESTS + 1):
request = urllib.request.Request(url, data=body, method="POST", headers={
"Authorization": "Bearer " + os.environ["DEPLOY_TOKEN"],
"Content-Type": "application/json",
})
try:
with opener.open(request, timeout=TIMEOUT) as response:
status, raw, headers = response.status, response.read(), response.headers
except urllib.error.HTTPError as error:
status, raw, headers = error.code, error.read(65536), error.headers
except (urllib.error.URLError, OSError) as error:
reason = getattr(error, "reason", error)
if isinstance(reason, timeouts) or isinstance(error, timeouts):
sys.exit(f"建立部署逾時:Deployment API 在 {TIMEOUT:g} 秒內沒有回應,可能仍在處理。"
"重跑這個 job 即可,同一個 commit 會沿用既有的部署紀錄")
sys.exit(f"連不到 Deployment API:{type(reason).__name__}")
text = raw.decode("utf-8", "replace")
print(text)
# 201 建立、200 表示同一個 SHA 已經有部署紀錄,兩者都算成功。
if status in (200, 201):
sys.exit(0)
try:
code = json.loads(text)["error"]["code"]
except (ValueError, KeyError, TypeError):
code = None
if code not in RETRYABLE:
sys.exit(f"建立部署失敗:HTTP {status}")
wait = (headers.get("Retry-After") or "").strip()
# 正整數秒;0 等於不等待就重送。
if not re.fullmatch(r"[1-9][0-9]{0,3}", wait):
sys.exit(f"建立部署失敗:API 回 {code},但沒有合法的 Retry-After,不重試")
wait = int(wait)
if attempt == MAX_REQUESTS or time.monotonic() - started + wait + TIMEOUT > BUDGET:
sys.exit(f"建立部署失敗:{code}。另一個部署正在使用這個應用程式的設定,"
"重試後仍未完成;請稍後重跑這個 job")
print(f"API 回 {code},{wait} 秒後重試(第 {attempt}/{MAX_REQUESTS - 1} 次重試)", flush=True)
time.sleep(wait)
PY
- name: 清理
if: always()
+33 -23
View File
@@ -10,7 +10,7 @@ Stack: **Next.js 16 (App Router, TypeScript strict, full-stack) + SQLite** (bett
Next.js 16 has breaking changes vs. older versions — read `AGENTS.md` and the guides in `node_modules/next/dist/docs/` before writing Next.js code.
Git repository on branch `main`; remote `origin` = company Gitea `https://gitea.moonshine-studio.net/pkgsp50777/aisubsidy.git` (HTTPS only, no SSH; push auth via `git-credential-oauth` configured for that host — first push opens a browser for Authentik login, so the user runs it). Pushing to `main` triggers Gitea Actions **and deploys** to the vibe platform. Files use LF line endings (`.gitattributes`); Prettier checks this.
Git repository on branch `main`; remote `origin` = company Gitea `https://gitea.moonshine-studio.net/pkgsp50777/aisubsidy.git` (HTTPS only, no SSH; push auth via a per-machine Gitea personal access token stored in the system credential helper (`wincred`), set up with `/mason:gitea-access`; the old `git-credential-oauth` browser login was removed 2026-11-11. Never print the token: no `git credential fill`). Pushing to `main` triggers Gitea Actions **and deploys** to the vibe platform. Files use LF line endings (`.gitattributes`); Prettier checks this.
## Commands
@@ -30,14 +30,14 @@ First-time setup: `npm ci` → copy `.env.example` to `.env` and set `SESSION_SE
| `npm run notifications:remind` | Generate today's deadline reminders now (also runs hourly in the server; same-day reruns don't duplicate) |
| `npm run backup` | Online SQLite backup + attachments copy to `BACKUP_DIR`; see `docs/operations/backup.md` |
CI is `.gitea/workflows/ci.yaml`, **generated from the vibe-deploy `containerize` template — don't hand-edit it; re-run `/vibe-deploy:containerize`** (only `{{TEST_COMMAND}}` is project-specific: `docker build --target test .`, i.e. the Dockerfile `test` stage runs lint, format:check, typecheck, `npm test`). Then it builds the image, smoke-tests it with **no secrets** until the HEALTHCHECK is healthy, and on the default branch publishes the image and creates a deployment. E2E is **not** in CI (user decision) — run it locally before pushing. E2E helpers: `tests/e2e/helpers.ts` (`loginAs(page, employeeNo)`, demo users). Parallel e2e tests share one DB — use fresh employee numbers/department names instead of mutating demo users.
CI is `.gitea/workflows/ci.yaml`, **generated from the mason (formerly vibe-deploy) `containerize` template — don't hand-edit it; re-run `/mason:containerize`** (only `{{TEST_COMMAND}}` is project-specific: `docker build --target test .`, i.e. the Dockerfile `test` stage runs lint, format:check, typecheck, `npm test`). Then it builds the image, smoke-tests it with **no secrets** until the HEALTHCHECK is healthy, and on the default branch publishes the image and creates a deployment. E2E is **not** in CI (user decision) — run it locally before pushing. E2E helpers: `tests/e2e/helpers.ts` (`loginAs(page, employeeNo)`, demo users). Parallel e2e tests share one DB — use fresh employee numbers/department names instead of mutating demo users.
If Playwright's browser download fails (CDN returns 403 on this machine), set `PLAYWRIGHT_CHANNEL=chrome` (or `msedge`) to use the installed browser. On this machine Playwright may hang after the tests finish (Chrome profile cleanup); results are already printed by then.
If Playwright's browser download fails (CDN returns 403 on this machine), set `PLAYWRIGHT_CHANNEL=chrome` (or `msedge`) to use the installed browser. On this machine Playwright may hang after the tests finish (Chrome profile cleanup): closing the browser hangs, so the run also stalls right after any **failed** test (the worker restarts). Use `--reporter=list` to see each result as it lands, look in `test-results/` for failures, and kill leftover `node …playwright…` processes before the next run (stopped runs keep their workers alive).
## Deployment (vibe platform)
- Files: `Dockerfile` (stages `deps` → `test` → `build` → `runtime`; Next.js `output: "standalone"`, runs as `node` UID 1000, port 3000, HEALTHCHECK hits `/api/health`), `.dockerignore`, `compose.yaml` (local container check only, `AUTH_MODE=dev`), `vibe.yaml` (port, health path, `persistence` at `/app/data`, `auth.mode: oidc`, required secret **names**).
- App name `aisubsidy` → `https://aisubsidy-vibe.moonshine-studio.net`. Runtime secrets (`vibe.yaml` `environment.required`): `SESSION_SECRET`, `APP_URL`, `BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS` — values live in the developer's local `.env` and are handed to the Deployment API by `/vibe-deploy:deploy-site`; never commit them. Adding a new required env var means updating `vibe.yaml`.
- App name `aisubsidy` → `https://aisubsidy-vibe.moonshine-studio.net`. Runtime secrets (`vibe.yaml` `environment.required`): `SESSION_SECRET`, `APP_URL`, `BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS` — values live in the developer's local `.env` and are handed to the Deployment API by `/mason:deploy-site`; never commit them. Adding a new required env var means updating `vibe.yaml`.
- The app must **start and pass the health check with no secrets at all** (CI smoke test): missing `SESSION_SECRET` → random + warning; missing OIDC settings in `oidc` mode → login disabled + warning. Keep new config degrading the same way instead of exiting.
- Migrations run on startup (`src/instrumentation.ts` → `migrateOnStartup`); the image has no `tsx`. Migration SQL is copied into the image explicitly (standalone tracing doesn't include it).
- `/api/health` must stay public (excluded in `src/proxy.ts`).
@@ -68,7 +68,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Department manager: cases and members belonging to departments in `department_managers`. Scope follows `department_managers`, not the role: someone with the manager role but no assignment sees no department. HR secondary managers have no manager role.
- Cases are attributed by the case's own department, so cases from before a transfer stay with the old department's manager.
- Admin: company-wide applications and settlements (including the approved-list export). Sysadmin: accounts and settings.
- Per-person full-time status is never shown. The headcount snapshot's 1-day member list (admin / sysadmin only) marks non-full-time people as plain 「不計入」 with no reason.
- Per-person full-time status is never shown. The headcount snapshot's base-date member list (admin / sysadmin only) marks non-full-time people (interns, part-timers) as plain 「不計入」 with no reason.
- Every new page, export or API that shows personal data needs a cross-scope case in `tests/e2e/visibility.spec.ts`.
- Org data lives in `src/server/org/` (departments, accounts, roster CSV import). Department membership on a date (for headcount snapshots) is `departmentMembersAt(db, departmentId, "YYYY-MM-DD")`, based on `user_department_history`.
@@ -88,25 +88,26 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Syncs **at login**, on the server, for the logged-in employee number from the ID token:
- The HR token is used for this login's sync and, at most once a day, for the roster sync below; then it is discarded. Deactivated accounts and dev login never call HR Sync.
- The snapshot is fetched outside the transaction. It is applied inside `provisionOnLogin`'s transaction through `afterProvision`, in a savepoint, before the session is created.
- Any failure (token, query, timeout, bad response, write) still completes the login and records `hr_sync.failed` (stage + reason only).
- Any failure (token, query, timeout, bad response, write) still completes the login and records `hr_sync.failed` (stage + reason only). A token exchange rejected by Authentik also records the OAuth `code` (`record-token-exchange-error`: `oauthErrorCode` keeps only the RFC 6749 / 8693 standard codes, anything else is `other`, never `error_description`); per the HR Sync manual `invalid_grant` means the user is in `hr-sync-deny` (no token at all, not even self data) and `invalid_target` means the site's provider is not registered with HR Sync.
- Queries that succeed but return unusable data record `hr_sync.incomplete` 「HR 同步資料不完整」 inside `applyHrSnapshot` (`record-hr-sync-gaps`, after the 2026-11-16 case of a new hire stuck on 待指派部門 with no audit trail): `reasons` = `name_missing` (profile without a name), `not_active` (+ `status`, e.g. `NOT_YET_HIRED`), `no_organization`, `unit_not_in_tree` (+ `deptCode`), plus `hrDate` (the assignment's `date`, i.e. HR Sync `coverageTo`). Department reasons are judged only when both the assignment and the organization tree were fetched (failures are already in `hr_sync.failed`). Codes only, never names or response content. Behavior is unchanged.
- **Daily roster sync** (`runRosterSyncIfDue`): the callback route runs it with `after()` once the response is sent, using the token from that login.
- Runs only if today (Asia/Taipei) has no succeeded run. `claimRosterSync` writes a `running` row in `hr_roster_syncs`; a `running` row older than 10 minutes counts as abandoned.
- Exception: 「下次登入時重新同步名冊」 on `/admin/settings` (headcount tab).
- `requestRosterResync` stores `_meta.roster_resync_requested` (real time, not system time, and requester) and records `hr_sync.roster_resync_requested`.
- The request counts as pending until a run succeeds that started after it (`rosterResyncStatus`). While it is pending, the next company login runs the sync even if today already succeeded.
- It is refused when HR Sync isn't configured.
- Fetches the current roster and organization tree, plus the roster and tree on the 1st of this month and last month (30 s shared timeout).
- Fetches the current roster and organization tree, plus the roster and tree on the 1st of this month and last month (30 s shared timeout). Those dates are snapshot **base dates**: this month's 1st → last card month, last month's 1st → the card month before (`rebase-headcount-snapshot`).
- Departments step (one transaction, `syncHrDepartments`):
- Creates every active 部, renames on HR change, and syncs managers. It never reactivates a department an admin deactivated, and never changes type.
- Cleans up group-level departments: HR-managed departments whose code resolves to another department. Members move with the same effective date (a correction, not a transfer). Cases not yet in a submitted settlement move too (`application.department_corrected`). Managers are removed and the department is deactivated (`department.hr_deactivated`).
- A department with a non-`open` settlement is skipped and listed in the summary audit.
- A tree with no 部 fails with stage `departments`, and nothing is changed.
- Writes full-time history (`employeeGroupCode === "1"`). The first record starts at the HR hire date, later changes start today. No record = not full-time.
- Creates or updates snapshots with `syncSnapshotsFromHr`: ACTIVE on the 1st, unit resolved to the department through that day's tree (group members count toward their 部), full-time on the 1st. Locked or manually adjusted snapshots are never overwritten. Departments without a code in that roster are skipped. Last month is processed before this month.
- 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), `excluded` (ACTIVE, not full-time; shown without a reason), `suspended`, `offboarded` (only `leaveDate` ≥ the 1st of the previous 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 → 「此快照沒有名單紀錄」).
- Writes full-time history (`employeeGroupCode === "1"`). The first record starts at the HR hire date, later changes start today. No record = not full-time. Snapshots read it on the base date (`fullTimeOn`, `exclude-part-time-from-headcount`, user decision 2026-11-02: interns and part-timers don't count) — never the roster's `employeeGroupCode`, which is the group at query time even for dated queries. With no history rows at all (`hasEmploymentData` false: dev, e2e, never synced) nobody is excluded.
- 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; ACTIVE and full-time on the base date), `excluded` (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.
- Per-person full-time status is never shown on any page; only headcount totals use it.
- 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.
- HR wins:
- HR name over the ID token name.
- ACTIVE assignment → the unit's 部 (`resolveDivision` over `/organizations`) → department by `departments.code`, auto-created (type general; admins set 研發) / renamed / reactivated and marked `hr_managed`. If the organization query failed, the department is left unchanged. Moving between groups inside one 部 is not a transfer. A transfer writes `user_department_history` from the HR `hr.employee.transferred` effective date (`transferEffectiveDate`: only events whose new unit resolves to the new department and old unit to a different one; not before the user's last history row and not after today, otherwise today), and sets `users.hr_synced_at`. Non-ACTIVE or no organization → department untouched.
@@ -120,7 +121,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- **No HR query entry points.** Only the callback route (login + roster sync) and the settings page and its actions (roster sync status and resync request only) may import `@/server/hr-sync/*` from `src/app`. `client`, `token` and `snapshot` are server-only (`entrypoints.test.ts` enforces this).
- No page, action or route lets a user name an employee, department or date to query HR.
- Stored HR fields: name, ACTIVE assignment → department (code, name), primary supervisors, and the roster's employee number / name / status / department code / employee group / hire date / leave date / suspended-since (full-time history, snapshot member lists and account status only). Everything else is dropped by the Zod schemas in `client.ts`.
- Tests inject a fake `fetchSnapshot` / `HrDirectory` / `HrRosterSource`. E2E must not insert `hr_employment_history` rows: the e2e DB is shared, and once any row exists every locally computed snapshot counts full-time only (use `markSnapshotFromHr` / `insertRosterSync` to simulate). E2E (dev login) simulates synced data with `createHrSyncedTeam()` (`tests/e2e/db.ts`).
- Tests inject a fake `fetchSnapshot` / `HrDirectory` / `HrRosterSource`. E2E should not insert `hr_employment_history` rows (the e2e DB is shared; simulate with `markSnapshotFromHr` / `insertRosterSync`). E2E (dev login) simulates synced data with `createHrSyncedTeam()` (`tests/e2e/db.ts`).
- HR Sync endpoints and response fields: the API manual in the `hr-sync` skill of [MoonShineVFX/mason](https://github.com/MoonShineVFX/mason) (`skills/hr-sync/`: `references/api-contract.md`, `references/hr-sync-openapi.json`). The copy in the vibe-deploy plugin (moonshine-skills) is kept only for compatibility and no longer maintained.
## Audit trail (操作紀錄)
@@ -137,7 +138,8 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- **Never hard-code rule values** (quota, deadlines, platforms, attachment limits; the subsidy ratio and rounding still live in the parameters). Read them from versioned parameters: `getEffectiveRuleVersion(db, at)` / `requireEffectiveRuleVersion` (`src/server/rules/params.ts`); the schema and defaults are in `src/lib/rule-params.ts`. Versions are append-only (DB triggers).
- Deadlines: `deriveDeadlines(db, cardDate, tz)` — uses the version effective at the **end of the card month**; pure date math in `src/domain/deadlines.ts`.
- Platform options: `platformOptions(params)` (always appends 「其他」). Applications must store the platform name itself, not a reference into the parameter list.
- Department cap: `getDepartmentCap(db, departmentId, month, tz)` is read-only and returns 「尚未建立人數快照」 when missing — call `ensureMonthSnapshots` first where a snapshot must exist (settlement). Snapshots count members at 00:00 on the 1st (from `user_department_history`), and once any full-time history exists only those full-time on the 1st (`localHeadcount`). Snapshots have a `source` (`local` / `hr`); the daily HR roster sync replaces unlocked, unadjusted ones with the HR count.
- **Snapshot base date** (`rebase-headcount-snapshot`, user decision 2026-10-30): card month M uses the **1st of month M+1** at 00:00 (`snapshotBaseDate` / `baseDateReached` / `capPendingMessage` in `src/domain/deadlines.ts`) — employees apply in the following month, so people who left by the end of M no longer count. Before the base date no snapshot can be created (`ensureMonthSnapshots` / `createDepartmentSnapshot` fail with 「YYYY/MM/01 名冊確定後計算」), and the review cap preview, dashboard `QuotaCard` (`message`) and settlement show that text. Only people full-time on the base date count (`hr_employment_history`; interns / part-timers excluded, nobody excluded while there is no history at all). A one-time startup step `rebaseHeadcountSnapshots` (`_meta` `headcount_base_next_month`) deleted unlocked, unadjusted snapshots whose base date had not arrived (`headcount.snapshot_removed`).
- Department cap: `getDepartmentCap(db, departmentId, month, tz)` is read-only and returns 「尚未建立人數快照」 when missing — call `ensureMonthSnapshots` first where a snapshot must exist (settlement). Snapshots count members at 00:00 on the base date (from `user_department_history`; `localHeadcount`). Snapshots have a `source` (`local` / `hr`); the daily HR roster sync replaces unlocked, unadjusted ones with the HR count.
- Settlement submit/return must call `setSnapshotLocked(tx, audit, departmentId, month, locked)` inside its transaction.
- An initial parameter version is created by `ensureDefaultRuleVersion` at startup and in seed.
- Personal cap 50% (2026-10-20 rule correction, replacing the 2026-10-14 full subsidy):
@@ -149,14 +151,16 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Application state changes go **only** through `applyTransition(tx, audit, …)` (`src/server/applications/lifecycle.ts`) inside `withTransaction`: it re-reads the status, checks the transition table, actor role and comment, runs an optional `guard`, then writes status + `application_transitions` (timeline, append-only) + audit. New transitions (approve/return/reject, settlement…) are added to `TRANSITIONS` in `src/lib/application-lifecycle.ts` plus an audit action — never update `applications.status` directly.
- Form rules live once in `src/lib/application-form.ts` (`validateApplication`, draft vs submit mode), shared by the client form and the server services (`src/server/applications/service.ts`: `saveDraft`, `submitApplication`, `withdrawApplication`, `deleteDraft`). Submit re-validates, checks both attachments and the deadline, and records `rule_version_id`.
- No estimated subsidy is shown anywhere for employees: before settlement the amount reads 「月結後確認」.
- `applications.department_id` is the department the applicant belonged to on the 1st of the card month (the same base date as headcount snapshots).
- `applications.department_id` is the department the applicant belonged to on the snapshot base date (the 1st of the month after the card month).
- No current-month claims: a card month M application can be submitted only from the 1st of M+1 (`deadlinesFor(...).start`, `submissionOpensAt`; `submitApplication` returns 「此筆刷卡日期屬於 YYYY/MM,YYYY/MM/01 起才能送出。」). Drafts can be saved any time; the form shows 「可送出期間」 and disables 送出 before the start.
- Rule: `attributedDepartment` (`src/domain/attribution.ts`), falling back to the department on the card date, then the current one. History comes from `departmentHistoryOf`.
- Recomputed on create, save and submit while editable; fixed once submitted, and never follows later transfers.
- `applyTransition` notifies and lock-checks the post-patch department.
- The form shows the same attribution live. Deleting a never-submitted draft is a soft delete (`deleted_at`); deleted drafts don't exist for queries (`getApplicationDetail`, `getApplicationAccess`).
- Withdraw: `withdrawBlocker` (`lifecycle.ts`: not yet reviewed and settlement not locked) decides the detail button; `withdrawableIds` batches the same check for the 「我的申請」 list, which has a 撤回 action per row (`WithdrawButton`). The detail page has one 「撤回申請」 button (page header) and a text-only 「主管審核前可撤回修改」 hint below the status. `ConfirmDialog.onConfirm` may return an error string (shown in the dialog) and thrown errors are shown too.
- Withdraw: `withdrawBlocker` (`lifecycle.ts`: not yet reviewed and settlement not locked) decides the detail button; `withdrawableIds` batches the same check for the 「我的申請」 list, which has a 「撤回修改」 action per row (`WithdrawButton`). The detail page has one 「撤回並修改」 button (page header) and a text-only hint below the status explaining how to edit before review (`clarify-edit-after-submit`, user decision 2026-11-13: colleagues thought submitted cases could not be edited). A successful withdraw navigates to `/applications/:id/edit` with a 「修改後請再按「送出」」 toast; audit and timeline labels stay 「撤回」. `ConfirmDialog.onConfirm` may return an error string (shown in the dialog) and thrown errors are shown too.
- New application form: the first upload creates the draft once (`ensureApplicationId` keeps the id and the in-flight request in refs); 儲存草稿/送出 are disabled while any `FileUploader` reports busy (`onBusyChange`).
- Attachments: service in `src/server/attachments/service.ts` (upload streams with magic-number format check and size limit from rule params, replace/delete mark `superseded_at` and keep the file, `attachmentCompleteness`, `authorizeAttachmentRead`). Files live under `ATTACHMENTS_DIR` with random keys and are served only by `GET /api/attachments/:id` (same 404 for missing/unauthorized). UI: `FileUploader` / `FilePreview` (see `docs/ui-guide.md`).
- Attachment retention (`attachment-retention`, user decision 2026-11-12): `runAttachmentRetention` (`src/server/attachments/retention.ts`, `startRetentionScheduler`: startup + hourly, idempotent, ≤ 50 department-months per run) deletes the files of every case of a (department, card month) once its settlement is `finalized` (or legacy `paid`) and the Taipei finalized date + 3 months is reached; a month with no settleable case (only rejected / withdrawn / drafts) and no submitted-or-later settlement goes on the 1st of M+5. Open / submitted settlements or still-pending cases block it. Rules and constants in `src/lib/attachment-retention.ts` (a policy, not a rule param). Uses **real time** (`realNow()`), so system clock adjustments never purge early. Rows stay (`attachments.purged_at`; sha256 kept for duplicate detection); files are removed after the commit; one `attachment.retention_purged` audit per department-month (actor 「系統(附件保存期限)」). Purged attachments return 404 from `authorizeAttachmentRead`, `FilePreview` shows 「附件已依保存期限刪除(日期)」, and storage usage lists them separately (`attachments.purged`).
- Review (`src/server/applications/review.ts`, `reviewer.ts`): reviewers are the managers of the application's department (`resolveReviewers` / `reviewDecision`, same data as `canReview`); a department without a manager has **no** reviewer — cases wait and `/admin/departments` lists them (user decision: admins never review). Pass `expectedStatus` to `applyTransition` from UI actions so races return 「案件狀態已變更,請重新整理」. After the employee deadline of the case's card month (system time), `return` is refused (`returnBlockedReason`, checked in `reviewApplication`'s guard) and the review UI hides 退回補件 with that message: the employee could not resubmit anyway.
- Review UI (`/department/review`):
- Desktop default `?view=list`: a table (`review-table.tsx`, ≥ xl) with row expansion, attachment previews and in-row approve / return / reject.
@@ -167,7 +171,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Card-month filter `?month=YYYY-MM|all` (`reviewQueueMonths`; `listReviewQueue` / `reviewQueueCounts` take the month): default is the earliest month with cases in the current tab, or the case's month for a bare `?id=`; tab counts, list, batch approve and cap summaries follow the month; links keep it.
- Narrow screens: a card list, plus `/department/review/:id`.
- Above the lists, and in the detail: 部門額度試算 per (department, card month).
- `reviewCapPreview` / `reviewCapPreviews` cover pending + approved + pending-settlement cases, using the settlement calculation (equal share, current adjustments) with the current params (read-only; creates a missing snapshot for started months).
- `reviewCapPreview` / `reviewCapPreviews` cover pending + approved + pending-settlement cases, using the settlement calculation (equal share, current adjustments) with the current params (read-only; creates a missing snapshot once the base date has passed; before that it shows 「YYYY/MM/01 名冊確定後計算」).
- Shown with `ReviewCapSummary` and `MoneyDisplay kind="preview"` 「試算」. A submitted month shows final amounts.
- 已核准, 待審 and 合計 are personal-cap sums (each case × 50%, floored per case), so 已核准 + 待審 = 合計. 合計 is `totalEligible`, not affected by adjustments, the same base as 超出 (user decisions 2026-10-16 / 2026-10-20). Each case's 試算 is ≤ 50% of that case. When over, 合計 and the 超出 amount turn `text-danger`.
- E2E: create isolated users with `createEmployee()`, or a department with its own manager via `createTeam()`, and ready-to-review cases with `insertPendingApplication()` (`tests/e2e/db.ts`); states from later changes can be simulated there. Shared form steps live in `tests/e2e/application-helpers.ts`.
@@ -197,7 +201,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- An override must be ≤ that person's personal cap (`adjustOverPaidMessage`), and the sum of all overrides ≤ the cap (`adjustOverCapMessage`); restoring is never limited.
- Allocations keep `system_eligible`. `AllocationTable` shows 「已調整」, the system value and the reason, also on the admin detail (read-only).
- The audit action is `settlement.eligible_adjusted`.
- The quota block shows four stats: 計算人數|月上限|補助合計|超額 (no 「每人額度」, no 「可補助總額」; the admin detail keeps 每人額度 in its parameter snapshot). 補助合計 is the personal-cap total (`totalEligible`, live for an open trial; user decision 2026-10-20); 超額 = 補助合計 − cap and turns `text-danger` when it is > 0. The paid total appears only in the allocation table's total row. 「支付金額(當月合計)」 is the person's sum of approved cases.
- The quota block shows four stats: 計算人數|月上限|補助合計|超額 (no 「每人額度」, no 「可補助總額」; the admin detail keeps 每人額度 in its parameter snapshot). 補助合計 is the personal-cap total (`totalEligible`, live for an open trial; user decision 2026-10-20); 超額 = 補助合計 − cap and turns `text-danger` when it is > 0. The paid total appears only in the allocation table's total row, which starts with 「核准人數 N 人」 (`add-approved-count`: the number of allocation rows, i.e. people with approved cases that month, new applicants included; also on the admin detail). 「支付金額(當月合計)」 is the person's sum of approved cases.
- `AllocationTable` and the department CSV preview have a 「個人上限(50%)」 column (`settlement_allocations.personal_cap`; rows from before it are null and show 「—」).
- The department CSV preview (`department/settlement/export/route.ts`) and the admin approved list share one settlement sheet (`unify-settlement-sheet`, user decision 2026-10-29): `SETTLEMENT_SHEET_COLUMNS` / `departmentSheetRows` / `sheetCells` in `src/lib/settlement-sheet.ts` — 刷卡月份, 發放月份 (card month + 2), 部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例 (final ÷ cap), 最終補助, 尾差調整, then a 「部門合計」 row (format from the user, 2026-10-22). The preview uses `display` cells (NT$ text, same as the page); new applicants leave the calculated columns blank.
- The allocation table's 「占月上限」 column (page, admin detail, CSV) is final ÷ cap (`capShareBp`, computed at display time; 「—」 when the cap is 0). The stored `share_bp` is final ÷ cap too (not shown).
@@ -208,7 +212,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Locking after submit:
- `isSettlementLocked` (`src/server/settlement/lock.ts`) is checked in `applyTransition` and when editing a case. Any new write path for a case or settlement must check it too.
- DB triggers reject changes to amounts/allocations of non-`open` settlements. Only `status` may change.
- E2E: `monthsAgo(2)` is always past the submission deadline. Control the cap with `setHeadcount(departmentId, month, n)` before opening the page. `insertPendingApplication` takes `cardDate` / `twdAmount` / `status`.
- E2E: the system clock is pinned to the 10th of the current month (see System clock), so `monthsAgo(1)` is inside the submission window (1st–20th) with its snapshot base date passed, `monthsAgo(2)` is always past the submission deadline, and the current month cannot be submitted and has no cap. Control the cap with `setHeadcount(departmentId, month, n)` before opening the page. `insertPendingApplication` takes `cardDate` (default `claimDate(5)`, last month) / `twdAmount` / `status`.
- Admin side (`src/server/settlement/company.ts`, `payouts.ts`; pages `/admin/settlements`, `/admin/settlements/:departmentId/:month`, `/admin/settlements/export`). Admin role only; the services also check it.
- Overdue forced submit (`force-submit-overdue-settlement`, user decision 2026-10-30): after the manager deadline an admin can 「代為提交」 next to the 「逾期未提交」 badge on the `/admin/settlements` overview (`force-submit-button.tsx`; moved from the detail page, user decision 2026-10-30; `forceSubmitSettlement` mode `admin`, reason required, `ReasonDialog` + `confirmStep`); when the rule param `autoSubmit.enabled` (default off, `graceDays` 0–10, default 3, read from the version effective **now**) is on, the hourly settlement scheduler (`runAutoSubmit`, `auto-submit.ts`) submits overdue departments with at least one non-draft case in the previous 1–2 card months after deadline + grace days (mode `auto`, actor `SYSTEM_ACTOR`, label 「系統(自動提交)」). Both share `submitInTx` with the manager submit: pending-review / needs-revision cases first go through the `overdue_reject` transition (actor admin or system, system comment) and stay rejected after a later return; overrides over the cap/personal cap block (auto skips the department and sends `reminder.auto_submit_failed` once a day per month). `submission_mode` / `submission_reason` on `department_settlements` and `settlement_submissions`; managers get `settlement.force_submitted`; audits `settlement.proxy_submitted` / `settlement.auto_submitted`. Managers' own submit is still blocked by unreviewed cases.
- Settlement status: `open → submitted → finalized`. **Final approval is the end** (`remove-payout-management`, user decision 2026-10-28): no payout tracking, no `paid` transition, no corrections. A return goes `submitted → open` and unlocks the snapshot; a finalized settlement can't be returned or corrected.
@@ -231,6 +235,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Attachment files are deleted only after the commit.
- Kept: accounts and roles, departments and managers, department history, rule versions, HR employment and roster syncs, audit log, sessions.
- **A new business table must be added to `BUSINESS_TABLES`**, or it survives a clear.
- Storage usage (same tab, `storageUsage` in `src/server/maintenance/storage-usage.ts`, computed live): disk free/total via `statfs` on the database directory (「剩餘空間不足」 below `DISK_LOW_RATIO` 15%, checked only when the page renders, no background alert), database + WAL, active / stale / purged attachments, pre-clear backups (deletable one at a time, `data.backup_deleted`), and a 6-month 「每月新增附件」 bar chart (`monthly`: this month so far + the 5 before, Taipei upload month, including later superseded / purged files, zeros kept; `monthly-additions-chart.tsx`, server-rendered, no chart library). No average or yearly estimate (user decision 2026-11-13).
## System clock (系統時間)
@@ -243,7 +248,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- `auditContextFor` gives `now` (system time) and `realNow`. `recordAudit` writes `occurred_at` as real time and, when they differ, `simulated_at` as system time (`/admin/audit-log` shows 「系統時間 …」). Contexts rebuilt from another context must carry `realNow` over (see `systemContext` in the settlement service). The schedulers pass both.
- While adjusted, `(app)/layout.tsx` passes `clockNotice` to `AppFrame`. Every page then shows 「系統時間已調整為 …(真實時間 …)」, and sysadmins also get a link to the tab.
- Clearing business data keeps the offset.
- E2E: `tests/e2e/clock.spec.ts` runs in its own Playwright project (`clock`) after all other tests. It clears the offset before and after (`clearClockOffset`). No other spec may set it.
- E2E: the `pin-clock` setup project (`tests/e2e/pin-clock.setup.ts`, `pinSystemClock` in `db.ts`) sets the offset to the 10th of the current month at 12:00 Taipei before the `chromium` project, and its teardown clears it. Test code uses `today()` (the pinned system date) and `claimDate()` (last month, submittable) from `db.ts`; `monthsAgo` follows the real month (unchanged by the pin). `tests/e2e/clock.spec.ts` runs in its own Playwright project (`clock`) after all other tests and clears the offset before and after (`clearClockOffset`). No spec may set it otherwise.
## Duplicate detection & notifications
@@ -264,8 +269,13 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- When a case leaves `pending_review` (approve, return, reject, withdraw…), `notifyTransition` calls `clearPendingReview`, which marks every recipient's unread pending-review notification for that case as read. Nothing is deleted.
- `clearStalePendingReviews` runs once at startup and is idempotent.
- After a review, the review UI dispatches `notifications:changed`, so the bell updates without a page change.
- Zulip direct messages (`zulip-notifications` + `zulip-reject-and-settlement-reminder`, user decisions 2026-11-11): only `application.pending_review`, `application.returned`, `application.rejected` and `reminder.settlement_open` (`CHAT_NOTIFICATION_TYPES`) are also sent as Zulip DMs, to the recipient's account email, by an incoming-webhook bot.
- `notifications.chat_status` (NULL = pending) / `chat_attempts` / `chat_at` make the table the outbox; no audit for these technical fields.
- `runChatDispatch` (`src/server/notifications/zulip.ts`) runs at startup and every minute (`startChatScheduler`), after the business transaction: rows from the last 24 h only (no backlog), pending reviews already read (case reviewed) and recipients without email / inactive are `skipped`, the rest are merged per (recipient, type) into one message — reviews list applicant + case number (first 10), returns / rejections carry the latest `return` / `reject|expire_reject|overdue_reject` comment in full (`@` neutralized), settlement reminders list one line per department from the notification's own title and body. No amounts. Network errors / 429 / 5xx retry up to 3 times, then `failed`; `400 Invalid email` → `skipped`. Failures only log.
- Config: `ZULIP_SITE`, `ZULIP_BOT_EMAIL`, `ZULIP_API_KEY` (+ `APP_URL` for links; `zulipConfigured`) — all required in `vibe.yaml`, values in `.env.deploy`; missing → no scheduler, a startup warning, in-app only. `ZULIP_DELIVERY=dry-run` (local only, never in `vibe.yaml`) logs instead of sending. Never print the API key.
- The top-bar bell polls the `notificationSummary` server action every 60 seconds and on navigation.
- Daily deadline reminders: `runDailyReminders`. Reminders are deduped by (recipient, type, target, Taipei date).
- `reminder.settlement_open`: the day after the employee deadline (default the 21st, derived from params), managers of unsubmitted departments with at least one submitted case (pending review / needs revision / approved / pending settlement) in that card month get 「{部門} {月} 月結請於 {截止日} 前提交」 with the three counts. The 3- and 1-day `reminder.manager_deadline` stay in-app only.
- `startBackgroundJobs` (`src/server/startup.ts`) runs them at startup and hourly, from 08:00 Asia/Taipei.
- Manual trigger: `npm run notifications:remind`. It is safe to rerun the same day.
- Route Handlers must return `new Response(..., { status: 404 })`. Don't call `notFound()` there: it breaks the response instead of returning 404.
@@ -275,7 +285,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- `/dashboard` is composed per role: admin section first, then one manager section per managed department, then the employee section.
- Data comes from `src/server/dashboard/queries.ts`. Permissions are filtered in each query.
- Logic lives in `src/domain/dashboard.ts`: `resolveCurrentCycle` and `quotaReference`. `quotaReference` reuses the settlement `personalEligible`.
- Show department quota only through `QuotaCard`. Its 「參考」 tag and explanation are built in; never show a bare "remaining quota".
- Show department quota only through `QuotaCard`. The employee and manager cards show the **previous card month** (`quotaMonth`, the month being applied for now; the current month's cap is only known from the 1st of next month — `rebase-headcount-snapshot`). Its 「參考」 tag and explanation are built in; never show a bare "remaining quota".
- Show case amounts through `SubsidyAmount`: 「月結後確認」 before submission (no estimate), 最終 after. The employee section has no month estimate. The admin 「全公司預估補助」 stays.
## UI (app-shell)
@@ -325,9 +335,9 @@ Changes go through OpenSpec (`openspec/config.yaml`, schema `spec-driven`). Spec
## Domain rules that are easy to get wrong
- **Month attribution** is by **刷卡日期 (card charge date)** only — never invoice date, service period, or submission date. It drives the application month and both deadlines.
- **Deadlines**: employee submission by the 20th of the following month; department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
- **Deadlines**: employee submission from the 1st to the 20th of the following month (no current-month claims); department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
- **Personal amount**: 支付金額 = sum of the month's approved TWD amounts; the **personal cap is 50%** of it, floored per case (rule corrected 2026-10-20; settlements between 2026-10-14 and then used 100%). TWD amount from the card statement is the basis; foreign-currency amount is reference only.
- **Department monthly cap** = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a **monthly snapshot**, not live headcount. Unused quota does not carry over.
- **Department monthly cap** = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a **monthly snapshot** taken on the 1st of the month after the card month (active full-time staff; interns and part-timers don't count), not live headcount. Unused quota does not carry over.
- **Over cap** → equal share (user decision 2026-10-15, replacing the spec document's pro-rata): adjusted people keep their adjusted amount, the rest split `cap − adjusted total` equally, nobody above their own personal cap; leftover yuan go by employee number. The total **never exceeds** the cap (paid 900/1,700 → caps 450/850, with cap 1,000 → 450/550). Submitted settlements keep their stored results.
- **Approval ≠ payout.** Managers review work purpose only; amounts are settled at month end across all approved cases. UI must never make the quota look first-come-first-served, and must not show employees an amount before settlement (「月結後確認」), only 「最終」 after.
- **Statuses**: 草稿 → 待主管審核 → (待補件 ↔ resubmit) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 (end; legacy rows may be 已發放); plus 撤回. Return/reject require a comment.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-02
@@ -0,0 +1,37 @@
## Context
- `recordEmployment`(名冊同步的 `employment` 步驟)每天依現況名冊寫正職身分歷程:第一次看到某人自 HR 到職日起生效,之後群組變動自同步當日起生效。`fullTimeOn(db, employeeNos, date)` 與 `hasEmploymentData(db)` 已存在,但 2026-10-30 起沒有被讀取。
- `syncSnapshotsFromHr` 以基準日(下個月 1 日)名冊算 ACTIVE 且歸到部門的人;`localMembers` 依部門歷程算本系統快照。名單狀態已有 `excluded`(舊名單用)。
- 同一次名冊同步中,`employment` 步驟在 `snapshots` 之前執行。
## Goals / Non-Goals
**Goals:** 基準日非正職者不計入快照人數;名單標「不計入」不寫原因;不需要 HR Sync 改版。
**Non-Goals:** 修正正職身分歷程開始之前(2026-10-15 前)的群組變動;在任何頁面顯示個人的正職身分;改動已鎖定或人工調整的快照。
## Decisions
### D1 以本系統的正職身分歷程判斷基準日身分
基準日 D 的身分 = `hr_employment_history` 中 D(含)之前最後一筆。不用基準日名冊上的 `employeeGroupCode`:那是**查詢當下**的群組,HR 補查過去日期時會用到之後才轉正的身分。
正確性:基準日 2026-11-01 之後的快照,歷程已每天記錄,群組變動最多晚到「該日第一次登入」才寫入,生效日就是當天,所以 1 日轉正的人當天就算正職。歷程開始前就存在的人,第一筆以到職日起算目前身分,只影響 2026-10-15 前轉正的人在更早基準日的判斷;那些月份的快照都已在暫行規則下建立,若已鎖定則不變。
### D2 沒有身分資料時不排除
`hasEmploymentData(db)` 為 false(從未成功名冊同步,例如開發環境、e2e)時一律計入,避免沒有歷程時所有人都被當成非正職(歷程查不到 = 非正職)。有資料但某人沒有紀錄(例如名冊沒有提供群組)時依規格視為非正職。
### D3 名單狀態
被排除者狀態 `excluded`,畫面照舊只顯示「不計入」不寫原因。`counted` 數量 = 快照人數不變。留停、離職的判斷優先於正職(他們本來就不計入,照原本的原因顯示)。
### D4 套用時機
不加一次性的啟動步驟:未鎖定、未調整的 HR 快照在下一次名冊同步更新(現有機制,`headcount.snapshot_updated` 記前後人數);本系統計算的快照只在建立時計算,與現在相同。管理者要立即套用可按「下次登入時重新同步名冊」。
## Risks / Trade-offs
- [群組變動晚一天] 1 日當天轉正但當天沒人登入,歷程會在 2 日記錄、生效日 2 日 → 1 日基準日仍算非正職。下一次名冊同步重算時也一樣(歷程不回溯)。影響很小;需要時管理者可人工調整快照。
- [HR 沒給群組] 該人沒有歷程 → 視為非正職不計入。可由名單上的「不計入」發現,必要時人工調整。
- [月上限變小] 部署後各部門未鎖定快照可能少算工讀生,月結試算會提示重新計算(現有行為)。
@@ -0,0 +1,31 @@
## Why
2026-10-30 起人數快照暫時不依正職排除(`rebase-headcount-snapshot` D5):HR Sync 依日期查名冊時回傳的是**目前**的員工群組,也沒有群組異動事件,無法知道某人在基準日是不是工讀。使用者 2026-11-02 要求恢復工讀判斷:部門月上限只算正職,工讀生不計入。
本系統自 2026-10-15 起每天名冊同步都會寫入正職身分歷程(`hr_employment_history`),群組變動會在變動當天(第一位登入者觸發的同步)記錄下來。基準日(每月 1 日)落在歷程開始之後的快照,可以用這份歷程判斷基準日的身分,不必等 HR Sync 提供依日期的群組。
## What Changes
- 人數快照恢復排除非正職:基準日在職、且依正職身分歷程在基準日**不是正職**(HR 員工群組不是「1」,例如工讀、實習)的人不計入。
- HR 名冊產生的快照與本系統部門歷程計算的快照都套用。
- 系統還沒有任何正職身分資料時(從未成功名冊同步,例如開發環境)不排除,維持現在的行為。
- 快照人員名單:被排除的人標示「不計入」,**不寫原因**(維持「每個人的正職身分不顯示」)。「計入」人數仍等於快照人數。
- 已鎖定或有人工調整的快照不變;其他未鎖定的 HR 快照在下一次名冊同步依新規則更新(可用「下次登入時重新同步名冊」立即套用),每筆人數變動照舊寫操作紀錄。
- 說明頁(`/help` 管理端)與 CLAUDE.md 的人數規則改回「工讀不計入」。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `headcount-snapshot`:「建立每月人數快照」「由 HR 名冊自動建立與更新快照」「快照人員名單」改為排除基準日非正職者。
## Impact
- 程式:`src/server/rules/headcount.ts`(`syncSnapshotsFromHr`、`localMembers` 依 `fullTimeOn` / `hasEmploymentData` 排除,名單狀態 `excluded`)。`src/server/hr-sync/employment.ts` 不變(已有 `fullTimeOn`、`hasEmploymentData`)。
- 資料:沒有 migration。部署後未鎖定、未調整的快照人數可能變少,月上限跟著變;已提交月結的鎖定快照不受影響。
- 測試:`headcount` 整合測試(工讀不計入、沒有身分資料時不排除、鎖定不變、名單 `excluded`);e2e `settings.spec.ts` 名單顯示「不計入」不寫原因(e2e 不寫 `hr_employment_history`,用 helper 模擬名單)。
- 文件:CLAUDE.md「Rule parameters & headcount」「HR Sync」段落、`/help`。
@@ -0,0 +1,110 @@
## MODIFIED Requirements
### Requirement: 建立每月人數快照
系統 SHALL 為每個部門、每個刷卡月份建立一筆計算人數快照。刷卡月份 M 的快照以**基準日**——M 的下個月 1 日 00:00(Asia/Taipei)——時隸屬該部門且在職的人數計算(使用者決定 2026-10-30:員工在刷卡月份的下個月申請,基準日前離職的人已無法申請)。基準日依正職身分歷程(見 hr-sync「正職身分歷程」)不是正職的人(工讀、實習等,使用者決定 2026-11-02)MUST NOT 計入;系統還沒有任何正職身分資料時(從未成功名冊同步)SHALL 不依正職排除。HR Sync 已設定時人數以 HR 名冊為準(見「由 HR 名冊自動建立與更新快照」)。快照 SHALL 在基準日之後首次需要時(查詢月上限或開啟設定頁)自動建立,管理者亦 SHALL 可手動觸發建立;基準日之前 MUST NOT 建立。在名冊同步之前建立時以本系統部門歷程計算,之後由名冊同步更新。無論何時建立,人數皆以基準日 00:00 的狀態計算。同一部門同一月份 MUST 只有一筆快照。
#### Scenario: 月初後首次需要時自動建立
- **WHEN** 2026/10/01 00:00 設計部有 20 位在職人員,2026/10/03 管理者首次開啟 2026/09 的人數快照
- **THEN** 系統建立設計部 2026/09 快照,人數為 20
#### Scenario: 月中到職不影響當月快照
- **WHEN** 2026/10/10 有一位新人加入設計部
- **THEN** 設計部 2026/09 快照人數仍為 20;這位新人計入 2026/10 快照(基準日 2026/11/01)
#### Scenario: 非正職不計入
- **WHEN** 2026/12/01 00:00 設計部的 20 位在職人員中有 2 位依正職身分歷程在 12/01 是工讀生
- **THEN** 設計部 2026/11 快照人數為 18
#### Scenario: 基準日當天轉正
- **WHEN** 工讀生 E3001 的正職身分歷程自 2026/12/01 起為正職
- **THEN** 他計入 2026/11 快照(基準日 2026/12/01)
#### Scenario: 沒有正職身分資料
- **WHEN** 系統從未成功名冊同步、沒有任何正職身分歷程,設計部 2026/11/01 有 20 位在職人員
- **THEN** 設計部 2026/10 快照人數為 20,不依正職排除
#### Scenario: 刷卡月份最後一天離職
- **WHEN** 設計部一位員工 2026/09/30 為最後工作日、10/01 起離職
- **THEN** 他不計入設計部 2026/09 快照
#### Scenario: 基準日之前不建立
- **WHEN** 今天是 2026/09/20,管理者開啟 2026/09 的人數快照
- **THEN** 系統不建立快照,說明「2026/10/01 名冊確定後計算」
#### Scenario: 未設定 HR Sync
- **WHEN** 開發環境沒有 HR Sync,2026/10/01 設計部有 5 位成員
- **THEN** 設計部 2026/09 快照人數為 5
#### Scenario: 重複建立
- **WHEN** 管理者對已有快照的部門與月份再次觸發建立
- **THEN** 系統不建立第二筆快照,並提示該月份快照已存在
### Requirement: 由 HR 名冊自動建立與更新快照
名冊同步(見 hr-sync)SHALL 以 HR 本月 1 日的名冊(`GET /employees?date=YYYY-MM-01`)與該日的組織結構計算**上個刷卡月份**各部門的快照人數,並 SHALL 以上個月 1 日的名冊與組織結構重算上上個刷卡月份(該月快照尚未鎖定時)。某部門的人數為:基準日 HR 狀態為在職(ACTIVE)、且該日所屬單位依該日組織結構歸到該部門(見 hr-sync「HR 部門對應與自動建立」,部底下各組的人計入部)、且依正職身分歷程在基準日為正職的人數(沒有任何正職身分資料時不依正職排除;名冊上的員工群組是查詢當下的群組,MUST NOT 用來判斷基準日身分)。系統 SHALL 依計算結果建立缺少的快照;已存在且未鎖定、也沒有人工調整的快照,人數不同時 SHALL 更新為 HR 人數,並寫入操作紀錄(操作者「系統(HR 同步)」,含前後人數)。已鎖定或有人工調整的快照 MUST NOT 被覆寫。基準日 HR 名冊中沒有任何人歸到的啟用部門(含手動建立、沒有代碼的部門)SHALL 照舊以本系統部門歷程計算。
#### Scenario: 月初自動建立
- **WHEN** 2026/12/01 HR 名冊中設計部在職的有 20 位正職與 2 位工讀生,2026/12/02 第一位員工登入觸發名冊同步
- **THEN** 系統建立設計部 2026/11 快照,人數為 20,來源為 HR 名冊
#### Scenario: 1 日之後到職或離職
- **WHEN** 一位新人 2026/12/10 到職設計部、另一位設計部員工 2026/12/12 離職
- **THEN** 設計部 2026/11 快照仍為 20;兩人只影響 2026/12 快照(基準日 2027/01/01)
#### Scenario: HR 補登上個月的入職
- **WHEN** 設計部 2026/09 快照為 18 且尚未鎖定、沒有人工調整,HR 在 11/03 補登一位 2026/09/25 到職的設計部員工
- **THEN** 11/03 之後的名冊同步以 10/01 名冊把設計部 2026/09 快照更新為 19,操作紀錄有一筆 18 → 19
#### Scenario: 規則變更後未鎖定快照依新規則更新
- **WHEN** 設計部 2026/10 快照依暫行規則(工讀也計入)為 22、未鎖定、沒有人工調整,2026/11/01 名冊中設計部在職 22 人,其中 2 位依正職身分歷程在 11/01 是工讀生
- **THEN** 下一次名冊同步把快照更新為 20,操作紀錄有一筆 22 → 20;已鎖定的快照不變
#### Scenario: 已人工調整不覆寫
- **WHEN** 管理者已把研發部 2026/10 快照由 20 調整為 21,之後名冊同步算出 20
- **THEN** 快照維持 21
#### Scenario: 各組人數計入部
- **WHEN** 2026/11/01 研發部本身掛 1 位、前端組 8 位、後端組 11 位在職人員(兩組都屬研發部)
- **THEN** 研發部 2026/10 快照人數為 20
### Requirement: 快照人員名單
管理者與系統管理員 SHALL 能在後台設定頁的人數快照中,展開每個部門某月的基準日名單(標示基準日,例如 2026/09 的「2026/10/01 名單」),看出快照人數由哪些人組成。名單每列顯示員工編號、姓名與名單狀態:
- 「計入」:基準日在職,計入快照人數。
- 「不計入(留停)」:基準日 HR 狀態為留停。
- 「不計入(離職)」:基準日已離職,且離職生效日在基準日的上個月 1 日(含)之後。更早離職的人不列出。
- 「不計入」:基準日在職但依正職身分歷程不是正職(工讀、實習等)。MUST NOT 顯示原因,任何頁面 MUST NOT 顯示個人的正職身分。
規則如下:
- 「計入」的人數 MUST 等於快照的計算人數。人工調整後的人數另以調整紀錄說明。
- 由 HR 名冊產生的快照,名單 SHALL 在名冊同步更新快照時一併保存。
- 部門歸屬與人數相同:依基準日所屬單位歸到部門。
- 留停或離職者在基準日名冊沒有所屬單位時,以上個月快照名單中的部門歸屬;仍找不到時不列出。
- 名單與快照人數一起更新:快照已鎖定或有人工調整時,名單 MUST NOT 變動。
- 本系統計算的快照(沒有 HR 名冊資料的部門),名單 SHALL 列出依部門歷程在基準日隸屬該部門的成員,正職為「計入」、非正職為「不計入」。不提供離職/留停原因。
- 建立於名單功能上線前、之後也未再更新的 HR 快照,SHALL 顯示「此快照沒有名單紀錄」。
- 名單 MUST NOT 出現在部門主管或員工可見的任何頁面或匯出。
#### Scenario: 展開名單看到計入與不計入
- **WHEN** 2026/12/01 HR 名冊中設計部有 20 位在職正職、1 位工讀生、1 位留停,另有 1 位 11/30 離職(離職生效日 12/01),管理者在 2026/11 的人數快照展開設計部
- **THEN** 名單標示「2026/12/01 名單」,列出 20 位「計入」、1 位「不計入」(工讀生,不寫原因)、1 位「不計入(留停)」、1 位「不計入(離職)」,快照人數為 20
#### Scenario: 早已離職的人不列出
- **WHEN** 某人 2026/08/15 已離職,管理者展開 2026/09 設計部名單(基準日 2026/10/01)
- **THEN** 名單沒有這個人
#### Scenario: 鎖定後名單不變
- **WHEN** 研發部 2026/10 月結已提交(快照鎖定),之後 HR 補登一位 10 月留停的研發部員工
- **THEN** 2026/10 研發部的名單與人數都維持鎖定時的內容
#### Scenario: 本系統計算的部門
- **WHEN** 管理者展開一個沒有部門代碼、由本系統計算人數的部門
- **THEN** 名單列出基準日隸屬該部門的成員,正職為「計入」、工讀生為「不計入」,沒有離職或留停原因
#### Scenario: 主管看不到名單
- **WHEN** 部門主管直接請求後台設定頁的人數快照或其名單
- **THEN** 系統拒絕存取
#### Scenario: 舊規則的鎖定名單
- **WHEN** 設計部 2026/08 快照在規則變更前已鎖定,名單有 2 位「不計入」
- **THEN** 名單與人數維持原樣,「不計入」照舊不寫原因
@@ -0,0 +1,15 @@
# Tasks
## 1. 快照排除非正職
- [x] 1.1 `syncSnapshotsFromHr`:有身分資料(`hasEmploymentData`)時,基準日 ACTIVE 但 `fullTimeOn(基準日)` 不含的人列為 `excluded`、不計入人數。整合測試:工讀不計入、1 日轉正計入、沒有身分資料時全部計入、鎖定與人工調整的快照不變、留停/離職維持原狀態。
- [x] 1.2 `localMembers` / `localHeadcount`:同樣規則(依員工編號查 `fullTimeOn`)。整合測試涵蓋本系統計算的快照。
- [x] 1.3 名單顯示:`excluded` 仍只顯示「不計入」不寫原因;e2e `settings.spec.ts` 以 helper 模擬含 `excluded` 的名單並檢查文字(不寫 `hr_employment_history`)。
## 2. 文件
- [x] 2.1 CLAUDE.md(Rule parameters & headcount、HR Sync、Domain rules)與 `/help` 管理端說明改為「基準日非正職(工讀、實習)不計入」;不寫「全額」。
## 3. 驗證
- [x] 3.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `settings.spec.ts`、`visibility.spec.ts` 通過。
@@ -27,5 +27,5 @@
## 6. 驗證
- [ ] 6.1 e2e(`company-settlement.spec.ts`):截止前看不到「代為提交」;截止後代提交含 1 筆待審案件 → 月結已提交、標示代提交、案件不核准、部長頁顯示原因。`visibility.spec.ts`:主管與員工直接呼叫代提交被拒。
- [ ] 6.2 `npm run lint`、`format:check`、`typecheck`、`npm test` 與受影響的 e2e 全過。
- [x] 6.1 e2e(`company-settlement.spec.ts`):截止前看不到「代為提交」;截止後代提交含 1 筆待審案件 → 月結已提交、標示代提交、案件不核准、部長頁顯示原因。`visibility.spec.ts`:主管與員工直接呼叫代提交被拒。
- [x] 6.2 `npm run lint`、`format:check`、`typecheck`、`npm test` 與受影響的 e2e 全過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-02
@@ -0,0 +1,13 @@
## Context
`notFound()` 由登入後頁面在案件不存在或不在資料範圍內時呼叫(刻意與「不存在」相同,不透露案件存在)。目前沒有任何 `not-found.tsx`,Next.js 顯示預設英文畫面。
## Decisions
1. **兩個 not-found 檔**:`src/app/(app)/not-found.tsx` 接住登入後頁面的 `notFound()`,在系統框架(頂列、側欄)內以 `Card` 顯示;`src/app/not-found.tsx` 接住不對應任何路由的網址,用 `AuthShell`(與 403 頁一致)。不用實驗性的 `global-not-found`。
2. **文字不分不存在與無權限**:「找不到這個頁面。可能是網址有誤、資料已刪除,或您沒有權限查看。」避免透露案件是否存在。
3. **狀態碼**:頁面沒有 `loading.tsx`(spec 已要求不使用串流載入畫面),`notFound()` 仍回 HTTP 404。
## Risks / Trade-offs
- 未登入時不對應路由的網址會先被 proxy 導向登入,登入後才看到找不到頁面,行為與現在相同。
@@ -0,0 +1,25 @@
## Why
2026-11-02 使用者在手機開啟 `/applications/68`,登入後依 `returnTo` 回到該案件;案件不在其資料範圍內,系統依設計回 404,但畫面是 Next.js 預設的英文「404 This page could not be found.」,沒有說明也沒有回首頁的按鈕,使用者以為手機無法查看網站。
## What Changes
- 登入後頁面呼叫 `notFound()`(案件不存在或不在資料範圍內、審核詳情不是審核者、月結明細的部門或月份不存在等)時,在系統框架內顯示中文的「找不到頁面」:說明「這個頁面不存在,或您沒有權限查看」,並提供「回首頁」。
- 網址不對應任何頁面時,也顯示同樣說明的中文找不到頁面(登入頁風格)。
- 維持 HTTP 404,也不透露案件是否存在(不存在與無權限顯示相同文字)。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `app-shell`:「頁面錯誤與載入畫面」增加找不到頁面的中文畫面。
## Impact
- 程式:新增 `src/app/(app)/not-found.tsx`、`src/app/not-found.tsx`。
- 測試:e2e `applications.spec.ts`(他人案件 404 顯示中文說明與「回首頁」)。
- 權限與資料範圍不變。
@@ -0,0 +1,16 @@
## MODIFIED Requirements
### Requirement: 頁面錯誤與載入畫面
登入後頁面載入或執行發生錯誤時,系統 SHALL 顯示錯誤畫面,說明頁面載入失敗並提供「重新整理」與「回首頁」;整個網站無法顯示時 SHALL 顯示全站錯誤畫面。系統 MUST NOT 只顯示背景色的空白畫面。找不到頁面(網址不存在,或資料不存在、不在使用者的資料範圍內)SHALL 顯示中文說明「找不到這個頁面。可能是網址有誤、資料已刪除,或您沒有權限查看。」與「回首頁」,且不區分資料不存在與沒有權限。無權限與找不到頁面 MUST 維持 HTTP 403/404(因此不使用會先送出 200 的串流載入畫面)。
#### Scenario: 頁面發生錯誤
- **WHEN** 使用者開啟的頁面在載入時發生錯誤
- **THEN** 畫面顯示「頁面載入失敗」與「重新整理」「回首頁」按鈕,而不是空白
#### Scenario: 無權限頁維持 403
- **WHEN** 員工直接開啟管理端頁面
- **THEN** 回應 HTTP 403 並顯示無權限頁
#### Scenario: 找不到頁面顯示中文說明
- **WHEN** 員工開啟不在其資料範圍內的案件網址
- **THEN** 回應 HTTP 404,畫面顯示「找不到頁面」、說明文字與「回首頁」,不顯示英文預設畫面
@@ -0,0 +1,11 @@
# Tasks
## 1. 找不到頁面
- [x] 1.1 新增 `src/app/(app)/not-found.tsx`:系統框架內 `Card`「找不到頁面」、說明文字與「回首頁」(`data-testid="not-found"`)。
- [x] 1.2 新增 `src/app/not-found.tsx`:`AuthShell`「找不到頁面」、同樣說明與「回首頁」。
- [x] 1.3 e2e `applications.spec.ts`:開他人案件仍回 404,畫面顯示「找不到頁面」與「回首頁」。
## 2. 驗證
- [x] 2.1 `npm run lint`、`format:check`、`typecheck` 通過;`npm run test:e2e:prepare` 後 `applications.spec.ts` 通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-02
@@ -0,0 +1,22 @@
## Context
- 通知列表頁(`notifications/page.tsx`)每則是 `flex gap-3`:左側 `size-2 rounded-full`,未讀 `bg-accent`、已讀 `bg-transparent`(保留空位),未讀列加 `bg-accent-soft/40`,標題未讀 `font-semibold`,另有 sr-only「(未讀)」。
- 鈴鐺下拉(`app-frame.tsx` 的 `NotificationBell`,Radix DropdownMenu)每則是區塊式 `<a>`:標題 `text-sm`,未讀只加 `font-semibold` 與 sr-only「未讀:」;資料來自 `notificationSummary` server action(每 60 秒與換頁時更新,`notifications:changed` 事件立即更新)。
## Decisions
### D1 共用 `UnreadDot`
新增 `src/components/ui/unread-dot.tsx`:`<UnreadDot unread={boolean} />` 輸出 `aria-hidden` 的 `size-2 shrink-0 rounded-full`,未讀 `bg-accent`、已讀 `bg-transparent`,並帶 `data-testid="unread-dot"` 與 `data-unread`。圓點本身不傳達文字資訊(`aria-hidden`),未讀的文字提示仍由各處的 sr-only 負責,符合「狀態不能只靠顏色」。
### D2 下拉排版
下拉每則改為 `flex gap-2.5`:左側 `UnreadDot`(`mt-1.5` 對齊標題第一行),右側原本的標題與兩行內文。未讀加 `bg-accent-soft/40`(hover/focus 時仍是 `bg-canvas`)。標題粗體保留,讓有色覺障礙的人仍有非顏色的區別。
### D3 不改資料與更新機制
`notificationSummary` 已回傳 `read`,不需要新欄位;已讀狀態變化(點開通知、審核後清除待審通知)照現有機制更新,圓點跟著消失。
## Risks / Trade-offs
- [下拉寬度] 多一個 10px 左右的欄位,標題在 360px 寬時可能多換一行 → 內文仍是 `line-clamp-2`,`mobile-layout.spec.ts` 確認不超出。
@@ -0,0 +1,26 @@
## Why
頂部列鈴鐺的通知下拉只用**粗體**區分未讀與已讀,使用者 2026-11-02 反映不容易看出哪幾則還沒讀。完整通知列表頁(`/notifications`)已經用藍色圓點加淡藍底標示未讀,兩處的呈現不一致。
## What Changes
- 通知下拉的每則通知,未讀時在標題左側顯示**藍色圓點**,並加上與通知列表頁相同的淡藍底色;已讀的保留同寬的空位(不顯示圓點),標題與內文對齊不跳動。
- 未讀的標題仍維持粗體,螢幕報讀器照舊讀出「未讀:」。
- 把圓點抽成共用元件,下拉與通知列表頁共用同一個樣式,之後只改一處。
- 已讀判斷、未讀數、點擊後標為已讀等行為都不變。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `notifications`:「通知中心顯示與已讀狀態」規定下拉與列表頁的未讀通知以藍色圓點標示,不能只靠粗體。
## Impact
- 程式:新增共用元件(例如 `src/components/ui/unread-dot.tsx`),`src/components/shell/app-frame.tsx`(通知下拉)、`src/app/(app)/notifications/page.tsx` 改用它。
- 測試:e2e `notifications.spec.ts`(下拉中未讀通知有圓點、點開後變已讀圓點消失);360px 手機版面(`mobile-layout.spec.ts`)照舊不超出。
- 沒有資料或權限變更。
@@ -0,0 +1,24 @@
## MODIFIED Requirements
### Requirement: 通知中心顯示與已讀狀態
系統 SHALL 在頂部列顯示目前使用者的未讀通知數,並提供下拉最近通知與完整通知列表頁。每則通知 MUST 包含標題、說明、產生時間、已讀狀態與目標連結;使用者 SHALL 能標記單則或全部為已讀。頂部列的通知下拉與通知列表頁 SHALL 以相同樣式標示未讀:未讀通知在標題左側顯示藍色圓點並以淡藍底色呈現,已讀通知不顯示圓點;未讀 MUST NOT 只以粗體區分,且 SHALL 另有文字提示供螢幕報讀器讀出。
#### Scenario: 顯示未讀數
- **WHEN** 使用者有 3 則未讀通知並開啟任一頁面
- **THEN** 頂部列鈴鐺顯示未讀數 3
#### Scenario: 點擊通知前往目標並標為已讀
- **WHEN** 使用者點擊一則「待補件」通知
- **THEN** 系統導向該案件詳情頁,且該通知變為已讀、未讀數減 1
#### Scenario: 全部標為已讀
- **WHEN** 使用者在通知列表頁點選「全部標為已讀」
- **THEN** 該使用者所有通知皆為已讀,鈴鐺不再顯示未讀數
#### Scenario: 下拉以藍色圓點標示未讀
- **WHEN** 使用者有 2 則未讀、1 則已讀通知,開啟頂部列鈴鐺的通知下拉
- **THEN** 2 則未讀通知的標題左側有藍色圓點且底色為淡藍,已讀的那則沒有圓點
#### Scenario: 點開後圓點消失
- **WHEN** 使用者點開下拉中一則未讀通知,之後再開啟下拉
- **THEN** 該則通知不再顯示藍色圓點
@@ -0,0 +1,15 @@
# Tasks
## 1. 圓點
- [x] 1.1 新增 `src/components/ui/unread-dot.tsx`(`UnreadDot`,`aria-hidden`、`data-testid="unread-dot"`、`data-unread`);元件測試:未讀為 `bg-accent`、已讀保留空位不上色。
- [x] 1.2 通知列表頁改用 `UnreadDot`,畫面不變。
- [x] 1.3 鈴鐺下拉(`app-frame.tsx`)每則加 `UnreadDot` 與未讀淡藍底,保留粗體與 sr-only「未讀:」。
## 2. 測試
- [x] 2.1 e2e `notifications.spec.ts`:下拉中未讀通知的圓點 `data-unread="true"`,點開該通知後再開下拉,同一則圓點為 `data-unread="false"`。`mobile-layout.spec.ts` 照舊通過。
## 3. 驗證
- [x] 3.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `notifications.spec.ts`、`mobile-layout.spec.ts` 通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-30
@@ -0,0 +1,66 @@
## Context
- 快照(`src/server/rules/headcount.ts`):刷卡月份 M 以 `M-01` 為基準日;`ensureMonthSnapshots` 在 `monthStarted(M)` 之後懶建立;`localMembers` / `localHeadcount` 依部門歷程(`departmentMembersAt`),有正職資料時排除非正職;`syncSnapshotsFromHr(month, rosterOnFirst, tree)` 依 1 日名冊算人數與名單,離職者列出條件是 `leaveDate ≥ previousMonth(M)-01`。
- 名冊同步(`src/server/hr-sync/roster.ts` 的 `run`):抓本月與上月 1 日的名冊、組織樹,`months = [本月, 上月]`,先上月再本月呼叫 `syncSnapshotsFromHr`。
- 申請歸屬(`src/domain/attribution.ts` 的 `attributedDepartment`):`M-01` → 刷卡日 → 目前部門。建立、儲存、送出時重算;送出後固定。
- 月上限:`getDepartmentCap` 沒有快照時回 `NO_SNAPSHOT_MESSAGE`;審核頁試算(`reviewCapPreview(s)`)與首頁 `QuotaCard` 會替「已開始的月份」建立缺少的快照。
- 月結:主管提交在員工申請截止(M+1 月 20 日)之後,那時基準日(M+1 月 1 日)已過,快照一定建得出來。
## Goals / Non-Goals
**Goals:**
- 基準日一個定義(`snapshotBaseDate(M)` = M+1 月 1 日),快照、名單、歸屬、名冊同步都用它。
- 不依正職排除;留停與離職名單規則不變(以基準日為準)。
- 部署後不需要人工修資料。
**Non-Goals:**
- 實習生判斷(等 mason HR Sync 提供依日期的員工群組)。
- 改寫已送出申請的歸屬部門、已鎖定或人工調整的快照。
## Decisions
### D1 單一基準日函式
`src/domain/` 新增 `snapshotBaseDate(month)`(`YYYY-MM` → 下個月 `YYYY-MM-01`,跨年)。所有原本寫 `` `${month}-01` `` 的快照與歸屬程式改呼叫它;「已開始的月份」判斷改成 `baseDateReached(month, now, tz)`(基準日 00:00 已過)。離職名單截止日改為基準日的上個月 1 日(= 刷卡月份 1 日),維持「上個月 1 日之後離職」的語意。
### D2 申請歸屬同一基準日
`attributedDepartment` 改用 `snapshotBaseDate(cardMonth)`,退路不變(刷卡日 → 目前部門)。基準日在未來時,`departmentOn` 取「不晚於基準日的最後一筆歷程」,也就是目前所屬的部門,不需特別處理;送出後固定,之後調部門不影響(與現在相同)。
### D2a 申請開始日
`deriveDeadlines` 加上 `employeeStart`(= 基準日 00:00)。`submitApplication` 與補件重送在 guard 裡先檢查開始日、再檢查截止,訊息「此筆刷卡日期屬於 YYYY/MM,YYYY/MM/01 起才能送出。」;表單(`validateApplication` submit 模式與摘要區)顯示可送出期間並在開始日前停用「送出」。草稿照常可存。因為送出時基準日一定已到,歸屬部門一定以基準日判斷;只有草稿在基準日前顯示目前所屬部門。
補件重送:退回補件只會發生在已送出(基準日已過)的案件,不受開始日影響。
### D3 名冊同步的月份對應
`run` 仍抓本月與上月 1 日的名冊(HR 查詢日期不變),但對應的快照月份往前一個月:本月 1 日名冊 → 上個刷卡月份,上月 1 日名冊 → 上上個刷卡月份。先算較早的月份(名單的留停/離職退路取上個月名單,現有順序)。部門清理用的組織樹不變。
### D4 基準日前的月上限
`getDepartmentCap` 在基準日未到時回傳新的訊息「YYYY/MM/01 名冊確定後計算」(`capPendingMessage(month)`),不嘗試建立快照。審核頁試算、首頁額度、月結頁遇到這個訊息時照現有「無快照」的呈現顯示這句話。月結提交在申請截止後,不會遇到。
### D5 不依正職排除
`syncSnapshotsFromHr` 與 `localMembers` 不再呼叫 `fullTimeOn` / `hasEmploymentData`,在職者一律 `counted`。`recordEmployment` 照常寫入正職身分歷程(不讀取),之後恢復判斷時可參考;`excluded` 狀態保留給舊名單顯示。
### D6 部署時清掉基準日未到的快照
啟動時(`migrateOnStartup` 之後、背景排程之前)執行一次 `rebaseHeadcountSnapshots`,以 `_meta` 鍵 `headcount_base_next_month` 記錄已執行:刪除「基準日尚未到、未鎖定、沒有人工調整」的快照與其名單(就是部署當下的刷卡月份),每筆寫 `headcount.snapshot_removed` 操作紀錄(操作者「系統」,原因「人數快照基準日改為下個月 1 日」)。其他月份不刪:未鎖定、未調整的 HR 快照由下一次名冊同步依新對應更新;本系統計算的舊快照維持(只在建立時計算,與現在相同)。替代方案「重算所有未鎖定快照」被否決:本系統快照的部門歷程在部署當下不一定齊全,HR 快照也只有名冊同步能取得當日名冊。
月結試算若用到被刪的快照,`getSettlementView` 會因月上限改變顯示「請按重新計算」(現有行為);基準日未到的月份不能提交,不受影響。
## Risks / Trade-offs
- [刷卡月份當月的額度看不到] 主管在當月審核時沒有月上限試算 → 依使用者說明,申請在下個月才開始,月初快照就會建立;畫面明確說明哪一天確定。
- [每月 21 日到月底沒有可送出的月份] 前一個月已截止、當月還不能送 → 這是使用者定的制度;表單摘要清楚顯示期間。
- [e2e 的送出流程] 現在的 e2e 以「今天」為刷卡日期送出;改制後要用前一個月的日期,但每月 21 日之後前一個月已截止,送出類 e2e 會因日期而失敗 → 新增 `pin-clock` setup project:所有一般 e2e 開始前把系統時間固定在本月 10 日 12:00(台北),結束後由 teardown 清除;`clock.spec` 照舊最後執行並自行清除。月份不變,上個月的申請在可送出期間內、基準日已過,上上個月一定已截止。
- [部門月上限變化] 實習生計入、基準日後移,各部門人數與月上限會變;已提交月結的鎖定快照不受影響。
- [舊 HR 快照的名單] 名冊同步更新前,未鎖定的舊快照名單仍是 1 日名單 → 下一次同步就會更新;需要立即生效可用「下次登入時重新同步名冊」。
## Migration Plan
1. 部署:啟動時跑 `rebaseHeadcountSnapshots`(只一次)。
2. 管理者可在設定頁按「下次登入時重新同步名冊」,讓下一次登入就以新對應更新上個月與上上個月的快照。
3. 回滾:程式回到前一版;被刪除的快照會由舊規則在需要時重新建立。
@@ -0,0 +1,36 @@
## Why
兩個人數快照的問題(使用者 2026-10-30):
1. **基準日**:快照以「刷卡月份 1 日」的名冊計算,但員工是在刷卡月份的**下個月**才申請(例:10 月申請 9 月補助,11 月發放)。9/30 離職的人 10 月已經不能申請,卻仍算在 9 月的部門人數裡,墊高了部門月上限;9 月中到職的人反而不算。使用者決定改用「刷卡月份下個月 1 日」的名冊(9 月補助用 10/1 名冊),申請的歸屬部門也一起改用同一天,讓人頭與申請落在同一個部門。
2. **正職判斷**:快照只計入當日「正職」,但 HR Sync 帶 `date` 查名冊時員工群組回傳現況值,也沒有員工群組變更事件,系統無法知道某人在基準日是不是正職。使用者已在 MoonShineVFX/mason 開 issue;在那之前,快照計入基準日名冊上所有在職的人。
## What Changes
- **基準日改為刷卡月份的下個月 1 日**:刷卡月份 M 的快照依 (M+1) 月 1 日 00:00(Asia/Taipei)的名冊或部門歷程計算,例如 2026/09 的快照用 2026/10/01。基準日之前不建立該月快照,月上限顯示「YYYY/MM/01 名冊確定後計算」。
- **申請歸屬部門同一基準日**:刷卡月份 M 的申請歸屬申請人在 (M+1) 月 1 日所屬的部門;當天不屬於任何部門(例如月底離職)時用刷卡日當天的部門,仍沒有則用目前的部門。送出後不再改變(現有規則)。**BREAKING**:調部門前後的申請歸屬會和以前不同。
- **不得申請當月補助**:刷卡月份 M 的申請從 M 的下個月 1 日起才能送出(例:10 月只能申請 9 月;10/28 送出 10 月刷卡會被拒絕),截止仍是次月 20 日;草稿不受限。表單摘要顯示可送出的期間。**BREAKING**。
- **首頁額度卡改顯示上個刷卡月份**:本月刷卡的月上限要到下個月 1 日才確定,首頁員工與主管的額度卡改為顯示本月正在申請的月份(上個月)。
- **名冊同步的月份對應**:每日名冊同步原本用本月 1 日名冊算本月、上月 1 日名冊算上月;改為本月 1 日名冊算**上個月**、上月 1 日名冊算**上上個月**(未鎖定時)。
- **不再依正職身分排除**:在職者一律計入,名單不再出現沒有原因的「不計入」;留停、離職照舊列出。正職身分歷程照常記錄、暫不使用,等 HR Sync 提供依日期的員工群組後另開 change 恢復實習生判斷。
- **既有資料**:已鎖定或人工調整的快照不動。基準日尚未到的未鎖定、未調整快照(目前刷卡月份的)在部署後刪除;其他未鎖定、未調整的 HR 快照由下一次名冊同步依新規則更新。已送出的申請歸屬不變。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `headcount-snapshot`:基準日改為刷卡月份下個月 1 日;不依正職排除;月上限在基準日前顯示尚未確定;名冊同步的月份對應。
- `subsidy-application`:申請歸屬部門改為刷卡月份下個月 1 日的部門;刷卡月份當月不能送出(下個月 1 日起才可送出)。
- `dashboard`:額度卡(員工、主管)顯示上個刷卡月份的額度。
- `hr-sync`:調部門與申請歸屬的情境依新基準日;名冊同步用的 1 日名冊對應到前一個刷卡月份。
## Impact
- 程式:`src/domain/attribution.ts`(基準日)、`src/domain/deadlines.ts` 與送出檢查(申請開始日)、申請表單摘要、`src/server/rules/headcount.ts`(快照基準日、`monthStarted` → 基準日已到、名單、`localMembers` / `localHeadcount`、`syncSnapshotsFromHr` 的離職截止日、月上限訊息)、`src/server/hr-sync/roster.ts`(名冊日期與快照月份對應)、審核頁額度試算與首頁額度(`reviewCapPreview`、`QuotaCard` 的「尚未確定」)、設定頁人數快照(顯示基準日、建立按鈕條件)。
- 資料:一次性的啟動步驟刪除基準日未到的未鎖定、未調整快照(寫操作紀錄),以 `_meta` 旗標確保只跑一次。
- 測試:快照、名冊同步、歸屬、審核額度、首頁、月結的單元與整合測試;e2e 中依「本月快照」的測試(例如審核頁額度試算)要改用基準日已到的月份。
- 文件:CLAUDE.md(Applications 的歸屬、Rule parameters & headcount、HR Sync 的 snapshot 與 full-time 段落、Department settlement)、`/help`、設定頁說明文字。
@@ -0,0 +1,27 @@
## MODIFIED Requirements
### Requirement: 部門額度以參考值呈現
首頁顯示部門額度時 SHALL 呈現「目前已通過可補助總額/部門月上限」與使用百分比,並 MUST 標示「參考」及說明「實際補助於當月結算後依全體通過案件與部門額度統一確認,可能因其他申請而變動」。系統 MUST NOT 以未加上述說明的「剩餘可用額度」呈現,也 MUST NOT 暗示先申請者優先取得額度。已通過可補助總額只計入該部門該月「審核通過」以後狀態的案件。額度卡 SHALL 顯示**上個刷卡月份**——也就是員工本月正在申請的月份——的額度(使用者決定 2026-10-30:本月刷卡要到下個月 1 日名冊確定後才有月上限),卡片標題標示該月份。
#### Scenario: 顯示參考額度
- **WHEN** 今天是 2026/11/05,設計部 10 月已通過可補助總額 NT$3,250、月上限 NT$10,000
- **THEN** 額度卡標示 10 月,顯示「NT$3,250/NT$10,000(參考)」、已使用 32.5%,並附月結後確認的說明
#### Scenario: 已超過月上限
- **WHEN** 已通過可補助總額 NT$13,000 超過月上限 NT$10,000
- **THEN** 額度卡顯示超過上限,並說明月結時將由申請人平分月上限,不顯示負數剩餘額度
#### Scenario: 尚無人數快照
- **WHEN** 該月尚未建立部門人數快照
- **THEN** 額度卡顯示「本月額度尚未設定」,不顯示百分比
### Requirement: 主管區塊內容
主管區塊 SHALL 顯示所屬部門的待審件數、待補件件數、上個刷卡月份(本月正在申請的月份)的額度使用(同參考值規範)、距部長提交截止剩餘天數、目前月結狀態,以及最近 5 筆待處理案件(連往部門審核)。
#### Scenario: 待處理摘要
- **WHEN** 設計部有 3 筆待主管審核、1 筆待補件,今天 2026/11/22
- **THEN** 主管區塊顯示待審 3、待補件 1、10 月的額度使用、距 10 月月結截止剩 3 天,並列出待審案件
#### Scenario: 月結已提交
- **WHEN** 設計部 10 月月結已提交
- **THEN** 主管區塊顯示 10 月月結「已提交」,不再顯示其截止倒數
@@ -0,0 +1,121 @@
## MODIFIED Requirements
### Requirement: 建立每月人數快照
系統 SHALL 為每個部門、每個刷卡月份建立一筆計算人數快照。刷卡月份 M 的快照以**基準日**——M 的下個月 1 日 00:00(Asia/Taipei)——時隸屬該部門且在職的人數計算(使用者決定 2026-10-30:員工在刷卡月份的下個月申請,基準日前離職的人已無法申請)。在 HR Sync 能提供依日期的員工群組之前,系統 MUST NOT 依正職身分排除任何人。HR Sync 已設定時人數以 HR 名冊為準(見「由 HR 名冊自動建立與更新快照」)。快照 SHALL 在基準日之後首次需要時(查詢月上限或開啟設定頁)自動建立,管理者亦 SHALL 可手動觸發建立;基準日之前 MUST NOT 建立。在名冊同步之前建立時以本系統部門歷程計算,之後由名冊同步更新。無論何時建立,人數皆以基準日 00:00 的狀態計算。同一部門同一月份 MUST 只有一筆快照。
#### Scenario: 月初後首次需要時自動建立
- **WHEN** 2026/10/01 00:00 設計部有 20 位在職人員,2026/10/03 管理者首次開啟 2026/09 的人數快照
- **THEN** 系統建立設計部 2026/09 快照,人數為 20
#### Scenario: 月中到職不影響當月快照
- **WHEN** 2026/10/10 有一位新人加入設計部
- **THEN** 設計部 2026/09 快照人數仍為 20;這位新人計入 2026/10 快照(基準日 2026/11/01)
#### Scenario: 非正職不計入
- **WHEN** 2026/10/01 00:00 設計部的 20 位在職人員中有 2 位是工讀生,且系統已有正職身分歷程
- **THEN** 暫行規則下工讀生也計入,設計部 2026/09 快照人數為 20(等 HR Sync 提供依日期的員工群組後另行恢復排除)
#### Scenario: 刷卡月份最後一天離職
- **WHEN** 設計部一位員工 2026/09/30 為最後工作日、10/01 起離職
- **THEN** 他不計入設計部 2026/09 快照
#### Scenario: 基準日之前不建立
- **WHEN** 今天是 2026/09/20,管理者開啟 2026/09 的人數快照
- **THEN** 系統不建立快照,說明「2026/10/01 名冊確定後計算」
#### Scenario: 未設定 HR Sync
- **WHEN** 開發環境沒有 HR Sync,2026/10/01 設計部有 5 位成員
- **THEN** 設計部 2026/09 快照人數為 5
#### Scenario: 重複建立
- **WHEN** 管理者對已有快照的部門與月份再次觸發建立
- **THEN** 系統不建立第二筆快照,並提示該月份快照已存在
### Requirement: 部門月上限計算
系統 SHALL 以「快照人數 × 該月生效之部門類型每人月額度」計算部門月上限:一般部門使用一般部門每人月額度,研發部使用研發部每人月額度(規格 §7.2)。快照不存在時 MUST NOT 回傳月上限:基準日已到時 SHALL 回傳「尚未建立人數快照」;基準日未到時 SHALL 回傳「YYYY/MM/01 名冊確定後計算」(YYYY/MM/01 為基準日),審核頁的部門額度試算與首頁額度顯示同一句說明。
#### Scenario: 一般部門月上限
- **WHEN** 設計部(一般部門)2026/10 快照人數為 20,每人額度 NT$500
- **THEN** 部門月上限為 NT$10,000
#### Scenario: 研發部月上限
- **WHEN** 研發部 2026/10 快照人數為 2,每人額度 NT$1,000
- **THEN** 部門月上限為 NT$2,000
#### Scenario: 無快照
- **WHEN** 查詢一個尚未建立 2026/10 快照之部門的月上限,今天是 2026/11/03
- **THEN** 系統回傳「尚未建立人數快照」而非數值
#### Scenario: 基準日未到
- **WHEN** 今天是 2026/10/15,主管在審核頁看 2026/10 刷卡的案件
- **THEN** 部門額度試算顯示「2026/11/01 名冊確定後計算」,不顯示月上限與超額
### Requirement: 由 HR 名冊自動建立與更新快照
名冊同步(見 hr-sync)SHALL 以 HR 本月 1 日的名冊(`GET /employees?date=YYYY-MM-01`)與該日的組織結構計算**上個刷卡月份**各部門的快照人數,並 SHALL 以上個月 1 日的名冊與組織結構重算上上個刷卡月份(該月快照尚未鎖定時)。某部門的人數為:基準日 HR 狀態為在職(ACTIVE)、且該日所屬單位依該日組織結構歸到該部門(見 hr-sync「HR 部門對應與自動建立」,部底下各組的人計入部)的人數,不依正職身分排除。系統 SHALL 依計算結果建立缺少的快照;已存在且未鎖定、也沒有人工調整的快照,人數不同時 SHALL 更新為 HR 人數,並寫入操作紀錄(操作者「系統(HR 同步)」,含前後人數)。已鎖定或有人工調整的快照 MUST NOT 被覆寫。基準日 HR 名冊中沒有任何人歸到的啟用部門(含手動建立、沒有代碼的部門)SHALL 照舊以本系統部門歷程計算。
#### Scenario: 月初自動建立
- **WHEN** 2026/10/01 HR 名冊中設計部在職的有 20 位正職與 2 位工讀生,2026/10/02 第一位員工登入觸發名冊同步
- **THEN** 系統建立設計部 2026/09 快照,人數為 22,來源為 HR 名冊
#### Scenario: 1 日之後到職或離職
- **WHEN** 一位新人 2026/10/10 到職設計部、另一位設計部員工 2026/10/12 離職
- **THEN** 設計部 2026/09 快照仍為 22;兩人只影響 2026/10 快照(基準日 2026/11/01)
#### Scenario: HR 補登上個月的入職
- **WHEN** 設計部 2026/09 快照為 18 且尚未鎖定、沒有人工調整,HR 在 11/03 補登一位 2026/09/25 到職的設計部員工
- **THEN** 11/03 之後的名冊同步以 10/01 名冊把設計部 2026/09 快照更新為 19,操作紀錄有一筆 18 → 19
#### Scenario: 規則變更後未鎖定快照依新規則更新
- **WHEN** 設計部 2026/09 快照依舊規則(9/1 名冊、排除非正職)為 20、未鎖定、沒有人工調整,2026/10/01 名冊中設計部在職 22 人
- **THEN** 下一次名冊同步把快照更新為 22,操作紀錄有一筆 20 → 22;已鎖定的快照不變
#### Scenario: 已人工調整不覆寫
- **WHEN** 管理者已把研發部 2026/10 快照由 20 調整為 21,之後名冊同步算出 20
- **THEN** 快照維持 21
#### Scenario: 各組人數計入部
- **WHEN** 2026/11/01 研發部本身掛 1 位、前端組 8 位、後端組 11 位在職人員(兩組都屬研發部)
- **THEN** 研發部 2026/10 快照人數為 20
### Requirement: 快照人員名單
管理者與系統管理員 SHALL 能在後台設定頁的人數快照中,展開每個部門某月的基準日名單(標示基準日,例如 2026/09 的「2026/10/01 名單」),看出快照人數由哪些人組成。名單每列顯示員工編號、姓名與名單狀態:
- 「計入」:基準日在職,計入快照人數。
- 「不計入(留停)」:基準日 HR 狀態為留停。
- 「不計入(離職)」:基準日已離職,且離職生效日在基準日的上個月 1 日(含)之後。更早離職的人不列出。
- 「不計入」:只出現在依舊規則(排除非正職)保存、之後未再更新的名單。MUST NOT 顯示原因。
規則如下:
- 「計入」的人數 MUST 等於快照的計算人數。人工調整後的人數另以調整紀錄說明。
- 由 HR 名冊產生的快照,名單 SHALL 在名冊同步更新快照時一併保存。
- 部門歸屬與人數相同:依基準日所屬單位歸到部門。
- 留停或離職者在基準日名冊沒有所屬單位時,以上個月快照名單中的部門歸屬;仍找不到時不列出。
- 名單與快照人數一起更新:快照已鎖定或有人工調整時,名單 MUST NOT 變動。
- 本系統計算的快照(沒有 HR 名冊資料的部門),名單 SHALL 列出依部門歷程在基準日隸屬該部門的成員,全部為「計入」。不提供離職/留停原因。
- 建立於名單功能上線前、之後也未再更新的 HR 快照,SHALL 顯示「此快照沒有名單紀錄」。
- 名單 MUST NOT 出現在部門主管或員工可見的任何頁面或匯出。
#### Scenario: 展開名單看到計入與不計入
- **WHEN** 2026/10/01 HR 名冊中設計部有 20 位在職正職、1 位工讀生、1 位留停,另有 1 位 09/30 離職(離職生效日 10/01),管理者在 2026/09 的人數快照展開設計部
- **THEN** 名單標示「2026/10/01 名單」,列出 21 位「計入」(含工讀生)、1 位「不計入(留停)」、1 位「不計入(離職)」,快照人數為 21
#### Scenario: 早已離職的人不列出
- **WHEN** 某人 2026/08/15 已離職,管理者展開 2026/09 設計部名單(基準日 2026/10/01)
- **THEN** 名單沒有這個人
#### Scenario: 鎖定後名單不變
- **WHEN** 研發部 2026/10 月結已提交(快照鎖定),之後 HR 補登一位 10 月留停的研發部員工
- **THEN** 2026/10 研發部的名單與人數都維持鎖定時的內容
#### Scenario: 本系統計算的部門
- **WHEN** 管理者展開一個沒有部門代碼、由本系統計算人數的部門
- **THEN** 名單列出基準日隸屬該部門的成員,全部為「計入」,沒有離職或留停原因
#### Scenario: 主管看不到名單
- **WHEN** 部門主管直接請求後台設定頁的人數快照或其名單
- **THEN** 系統拒絕存取
#### Scenario: 舊規則的鎖定名單
- **WHEN** 設計部 2026/08 快照在規則變更前已鎖定,名單有 2 位「不計入」
- **THEN** 名單與人數維持原樣,「不計入」照舊不寫原因
@@ -0,0 +1,24 @@
## MODIFIED Requirements
### Requirement: 以 HR 為準覆寫部門歸屬
同步得到的所屬部門(依「HR 部門對應與自動建立」由 HR 所屬單位歸到的部)與系統紀錄不同時,系統 SHALL 以 HR 為準改變登入者的部門,並記錄調部門紀錄(供人數快照與申請歸屬使用)。同一部門內換單位(例如同一部內換組)MUST NOT 視為調部門。調部門紀錄的生效日 SHALL 取 HR 異動事件中最近一筆「由其他部門轉入新部門」的調動(`hr.employee.transferred`,前後單位各自歸到的部門不同)的生效日;查不到該事件、或生效日早於系統中此人最後一筆部門紀錄、或晚於當日時,以同步當日(Asia/Taipei)為生效日。既有申請的歸屬部門 MUST NOT 因調部門而改變。HR 回報登入者非在職(狀態不是 ACTIVE)或沒有組織歸屬時,或本次同步沒有取得 HR 組織結構而無法判斷所屬部門時,系統 MUST NOT 改變其部門。
#### Scenario: HR 調部門
- **WHEN** 王小明在系統中屬設計部,10/15 登入時 HR 所屬單位為研發部底下的前端組,HR 異動事件沒有這次調動
- **THEN** 王小明改屬研發部,調部門自 10/15 起生效,他已建立的申請仍歸屬設計部
#### Scenario: 以 HR 生效日記錄調部門
- **WHEN** 王小明 9/15 由設計部調至研發部(HR 異動事件生效日 2026/09/15),10/03 才登入本系統
- **THEN** 調部門自 2026/09/15 起生效,他之後補申請刷卡日期 2026/08/20 的訂閱時歸屬設計部(基準日 2026/09/01 的部門),刷卡日期 2026/09/20 的則歸屬研發部(基準日 2026/10/01 的部門)
#### Scenario: 無組織歸屬
- **WHEN** 登入者的 HR 狀態為 SUSPENDED,組織歸屬為空
- **THEN** 系統不改變其部門,照常完成登入
#### Scenario: 部內換組
- **WHEN** 王小明屬研發部,HR 把他由前端組調到後端組(同屬研發部)
- **THEN** 王小明仍屬研發部,系統不新增調部門紀錄
#### Scenario: 組織結構查詢失敗
- **WHEN** 王小明登入時 HR 組織結構查詢失敗,本人組織歸屬查詢成功
- **THEN** 系統不改變其部門,照常完成登入並記錄同步失敗
@@ -0,0 +1,59 @@
## MODIFIED Requirements
### Requirement: 申請人資訊自動帶入
系統 SHALL 在新增申請時以登入帳號自動帶入申請人姓名與歸屬部門,兩者 MUST 為唯讀,員工不得修改(規格 §9、介面規劃 §3.1)。歸屬部門 SHALL 為申請人在刷卡月份**下個月 1 日** 00:00(Asia/Taipei)時所屬的部門,與該月人數快照的基準日一致(使用者決定 2026-10-30);申請人當時不屬於任何部門(例如刷卡月份月底離職)時,改用刷卡日當天所屬的部門,仍沒有則用目前的部門。(刷卡月份當月不能送出申請,見「申請期限」,所以送出時基準日一定已到;草稿在基準日前以目前所屬的部門顯示。)尚未填刷卡日期時顯示目前的部門。可編輯的申請(草稿、待補件)變更刷卡日期時 SHALL 重新判斷歸屬部門;歸屬部門 MUST NOT 因送出後的調部門而改變。
#### Scenario: 開啟新增申請頁
- **WHEN** 員工王小明(設計部)開啟新增申請頁
- **THEN** 申請人欄位顯示「王小明」、部門欄位顯示「設計部」,且兩者皆不可編輯
#### Scenario: 竄改申請人資料的請求
- **WHEN** 送出的申請資料中夾帶不同於登入者的申請人或部門
- **THEN** 系統忽略該值,以登入帳號與基準日的所屬部門建立申請
#### Scenario: 調部門後補申請調動前的月份
- **WHEN** 王小明 2026/09/15 由設計部調至研發部,2026/10/05 新增一筆刷卡日期 2026/09/20 的申請
- **THEN** 部門欄位顯示「研發部」(2026/10/01 所屬部門),送出後由研發部主管審核並計入研發部 2026/09 月結;他也計入研發部 2026/09 快照
#### Scenario: 調部門後申請調動後的月份
- **WHEN** 同上,王小明新增一筆刷卡日期 2026/10/02 的申請
- **THEN** 部門欄位顯示「研發部」,申請歸屬研發部 2026/10
#### Scenario: 月中到職
- **WHEN** 陳小華 2026/09/10 到職加入設計部,2026/10/03 申請刷卡日期 2026/09/12 的訂閱
- **THEN** 申請歸屬 10/01 所屬的設計部,她也計入設計部 2026/09 快照
#### Scenario: 刷卡月份月底離職
- **WHEN** 林小美 2026/09/30 後離職(10/01 不屬於任何部門),帳號仍可登入時於 10/01 送出刷卡日期 2026/09/05 的申請
- **THEN** 申請歸屬刷卡日當天的部門
#### Scenario: 草稿改刷卡日期
- **WHEN** 王小明(2026/09/15 由設計部調至研發部)的草稿刷卡日期由 2026/10/02 改為 2026/08/20 並儲存
- **THEN** 部門欄位改為「設計部」(2026/09/01 所屬部門),草稿的歸屬部門同步改為設計部
#### Scenario: 送出後申請人調部門
- **WHEN** 王小明 2026/11/03 以設計部身分送出刷卡日期 2026/10/05 的申請後,於 2026/11/20 被調至研發部
- **THEN** 該申請的部門仍記為「設計部」,並計入設計部該月份的審核與月結,不隨人員調部門而移動
### Requirement: 申請期限
刷卡月份 M 的申請 SHALL 只能在 M 的下個月 1 日 00:00 起、到 M 的次月 20 日 23:59:59(Asia/Taipei,截止日取自後台截止日參數)之間送出(使用者決定 2026-10-30:員工不得申請當月補助,例如 10 月只能申請 9 月)。期限開始前 MUST 拒絕送出,期限後 MUST 拒絕送出與補件重送,且不提供逾期例外補登。草稿不受期限限制。期限(開始與截止)需在表單摘要中顯示。
#### Scenario: 期限內送出
- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/20 23:59:00 送出
- **THEN** 系統接受送出
#### Scenario: 當月不能送出
- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/10/28 送出
- **THEN** 系統拒絕送出,並顯示「此筆刷卡日期屬於 2026/10,2026/11/01 起才能送出。」;可以儲存草稿
#### Scenario: 下個月 1 日起可送出
- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/01 00:00:01 送出
- **THEN** 系統接受送出
#### Scenario: 逾期送出
- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/21 00:00:01 送出
- **THEN** 系統拒絕送出,並顯示「此筆刷卡日期屬於 2026/10,申請期限已於 2026/11/20 截止。」
#### Scenario: 逾期案件仍可存草稿
- **WHEN** 員工對已逾期月份的申請點擊「儲存草稿」
- **THEN** 系統可儲存草稿,但頁面明確提示該筆已逾期、無法送出
@@ -0,0 +1,25 @@
## 1. 基準日
- [x] 1.1 `src/domain/` 新增 `snapshotBaseDate(month)`(下個月 1 日,跨年)與基準日已到的判斷;單元測試含 12 月 → 隔年 1/1。
- [x] 1.2 `attributedDepartment` 改用基準日(退路不變);`attribution.test.ts` 與申請服務測試更新:9/15 調部門後 9 月刷卡歸新部門、8 月刷卡歸舊部門、月底離職退回刷卡日部門。
- [x] 1.3 申請開始日:`deriveDeadlines` 回傳開始日(基準日 00:00);送出在開始日前被拒(訊息「此筆刷卡日期屬於 YYYY/MM,YYYY/MM/01 起才能送出。」),草稿可存;表單摘要顯示可送出期間、開始日前停用「送出」。服務與表單測試涵蓋 10/28 送 10 月被拒、11/01 可送。
## 2. 人數快照
- [x] 2.1 `headcount.ts`:`localMembers` / `localHeadcount`、`ensureMonthSnapshots` 用基準日;基準日前不建立並回傳「YYYY/MM/01 名冊確定後計算」;`getDepartmentCap` 基準日未到時回傳同一句。不再依正職排除(`fullTimeOn` / `hasEmploymentData` 不再使用)。
- [x] 2.2 `syncSnapshotsFromHr`:基準日名冊在職者一律計入;離職名單截止日為刷卡月份 1 日;更新文件註解。
- [x] 2.3 `roster.ts`:本月 1 日名冊 → 上個刷卡月份、上月 1 日名冊 → 上上個刷卡月份(先早後晚)。
- [x] 2.4 啟動步驟 `rebaseHeadcountSnapshots`(`_meta` 旗標只跑一次):刪除基準日未到、未鎖定、未調整的快照與名單,寫 `headcount.snapshot_removed`(加入 `AUDIT_ACTIONS`)。
- [x] 2.5 更新 `headcount*.test.ts`、`roster*.test.ts`、相關 settlement/review/dashboard 測試的快照月份與基準日;新增:基準日前不建立、工讀生計入、9/30 離職不計入 9 月、名冊同步月份對應、啟動清除只跑一次且不動鎖定或調整的快照。`npm test` 通過。
## 3. 畫面與文件
- [x] 3.1 審核頁額度試算、首頁 `QuotaCard`、月結頁遇到基準日未到時顯示「YYYY/MM/01 名冊確定後計算」;設定頁人數快照顯示基準日(「2026/10/01 名單」)、說明改為「在職人員」、基準日前不提供建立。
- [x] 3.3 首頁員工與主管的額度卡改顯示上個刷卡月份(`quotaMonth`),標題標示該月份;`queries.test.ts` 涵蓋。
- [x] 3.2 `/help` 與 CLAUDE.md(Applications 歸屬、Rule parameters & headcount、HR Sync snapshot/full-time、Department settlement)更新。
## 4. 驗證
- [x] 4.0 e2e 送出流程:表單送出改用前一個月的刷卡日期(`claimDate()`);新增 `pin-clock` setup project(含 teardown),在所有一般 e2e 前把系統時間固定在本月 10 日、結束後清除(實作時改為全體固定,取代只移出送出類 spec 的做法:審核、月結測試也依賴上個月的截止尚未到);CLAUDE.md 的 e2e 說明同步更新。
- [x] 4.1 e2e:依「本月快照」的測試改用基準日已到的月份(`monthsAgo(1)` 以前),設定頁人數快照顯示基準日;受影響的 spec(settings、review、settlement、company-settlement、dashboard、visibility)通過。
- [x] 4.2 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-02
@@ -0,0 +1,29 @@
## Context
`/admin/accounts`(`src/app/(app)/admin/accounts/page.tsx`)是 Server Component,以 `?filter=all|pending|inactive` 呼叫 `listAccounts(db, filter)` 取全部列。每列內有指派部門、更新角色、停用等 Server Action 表單,帶 `back` 網址讓動作完成後回到同一個清單。
## Decisions
### D1 GET 表單 + 網址參數,伺服器端過濾
搜尋與篩選做成一個 `method="get"` 的 `<form>`(搜尋欄位、三個下拉選單、「搜尋」按鈕),送出後由頁面讀 `searchParams` 呼叫 `listAccounts(db, { filter, q, departmentId, role, hrStatus })`。不用 client 端即時過濾:清單可能上千列,而且不需要額外 JS;網址可分享、重新整理不會遺失。目前的標籤 `filter` 以隱藏欄位帶在表單裡,標籤連結也帶上其他條件。
### D2 比對規則
- `q`:去除前後空白後,員工編號、姓名、Email 任一包含即符合,不分大小寫(SQLite `lower(...) LIKE lower(?)`,`%`、`_`、`\` 先跳脫,`ESCAPE '\'`)。空字串視為沒有條件。
- `department`:部門 id,或 `none` 代表待指派部門(`users.department_id IS NULL`);選項列出所有部門(停用的部門標「(已停用)」),因為停用部門仍可能有人。
- `role`:`ROLES` 其中之一,以 `user_roles` 存在判斷。
- `hr`:`ACTIVE` / `SUSPENDED` / `OFFBOARDED` / `none`(`hr_status IS NULL`)。
- 不合法的值視為沒有該條件(不報錯)。
### D3 保留條件
`back` 改為目前完整的查詢字串(`/admin/accounts?` + 現有參數),列上動作完成後回到同樣的結果;動作端既有的 `back` 驗證(只允許 `/admin/accounts` 開頭)不變。
### D4 呈現
搜尋列在標籤下方,桌機一列排開、手機換行(`flex-wrap`,欄位 `min-w-0`),標籤與欄位都有可見 label。清單上方「共 N 筆」,有條件時加「清除條件」連結(回到 `?filter=<目前標籤>`)。
## Risks / Trade-offs
- [大量資料] 全在 SQLite 單一查詢內過濾,千筆等級沒有效能問題;不做分頁(現在也沒有)。
@@ -0,0 +1,31 @@
## Why
HR 名冊同步上線後,`/admin/accounts` 會列出全公司的人(包含還沒登入的人),清單只能用「全部/待指派部門/已停用」三個標籤切換,找一個人只能整頁捲動或用瀏覽器搜尋。使用者 2026-11-02 要求在帳號清單加上搜尋欄位與篩選。
## What Changes
- 帳號清單上方新增**搜尋欄位**:輸入員工編號、姓名或 Email 的任一部分即可找到人(不分大小寫,前後空白忽略)。
- 新增**篩選**(下拉選單,可同時使用):
- 部門:所有部門(含已停用的部門)與「待指派部門」。
- 角色:員工、部門主管、管理者、系統管理員。
- HR 狀態:在職、留停、離職、無 HR 資料。
- 原有的「全部/待指派部門/已停用」標籤保留,與搜尋、篩選同時生效(AND)。
- 條件放在網址(`?q=&department=&role=&hr=&filter=`),重新整理、分享連結、在列上指派部門或更新角色後回到同樣的結果。
- 清單上方顯示「共 N 筆」;有任何條件時提供「清除條件」。沒有結果時顯示「沒有符合條件的帳號」。
- 權限不變:只有系統管理員能開這頁。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `org-directory`:新增「帳號清單搜尋與篩選」需求。
## Impact
- 程式:`src/server/org/accounts.ts`(`listAccounts` 接受搜尋與篩選條件,在伺服器端過濾)、`src/app/(app)/admin/accounts/page.tsx`(搜尋表單、篩選、筆數、清除條件、`back` 網址保留條件)。
- 測試:`accounts` 整合測試(關鍵字比對員工編號/姓名/Email、各篩選與組合);e2e `admin.spec.ts`(搜尋、篩選、清除條件、操作後保留條件)。
- 沒有 migration、沒有新的操作紀錄(只讀)。
@@ -0,0 +1,31 @@
## ADDED Requirements
### Requirement: 帳號清單搜尋與篩選
系統管理員在帳號與角色頁 SHALL 能以搜尋欄位與篩選縮小帳號清單:
- 搜尋:員工編號、姓名或 Email 任一包含輸入文字即符合,不分大小寫,忽略前後空白。
- 部門:某一部門(含已停用的部門)或「待指派部門」。
- 角色:員工、部門主管、管理者、系統管理員。
- HR 狀態:在職、留停、離職、無 HR 資料。
搜尋、各篩選與原有的「全部/待指派部門/已停用」標籤 SHALL 同時生效(全部符合才列出)。條件 SHALL 保存在網址中,重新整理或在清單列上執行指派部門、更新角色、停用等操作後 SHALL 回到同樣條件的清單。清單 SHALL 顯示符合的筆數;有任何搜尋或篩選條件時 SHALL 提供「清除條件」。沒有符合的帳號時 SHALL 顯示「沒有符合條件的帳號」。不合法的條件值 SHALL 視為沒有該條件。
#### Scenario: 以姓名的一部分搜尋
- **WHEN** 系統管理員在搜尋欄位輸入「坤」並送出
- **THEN** 清單只列出姓名、員工編號或 Email 含「坤」的帳號,例如林坤靜,並顯示「共 1 筆」
#### Scenario: 以 Email 搜尋不分大小寫
- **WHEN** 系統管理員輸入「LINJUANG」
- **THEN** Email 為 linjuang@gmail.com 的帳號出現在清單
#### Scenario: 篩選與標籤同時生效
- **WHEN** 系統管理員選擇部門「研發部」、角色「部門主管」,並在「已停用」標籤下
- **THEN** 清單只列出研發部、有部門主管角色且已停用的帳號
#### Scenario: 操作後保留條件
- **WHEN** 系統管理員搜尋「凌」後,在結果列上按「更新角色」
- **THEN** 更新完成後回到搜尋「凌」的清單,搜尋欄位仍是「凌」
#### Scenario: 清除條件
- **WHEN** 系統管理員已設定搜尋與篩選,按「清除條件」
- **THEN** 搜尋與篩選清空,清單回到目前標籤的全部帳號
@@ -0,0 +1,14 @@
# Tasks
## 1. 伺服器端過濾
- [x] 1.1 `listAccounts(db, options)`:`filter`(原標籤)、`q`、`departmentId | "none"`、`role`、`hrStatus | "none"`,全部以 AND 組合在同一個查詢;`q` 跳脫 `%`/`_`/`\` 後以 `lower(...) LIKE` 比對員工編號、姓名、Email。新增 `parseAccountQuery(searchParams)`(不合法值丟棄)。整合測試:關鍵字比對三個欄位且不分大小寫、特殊字元不當萬用字元、各篩選、與標籤組合、空條件等於全部。
## 2. 頁面
- [x] 2.1 `admin/accounts/page.tsx`:標籤下方加 GET 搜尋表單(搜尋欄位、部門/角色/HR 狀態下拉、「搜尋」),帶目前標籤;標籤連結保留其他條件;「共 N 筆」與「清除條件」;`back` 用目前完整查詢字串。手機寬度不超出(360px)。
- [x] 2.2 e2e `admin.spec.ts`:用新建的帳號(`createEmployee`)搜尋員工編號與姓名片段、Email 大小寫、部門與角色篩選、清除條件、在結果列「更新角色」後條件仍在。`mobile-layout.spec.ts` 若有涵蓋帳號頁一併確認。
## 3. 驗證
- [x] 3.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `admin.spec.ts`、`visibility.spec.ts`、`mobile-layout.spec.ts` 通過。
@@ -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` 通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-11
@@ -0,0 +1,35 @@
## Context
附件記錄在 `attachments`:有 `size_bytes`、`superseded_at`;草稿刪除是軟刪除,`applications.deleted_at`。清除前備份由 `createBackup` 寫到 `<dirname(DATABASE_PATH)>/backups/<名稱>/`,名稱格式為 `BACKUP_NAME`(UTC 時間),超過 `BACKUP_KEEP`(預設 14)份時刪掉最舊的。每份都是資料庫加上附件目錄的完整複本。
## Decisions
### S1 用量來源
- **附件**用資料庫的 `size_bytes` 加總,不掃描附件目錄,大量檔案時也很快。
- 有效:`superseded_at IS NULL` 且所屬申請未刪除。
- 舊檔:其餘,包含已換掉、已刪除,以及已刪除草稿的附件。
- 實際檔案與資料庫記錄不一致(例如手動刪過檔)不在本次處理範圍。
- **每月新增**以附件的 `created_at` 依台北月份分組,取本月以前最近 3 個整月的平均;不足 3 個月時用現有的月份平均,沒有資料顯示「—」。一年推估 = 平均 × 12。
- **磁碟**用 `fs.promises.statfs(dirname(DATABASE_PATH))`:總容量 `blocks × bsize`,剩餘 `bavail × bsize`。取不到時,例如平台不支援,顯示「無法取得」,不讓頁面失敗。
- **資料庫**:`DATABASE_PATH` 加上 `-wal` 的檔案大小。
- **備份**:列出 `backups/` 底下符合 `BACKUP_NAME` 的目錄,遞迴加總檔案大小,依時間新到舊排列。目錄不存在時視為沒有備份。
### S2 警示門檻
剩餘空間 < 15% 時,磁碟數字旁顯示 `ToneBadge tone="warning"`「剩餘空間不足」,並提示這顆硬碟與其他網站共用,請洽平台組。15% 寫成 `src/lib` 的常數;這是技術顯示門檻,不是制度參數。
### S3 刪除備份
- Server action:`requireRole("sysadmin")`;名稱必須符合 `BACKUP_NAME`,解析後的路徑必須在 `backups/` 底下,防止路徑穿越;原因必填。
- 先在交易內記錄 `data.backup_deleted`(`targetType: "system"`,after `{ name, sizeBytes }`,comment = 原因),提交後再刪目錄。刪除失敗時回報錯誤,紀錄照樣保留,並在錯誤訊息說明「已記錄但刪除失敗」。
- UI:每列一個刪除按鈕,用 `ReasonDialog` 搭配 `confirmStep`,提示刪除後無法用這份備份還原。
### S4 時間
「本月」與月份分組用 `appNow()` 加上 `TZ_APP`;備份名稱是真實 UTC 時間,顯示時用 `formatDateTime`。
## Risks / Trade-offs
- 每次開頁都掃描備份目錄:最多 14 份,每份是資料庫加附件,檔案數多時開頁會慢一點,可接受;需要時再改成快取。
- 只刪清除前備份。`npm run backup` 的備份在 `BACKUP_DIR`(容器內預設 `./backups`,不在持久化空間),不列入。
@@ -0,0 +1,43 @@
## Why
附件存在網站自己的持久化資料夾(`/app/data/attachments`,與資料庫同一個空間),位在所有 vibe 網站共用的 `.64` 硬碟上。平台對這種存法沒有每個網站的容量上限,這裡寫滿,其他網站也會受影響。
以使用者 2026-11-11 提供的規模估算:150 人、一個 PDF 最小約 3 MB、每筆申請 2 個檔:
- 每月約 75 筆申請,附件約 0.5–1 GB,一年約 5–10 GB。
- 換掉的舊檔也保留。
- 每次「清除業務資料」前都會整份複製資料庫與附件,最多保留 14 份(`BACKUP_KEEP`),附件多了以後,這部分會是附件本身的好幾倍。
目前系統管理員完全看不到用了多少空間。使用者決定先做預防性的第一步:讓用量看得見,並能刪掉舊的清除前備份。保留規則與改用 S3 之後再議。
## What Changes
- 「系統設定 → 資料維護」(僅系統管理員)新增「儲存空間」區塊:
- **磁碟**:資料所在磁碟的總容量與剩餘空間。這顆硬碟與其他網站共用,剩餘低於 15% 時顯示警示。
- **資料庫**:資料庫檔案大小,包含 WAL。
- **附件**:有效附件的檔數與大小;已換掉或已刪除草稿的舊檔另列檔數與大小;最近 3 個整月的平均每月新增量,以及依此推估的一年用量。
- **清除前備份**:列出每份備份的時間與大小,以及合計。
- 每份清除前備份可以**刪除**:需填原因並再次確認,記錄操作紀錄 `data.backup_deleted`(備份名稱、大小、原因)。只能刪除備份目錄底下名稱格式正確的備份。
- 數字都是開頁時即時計算,不新增資料表。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `data-reset`:新增「儲存空間用量」與「刪除清除前備份」需求。
## Impact
- 程式:
- 新增 `src/server/maintenance/storage-usage.ts`(用量計算、列出與刪除備份)。
- `admin/settings` 資料維護分頁加區塊與刪除動作(`requireRole("sysadmin")`)。
- `src/lib/audit-actions.ts` 加 `data.backup_deleted`。
- 不改附件的存放方式,不刪任何附件。
- 後續(不在本次範圍):
- 保留規則:使用者答覆「核定後 3 個月」,要另開 change 確認範圍。
- 改用平台 S3。
- 異地備份:找平台組討論。
@@ -0,0 +1,23 @@
## ADDED Requirements
### Requirement: 儲存空間用量
系統 SHALL 在資料維護分頁(僅系統管理員)顯示儲存空間用量:資料所在磁碟的總容量與剩餘空間、資料庫檔案大小、有效附件與舊檔(已取代、已刪除或屬於已刪除草稿)的檔數與大小、最近 3 個整月平均每月新增的附件大小與一年推估,以及每份清除前備份的時間與大小與合計。磁碟剩餘空間低於 15% 時 SHALL 顯示警示;無法取得磁碟資訊時 SHALL 顯示「無法取得」,頁面其他內容照常顯示。非系統管理員 MUST NOT 看到此區塊。
#### Scenario: 系統管理員查看用量
- **WHEN** 系統管理員開啟資料維護分頁,系統有 10 個有效附件共 40 MB、2 個已取代附件共 6 MB 與 1 份清除前備份
- **THEN** 頁面顯示有效附件 10 個 40 MB、舊檔 2 個 6 MB,以及該份備份的時間與大小
#### Scenario: 剩餘空間不足
- **WHEN** 資料所在磁碟剩餘空間低於總容量的 15%
- **THEN** 頁面在磁碟用量旁顯示「剩餘空間不足」警示
### Requirement: 刪除清除前備份
系統管理員 SHALL 能刪除單一份清除前備份;刪除 MUST 填寫原因並再次確認,並記錄操作紀錄(備份名稱、大小與原因)。系統 MUST 只允許刪除備份目錄下名稱符合備份格式的目錄,MUST NOT 因請求內容刪除其他路徑。
#### Scenario: 刪除一份備份
- **WHEN** 系統管理員對一份清除前備份按刪除,填寫原因「空間整理」並確認
- **THEN** 該備份目錄被刪除,操作紀錄出現「刪除清除前備份」並含備份名稱、大小與原因
#### Scenario: 拒絕不合法的名稱
- **WHEN** 有人以 `../app.db` 之類的名稱呼叫刪除備份
- **THEN** 系統拒絕,不刪除任何檔案
@@ -0,0 +1,20 @@
# Tasks
## 1. 用量計算
- [x] 1.1 `src/server/maintenance/storage-usage.ts`:`storageUsage(db, options)` 回傳磁碟(可為 null)、資料庫、附件有效/舊檔、最近 3 個整月平均與一年推估、備份清單與合計(S1、S4)。
- [x] 1.2 `deleteBackup(db, audit, { backupsDir, name, reason })`:名稱與路徑檢查、操作紀錄後刪除(S3);`AUDIT_ACTIONS` 加 `data.backup_deleted`。
## 2. 畫面
- [x] 2.1 資料維護分頁加「儲存空間」區塊:磁碟、資料庫、附件、每月新增與一年推估、備份清單;剩餘 < 15% 顯示警示(S2)。
- [x] 2.2 每份備份的刪除按鈕(`ReasonDialog` + `confirmStep`),server action `requireRole("sysadmin")`。
## 3. 測試
- [x] 3.1 單元測試:有效/舊檔(含已刪除草稿)分類與加總、3 個月平均(不足 3 個月、沒有資料)、備份清單排序與大小、名稱不合法或路徑穿越被拒、刪除寫入操作紀錄、statfs 失敗回 null。
- [x] 3.2 e2e:系統管理員看得到「儲存空間」區塊;非系統管理員看不到(`settings.spec.ts`)。
## 4. 驗證
- [x] 4.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `settings.spec.ts` 通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-11
@@ -0,0 +1,57 @@
## Context
站內通知在狀態轉移的同一交易內寫入(`notifyTransition` → `notify`)。Zulip 是外部 HTTP 呼叫,不能放在 SQLite 的 `BEGIN IMMEDIATE` 交易裡(會拖住寫鎖,失敗也不該回滾業務)。公司一般員工只能建**傳入 webhook bot**:可以用 email 私訊,不能查詢使用者(mason `zulip-notify`,公司 Zulip 12.2 實測)。
## Goals / Non-Goals
- Goals:待審與退回兩種通知私訊到 Zulip;同一人多則合併;失敗不影響業務;本機與 e2e 不會真的發給同事。
- Non-Goals:其他通知類型、頻道訊息、使用者自訂開關、在 Zulip 裡回覆操作。
## Decisions
### Z1 通知表當待發佇列(outbox)
`notifications` 加三欄:`chat_status`(NULL=待發、`sent`、`skipped`、`failed`、`dry_run`)、`chat_attempts`(整數,預設 0)、`chat_at`(最後處理時間)。不另建表:一則站內通知對應最多一次 Zulip 發送,收件人、類型、案件都在同一列。
- 只有 `application.pending_review`、`application.returned` 會被派送;其他類型永遠是 NULL 且不處理。
- **不補發舊通知**:派送只處理 `created_at` 在 24 小時內的列,上線時累積的舊通知自然排除,也避免停機很久後一次送出過時訊息。
- 派送狀態是技術性欄位,不寫操作紀錄(同已讀標記)。`notifications` 已在 `BUSINESS_TABLES`,清除業務資料會一起清掉。
### Z2 每分鐘派送與合併
`startBackgroundJobs` 加每分鐘的 `runChatDispatch`(啟動時也跑一次)。每次:
1. 取待發列(`chat_status` NULL、`chat_attempts` < 3、類型符合、24 小時內)。
2. 待審通知已標為已讀(案件已審或已撤回)→ 標 `skipped`,不發。
3. 依(收件人、類型)分組,每組組成一則訊息、發一次;結果寫回組內每一列。
4. 收件人沒有 email 或帳號已停用 → `skipped`。
一分鐘的間隔就是合併的窗口:月初同時送出的多筆會落在同一則。不另設延遲。
### Z3 訊息內容
訊息是 Markdown,開頭標明「AI 補助申請系統」,連結用 `APP_URL` 組成絕對網址(沒有 `APP_URL` 視同未設定)。
- 待審(部長):`你有 N 筆待審案件`,每筆一行「申請人 · 案件編號」(重送的標「補件重送」),最後 `[前往審核](APP_URL/department/review)`。N > 10 時只列前 10 筆並註明其餘筆數。
- 退回(員工):`你有 N 筆申請被退回補件`,每筆案件編號+主管意見全文(引用區塊),最後連到該案件;多筆時連到 `/applications`。
- 意見全文從該案件最新一筆 `return` 轉移的 comment 取得(站內通知的內文是截短版)。
- 不含金額與平台費用。使用者輸入的文字把 `@` 換成全形 `@`,避免觸發提及;換行保留。
### Z4 發送與設定
`src/server/notifications/zulip.ts`:`POST {ZULIP_SITE}/api/v1/messages`,Basic auth(bot email + API key),`type=private`、`to=["email"]`,5 秒逾時。回傳 `sent | dry_run | skipped | failed`。
- 三個 `ZULIP_*` 缺任一 → 整個派送不跑(啟動時印一次警告),站內通知照舊。
- `ZULIP_DELIVERY=dry-run` → 只 `console.info` 收件人與內容,標 `dry_run`。沒設時照常發送(**不**依 `NODE_ENV` 判斷,與本專案慣例一致;本機與 e2e 沒有 `ZULIP_*` 本來就不會發)。`ZULIP_DELIVERY` 不列進 `vibe.yaml`。
- `400 Invalid email` → `skipped`(對方沒登入過 Zulip),不重試;`401` → `failed` 並記警告(金鑰錯或 bot 停用);網路錯誤、逾時、`429`、5xx → `chat_attempts + 1`,下一分鐘再試,滿 3 次標 `failed`。
- log 不印 API key,也不印訊息全文以外的個資;`console.error` 只印收件人帳號 id 與錯誤代碼。
### Z5 時間
24 小時窗口與 `chat_at` 用 `appNow()`(`created_at` 也是系統時間)。
## Risks / Trade-offs
- 最多延遲約 1 分鐘;可接受,換來合併。
- 單一實例部署,排程不會重複派送;若同一則在發送後、寫回前程式中斷,可能重發一次,可接受。
- bot 屬於建立它的人:離職時要重建 bot、更新 `.env.deploy` 並 redeploy(寫進說明)。
@@ -0,0 +1,33 @@
## Why
部長與員工目前只能在系統的鈴鐺看到「有新的待審案件」與「申請待補件」,不登入就不知道有事要處理。公司的即時通訊是 Zulip(`https://chat.moonshine.tw`),帳號與公司登入是同一個 email。使用者 2026-11-11 決定:這兩種通知同時用 Zulip 機器人私訊本人,退回意見要寫進訊息,部長同時有多筆待審時合併成一則。
## What Changes
- 站內通知「有新的待審案件/補件已重新送出」(`application.pending_review`)與「申請待補件」(`application.returned`)產生時,同時排入 Zulip 私訊,收件人是同一個人帳號上的公司 email。其他通知類型不發 Zulip。
- **合併**:背景工作每分鐘處理一次待發的 Zulip 通知,同一收件人、同一類型的多則合併成一則:
- 部長:「你有 N 筆待審案件」,附申請人與案件編號清單與前往審核的連結。
- 員工:每筆被退回的案件編號與**主管意見全文**,附查看並補件的連結。
- 發送在案件交易**提交之後**、由背景工作進行:Zulip 失敗、逾時或沒設定都不影響送出與退回。暫時性失敗最多重試 3 次,之後只記 log。
- 待發期間案件已被審核(待審通知已標為已讀)就不發,避免通知過時的事。
- 訊息不含金額;使用者輸入的意見會中和 Zulip 的 `@` 提及語法。
- 新增環境變數 `ZULIP_SITE`、`ZULIP_BOT_EMAIL`、`ZULIP_API_KEY`(三者都有才發送)與只在本機用的 `ZULIP_DELIVERY=send|dry-run`(`dry-run` 只寫 log)。沒有設定時網站照常啟動、不發 Zulip。`vibe.yaml` 的 `environment.required` 加上三個名稱,值放 `.env.deploy`,由 `/mason:deploy-site` 交給平台。
- 收件人沒有 email(名冊匯入、從未登入)或 Zulip 找不到這個人時略過,站內通知不受影響。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `notifications`:新增「待審與退回通知同步私訊 Zulip」需求。
## Impact
- 資料:`notifications` 加上 Zulip 發送狀態欄位(migration);上線前已存在的通知不補發。
- 程式:新增 `src/server/notifications/zulip.ts`(發送、訊息組成)與每分鐘的派送排程(`startBackgroundJobs`);`src/server/env.ts` 加四個選填變數;`vibe.yaml`。
- 部署:使用者在 Zulip 建傳入 webhook 機器人,把金鑰寫進 `.env.deploy`;第一次部署前要先設值。
- 說明頁(`/help`)提到會收到 Zulip 私訊。
- 不改權限:收件人與站內通知完全相同(部門主管、申請人本人)。
@@ -0,0 +1,24 @@
## ADDED Requirements
### Requirement: 待審與退回通知同步私訊 Zulip
系統產生「待審案件」(含補件重送)或「申請待補件」站內通知時,SHALL 另以公司 Zulip 機器人私訊同一位收件人,收件人以其帳號上的公司 email 對應 Zulip 帳號;其他通知類型 MUST NOT 發送 Zulip。同一收件人同類型的多則待發通知 SHALL 合併為一則訊息。退回補件的訊息 MUST 包含主管意見全文;訊息 MUST NOT 包含金額。Zulip 發送 MUST 在業務交易提交後進行,發送失敗、逾時或未設定機器人 MUST NOT 影響案件操作與站內通知。待發期間案件已離開待主管審核時,該則待審通知 MUST NOT 發送。收件人沒有 email 或 Zulip 找不到該人時,系統 SHALL 略過該則。
#### Scenario: 部長收到合併的待審私訊
- **WHEN** 設計部三位員工在同一分鐘內各送出一筆申請
- **THEN** 設計部部長在 Zulip 收到一則「你有 3 筆待審案件」私訊,列出三筆申請人與案件編號並附前往審核的連結
#### Scenario: 員工收到含意見的退回私訊
- **WHEN** 主管退回一筆案件並填寫意見「請補上刷卡帳單」
- **THEN** 申請人在 Zulip 收到私訊,內容含案件編號、意見「請補上刷卡帳單」與查看案件的連結,不含金額
#### Scenario: 已審案件不再通知
- **WHEN** 員工送出案件後,部長在 Zulip 派送前就核准了該案件
- **THEN** 部長不會收到該案件的 Zulip 待審私訊
#### Scenario: Zulip 失敗不影響操作
- **WHEN** 主管退回案件時 Zulip 無法連線
- **THEN** 退回成功、申請人照常收到站內通知,Zulip 私訊稍後重試,重試失敗只記錄於系統日誌
#### Scenario: 其他通知不發 Zulip
- **WHEN** 主管核准一筆案件
- **THEN** 申請人收到站內通知,但不會收到 Zulip 私訊
@@ -0,0 +1,22 @@
# Tasks
## 1. 設定與資料
- [x] 1.1 `src/server/env.ts` 加選填 `ZULIP_SITE`(url)、`ZULIP_BOT_EMAIL`、`ZULIP_API_KEY`、`ZULIP_DELIVERY`(`send|dry-run`);缺值不影響啟動,只警告;`.env.example` 補註解範例(不含值)。
- [x] 1.2 `notifications` 加 `chat_status`、`chat_attempts`、`chat_at`,`npm run db:generate` 產生 migration。
- [x] 1.3 `vibe.yaml` `environment.required` 加三個 `ZULIP_*` 名稱;CLAUDE.md 記錄 Zulip 通知。
## 2. 發送與派送
- [x] 2.1 `src/server/notifications/zulip.ts`:`sendZulipDirect`(Basic auth、5 秒逾時、結果分類 Z4,可注入 fetch)與訊息組成(Z3:合併、前 10 筆、意見全文、`@` 中和、無金額)。
- [x] 2.2 `runChatDispatch(db, sender, now)`:取待發列、已讀待審標 `skipped`、依收件人+類型分組發送、寫回狀態與重試次數(Z1、Z2)。
- [x] 2.3 `startBackgroundJobs` 加每分鐘排程(啟動時跑一次;未設定 `ZULIP_*` 不啟動並印一次警告)。
## 3. 測試與說明
- [x] 3.1 單元測試:合併成一則、24 小時外與其他類型不發、已審案件不發、無 email 略過、`dry-run` 不呼叫 fetch、`400 Invalid email` 略過、5xx 重試滿 3 次為 `failed`、退回意見全文與 `@` 中和、訊息不含金額。
- [x] 3.2 `/help` 說明待審與退回會同時收到 Zulip 私訊(沒登入過 Zulip 的人收不到)。
## 4. 驗證
- [x] 4.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `notifications.spec.ts`、`review.spec.ts` 照舊通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-11
@@ -0,0 +1,36 @@
## Context
`zulip-notifications` 用 `notifications` 當待發佇列,每分鐘依(收件人、類型)合併派送,`CHAT_NOTIFICATION_TYPES` 決定哪些類型要派送。期限提醒由 `runDailyReminders` 在台北 08:00 後每天產生一次,並以 `dedupe_date` 去重。
## Decisions
### R1 不核准沿用退回的訊息格式
`application.rejected` 加進 `CHAT_NOTIFICATION_TYPES`。訊息是「你有 N 筆申請不核准」,每筆列出案件編號與意見全文(引用區塊,中和 `@`),一筆時連到案件,多筆時連到 `/applications`。
意見取該案件最新一筆 `reject`、`expire_reject` 或 `overdue_reject` 轉移的 comment。系統產生的不核准(逾期、代為提交)帶的是系統說明文字,照樣列出。
### R2 月結開始提醒的日期與對象
- **日期**:對每個候選刷卡月份 M,以 `deriveDeadlines` 取得員工截止日 E 與部長截止日 D(台北日期)。今天 == E + 1 天時產生提醒。預設 E = 20 日、D = 25 日,所以是 21 日。參數改了跟著變,不寫死 21。
- **對象**:`unsubmittedDepartments(M)` 中,該月有「已送出案件」的部門。已送出案件指 `pending_review`、`needs_revision`、`approved`、`pending_settlement`,未刪除。收件人是 `resolveReviewers` 回傳的部門主管,和現有月結提醒相同。
- **類型** `reminder.settlement_open`:
- 標題「{部門} {M} 月結請於 {D} 前提交」。
- 內文「待審 a 筆、待補件 b 筆、已核准 c 筆。」,其中已核准 = `approved` + `pending_settlement`。
- 連結 `/department/settlement?department={id}&month={M}`,`targetKey` `{id}:{M}`,`dedupeDate` 今天。
- 計入 `ReminderRun.manager`,沿用 `notification.reminders_sent` 操作紀錄。
### R3 月結提醒的 Zulip 訊息
`reminder.settlement_open` 加進 `CHAT_NOTIFICATION_TYPES`。合併後每個部門一行:「設計部 2026/10:待審 a 筆、待補件 b 筆、已核准 c 筆,請於 2026/11/25 前提交」,附該部門月結頁的連結。訊息不含金額。
訊息直接取通知的標題與內文,不再另外查詢:產生時的件數就是提醒當下的狀態,和站內通知一致。
### R4 不變的部分
24 小時窗口、重試、略過規則、dry-run 都照舊。截止前 3 天、1 天的 `reminder.manager_deadline` 不加進 Zulip。
## Risks / Trade-offs
- 21 日 08:00 產生之後,部長當天才審完的案件,件數不會在提醒裡更新;可接受,連結進去看到的是最新狀態。
- 沒有案件的部門不提醒:這類部門月結本來就沒有東西要分配,不提交也不影響任何人的補助。
@@ -0,0 +1,35 @@
## Why
Zulip 私訊(`zulip-notifications`)目前只發「待審」與「退回補件」。使用者 2026-11-11 要求再加兩種:申請**不核准**時通知申請人,以及**每月 21 日**提醒部長在 25 日前提交部門月結(員工申請 20 日截止後,部長就可以開始月結)。
## What Changes
- **不核准**:站內通知「申請不核准」(`application.rejected`)也同步私訊申請人,訊息含案件編號與**主管意見全文**,同一人多筆合併成一則(和退回補件相同)。主管不核准、待補件逾期不核准、月結代為提交或自動提交時改為不核准,三種都屬於這一類,都會發。
- **月結開始提醒(新的站內通知類型)**:每月**員工申請截止日的隔天**(預設 21 日,依後台參數推算,不寫死日期),對該刷卡月份**尚未提交月結、而且有案件要月結**的部門主管產生「設計部 2026/10 月結請於 2026/11/25 前提交」提醒:
- 「有案件要月結」:該月至少一筆已送出且未撤回的案件,也就是待審、待補件、已核准、待月結這幾種。沒有任何案件的部門不提醒,避免每月對所有部長發空的通知。
- 內容列出待審、待補件與已核准的件數,不含金額,連到該部門該月的月結頁。
- 站內通知和 Zulip 私訊都發。跟其他期限提醒一樣,同一天只產生一次,08:00 後產生。
- 一個人管多個部門時,Zulip 合併成一則,列出各部門。
- 現有的截止前 3 天、1 天月結提醒(22 日、24 日)維持只發站內通知,不發 Zulip。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `notifications`:
- 「待審與退回通知同步私訊 Zulip」加上不核准與月結開始提醒。
- 新增「月結開始提醒」需求。
## Impact
- 程式:
- `src/lib/notifications.ts`:新增類型 `reminder.settlement_open`,`CHAT_NOTIFICATION_TYPES` 加兩種。
- `src/server/notifications/reminders.ts`:產生月結開始提醒。
- `src/server/notifications/zulip.ts`:組成不核准與月結提醒的訊息。
- 資料:`notifications.type` 是文字 enum,只改 TypeScript 型別,不需要 migration。
- 說明頁(`/help`)通知段落同步更新。
- 不改權限:收件人與現有的不核准通知、月結提醒相同。
@@ -0,0 +1,45 @@
## MODIFIED Requirements
### Requirement: 待審與退回通知同步私訊 Zulip
系統產生「待審案件」(含補件重送)、「申請待補件」、「申請不核准」或「月結開始提醒」站內通知時,SHALL 另以公司 Zulip 機器人私訊同一位收件人,收件人以其帳號上的公司 email 對應 Zulip 帳號;其他通知類型 MUST NOT 發送 Zulip。同一收件人同類型的多則待發通知 SHALL 合併為一則訊息。退回補件與不核准的訊息 MUST 包含主管意見全文;訊息 MUST NOT 包含金額。Zulip 發送 MUST 在業務交易提交後進行,發送失敗、逾時或未設定機器人 MUST NOT 影響案件操作與站內通知。待發期間案件已離開待主管審核時,該則待審通知 MUST NOT 發送。收件人沒有 email 或 Zulip 找不到該人時,系統 SHALL 略過該則。
#### Scenario: 部長收到合併的待審私訊
- **WHEN** 設計部三位員工在同一分鐘內各送出一筆申請
- **THEN** 設計部部長在 Zulip 收到一則「你有 3 筆待審案件」私訊,列出三筆申請人與案件編號並附前往審核的連結
#### Scenario: 員工收到含意見的退回私訊
- **WHEN** 主管退回一筆案件並填寫意見「請補上刷卡帳單」
- **THEN** 申請人在 Zulip 收到私訊,內容含案件編號、意見「請補上刷卡帳單」與查看案件的連結,不含金額
#### Scenario: 員工收到含意見的不核准私訊
- **WHEN** 主管不核准一筆案件並填寫意見「此訂閱與工作無關」
- **THEN** 申請人在 Zulip 收到私訊,內容含案件編號、意見「此訂閱與工作無關」與查看案件的連結,不含金額
#### Scenario: 已審案件不再通知
- **WHEN** 員工送出案件後,部長在 Zulip 派送前就核准了該案件
- **THEN** 部長不會收到該案件的 Zulip 待審私訊
#### Scenario: Zulip 失敗不影響操作
- **WHEN** 主管退回案件時 Zulip 無法連線
- **THEN** 退回成功、申請人照常收到站內通知,Zulip 私訊稍後重試,重試失敗只記錄於系統日誌
#### Scenario: 其他通知不發 Zulip
- **WHEN** 主管核准一筆案件,或系統產生月結截止前 3 天的提醒
- **THEN** 收件人收到站內通知,但不會收到 Zulip 私訊
## ADDED Requirements
### Requirement: 月結開始提醒
系統 SHALL 於每個刷卡月份的員工申請截止日隔天(預設次月 21 日,依後台參數推算),對尚未提交該月月結、且該月有已送出案件(待審、待補件、已核准或待月結)的部門主管產生提醒,內容 MUST 包含月結提交截止日與待審、待補件、已核准件數,MUST NOT 包含金額,並連結至該部門該月的月結頁。該月沒有已送出案件或已提交月結的部門 MUST NOT 提醒;同一天重複執行 MUST NOT 產生重複提醒。
#### Scenario: 21 日提醒部長月結
- **WHEN** 今日為 2026/11/21,設計部尚未提交 2026/10 月結,該月有 1 筆待審、3 筆已核准
- **THEN** 設計部主管收到「設計部 2026/10 月結請於 2026/11/25 前提交」提醒,內容含「待審 1 筆、待補件 0 筆、已核准 3 筆」,並同時收到 Zulip 私訊
#### Scenario: 沒有案件的部門不提醒
- **WHEN** 今日為 2026/11/21,行銷部 2026/10 沒有任何已送出案件
- **THEN** 行銷部主管不會收到月結開始提醒
#### Scenario: 非截止隔天不提醒
- **WHEN** 今日為 2026/11/20 或 2026/11/22
- **THEN** 系統不產生月結開始提醒
@@ -0,0 +1,20 @@
# Tasks
## 1. 不核准
- [x] 1.1 `CHAT_NOTIFICATION_TYPES` 加 `application.rejected`;`zulip.ts` 組成「N 筆申請不核准」訊息,意見取最新一筆 reject/expire_reject/overdue_reject 的 comment(R1)。
## 2. 月結開始提醒
- [x] 2.1 `NOTIFICATION_TYPES` 加 `reminder.settlement_open`(通知列表的類型顯示若有對照表一併補上)。
- [x] 2.2 `runDailyReminders`:今天 == 員工截止日 + 1 天時,對未提交且有已送出案件的部門主管產生提醒(R2)。
- [x] 2.3 `CHAT_NOTIFICATION_TYPES` 加 `reminder.settlement_open`;`zulip.ts` 合併成每部門一行並附連結(R3)。
## 3. 測試與說明
- [x] 3.1 單元測試:不核准私訊含意見全文;21 日產生提醒,20 日、22 日不產生;已提交或沒有已送出案件的部門不提醒;同日重跑不重複;件數正確;管理兩個部門的部長收到一則合併的 Zulip 訊息;`reminder.manager_deadline` 仍不發 Zulip。
- [x] 3.2 `/help` 通知段落加上不核准與 21 日月結提醒;CLAUDE.md 更新。
## 4. 驗證
- [x] 4.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `notifications.spec.ts` 照舊通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-12
@@ -0,0 +1,62 @@
## Context
- 附件:`attachments`(`application_id`、`size_bytes`、`storage_key`、`sha256`、`superseded_at`),檔案在 `ATTACHMENTS_DIR/<storage_key>`,只經 `GET /api/attachments/:id`(`authorizeAttachmentRead`)讀取。替換/刪除只標記 `superseded_at`,檔案保留。
- 案件歸屬:`applications.department_id` + `application_month`(刷卡月份 `YYYY-MM`)。
- 月結:`department_settlements`(department_id, month)狀態 `open → submitted → finalized`(舊資料 `paid`),`finalized_at` 是核定當下的系統時間。
- 背景工作:`startBackgroundJobs`(`src/server/startup.ts`)已有每小時的月結、提醒排程。
## Decisions
### R1 到期判斷(以部門月份為單位)
對每個 (department_id, application_month) 有尚未刪除附件的組合:
1. 該部門月份的月結為 `finalized` 或 `paid`:`addMonths(localDate(finalized_at), 3)` ≤ 今天(台北日期)即到期。月底日期加月份時取當月最後一天(例:11/30 + 3 個月 = 2/28)。
2. 沒有 `submitted`/`finalized`/`paid` 的月結,且該部門月份**沒有**狀態為待主管審核、待補件、審核通過、待月結、已提交的案件(只剩不核准、撤回、草稿、已刪除草稿):今天 ≥ M+5 月 1 日即到期(例:2026-10 → 2027-03-01)。這是正常流程「M+2 月初核定 + 3 個月」的時間點。
3. 其他(月結進行中、被退回、還有待審案件):不到期,之後每天再判斷。
`paid` 的 `finalized_at` 若為空,改用 `paid_at`。兩者都空則不處理(不猜)。
保存月數(3)與無月結時的月數(5)放在 `src/lib/attachment-retention.ts` 的常數。這是使用者決定的保存政策,暫不做成制度參數;要調整時再另開 change。
### R2 用真實時間判斷
「今天」用**真實時間**(`realNow()`),不用系統時間:系統管理員在正式環境調整系統時間(最多 ±366 天)做試算時,不能因此提早刪掉真的檔案。`retention.ts` 以 `realNow()` 取真實時間(不直接 `new Date()`,不需加入 `clock-usage.test.ts` 允許清單)。
`finalized_at` 是系統時間:若核定時系統時間被往後調,核定日會比真實日期晚,刪除跟著延後(安全方向);往前調會提早,但仍受「核定日 + 3 個月」限制,可接受。
### R3 刪除流程
每個到期的部門月份:
1. 交易內:將該部門月份所有案件中 `purged_at IS NULL` 的附件設 `purged_at = 真實時間`,並記錄 `attachment.retention_purged`(`targetType: "department"`,`targetId` = 部門 id,after `{ month, files, bytes, rule: "finalized" | "no_settlement" }`,操作者 `SYSTEM_ACTOR`「系統(附件保存期限)」)。
2. 提交後逐一刪檔(`removeStoredFile`,檔案不存在視為成功)。刪檔失敗只記 log(不印檔名以外的內容),記錄仍為已刪除;檔案留在硬碟上,不影響功能。
3. 一次執行最多處理 50 個部門月份,避免啟動時卡太久,剩下的下一輪處理。
標記與刪檔分開:先提交記錄再刪檔,失敗時最多是硬碟多留一個檔,不會出現記錄指向不存在的檔卻仍可預覽的情況。
### R4 排程
`startRetentionScheduler(db)`:啟動時與每小時執行一次 `runAttachmentRetention`。判斷是冪等的(已刪除的不再出現),所以不需要另記「今天跑過」。只在 `startBackgroundJobs` 中啟動,與其他排程一致。
### R5 已刪除附件的顯示與讀取
- `authorizeAttachmentRead`:`purged_at` 不為空時回傳 null → 404,與不存在相同。
- `listActiveAttachments`/`AttachmentInfo` 加 `purgedAt`。附件 UI(`FilePreview` 或呼叫端)遇到已刪除時顯示檔名與「附件已依保存期限刪除(YYYY/MM/DD)」,不顯示預覽與下載連結。
- 附件完整性(`attachmentCompleteness`)不變:已刪除的案件都已結束,不會再送出。
- 疑似重複判斷用 `sha256`,記錄保留,不受影響。
### R6 儲存空間用量
`attachmentTotals`:有效、舊檔都排除 `purged_at` 不為空;另回傳 `purged: { count, bytes }`,畫面列為「已依保存期限刪除」。每月新增的平均照舊(以上傳時間計,代表成長速度)。
### R7 清除業務資料
`attachments` 已在 `BUSINESS_TABLES`,不用改。清除時刪檔會遇到已刪除的檔案,`removeStoredFile` 已忽略不存在的檔。
## Risks / Trade-offs
- **刪除無法復原。** 稽核或爭議需要原始檔時,只能從清除前備份找(若還在)。這是使用者接受的取捨。
- 被退回後重新開啟的月結(`finalized` 不可退回,所以不會發生):核定是終點,不會有核定後再變動的情況。
- 部門改名或停用不影響判斷(用 department_id)。
- 系統沒有異地備份;刪除前不另外通知。
@@ -0,0 +1,43 @@
## Why
附件存在網站自己的持久化資料夾(`/app/data/attachments`),位在所有 vibe 網站共用的 `.64` 硬碟上,沒有每個網站的容量上限。以 150 人、一個 PDF 至少 3 MB 估算,一年約 5–10 GB,而且目前附件永遠保留(換掉的舊檔也留著)。
`storage-usage-overview` 已讓用量看得見。使用者 2026-11-11/11-12 決定保留規則(B 方案):
- 部門月結**最終核定滿 3 個月**後,該部門該月份的附件全部刪除。
- 範圍包含退回、不核准的案件,以及換掉的舊檔。
- 由系統**每天自動**執行,不需要人去按。
- 整個月份都沒有可月結案件(例如全部不核准)、因此沒有核定日的部門月份:刷卡月份往後算 5 個月後刪除。
## What Changes
- 新增每日自動清理:符合保存期限的部門月份,刪除其所有案件(任何狀態,含草稿、撤回、已刪除草稿)的附件實體檔案。
- 有月結且已最終核定(含舊資料的「已發放」):核定日(台北日期)加 3 個月當天起。
- 沒有任何可月結案件(只剩不核准、撤回、草稿)且沒有已提交以上的月結:刷卡月份 M 往後 5 個月,即 M+5 月 1 日起。
- 月結還在進行中(未提交、已提交未核定、被退回)一律不刪。
- 附件**記錄保留**,只刪檔案:`attachments` 新增 `purged_at`。檔名、大小、雜湊值都留著,疑似重複判斷照常可用。
- 刪除後畫面上的附件位置顯示「附件已依保存期限刪除(YYYY/MM/DD)」,不提供預覽與下載;`/api/attachments/:id` 回 404。
- 每個部門月份清理一次記一筆操作紀錄 `attachment.retention_purged`(部門、月份、檔數、大小)。
- 「儲存空間」區塊:附件數字不再計入已刪除的檔案,另列「已依保存期限刪除」的檔數與大小。
- 說明頁加上附件保存期限的說明。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `application-attachments`:新增「附件保存期限」需求;修改「替換與刪除限制」(舊檔保留到保存期限為止)。
- `data-reset`:修改「儲存空間用量」(已依保存期限刪除的附件另列,不計入有效與舊檔)。
## Impact
- 資料庫:`attachments.purged_at`(migration)。
- 程式:
- 新增 `src/server/attachments/retention.ts`(找出到期的部門月份、標記與刪檔)與每小時排程(當天已處理過的不重做)。
- 附件讀取、`listActiveAttachments`、附件 UI(申請詳情、審核、全公司月結詳情)處理已刪除狀態。
- `storage-usage.ts` 調整統計;`audit-actions.ts` 加動作。
- 刪除無法復原。清除前備份裡的複本不受影響,會隨備份輪替(最多 14 份)或手動刪除而消失。
- 不在本次範圍:改用 S3、保存期限做成後台可設定、刪除前通知。
@@ -0,0 +1,41 @@
## ADDED Requirements
### Requirement: 附件保存期限
系統 SHALL 每天自動刪除超過保存期限的附件檔案,以部門與刷卡月份為單位:該部門該月份的月結最終核定(含舊資料的已發放)滿 3 個月當天起,刪除該部門該月份所有案件(任何狀態,含退回、不核准、撤回、草稿)的附件,包含已被取代的舊檔;該部門該月份沒有任何可月結的案件(只剩不核准、撤回或草稿)且沒有已提交以上的月結時,自刷卡月份往後第 5 個月的 1 日起刪除。月結尚未最終核定、或仍有待審、待補件、審核通過、待月結、已提交的案件時 MUST NOT 刪除。到期判斷 MUST 使用真實時間,不受系統時間調整影響。附件記錄(檔名、大小、雜湊值)SHALL 保留並標記刪除時間;已刪除的附件 MUST NOT 可預覽或下載,畫面 SHALL 顯示「附件已依保存期限刪除」與刪除日期。每個部門月份的清理 SHALL 記錄一筆操作紀錄(部門、月份、檔數、大小)。
#### Scenario: 核定滿 3 個月後刪除
- **WHEN** 設計部 2026/10 的月結在 2026/12/05 最終核定,系統在 2027/03/05 執行每日清理
- **THEN** 設計部 2026/10 所有案件的附件檔案(含不核准案件與被取代的舊檔)被刪除,操作紀錄記下部門、月份、檔數與大小
#### Scenario: 未滿 3 個月不刪除
- **WHEN** 設計部 2026/10 的月結在 2026/12/05 最終核定,系統在 2027/03/04 執行每日清理
- **THEN** 該月份的附件都保留
#### Scenario: 月結尚未核定不刪除
- **WHEN** 研發部 2026/10 的月結已提交但尚未最終核定,已超過刷卡月份 5 個月
- **THEN** 系統不刪除研發部 2026/10 的附件
#### Scenario: 整月只有不核准案件
- **WHEN** 業務部 2026/10 只有不核准的案件、沒有已提交的月結,系統在 2027/03/01 執行每日清理
- **THEN** 業務部 2026/10 的附件被刪除
#### Scenario: 系統時間被往後調整
- **WHEN** 系統管理員把系統時間調到一年後,真實時間距最終核定未滿 3 個月
- **THEN** 系統不刪除該月份的附件
#### Scenario: 查看已刪除的附件
- **WHEN** 管理者開啟附件已依保存期限刪除的案件
- **THEN** 附件位置顯示檔名與「附件已依保存期限刪除(2027/03/05)」,沒有預覽;直接請求該附件網址得到與檔案不存在相同的結果
## MODIFIED Requirements
### Requirement: 替換與刪除限制
附件 SHALL 只在申請狀態為「草稿」或「待補件」時可由申請人替換或刪除;其他狀態的附件 MUST 為唯讀。替換或刪除 SHALL 寫入操作紀錄,被取代或刪除的檔案 SHALL 保留於系統以供稽核,直到附件保存期限屆滿,但 MUST NOT 再出現在一般使用者的附件清單。
#### Scenario: 待補件時替換
- **WHEN** 案件狀態為待補件,員工以新的 card_statement.pdf 替換刷卡帳單
- **THEN** 案件顯示新檔案,操作紀錄記下替換的操作者與時間,舊檔案保留供稽核
#### Scenario: 待審核時嘗試刪除
- **WHEN** 案件狀態為待主管審核,員工嘗試刪除 Invoice
- **THEN** 系統拒絕,畫面不提供刪除按鈕
@@ -0,0 +1,16 @@
## MODIFIED Requirements
### Requirement: 儲存空間用量
系統 SHALL 在資料維護分頁(僅系統管理員)顯示儲存空間用量:資料所在磁碟的總容量與剩餘空間、資料庫檔案大小、有效附件與舊檔(已取代、已刪除或屬於已刪除草稿)的檔數與大小、已依保存期限刪除的附件檔數與大小(不計入有效與舊檔)、最近 3 個整月平均每月新增的附件大小與一年推估,以及每份清除前備份的時間與大小與合計。磁碟剩餘空間低於 15% 時 SHALL 顯示警示;無法取得磁碟資訊時 SHALL 顯示「無法取得」,頁面其他內容照常顯示。非系統管理員 MUST NOT 看到此區塊。
#### Scenario: 系統管理員查看用量
- **WHEN** 系統管理員開啟資料維護分頁,系統有 10 個有效附件共 40 MB、2 個已取代附件共 6 MB 與 1 份清除前備份
- **THEN** 頁面顯示有效附件 10 個 40 MB、舊檔 2 個 6 MB,以及該份備份的時間與大小
#### Scenario: 已依保存期限刪除的附件另列
- **WHEN** 系統有 5 個附件共 15 MB 已依保存期限刪除
- **THEN** 頁面另列「已依保存期限刪除」5 個 15 MB,有效附件與舊檔的數字不包含它們
#### Scenario: 剩餘空間不足
- **WHEN** 資料所在磁碟剩餘空間低於總容量的 15%
- **THEN** 頁面在磁碟用量旁顯示「剩餘空間不足」警示
@@ -0,0 +1,23 @@
## 1. 資料與規則
- [x] 1.1 `attachments` 加 `purged_at`,`npm run db:generate` 產生 migration
- [x] 1.2 `src/lib/attachment-retention.ts`:保存月數 3、無月結月數 5、`addMonths` 月底取最後一天;`AUDIT_ACTIONS` 加 `attachment.retention_purged`
## 2. 每日清理
- [x] 2.1 `src/server/attachments/retention.ts`:`dueRetentionMonths(db, today)` 依 R1 找出到期的部門月份(最多 50 個)
- [x] 2.2 `runAttachmentRetention(db, root, realNow)`:交易內標記 `purged_at` 並記操作紀錄,提交後刪檔,失敗只記 log
- [x] 2.3 `startRetentionScheduler`:啟動時與每小時執行,接到 `startBackgroundJobs`(以 `realNow()` 取真實時間,不需加入 `clock-usage.test.ts` 允許清單)
- [x] 2.4 單元測試:核定滿/未滿 3 個月、月底加月份、`paid` 舊資料、月結進行中/已提交不刪、整月只有不核准(M+5)、仍有待審案件不刪、含被取代舊檔與已刪除草稿、冪等、刪檔失敗仍標記
## 3. 顯示與讀取
- [x] 3.1 `authorizeAttachmentRead` 對已刪除附件回傳 null(404);`listActiveAttachments`/`AttachmentInfo` 帶 `purgedAt`
- [x] 3.2 附件 UI(申請詳情、審核清單與詳情、全公司月結詳情)顯示「附件已依保存期限刪除(日期)」,不提供預覽
- [x] 3.3 `storageUsage` 排除已刪除附件並回傳 `purged`;資料維護分頁顯示「已依保存期限刪除」
- [x] 3.4 說明頁加附件保存期限說明(不得出現「全額」);CLAUDE.md 補充
## 4. 驗證
- [x] 4.1 E2E:已刪除附件的案件顯示提示、附件網址 404(以 `tests/e2e/db.ts` 直接標記 `purged_at`)
- [x] 4.2 `npm run lint`、`typecheck`、`format:check`、`npm test`
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-12
@@ -0,0 +1,26 @@
## Why
申請表的「工作用途說明」少於 20 字時,欄位下方會出現「建議至少 20 字,並具體描述與工作的關聯」。這個提示不擋送出,但員工看到的感覺是「至少要寫 20 字」,對一句話就能說清楚的用途來說負擔太重。使用者 2026-11-12 決定:不要硬性限制,只是不要讓人誤以為「至少要寫 20 字」。
## What Changes
- 提示文字不再出現字數門檻,改為「請具體說明與工作的關聯」。
- 顯示提示的門檻從 20 字降為 10 字:已開始輸入且少於 10 字才顯示,寫了一句完整的話就不會再看到提示。
- 行為不變:仍然只是提示、不阻擋送出;空白仍拒絕送出;上限仍是 500 字。
- 「成果產出」沒有建議字數提示,不受影響。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `subsidy-application`:修改「工作用途與成果產出」(建議字數提示不寫數字,顯示門檻 20 字改為 10 字)。
## Impact
- 程式:`src/lib/application-form.ts` 的 `PURPOSE_SUGGESTED_MIN` 與 `PURPOSE_SHORT_HINT`。申請表元件直接引用這兩個常數,不需修改。
- 測試:`src/lib/application-form.test.ts`、`tests/e2e/applications.spec.ts` 的 20 字案例改為 10 字。
- 不需要 migration,不影響已送出的案件。
@@ -0,0 +1,20 @@
## MODIFIED Requirements
### Requirement: 工作用途與成果產出
系統 SHALL 要求填寫工作用途說明與成果產出,兩者皆為必填;系統 MUST 提供範例提示與字數計數;工作用途說明少於 10 字時 MUST 提示可再具體描述,提示 MUST NOT 寫出最少字數,且 MUST NOT 阻擋送出;超過 500 字 MUST 拒絕。成果產出 MAY 另附成果連結,連結若有填寫 MUST 為有效 URL。
#### Scenario: 用途空白
- **WHEN** 員工未填工作用途說明即送出
- **THEN** 系統拒絕送出,並顯示「請完成「工作用途說明」後再送出。」
#### Scenario: 用途少於建議字數
- **WHEN** 員工填寫 6 個字的用途
- **THEN** 系統在欄位下方提示「請具體說明與工作的關聯」,且不阻擋送出
#### Scenario: 用途達到建議字數
- **WHEN** 員工填寫 10 個字的用途
- **THEN** 系統不顯示建議字數提示
#### Scenario: 超過字數上限
- **WHEN** 員工填寫 501 字的成果產出
- **THEN** 系統拒絕送出並提示上限 500 字
@@ -0,0 +1,10 @@
## 1. 修改
- [x] 1.1 `src/lib/application-form.ts`:`PURPOSE_SUGGESTED_MIN` 改為 10,`PURPOSE_SHORT_HINT` 改為「請具體說明與工作的關聯」
- [x] 1.2 `src/lib/application-form.test.ts`:測試名稱「少於 20 字不阻擋」改為 10 字
- [x] 1.3 `tests/e2e/applications.spec.ts`:提示文字改為新文字,並補 10 字時提示消失的檢查
## 2. 驗證
- [x] 2.1 `npm run lint`、`typecheck`、`format:check`、`npm test`
- [x] 2.2 E2E:`tests/e2e/applications.spec.ts`
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-13
@@ -0,0 +1,40 @@
## Why
申請送出後、主管審核前,員工其實可以修改,做法是先「撤回」讓案件回到草稿再編輯。但目前:
- 待主管審核的申請詳情沒有「編輯」按鈕,只有「撤回申請」;「撤回」聽起來像是取消申請,看不出撤回是為了修改。
- 說明文字「主管審核前可撤回修改:按上方「撤回申請」,案件回到草稿,修改後再送出。」需要員工自己把「撤回」和「修改」串起來。
- 撤回後停在詳情頁,還要再找「編輯申請」。
結果有同事以為送出後就不能修改(使用者 2026-11-13 回報)。
## What Changes
- **按鈕名稱直接說用途**:
- 申請詳情頁首的「撤回申請」改為「撤回並修改」。
- 「我的申請」清單每列的「撤回」改為「撤回修改」(無障礙名稱「撤回修改 AI-…」)。
- **撤回後直接進入編輯頁**:確認撤回成功後,導向該案件的編輯頁並提示「已撤回,案件回到草稿,修改後請再按「送出」」。
- **確認視窗說清楚會發生什麼**:
- 標題「撤回並修改這筆申請?」,確認按鈕「撤回並修改」。
- 說明「案件會回到草稿並打開編輯頁,改好後請再按「送出」;沒有再送出就不會進入主管審核。審核紀錄會保留「撤回」,之後這筆申請無法刪除。」
- **詳情頁的引導文字**:
- 待主管審核且可撤回時:「要修改這筆申請?主管審核前都可以:按上方「撤回並修改」,改好後再送出。」
- 送出成功的提示:「已送出申請,等待主管審核。主管審核前仍可按「撤回並修改」修改內容。」
- **說明頁新增「送出後還能修改嗎?」**,依狀態說明:草稿可直接編輯;待主管審核可「撤回並修改」;待補件按「編輯並重新送出」;審核通過、不核准之後無法修改。
- 撤回的規則不變:只有待主管審核、且月結未鎖定時可以撤回;無法撤回時的原因說明不變。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `application-lifecycle`:修改「撤回失敗與無法撤回的說明」(按鈕名稱、撤回後進入編輯頁、引導文字)。
## Impact
- 程式:`src/app/(app)/applications/withdraw-button.tsx`(名稱、確認視窗、成功後導向編輯頁)、`src/app/(app)/applications/[id]/page.tsx`(引導文字與送出提示)、`src/app/(app)/help/page.tsx`。
- 測試:`tests/e2e/draft-and-withdraw.spec.ts`、`tests/e2e/applications.spec.ts` 的按鈕名稱與文字。
- 不改後端、不需要 migration;操作紀錄與審核紀錄的「撤回」字樣不變。
@@ -0,0 +1,32 @@
## MODIFIED Requirements
### Requirement: 撤回失敗與無法撤回的說明
可撤回的案件 SHALL 在「我的申請」清單的該列提供「撤回修改」,申請詳情 SHALL 在頁首提供唯一一個「撤回並修改」,並在狀態說明下方以文字說明主管審核前都可以按「撤回並修改」修改後再送出(不另放按鈕);送出成功的提示 SHALL 說明主管審核前仍可按「撤回並修改」修改內容。確認視窗 SHALL 說明案件會回到草稿並打開編輯頁、改好後須再送出才會進入主管審核。撤回成功後 SHALL 導向該案件的編輯頁並提示修改後須再送出。申請詳情與清單的撤回 SHALL 只在撤回會被接受時顯示(與撤回時的檢查相同,包括月結鎖定)。案件為「待主管審核」卻無法撤回時,申請詳情 SHALL 說明原因(例如「該月月結已提交,無法撤回」)。撤回請求失敗時(包括狀態已變更、登入逾時或連線錯誤),確認視窗 SHALL 顯示錯誤訊息,MUST NOT 沒有任何回應。
#### Scenario: 從清單撤回
- **WHEN** 員工在「我的申請」看到主管尚未處理的待審核案件 AI-202610-0006,按該列的「撤回修改」並確認
- **THEN** 案件回到草稿,畫面進入該案件的編輯頁,並提示修改後請再按「送出」
#### Scenario: 送出後立即看到撤回
- **WHEN** 員工送出申請後回到申請詳情
- **THEN** 成功提示說明主管審核前仍可按「撤回並修改」修改內容,詳情頁首有「撤回並修改」,狀態說明下方說明修改方式
#### Scenario: 從詳情撤回並修改
- **WHEN** 員工在待主管審核案件的詳情按「撤回並修改」並確認
- **THEN** 案件回到草稿,畫面進入該案件的編輯頁
#### Scenario: 主管已處理
- **WHEN** 員工送出的案件已被主管核准
- **THEN** 申請詳情顯示「審核通過」,不顯示「撤回並修改」
#### Scenario: 月結已提交
- **WHEN** 待主管審核的案件因部門調整歸到月結已提交的部門月份
- **THEN** 申請詳情不顯示「撤回並修改」,並說明「該月月結已提交,無法撤回」
#### Scenario: 撤回時發生錯誤
- **WHEN** 員工在確認視窗按「撤回並修改」時登入已逾時或連線中斷
- **THEN** 確認視窗顯示錯誤訊息,案件維持原狀態,不進入編輯頁
#### Scenario: 撤回時主管剛核准
- **WHEN** 員工開著申請詳情時主管核准了案件,員工再於確認視窗按「撤回並修改」
- **THEN** 確認視窗顯示「案件狀態已變更,請重新整理」
@@ -0,0 +1,10 @@
## 1. 畫面
- [x] 1.1 `withdraw-button.tsx`:按鈕「撤回並修改」/清單「撤回修改」(aria-label「撤回修改 AI-…」);確認視窗標題、說明與確認按鈕;成功後導向 `/applications/:id/edit` 並提示「已撤回,案件回到草稿,修改後請再按「送出」」
- [x] 1.2 `applications/[id]/page.tsx`:送出成功提示與 `withdraw-hint` 改為新文字
- [x] 1.3 說明頁新增「送出後還能修改嗎?」(依狀態說明;不得出現「全額」)
## 2. 驗證
- [x] 2.1 E2E:`draft-and-withdraw.spec.ts`、`applications.spec.ts` 更新按鈕名稱與文字,並檢查撤回後進入編輯頁(清單與詳情各一)
- [x] 2.2 `npm run lint`、`typecheck`、`format:check`、`npm test`
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-13
@@ -0,0 +1,43 @@
## Context
`storageUsage`(`src/server/maintenance/storage-usage.ts`)目前用 `monthlyAverage` 算最近 3 個整月的平均新增量,`StorageCard`(`/admin/settings?tab=maintenance`)顯示平均與一年推估。專案沒有圖表套件。
## Goals / Non-Goals
**Goals:**
- 一眼看出最近 6 個月每個月新增多少附件,以及趨勢。
- 不顯示任何平均或推估。
**Non-Goals:**
- 不做互動(篩選、切換月數、縮放)。
- 不追蹤資料庫或備份大小的歷史:沒有歷史紀錄可用,只有附件有上傳時間。
- 不改「剩餘空間不足」的判斷。
## Decisions
### D1:6 個月 = 本月至今 + 前 5 個月
本月最能反映現在的情況,所以要顯示;但本月還沒結束,長條旁標「至今」避免被誤讀成偏低。月份依台北時間切分,與現有計算相同;「現在」沿用頁面傳入的系統時間(`appNow()`),與附件 `uploaded_at` 的時間基準一致。
替代方案:只顯示 6 個整月。缺點是看不到這個月的情況,最晚要等一個月才看得到。
### D2:每月新增 = 當月上傳的所有附件
依 `attachments.uploaded_at` 歸月,加總 `size_bytes` 與筆數,**不排除**之後被換掉、刪除或已依保存期限刪除的附件。圖表回答的是「那個月多了多少」,事後刪掉不會改變當時新增的量。一次查詢 `GROUP BY` 月份即可;沒有資料的月份補 0。
### D3:伺服器端繪製的長條圖,不加套件
只有 6 根長條,用 server component 輸出 HTML/CSS 即可,不需要 client JavaScript,也不增加依賴。
- 長條高度依 6 個月中的最大值等比例縮放;全部為 0 時顯示「最近 6 個月沒有新增附件」。
- 每根長條上方直接寫大小(`formatBytes`),下方寫月份(`YYYY/MM`)與檔數,不靠顏色或滑鼠移入才看得到數字。
- 顏色只用設計 token(`bg-primary`),本月長條用較淺的同色系並標「至今」。
- 加上 `role="img"` 與完整數字的 `aria-label`,並附一個視覺隱藏的表格,讓螢幕閱讀器讀得到每個月的數字。
- 手機寬度下 6 根長條仍並排、不水平捲動。
## Risks / Trade-offs
- 本月數字偏低容易被誤讀 → 標「至今」並用較淺顏色。
- 最大月份特別大時其他月份長條很矮 → 每根都直接寫數字,不依賴高度判讀。
@@ -0,0 +1,32 @@
## Why
資料維護分頁的「儲存空間」目前只顯示「每月新增(近 3 個月平均)」與一年推估。平均值看不出哪個月特別多、用量是不是在變大。使用者 2026-11-13 決定:改成每月新增用量的圖表,顯示 6 個月,不要平均。
## What Changes
- 「儲存空間」新增「每月新增附件」長條圖,一個月一根,共 6 個月:本月(至今)加上前 5 個月,由舊到新。
- 每根長條標示該月新增的附件大小與檔數。
- 本月標示「至今」,因為還沒結束。
- 沒有新增附件的月份顯示 0,不省略。
- 「每月新增」依附件的上傳時間(台北時間)歸月,包含之後被換掉、刪除或已依保存期限刪除的附件:它是當月實際新增過的量。
- **移除**「每月新增(近 3 個月平均)」與「推估一年約…」這兩個數字,不再計算平均。
- 其他用量數字(磁碟剩餘、資料庫、有效附件、舊檔、已依保存期限刪除、清除前備份)與「剩餘空間不足」警示不變。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `data-reset`:修改「儲存空間用量」(平均每月新增與一年推估改為最近 6 個月每月新增的圖表)。
## Impact
- 程式:
- `src/server/maintenance/storage-usage.ts`:`monthlyAverageBytes`、`averageMonths` 改為 `monthly: { month, count, bytes }[]`(6 筆)。
- `src/app/(app)/admin/settings/page.tsx`:`StorageCard` 移除平均統計,加上圖表元件。
- 新增一個伺服器端繪製的長條圖元件(不加圖表套件)。
- 測試:`storage-usage.test.ts` 的平均案例改為每月案例;E2E 檢查圖表有 6 個月。
- 不需要 migration。
@@ -0,0 +1,20 @@
## MODIFIED Requirements
### Requirement: 儲存空間用量
系統 SHALL 在資料維護分頁(僅系統管理員)顯示儲存空間用量:資料所在磁碟的總容量與剩餘空間、資料庫檔案大小、有效附件與舊檔(已取代、已刪除或屬於已刪除草稿)的檔數與大小、已依保存期限刪除的附件檔數與大小(不計入有效與舊檔)、最近 6 個月(本月至今與前 5 個月)每月新增附件大小與檔數的長條圖,以及每份清除前備份的時間與大小與合計。每月新增 SHALL 依附件上傳時間(台北時間)歸月,並包含之後被取代、刪除或已依保存期限刪除的附件;沒有新增的月份 SHALL 顯示 0;本月 SHALL 標示「至今」。系統 MUST NOT 顯示平均每月新增量或一年推估。磁碟剩餘空間低於 15% 時 SHALL 顯示警示;無法取得磁碟資訊時 SHALL 顯示「無法取得」,頁面其他內容照常顯示。非系統管理員 MUST NOT 看到此區塊。
#### Scenario: 系統管理員查看用量
- **WHEN** 系統管理員開啟資料維護分頁,系統有 10 個有效附件共 40 MB、2 個已取代附件共 6 MB 與 1 份清除前備份
- **THEN** 頁面顯示有效附件 10 個 40 MB、舊檔 2 個 6 MB,以及該份備份的時間與大小
#### Scenario: 已依保存期限刪除的附件另列
- **WHEN** 系統有 5 個附件共 15 MB 已依保存期限刪除
- **THEN** 頁面另列「已依保存期限刪除」5 個 15 MB,有效附件與舊檔的數字不包含它們
#### Scenario: 每月新增圖表
- **WHEN** 今天是 2026/11/13(台北),2026/08 上傳 3 個附件共 9 MB、2026/10 上傳 2 個共 4 MB(其中 1 個之後被換掉)、2026/11 至今上傳 1 個 2 MB,其他月份沒有上傳
- **THEN** 圖表依序顯示 2026/06 0、2026/07 0、2026/08 9 MB(3 個)、2026/09 0、2026/10 4 MB(2 個)、2026/11 2 MB(1 個,標示「至今」),且頁面沒有平均或一年推估
#### Scenario: 剩餘空間不足
- **WHEN** 資料所在磁碟剩餘空間低於總容量的 15%
- **THEN** 頁面在磁碟用量旁顯示「剩餘空間不足」警示
@@ -0,0 +1,15 @@
## 1. 資料
- [x] 1.1 `storage-usage.ts`:移除 `monthlyAverage`/`AVERAGE_MONTHS`,新增 `monthlyAdditions(db, now, tz)` 回傳本月與前 5 個月的 `{ month, count, bytes }`(依台北時間歸月,含已取代、已刪除、已依保存期限刪除,沒有資料補 0);`StorageUsage` 改為 `monthly`
- [x] 1.2 `storage-usage.test.ts`:平均案例改為每月案例(月份切分邊界、補 0、含已取代與已依保存期限刪除、本月至今)
## 2. 畫面
- [x] 2.1 新增伺服器端長條圖元件(設計 token、數字直接標示、本月「至今」、全 0 空狀態、`aria-label` 與視覺隱藏表格、手機寬度不水平捲動)
- [x] 2.2 `StorageCard` 移除「每月新增(近 3 個月平均)」與一年推估,加上「每月新增附件」圖表
- [x] 2.3 說明頁若提到平均每月新增則一併更新(不得出現「全額」);CLAUDE.md 補充
## 3. 驗證
- [x] 3.1 E2E:資料維護分頁的圖表有 6 個月、本月標「至今」、沒有「平均」字樣
- [x] 3.2 `npm run lint`、`typecheck`、`format:check`、`npm test`
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-17
@@ -0,0 +1,23 @@
## Context
`completeOidcLogin` 取得 HR 快照後,在 `provisionOnLogin` 交易的 savepoint 內呼叫 `applyHrSnapshot`。查詢失敗會進 `snapshot.failures`,登入後以 `recordHrSyncFailure` 記「HR 同步失敗」。但查詢成功、資料不足時(`assignment.status !== "ACTIVE"`、`organization` 為 null、`resolveDivision` 找不到單位、`profile.name` 為空),`applyHrSnapshot` 只是不更新,沒有任何紀錄。
## Goals / Non-Goals
**Goals:** 下次遇到「登入成功但沒有部門」時,操作紀錄直接說明 HR 回的是哪一種不完整。
**Non-Goals:** 不改變同步規則(不以名冊補部門、不帶 `date` 查詢);不在畫面上新增提示;不通知任何人。
## Decisions
- **D1 在 `applyHrSnapshot` 內判斷並記錄**:它已知道每一步的結果,且在同一交易(savepoint)內,與其他 HR 同步紀錄一致;套用失敗回滾時這筆也一起回滾(那時會改記「HR 同步失敗」的 `apply` 階段)。
- **D2 何時記**:
- 部門:`snapshot.assignment` 存在(查詢成功)且 `snapshot.organizations` 存在(組織結構查詢成功)時,若最後沒有歸到部門才記;組織結構失敗已經有「HR 同步失敗」,不重複。
- 姓名:`snapshot.profile` 存在但姓名為空才記。
- 兩者都完整時不記;每次登入各自判斷,不去重(登入本身也是每次一筆紀錄)。
- **D3 紀錄內容**:`after: { reasons: [{ code, status?, deptCode? }], hrDate? }`。狀態值、單位代碼、資料日期都是 HR 代碼或日期,不是個資或回應原文;姓名一律不記。
- **D4 動作名稱**:`hr_sync.incomplete`「HR 同步資料不完整」,放在 `hr_sync.failed` 旁,`/admin/audit-log` 篩選自動出現。
## Risks / Trade-offs
- 長期不完整的人每次登入都多一筆紀錄 → 量小(只有資料異常的人),且正好提醒管理者處理。
@@ -0,0 +1,31 @@
## Why
2026-11-16 員工 20260105(10/15 到職、研發部正職)用公司帳號登入三次都成功,但帳號一直停在「待指派部門」,姓名也仍是 Authentik 的顯示名稱。操作紀錄只有「登入」,沒有「HR 同步失敗」也沒有「HR 同步人員資料」,無法判斷原因:HR Sync 的查詢都成功回應,但回傳的資料不足以寫入(例如任職狀態不是 ACTIVE、沒有單位、單位不在組織結構裡、沒有姓名),系統目前在這種情況下安靜跳過、什麼都不記。
## What Changes
- 登入時的 HR 同步,若本人資料與任職資料都查詢成功,卻**無法決定所屬部門**或**沒有取得姓名**,系統 SHALL 記一筆新的操作紀錄「HR 同步資料不完整」(`hr_sync.incomplete`),操作者「系統(HR 同步)」,對象為該帳號,只記原因代碼與判斷用的中繼資料:
- `name_missing`:HR 本人資料沒有姓名。
- `not_active`:任職狀態不是 ACTIVE,記狀態值(例如 `NOT_YET_HIRED`、`SUSPENDED`)。
- `no_organization`:ACTIVE 但沒有所屬單位。
- `unit_not_in_tree`:所屬單位代碼不在 HR 組織結構中,記單位代碼。
- 一併記任職資料回傳的資料日期(HR Sync 的 `date`,即 `coverageTo`),用來看出 HR Sync 每日重建是否停住。
- 已經記為「HR 同步失敗」的部分(查詢失敗、組織結構查詢失敗等)不重複記錄;同步結果完整時不記錄。
- 不記 token、HR 回應內容或姓名等個資;不改變任何同步行為(仍不寫入部門、不阻擋登入)。
- 任職資料的 Zod schema 多保留 `date` 欄位(只用於這筆紀錄)。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `hr-sync`:「同步失敗不阻擋登入」補上「查到但資料不完整」時須記錄原因。
## Impact
- `src/server/hr-sync/apply.ts`(判斷原因並記錄)、`src/server/hr-sync/client.ts`(assignment schema 加 `date`)、`src/lib/audit-actions.ts`(新動作「HR 同步資料不完整」)。
- 測試:`apply.test.ts`/`oidc.test.ts` 各原因案例、完整時不記、失敗時不重複。
- CLAUDE.md HR Sync 段落補一句。不需要 migration。
@@ -0,0 +1,34 @@
## MODIFIED Requirements
### Requirement: 同步失敗不阻擋登入
HR Sync 未設定、無法換得 token、逾時、回傳錯誤或資料格式不符時,系統 SHALL 照常完成登入並沿用系統內既有資料,MUST 記錄一筆同步失敗紀錄(不含 token 與 HR 回應內容)。單次同步對 HR Sync 的等待 MUST 有上限,不得讓登入無限期等待。部分查詢失敗時(例如組織結構失敗但本人資料成功),系統 SHALL 套用已成功取得的部分。
查詢都成功、但回傳資料不足以寫入時,系統 SHALL 照常完成登入並記錄一筆「HR 同步資料不完整」,操作者為「系統(HR 同步)」,對象為登入者,只包含原因代碼與判斷用的代碼或日期:本人資料沒有姓名(`name_missing`);任職狀態不是 ACTIVE(`not_active`,附狀態值);ACTIVE 但沒有所屬單位(`no_organization`);所屬單位不在組織結構中(`unit_not_in_tree`,附單位代碼);並附任職資料回傳的資料日期。部門原因只在本人任職資料與組織結構都查詢成功時判斷;已記為同步失敗的部分 MUST NOT 重複記錄;資料完整時 MUST NOT 寫入這筆紀錄。紀錄 MUST NOT 包含 token、姓名或 HR 回應原文。
#### Scenario: HR Sync 逾時
- **WHEN** 王小明登入時 HR Sync 超過等待上限仍未回應
- **THEN** 王小明照常登入,姓名與部門維持原值,操作紀錄有一筆「HR 同步失敗」
#### Scenario: 尚未核准跨人能力
- **WHEN** 部署環境沒有提供 HR Sync 設定,員工登入
- **THEN** 系統不嘗試同步,登入行為與未串接 HR Sync 時相同
#### Scenario: 任職狀態不是在職
- **WHEN** 新進員工 E9001 登入,HR 本人資料有姓名,任職資料回傳狀態 NOT_YET_HIRED、資料日期 2026/10/10
- **THEN** E9001 照常登入、部門不變,操作紀錄有一筆「HR 同步資料不完整」,原因 `not_active`(NOT_YET_HIRED)與資料日期 2026/10/10,沒有「HR 同步失敗」
#### Scenario: 單位不在組織結構
- **WHEN** 員工登入,任職資料為 ACTIVE、單位代碼 X999,HR 組織結構中沒有 X999
- **THEN** 部門不變,操作紀錄有一筆「HR 同步資料不完整」,原因 `unit_not_in_tree`(X999)
#### Scenario: 沒有姓名
- **WHEN** 員工登入,HR 本人資料的姓名為空,任職資料可歸到研發部
- **THEN** 部門照常更新為研發部,姓名不變,操作紀錄另有一筆「HR 同步資料不完整」,原因 `name_missing`
#### Scenario: 組織結構查詢失敗不重複記錄
- **WHEN** 員工登入時 HR 組織結構查詢失敗,任職資料為 ACTIVE
- **THEN** 操作紀錄只有「HR 同步失敗」,沒有「HR 同步資料不完整」
#### Scenario: 資料完整
- **WHEN** 員工登入,HR 回傳姓名與可歸到部門的 ACTIVE 任職資料
- **THEN** 操作紀錄沒有「HR 同步資料不完整」
@@ -0,0 +1,15 @@
## 1. 實作
- [x] 1.1 `src/server/hr-sync/client.ts`:`hrAssignmentSchema` 保留選填的 `date`(`YYYY-MM-DD`)
- [x] 1.2 `src/lib/audit-actions.ts`:新增 `hr_sync.incomplete`「HR 同步資料不完整」
- [x] 1.3 `src/server/hr-sync/apply.ts`:`applyHrSnapshot` 依 design D2 判斷原因(`name_missing`、`not_active`、`no_organization`、`unit_not_in_tree`),有原因時在同一交易記錄 `hr_sync.incomplete`(`reasons` + `hrDate`),不改變既有寫入行為
## 2. 測試
- [x] 2.1 `apply.test.ts`:四種原因各一、資料完整不記、組織結構缺(失敗)時不記部門原因、姓名缺但部門照常更新
- [x] 2.2 `oidc.test.ts`:登入流程中任職狀態非 ACTIVE 時有「HR 同步資料不完整」、沒有「HR 同步失敗」
- [x] 2.3 `npm test`、lint、typecheck、format:check 通過
## 3. 文件
- [x] 3.1 CLAUDE.md HR Sync 段落補上「查到但資料不完整」的紀錄
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-17
@@ -0,0 +1,14 @@
## Context
`exchangeHrSyncToken` 以 openid-client 的 `genericGrantRequest` 換 token;失敗時 openid-client 拋 `ResponseBodyError`,帶 `status`、`error`(OAuth 錯誤代碼)與 `error_description`。目前只取 `status` 寫成 `http_<status>`。`recordHrSyncFailure` 寫入 `{ failures: [{ stage, reason }] }`。
## Decisions
- **D1 代碼放在獨立欄位 `code`**,不併進 `reason`:`reason` 的格式(`http_400`)被 `rosterSyncFailureText` 等地方解析,維持不變;舊紀錄沒有 `code` 照常顯示。
- **D2 白名單**:只記 RFC 6749 §5.2 與 RFC 8693 §2.2.2 的標準代碼,其餘記 `other`。上游可能把任意字串放在 `error`,白名單確保紀錄裡只有已知、不含個資的值。`error_description` 一律不記(可能含使用者或群組資訊)。
- **D3 只在換 token 階段**:HR Sync 的 API 錯誤(401/403/404)不是 OAuth 錯誤格式,維持只記狀態碼。
- **D4 不改顯示**:操作紀錄詳情已以 JSON 顯示 `failures`,新欄位自然出現;不新增中文對照,避免與手冊的處理方式說明不同步。
## Risks / Trade-offs
- Authentik 未來回非標準代碼時只看到 `other` → 仍比現在多資訊;需要時再擴充白名單。
@@ -0,0 +1,25 @@
## Why
2026-11-17 員工 20260105 登入時的「HR 同步失敗」只記了 `stage: token`、`reason: http_400`。HR Sync 手冊(mason `hr-sync` skill,`references/api-contract.md`〈錯誤對照〉)依 Authentik 回的 OAuth 錯誤代碼區分原因與處理方式:`invalid_grant` 是整張 token 不發(使用者在 `hr-sync-deny`,或請求了未核准的 scope),`invalid_target` 是站台的 provider 沒登記進 HR Sync,兩者都回 400。目前只存狀態碼,只能推測是哪一種,要請平台組另外查。
## What Changes
- 換 HR Sync token(RFC 8693 token exchange)被 Authentik 拒絕時,「HR 同步失敗」的每一筆失敗除了 `stage`、`reason`(`http_<狀態碼>`)之外,多記 Authentik 回應的 OAuth 錯誤代碼 `code`(例如 `invalid_grant`)。
- `code` 只接受 RFC 6749/RFC 8693 定義的標準代碼(`invalid_request`、`invalid_client`、`invalid_grant`、`unauthorized_client`、`unsupported_grant_type`、`invalid_scope`、`invalid_target`);其他值記為 `other`,回應沒有代碼時不記。**不記** `error_description` 或任何回應原文。
- 每日名冊同步的失敗顯示(`/admin/settings` 人數快照分頁)不受影響(名冊同步沿用登入換得的 token,不會在換 token 階段失敗)。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `hr-sync`:「同步失敗不阻擋登入」的失敗紀錄在換 token 被拒時包含 Authentik 的標準錯誤代碼。
## Impact
- `src/server/hr-sync/errors.ts`(`HrSyncError` 加選填 `code`)、`token.ts`(從 `ResponseBodyError.error` 取代碼並過濾)、`apply.ts` 的 `recordHrSyncFailure`(有 `code` 才寫入)。
- 測試:`token.test.ts`(invalid_grant、非標準代碼記 `other`、沒有代碼不記、不含 description)、`apply.test.ts`/`oidc.test.ts` 失敗紀錄內容。
- CLAUDE.md HR Sync 段落補一句。不需要 migration,不改畫面。
@@ -0,0 +1,44 @@
## MODIFIED Requirements
### Requirement: 同步失敗不阻擋登入
HR Sync 未設定、無法換得 token、逾時、回傳錯誤或資料格式不符時,系統 SHALL 照常完成登入並沿用系統內既有資料,MUST 記錄一筆同步失敗紀錄(不含 token 與 HR 回應內容)。單次同步對 HR Sync 的等待 MUST 有上限,不得讓登入無限期等待。部分查詢失敗時(例如組織結構失敗但本人資料成功),系統 SHALL 套用已成功取得的部分。
換 HR Sync token 被 Authentik 拒絕時,同步失敗紀錄 SHALL 另記 Authentik 回應的 OAuth 錯誤代碼:只接受標準代碼(`invalid_request`、`invalid_client`、`invalid_grant`、`unauthorized_client`、`unsupported_grant_type`、`invalid_scope`、`invalid_target`),其他值記為 `other`,回應沒有代碼時不記。紀錄 MUST NOT 包含錯誤說明(`error_description`)或回應原文。
查詢都成功、但回傳資料不足以寫入時,系統 SHALL 照常完成登入並記錄一筆「HR 同步資料不完整」,操作者為「系統(HR 同步)」,對象為登入者,只包含原因代碼與判斷用的代碼或日期:本人資料沒有姓名(`name_missing`);任職狀態不是 ACTIVE(`not_active`,附狀態值);ACTIVE 但沒有所屬單位(`no_organization`);所屬單位不在組織結構中(`unit_not_in_tree`,附單位代碼);並附任職資料回傳的資料日期。部門原因只在本人任職資料與組織結構都查詢成功時判斷;已記為同步失敗的部分 MUST NOT 重複記錄;資料完整時 MUST NOT 寫入這筆紀錄。紀錄 MUST NOT 包含 token、姓名或 HR 回應原文。
#### Scenario: HR Sync 逾時
- **WHEN** 王小明登入時 HR Sync 超過等待上限仍未回應
- **THEN** 王小明照常登入,姓名與部門維持原值,操作紀錄有一筆「HR 同步失敗」
#### Scenario: 尚未核准跨人能力
- **WHEN** 部署環境沒有提供 HR Sync 設定,員工登入
- **THEN** 系統不嘗試同步,登入行為與未串接 HR Sync 時相同
#### Scenario: 換 token 被拒記錄錯誤代碼
- **WHEN** 員工登入,Authentik 拒絕換 HR Sync token,回應 400、錯誤代碼 `invalid_grant` 與一段錯誤說明
- **THEN** 員工照常登入,「HR 同步失敗」記錄階段 token、`http_400` 與代碼 `invalid_grant`,不含錯誤說明
#### Scenario: 非標準錯誤代碼
- **WHEN** Authentik 拒絕換 token,錯誤代碼不是標準代碼
- **THEN** 「HR 同步失敗」的代碼記為 `other`
#### Scenario: 任職狀態不是在職
- **WHEN** 新進員工 E9001 登入,HR 本人資料有姓名,任職資料回傳狀態 NOT_YET_HIRED、資料日期 2026/10/10
- **THEN** E9001 照常登入、部門不變,操作紀錄有一筆「HR 同步資料不完整」,原因 `not_active`(NOT_YET_HIRED)與資料日期 2026/10/10,沒有「HR 同步失敗」
#### Scenario: 單位不在組織結構
- **WHEN** 員工登入,任職資料為 ACTIVE、單位代碼 X999,HR 組織結構中沒有 X999
- **THEN** 部門不變,操作紀錄有一筆「HR 同步資料不完整」,原因 `unit_not_in_tree`(X999)
#### Scenario: 沒有姓名
- **WHEN** 員工登入,HR 本人資料的姓名為空,任職資料可歸到研發部
- **THEN** 部門照常更新為研發部,姓名不變,操作紀錄另有一筆「HR 同步資料不完整」,原因 `name_missing`
#### Scenario: 組織結構查詢失敗不重複記錄
- **WHEN** 員工登入時 HR 組織結構查詢失敗,任職資料為 ACTIVE
- **THEN** 操作紀錄只有「HR 同步失敗」,沒有「HR 同步資料不完整」
#### Scenario: 資料完整
- **WHEN** 員工登入,HR 回傳姓名與可歸到部門的 ACTIVE 任職資料
- **THEN** 操作紀錄沒有「HR 同步資料不完整」
@@ -0,0 +1,15 @@
## 1. 實作
- [x] 1.1 `src/server/hr-sync/errors.ts`:`HrSyncError` 加選填 `code`;`toHrSyncError` 保留它
- [x] 1.2 `src/server/hr-sync/token.ts`:`ResponseBodyError` 時取 `error`,依白名單轉成 `code`(其他值 `other`、沒有則省略),不讀 `error_description`
- [x] 1.3 `src/server/hr-sync/apply.ts`:`recordHrSyncFailure` 有 `code` 時寫入 `{ stage, reason, code }`
## 2. 測試
- [x] 2.1 `token.test.ts`:400 `invalid_grant` → `code: invalid_grant`;非標準代碼 → `other`;沒有代碼不帶 `code`;錯誤說明不出現在錯誤物件
- [x] 2.2 `apply.test.ts` `recordHrSyncFailure`:有 `code` 時寫入、沒有時維持原格式
- [x] 2.3 `npm test`、lint、typecheck、format:check 通過
## 3. 文件
- [x] 3.1 CLAUDE.md HR Sync 段落補上錯誤代碼
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-18
@@ -0,0 +1,19 @@
## Context
`AllocationTable` 的合計列是 `<dl data-testid="allocation-total">`,部門月結頁與 `/admin/settlements/:departmentId/:month` 共用。分配明細的每一列就是一位有審核通過案件的申請人(`v.allocations`)。
## Goals / Non-Goals
**Goals:** 合計列一眼看出核准人數。
**Non-Goals:** 不加到額度區、CSV 預覽或核定名單匯出;不區分最終補助為 0 的人。
## Decisions
- **人數 = `v.allocations.length`**:與表格列數一致,不另外查詢。新申請人(`newApplicant`)也算,因為他們同樣有審核通過案件;金額部分照舊顯示「待重新計算」。
- **位置放在合計列第一項**,文字「核准人數」+「N 人」,沿用其他項目的 `dt text-muted` / `dd` 樣式,加 `data-testid="approved-count"`。
- **名稱用「核准人數」**(使用者用語),與額度區的「計算人數」(人數快照)區分;不改額度區。
## Risks / Trade-offs
- 「核准人數」與「計算人數」名稱相近,可能被誤以為相關 → 兩者位置不同(合計列 vs 額度區),維持現有額度區說明即可。
@@ -0,0 +1,26 @@
## Why
部門月結的分配明細合計列只有金額(支付金額合計、個人上限合計、最終補助合計、占月上限合計),主管與管理端要知道這個月有幾個人拿到補助,得自己數表格的列數(使用者要求,2026-11-18)。
## What Changes
- 分配明細合計列最前面新增「核准人數 N 人」:本月有審核通過案件、列在分配明細的人數(一人多筆案件只算一人)。
- 部門月結頁與管理端月結詳情共用同一張表,兩邊一起出現。
- 試算後才出現的新申請人(「待重新計算」)也算在內,與表格列數一致。
- 不改計算、不改 CSV/核定名單匯出、不改額度區的「計算人數」(那是人數快照,不是核准人數)。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `department-settlement`:「分配明細與尾差說明」的合計列加上核准人數。
## Impact
- `src/app/(app)/department/settlement/allocation-table.tsx`(合計列)
- 元件測試與 e2e(`tests/e2e/` 月結相關 spec)
- 無資料庫、API 或權限變更
@@ -0,0 +1,20 @@
## MODIFIED Requirements
### Requirement: 分配明細與尾差說明
部門月結頁 SHALL 列出每位申請人的姓名、平台、支付金額(當月合計:該申請人當月所有審核通過案件的台幣金額總和)、個人上限(50%:各筆台幣金額 50% 無條件捨去後加總)、個人可補助、占月上限(最終補助 ÷ 部門月上限,小數兩位百分比;月上限為 0 時顯示「—」)與最終補助,並顯示合計列(依序為核准人數、支付金額合計、個人上限合計、最終補助合計與占月上限合計)。核准人數 SHALL 等於分配明細列出的人數(當月有審核通過案件的申請人,一人多筆只算一人;試算後才出現、待重新計算的申請人也計入),管理端月結詳情的分配明細同樣顯示。若有申請人因平分的零頭加 1 元,頁面 SHALL 說明零頭規則並標示該申請人。
#### Scenario: 顯示分配明細
- **WHEN** 月上限 NT$1,000,A 當月兩筆審核通過案件 NT$500 與 NT$399、B 一筆 NT$1,700
- **THEN** 明細列出 A 支付金額 NT$899、個人上限 NT$449、個人可補助 NT$449、占月上限 44.90%,B 支付金額 NT$1,700、個人上限 NT$850、個人可補助 NT$551、占月上限 55.10%,合計核准人數 2 人、支付 NT$2,599、個人上限 NT$1,299、最終 NT$1,000、占月上限 100.00%
#### Scenario: 待重新計算的申請人計入核准人數
- **WHEN** 試算後 C 的案件才審核通過,C 在明細顯示「待重新計算」,明細共 3 人
- **THEN** 合計列顯示核准人數 3 人
#### Scenario: 尾差標示
- **WHEN** 平分的零頭依員工編號給某位申請人加 1 元
- **THEN** 該列標示「含尾差調整 +1」,頁面說明零頭依員工編號由小到大每人加 1 元
#### Scenario: 未超額時的占月上限
- **WHEN** 月上限 NT$1,000,A 最終 NT$200、B 最終 NT$300
- **THEN** A 占月上限 20.00%、B 30.00%,合計 50.00%

Some files were not shown because too many files have changed in this diff Show More