47 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
pkgsp50777_楊舒諠andClaude Opus 5.5 bd028407e0 1.3.0: unified settlement sheet, overdue settlement force submit (proxy and auto submit)
CI / build (push) Successful in 9m7s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:46:16 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 2ec341db35 force-submit-overdue-settlement: move 代為提交 from the settlement detail page to the /admin/settlements overview, next to the 逾期未提交 badge (user decision 2026-10-30); the detail page links to the overview instead
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:46:15 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 9bf9a93c4e force-submit-overdue-settlement: overdue department settlements can be force-submitted (user decision 2026-10-30). After the manager deadline an admin can 代為提交 on the settlement detail page (reason required, confirm step); with the new rule param 逾期自動提交月結 (default off, grace days 0-10, default 3) the hourly scheduler submits overdue departments with cases in the previous 1-2 card months. Both share the manager submit core: pending-review / needs-revision cases become 不核准 via the new overdue_reject transition (admin or system), the settlement records submission_mode / submission_reason, managers are notified, and auto-submit failures are reported to admins once a day
CI / build (push) Successful in 4m59s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:19:06 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 2e6e8f9dce unify-settlement-sheet: HR's approved list and the department CSV preview share one settlement sheet (user decision 2026-10-29). Columns: 刷卡月份, 發放月份 (card month + 2), then the department preview format (部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例, 最終補助, 尾差調整) with a 部門合計 row per department. The approved list is one file with every finalized department plus a 全公司合計 row; Excel uses number cells with NT$ / % formats, CSV plain integers. The 薪資名目 column is dropped (always 其他獎金)
CI / build (push) Successful in 5m16s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 17:37:23 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 48935fd91e archive confirm-clear-business-data and sync the data-reset spec
CI / build (push) Successful in 44s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:29:27 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 bf038f3c27 Merge branch 'docs/hr-sync-manual-source': HR Sync API manual now lives in MoonShineVFX/mason skills/hr-sync
CI / build (push) Successful in 5m14s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:19:23 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 b0da9b6001 confirm-clear-business-data: clearing business data needs a double confirmation (user decision 2026-10-29). The dialog requires a reason and the typed phrase 「清除業務資料」 before 確認清除 is enabled; the server checks both again before backing up (mismatch → no backup, nothing cleared); the reason is stored as the data.business_cleared audit comment. ReasonDialog gains canConfirm / onClose
CI / build (push) Successful in 5m35s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:07:33 +08:00
noflame.linandClaude Opus 5.5 ff16ea6953 docs: HR Sync API manual now lives in MoonShineVFX/mason skills/hr-sync (the vibe-deploy copy is no longer maintained)
CI / build (push) Successful in 4m43s
CI / build (pull_request) Successful in 4m5s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:24:48 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 7f53ac1815 remove-payout-management: record acceptance (7.2) in archived tasks
CI / build (push) Successful in 9m18s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 09:37:53 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 59956dc3fa archive remove-payout-management and sync its specs (payout-management and settlement-correction retired)
CI / build (push) Successful in 4m27s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 20:16:57 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 5fd71a35f4 remove-payout-management: final approval is the end of the settlement flow (user decision 2026-10-28). Removes the payout management page, the paid transition, payout notifications and settlement corrections; the approved list (7 columns, Excel/CSV) is exported from /admin/settlements/export; the company stat card shows approved people; my applications shows the approved subsidy total; legacy paid rows, payout records and corrections stay in the DB for display only
CI / build (push) Successful in 5m47s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 18:06:00 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 d752995641 HR sync: the roster resync request is stored in real time (compared with sync start times), so it still triggers after the system clock is moved back; the login assignment query no longer sends today's date (HR answers for coverageTo, so it no longer returns 400 before the daily HR rebuild or when it fails)
CI / build (push) Successful in 5m25s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 14:53:04 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 109db683a6 v1.2.0: archive sync-hr-employment-status, fix-preview-back-gesture and fix-mobile-layout and sync their specs; bump version to 1.2.0
CI / build (push) Successful in 9m48s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 22:08:02 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 a677b77eeb sync-hr-employment-status (roadmap 5.2): headcount snapshots keep the 1st-of-month member list (counted / suspended / offboarded / excluded without reason, locked with the snapshot) and the headcount settings tab expands it; the daily roster sync stores each account's HR status and deactivates suspended / offboarded accounts (sessions ended, department history closed from the HR date), re-enabling only HR-deactivated accounts when they return to ACTIVE; accounts list shows HR status and refuses manual activation while HR is not active; review-month e2e accepts pending_settlement after the employee deadline
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 22:07:38 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 38dbb50b23 department settlement CSV preview: columns follow the user's format (部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例, 最終補助, 尾差調整) with a 部門合計 row; 個人可補助 and 狀態 columns removed
CI / build (push) Successful in 5m26s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 12:50:03 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 6dd1df52e8 archive 8 accepted changes (cap-personal-subsidy-at-half, show-paid-total-in-quota, block-return-after-deadline, refine-duplicate-detection, fix-withdraw-and-draft-uploads, filter-review-by-month, scroll-review-detail-pane, show-help-by-role) and sync specs; lifecycle spec: single withdraw button in the detail header
CI / build (push) Successful in 10m45s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 12:08:06 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 fcaacc8d99 quota card: lay out by the card's own width (container query), stack the two figures when the card is narrower than 22rem and scale them with the card when side by side, so amounts keep clear of the divider and border on the three-column dashboard
CI / build (push) Successful in 5m6s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 12:19:50 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 9bac5fb77d application detail: one withdraw button (page header); the hint below the status is text only
CI / build (push) Successful in 5m16s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 10:43:15 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 c177c553f7 review workbench: case heading stays pinned at the top of the independently scrolling detail pane, so it is never half clipped
CI / build (push) Successful in 5m17s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 19:06:59 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 62e41c5efe filter-review-by-month + scroll-review-detail-pane + show-help-by-role: review page card-month filter (default earliest month, tab counts and cap summaries follow the month, kept across tabs and views, bare ?id= picks the case month); detail pane in the review workbench is sticky and scrolls on its own; help page shows manager/admin sections only to non-employee roles
CI / build (push) Successful in 5m30s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 18:27:51 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 27c898005f fix-preview-back-gesture + fix-mobile-layout: back gesture closes the attachment preview (history entry), mobile PDF preview shows an open-file button; large money figures shrink on phones and the quota card stacks below 400px; sticky action bar wraps with the primary button on its own row; app error and global error pages (auto reload once on chunk errors); 360px mobile layout e2e
CI / build (push) Successful in 5m13s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 17:57:50 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 8eb21c7c5d settlement quota block: third stat is 補助合計 (personal-cap total, the over-cap base) instead of 支付金額合計; the small personal-cap line under 超額 is removed
CI / build (push) Successful in 5m13s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 17:19:57 +08:00
pkgsp50777_楊舒諠andClaude Opus 5.5 050f28367f refine-duplicate-detection + fix-withdraw-and-draft-uploads: duplicates compare Invoice only (shared card statements no longer flagged) and list the actual reason per case; new applications create one draft even with concurrent uploads, save/submit disabled while uploading; withdraw on the My Applications list and next to the status, button follows the same check as the server, ConfirmDialog shows errors
CI / build (push) Successful in 5m12s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 17:06:47 +08:00
403 changed files with 31046 additions and 4265 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()
+60 -52
View File
@@ -4,13 +4,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project status
**AI 補助申請系統** (AI subscription subsidy system): an internal web app for employees to claim reimbursement of work-related AI subscriptions (each person up to 50% of what they paid; when a department exceeds its monthly cap the cap is shared equally) (ChatGPT / Claude / Gemini / other), with manager review, monthly department settlement, and HR/finance payout tracking.
**AI 補助申請系統** (AI subscription subsidy system): an internal web app for employees to claim reimbursement of work-related AI subscriptions (each person up to 50% of what they paid; when a department exceeds its monthly cap the cap is shared equally) (ChatGPT / Claude / Gemini / other), with manager review, monthly department settlement, and HR/finance final approval (the approved list is exported for payroll).
Stack: **Next.js 16 (App Router, TypeScript strict, full-stack) + SQLite** (better-sqlite3 + Drizzle ORM), Zod, Vitest, Playwright; single-instance deployment, attachments on local disk (see `openspec/changes/archive/2026-10-20-plan-system-roadmap/design.md` D3). The project skeleton exists; business features are built change by change per the roadmap. Node 24 / npm 11.
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`).
@@ -67,8 +67,8 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Employee: only self. Department level shows totals only.
- 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, settlements and payouts. Sysadmin: accounts and settings.
- Per-person full-time status is never shown.
- 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 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,23 +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` (time and requester) and records `hr_sync.roster_resync_requested`.
- `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.
- 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.
- 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 (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.
@@ -117,9 +120,9 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Roster import skips their department column (`hrSkipped` in the preview).
- **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 / status / department code / employee group / hire date (full-time history 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`).
- HR Sync endpoints and response fields: the API manual in the vibe-deploy `hr-sync` skill (`references/api-contract.md`).
- 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 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 (操作紀錄)
@@ -135,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):
@@ -147,22 +151,27 @@ 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 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.
- Return and reject use `ReasonDialog`; reject adds its `confirmStep`.
- Rows can be ticked for batch approve. 「已勾選 N 筆」 and 「批次核准」 sit top-left, on the checkbox side.
- `DataTable sticky={{ first, last }}` pins the checkbox + 申請人 columns left and the 操作 column right while scrolling sideways (view-only tabs pin 申請人 only).
- `?view=detail`: the two-column workbench, where `?id=` selects a case. A bare `?id=` also opens it.
- `?view=detail`: the two-column workbench, where `?id=` selects a case. A bare `?id=` also opens it. The right detail pane is sticky under the top bar and scrolls on its own (keyed by the case id, so it resets to the top).
- 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`.
@@ -192,8 +201,9 @@ 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 計算人數, 月上限 and 超額 only (no 「每人額度」, no 「可補助總額」; the admin detail keeps 每人額度 in its parameter snapshot). 超額 = personal-cap total − cap (shown with 「個人上限合計」 under it; live for an open trial) and turns `text-danger` when it is > 0. 「支付金額(當月合計)」 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).
- Approved → pending settlement is time-based:
- `promoteApprovedToPendingSettlement` is idempotent. The `SYSTEM_ACTOR` transition `promote` runs it.
@@ -202,40 +212,30 @@ 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`.
- Admin side (`src/server/settlement/company.ts`, `payouts.ts`; pages `/admin/settlements`, `/admin/settlements/:departmentId/:month`, `/admin/payments`). Admin role only; the services also check it.
- Settlement status: `open → submitted → finalized → paid`. A return goes `submitted → open` and unlocks the snapshot.
- 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.
- Every submit appends a `settlement_submissions` version. Versions are append-only; return info is written once.
- `finalizeSettlement` creates `payout_records`. Only people with final > 0 get one. `payoutMonth` = card month + 2. Pay item is fixed 「其他獎金」.
- `markPayoutsPaid` moves cases to `paid`. When all records are paid, the settlement becomes `paid`.
- Payout items leave `pending` only once (→ `paid` / `failed` / `cancelled`; DB trigger). Corrections are below.
- `finalizeSettlement` moves cases to `finalized` and notifies applicants (final amount, expected payout month = card month + 2, pay item 「其他獎金」). It creates no payout records.
- Multi-step settlement writes use `abortableTransaction` + `SettlementAbort` (`src/server/settlement/transaction.ts`), so a mid-way failure rolls everything back.
- Payout export columns live in `PAYOUT_EXPORT_COLUMNS` (`src/lib/payouts.ts`) and are shared by Excel (exceljs) and CSV.
## Settlement corrections (更正)
- After finalize, never change settlements, allocations or original payout records. Changes are append-only rows in `settlement_corrections` (`src/server/settlement/corrections.ts`; pure rules in `src/domain/corrections.ts`). Admin only, reason required, one admin is enough.
- Types:
- `adjustment` (補發): positive amount only, payout month ≥ current month. Blocked when the department's corrected total would exceed the settlement's snapshot cap.
- `revoke` (撤銷): only when nothing for that person/settlement is paid. Cancels their pending items, cannot be cancelled. There is no recovery and no negative payout item (user decision: overpayment does not happen).
- `reschedule` (改期): only for a `failed` payout item. Always the next payout month (`reschedulePayoutMonth`), never chosen.
- Corrected amount = original final + active adjustment/revoke amounts. Reschedule moves money only.
- Adjustments and reschedules also create a `payout_records` row (`kind`, `correction_id`). Payout list totals count only `pending` + `paid`.
- A settlement becomes `paid` through `settleIfComplete`: no pending original/reschedule items, and every failed item has an active reschedule.
- Export columns 9–11 (項目類型, 更正編號, 原發放月份) are documented in `docs/operations/payout-export.md`. A test keeps that doc in sync with `PAYOUT_EXPORT_COLUMNS`. Only append new columns.
- 「匯出核定名單」 on `/admin/settlements` (`approvedSheetRows` in `payouts.ts`): the same settlement sheet for every finalized (or legacy `paid`) department of the selected card month, sorted by name, each with all its members (including 0) and its 「部門合計」 row (from the stored `getSettlementView`), then one 「全公司合計」 row (share blank). `numeric` cells: Excel (exceljs) number cells formatted `"NT$"#,##0` / `0.00%`, totals bold; CSV plain integers. No 薪資名目 column (always 其他獎金). Columns are documented in `docs/operations/payout-export.md` (a test keeps them in sync). Audit `payout.exported` (「匯出核定名單」, `rows` = member rows).
- Legacy data from the removed payout management and settlement corrections: `paid` cases/settlements still show 「已發放」 and stay read-only; `payout_records` and `settlement_corrections` keep their rows and triggers (still in `BUSINESS_TABLES`) but nothing reads or writes them; their status/type enums, the `pay` transition action (timeline label only), the `payout.paid` notification type and the old audit actions stay only so old rows still display.
- Dialogs that need a reason use `ReasonDialog` (`src/components/ui/reason-dialog.tsx`).
## Data reset (清除業務資料)
- `/admin/settings?tab=maintenance` is visible to sysadmins only; `clearBusinessDataAction` checks `requireRole("sysadmin")`.
- Double confirmation (`confirm-clear-business-data`, user decision 2026-10-29): the dialog (`ReasonDialog` with `canConfirm`) needs a reason and the typed phrase `CLEAR_CONFIRM_PHRASE` (「清除業務資料」, `src/lib/data-reset.ts`). `clearBusinessDataWithBackup` checks both again (`clearConfirmationError`) before backing up; the reason is the `data.business_cleared` audit comment.
- `clearBusinessDataWithBackup` (`src/server/maintenance/clear-business-data.ts`):
- Backs up first, to `<dirname(DATABASE_PATH)>/backups/` (inside the persisted volume). A failed backup means nothing is cleared.
- `clearBusinessData` then runs one transaction over `BUSINESS_TABLES` (applications, attachments, transitions, notifications, settlements and their allocations / submissions / eligible overrides, payouts, corrections, headcount snapshots and adjustments):
- `clearBusinessData` then runs one transaction over `BUSINESS_TABLES` (applications, attachments, transitions, notifications, settlements and their allocations / submissions / eligible overrides, legacy payouts and corrections, headcount snapshots and adjustments):
- reads the tables' trigger SQL from `sqlite_master`, drops the triggers, deletes the rows (`defer_foreign_keys` for the payout ↔ correction cycle), recreates the triggers;
- records `data.business_cleared`.
- 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 (系統時間)
@@ -248,27 +248,34 @@ 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
- **Duplicate detection**:
- The pure rule is `findDuplicates` (`src/domain/duplicates.ts`). Server side lives in `src/server/applications/duplicates.ts`.
- Rule (user decision 2026-10-20): same applicant and (platform + card date + TWD amount all equal → reason `fields`, or the **Invoice** file content equal → `invoice`). Card statements are not compared: one statement often lists several subscriptions. Old flags may carry `attachment` (any file equal); they are shown as 「附件相同」 and never recomputed.
- Texts live in `src/lib/duplicates.ts` (`DUPLICATE_WARNING`, `DUPLICATE_REASON_LABELS`); the dialog and the 「疑似重複」 notice list each matched case's reasons.
- `submitApplication` checks inside its transaction. If unconfirmed, it returns `duplicates` and writes nothing. The UI shows `DuplicateDialog` and resubmits with `confirmDuplicate=1`.
- The result is stored on the case (`duplicate_of_json`, confirmer, time) and shown as 「疑似重複」 in review.
- Test helpers that submit identical cases for one user must pass `confirmDuplicate: true`. Attachment test hashes are unique per file.
- **Notifications** (`src/server/notifications/`): in-app only, no email.
- Event notifications are written inside the business transaction:
- `applyTransition` calls `notifyTransition`.
- The settlement services call `notifySettlement*` / `notifyPayoutPaid`.
- The settlement services call `notifySettlement*`.
- New events go in `events.ts`, plus a type in `NOTIFICATION_TYPES` (`src/lib/notifications.ts`).
- Only the recipient can read a notification. `/notifications/:id` marks it read, then redirects. It returns 404 for anyone else.
- Pending-review notifications follow the case:
- 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.
@@ -278,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)
@@ -293,6 +300,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Decorative images:
- Cropped from the mockups by `scripts/crop-mockup-images.ts` into `public/images/`, shown via `Illustration`. To upgrade, replace the files with higher-resolution ones under the same names.
- `public/images/` is excluded from the login redirect in `src/proxy.ts`. The Dockerfile copies `public/` into the runtime image (standalone output doesn't).
- `/help` renders the 主管 / 管理端 sections only for users with any role besides employee (show-help-by-role).
- Login, dev login and 403 pages use `AuthShell` (`src/components/auth-shell.tsx`).
- Component tests: `// @vitest-environment jsdom` + Testing Library.
@@ -316,7 +324,7 @@ Python is available via the `py -3` launcher (also `C:\Python\Python310`); `.doc
## Workflow: OpenSpec (spec-driven)
Changes go through OpenSpec (`openspec/config.yaml`, schema `spec-driven`). Specs live in `openspec/specs/` (`identity-access`, `org-directory`, `audit-trail`, `app-shell`, `rule-settings`, `headcount-snapshot`, `application-attachments`, `subsidy-application`, `application-lifecycle`, `application-review`, `settlement-calculation`, `department-settlement`, `company-settlement`, `payout-management`, `duplicate-detection`, `notifications`, `dashboard`, `settlement-correction`, `hr-sync`, `system-clock` so far — read the relevant one before changing that behavior; later changes modify them via delta specs), proposed changes in `openspec/changes/`, completed ones in `openspec/changes/archive/`. Use the bundled skills/commands rather than ad-hoc edits:
Changes go through OpenSpec (`openspec/config.yaml`, schema `spec-driven`). Specs live in `openspec/specs/` (`identity-access`, `org-directory`, `audit-trail`, `app-shell`, `rule-settings`, `headcount-snapshot`, `application-attachments`, `subsidy-application`, `application-lifecycle`, `application-review`, `settlement-calculation`, `department-settlement`, `company-settlement`, `duplicate-detection`, `notifications`, `dashboard`, `hr-sync`, `system-clock` so far — read the relevant one before changing that behavior; later changes modify them via delta specs), proposed changes in `openspec/changes/`, completed ones in `openspec/changes/archive/`. Use the bundled skills/commands rather than ad-hoc edits:
- `/opsx:explore` — think through requirements before committing to a change
- `/opsx:propose` — create a change with proposal, design, specs and tasks
@@ -327,19 +335,19 @@ 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) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 → 已發放; plus 撤回. Return/reject require a comment.
- **Locking & audit**: after a department head submits settlement, data is locked; corrections go through admin rollback or correction records, never overwriting history. Snapshots, parameters and settlement results must be versioned/retained; every state transition logs actor and time.
- **Statuses**: 草稿 → 待主管審核 → (待補件 ↔ resubmit) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 (end; legacy rows may be 已發放); plus 撤回. Return/reject require a comment.
- **Locking & audit**: after a department head submits settlement, data is locked; changes go through an admin return before final approval; after final approval nothing changes. Never overwrite history. Snapshots, parameters and settlement results must be versioned/retained; every state transition logs actor and time.
- Rule parameters (per-person quota, deadlines, platforms, attachment limits) are admin-configurable, not hard-coded. The ratio (50%) and rounding (floor) are versioned but not editable.
## Roles
Employee, department manager/head (own department only), admin / HR-finance (all departments, final approval, payout; does not judge work purpose), system admin (settings, accounts, audit log). Routes in the frontend plan: `/dashboard`, `/applications[/new|/:id]`, `/department/review`, `/department/settlement`, `/admin/settlements|payments|settings|audit-log`.
Employee, department manager/head (own department only), admin / HR-finance (all departments, final approval, approved-list export for payroll; does not judge work purpose), system admin (settings, accounts, audit log). Routes in the frontend plan: `/dashboard`, `/applications[/new|/:id]`, `/department/review`, `/department/settlement`, `/admin/settlements|settings|audit-log`.
## UI conventions (from the frontend plan)
Desktop-first internal tool with RWD; white/light-grey with dark blue brand color. Money as `NT$` + thousands separators, dates `YYYY/MM/DD`, months `YYYY/MM`. Status badges always include text (not color alone). Labels always visible (no placeholder-as-label). One primary action per view; destructive/irreversible actions (不核准, settlement submit, final approval, mark paid) require a confirm dialog. Planned shared components: StatusBadge, MoneyDisplay, MonthPicker, FileUploader, FilePreview, ReviewTimeline, QuotaCard, ConfirmDialog, EmptyState, ErrorSummary.
Desktop-first internal tool with RWD; white/light-grey with dark blue brand color. Money as `NT$` + thousands separators, dates `YYYY/MM/DD`, months `YYYY/MM`. Status badges always include text (not color alone). Labels always visible (no placeholder-as-label). One primary action per view; destructive/irreversible actions (不核准, settlement submit, final approval) require a confirm dialog. Planned shared components: StatusBadge, MoneyDisplay, MonthPicker, FileUploader, FilePreview, ReviewTimeline, QuotaCard, ConfirmDialog, EmptyState, ErrorSummary.
+35 -21
View File
@@ -1,29 +1,43 @@
# 發放名單匯出欄位
# 月結明細表與核定名單匯出欄位
`/admin/payments` 的「匯出 Excel」與「匯出 CSV」輸出相同欄位與順序(定義在 `src/lib/payouts.ts` 的 `PAYOUT_EXPORT_COLUMNS`,測試會比對本文件的表格與程式一致)。CSV 為 UTF-8(含 BOM),以 Excel 開啟中文不亂碼。
部門主管的「匯出預覽」(`/department/settlement`,CSV)與管理端的「匯出核定名單」(`/admin/settlements`,Excel 與 CSV)使用同一份月結明細表,欄位與順序相同(定義在 `src/lib/settlement-sheet.ts` 的 `SETTLEMENT_SHEET_COLUMNS`,測試會比對本文件的表格與程式一致)。CSV 為 UTF-8(含 BOM),以 Excel 開啟中文不亂碼。
一個發放月份的名單包含排入該月份的**所有發放項目**:原核定、補發、改期,以及已標記發放失敗或已撤銷的項目(方便對帳)。**薪資作業只發「發放狀態」為待發放的列**;頁面上的合計也只計算待發放與已發放。
## 內容
- **部門主管匯出預覽**:自己部門所選刷卡月份的分配明細(提交前為試算),最後一列「部門合計」。
- **管理端核定名單**:所選**刷卡月份**中所有已最終核定(含移除發放管理前已標記發放)的部門,依部門名稱排列;每個部門列出月結裡的所有申請人(依員工編號,含最終補助為 0 的人),接著一列該部門的「部門合計」;最後一列「全公司合計」。尚未最終核定的部門不會列入。系統不追蹤實際是否已發放,發放由薪資作業處理。
- 合計列的「員工編號」留白,「姓名」為「部門合計」或「全公司合計」,篩選時可用這兩欄排除;Excel 的合計列為粗體。
- 補助一律以薪資名目「其他獎金」發放(表上不另列欄位)。
## 欄位
| 順序 | 欄位 | 內容 |
| ---- | ---- | ---- |
| 1 | 發放月份 | `YYYY/MM`,隨該月薪資發放 |
| 2 | 員工編號 | |
| 3 | 姓名 | |
| 4 | 部門 | 申請當時所屬部門(月結的部門) |
| 5 | 刷卡月份 | `YYYY/MM`,補助所屬的月結月份 |
| 6 | 補助金額 | 整數元數值(不含 NT$ 與千分位),一律為正數 |
| 7 | 薪資名目 | 固定「其他獎金」 |
| 8 | 發放狀態 | 待發放/已發放/發放失敗/已撤銷 |
| 9 | 項目類型 | 原核定/補發/改期 |
| 10 | 更正編號 | 補發、改期項目的更正編號(如 `C-00012`);原核定為空白 |
| 11 | 原發放月份 | 改期項目原本的發放月份(`YYYY/MM`);其他為空白 |
| 1 | 刷卡月份 | `YYYY/MM`,補助所屬的月結月份 |
| 2 | 發放月份 | `YYYY/MM`,刷卡月份後第 2 個月,隨該月薪資發放(預覽為預計發放月份) |
| 3 | 部門 | 申請當時所屬部門(月結的部門);全公司合計留白 |
| 4 | 員工編號 | 合計列留白 |
| 5 | 姓名 | 合計列為「部門合計」/「全公司合計」 |
| 6 | 平台 | 該月核准案件的平台,以「、」分隔 |
| 7 | 實際支付金額 | 該月核准案件的台幣金額合計 |
| 8 | 個人可補助上限 | 支付金額 × 50%,逐筆無條件捨去後加總;舊月結沒有此值時為「—」(核定名單留白) |
| 9 | 系統計算可補助/部門分配上限 | 系統依規則計算的個人可補助(超額時為平分後的分配上限) |
| 10 | 佔月上限/部門成員補助比例 | 最終補助 ÷ 部門月上限;全公司合計留白(各部門月上限不同) |
| 11 | 最終補助 | 實際發放的補助金額 |
| 12 | 尾差調整 | 平分時分到的尾差元數(`+1`),沒有時留白 |
## 格式差異
| 匯出 | 金額 | 比例 |
| ---- | ---- | ---- |
| 部門主管匯出預覽(CSV) | `NT$1,276`(與頁面一致) | `4.73%` |
| 核定名單 CSV | 整數元 `1276`(不含 NT$ 與千分位) | `4.73%` |
| 核定名單 Excel | 數值儲存格,顯示為 `NT$1,276`,可直接加總 | 數值儲存格,顯示為 `4.73%` |
部門主管的預覽中,試算後才出現的申請人只填到個人可補助上限,其餘留白(等主管重新計算)。
## 欄位變更紀錄
- 2026/10(`add-settlement-corrections`):新增第 9–11 欄,附加在最後;第 1–8 欄位置不變,依欄位位置讀取的既有試算表不受影響。
## 更正與發放失敗(摘要)
- 不會有負數金額,也沒有追回:已發放的補助不可撤銷。
- 標記「發放失敗」的項目不會被發放,管理者建立改期後,同額會出現在**下一個發放月份**的名單,項目類型為「改期」並帶原發放月份。
- 撤銷尚未發放的補助時,該人的待發放項目變為「已撤銷」。
- 2026/10(`add-settlement-corrections`):發放名單新增第 9–11 欄(項目類型、更正編號、原發放月份)。
- 2026/10/28(`remove-payout-management`):移除發放管理與月結更正,核定名單改在全公司月結頁依刷卡月份匯出,只保留 7 欄(發放月份、員工編號、姓名、部門、刷卡月份、補助金額、薪資名目)。
- 2026/10/29(`unify-settlement-sheet`):核定名單改用與部門主管匯出預覽相同的 12 欄月結明細表(上表),加上部門合計與全公司合計列;「補助金額」改名為「最終補助」,「薪資名目」欄移除(固定其他獎金)。部門主管的預覽在最前面加上刷卡月份與發放月份。
+10
View File
@@ -124,6 +124,16 @@ const files = listActiveAttachments(db, application.id);
- 刷卡帳單上傳區會自動顯示遮蔽提示,不要另外再寫。
- 範例:開發登入模式的 `/design-tokens`「附件上傳與預覽」(建立示範草稿後即可試用)。
- 附件預覽開啟時會新增一筆同網址的瀏覽紀錄:手機返回手勢只關閉預覽;手機寬度的 PDF 不內嵌,改顯示「開啟檔案」。
- 新申請的附件上傳中(含建立草稿),表單會停用「儲存草稿」與「送出」(`FileUploader` 的 `onBusyChange`)。
## 手機版面
- 以 360px 寬為下限:頁面不得水平捲動,文字與金額不得超出畫面或卡片內距(`tests/e2e/mobile-layout.spec.ts` 會檢查各角色主要頁面)。
- 大字金額一律用 `MoneyDisplay size="figure"`:手機自動縮小字級;兩欄並排的大字金額依**卡片本身的寬度**排版(`@container`,不是視窗寬度:首頁三欄時卡片也很窄),卡片窄於 22rem 改為上下排列,兩欄時字級以 `cqi` 縮放(參考 `QuotaCard`)。
- 主要操作用 `StickyActions`:手機固定在底部,三顆以上按鈕時換行,最後一顆(主要按鈕)獨占最下一行;主要按鈕放最後。
- 頁面錯誤與載入:`src/app/(app)/error.tsx`(「頁面載入失敗」+重新整理/回首頁,部署後程式片段載入失敗自動重新載入一次)、`src/app/global-error.tsx`。不要加 `loading.tsx`:串流會先送出 200,`forbidden()`/`notFound()` 就回不了 403/404。
## 常見陷阱
- **不要依賴前端狀態決定欄位是否出現**(例如勾選某選項後才顯示輸入框):頁面尚未完成 hydration 時,使用者的點選不會觸發 React 的 `onChange`。改為一律顯示,由伺服器依選項決定是否採用。
@@ -8,4 +8,4 @@
- [x] 2.1 e2e:`monthsAgo(2)` 的待審案件在條列與逐筆檢視沒有「退回補件」且有說明;本月待審案件可退回補件
- [x] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 2.3 使用者授權後 push 部署;使用者驗收(可用系統時間調整到 21 日)
- [x] 2.3 使用者授權後 push 部署;使用者驗收(可用系統時間調整到 21 日)(2026-10-22 使用者驗收通過)
@@ -30,4 +30,4 @@
- [x] 6.1 e2e:更新依全額寫死的金額(月結、審核、首頁、管理端);新增審核試算合計一致與月結頁無「每人額度」、調整超過個人上限被拒的案例
- [x] 6.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 6.3 使用者授權後 push 部署;通知部門主管重新計算未提交的月結;使用者驗收:審核試算 50% 與合計、月結頁欄位與調整上限、使用說明文字
- [x] 6.3 使用者授權後 push 部署;通知部門主管重新計算未提交的月結;使用者驗收:審核試算 50% 與合計、月結頁欄位與調整上限、使用說明文字(2026-10-22 使用者驗收通過)
@@ -1,15 +1,15 @@
## 1. 服務
- [ ] 1.1 `listReviewQueue`、`reviewQueueCounts` 接受選填月份(D3);新增 `reviewQueueMonths`(目前分頁各月份筆數,由舊到新)。測試:9 月 5 筆、10 月 18 筆時的清單、筆數與月份列表;他部門案件不計入
- [x] 1.1 `listReviewQueue`、`reviewQueueCounts` 接受選填月份(D3);新增 `reviewQueueMonths`(目前分頁各月份筆數,由舊到新)。測試:9 月 5 筆、10 月 18 筆時的清單、筆數與月份列表;他部門案件不計入
## 2. 頁面
- [ ] 2.1 `page.tsx` 解析 `?month=`(`YYYY-MM`/`all`),依 D2 決定預設(`?id=` 取案件月份、否則最早月份、沒有案件為全部);狀態分頁筆數、清單、試算摘要依所選月份
- [ ] 2.2 「刷卡月份」膠囊選擇(全部+各月份與筆數,所選月份即使 0 筆也保留);狀態分頁、檢視切換與逐筆檢視的案件連結(`review-queue.tsx`、`review-table.tsx`)帶上 `month`
- [ ] 2.3 CLAUDE.md「Review UI」補上月份選擇與預設規則
- [x] 2.1 `page.tsx` 解析 `?month=`(`YYYY-MM`/`all`),依 D2 決定預設(`?id=` 取案件月份、否則最早月份、沒有案件為全部);狀態分頁筆數、清單、試算摘要依所選月份
- [x] 2.2 「刷卡月份」膠囊選擇(全部+各月份與筆數,所選月份即使 0 筆也保留);狀態分頁、檢視切換與逐筆檢視的案件連結(`review-queue.tsx`、`review-table.tsx`)帶上 `month`
- [x] 2.3 CLAUDE.md「Review UI」補上月份選擇與預設規則
## 3. 驗證
- [ ] 3.1 e2e:兩個月份的待審案件 → 預設最早月份、摘要只有該月、切換月份與「全部」的清單與筆數、切換分頁保留月份、批次核准只含所選月份、首頁 `?id=` 連結自動選月份
- [ ] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 3.3 使用者授權後 push 部署;使用者驗收:正式站審核頁依月份檢視
- [x] 3.1 e2e:兩個月份的待審案件 → 預設最早月份、摘要只有該月、切換月份與「全部」的清單與筆數、切換分頁保留月份、批次核准只含所選月份、首頁 `?id=` 連結自動選月份
- [x] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 3.3 使用者授權後 push 部署;使用者驗收:正式站審核頁依月份檢視(2026-10-22 使用者驗收通過)
@@ -26,11 +26,11 @@
`StickyActions` 手機改為 `flex-wrap`:主要按鈕(最後一個子元素、`variant="primary"`)`basis-full order-last`,其他按鈕在上一行平分;只有一兩顆按鈕時維持一行。按鈕文字 `whitespace-nowrap`。底部列高度增加時,主內容的下方留白(`pb-28`)一併加大,避免內容被遮住。
### D3 錯誤與載入畫面
### D3 錯誤畫面
- `src/app/(app)/error.tsx`(client component):在框架內顯示「頁面載入失敗」、說明可重新整理,按鈕「重新整理」(`reset()`,失敗時 `location.reload()`)與「回首頁」。錯誤偵測到程式片段載入失敗(`ChunkLoadError`)時直接 `location.reload()` 一次(以 `sessionStorage` 防止迴圈)。
- `src/app/global-error.tsx`:根 layout 也失敗時的最小畫面(自帶 `<html><body>`)。
- `src/app/(app)/loading.tsx`:內容區的載入狀態(骨架或「載入中…」),不影響側欄與頂部列。
- 不加 `loading.tsx`(實作時發現):有載入畫面時 Next.js 先串流 200,頁面中的 `forbidden()`/`notFound()` 無法再改狀態碼,違反「無權限回 403」(identity-access)。換頁時 App Router 會保留原頁面直到新頁面就緒,不會出現空白。
### D4 手機版面 e2e
@@ -38,5 +38,5 @@
## Risks / Trade-offs
- [空白畫面原因未確認] → D3 讓錯誤與載入都有畫面,並對部署後的程式片段錯誤自動重新載入;請使用者提供網址、機型、瀏覽器與時間以確認,若是其他原因再補修。
- [空白畫面原因未確認] → D3 讓錯誤一定有畫面,並對部署後的程式片段錯誤自動重新載入;請使用者提供網址、機型、瀏覽器與時間以確認,若是其他原因再補修。
- [縮小字級影響桌機] → 只在窄於 `sm` 時縮小,桌機不變。
@@ -13,7 +13,7 @@
- **額度卡**:金額字級在窄螢幕縮小、兩欄在放不下時改為上下排列,數字與卡片邊框之間至少保留卡片內距;所有使用大字金額的統計卡(`MoneyDisplay` 大字、首頁與月結統計)一併檢查。
- **底部固定操作列**:手機上最多並排兩顆按鈕;超過時主要按鈕獨占一行在最下方,其他按鈕在上一行(或收進「更多」),文字不換行也不被切掉。
- **錯誤與載入畫面**:新增登入後頁面的錯誤畫面(說明「頁面載入失敗」、提供「重新整理」與「回首頁」)與全站錯誤畫面,以及載入中畫面,不再出現只剩背景色的空白頁。
- **錯誤畫面**:新增登入後頁面的錯誤畫面(說明「頁面載入失敗」、提供「重新整理」與「回首頁」)與全站錯誤畫面,不再出現只剩背景色的空白頁。(不加串流載入畫面:會讓無權限頁無法回 403。)
- **手機版面檢查測試**:e2e 以 360px 寬度開啟各角色的主要頁面,確認頁面沒有水平捲動、元素不超出畫面、卡片內的文字不超出卡片內距。
- 請使用者提供空白畫面發生時的網址、手機與瀏覽器、大約時間(是否剛好在更新部署後),以確認原因。
@@ -16,12 +16,12 @@
- **THEN** 頁面沒有水平捲動,沒有元素超出畫面
### Requirement: 頁面錯誤與載入畫面
登入後頁面載入或執行發生錯誤時,系統 SHALL 顯示錯誤畫面,說明頁面載入失敗並提供「重新整理」與「回首頁」;整個網站無法顯示時 SHALL 顯示全站錯誤畫面。頁面載入中 SHALL 顯示載入狀態。系統 MUST NOT 只顯示背景色的空白畫面。
登入後頁面載入或執行發生錯誤時,系統 SHALL 顯示錯誤畫面,說明頁面載入失敗並提供「重新整理」與「回首頁」;整個網站無法顯示時 SHALL 顯示全站錯誤畫面。系統 MUST NOT 只顯示背景色的空白畫面。無權限與找不到頁面 MUST 維持 HTTP 403/404(因此不使用會先送出 200 的串流載入畫面)。
#### Scenario: 頁面發生錯誤
- **WHEN** 使用者開啟的頁面在載入時發生錯誤
- **THEN** 畫面顯示「頁面載入失敗」與「重新整理」「回首頁」按鈕,而不是空白
#### Scenario: 載入較慢
- **WHEN** 使用者在網路較慢的手機上切換到另一個頁面
- **THEN** 內容區顯示載入中狀態,直到頁面載入完成
#### Scenario: 無權限頁維持 403
- **WHEN** 員工直接開啟管理端頁面
- **THEN** 回應 HTTP 403 並顯示無權限頁
@@ -1,16 +1,16 @@
## 1. 版面
- [ ] 1.1 大字金額響應式字級與 `QuotaCard` 窄螢幕單欄(D1);首頁與月結統計區一併套用。元件測試更新
- [ ] 1.2 `StickyActions` 手機多按鈕換行、主要按鈕獨占最下一行,主內容下方留白配合(D2)
- [x] 1.1 大字金額響應式字級與 `QuotaCard` 窄螢幕單欄(D1);首頁與月結統計區一併套用。元件測試更新
- [x] 1.2 `StickyActions` 手機多按鈕換行、主要按鈕獨占最下一行,主內容下方留白配合(D2)
## 2. 錯誤與載入
- [ ] 2.1 `src/app/(app)/error.tsx`(含程式片段載入失敗自動重新載入一次)、`src/app/global-error.tsx`、`src/app/(app)/loading.tsx`(D3)
- [ ] 2.2 `docs/ui-guide.md` 補上手機版面規則(大字金額、底部操作列、錯誤畫面)
- [x] 2.1 `src/app/(app)/error.tsx`(含程式片段載入失敗自動重新載入一次)、`src/app/global-error.tsx`(D3;不加 `loading.tsx`,以免 403/404 變成 200)
- [x] 2.2 `docs/ui-guide.md` 補上手機版面規則(大字金額、底部操作列、錯誤畫面)
## 3. 驗證
- [ ] 3.1 e2e `mobile-layout.spec.ts`(D4):各角色主要頁面 360px 無水平捲動與超出;首頁 NT$26,000 額度卡;部門月結三顆按鈕完整顯示
- [ ] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 3.1 e2e `mobile-layout.spec.ts`(D4):各角色主要頁面 360px 無水平捲動與超出;首頁 NT$26,000 額度卡;部門月結三顆按鈕完整顯示
- [x] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 3.3 請使用者提供空白畫面的網址、手機機型與瀏覽器、發生時間,確認原因是否在本 change 範圍內
- [ ] 3.4 使用者授權後 push 部署;使用者驗收:手機開啟首頁額度卡與部門月結頁
@@ -1,10 +1,10 @@
## 1. 預覽
- [ ] 1.1 `FilePreview` 改為受控,開啟時 `pushState`、`popstate` 關閉、其他方式關閉時 `history.back()` 移除紀錄(D1)。元件測試:開啟新增紀錄、popstate 關閉、✕ 關閉呼叫 back
- [ ] 1.2 手機寬度的 PDF 改為檔名與「開啟檔案」按鈕,不內嵌(D2)。元件測試
- [x] 1.1 `FilePreview` 改為受控,開啟時 `pushState`、`popstate` 關閉、其他方式關閉時 `history.back()` 移除紀錄(D1)。元件測試:開啟新增紀錄、popstate 關閉、✕ 關閉呼叫 back
- [x] 1.2 手機寬度的 PDF 改為檔名與「開啟檔案」按鈕,不內嵌(D2)。元件測試
## 2. 驗證
- [ ] 2.1 e2e(375px):申請詳情與部門審核開啟預覽後 `page.goBack()` → 預覽關閉、網址不變、頁面可操作;✕ 關閉後 `goBack()` → 回到前一頁;手機 PDF 預覽顯示「開啟檔案」
- [ ] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 2.1 e2e(375px):申請詳情與部門審核開啟預覽後 `page.goBack()` → 預覽關閉、網址不變、頁面可操作;✕ 關閉後 `goBack()` → 回到前一頁;手機 PDF 預覽顯示「開啟檔案」
- [x] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 2.3 使用者授權後 push 部署;使用者以 Android 與 iPhone 實機驗收左滑/返回鍵關閉預覽
@@ -1,18 +1,18 @@
## 1. 草稿附件
- [ ] 1.1 `application-form.tsx`:建立草稿改為單一請求(D1,ref 保存 Promise 與 id,同步寫入隱藏欄位 `id`)。元件測試:兩個上傳同時呼叫只建立一次草稿;建立中按「儲存草稿」使用同一個 id
- [ ] 1.2 `FileUploader` 回報上傳中狀態;表單在上傳或建立草稿中停用「儲存草稿」「送出申請」並顯示「附件上傳中,請稍候」,上傳中離開頁面提示(D2)。元件測試
- [x] 1.1 `application-form.tsx`:建立草稿改為單一請求(D1,ref 保存 Promise 與 id,同步寫入隱藏欄位 `id`)。元件測試:兩個上傳同時呼叫只建立一次草稿;建立中按「儲存草稿」使用同一個 id
- [x] 1.2 `FileUploader` 回報上傳中狀態;表單在上傳或建立草稿中停用「儲存草稿」「送出申請」並顯示「附件上傳中,請稍候」,上傳中離開頁面提示(D2)。元件測試
## 2. 撤回
- [ ] 2.1 `withdrawBlocker`(D3)供按鈕條件與 `applyTransition` 共用,含月結鎖定。單元測試:未審核可撤回、已核准不可、月結鎖定時按鈕不顯示且原因為 `settlement_locked`
- [ ] 2.2 申請詳情在待主管審核但無法撤回時顯示原因;可撤回時在狀態說明與送出成功提示旁顯示「主管審核前可撤回修改」與「撤回申請」(D3b)
- [ ] 2.2b 「我的申請」清單(表格與手機卡片)在可撤回的列提供「撤回」(D3b,批次判斷不逐列查詢)
- [ ] 2.3 `ConfirmDialog` 捕捉錯誤並在對話框內顯示(D4);撤回失敗在對話框內顯示錯誤。元件測試
- [x] 2.1 `withdrawBlocker`(D3)供按鈕條件與 `applyTransition` 共用,含月結鎖定。單元測試:未審核可撤回、已核准不可、月結鎖定時按鈕不顯示且原因為 `settlement_locked`
- [x] 2.2 申請詳情在待主管審核但無法撤回時顯示原因;可撤回時在狀態說明與送出成功提示旁顯示「主管審核前可撤回修改」與「撤回申請」(D3b)
- [x] 2.2b 「我的申請」清單(表格與手機卡片)在可撤回的列提供「撤回」(D3b,批次判斷不逐列查詢)
- [x] 2.3 `ConfirmDialog` 捕捉錯誤並在對話框內顯示(D4);撤回失敗在對話框內顯示錯誤。元件測試
## 3. 驗證
- [ ] 3.1 e2e:從「我的申請」清單撤回待審案件後回到草稿;送出後詳情看得到撤回說明與按鈕;新申請連續上傳 Invoice 與刷卡帳單後重開草稿兩個都在;上傳中「儲存草稿」停用;主管核准後申請詳情沒有撤回按鈕;開著詳情時主管核准,再撤回顯示「案件狀態已變更,請重新整理」
- [ ] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 3.1 e2e:從「我的申請」清單撤回待審案件後回到草稿;送出後詳情看得到撤回說明與按鈕;新申請連續上傳 Invoice 與刷卡帳單後重開草稿兩個都在;上傳中「儲存草稿」停用;主管核准後申請詳情沒有撤回按鈕;開著詳情時主管核准,再撤回顯示「案件狀態已變更,請重新整理」
- [x] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 3.3 請使用者提供撤回失敗的案件編號,確認原因是否在本 change 範圍內(2026-10-20:AI-202610-0006,使用者找不到撤回按鈕 → D3b)
- [ ] 3.4 使用者授權後 push 部署;使用者驗收:手機上傳兩個附件後存草稿、撤回待審案件
- [x] 3.4 使用者授權後 push 部署;使用者驗收:手機上傳兩個附件後存草稿、撤回待審案件(2026-10-22 使用者驗收通過)
@@ -1,16 +1,16 @@
## 1. 判斷
- [ ] 1.1 `src/domain/duplicates.ts`:原因 `fields`/`invoice`(型別保留 `attachment` 供舊資料),附件只比 Invoice 雜湊(D1、D2)。測試:Invoice 相同 → `invoice`;只有刷卡帳單相同 → 不重複;欄位與 Invoice 都相同 → 兩個原因
- [ ] 1.2 `detectDuplicates` 只查 `kind = 'invoice'` 的有效附件雜湊。測試:共用刷卡帳單的兩筆(ChatGPT 10/17 3,300、Gemini 10/19 650)直接送出;不同平台、同日期同金額、共用刷卡帳單(ChatGPT/Gemini 10/05 650)直接送出;Invoice 相同仍警示
- [x] 1.1 `src/domain/duplicates.ts`:原因 `fields`/`invoice`(型別保留 `attachment` 供舊資料),附件只比 Invoice 雜湊(D1、D2)。測試:Invoice 相同 → `invoice`;只有刷卡帳單相同 → 不重複;欄位與 Invoice 都相同 → 兩個原因
- [x] 1.2 `detectDuplicates` 只查 `kind = 'invoice'` 的有效附件雜湊。測試:共用刷卡帳單的兩筆(ChatGPT 10/17 3,300、Gemini 10/19 650)直接送出;不同平台、同日期同金額、共用刷卡帳單(ChatGPT/Gemini 10/05 650)直接送出;Invoice 相同仍警示
## 2. 文字與畫面
- [ ] 2.1 `src/lib/duplicates.ts`:`DUPLICATE_WARNING` 與 `DUPLICATE_REASON_LABELS`(D3);server 與對話框共用
- [ ] 2.2 `duplicate-dialog.tsx` 改用通用警示文字並逐案列出原因;`duplicate-notice.tsx` 顯示原因(舊 `attachment` 為「附件相同」)
- [ ] 2.3 CLAUDE.md「Duplicate detection」更新判斷條件與原因
- [x] 2.1 `src/lib/duplicates.ts`:`DUPLICATE_WARNING` 與 `DUPLICATE_REASON_LABELS`(D3);server 與對話框共用
- [x] 2.2 `duplicate-dialog.tsx` 改用通用警示文字並逐案列出原因;`duplicate-notice.tsx` 顯示原因(舊 `attachment` 為「附件相同」)
- [x] 2.3 CLAUDE.md「Duplicate detection」更新判斷條件與原因
## 3. 驗證
- [ ] 3.1 e2e `duplicates.spec.ts`:相同欄位 → 警示顯示「平台、刷卡日期與金額相同」;不同平台/日期/金額但共用刷卡帳單 → 直接送出;不同平台、同日期同金額、共用刷卡帳單 → 直接送出;Invoice 相同 → 警示顯示「Invoice 內容與此案件相同」;主管詳情顯示原因
- [ ] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 3.3 使用者授權後 push 部署;使用者驗收:正式站以共用刷卡帳單送出兩筆不同訂閱
- [x] 3.1 e2e `duplicates.spec.ts`:相同欄位 → 警示顯示「平台、刷卡日期與金額相同」;不同平台/日期/金額但共用刷卡帳單 → 直接送出;不同平台、同日期同金額、共用刷卡帳單 → 直接送出;Invoice 相同 → 警示顯示「Invoice 內容與此案件相同」;主管詳情顯示原因
- [x] 3.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 3.3 使用者授權後 push 部署;使用者驗收:正式站以共用刷卡帳單送出兩筆不同訂閱(2026-10-22 使用者驗收通過)
@@ -0,0 +1,10 @@
## 1. 版面
- [x] 1.1 逐筆檢視右側詳情 sticky、限制高度、獨立捲動(D1),系統時間提示列存在時的偏移
- [x] 1.2 切換案件時詳情捲回頂端(D2)
## 2. 驗證
- [x] 2.1 e2e(1440×900,案件詳情夠長):捲動詳情時左側清單 `scrollY`/位置不變;捲動頁面時詳情仍在可視範圍;捲到底後點另一筆,詳情 `scrollTop` 為 0;條列檢視不受影響
- [x] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 2.3 使用者授權後 push 部署;使用者驗收(2026-10-22 使用者驗收通過)
@@ -1,9 +1,9 @@
## 1. 頁面
- [ ] 1.1 `help/page.tsx` 依 D1 判斷角色,「部門月結(主管)」「核定與發放(管理端)」「更正與發放失敗(管理端)」只對主管、管理者、系統管理員輸出(D2)
- [x] 1.1 `help/page.tsx` 依 D1 判斷角色,「部門月結(主管)」「核定與發放(管理端)」「更正與發放失敗(管理端)」只對主管、管理者、系統管理員輸出(D2)
## 2. 驗證
- [ ] 2.1 e2e:員工開啟使用說明看得到申請流程、補助怎麼算、截止日,看不到三個主管端/管理端段落;主管、管理者、系統管理員看得到全部
- [ ] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 2.3 使用者授權後 push 部署;使用者驗收:以員工與主管帳號分別開啟使用說明
- [x] 2.1 e2e:員工開啟使用說明看得到申請流程、補助怎麼算、截止日,看不到三個主管端/管理端段落;主管、管理者、系統管理員看得到全部
- [x] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [x] 2.3 使用者授權後 push 部署;使用者驗收:以員工與主管帳號分別開啟使用說明(2026-10-22 使用者驗收通過)
@@ -6,10 +6,9 @@
## What Changes
- 部門月結頁額度區改為四欄:**計算人數|月上限|支付金額合計|超額**。
- 「支付金額合計」為新的一欄,金額為分配明細「支付金額(當月合計)」的合計;未提交的試算為即時值(與明細一致)。
- 「超額」下方保留小字「個人上限合計 NT$x」,說明超額的計算基準(使用者選擇)。
- 手機寬度維持兩欄排列(計算人數、月上限/支付金額合計、超額)。
- 部門月結頁額度區改為四欄:**計算人數|月上限|補助合計|超額**(2026-10-20 部署後使用者再調整:原本的「支付金額合計」欄改為「補助合計」,數字為個人上限合計;超額下方不再另列小字)。
- 「補助合計」為個人上限合計(每人支付金額 50% 的加總,超額依它判斷);未提交的試算為即時值(與明細一致)。支付金額合計只留在分配明細的合計列。
- 手機寬度維持兩欄排列(計算人數、月上限/補助合計、超額)。
- 管理端全公司月結詳情不變。
## Capabilities
@@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: 額度區顯示補助合計
部門月結頁的額度區 SHALL 依序顯示四欄:計算人數、月上限、補助合計、超額。補助合計 SHALL 等於分配明細「個人上限」欄的合計(每人支付金額 50% 的加總),也就是判斷超額的基準;未提交的試算為即時值。超額 SHALL 等於補助合計 − 月上限(最低為 0)。額度區 MUST NOT 顯示每人額度,也不另外顯示支付金額合計(支付金額合計在分配明細的合計列)。
#### Scenario: 額度區四欄
- **WHEN** 研發部主管開啟 2026/09 部門月結,計算人數 27 人、月上限 NT$27,000、支付金額合計 NT$8,194、個人上限合計 NT$4,097
- **THEN** 額度區依序顯示「計算人數 27 人」「月上限 NT$27,000」「補助合計 NT$4,097」「超額 NT$0」,不顯示每人額度
#### Scenario: 試算後又有案件核准
- **WHEN** 已存試算後又有一筆 NT$600 的案件核准
- **THEN** 補助合計立即增加 NT$300,與分配明細的個人上限合計一致
@@ -7,4 +7,5 @@
- [x] 2.1 e2e `settlement.spec.ts`:額度區四欄順序與金額、無每人額度、試算後新核准案件的支付金額合計即時更新
- [x] 2.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過
- [ ] 2.3 使用者授權後與 `cap-personal-subsidy-at-half` 一起(或之後)push 部署;使用者驗收
- [x] 2.4 使用者再調整(2026-10-20):第三欄改為「補助合計」=個人上限合計,移除超額下方小字;e2e 更新
- [x] 2.3 使用者授權後與 `cap-personal-subsidy-at-half` 一起(或之後)push 部署;使用者驗收(2026-10-22 使用者驗收通過)
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-22
@@ -0,0 +1,133 @@
## Context
- **每日名冊同步**(`src/server/hr-sync/roster.ts` 的 `runRosterSync`)已抓取:
- 現況名冊、組織樹;
- 本月 1 日與上月 1 日的名冊和組織樹。
- **處理步驟**依序為:部門 → 正職歷程 → 快照(`syncSnapshotsFromHr`),每步一個交易。
- **人數計算**:快照只計 1 日 ACTIVE 且正職的人,所以離職或留停的人本來就不計入。
- **名冊欄位**:`rosterEntrySchema` 目前只留 `employeeNumber`、`status`、`departmentCode`、`employeeGroupCode`、`hireDate`。HR API 另有:
- `name`(帶 `date` 時為該日姓名);
- `leaveDate`(離職生效日,現況值);
- `suspendedSince`(留停起日,現況值)。
- **狀態值**:現況名冊只有 `ACTIVE`、`SUSPENDED`、`OFFBOARDED` 三種。HR 手冊提醒:「`status=ACTIVE` 可能含少數實際已離職者」,所以要保留人工停用。
- **帳號停用**:`setAccountActive`(`src/server/org/accounts.ts`)會停用帳號、刪除 sessions、寫部門歷程 null,並記錄 `account.deactivated`。
- `provisionOnLogin` 拒絕停用帳號,而且在 HR 同步之前就拒絕。
- `session.ts` 每次請求檢查 `users.active`。
- **權限**:
- `/admin/settings`(含人數快照分頁)開放 admin 與 sysadmin。
- `/admin/accounts` 只開放 sysadmin。
- 目前規格要求「人數快照只顯示部門合計」,所以名單是權限範圍的擴大。這是使用者 2026-10-22 的決定,`identity-access` 一併修改。
## Goals / Non-Goals
**Goals:**
- 快照可展開 1 日名單:計入/不計入(留停)/不計入(離職)/不計入。
- 名冊同步依 HR 現況停用離職/留停帳號,留停復職自動恢復。
- 帳號列表顯示 HR 在職狀態。
**Non-Goals:**
- 不改人數規則(仍以 1 日為準)。月中異動不改當月人數。
- 不為從未登入的人建立帳號。名單直接用 HR 的員工編號與姓名,不需要帳號。
- 不處理被停用者擔任主管的情況。主管仍由組織結構同步決定,停用帳號本來就不能登入審核。
- 登入時不即時判斷離職。停用帳號在登入前就被拒絕,最多延遲到當天的名冊同步。
## Decisions
### D1 名單存成快照的附表,跟著人數一起更新
- **新表** `headcount_snapshot_members`:
- 欄位:`snapshot_id`、`employee_no`、`name`、`status`(`counted` | `suspended` | `offboarded` | `excluded`)。
- 主鍵為 (`snapshot_id`, `employee_no`)。
- **寫入時機**:`syncSnapshotsFromHr` 在同一交易中寫入,條件與人數相同(未鎖定且沒有人工調整)。方式是先刪掉該快照的舊名單,再寫入新的。
- **觸發器**:
- 這張表可以整批替換,所以不設「只新增」觸發器。
- 改為:快照 `locked = 1` 時,DB 觸發器拒絕 INSERT/DELETE 該快照的名單,與月結鎖定同一層保護。
- **操作紀錄**:
- 建立快照時,在 `snapshot_created` 的 `after` 加 `members`(筆數)。
- 人數變了:在 `snapshot_synced` 的 `after` 加 `members`。
- 人數沒變、名單變了:記 `headcount.snapshot_members_updated`,只寫各狀態筆數,不寫姓名。
- **清除業務資料**:表加入 `BUSINESS_TABLES`,排在 `headcount_snapshots` 前面(外鍵順序)。
- **為什麼存起來而不是即時算**:
- 鎖定後,名單必須和當時的人數一致,不能因 HR 之後補登而改變。
- 檢視頁也不能查 HR(規定沒有 HR 查詢入口)。
**替代方案**:只存 JSON 欄位在 `headcount_snapshots`。沒採用,因為觸發器和清除業務資料都比較難處理,個別查詢也不方便。
### D2 名單狀態的判定
以該月 1 日名冊(`rosterOnFirst`)為準,對每筆資料:
1. 決定部門(`division(departmentCode)`,與人數同一套規則)。
- 沒有 `departmentCode` 的留停或離職者,改用上個月快照名單中同員工編號的部門。
- 還是找不到就略過。
2. 判定狀態:
- `ACTIVE` 且正職 → `counted`。
- `ACTIVE` 但非正職 → `excluded`。
- `SUSPENDED` → `suspended`。
- `OFFBOARDED`:`leaveDate` 在上個月 1 日(含)之後 → `offboarded`;更早或沒有 `leaveDate` → 略過,避免列出多年前離職的人。
- `NOT_YET_HIRED` → 略過。
不變式:`counted` 的筆數 = `computedHeadcount`。單元測試要檢查這一點。
`leaveDate` 是現況值,不是該日值,但只用來判斷「是否為近期離職」,影響可以接受。
### D3 本系統計算的快照:檢視時即時列出
- 沒有 HR 名單的快照(`source = local`),在檢視時用與 `localHeadcount` 同一套邏輯列出 1 日成員:
- 有正職歷程時,非正職列為 `excluded`,其餘為 `counted`。
- 沒有離職/留停原因。
- 部門歷程只會新增,所以結果穩定。
- `source = hr` 但名單為空的舊快照,顯示「此快照沒有名單紀錄」。
### D4 帳號的 HR 狀態欄位與停用規則
- **`users` 新增欄位**:
- `hr_status`:`ACTIVE` | `SUSPENDED` | `OFFBOARDED` | null。
- `hr_status_since`:留停起日或離職生效日,`YYYY-MM-DD`。
- `hr_deactivated`:boolean,預設 false。
- **名冊同步新步驟** `employment_status`:在快照之後執行,用現況名冊,自己一個交易。對名冊中有帳號的人:
- 更新 `hr_status` 與 `hr_status_since`。只有值改變時才寫,不另記操作紀錄(屬於同步資料,比照正職歷程)。
- 非在職且 `active = true`:
- 設 `active = false`、`hr_deactivated = true`,刪除 sessions。
- 寫部門歷程 null,日期 = clamp(HR 日期,最後一筆歷程日期,今天)。
- 記錄 `account.hr_deactivated`(`after: { hrStatus, since }`)。
- 在職且 `active = false` 且 `hr_deactivated = true`:
- 設 `active = true`、`hr_deactivated = false`。
- `departmentId` 不為 null 時,寫部門歷程(今天、原部門)。
- 記錄 `account.hr_reactivated`。
- **後台**:
- 手動停用:`hr_deactivated` 維持 false,所以名冊同步永遠不會自動啟用。
- 手動啟用:`hr_status` 不是在職時拒絕,錯誤為 `HR_INACTIVE_ACCOUNT_ERROR`。成功時清除 `hr_deactivated`。
- **日期換算**:HR 日期是 ISO 字串(`2026-11-01T00:00:00.000Z`)。取 Asia/Taipei 日期,沿用 `transferEffectiveDate` 的日期換算。
- **共用函式**:抽出 `deactivateUser(tx, …)`,給 `setAccountActive` 與名冊同步共用:刪 sessions、寫歷程。
### D5 頁面
- **人數快照表**:每個部門列加「名單」展開,與既有「調整紀錄」展開並列。名單依狀態排序(計入 → 不計入(留停)→ 不計入(離職)→ 不計入),各組再依員工編號排序。展開區上方顯示各狀態人數。
- **帳號列表**:加「HR 狀態」欄。由 HR 停用的帳號,在停用標示旁寫「由 HR 停用」。HR 非在職時,啟用按鈕停用並顯示原因。
- **權限**:名單資料只在 `/admin/settings` 伺服器端讀取,該頁已限 admin/sysadmin。`visibility.spec.ts` 補一個案例:主管開設定頁被拒絕,頁面裡沒有名單。
## Risks / Trade-offs
- **[推得出非正職身分]** 名單中「不計入」又沒寫原因的人,看名單的管理者可以推得他是非正職。
- 使用者已選擇這個呈現方式(2026-10-22)。
- 能看名單的只有管理者(人資/財務)與系統管理員,他們本來就掌握人事資料。
- 在 identity-access 中明文記錄。
- **[HR 狀態延遲或錯誤]** HR 可能把已離職者暫時留在 ACTIVE。
- 保留手動停用,且手動停用不會被自動啟用。
- 反過來,HR 誤標離職時,人事更正 HR 後,下一次名冊同步才會恢復。這是「由 HR 停用」帳號唯一的恢復方式,比照 HR 為準的原則。
- **[復職到能登入有延遲]** 復職者要等當天有人登入、觸發名冊同步後才恢復。系統管理員可用「下次登入時重新同步名冊」加速。
- **[舊快照沒有名單]** 上線前建立、又已鎖定的快照永遠沒有名單,畫面會明確說明。
## Migration Plan
- **Migration**(`npm run db:generate`):
- 新表與鎖定觸發器;
- `users` 三個欄位,預設 null/false。
- **上線後**:第一次名冊同步會補上本月與上月未鎖定快照的名單,並為現有帳號寫入 HR 狀態。
- 這次同步會一次停用所有目前已離職或留停的帳號。屬於預期行為,上線說明要提醒。
- **回復**:程式回到前一版即可。欄位與表留著無害;已被停用的帳號可由系統管理員手動處理。
## Open Questions
- 離職者在該日名冊是否仍帶 `departmentCode`,API 手冊沒有明寫。D2 已有退路(上個月名單)。實作時用正式站的名冊同步紀錄驗證筆數。
@@ -0,0 +1,63 @@
## Why
roadmap 5.2(`integrate-hr-org-sync`)只剩離職/留停沒做。每日名冊同步已經只把 1 日在職(ACTIVE)的正職算進人數快照,但現在有三個缺口:
- 管理者看不到快照是由哪些人組成,誰因離職或留停沒被算進去。
- 離職或留停的人帳號沒有停用,還能登入。
- 後台帳號也看不到 HR 的在職狀態。
使用者 2026-10-22 決定一起補齊。本 change 完成後,roadmap 5.2 即全部完成(plan-system-roadmap 已歸檔,記錄於此)。
## What Changes
- **快照人員名單**:後台設定「人數快照」的每個部門可展開該月 1 日的名單。
- 「計入」:1 日在職的正職。
- 「不計入(留停)」「不計入(離職)」:寫出原因。
- 「不計入」:1 日在職但非正職的人,**不寫原因**,維持不公開個人正職身分的決定。
- HR 名冊產生的快照:名冊同步時保存名單,鎖定後不再變動。
- 本系統計算的快照(沒有 HR 資料的部門):顯示依部門歷程算出的成員,沒有離職/留停原因。
- **離職/留停停用帳號**:每日名冊同步依 HR 現況名冊處理。
- 狀態為離職(OFFBOARDED)或留停(SUSPENDED)的人,帳號自動停用:不能登入,現有登入狀態失效。
- 停用時,自離職生效日/留停起日起不再隸屬部門。
- 留停者在 HR 名冊回到在職時,自動重新啟用。
- 管理者手動停用的帳號,MUST NOT 被自動啟用。
- **帳號列表顯示 HR 在職狀態**:在職/留停/離職,沒有 HR 資料時顯示「—」。
- 由 HR 停用的帳號標示「由 HR 停用」。
- HR 狀態不是在職時,管理者不能手動重新啟用。
- **HR 欄位**:名冊多保存姓名、離職生效日、留停起日(僅供上述用途)。
- **規則不變**:人數規則仍以 1 日 00:00 為準。月中離職或留停不改變當月人數。已鎖定的快照與已提交的月結不受影響。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `headcount-snapshot`:新增「快照人員名單」需求。
- `hr-sync`:
- 新增「依 HR 在職狀態停用與恢復帳號」需求。
- 修改「HR 資料只在伺服器端使用」:保存的欄位加上姓名、離職生效日、留停起日。
- `org-directory`:新增「帳號顯示 HR 在職狀態」需求,包含 HR 停用的帳號不能手動啟用。
- `identity-access`:修改「資料範圍控制」:管理者與系統管理員可在人數快照看到各部門 1 日名單的姓名與員工編號;逐人正職身分仍不顯示。
## Impact
- **資料庫(migration)**:
- 新表 `headcount_snapshot_members`:快照 id、員工編號、姓名、名單狀態。
- `users` 加 `hr_status`、`hr_status_since`、`hr_deactivated`。
- **名冊同步**:
- `src/server/hr-sync/client.ts`:名冊 schema 加 `name`、`leaveDate`、`suspendedSince`。
- `src/server/hr-sync/roster.ts`:新增「在職狀態」步驟,在自己的交易中執行。
- `src/server/rules/headcount.ts`:`syncSnapshotsFromHr` 一併寫名單。
- **帳號**:
- `src/server/org/accounts.ts`:清單帶出 HR 狀態;`setAccountActive` 拒絕重新啟用 HR 非在職的帳號。
- `/admin/accounts` 頁面。
- **頁面**:`/admin/settings?tab=headcount` 可展開名單(管理者、系統管理員)。
- **其他**:
- 操作紀錄新增 `account.hr_deactivated`、`account.hr_reactivated`、`headcount.snapshot_members_updated`。
- 清除業務資料:新表加入 `BUSINESS_TABLES`。
- 測試:unit(名冊同步、快照名單、帳號停用/恢復);e2e(快照名單顯示、帳號列表 HR 狀態、`visibility.spec.ts` 名單只有管理者與系統管理員看得到)。
- 文件:CLAUDE.md HR Sync 段落。
- **不影響**:申請、審核、月結計算、發放。被停用者已核准的案件照常月結與發放。
@@ -0,0 +1,42 @@
## ADDED Requirements
### Requirement: 快照人員名單
管理者與系統管理員 SHALL 能在後台設定頁的人數快照中,展開每個部門某月的 1 日名單,看出快照人數由哪些人組成。名單每列顯示員工編號、姓名與名單狀態:
- 「計入」:該日在職且為正職,計入快照人數。
- 「不計入(留停)」:該日 HR 狀態為留停。
- 「不計入(離職)」:該日已離職,且離職生效日在上個月 1 日(含)之後。更早離職的人不列出。
- 「不計入」:其他不計入的人(該日在職但非正職)。MUST NOT 顯示原因,逐人正職身分不公開。
規則如下:
- 「計入」的人數 MUST 等於快照的計算人數。人工調整後的人數另以調整紀錄說明。
- 由 HR 名冊產生的快照,名單 SHALL 在名冊同步更新快照時一併保存。
- 部門歸屬與人數相同:依該日所屬單位歸到部門。
- 留停或離職者在該日名冊沒有所屬單位時,以上個月快照名單中的部門歸屬;仍找不到時不列出。
- 名單與快照人數一起更新:快照已鎖定或有人工調整時,名單 MUST NOT 變動。
- 本系統計算的快照(沒有 HR 名冊資料的部門),名單 SHALL 列出依部門歷程在 1 日隸屬該部門的成員。
- 有正職身分資料時,非正職者列為「不計入」。
- 不提供離職/留停原因。
- 建立於名單功能上線前、之後也未再更新的 HR 快照,SHALL 顯示「此快照沒有名單紀錄」。
- 名單 MUST NOT 出現在部門主管或員工可見的任何頁面或匯出。
#### Scenario: 展開名單看到計入與不計入
- **WHEN** 2026/11/01 HR 名冊中設計部有 20 位在職正職、1 位工讀生、1 位留停,另有 1 位 10/31 離職,管理者在 2026/11 的人數快照展開設計部
- **THEN** 名單列出 20 位「計入」、1 位「不計入」(不寫原因)、1 位「不計入(留停)」、1 位「不計入(離職)」,快照人數為 20
#### Scenario: 早已離職的人不列出
- **WHEN** 某人 2026/08/15 已離職,管理者展開 2026/11 設計部名單
- **THEN** 名單沒有這個人
#### Scenario: 鎖定後名單不變
- **WHEN** 研發部 2026/10 月結已提交(快照鎖定),之後 HR 補登一位 9 月留停的研發部員工
- **THEN** 2026/10 研發部的名單與人數都維持鎖定時的內容
#### Scenario: 本系統計算的部門
- **WHEN** 管理者展開一個沒有部門代碼、由本系統計算人數的部門
- **THEN** 名單列出 1 日隸屬該部門的成員,沒有離職或留停原因
#### Scenario: 主管看不到名單
- **WHEN** 部門主管直接請求後台設定頁的人數快照或其名單
- **THEN** 系統拒絕存取
@@ -0,0 +1,43 @@
## ADDED Requirements
### Requirement: 依 HR 在職狀態停用與恢復帳號
每日名冊同步 SHALL 依 HR 現況名冊,更新本系統既有帳號的 HR 在職狀態:在職、留停或離職,以及留停起日或離職生效日。HR 名冊中沒有的員工編號 MUST NOT 被改變。
- **停用**:HR 狀態為留停或離職、且帳號目前啟用時,系統 SHALL 停用該帳號並標記「由 HR 停用」。
- 該帳號不能登入,現有的登入狀態 MUST 立即失效。
- 自留停起日或離職生效日起,SHALL 不再隸屬任何部門。日期早於該帳號最後一筆部門歷程時,以最後一筆的日期為準;晚於當日時以當日為準。
- **恢復**:HR 狀態回到在職、且帳號是「由 HR 停用」的,系統 SHALL 重新啟用。
- 自當日起恢復原部門。之後登入時的 HR 同步依 HR 更新部門。
- **不自動啟用**:管理者手動停用的帳號 MUST NOT 因 HR 狀態為在職而被自動啟用。
- **操作紀錄**:每次停用與恢復 SHALL 寫入操作紀錄(操作者「系統(HR 同步)」,含 HR 狀態與日期)。
- **失敗處理**:此步驟失敗時 SHALL 記錄失敗階段,MUST NOT 改變任何帳號。
- **已有資料不受影響**:被停用者的既有申請、月結與發放資料 MUST 保留,並照原流程處理。
#### Scenario: 離職停用
- **WHEN** 2026/11/03 的名冊同步看到王小明(帳號啟用中)狀態為離職,離職生效日 2026/11/01
- **THEN** 王小明的帳號停用並標示「由 HR 停用」,已開啟的頁面下一次請求即被登出,自 11/01 起不隸屬任何部門,操作紀錄記錄這次停用
#### Scenario: 留停後復職
- **WHEN** 陳小華 2026/11 留停被 HR 停用,2027/02/05 的名冊同步看到她狀態回到在職
- **THEN** 陳小華的帳號自動重新啟用並自 2/05 起恢復原部門,可以再登入
#### Scenario: 手動停用不會被自動啟用
- **WHEN** 系統管理員手動停用李大同的帳號,之後名冊同步看到李大同 HR 狀態為在職
- **THEN** 李大同的帳號維持停用
#### Scenario: 已核准案件照常月結
- **WHEN** 王小明 2026/10 有已核准的案件,11/03 因離職被停用
- **THEN** 該案件照常列入 2026/10 研發部月結並發放
## MODIFIED Requirements
### Requirement: HR 資料只在伺服器端使用
HR Sync 不限制查詢者能查哪些員工,本系統 SHALL 自行負責 HR 資料的權限邊界:HR Sync 的查詢 MUST 只由伺服器端的同步流程發起,查詢對象只能是登入者本人(員工編號取自已驗證的登入身分)或名冊同步所需的全公司名冊;系統 MUST NOT 提供任何頁面、Server Action 或 Route Handler 讓使用者指定員工編號、部門或日期去查詢 HR Sync,MUST NOT 把 HR Sync token 或原始回應送到瀏覽器。本系統只保存同步所需的欄位(名冊:員工編號、姓名、狀態、部門代碼、員工群組、到職日、離職生效日、留停起日),其可見範圍依 identity-access「資料範圍控制」。
#### Scenario: 沒有查詢 HR 的入口
- **WHEN** 任何角色嘗試以網址或請求參數指定他人員工編號查詢 HR 資料
- **THEN** 系統沒有對應的入口,不會向 HR Sync 發出該查詢
#### Scenario: 不保存未使用的欄位
- **WHEN** 名冊同步回應中含有 email、職稱、英文名等本系統用不到的欄位
- **THEN** 系統只保存員工編號、姓名、狀態、部門代碼、員工群組、到職日、離職生效日與留停起日等同步所需欄位,其餘丟棄
@@ -0,0 +1,40 @@
## MODIFIED Requirements
### Requirement: 資料範圍控制
系統 MUST 依角色限制可讀寫的資料,個人資料(姓名、員工編號、部門、正職身分、到職日等來自 HR 同步或帳號的資料)與申請、月結、發放資料適用同一範圍:員工僅能存取本人的資料與申請,部門層級只能看到合計數字(例如部門本月補助使用情況、快照人數),MUST NOT 看到其他同仁的個人資料或申請;部門主管(HR 主要主管)僅能存取歸屬其所轄部門的申請與月結,以及其中成員的個人資料;歸屬依案件的部門,調部門前月份歸屬原部門的案件由原部門主管存取;沒有部門主管角色的人(含 HR 次要主管)與員工相同,只能存取本人;管理者可存取全公司申請、月結與發放資料及其中申請人的個人資料;系統管理員可存取設定、帳號與操作紀錄;管理者與系統管理員可在人數快照看到各部門 1 日名單(員工編號、姓名、計入與否,以及留停或離職的原因,見 headcount-snapshot「快照人員名單」)。逐人的正職身分 MUST NOT 顯示於任何頁面或匯出,只用於人數合計:名單中非正職者只標示「不計入」,不寫原因。超出範圍的存取 MUST 被拒絕,即使直接呼叫 API、Server Action 或輸入網址。
#### Scenario: 員工存取他人申請
- **WHEN** 員工直接開啟他人申請的網址
- **THEN** 系統回應無權限,不顯示該申請內容
#### Scenario: 主管存取其他部門
- **WHEN** 設計部主管要求研發部的申請清單
- **THEN** 系統拒絕並回傳無權限
#### Scenario: 管理者查看全公司
- **WHEN** 管理者開啟全公司月結
- **THEN** 系統顯示所有部門資料
#### Scenario: 員工只看到部門合計
- **WHEN** 設計部員工王小明開啟首頁
- **THEN** 部門本月補助使用情況只顯示部門合計與月上限,不顯示其他同仁的姓名或金額
#### Scenario: 次要主管只看到本人
- **WHEN** HR 中為設計部次要主管的陳組長登入
- **THEN** 他沒有部門審核與部門月結,只看得到自己的申請;直接開啟同部門他人申請的網址被拒絕
#### Scenario: 主要主管只看到所轄部門成員
- **WHEN** 設計部主要主管李經理開啟部門審核與部門月結
- **THEN** 只列出歸屬設計部的案件與成員;直接開啟研發部案件或研發部月結匯出被拒絕
#### Scenario: 調部門前的案件
- **WHEN** 王小明 9/15 由設計部調至研發部,他 2026/09 的案件歸屬設計部
- **THEN** 設計部主管可檢視與審核該案件;研發部主管看不到該案件
#### Scenario: 不顯示逐人正職身分
- **WHEN** 任何角色瀏覽頁面或下載匯出檔
- **THEN** 看不到任何人的正職或工讀身分;人數快照名單中的非正職者只顯示「不計入」,不寫原因
#### Scenario: 快照名單限管理者與系統管理員
- **WHEN** 部門主管或員工直接開啟後台設定頁的人數快照
- **THEN** 系統拒絕存取,看不到任何部門的 1 日名單
@@ -0,0 +1,21 @@
## ADDED Requirements
### Requirement: 帳號顯示 HR 在職狀態
系統管理員的帳號列表 SHALL 顯示每個帳號最近一次名冊同步取得的 HR 在職狀態:「在職」「留停」「離職」,沒有 HR 資料時顯示「—」。
- 留停與離職 SHALL 一併顯示留停起日或離職生效日。
- 由 HR 停用的帳號 SHALL 標示「由 HR 停用」,與手動停用區分。
- HR 狀態不是在職時,系統管理員 MUST NOT 能手動重新啟用該帳號,介面與伺服器端都要拒絕,並說明「HR 狀態為留停/離職,無法啟用」。
- 手動停用 HR 在職的帳號仍 SHALL 可行,例如 HR 資料尚未更新的實際離職者。
#### Scenario: 帳號列表顯示狀態
- **WHEN** 系統管理員開啟帳號與角色
- **THEN** 王小明顯示「離職(2026/11/01)・由 HR 停用」,陳小華顯示「在職」,從未出現在 HR 名冊的測試帳號顯示「—」
#### Scenario: 不能啟用 HR 離職的帳號
- **WHEN** 系統管理員嘗試重新啟用 HR 狀態為離職的王小明
- **THEN** 系統拒絕並說明「HR 狀態為離職,無法啟用」,帳號維持停用
#### Scenario: HR 在職但手動停用
- **WHEN** 李大同 HR 狀態為在職,系統管理員手動停用他
- **THEN** 停用成功,帳號顯示「在職」與「已停用」,之後的名冊同步不會自動啟用
@@ -0,0 +1,55 @@
## 1. 資料
- [x] 1.1 schema:
- 新表 `headcount_snapshot_members`(`snapshot_id`、`employee_no`、`name`、`status`;主鍵 (`snapshot_id`, `employee_no`));
- `users` 加 `hr_status`、`hr_status_since`、`hr_deactivated`。
- `npm run db:generate`,再補上「快照鎖定時拒絕寫入名單」的觸發器(D1)。
- [x] 1.2 `BUSINESS_TABLES` 加入新表(排在 `headcount_snapshots` 之前)。測試:清除後名單一併清空、觸發器重建。
- [x] 1.3 `AUDIT_ACTIONS` 加 `account.hr_deactivated`、`account.hr_reactivated`、`headcount.snapshot_members_updated`。
- [x] 1.4 `rosterEntrySchema` 加 `name`、`leaveDate`、`suspendedSince`。測試:其他欄位仍丟棄。
## 2. 快照名單
- [x] 2.1 `syncSnapshotsFromHr` 依 D2 產生名單,在同一交易中與人數一起建立或替換;人數不變但名單變時記 `snapshot_members_updated`。單元測試涵蓋:
- 計入/不計入(非正職,不帶原因)/留停/近期離職/早已離職不列;
- 沒有部門代碼的留停者用上個月名單歸屬;
- `counted` 筆數 = 人數;
- 鎖定或人工調整後不變;
- 觸發器擋下鎖定快照的寫入。
- [x] 2.2 快照名單讀取函式:
- HR 快照讀名單表;
- 本系統快照依 D3 即時列出;
- HR 快照沒有名單時回傳「沒有名單紀錄」。
- 測試涵蓋三種來源。
## 3. 帳號狀態
- [x] 3.1 抽出共用的停用/啟用函式(刪 sessions、寫部門歷程),`setAccountActive` 改用它。HR 狀態非在職時拒絕手動啟用(`HR_INACTIVE_ACCOUNT_ERROR`),手動啟用成功時清除 `hr_deactivated`。測試。
- [x] 3.2 名冊同步新增 `employment_status` 步驟(D4),在快照之後、自己的交易中執行:更新 HR 狀態;離職/留停停用並標記;`hr_deactivated` 的帳號在 HR 在職時恢復;手動停用者不動;部門歷程日期 clamp;失敗時記錄階段、不改帳號。單元測試涵蓋各情境與名冊中沒有的員工編號。
- [x] 3.3 `listAccounts` 帶出 HR 狀態、日期與 `hr_deactivated`。
## 4. 頁面
- [x] 4.1 `/admin/settings?tab=headcount`:每個部門列可展開名單,含狀態分組、各狀態人數與「此快照沒有名單紀錄」;非正職只顯示「不計入」。
- [x] 4.2 `/admin/accounts`:
- 加「HR 狀態」欄(在職/留停(日期)/離職(日期)/—);
- 由 HR 停用的帳號標示「由 HR 停用」;
- HR 非在職時不能按啟用,並說明原因。
## 5. 文件
- [x] 5.1 CLAUDE.md 的 HR Sync 段落:
- 名冊同步多了在職狀態步驟;
- 保存欄位加上姓名、離職生效日、留停起日;
- 補上快照名單與帳號停用規則。
- 「Per-person full-time status is never shown」補上名單呈現方式。
## 6. 驗證
- [x] 6.1 e2e(不寫 `hr_employment_history`;用 `markSnapshotFromHr`/新的 db helper 模擬名單與 HR 狀態):
- 管理者展開快照名單看到四種狀態;
- 系統管理員看到帳號 HR 狀態與「由 HR 停用」,且無法啟用;
- `visibility.spec.ts`:主管開設定頁被拒絕。
- [x] 6.2 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 e2e 全過。
- [ ] 6.3 使用者授權後 push 部署。上線說明要提醒:第一次名冊同步會停用目前已離職/留停的帳號。使用者驗收:正式站快照名單與帳號 HR 狀態。
- [x] 6.4 roadmap 5.2 完成註記(plan-system-roadmap 已歸檔,在本 change 的 proposal 註明即可)。
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-28
retire_capabilities: true
@@ -0,0 +1,94 @@
# Design
## Context
目前月結的流程是:最終核定 → 建立 `payout_records`(原核定)→ 在 `/admin/payments` 匯出名單,逐筆標記已發放或發放失敗 → 全部處理完,月結才變成 `paid`。
案件也跟著轉成 `paid`(`TRANSITIONS` 的 `pay`)。
最終核定之後的更正(`settlement_corrections`)也依賴發放紀錄:
- 補發與改期會建立新的發放項目。
- 撤銷會取消待發放的項目。
- 只有改期能用在發放失敗的項目上。
- 月結是否 `paid` 由 `settleIfComplete` 判斷。
正式站還在試營運,已有測試資料(核定、發放、更正),也有「清除業務資料」可以在正式使用前清掉。
## Goals / Non-Goals
**Goals:**
- 系統只到最終核定為止。核定名單可以在全公司月結頁匯出,交給薪資作業。
- 拿掉所有發放與更正的頁面、操作、通知與說明文字。
- 舊資料(已發放的案件與月結、舊的發放紀錄與更正紀錄)不壞、不消失,仍可讀。
**Non-Goals:**
- 不刪資料表、不寫刪除資料的 migration(D3)。
- 不提供最終核定後的任何調整方式。核定前發現錯誤,只能退回。
- 不改月結計算、部門月結、提交與退回的規則。
## Decisions
### D1. 匯出改由月結分配算出,不用發放紀錄
匯出「核定名單」時直接讀 `settlement_allocations`,不讀 `payout_records`:
- 條件:所選刷卡月份、月結狀態為 `finalized` 或舊的 `paid`、最終補助大於 0。
- 發放月份用 `payoutMonth(month)`,名目固定「其他獎金」。
理由:不再建立發放紀錄,新的核定月結本來就沒有發放紀錄。用分配結果一律算得出來,舊資料也一樣。
其他做法:繼續在核定時建 `payout_records` 只拿來匯出。不採用,因為這等於留下一份沒人更新狀態的資料。
匯出欄位:
- `PAYOUT_EXPORT_COLUMNS` 縮成前 7 欄:發放月份、員工編號、姓名、部門、刷卡月份、補助金額、薪資名目。
- `docs/operations/payout-export.md` 同步改寫,原本比對兩者的測試保留。
位置與紀錄:
- 匯出 route 放在 `/admin/settlements/export`,權限與全公司月結相同(`requireRole("admin")`),參數是 `month`、`format`。
- 操作紀錄沿用 `payout.exported`,標籤改為「匯出核定名單」,只記月份、格式與筆數。舊紀錄因此也顯示新標籤。
### D2. 狀態:保留 `paid` 這個值,但不再轉入
- 案件狀態 `paid`、月結狀態 `paid` 都保留在型別與標籤裡,舊資料才能顯示「已發放」。
- `TRANSITIONS` 拿掉 `pay`,因此沒有任何程式路徑能再轉入 `paid`。
- 「已提交以後」「已核定以後」的判斷(例如 `SUBMITTED_STATUSES`、鎖定、可見性)照舊包含 `paid`,舊資料的行為不變。
- 篩選選項與統計:已核定的計數一律算成 `finalized` 加 `paid`。總覽的「已核定人數」也一樣。
### D3. 舊的發放紀錄與更正紀錄:保留但不顯示
- `payout_records`、`settlement_corrections` 兩張表與它們的 DB trigger 都保留,仍列在 `BUSINESS_TABLES`,「清除業務資料」照樣清得掉。
- 程式不再讀寫這兩張表。唯一例外是「清除業務資料」,它需要先計算筆數,之後才能刪除。
- 更正影響過的舊月結會改顯示**原核定金額**,不再顯示更正後金額,匯出也是原核定金額。這些都是試營運資料,風險可以接受;正式使用前建議清除業務資料。
- 部署前要先查正式站有沒有更正紀錄(tasks 7.1)。有的話,先讓使用者決定是否清除業務資料。
其他做法:
- 寫 migration 刪掉兩張表。不採用:資料不可逆地消失,而且 append-only 的 trigger 需要額外處理。
- 留一個唯讀的舊更正列表。不採用:使用者明確要求整個拿掉。
### D4. 刪掉的程式
- 頁面:`/admin/payments` 整個目錄、管理端月結詳情的更正卡片與操作(`corrections-card.tsx`、`correction-actions.tsx`、`components/settlement/correction-list.tsx`)。
- 服務:
- `src/server/settlement/corrections.ts`、`src/domain/corrections.ts`。
- `payouts.ts` 的清單、標記、`settleIfComplete`。
- `finalizeSettlement` 裡建立發放紀錄的部分。
- 通知:`notifyPayoutPaid`,以及 `NOTIFICATION_TYPES` 的 `payout.paid`。舊通知的型別標籤保留,讓清單還能顯示。
- 操作紀錄:
- 不能從 `AUDIT_ACTIONS` 刪除舊動作,否則舊紀錄的標籤與篩選會壞。
- 保留 `payout.marked_paid`、`payout.marked_failed`、`correction.*`、`application.paid`、`settlement.paid`,只是不再寫入。
- 導覽:`ROUTE_RULES` 與 `buildNavigation` 拿掉 `/admin/payments`,`icons.tsx` 的 payout 圖示若沒有其他地方使用就刪掉。
### D5. 文字
- 案件詳情的「月結與發放」卡片:
- 已核定時顯示「已最終核定,預計 YYYY/MM 隨薪資以「其他獎金」發放。」
- 舊的已發放案件維持「已發放:YYYY/MM 其他獎金。」
- 撤銷的說明拿掉。
- 我的申請頁首:「已發放總額」改成「已核定補助總額」,算 `finalized` 加 `paid` 的最終補助。
- 使用說明拿掉「更正與發放失敗(管理端)」,「核定與發放(管理端)」改名為「核定與匯出(管理端)」。FAQ 拿掉標記發放與更正的問答,文字不得出現「全額」。
## Risks / Trade-offs
- **核定後發現錯誤沒有補救方式**(使用者決定)→ 核定確認視窗加一句「核定後不能再退回或更正」,在核定前提醒。
- **舊的更正金額從畫面消失**(D3)→ 部署前查正式站資料。有更正紀錄就提醒使用者,可以選擇清除業務資料。
- **e2e 與單元測試大量刪改** → 刪掉發放與更正專屬的測試;其他測試若用 `pay` 或發放紀錄建資料,改成只到 `finalized`。
- **舊的 `/admin/payments` 書籤**:路由不在 `ROUTE_RULES` 內,會被拒絕(403 或 404),不會洩露資料。
@@ -0,0 +1,79 @@
## Why
使用者 2026-10-28 決定:系統完全不需要「發放管理」。
實際發放由薪資作業處理。在系統裡逐筆標記已發放、發放失敗,以及最終核定後的更正(補發、撤銷、改期),都不會在本系統使用。系統只要做到「最終核定」,並能匯出核定名單交給薪資作業。
## What Changes
- **BREAKING 移除發放管理**:
- 拿掉 `/admin/payments` 頁面(含篩選、匯出、標記已發放、標記發放失敗)與側邊欄「發放管理」。
- 拿掉「已發放」通知。
- 最終核定時不再建立發放紀錄。
- **核定名單匯出移到全公司月結**:
- 全公司月結頁提供「匯出核定名單」(Excel/CSV),匯出所選刷卡月份已最終核定的部門中,最終補助大於 0 的申請人。
- 欄位沿用現在發放匯出的前 7 欄:發放月份、員工編號、姓名、部門、刷卡月份、補助金額、薪資名目。
- 拿掉只對發放紀錄有意義的欄位:發放狀態、項目類型、更正編號、原發放月份。
- **最終核定就是終點**:
- 案件與月結都停在「最終核定」,不再轉為「已發放」。
- 員工在案件詳情與通知看到最終補助金額與預計發放月份(刷卡月份後第 2 個月,名目「其他獎金」)。
- 已經標記為「已發放」的舊案件與舊月結維持原狀態並照常顯示,不回改。
- **BREAKING 移除月結更正**:
- 拿掉補發、撤銷、改期與取消更正,以及管理端月結詳情與案件詳情上的更正明細。
- 最終核定後不能再更正;有誤時只能在核定前退回部門重新提交。
- 舊的更正紀錄保留在資料庫,不再顯示,也不列入匯出(見 design D3)。
- **頁面與文字調整**:
- 全公司月結統計卡:拿掉「待發放人數」,改為「已核定人數」。
- 首頁管理者區塊:拿掉「待發放人數與金額」與「前往發放管理」。
- 我的申請:頁首「已發放總額」改為「已核定補助總額」。
- 使用說明:拿掉「更正與發放失敗(管理端)」段落,並把「核定與發放(管理端)」改寫為核定與匯出。
- FAQ 刪除發放相關內容。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `payout-management`:移除全部需求(發放管理存取權限、發放月份規則、發放名單彙整、匯出發放名單、標記已發放、標記發放失敗)。
- 「發放月份規則」移到 `company-settlement`。
- 「匯出發放名單」改為 `company-settlement` 的「匯出核定名單」。
- `settlement-correction`:移除全部需求。
- `company-settlement`:
- 修改「全公司月結總覽」「最終核定」「退回月結」。
- 移除「部門月結詳情顯示更正後金額」。
- 新增「匯出核定名單」「發放月份規則」。
- `application-lifecycle`:
- 修改「案件狀態與顯示標籤」「最終核定時案件轉為最終核定」「最終核定與已發放案件唯讀」。
- 移除「發放後案件轉為已發放」。
- `app-shell`:修改「依角色顯示導覽」「狀態標籤」「重要操作確認視窗」「全站視覺風格」「使用說明依角色顯示」。
- `identity-access`:修改「角色導向的路由與導覽」(管理者不再有發放管理)。
- `dashboard`:修改「管理者區塊內容」。
- `notifications`:修改「月結流程通知」(不再有已發放通知)。
- `subsidy-application`:修改「我的申請清單」(已核定補助總額)、「申請詳情」(月結結果與預計發放月份)。
- `system-clock`:修改「使用系統時間的判斷」(不再有更正的發放月份限制)。
## Impact
- **頁面**:
- 刪除 `src/app/(app)/admin/payments/`。
- 刪除 `/admin/settlements/[departmentId]/[month]` 的更正卡片與操作。
- 修改:全公司月結頁(加匯出按鈕與匯出 route)、案件詳情、我的申請、首頁管理者區塊、使用說明、FAQ。
- **路由與導覽**:`src/lib/access.ts` 的 `ROUTE_RULES`、`src/lib/navigation.ts` 拿掉 `/admin/payments`。
- **伺服器**:
- 刪除 `src/server/settlement/payouts.ts` 的標記與清單功能,保留並改寫匯出。
- 刪除 `src/server/settlement/corrections.ts`、`src/domain/corrections.ts`。
- `finalizeSettlement` 不再建立 `payout_records`。
- `TRANSITIONS` 拿掉 `pay`。
- 拿掉 `notifyPayoutPaid` 與 `payout.paid` 通知類型。
- **資料庫**:不刪表、不改 migration。`payout_records`、`settlement_corrections` 保留舊資料,仍在「清除業務資料」範圍內。
- **匯出**:
- `src/lib/payouts.ts` 的 `PAYOUT_EXPORT_COLUMNS` 縮為 7 欄。
- `docs/operations/payout-export.md` 同步改寫(有測試比對)。
- **操作紀錄**:移除發放、更正相關動作的選項。舊紀錄的動作仍以原標籤顯示。
- **測試**:
- 刪除 `tests/e2e/corrections.spec.ts` 與發放相關 e2e。
- 調整 `company-settlement.spec.ts`、`settlement.spec.ts`、`visibility.spec.ts`,以及相關的 unit 測試。
- **文件**:CLAUDE.md 的 Department settlement admin side、Settlement corrections 段落。
@@ -0,0 +1,68 @@
## MODIFIED Requirements
### Requirement: 依角色顯示導覽
左側導覽 SHALL 只顯示使用者角色可使用的功能,目前所在頁面 MUST 高亮。導覽項目:一般員工為「首頁、新增申請、我的申請」;部門主管另加「部門審核、部門月結」;管理者另加「全公司月結、後台設定」;系統管理員另加「後台設定、帳號與角色、操作紀錄」。所有角色 SHALL 另有「使用說明、常見問題」。同時擁有多個角色的使用者 SHALL 看到各角色項目的聯集且不重複(介面規劃 §2)。
#### Scenario: 一般員工的導覽
- **WHEN** 只有員工角色的使用者登入
- **THEN** 導覽只顯示首頁、新增申請、我的申請、使用說明、常見問題,不顯示部門審核或後台設定
#### Scenario: 兼任主管的員工
- **WHEN** 同時具有員工與部門主管角色的使用者登入
- **THEN** 導覽顯示首頁、新增申請、我的申請、部門審核、部門月結、使用說明、常見問題
#### Scenario: 目前頁面高亮
- **WHEN** 使用者位於「我的申請」頁
- **THEN** 導覽中的「我的申請」以高亮樣式呈現,其餘項目不高亮
#### Scenario: 管理者沒有發放管理
- **WHEN** 管理者登入
- **THEN** 導覽顯示全公司月結與後台設定,不出現「發放管理」
### Requirement: 狀態標籤
案件與月結狀態 SHALL 以狀態標籤呈現,標籤 MUST 同時有文字與語意色,不可只靠顏色區分。案件狀態文字 SHALL 使用:草稿、待審核、待補件、已通過、不核准、待月結、已提交、已核定、已撤回;移除發放管理前已標記發放的舊案件與舊月結顯示「已發放」(介面規劃 §9)。
#### Scenario: 待主管審核的案件
- **WHEN** 案件狀態為「待主管審核」
- **THEN** 標籤文字顯示「待審核」,而非「審核中」
#### Scenario: 色彩無法辨識時仍可讀
- **WHEN** 使用者以灰階模式檢視案件清單
- **THEN** 每個狀態仍可由標籤文字區分
### Requirement: 重要操作確認視窗
不核准、提交月結、最終核定等重要或不可逆操作 SHALL 在執行前顯示確認視窗,說明操作後果;使用者取消時 MUST NOT 執行操作(介面規劃 §13)。
#### Scenario: 取消提交月結
- **WHEN** 主管按下「確認並提交」,確認視窗顯示「提交後本月份名單將鎖定,如需更正須由管理者退回。確定提交?」,主管按取消
- **THEN** 月結未被提交,頁面維持原狀
### Requirement: 全站視覺風格
所有頁面(含登入頁)SHALL 依風格稿(`docs/風格2_首頁.png`、`docs/風格2_新增申請頁.png`)呈現:白色卡片配淺色背景、大圓角與柔和陰影、深藍黑主要按鈕、綠色金額強調、膠囊式狀態標籤、淺灰表頭的表格。卡片、按鈕、輸入框、狀態標籤與表格 MUST 在各頁一致,不得出現同類元件各頁樣式不同。
#### Scenario: 各頁元件一致
- **WHEN** 使用者依序開啟我的申請、部門審核、全公司月結
- **THEN** 三頁的卡片、主要按鈕、狀態標籤與表格表頭樣式相同
#### Scenario: 登入頁
- **WHEN** 未登入的使用者開啟登入頁
- **THEN** 登入頁顯示系統 Logo 與名稱,並使用與內頁相同的色彩、按鈕與卡片風格
### Requirement: 使用說明依角色顯示
「使用說明」頁 SHALL 依登入者角色決定顯示的段落:所有登入者都看得到申請流程、帳號與部門、補助怎麼算與截止日;「部門月結(主管)」「核定與匯出(管理端)」兩段 SHALL 只對具有部門主管、管理者或系統管理員角色的登入者顯示,且 MUST NOT 輸出給只有員工角色的登入者(不只是隱藏)。具有多個角色時,只要其中一個角色可看即顯示。說明 MUST NOT 提到發放管理、標記已發放或更正。
#### Scenario: 一般員工
- **WHEN** 只有員工角色的使用者開啟「使用說明」
- **THEN** 頁面顯示申請流程、帳號與部門、補助怎麼算與截止日,不出現「部門月結(主管)」「核定與匯出(管理端)」段落
#### Scenario: 部門主管
- **WHEN** 具有部門主管角色的使用者開啟「使用說明」
- **THEN** 頁面顯示全部段落,包含主管端與管理端
#### Scenario: 管理者
- **WHEN** 管理者(人資/財務)開啟「使用說明」
- **THEN** 頁面顯示全部段落,包含主管端與管理端,且沒有「更正與發放失敗」段落
#### Scenario: 系統管理員
- **WHEN** 系統管理員開啟「使用說明」
- **THEN** 頁面顯示全部段落
@@ -0,0 +1,32 @@
## MODIFIED Requirements
### Requirement: 案件狀態與顯示標籤
系統 SHALL 以下列狀態管理案件,並以對應標籤顯示(規格 §14、介面規劃 §9):草稿→「草稿」、待主管審核→「待審核」、待補件→「待補件」、審核通過→「已通過」、不核准→「不核准」、待月結→「待月結」、已提交→「已提交」、最終核定→「已核定」。最終核定是案件的最後狀態;「已發放」只出現在 2026-10-28 前已標記發放的舊案件,仍以「已發放」標籤顯示,新案件 MUST NOT 進入此狀態。狀態標籤 MUST 同時顯示文字,不得僅以顏色區分。
#### Scenario: 待主管審核的標籤
- **WHEN** 案件狀態為待主管審核
- **THEN** 所有清單與詳情頁以文字標籤「待審核」顯示
#### Scenario: 舊的已發放案件
- **WHEN** 員工開啟一筆移除發放管理前已標記發放的案件
- **THEN** 狀態標籤仍顯示「已發放」,案件唯讀
### Requirement: 最終核定時案件轉為最終核定
管理者最終核定某部門月結時,系統 SHALL 在同一交易內把該月結所含所有「已提交」案件轉為「最終核定」,案件詳情顯示最終補助金額與預計發放月份(刷卡月份後第 2 個月,名目「其他獎金」)。案件之後不再有狀態轉移。
#### Scenario: 核定後案件狀態
- **WHEN** 管理者核定設計部 2026/10 月結
- **THEN** 該月結所有案件變為最終核定,員工在案件詳情看到最終補助金額與預計發放月份 2026/12
### Requirement: 最終核定與已發放案件唯讀
狀態為「最終核定」或「已發放」的案件 MUST NOT 被任何角色修改,包括金額與狀態。
#### Scenario: 嘗試修改已核定案件
- **WHEN** 任何使用者嘗試修改最終核定案件的金額或狀態
- **THEN** 系統拒絕該操作
## REMOVED Requirements
### Requirement: 發放後案件轉為已發放
**Reason**: 使用者 2026-10-28 決定移除發放管理,系統不再標記已發放。
**Migration**: 案件停在最終核定;已轉為已發放的舊案件維持原狀態。
@@ -0,0 +1,72 @@
## ADDED Requirements
### Requirement: 發放月份規則
已最終核定補助的預計發放月份 SHALL 為刷卡月份後第 2 個月(例:10 月刷卡、11 月申請與月結、12 月隨 11 月薪資發放),薪資名目固定為「其他獎金」。系統只用此規則顯示與匯出,不追蹤實際是否已發放。
#### Scenario: 10 月刷卡
- **WHEN** 2026/10 的部門月結被最終核定
- **THEN** 該月結申請人的預計發放月份為 2026/12,名目為「其他獎金」
#### Scenario: 跨年
- **WHEN** 2026/11 的部門月結被最終核定
- **THEN** 預計發放月份為 2027/01
### Requirement: 匯出核定名單
管理者 SHALL 能在全公司月結頁匯出所選刷卡月份的核定名單(Excel 與 CSV 兩種格式),內容為該月已最終核定(含舊資料中已發放)的部門月結中、最終補助大於 0 的每位申請人。欄位固定依序為:發放月份、員工編號、姓名、部門、刷卡月份、補助金額(整數元,不含 NT$ 與千分位)、薪資名目。尚未最終核定的部門 MUST NOT 列入。只有管理者能匯出;每次匯出 SHALL 寫入操作紀錄。
#### Scenario: 匯出 2026/10 核定名單
- **WHEN** 2026/10 有 3 個部門已最終核定、2 個仍為已提交,管理者在全公司月結頁選 2026/10 並匯出 Excel
- **THEN** 檔案只含 3 個已核定部門中最終補助大於 0 的申請人,每列發放月份為 2026/12、薪資名目為「其他獎金」
#### Scenario: 沒有已核定部門
- **WHEN** 所選月份沒有任何已最終核定的部門
- **THEN** 匯出按鈕停用並說明尚無已核定的部門
#### Scenario: 非管理者被拒
- **WHEN** 部門主管直接開啟匯出網址
- **THEN** 系統回應無權限,不回傳任何名單
## MODIFIED Requirements
### Requirement: 全公司月結總覽
總覽頁 SHALL 依所選月份(預設最近一個尚有部門未完成核定的月份)顯示統計卡:已提交部門數/部門總數、待提交部門數、總核定金額、已核定人數;並以表格列出每個部門的計算人數、月上限、最終補助合計、月結狀態、提交時間與可用操作。
#### Scenario: 顯示統計與部門列
- **WHEN** 2026/10 有 9 個部門,7 個已提交、2 個待提交
- **THEN** 統計卡顯示「已提交 7/9 部門」「待提交 2」,表格列出 9 個部門,待提交部門的最終補助與提交時間顯示「--」
#### Scenario: 切換月份
- **WHEN** 管理者切換到 2026/09
- **THEN** 統計卡與表格改為 9 月資料
### Requirement: 最終核定
管理者 SHALL 能對「已提交」的部門月結執行最終核定。系統 MUST 先顯示確認視窗;確認後記錄核定者與時間,月結狀態變為「最終核定」。最終核定是月結的最後狀態,系統 MUST NOT 建立發放紀錄或追蹤發放狀態。已核定的月結 MUST NOT 再被修改。
#### Scenario: 核定成功
- **WHEN** 管理者確認核定設計部 2026/10 月結
- **THEN** 月結狀態變為最終核定,名單可在全公司月結頁以「匯出核定名單」匯出,預計發放月份為 2026/12
#### Scenario: 未提交不可核定
- **WHEN** 管理者嘗試核定尚未提交的月結
- **THEN** 系統拒絕並說明需待部長提交
### Requirement: 退回月結
管理者 SHALL 能對「已提交」的部門月結執行退回,退回原因為必填且須經確認視窗。退回後月結回到可編輯狀態、部長可重新計算與提交;原提交版本(明細與參數快照)與退回紀錄(退回者、時間、原因)MUST 保留,MUST NOT 被覆寫。已最終核定的月結 MUST NOT 退回,也不能再更正;有誤時必須在核定前退回。
#### Scenario: 退回成功
- **WHEN** 管理者輸入原因「人數快照有誤,請重新確認」並確認退回設計部 2026/10 月結
- **THEN** 月結回到可編輯,部長可在部門月結頁看到退回原因,原提交版本仍可在詳情的歷史紀錄中檢視
#### Scenario: 未填原因
- **WHEN** 管理者未填退回原因就送出退回
- **THEN** 系統阻擋並提示需填寫原因
#### Scenario: 已核定不可退回
- **WHEN** 管理者嘗試退回已最終核定的月結
- **THEN** 系統拒絕並說明已核定的月結不能再退回或更正
## REMOVED Requirements
### Requirement: 部門月結詳情顯示更正後金額
**Reason**: 使用者 2026-10-28 決定移除月結更正,最終核定後不再更正。
**Migration**: 部門月結詳情只顯示核定金額;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
@@ -0,0 +1,12 @@
## MODIFIED Requirements
### Requirement: 管理者區塊內容
管理者區塊 SHALL 顯示所選月結月份的已提交部門數/部門總數、待提交部門數、全公司預估補助(未提交部門以已通過可補助總額估算)、待核定部門數,以及異常提醒(逾期未提交、逾期提交、缺少人數快照),並提供前往全公司月結的連結。MUST NOT 顯示待發放人數、待發放金額或前往發放管理的連結。
#### Scenario: 管理者摘要
- **WHEN** 2026/10 有 9 個部門,7 個已提交、其中 5 個已核定
- **THEN** 管理者區塊顯示已提交 7/9、待提交 2、待核定 2,不顯示待發放
#### Scenario: 異常提醒
- **WHEN** 2026/11/26 行銷部 10 月月結仍未提交
- **THEN** 管理者區塊列出「行銷部 10 月逾期未提交」並連往該部門月結詳情
@@ -0,0 +1,16 @@
## MODIFIED Requirements
### Requirement: 角色導向的路由與導覽
系統 SHALL 依使用者角色決定可進入的路由與側欄可見項目(員工:首頁、新增申請、我的申請;主管:部門審核、部門月結;管理者:全公司月結、後台設定;系統管理員:後台設定、帳號與角色、操作紀錄)。權限檢查 MUST 在伺服器端執行,前端隱藏不得作為唯一防線。
#### Scenario: 員工看不到管理功能
- **WHEN** 僅具員工角色的使用者登入
- **THEN** 側欄不顯示部門審核、全公司月結、後台設定等項目
#### Scenario: 直接輸入未授權路由
- **WHEN** 員工在網址列輸入 `/admin/settlements`
- **THEN** 系統顯示無權限頁面,不回傳任何管理資料
#### Scenario: 發放管理已移除
- **WHEN** 管理者在網址列輸入 `/admin/payments`
- **THEN** 系統不提供該頁(不在路由表中,回應無權限或找不到頁面),不回傳任何發放資料
@@ -0,0 +1,12 @@
## MODIFIED Requirements
### Requirement: 月結流程通知
系統 SHALL 在下列月結事件發生時通知相關人:部長提交月結時通知管理端;管理者退回月結時通知該部門部長;最終核定時通知該月結內所有申請人,並顯示最終補助金額與預計發放月份。系統 MUST NOT 發送「已發放」通知;舊的已發放通知仍可在通知清單中查看。
#### Scenario: 部長提交月結
- **WHEN** 設計部部長提交 2026/10 月結
- **THEN** 管理端使用者收到「設計部已提交 2026/10 月結」通知
#### Scenario: 最終核定通知申請人
- **WHEN** 管理者最終核定設計部 2026/10 月結
- **THEN** 該月結內每位申請人收到含其最終補助金額與預計發放月份的通知,之後不會再收到發放通知
@@ -0,0 +1,25 @@
## REMOVED Requirements
### Requirement: 發放管理存取權限
**Reason**: 使用者 2026-10-28 決定完全移除發放管理:實際發放由薪資作業處理,系統只到最終核定。
**Migration**: `/admin/payments` 移除;核定名單匯出改在全公司月結頁,權限同全公司月結(管理者)。
### Requirement: 發放月份規則
**Reason**: 使用者 2026-10-28 決定完全移除發放管理:實際發放由薪資作業處理,系統只到最終核定。
**Migration**: 規則移到 `company-settlement`「發放月份規則」,內容不變(刷卡月份後第 2 個月、名目「其他獎金」),只用於顯示與匯出。
### Requirement: 發放名單彙整
**Reason**: 使用者 2026-10-28 決定完全移除發放管理:實際發放由薪資作業處理,系統只到最終核定。
**Migration**: 改用 `company-settlement`「匯出核定名單」取得已核定名單;不再有發放項目與發放狀態。
### Requirement: 匯出發放名單
**Reason**: 使用者 2026-10-28 決定完全移除發放管理:實際發放由薪資作業處理,系統只到最終核定。
**Migration**: 改用 `company-settlement`「匯出核定名單」,欄位沿用前 7 欄。
### Requirement: 標記已發放
**Reason**: 使用者 2026-10-28 決定完全移除發放管理:實際發放由薪資作業處理,系統只到最終核定。
**Migration**: 不再標記;案件與月結停在最終核定。舊的已發放資料維持原狀態。
### Requirement: 標記發放失敗
**Reason**: 使用者 2026-10-28 決定完全移除發放管理:實際發放由薪資作業處理,系統只到最終核定。
**Migration**: 不再標記發放失敗;發放問題由薪資作業處理。
@@ -0,0 +1,29 @@
## REMOVED Requirements
### Requirement: 僅能對已核定或已發放的補助建立更正
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
### Requirement: 更正類型
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
### Requirement: 更正後部門合計不得超過月上限
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
### Requirement: 更正必填原因並留存稽核紀錄
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
### Requirement: 原月結結果不被覆寫
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
### Requirement: 未發放的更正可取消
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
### Requirement: 案件詳情顯示更正明細
**Reason**: 使用者 2026-10-28 決定移除月結更正:最終核定後不再更正。
**Migration**: 核定前發現錯誤,由管理者退回部門月結重新提交;舊更正紀錄保留在資料庫但不再顯示(見 design D3)。
@@ -0,0 +1,31 @@
## MODIFIED Requirements
### Requirement: 我的申請清單
系統 SHALL 在「我的申請」顯示登入者本人的案件,頁首摘要顯示本月案件數、待補件數、審核通過數與已核定補助總額(本人已最終核定與舊的已發放案件的最終補助合計);清單欄位包含申請編號、刷卡日期、平台、台幣金額、最終補助、狀態、最後更新。清單 MUST NOT 顯示預估或試算補助。
#### Scenario: 檢視清單
- **WHEN** 員工開啟「我的申請」
- **THEN** 只看到本人案件,每筆顯示上述欄位,最終補助尚未確定時顯示「--」
#### Scenario: 已核定補助總額
- **WHEN** 員工有一筆最終核定 NT$300 的案件與一筆舊的已發放 NT$200 的案件
- **THEN** 頁首「已核定補助總額」顯示 NT$500
#### Scenario: 員工無法存取他人案件
- **WHEN** 員工以網址開啟他人的申請詳情
- **THEN** 系統拒絕存取,且不洩露該案件內容
### Requirement: 申請詳情
系統 SHALL 在申請詳情顯示完整申請資料、附件、審核時間軸、主管意見、月結結果與預計發放月份,並依狀態只提供允許的操作:草稿可編輯/刪除、待補件可編輯並重新送出、允許階段可撤回,其他狀態僅檢視。待補件時主管意見 MUST 醒目顯示於頁面上方。金額摘要 MUST NOT 顯示預估補助;月結提交前最終補助顯示「--」並註明「月結後確認」。最終核定後顯示「預計 YYYY/MM 隨薪資以「其他獎金」發放」,MUST NOT 顯示更正明細。
#### Scenario: 待補件詳情
- **WHEN** 員工開啟主管退回補件的案件
- **THEN** 頁面上方醒目顯示主管意見與「編輯並重新送出」按鈕,金額摘要顯示支付金額與最終補助「--」,不顯示預估補助
#### Scenario: 已通過案件唯讀
- **WHEN** 員工開啟狀態為「已通過」的案件
- **THEN** 頁面不提供編輯、刪除或撤回操作,並顯示「等待月結」
#### Scenario: 已核定案件
- **WHEN** 員工開啟 2026/10 刷卡、已最終核定的案件
- **THEN** 頁面顯示最終補助金額與「預計 2026/12 隨薪資以「其他獎金」發放」
@@ -0,0 +1,20 @@
## MODIFIED Requirements
### Requirement: 使用系統時間的判斷
所有業務規則的「現在」SHALL 使用系統時間,包括:申請與月結截止、逾期提交標示、審核通過轉待月結(含排程)、逾期不核准、截止提醒(含排程)、生效參數版本、人數快照的月份是否已開始、首頁本期與日期、各頁預設月份、申請編號,以及案件與月結上記錄的時間。登入、session 期限、公司帳號登入與登出、備份與 HR 名冊同步的每日判斷 MUST 使用真實時間。
#### Scenario: 模擬申請截止已過
- **WHEN** 真實時間 2026/10/19,系統時間調整為 2026/11/21 09:00,員工送出刷卡日期 2026/10/05 的申請
- **THEN** 系統以已過 2026/11/20 截止拒絕送出
#### Scenario: 模擬月結逾期提交
- **WHEN** 系統時間調整為 2026/11/26 10:00,部門主管提交 10 月月結
- **THEN** 提交成功並標示「逾期提交」,提交時間記為系統時間 2026/11/26 10:00
#### Scenario: 排程依系統時間轉待月結
- **WHEN** 系統時間調整到 10 月申請截止之後,每小時排程執行
- **THEN** 10 月審核通過的案件轉為待月結
#### Scenario: 登入不受影響
- **WHEN** 系統時間調整到一年後
- **THEN** 使用者仍可正常登入,已登入的 session 依真實時間判斷是否過期
@@ -0,0 +1,40 @@
## 1. 核定與狀態
- [x] 1.1 `finalizeSettlement` 不再建立 `payout_records`。單元測試:核定後月結為 `finalized`,案件為最終核定,沒有新的發放紀錄。
- [x] 1.2 `TRANSITIONS` 拿掉 `pay`。保留 `paid` 的型別與標籤(D2)。測試:不能把任何案件轉入 `paid`;舊 `paid` 案件仍顯示「已發放」並維持唯讀。
- [x] 1.3 全公司月結確認視窗加「核定後不能再退回或更正」;退回已核定月結時,錯誤訊息改為「已核定的月結不能再退回或更正」。測試同步調整。
## 2. 移除發放管理
- [x] 2.1 刪除 `src/app/(app)/admin/payments/`。`ROUTE_RULES` 與導覽拿掉 `/admin/payments`;沒有其他地方使用的 payout 圖示一併刪除。測試:管理者的導覽不出現「發放管理」,開 `/admin/payments` 不回傳資料。
- [x] 2.2 `src/server/settlement/payouts.ts` 只留匯出需要的程式,刪掉清單、標記與 `settleIfComplete`。拿掉 `notifyPayoutPaid` 與 `payout.paid` 通知類型;舊通知的型別標籤保留,讓清單能顯示。單元測試同步刪改。
- [x] 2.3 首頁管理者區塊拿掉「待發放」統計與「前往發放管理」(`getAdminDashboard` 一併刪除對應欄位)。測試:`dashboard/queries.test.ts` 與首頁 e2e。
## 3. 核定名單匯出
- [x] 3.1 `PAYOUT_EXPORT_COLUMNS` 縮成 7 欄,資料來源改為月結分配(D1:`finalized` 加 `paid`、最終補助大於 0、發放月份 `payoutMonth`);改寫 `docs/operations/payout-export.md`。單元測試:只含已核定部門、排除 0 元、跨年發放月份正確,文件與欄位一致。
- [x] 3.2 新增 `/admin/settlements/export?month=&format=xlsx|csv`(`requireRole("admin")`),寫入 `payout.exported` 操作紀錄(標籤改「匯出核定名單」)。全公司月結頁加「匯出 Excel」「匯出 CSV」;沒有已核定部門時停用並說明。e2e:管理者匯出得到正確欄位,主管開網址得到 403(`visibility.spec.ts`)。
- [x] 3.3 全公司月結統計卡「待發放人數」改為「已核定人數」。測試:`company.test.ts` 與 e2e。
## 4. 移除月結更正
- [x] 4.1 刪除 `src/server/settlement/corrections.ts`、`src/domain/corrections.ts`、管理端月結詳情的更正卡片與操作,以及 `correction-list.tsx`。月結詳情只顯示原核定金額。刪除對應的單元測試與 `tests/e2e/corrections.spec.ts`。
- [x] 4.2 案件詳情拿掉「補助更正」與撤銷說明,「月結與發放」卡片依 D5 改寫文字。測試:已核定案件顯示預計發放月份,舊的已發放案件仍顯示已發放。
- [x] 4.3 `AUDIT_ACTIONS` 保留舊的發放與更正動作(只為了顯示舊紀錄,D4);確認不再有程式寫入這些動作,用 grep 檢查。
## 5. 文字與頁面
- [x] 5.1 我的申請頁首「已發放總額」改為「已核定補助總額」(`finalized` 加 `paid`)。測試:既有的我的申請 e2e 或單元測試。
- [x] 5.2 使用說明拿掉「更正與發放失敗(管理端)」,「核定與發放(管理端)」改為「核定與匯出(管理端)」。FAQ 拿掉標記發放與更正的問答,不得出現「全額」。測試:`review-month-and-help.spec.ts` 的角色段落測試同步調整。
- [x] 5.3 CLAUDE.md:改寫 Department settlement 的 Admin side(拿掉 payouts、標記發放),刪掉 Settlement corrections 段落並註明已移除;Data reset 註明兩張舊表保留。
## 6. 驗證
- [x] 6.1 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過。
- [x] 6.2 `npm run test:e2e:prepare` 之後 e2e 全過,涵蓋 company-settlement、settlement、visibility、dashboard、help。
- [x] 6.3 `grep` 確認 `src/` 不再引用 `/admin/payments`、`markPayoutsPaid`、`createCorrection`、`notifyPayoutPaid`。
## 7. 上線
- [ ] 7.1 部署前請使用者確認正式站有沒有更正紀錄或發放紀錄(後台操作紀錄篩「建立更正」「標記已發放」)。有的話,由使用者決定是否先「清除業務資料」(D3)。(未確認,直接部署;部署後驗收正常)
- [x] 7.2 使用者授權後 push 部署。使用者驗收:導覽沒有發放管理;全公司月結可以匯出核定名單;案件詳情顯示預計發放月份。(2026-10-29 使用者驗收通過)
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-29
@@ -0,0 +1,38 @@
## Context
`/admin/settings?tab=maintenance` 的「清除業務資料」目前用 `ConfirmDialog`:列出筆數,按「確認清除」就呼叫 `clearBusinessDataAction()`(沒有參數),由 `clearBusinessDataWithBackup` 備份、清除並寫入 `data.business_cleared` 操作紀錄。使用者要求加上雙重機制,並選擇「輸入確認文字+原因」(不需要重新登入公司帳號,也不需要第二位系統管理員核准)。
## Goals / Non-Goals
**Goals:**
- 單一系統管理員仍可完成,但必須有意識地輸入確認文字並說明原因,防止誤按。
- 前端與伺服器端用同一個確認文字常數,伺服器端獨立檢查。
- 原因留在操作紀錄。
**Non-Goals:**
- 不做重新登入(Authentik `max_age=0`)或兩人核准。
- 不改清除範圍、備份或交易流程。
## Decisions
### D1. 沿用 `ReasonDialog`,確認文字放在 `children`
`ReasonDialog` 已有必填原因、錯誤就地顯示、`onConfirm` 回傳錯誤時留在視窗。確認文字是額外欄位,用 `children` 放入,並新增 `canConfirm(reason)` 屬性(回傳 false 時停用確認按鈕)與 `onClose`(關閉時重設確認文字欄位)。不新增另一種對話框元件。
- 替代方案:在 `ConfirmDialog` 加輸入欄位——它沒有表單狀態,要補的東西比較多。
### D2. 確認文字常數 `CLEAR_CONFIRM_PHRASE = "清除業務資料"`
放在 `src/lib/data-reset.ts`(前後端共用;`src/lib` 不能 import `@/server/*`)。比對時只去掉前後空白,其餘完全相同(不忽略全形/半形差異)。文字與按鈕名稱相同,系統管理員一看就知道要輸入什麼。
### D3. 伺服器端在備份之前檢查
`clearBusinessDataWithBackup(db, audit, { confirmText, reason, ...options })` 第一步檢查,不符就 `fail(...)`,不建立備份(避免每次手滑都留下一份備份)。錯誤訊息:
- 確認文字不符:「確認文字不正確,未清除任何資料」
- 原因空白:「請填寫清除原因」
`clearBusinessDataAction(input: { confirmText: string; reason: string })` 仍先 `requireRole("sysadmin")`。
### D4. 原因寫入操作紀錄的 `comment`
`clearBusinessData(db, audit, { backup, reason })` 的 `recordAudit` 加 `comment: reason`,`/admin/audit-log` 已會顯示備註,不用改頁面。
## Risks / Trade-offs
- [只能防手滑,防不了蓄意操作] → 這是使用者選的程度;清除前仍會自動備份,操作紀錄有人、時間與原因。
- [測試或腳本若直接呼叫 `clearBusinessDataWithBackup` 要補參數] → 只有 action 與測試呼叫,型別會強制補上。
@@ -0,0 +1,31 @@
## Why
「清除業務資料」會刪掉所有申請、月結、通知與人數快照,目前只要在確認視窗按一下「確認清除」就執行,容易手滑誤按。使用者決定(2026-10-29)加上雙重機制:除了確認視窗,還要手動輸入確認文字並填寫原因,才能清除。
## What Changes
- 確認視窗新增兩個必填欄位:
- 「清除原因」(必填);
- 「請輸入『清除業務資料』以確認」,輸入的文字必須和指定文字完全相同。
- 兩個欄位都符合前,「確認清除」按鈕停用;取消或關閉視窗不清除任何資料(維持現狀)。
- 伺服器端也檢查:確認文字不符或原因空白時拒絕,不建立備份、不清除。直接呼叫動作也一樣。
- 原因寫進「清除業務資料」操作紀錄的備註。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `data-reset`:「清除前確認」改為確認視窗加上輸入確認文字與原因(雙重確認,伺服器端也檢查);「清除前自動備份與紀錄」的操作紀錄加上原因。
## Impact
- `src/app/(app)/admin/settings/clear-data-button.tsx`:改用 `ReasonDialog`(原因欄位)加上確認文字欄位。
- `src/app/(app)/admin/settings/actions.ts`:`clearBusinessDataAction` 接收原因與確認文字。
- `src/server/maintenance/clear-business-data.ts`:`clearBusinessDataWithBackup` 先檢查確認文字與原因,再備份;操作紀錄寫入原因。
- 確認文字常數放在 `src/lib/`(前後端共用)。
- 測試:`clear-business-data.test.ts`、`tests/e2e/settings.spec.ts`。
- 沒有資料庫 migration。
@@ -0,0 +1,43 @@
## MODIFIED Requirements
### Requirement: 清除前確認
清除前系統 SHALL 跳出確認視窗,說明會清除與會保留的資料,並列出目前各類資料的筆數。視窗 SHALL 要求雙重確認:填寫「清除原因」,並在確認欄位輸入指定文字「清除業務資料」;兩者都符合前「確認清除」MUST 停用。只有兩者都符合並按「確認清除」才執行;按取消或關閉視窗 MUST NOT 清除任何資料。伺服器端 SHALL 再次檢查:確認文字與指定文字不完全相同(前後空白除外)或原因空白時 MUST 拒絕,不建立備份、不清除任何資料,直接呼叫清除動作也一樣。
#### Scenario: 取消
- **WHEN** 系統管理員開啟確認視窗後按「取消」
- **THEN** 不清除任何資料,也不建立備份
#### Scenario: 顯示筆數
- **WHEN** 系統管理員開啟確認視窗,目前有 12 筆申請、3 筆部門月結
- **THEN** 視窗列出申請 12 筆、部門月結 3 筆等各類資料的筆數
#### Scenario: 確認文字不符時不能清除
- **WHEN** 系統管理員填了原因,但確認欄位輸入「清除資料」
- **THEN** 「確認清除」維持停用,不清除任何資料
#### Scenario: 原因未填時不能清除
- **WHEN** 系統管理員輸入正確的確認文字,但沒有填原因
- **THEN** 「確認清除」維持停用,不清除任何資料
#### Scenario: 兩者都符合才清除
- **WHEN** 系統管理員填寫原因「正式上線前清除測試資料」,並輸入「清除業務資料」後按「確認清除」
- **THEN** 系統執行備份與清除
#### Scenario: 直接呼叫也檢查
- **WHEN** 系統管理員直接呼叫清除動作,確認文字錯誤或原因空白
- **THEN** 回傳錯誤,不建立備份,不清除任何資料
### Requirement: 清除前自動備份與紀錄
清除前系統 SHALL 先備份資料庫與附件到與資料庫同一個持久化目錄下的備份目錄;備份失敗時 MUST NOT 清除任何資料並顯示失敗原因。清除 SHALL 在單一交易內完成:任一步驟失敗時整筆回滾,資料庫的保護機制也一併還原。完成後 SHALL 寫入一筆操作紀錄(各類資料的刪除筆數、備份目錄名稱,以及清除原因作為備註),並在畫面顯示備份目錄名稱。
#### Scenario: 備份後清除
- **WHEN** 系統管理員填寫原因並輸入確認文字後確認清除
- **THEN** 系統先建立備份,再清除,畫面顯示「已清除業務資料,備份:<目錄名稱>」,操作紀錄有一筆「清除業務資料」含各類刪除筆數,備註為清除原因
#### Scenario: 備份失敗
- **WHEN** 備份時磁碟空間不足而失敗
- **THEN** 不清除任何資料,畫面顯示「備份失敗,未清除任何資料」
#### Scenario: 清除後保護機制仍有效
- **WHEN** 清除完成後,有人嘗試刪除一筆發放紀錄或操作紀錄
- **THEN** 資料庫照常拒絕(只能新增的保護已還原)
@@ -0,0 +1,15 @@
## 1. 伺服器端
- [x] 1.1 新增 `src/lib/data-reset.ts`:`CLEAR_CONFIRM_PHRASE`、錯誤訊息常數,以及 `clearConfirmationError(confirmText, reason)`(回傳錯誤訊息或 null,前後端共用)。
- [x] 1.2 `clearBusinessDataWithBackup` 接收 `confirmText`、`reason`,在備份前檢查,不符時回傳錯誤且不建立備份;`clearBusinessData` 的操作紀錄加 `comment: reason`。單元測試:確認文字錯誤、原因空白都不建立備份、資料不變;成功時操作紀錄的備註是原因。
- [x] 1.3 `clearBusinessDataAction` 接收 `{ confirmText, reason }` 傳給 service(仍先 `requireRole("sysadmin")`)。
## 2. 畫面
- [x] 2.1 `ReasonDialog` 新增 `canConfirm(reason)`(回傳 false 時停用確認按鈕)與 `onClose`。
- [x] 2.2 `ClearDataButton` 改用 `ReasonDialog`:原因欄位「清除原因」,加上「請輸入「清除業務資料」以確認」欄位;原因空白或文字不符時「確認清除」停用;保留筆數、會清除/會保留的說明與完成提示。
## 3. 驗證
- [x] 3.1 e2e `tests/e2e/settings.spec.ts`:開啟視窗後,只填原因或只輸入錯誤文字時「確認清除」停用;按取消不清除(共用資料庫,不實際清除)。
- [x] 3.2 CLAUDE.md 的 Data reset 段落補上雙重確認。`npm run lint`、`format:check`、`typecheck`、`npm test` 與受影響的 e2e 全過。
@@ -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` 通過。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-30
@@ -0,0 +1,84 @@
## Context
- 主管提交走 `submitSettlement` → `submitInTx`(`src/server/settlement/service.ts`):權限(`managesDepartment`)→ 鎖定檢查 → `submitCheck`(申請截止已過、沒有待審/待補件)→ 推進審核通過案件 → 重算 → 寫入月結與明細 → `settle` 轉移 → 鎖人數快照 → 狀態 submitted、`is_late`、版本 → 通知與操作紀錄,全部在 `abortableTransaction` 內。
- 逾期判斷已有:`monthDeadlines` 的 `manager`(次月 25 日 23:59:59),總覽的 `overdueUnsubmitted`、截止隔天的 `reminder.admin_overdue`。
- `department_settlements.submitted_by_label` 與 `settlement_submissions.submitted_by_label` 已能存「誰提交」的文字。
- 背景排程 `startSettlementScheduler` 每小時執行(以系統時間判斷),已用於「審核通過 → 待月結」。
- 制度參數版本化(`rule_versions`,append-only),schema 在 `src/lib/rule-params.ts`,管理者與系統管理員都可在 `/admin/settings` 修改。
## Goals / Non-Goals
**Goals:**
- 逾期後管理者能以一個動作把部門月結推進到「已提交」,並留下原因與紀錄。
- 可選的自動提交,預設關閉,開關與天數由後台設定。
- 強制提交與主管提交產生相同的結果(金額、鎖定、版本、案件狀態),只多了「提交方式」。
**Non-Goals:**
- 管理者在代提交前修改分配金額或手動調整(仍只有部門主管能調整)。
- 自動最終核定;強制提交後仍由管理者最終核定。
- 沒有任何案件的部門的自動提交(見 D4)。
- 改變主管自行提交的規則(仍會被未審案件擋下)。
## Decisions
### D1 共用提交流程,以「提交方式」區分
`submitInTx` 抽出共用核心,參數加 `mode: "manager" | "admin" | "auto"`:
| | manager | admin(代提交) | auto(自動提交) |
|---|---|---|---|
| 權限 | 管轄該部門 | admin 角色 | 系統(`SYSTEM_ACTOR`) |
| 主管截止 | 不限(逾期標示) | 必須已過 | 必須已過 + 寬限天數 |
| 未審案件 | 擋下 | 轉不核准(D3) | 轉不核准(D3) |
| 原因 | 無 | 必填 | 系統帶入 |
| `submitted_by` / label | 主管 | 管理者 /「{姓名}(管理者代提交)」 | null /「系統(自動提交)」 |
其餘步驟(重算、`overridesExceedCap` / `overridesExceedPaid` 擋下、明細、`settle`、鎖快照、`is_late`、版本、通知)完全相同,避免兩套提交邏輯分歧。替代方案「另寫一個 admin 版提交函式」被否決:金額與鎖定步驟重複,日後改一邊忘另一邊。
### D2 資料:`submission_mode` 與 `submission_reason`
`department_settlements` 與 `settlement_submissions` 各加 `submission_mode`(enum `manager|admin|auto`,NOT NULL DEFAULT `manager`)與 `submission_reason`(text,可為 null)。既有資料 migration 後即為 `manager`。退回後主管重新提交時回到 `manager`;版本表保留每次的方式。不另建表:方式是提交這件事的屬性,跟著版本走最直接。DB trigger 只允許非 open 月結改 `status`:提交時從 open 寫入,不受影響。
### D3 新轉移 `overdue_reject`
`TRANSITIONS` 新增 `overdue_reject`:`pending_review → rejected` 與 `needs_revision → rejected`,actor `admin` 或 `system`,`requiresComment: true`,標籤「逾期未審核不核准」。原因由系統帶入:代提交為「部門月結逾期,由管理者代為提交時尚未審核完成」,自動提交為「部門月結逾期,由系統自動提交時尚未審核完成」;代提交時管理者填的原因附在後面。走 `applyTransition`,所以時間軸、操作紀錄、`notifyTransition`(申請人收到不核准通知、清掉主管的待審通知)都沿用。現有 `expire_reject`(主管、只限待補件)不變。
先轉不核准、再重算:被不核准的案件不進計算,跟主管自己處理完再提交的結果一致。
### D4 自動提交的範圍與時機
- 參數:`autoSubmit: { enabled: boolean; graceDays: number }`,預設 `{ enabled: false, graceDays: 3 }`,`graceDays` 0–10 的整數。舊版本 JSON 沒有這個欄位,schema 以 `.default()` 補上,不改寫歷史版本。
- 讀取「現在生效」的版本(不是卡片月份月底的版本):開關是營運設定,管理者打開後應該立刻對目前逾期的月份生效。截止日本身仍依原規則(卡片月份月底的版本)。
- 時機:系統時間超過「主管截止日 + `graceDays` 天」的當日 23:59:59(Asia/Taipei)。預設 3 天 → 10 月月結在 11/28 結束後自動提交,HR 在 26–28 日之間仍可先代提交。
- 月份:只看前 1、前 2 個刷卡月份(與提醒相同的 `candidateMonths`),開啟開關時不會把很久以前未提交的測試月份一次全部送出。
- 部門:啟用中、該月尚未提交、且該月有至少一筆非草稿、未刪除案件的部門。沒有案件的部門不自動提交(行為與現在相同)。
- 每小時執行一次(掛在現有月結排程),逐部門各自一個交易;一個部門失敗不影響其他部門。
### D5 自動提交跳過與通知
自動提交遇到擋下條件(手動調整合計超過月上限、調整超過個人上限、缺人數快照或其他計算錯誤)時跳過該部門,月結維持 open。每天對管理端發一則通知「YYYY/MM 月結自動提交失敗(N 個部門)」列出部門與原因,以 (收件人, 類型, 月份, 日期) 去重,與現有提醒相同,不會每小時重發。代提交遇到同樣條件則直接顯示錯誤。
### D6 介面
- 全公司月結總覽(使用者 2026-10-30 調整:從詳情頁改到總覽):「逾期未提交」提醒旁顯示小型次要按鈕「代為提交」,總覽可能有多個逾期部門,所以不用主要按鈕;詳情頁的「部長尚未提交」說明改為指向全公司月結。按下開 `ReasonDialog`:說明「將以目前試算提交,N 筆待審核、M 筆待補件案件將改為不核准」,原因必填,`confirmStep` 再確認一次。截止前不顯示按鈕,server action 也拒絕。
- 總覽與詳情:提交方式不是主管時加 `ToneBadge`「管理者代提交」/「系統自動提交」;詳情的版本清單顯示方式與原因。
- 部門月結頁:已提交資訊改為「由 {label} 於 … 提交(逾期提交)」,並顯示代提交原因。
- 後台「制度參數」:新增「逾期自動提交月結」核取方塊與「截止後第 N 天」欄位,說明「關閉時只能由管理者代提交」。
### D7 通知與操作紀錄
- 操作紀錄:`settlement.proxy_submitted`(管理者代提交,comment 為原因)、`settlement.auto_submitted`(系統)。案件轉移各自有 `application.overdue_reject` 紀錄。
- 通知:強制提交時通知該部門的主管(`settlement.force_submitted`:「設計部 2026/10 月結已由管理者代為提交」或「…已由系統自動提交」,含不核准件數);管理端照常收到「已提交」通知(自動提交時才發,代提交者本人不需要)。
## Risks / Trade-offs
- [主管正在處理時被代提交或自動提交] → 只能在截止後執行,自動提交另有寬限天數;提交後管理者仍可退回月結讓主管重新提交,但已轉為不核准的案件不會復原(不核准是終止狀態)。確認視窗明列會被不核准的件數。
- [開關打開時一次處理多個月份] → 只看前 1、2 個月份,且只處理有案件的部門。
- [自動提交在沒人看的時候失敗] → D5 每日通知管理端;總覽仍顯示「逾期未提交」。
- [舊參數版本缺欄位] → schema 預設值補上,測試涵蓋讀取沒有 `autoSubmit` 的舊版本。
## Migration Plan
1. Drizzle migration 新增兩張表的 `submission_mode`(DEFAULT `manager`)與 `submission_reason`;啟動時自動套用。
2. 部署後開關預設關閉,行為只多出「代為提交」按鈕。
3. 回滾:程式回到前一版即可;新欄位留著不影響舊程式。
@@ -0,0 +1,33 @@
## Why
部門主管過了月結提交截止(刷卡月份次月 25 日)仍未提交時,目前系統只標示「逾期未提交」並通知管理端,沒有任何強制處理:該部門的案件停在「待月結」,不會進核定名單,整個部門當月補助一直卡住,直到主管自己補提交。HR 需要在逾期後能把月結推進下去(使用者決定 2026-10-30)。
## What Changes
- **管理者代提交**:主管提交截止過後,管理者可在全公司月結總覽該部門「逾期未提交」提醒旁按「代為提交」,原因必填、確認後以當下試算提交;月結標示「管理者代提交」並記錄代提交者與原因。
- **系統自動提交(可開關)**:後台「制度參數」新增「逾期自動提交月結」開關(預設關閉)與「截止後第幾天自動提交」(預設 3 天)。開啟時,背景排程在期限過後自動以當下試算提交仍未提交的部門月結,標示「系統自動提交」。
- **未審案件視為不核准**:代提交或自動提交時,該部門該月仍為「待主管審核」或「待補件」的案件在同一交易內轉為「不核准」,原因由系統帶入(逾期未審核),申請人收到審核結果通知。
- 代提交或自動提交後的月結與主管提交相同:鎖定、標示逾期提交、可被管理者退回或最終核定。
- 自動提交無法完成的部門(例如手動調整合計超過月上限、缺人數快照)跳過並通知管理端,由管理者處理。
- 部門主管收到「月結已由管理者代為提交/系統自動提交」通知;部門月結頁、管理端總覽與詳情顯示提交方式。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `company-settlement`:新增管理者代提交與系統自動提交;總覽對逾期未提交部門提供代提交;總覽與詳情標示提交方式。
- `department-settlement`:被代提交/自動提交的月結在部門月結頁顯示提交方式與原因。
- `application-lifecycle`:新增「逾期強制提交時未審案件轉為不核准」轉移(待主管審核/待補件 → 不核准,執行者為管理者或系統);月結提交轉移的執行者可為管理者或系統。
- `rule-settings`:制度參數新增逾期自動提交開關與天數。
- `notifications`:強制提交通知部門主管;自動提交跳過的部門通知管理端。
## Impact
- 程式:`src/lib/rule-params.ts`(新參數與預設值)、後台參數表單;`src/lib/application-lifecycle.ts`(新轉移、`settle` 執行者);`src/server/settlement/service.ts`(共用提交流程加入強制模式)、`src/server/settlement/scheduler.ts`(自動提交);管理端月結詳情頁與 action、總覽、部門月結頁;`src/server/notifications/events.ts`;`src/lib/audit-actions.ts`。
- 資料庫:`department_settlements`、`settlement_submissions` 新增提交方式(與代提交原因)欄位,需要 migration;既有資料視為主管提交。
- 舊參數版本沒有新欄位,讀取時以預設值(關閉)補上,不需改寫歷史版本。
- 文件:CLAUDE.md、`/help` 管理端說明。
@@ -0,0 +1,23 @@
## ADDED Requirements
### Requirement: 逾期強制提交時未審案件轉為不核准
管理者代提交或系統自動提交部門月結時,系統 SHALL 在同一交易內先把該部門該月仍為「待主管審核」或「待補件」的案件轉為「不核准」(轉移「逾期未審核不核准」),原因由系統帶入並說明是代提交或自動提交,代提交時附上管理者填寫的原因;申請人 SHALL 收到不核准通知,案件時間軸記錄執行者(管理者或系統)。此轉移 MUST NOT 由部門主管或員工執行,也 MUST NOT 在強制提交以外發生。強制提交失敗時案件 MUST 維持原狀態。
#### Scenario: 代提交時待審案件不核准
- **WHEN** 管理者代提交行銷部 10 月月結,行銷部有 1 筆待主管審核案件
- **THEN** 該案件變為不核准,時間軸顯示「逾期未審核不核准」、執行者為該管理者與系統帶入的原因,申請人收到通知
#### Scenario: 自動提交時待補件案件不核准
- **WHEN** 系統自動提交行銷部 10 月月結,行銷部有 1 筆待補件案件
- **THEN** 該案件變為不核准,時間軸執行者為「系統」
#### Scenario: 強制提交失敗
- **WHEN** 代提交因手動調整超過月上限被擋下
- **THEN** 待主管審核與待補件案件維持原狀態
### Requirement: 強制提交時案件轉為已提交
管理者代提交或系統自動提交部門月結時,系統 SHALL 與主管提交相同,在同一交易內把該部門該月所有「待月結」案件轉為「已提交」並寫入最終補助金額;時間軸的執行者為代提交的管理者或「系統」。
#### Scenario: 自動提交的時間軸
- **WHEN** 系統自動提交設計部 10 月月結
- **THEN** 該月待月結案件變為已提交,時間軸的「部門月結提交」執行者為「系統」
@@ -0,0 +1,79 @@
## ADDED Requirements
### Requirement: 管理者代提交逾期月結
主管提交截止(刷卡月份次月 25 日 23:59:59,Asia/Taipei)過後,該部門該月月結仍未提交時,管理者 SHALL 能在全公司月結總覽該部門列的「逾期未提交」提醒旁按「代為提交」。代提交 MUST 填寫原因並經確認視窗確認;確認視窗 SHALL 說明將以目前試算提交,並列出將改為不核准的待主管審核與待補件件數。代提交 SHALL 以當下最新資料重新計算後提交,結果與主管提交相同(明細快照、案件轉為已提交、人數快照鎖定、標示逾期提交),並記錄代提交者、時間、原因與提交方式「管理者代提交」。主管提交截止前 MUST NOT 允許代提交;非管理者 MUST NOT 能代提交。手動調整合計超過月上限或調整超過個人上限時,代提交 SHALL 被擋下並顯示原因。
#### Scenario: 截止後代提交
- **WHEN** 2026/11/27 行銷部 10 月月結仍未提交,管理者在全公司月結總覽行銷部列的「逾期未提交」旁按「代為提交」、填寫原因「部長請假」並確認
- **THEN** 月結變為已提交,總覽該列改為標示「逾期提交」與「管理者代提交」,詳情的版本清單顯示代提交者與原因
#### Scenario: 代提交時有未審案件
- **WHEN** 行銷部 10 月仍有 1 筆待主管審核、1 筆待補件,管理者代提交
- **THEN** 確認視窗說明這 2 筆將改為不核准;確認後 2 筆案件變為不核准,不納入月結計算,其他待月結案件變為已提交
#### Scenario: 截止前不可代提交
- **WHEN** 2026/11/24 管理者開啟 2026/10 全公司月結總覽,行銷部尚未提交
- **THEN** 行銷部列不顯示「代為提交」;直接呼叫代提交被拒絕,月結不變
#### Scenario: 原因必填
- **WHEN** 管理者按「代為提交」但未填原因
- **THEN** 無法確認,月結不變
#### Scenario: 手動調整超過月上限
- **WHEN** 行銷部手動調整合計已超過月上限,管理者代提交
- **THEN** 系統擋下並顯示原因,月結與案件不變
### Requirement: 系統自動提交逾期月結
制度參數「逾期自動提交月結」開啟時,系統 SHALL 在主管提交截止日再過設定天數(當日 23:59:59,Asia/Taipei,依系統時間)之後,自動提交前 1、前 2 個刷卡月份中仍未提交、且該月有至少一筆非草稿案件的啟用中部門月結。自動提交 SHALL 與代提交相同(未審案件轉為不核准、重新計算、鎖定、標示逾期提交),提交者記為「系統(自動提交)」、提交方式「系統自動提交」。開關關閉時系統 MUST NOT 自動提交。無法提交的部門(手動調整超過月上限或個人上限、缺人數快照、其他計算錯誤)SHALL 跳過並維持未提交,不影響其他部門。
#### Scenario: 寬限期後自動提交
- **WHEN** 自動提交開啟、天數為 3,2026/11/29 行銷部 10 月仍未提交且有 3 筆待月結案件
- **THEN** 系統自動提交行銷部 10 月月結,標示「逾期提交」與「系統自動提交」
#### Scenario: 寬限期內不自動提交
- **WHEN** 自動提交開啟、天數為 3,今天是 2026/11/27
- **THEN** 行銷部 10 月月結維持未提交,管理者仍可代提交
#### Scenario: 開關關閉
- **WHEN** 自動提交關閉,2026/12/10 行銷部 10 月仍未提交
- **THEN** 月結維持未提交,總覽顯示「逾期未提交」
#### Scenario: 沒有案件的部門
- **WHEN** 自動提交開啟,總務部 10 月沒有任何申請
- **THEN** 系統不自動提交總務部 10 月月結
#### Scenario: 無法提交的部門被跳過
- **WHEN** 自動提交時行銷部手動調整合計超過月上限,設計部可正常提交
- **THEN** 設計部被自動提交,行銷部維持未提交
## MODIFIED Requirements
### Requirement: 異常提醒
總覽頁 SHALL 標示需要管理者注意的部門:逾期提交(次月 25 日後提交)、已過部長提交截止仍未提交、缺少該月計算人數快照。由管理者代提交或系統自動提交的月結 SHALL 另外標示「管理者代提交」或「系統自動提交」。
#### Scenario: 截止後未提交
- **WHEN** 今天是 2026/11/26,行銷部 10 月月結仍未提交
- **THEN** 行銷部列顯示「逾期未提交」提醒
#### Scenario: 逾期提交
- **WHEN** 研發部 10 月月結於 2026/11/26 提交
- **THEN** 研發部列顯示「逾期提交」標示
#### Scenario: 標示提交方式
- **WHEN** 行銷部 10 月月結由管理者代提交、設計部 10 月由系統自動提交
- **THEN** 行銷部列顯示「管理者代提交」,設計部列顯示「系統自動提交」
### Requirement: 部門月結詳情檢視
管理者 SHALL 能開啟任一部門某月的月結詳情,檢視部長提交的分配明細、提交當時的參數快照(補助比例、取整方式、每人額度、計算人數、月上限)、提交者、提交方式、代提交原因與時間,以及每筆案件的申請資料、附件與審核紀錄。管理者 MUST NOT 修改案件內容或分配金額。
#### Scenario: 檢視提交名單
- **WHEN** 管理者開啟設計部 2026/10 已提交月結
- **THEN** 頁面顯示提交時的分配明細與參數快照,以及每筆案件的附件與審核時間軸
#### Scenario: 未提交部門
- **WHEN** 管理者在主管提交截止前開啟尚未提交的行銷部 2026/10 月結
- **THEN** 頁面以唯讀顯示目前試算,並標示「部長尚未提交」,不提供核定與退回
#### Scenario: 逾期未提交部門
- **WHEN** 管理者在主管提交截止後開啟尚未提交的行銷部 2026/10 月結
- **THEN** 頁面以唯讀顯示目前試算,標示「部長尚未提交」並說明可在全公司月結代為提交,詳情頁本身不提供核定、退回與代提交
@@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: 顯示代提交與自動提交
部門月結由管理者代提交或系統自動提交時,部門月結頁 SHALL 在提交資訊中顯示提交方式與提交者(「管理者代提交」及管理者姓名,或「系統自動提交」),代提交時另顯示原因;頁面與主管自行提交後相同為唯讀。
#### Scenario: 主管看到被代提交
- **WHEN** 行銷部部長開啟已由管理者代提交的 10 月月結
- **THEN** 頁面顯示「由 王經理(管理者代提交)提交(逾期提交)」與代提交原因,名單唯讀
#### Scenario: 主管看到系統自動提交
- **WHEN** 行銷部部長開啟已由系統自動提交的 10 月月結
- **THEN** 頁面顯示「由 系統(自動提交)提交(逾期提交)」,名單唯讀
@@ -0,0 +1,29 @@
## MODIFIED Requirements
### Requirement: 月結流程通知
系統 SHALL 在下列月結事件發生時通知相關人:部長提交月結時通知管理端;系統自動提交月結時通知管理端;管理者代提交或系統自動提交月結時通知該部門部長,內容包含提交方式與被改為不核准的件數;管理者退回月結時通知該部門部長;最終核定時通知該月結內所有申請人,並顯示最終補助金額與預計發放月份。系統 MUST NOT 發送「已發放」通知;舊的已發放通知仍可在通知清單中查看。
#### Scenario: 部長提交月結
- **WHEN** 設計部部長提交 2026/10 月結
- **THEN** 管理端使用者收到「設計部已提交 2026/10 月結」通知
#### Scenario: 管理者代提交
- **WHEN** 管理者代提交行銷部 2026/10 月結,其中 2 筆未審案件改為不核准
- **THEN** 行銷部部長收到「行銷部 2026/10 月結已由管理者代為提交」通知,內容說明 2 筆案件改為不核准
#### Scenario: 系統自動提交
- **WHEN** 系統自動提交行銷部 2026/10 月結
- **THEN** 行銷部部長收到「行銷部 2026/10 月結已由系統自動提交」通知,管理端收到行銷部已提交的通知
#### Scenario: 最終核定通知申請人
- **WHEN** 管理者最終核定設計部 2026/10 月結
- **THEN** 該月結內每位申請人收到含其最終補助金額與預計發放月份的通知,之後不會再收到發放通知
## ADDED Requirements
### Requirement: 自動提交失敗通知
系統自動提交時有部門被跳過,系統 SHALL 通知管理端該月份被跳過的部門與原因;同一天同一月份 MUST NOT 重複通知。
#### Scenario: 部門被跳過
- **WHEN** 2026/11/29 自動提交時行銷部因手動調整超過月上限被跳過
- **THEN** 管理端收到「2026/10 月結自動提交失敗(1 個部門)」通知,列出行銷部與原因;當天之後的排程不再重複通知
@@ -0,0 +1,36 @@
## MODIFIED Requirements
### Requirement: 制度參數項目與預設值
系統 SHALL 提供以下制度參數,並在系統初始化時以預設值建立第一個版本:一般部門每人月額度 NT$500、研發部每人月額度 NT$1,000、員工申請截止日為刷卡月份次月 20 日、主管月結提交截止日為刷卡月份次月 25 日、主要平台 ChatGPT/Claude/Gemini、附件允許格式 PDF/JPG/PNG、附件單檔上限 10 MB(規格 §16)、逾期自動提交月結(預設關閉)與自動提交天數(主管截止後第 3 天,0 到 10 天)。沒有逾期自動提交欄位的舊版本 SHALL 視為關閉、天數 3。每人補助上限固定為支付金額的 50%(逐筆無條件捨去),記錄在參數版本中但後台不可修改:系統 SHALL NOT 提供個人補助比例、取整方式與個人月補助金額上限的設定欄位。目前生效的版本比例不是 50% 時,系統 SHALL 在啟動時以「系統」新增一個立即生效、比例 50%、其他參數沿用的版本並寫入操作紀錄。
#### Scenario: 初始化後的預設參數
- **WHEN** 系統首次初始化完成,管理者開啟後台設定頁
- **THEN** 頁面顯示上述各參數的預設值,且版本紀錄中有一筆初始版本
#### Scenario: 無個人上限
- **WHEN** 管理者檢視所有可設定的參數
- **THEN** 參數清單中不包含個人月補助金額上限
#### Scenario: 沒有補助比例與取整方式
- **WHEN** 管理者開啟後台設定頁
- **THEN** 頁面不顯示「個人補助比例」與「取整方式」欄位
#### Scenario: 偽造請求修改比例
- **WHEN** 儲存參數的請求夾帶補助比例 40% 或取整方式
- **THEN** 系統忽略這些值,補助仍以支付金額 50% 為上限
#### Scenario: 由全額改為 50%
- **WHEN** 正式站目前生效的參數版本比例為 100%,系統啟動
- **THEN** 系統新增一個比例 50% 的版本(建立者「系統」,原因說明制度更正),並寫入操作紀錄;再次啟動不重複新增
#### Scenario: 開啟逾期自動提交
- **WHEN** 管理者在制度參數勾選「逾期自動提交月結」、天數填 3 並儲存
- **THEN** 系統建立新的參數版本並寫入操作紀錄,之後依現在生效的版本判斷是否自動提交
#### Scenario: 舊版本沒有自動提交欄位
- **WHEN** 生效中的參數版本建立於本功能之前
- **THEN** 後台顯示「逾期自動提交月結」為關閉、天數 3,系統不自動提交
#### Scenario: 天數超出範圍
- **WHEN** 管理者把自動提交天數填為 11
- **THEN** 系統拒絕儲存並顯示天數須為 0 到 10

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