From 191bd3a2764cce9b8e232a826f407c6e7dab8dcb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?pkgsp50777=5F=E6=A5=8A=E8=88=92=E8=AB=A0?=
Date: Fri, 30 Oct 2026 21:28:31 +0800
Subject: [PATCH] =?UTF-8?q?rebase-headcount-snapshot:=20headcount=20snapsh?=
=?UTF-8?q?ots=20and=20application=20attribution=20use=20the=201st=20of=20?=
=?UTF-8?q?the=20month=20after=20the=20card=20month=20(user=20decision=202?=
=?UTF-8?q?026-10-30:=20employees=20apply=20in=20the=20following=20month,?=
=?UTF-8?q?=20so=20people=20who=20left=20by=20the=20end=20of=20the=20card?=
=?UTF-8?q?=20month=20no=20longer=20count).=20No=20current-month=20claims:?=
=?UTF-8?q?=20card=20month=20M=20can=20be=20submitted=20from=20the=201st?=
=?UTF-8?q?=20of=20M+1=20to=20the=2020th=20(drafts=20any=20time;=20the=20f?=
=?UTF-8?q?orm=20shows=20the=20submission=20window).=20Everyone=20active?=
=?UTF-8?q?=20on=20the=20base=20date=20counts=20(no=20full-time=20filter?=
=?UTF-8?q?=20until=20HR=20Sync=20provides=20dated=20employee=20groups;=20?=
=?UTF-8?q?issue=20opened=20in=20MoonShineVFX/mason).=20Before=20the=20bas?=
=?UTF-8?q?e=20date=20no=20snapshot=20is=20created=20and=20caps=20show=20?=
=?UTF-8?q?=E3=80=8CYYYY/MM/01=20=E5=90=8D=E5=86=8A=E7=A2=BA=E5=AE=9A?=
=?UTF-8?q?=E5=BE=8C=E8=A8=88=E7=AE=97=E3=80=8D;=20the=20daily=20roster=20?=
=?UTF-8?q?sync=20maps=20this=20month's=201st=20roster=20to=20last=20card?=
=?UTF-8?q?=20month;=20the=20dashboard=20quota=20cards=20show=20the=20prev?=
=?UTF-8?q?ious=20card=20month.=20A=20one-time=20startup=20step=20removes?=
=?UTF-8?q?=20unlocked,=20unadjusted=20snapshots=20whose=20base=20date=20h?=
=?UTF-8?q?as=20not=20arrived.=20E2E=20pins=20the=20system=20clock=20to=20?=
=?UTF-8?q?the=2010th=20of=20the=20current=20month=20(pin-clock=20setup=20?=
=?UTF-8?q?project)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
CLAUDE.md | 32 +++--
.../rebase-headcount-snapshot/.openspec.yaml | 2 +
.../rebase-headcount-snapshot/design.md | 66 +++++++++
.../rebase-headcount-snapshot/proposal.md | 36 +++++
.../specs/dashboard/spec.md | 27 ++++
.../specs/headcount-snapshot/spec.md | 121 ++++++++++++++++
.../specs/hr-sync/spec.md | 24 ++++
.../specs/subsidy-application/spec.md | 59 ++++++++
.../rebase-headcount-snapshot/tasks.md | 25 ++++
playwright.config.ts | 6 +-
src/app/(app)/admin/settings/page.tsx | 23 ++-
.../(app)/admin/settings/snapshot-members.tsx | 8 +-
.../(app)/applications/application-form.tsx | 35 ++++-
src/app/(app)/dashboard/employee-section.tsx | 2 +-
src/app/(app)/dashboard/manager-section.tsx | 2 +-
src/app/(app)/help/page.tsx | 13 +-
src/components/ui/quota-card.tsx | 2 +-
src/domain/application.ts | 12 +-
src/domain/attribution.test.ts | 34 +++--
src/domain/attribution.ts | 11 +-
src/domain/dashboard.ts | 2 +-
src/domain/deadlines.test.ts | 33 ++++-
src/domain/deadlines.ts | 30 +++-
src/lib/audit-actions.ts | 1 +
src/server/applications/duplicates.test.ts | 6 +-
src/server/applications/review.test.ts | 37 +++--
src/server/applications/review.ts | 8 +-
src/server/applications/service.test.ts | 57 +++++---
src/server/applications/service.ts | 16 ++-
src/server/dashboard/queries.test.ts | 19 ++-
src/server/dashboard/queries.ts | 15 +-
src/server/hr-sync/roster.test.ts | 16 ++-
src/server/hr-sync/roster.ts | 9 +-
src/server/rules/headcount-hr.test.ts | 133 +++++++++---------
src/server/rules/headcount.test.ts | 101 +++++++++----
src/server/rules/headcount.ts | 53 +++----
src/server/rules/rebase-snapshots.test.ts | 91 ++++++++++++
src/server/rules/rebase-snapshots.ts | 73 ++++++++++
src/server/settlement/service.ts | 12 +-
src/server/startup.ts | 11 +-
src/server/testing/applications.ts | 2 +-
tests/e2e/application-helpers.ts | 11 +-
tests/e2e/applications.spec.ts | 36 ++++-
tests/e2e/company-settlement.spec.ts | 2 +-
tests/e2e/db.ts | 39 ++++-
tests/e2e/mobile-layout.spec.ts | 4 +-
tests/e2e/pin-clock.setup.ts | 8 ++
tests/e2e/pin-clock.teardown.ts | 6 +
tests/e2e/review-list.spec.ts | 3 +-
tests/e2e/review-month-and-help.spec.ts | 13 +-
tests/e2e/settlement.spec.ts | 4 +-
51 files changed, 1126 insertions(+), 265 deletions(-)
create mode 100644 openspec/changes/rebase-headcount-snapshot/.openspec.yaml
create mode 100644 openspec/changes/rebase-headcount-snapshot/design.md
create mode 100644 openspec/changes/rebase-headcount-snapshot/proposal.md
create mode 100644 openspec/changes/rebase-headcount-snapshot/specs/dashboard/spec.md
create mode 100644 openspec/changes/rebase-headcount-snapshot/specs/headcount-snapshot/spec.md
create mode 100644 openspec/changes/rebase-headcount-snapshot/specs/hr-sync/spec.md
create mode 100644 openspec/changes/rebase-headcount-snapshot/specs/subsidy-application/spec.md
create mode 100644 openspec/changes/rebase-headcount-snapshot/tasks.md
create mode 100644 src/server/rules/rebase-snapshots.test.ts
create mode 100644 src/server/rules/rebase-snapshots.ts
create mode 100644 tests/e2e/pin-clock.setup.ts
create mode 100644 tests/e2e/pin-clock.teardown.ts
diff --git a/CLAUDE.md b/CLAUDE.md
index ac3134d..c7b3b7e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -68,7 +68,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Department manager: cases and members belonging to departments in `department_managers`. Scope follows `department_managers`, not the role: someone with the manager role but no assignment sees no department. HR secondary managers have no manager role.
- Cases are attributed by the case's own department, so cases from before a transfer stay with the old department's manager.
- Admin: company-wide applications and settlements (including the approved-list export). Sysadmin: accounts and settings.
- - Per-person full-time status is never shown. The headcount snapshot's 1-day member list (admin / sysadmin only) marks non-full-time people as plain 「不計入」 with no reason.
+ - Per-person full-time status is never shown. The headcount snapshot's base-date member list (admin / sysadmin only) marks non-full-time people as plain 「不計入」 with no reason (only old lists; full-time is not used for now, see Rule parameters & headcount).
- 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`.
@@ -95,18 +95,18 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- `requestRosterResync` stores `_meta.roster_resync_requested` (real time, not system time, and requester) and records `hr_sync.roster_resync_requested`.
- The request counts as pending until a run succeeds that started after it (`rosterResyncStatus`). While it is pending, the next company login runs the sync even if today already succeeded.
- It is refused when HR Sync isn't configured.
- - Fetches the current roster and organization tree, plus the roster and tree on the 1st of this month and last month (30 s shared timeout).
+ - Fetches the current roster and organization tree, plus the roster and tree on the 1st of this month and last month (30 s shared timeout). Those dates are snapshot **base dates**: this month's 1st → last card month, last month's 1st → the card month before (`rebase-headcount-snapshot`).
- Departments step (one transaction, `syncHrDepartments`):
- Creates every active 部, renames on HR change, and syncs managers. It never reactivates a department an admin deactivated, and never changes type.
- Cleans up group-level departments: HR-managed departments whose code resolves to another department. Members move with the same effective date (a correction, not a transfer). Cases not yet in a submitted settlement move too (`application.department_corrected`). Managers are removed and the department is deactivated (`department.hr_deactivated`).
- A department with a non-`open` settlement is skipped and listed in the summary audit.
- A tree with no 部 fails with stage `departments`, and nothing is changed.
- - Writes full-time history (`employeeGroupCode === "1"`). The first record starts at the HR hire date, later changes start today. No record = not full-time.
- - Creates or updates snapshots with `syncSnapshotsFromHr`: ACTIVE on the 1st, unit resolved to the department through that day's tree (group members count toward their 部), full-time on the 1st. Locked or manually adjusted snapshots are never overwritten. Departments without a code in that roster are skipped. Last month is processed before this month.
- - It also stores the 1-day member list in `headcount_snapshot_members` (same conditions as the count; a DB trigger rejects writes for a locked snapshot): `counted` (== the count), `excluded` (ACTIVE, not full-time; shown without a reason), `suspended`, `offboarded` (only `leaveDate` ≥ the 1st of the previous month). Non-ACTIVE people without a unit fall back to last month's list. A list-only change records `headcount.snapshot_members_updated` (counts only, no names). `listMonthSnapshots` returns `members` (local snapshots list `departmentMembersAt` live; an HR snapshot without a list is null → 「此快照沒有名單紀錄」).
+ - Writes full-time history (`employeeGroupCode === "1"`). The first record starts at the HR hire date, later changes start today. No record = not full-time. **Not read for now**: HR Sync returns the current group even for dated roster queries and has no group-change event, so snapshots count everyone ACTIVE (user decision 2026-10-30; an issue is open in MoonShineVFX/mason — restore the intern rule in a new change once HR Sync has dated groups).
+ - Creates or updates snapshots with `syncSnapshotsFromHr(tx, audit, cardMonth, rosterOnBaseDate, tree)`: ACTIVE on the base date, unit resolved to the department through that day's tree (group members count toward their 部). Locked or manually adjusted snapshots are never overwritten. Departments without a code in that roster are skipped. The earlier card month is processed first.
+ - It also stores the 1-day member list in `headcount_snapshot_members` (same conditions as the count; a DB trigger rejects writes for a locked snapshot): `counted` (== the count; every ACTIVE person), `excluded` (old lists only: ACTIVE, not full-time; shown without a reason), `suspended`, `offboarded` (only `leaveDate` ≥ the 1st of the card month). Non-ACTIVE people without a unit fall back to last month's list. A list-only change records `headcount.snapshot_members_updated` (counts only, no names). `listMonthSnapshots` returns `members` (local snapshots list `departmentMembersAt` live; an HR snapshot without a list is null → 「此快照沒有名單紀錄」).
- Employment status step (`syncEmploymentStatus`, `src/server/hr-sync/employment-status.ts`, stage `employment_status`, after snapshots, current roster): stores `users.hr_status` / `hr_status_since` for existing accounts. SUSPENDED / OFFBOARDED + active → `deactivateUser(…, hrDeactivated=true)` (sessions deleted, department history null from `suspendedSince` / `leaveDate`, clamped to [last history date, today]) and `account.hr_deactivated`. ACTIVE + inactive + `hr_deactivated` → `activateUser` (original department from today) and `account.hr_reactivated`. Manually deactivated accounts are never re-enabled; `setAccountActive` refuses to enable an account whose HR status is SUSPENDED / OFFBOARDED (`HR_INACTIVE_ACCOUNT_ERROR`). `/admin/accounts` shows HR 狀態 and 「由 HR 停用」.
- Each step is its own transaction. A failure stops the run and is recorded in the row (stage + reason). Success writes one `hr_sync.roster_synced` summary audit, not one per person.
- - Per-person full-time status is never shown on any page; only headcount totals use it.
+ - Per-person full-time status is never shown on any page (and is currently not used for headcounts).
- HR wins:
- HR name over the ID token name.
- ACTIVE assignment → the unit's 部 (`resolveDivision` over `/organizations`) → department by `departments.code`, auto-created (type general; admins set 研發) / renamed / reactivated and marked `hr_managed`. If the organization query failed, the department is left unchanged. Moving between groups inside one 部 is not a transfer. A transfer writes `user_department_history` from the HR `hr.employee.transferred` effective date (`transferEffectiveDate`: only events whose new unit resolves to the new department and old unit to a different one; not before the user's last history row and not after today, otherwise today), and sets `users.hr_synced_at`. Non-ACTIVE or no organization → department untouched.
@@ -120,7 +120,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- **No HR query entry points.** Only the callback route (login + roster sync) and the settings page and its actions (roster sync status and resync request only) may import `@/server/hr-sync/*` from `src/app`. `client`, `token` and `snapshot` are server-only (`entrypoints.test.ts` enforces this).
- No page, action or route lets a user name an employee, department or date to query HR.
- Stored HR fields: name, ACTIVE assignment → department (code, name), primary supervisors, and the roster's employee number / name / status / department code / employee group / hire date / leave date / suspended-since (full-time history, snapshot member lists and account status only). Everything else is dropped by the Zod schemas in `client.ts`.
-- Tests inject a fake `fetchSnapshot` / `HrDirectory` / `HrRosterSource`. E2E must not insert `hr_employment_history` rows: the e2e DB is shared, and once any row exists every locally computed snapshot counts full-time only (use `markSnapshotFromHr` / `insertRosterSync` to simulate). E2E (dev login) simulates synced data with `createHrSyncedTeam()` (`tests/e2e/db.ts`).
+- Tests inject a fake `fetchSnapshot` / `HrDirectory` / `HrRosterSource`. E2E should not insert `hr_employment_history` rows (the e2e DB is shared; simulate with `markSnapshotFromHr` / `insertRosterSync`). E2E (dev login) simulates synced data with `createHrSyncedTeam()` (`tests/e2e/db.ts`).
- HR Sync endpoints and response fields: the API manual in the `hr-sync` skill of [MoonShineVFX/mason](https://github.com/MoonShineVFX/mason) (`skills/hr-sync/`: `references/api-contract.md`, `references/hr-sync-openapi.json`). The copy in the vibe-deploy plugin (moonshine-skills) is kept only for compatibility and no longer maintained.
## Audit trail (操作紀錄)
@@ -137,7 +137,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. Everyone ACTIVE counts (no full-time filter for now). A one-time startup step `rebaseHeadcountSnapshots` (`_meta` `headcount_base_next_month`) deleted unlocked, unadjusted snapshots whose base date had not arrived (`headcount.snapshot_removed`).
+- Department cap: `getDepartmentCap(db, departmentId, month, tz)` is read-only and returns 「尚未建立人數快照」 when missing — call `ensureMonthSnapshots` first where a snapshot must exist (settlement). Snapshots count members at 00:00 on the base date (from `user_department_history`; `localHeadcount`). Snapshots have a `source` (`local` / `hr`); the daily HR roster sync replaces unlocked, unadjusted ones with the HR count.
- Settlement submit/return must call `setSnapshotLocked(tx, audit, departmentId, month, locked)` inside its transaction.
- An initial parameter version is created by `ensureDefaultRuleVersion` at startup and in seed.
- Personal cap 50% (2026-10-20 rule correction, replacing the 2026-10-14 full subsidy):
@@ -149,7 +150,8 @@ 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.
@@ -167,7 +169,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Card-month filter `?month=YYYY-MM|all` (`reviewQueueMonths`; `listReviewQueue` / `reviewQueueCounts` take the month): default is the earliest month with cases in the current tab, or the case's month for a bare `?id=`; tab counts, list, batch approve and cap summaries follow the month; links keep it.
- Narrow screens: a card list, plus `/department/review/:id`.
- Above the lists, and in the detail: 部門額度試算 per (department, card month).
- - `reviewCapPreview` / `reviewCapPreviews` cover pending + approved + pending-settlement cases, using the settlement calculation (equal share, current adjustments) with the current params (read-only; creates a missing snapshot for started months).
+ - `reviewCapPreview` / `reviewCapPreviews` cover pending + approved + pending-settlement cases, using the settlement calculation (equal share, current adjustments) with the current params (read-only; creates a missing snapshot once the base date has passed; before that it shows 「YYYY/MM/01 名冊確定後計算」).
- Shown with `ReviewCapSummary` and `MoneyDisplay kind="preview"` 「試算」. A submitted month shows final amounts.
- 已核准, 待審 and 合計 are personal-cap sums (each case × 50%, floored per case), so 已核准 + 待審 = 合計. 合計 is `totalEligible`, not affected by adjustments, the same base as 超出 (user decisions 2026-10-16 / 2026-10-20). Each case's 試算 is ≤ 50% of that case. When over, 合計 and the 超出 amount turn `text-danger`.
- E2E: create isolated users with `createEmployee()`, or a department with its own manager via `createTeam()`, and ready-to-review cases with `insertPendingApplication()` (`tests/e2e/db.ts`); states from later changes can be simulated there. Shared form steps live in `tests/e2e/application-helpers.ts`.
@@ -208,7 +210,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Locking after submit:
- `isSettlementLocked` (`src/server/settlement/lock.ts`) is checked in `applyTransition` and when editing a case. Any new write path for a case or settlement must check it too.
- DB triggers reject changes to amounts/allocations of non-`open` settlements. Only `status` may change.
-- E2E: `monthsAgo(2)` is always past the submission deadline. Control the cap with `setHeadcount(departmentId, month, n)` before opening the page. `insertPendingApplication` takes `cardDate` / `twdAmount` / `status`.
+- E2E: the system clock is pinned to the 10th of the current month (see System clock), so `monthsAgo(1)` is inside the submission window (1st–20th) with its snapshot base date passed, `monthsAgo(2)` is always past the submission deadline, and the current month cannot be submitted and has no cap. Control the cap with `setHeadcount(departmentId, month, n)` before opening the page. `insertPendingApplication` takes `cardDate` (default `claimDate(5)`, last month) / `twdAmount` / `status`.
- Admin side (`src/server/settlement/company.ts`, `payouts.ts`; pages `/admin/settlements`, `/admin/settlements/:departmentId/:month`, `/admin/settlements/export`). Admin role only; the services also check it.
- Overdue forced submit (`force-submit-overdue-settlement`, user decision 2026-10-30): after the manager deadline an admin can 「代為提交」 next to the 「逾期未提交」 badge on the `/admin/settlements` overview (`force-submit-button.tsx`; moved from the detail page, user decision 2026-10-30; `forceSubmitSettlement` mode `admin`, reason required, `ReasonDialog` + `confirmStep`); when the rule param `autoSubmit.enabled` (default off, `graceDays` 0–10, default 3, read from the version effective **now**) is on, the hourly settlement scheduler (`runAutoSubmit`, `auto-submit.ts`) submits overdue departments with at least one non-draft case in the previous 1–2 card months after deadline + grace days (mode `auto`, actor `SYSTEM_ACTOR`, label 「系統(自動提交)」). Both share `submitInTx` with the manager submit: pending-review / needs-revision cases first go through the `overdue_reject` transition (actor admin or system, system comment) and stay rejected after a later return; overrides over the cap/personal cap block (auto skips the department and sends `reminder.auto_submit_failed` once a day per month). `submission_mode` / `submission_reason` on `department_settlements` and `settlement_submissions`; managers get `settlement.force_submitted`; audits `settlement.proxy_submitted` / `settlement.auto_submitted`. Managers' own submit is still blocked by unreviewed cases.
- Settlement status: `open → submitted → finalized`. **Final approval is the end** (`remove-payout-management`, user decision 2026-10-28): no payout tracking, no `paid` transition, no corrections. A return goes `submitted → open` and unlocks the snapshot; a finalized settlement can't be returned or corrected.
@@ -243,7 +245,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- `auditContextFor` gives `now` (system time) and `realNow`. `recordAudit` writes `occurred_at` as real time and, when they differ, `simulated_at` as system time (`/admin/audit-log` shows 「系統時間 …」). Contexts rebuilt from another context must carry `realNow` over (see `systemContext` in the settlement service). The schedulers pass both.
- While adjusted, `(app)/layout.tsx` passes `clockNotice` to `AppFrame`. Every page then shows 「系統時間已調整為 …(真實時間 …)」, and sysadmins also get a link to the tab.
- Clearing business data keeps the offset.
-- E2E: `tests/e2e/clock.spec.ts` runs in its own Playwright project (`clock`) after all other tests. It clears the offset before and after (`clearClockOffset`). No other spec may set it.
+- E2E: the `pin-clock` setup project (`tests/e2e/pin-clock.setup.ts`, `pinSystemClock` in `db.ts`) sets the offset to the 10th of the current month at 12:00 Taipei before the `chromium` project, and its teardown clears it. Test code uses `today()` (the pinned system date) and `claimDate()` (last month, submittable) from `db.ts`; `monthsAgo` follows the real month (unchanged by the pin). `tests/e2e/clock.spec.ts` runs in its own Playwright project (`clock`) after all other tests and clears the offset before and after (`clearClockOffset`). No spec may set it otherwise.
## Duplicate detection & notifications
@@ -275,7 +277,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- `/dashboard` is composed per role: admin section first, then one manager section per managed department, then the employee section.
- Data comes from `src/server/dashboard/queries.ts`. Permissions are filtered in each query.
- Logic lives in `src/domain/dashboard.ts`: `resolveCurrentCycle` and `quotaReference`. `quotaReference` reuses the settlement `personalEligible`.
-- Show department quota only through `QuotaCard`. Its 「參考」 tag and explanation are built in; never show a bare "remaining quota".
+- Show department quota only through `QuotaCard`. The employee and manager cards show the **previous card month** (`quotaMonth`, the month being applied for now; the current month's cap is only known from the 1st of next month — `rebase-headcount-snapshot`). Its 「參考」 tag and explanation are built in; never show a bare "remaining quota".
- Show case amounts through `SubsidyAmount`: 「月結後確認」 before submission (no estimate), 最終 after. The employee section has no month estimate. The admin 「全公司預估補助」 stays.
## UI (app-shell)
@@ -325,9 +327,9 @@ Changes go through OpenSpec (`openspec/config.yaml`, schema `spec-driven`). Spec
## Domain rules that are easy to get wrong
- **Month attribution** is by **刷卡日期 (card charge date)** only — never invoice date, service period, or submission date. It drives the application month and both deadlines.
-- **Deadlines**: employee submission by the 20th of the following month; department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
+- **Deadlines**: employee submission from the 1st to the 20th of the following month (no current-month claims); department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
- **Personal amount**: 支付金額 = sum of the month's approved TWD amounts; the **personal cap is 50%** of it, floored per case (rule corrected 2026-10-20; settlements between 2026-10-14 and then used 100%). TWD amount from the card statement is the basis; foreign-currency amount is reference only.
-- **Department monthly cap** = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a **monthly snapshot**, not live headcount. Unused quota does not carry over.
+- **Department monthly cap** = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a **monthly snapshot** taken on the 1st of the month after the card month (everyone active; no full-time filter for now), not live headcount. Unused quota does not carry over.
- **Over cap** → equal share (user decision 2026-10-15, replacing the spec document's pro-rata): adjusted people keep their adjusted amount, the rest split `cap − adjusted total` equally, nobody above their own personal cap; leftover yuan go by employee number. The total **never exceeds** the cap (paid 900/1,700 → caps 450/850, with cap 1,000 → 450/550). Submitted settlements keep their stored results.
- **Approval ≠ payout.** Managers review work purpose only; amounts are settled at month end across all approved cases. UI must never make the quota look first-come-first-served, and must not show employees an amount before settlement (「月結後確認」), only 「最終」 after.
- **Statuses**: 草稿 → 待主管審核 → (待補件 ↔ resubmit) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 (end; legacy rows may be 已發放); plus 撤回. Return/reject require a comment.
diff --git a/openspec/changes/rebase-headcount-snapshot/.openspec.yaml b/openspec/changes/rebase-headcount-snapshot/.openspec.yaml
new file mode 100644
index 0000000..4bfa670
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-10-30
diff --git a/openspec/changes/rebase-headcount-snapshot/design.md b/openspec/changes/rebase-headcount-snapshot/design.md
new file mode 100644
index 0000000..417612f
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/design.md
@@ -0,0 +1,66 @@
+## Context
+
+- 快照(`src/server/rules/headcount.ts`):刷卡月份 M 以 `M-01` 為基準日;`ensureMonthSnapshots` 在 `monthStarted(M)` 之後懶建立;`localMembers` / `localHeadcount` 依部門歷程(`departmentMembersAt`),有正職資料時排除非正職;`syncSnapshotsFromHr(month, rosterOnFirst, tree)` 依 1 日名冊算人數與名單,離職者列出條件是 `leaveDate ≥ previousMonth(M)-01`。
+- 名冊同步(`src/server/hr-sync/roster.ts` 的 `run`):抓本月與上月 1 日的名冊、組織樹,`months = [本月, 上月]`,先上月再本月呼叫 `syncSnapshotsFromHr`。
+- 申請歸屬(`src/domain/attribution.ts` 的 `attributedDepartment`):`M-01` → 刷卡日 → 目前部門。建立、儲存、送出時重算;送出後固定。
+- 月上限:`getDepartmentCap` 沒有快照時回 `NO_SNAPSHOT_MESSAGE`;審核頁試算(`reviewCapPreview(s)`)與首頁 `QuotaCard` 會替「已開始的月份」建立缺少的快照。
+- 月結:主管提交在員工申請截止(M+1 月 20 日)之後,那時基準日(M+1 月 1 日)已過,快照一定建得出來。
+
+## Goals / Non-Goals
+
+**Goals:**
+- 基準日一個定義(`snapshotBaseDate(M)` = M+1 月 1 日),快照、名單、歸屬、名冊同步都用它。
+- 不依正職排除;留停與離職名單規則不變(以基準日為準)。
+- 部署後不需要人工修資料。
+
+**Non-Goals:**
+- 實習生判斷(等 mason HR Sync 提供依日期的員工群組)。
+- 改寫已送出申請的歸屬部門、已鎖定或人工調整的快照。
+
+## Decisions
+
+### D1 單一基準日函式
+
+`src/domain/` 新增 `snapshotBaseDate(month)`(`YYYY-MM` → 下個月 `YYYY-MM-01`,跨年)。所有原本寫 `` `${month}-01` `` 的快照與歸屬程式改呼叫它;「已開始的月份」判斷改成 `baseDateReached(month, now, tz)`(基準日 00:00 已過)。離職名單截止日改為基準日的上個月 1 日(= 刷卡月份 1 日),維持「上個月 1 日之後離職」的語意。
+
+### D2 申請歸屬同一基準日
+
+`attributedDepartment` 改用 `snapshotBaseDate(cardMonth)`,退路不變(刷卡日 → 目前部門)。基準日在未來時,`departmentOn` 取「不晚於基準日的最後一筆歷程」,也就是目前所屬的部門,不需特別處理;送出後固定,之後調部門不影響(與現在相同)。
+
+### D2a 申請開始日
+
+`deriveDeadlines` 加上 `employeeStart`(= 基準日 00:00)。`submitApplication` 與補件重送在 guard 裡先檢查開始日、再檢查截止,訊息「此筆刷卡日期屬於 YYYY/MM,YYYY/MM/01 起才能送出。」;表單(`validateApplication` submit 模式與摘要區)顯示可送出期間並在開始日前停用「送出」。草稿照常可存。因為送出時基準日一定已到,歸屬部門一定以基準日判斷;只有草稿在基準日前顯示目前所屬部門。
+
+補件重送:退回補件只會發生在已送出(基準日已過)的案件,不受開始日影響。
+
+### D3 名冊同步的月份對應
+
+`run` 仍抓本月與上月 1 日的名冊(HR 查詢日期不變),但對應的快照月份往前一個月:本月 1 日名冊 → 上個刷卡月份,上月 1 日名冊 → 上上個刷卡月份。先算較早的月份(名單的留停/離職退路取上個月名單,現有順序)。部門清理用的組織樹不變。
+
+### D4 基準日前的月上限
+
+`getDepartmentCap` 在基準日未到時回傳新的訊息「YYYY/MM/01 名冊確定後計算」(`capPendingMessage(month)`),不嘗試建立快照。審核頁試算、首頁額度、月結頁遇到這個訊息時照現有「無快照」的呈現顯示這句話。月結提交在申請截止後,不會遇到。
+
+### D5 不依正職排除
+
+`syncSnapshotsFromHr` 與 `localMembers` 不再呼叫 `fullTimeOn` / `hasEmploymentData`,在職者一律 `counted`。`recordEmployment` 照常寫入正職身分歷程(不讀取),之後恢復判斷時可參考;`excluded` 狀態保留給舊名單顯示。
+
+### D6 部署時清掉基準日未到的快照
+
+啟動時(`migrateOnStartup` 之後、背景排程之前)執行一次 `rebaseHeadcountSnapshots`,以 `_meta` 鍵 `headcount_base_next_month` 記錄已執行:刪除「基準日尚未到、未鎖定、沒有人工調整」的快照與其名單(就是部署當下的刷卡月份),每筆寫 `headcount.snapshot_removed` 操作紀錄(操作者「系統」,原因「人數快照基準日改為下個月 1 日」)。其他月份不刪:未鎖定、未調整的 HR 快照由下一次名冊同步依新對應更新;本系統計算的舊快照維持(只在建立時計算,與現在相同)。替代方案「重算所有未鎖定快照」被否決:本系統快照的部門歷程在部署當下不一定齊全,HR 快照也只有名冊同步能取得當日名冊。
+
+月結試算若用到被刪的快照,`getSettlementView` 會因月上限改變顯示「請按重新計算」(現有行為);基準日未到的月份不能提交,不受影響。
+
+## Risks / Trade-offs
+
+- [刷卡月份當月的額度看不到] 主管在當月審核時沒有月上限試算 → 依使用者說明,申請在下個月才開始,月初快照就會建立;畫面明確說明哪一天確定。
+- [每月 21 日到月底沒有可送出的月份] 前一個月已截止、當月還不能送 → 這是使用者定的制度;表單摘要清楚顯示期間。
+- [e2e 的送出流程] 現在的 e2e 以「今天」為刷卡日期送出;改制後要用前一個月的日期,但每月 21 日之後前一個月已截止,送出類 e2e 會因日期而失敗 → 新增 `pin-clock` setup project:所有一般 e2e 開始前把系統時間固定在本月 10 日 12:00(台北),結束後由 teardown 清除;`clock.spec` 照舊最後執行並自行清除。月份不變,上個月的申請在可送出期間內、基準日已過,上上個月一定已截止。
+- [部門月上限變化] 實習生計入、基準日後移,各部門人數與月上限會變;已提交月結的鎖定快照不受影響。
+- [舊 HR 快照的名單] 名冊同步更新前,未鎖定的舊快照名單仍是 1 日名單 → 下一次同步就會更新;需要立即生效可用「下次登入時重新同步名冊」。
+
+## Migration Plan
+
+1. 部署:啟動時跑 `rebaseHeadcountSnapshots`(只一次)。
+2. 管理者可在設定頁按「下次登入時重新同步名冊」,讓下一次登入就以新對應更新上個月與上上個月的快照。
+3. 回滾:程式回到前一版;被刪除的快照會由舊規則在需要時重新建立。
diff --git a/openspec/changes/rebase-headcount-snapshot/proposal.md b/openspec/changes/rebase-headcount-snapshot/proposal.md
new file mode 100644
index 0000000..dc66ddb
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/proposal.md
@@ -0,0 +1,36 @@
+## Why
+
+兩個人數快照的問題(使用者 2026-10-30):
+
+1. **基準日**:快照以「刷卡月份 1 日」的名冊計算,但員工是在刷卡月份的**下個月**才申請(例:10 月申請 9 月補助,11 月發放)。9/30 離職的人 10 月已經不能申請,卻仍算在 9 月的部門人數裡,墊高了部門月上限;9 月中到職的人反而不算。使用者決定改用「刷卡月份下個月 1 日」的名冊(9 月補助用 10/1 名冊),申請的歸屬部門也一起改用同一天,讓人頭與申請落在同一個部門。
+2. **正職判斷**:快照只計入當日「正職」,但 HR Sync 帶 `date` 查名冊時員工群組回傳現況值,也沒有員工群組變更事件,系統無法知道某人在基準日是不是正職。使用者已在 MoonShineVFX/mason 開 issue;在那之前,快照計入基準日名冊上所有在職的人。
+
+## What Changes
+
+- **基準日改為刷卡月份的下個月 1 日**:刷卡月份 M 的快照依 (M+1) 月 1 日 00:00(Asia/Taipei)的名冊或部門歷程計算,例如 2026/09 的快照用 2026/10/01。基準日之前不建立該月快照,月上限顯示「YYYY/MM/01 名冊確定後計算」。
+- **申請歸屬部門同一基準日**:刷卡月份 M 的申請歸屬申請人在 (M+1) 月 1 日所屬的部門;當天不屬於任何部門(例如月底離職)時用刷卡日當天的部門,仍沒有則用目前的部門。送出後不再改變(現有規則)。**BREAKING**:調部門前後的申請歸屬會和以前不同。
+- **不得申請當月補助**:刷卡月份 M 的申請從 M 的下個月 1 日起才能送出(例:10 月只能申請 9 月;10/28 送出 10 月刷卡會被拒絕),截止仍是次月 20 日;草稿不受限。表單摘要顯示可送出的期間。**BREAKING**。
+- **首頁額度卡改顯示上個刷卡月份**:本月刷卡的月上限要到下個月 1 日才確定,首頁員工與主管的額度卡改為顯示本月正在申請的月份(上個月)。
+- **名冊同步的月份對應**:每日名冊同步原本用本月 1 日名冊算本月、上月 1 日名冊算上月;改為本月 1 日名冊算**上個月**、上月 1 日名冊算**上上個月**(未鎖定時)。
+- **不再依正職身分排除**:在職者一律計入,名單不再出現沒有原因的「不計入」;留停、離職照舊列出。正職身分歷程照常記錄、暫不使用,等 HR Sync 提供依日期的員工群組後另開 change 恢復實習生判斷。
+- **既有資料**:已鎖定或人工調整的快照不動。基準日尚未到的未鎖定、未調整快照(目前刷卡月份的)在部署後刪除;其他未鎖定、未調整的 HR 快照由下一次名冊同步依新規則更新。已送出的申請歸屬不變。
+
+## Capabilities
+
+### New Capabilities
+
+(無)
+
+### Modified Capabilities
+
+- `headcount-snapshot`:基準日改為刷卡月份下個月 1 日;不依正職排除;月上限在基準日前顯示尚未確定;名冊同步的月份對應。
+- `subsidy-application`:申請歸屬部門改為刷卡月份下個月 1 日的部門;刷卡月份當月不能送出(下個月 1 日起才可送出)。
+- `dashboard`:額度卡(員工、主管)顯示上個刷卡月份的額度。
+- `hr-sync`:調部門與申請歸屬的情境依新基準日;名冊同步用的 1 日名冊對應到前一個刷卡月份。
+
+## Impact
+
+- 程式:`src/domain/attribution.ts`(基準日)、`src/domain/deadlines.ts` 與送出檢查(申請開始日)、申請表單摘要、`src/server/rules/headcount.ts`(快照基準日、`monthStarted` → 基準日已到、名單、`localMembers` / `localHeadcount`、`syncSnapshotsFromHr` 的離職截止日、月上限訊息)、`src/server/hr-sync/roster.ts`(名冊日期與快照月份對應)、審核頁額度試算與首頁額度(`reviewCapPreview`、`QuotaCard` 的「尚未確定」)、設定頁人數快照(顯示基準日、建立按鈕條件)。
+- 資料:一次性的啟動步驟刪除基準日未到的未鎖定、未調整快照(寫操作紀錄),以 `_meta` 旗標確保只跑一次。
+- 測試:快照、名冊同步、歸屬、審核額度、首頁、月結的單元與整合測試;e2e 中依「本月快照」的測試(例如審核頁額度試算)要改用基準日已到的月份。
+- 文件:CLAUDE.md(Applications 的歸屬、Rule parameters & headcount、HR Sync 的 snapshot 與 full-time 段落、Department settlement)、`/help`、設定頁說明文字。
diff --git a/openspec/changes/rebase-headcount-snapshot/specs/dashboard/spec.md b/openspec/changes/rebase-headcount-snapshot/specs/dashboard/spec.md
new file mode 100644
index 0000000..0dddeba
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/specs/dashboard/spec.md
@@ -0,0 +1,27 @@
+## MODIFIED Requirements
+
+### Requirement: 部門額度以參考值呈現
+首頁顯示部門額度時 SHALL 呈現「目前已通過可補助總額/部門月上限」與使用百分比,並 MUST 標示「參考」及說明「實際補助於當月結算後依全體通過案件與部門額度統一確認,可能因其他申請而變動」。系統 MUST NOT 以未加上述說明的「剩餘可用額度」呈現,也 MUST NOT 暗示先申請者優先取得額度。已通過可補助總額只計入該部門該月「審核通過」以後狀態的案件。額度卡 SHALL 顯示**上個刷卡月份**——也就是員工本月正在申請的月份——的額度(使用者決定 2026-10-30:本月刷卡要到下個月 1 日名冊確定後才有月上限),卡片標題標示該月份。
+
+#### Scenario: 顯示參考額度
+- **WHEN** 今天是 2026/11/05,設計部 10 月已通過可補助總額 NT$3,250、月上限 NT$10,000
+- **THEN** 額度卡標示 10 月,顯示「NT$3,250/NT$10,000(參考)」、已使用 32.5%,並附月結後確認的說明
+
+#### Scenario: 已超過月上限
+- **WHEN** 已通過可補助總額 NT$13,000 超過月上限 NT$10,000
+- **THEN** 額度卡顯示超過上限,並說明月結時將由申請人平分月上限,不顯示負數剩餘額度
+
+#### Scenario: 尚無人數快照
+- **WHEN** 該月尚未建立部門人數快照
+- **THEN** 額度卡顯示「本月額度尚未設定」,不顯示百分比
+
+### Requirement: 主管區塊內容
+主管區塊 SHALL 顯示所屬部門的待審件數、待補件件數、上個刷卡月份(本月正在申請的月份)的額度使用(同參考值規範)、距部長提交截止剩餘天數、目前月結狀態,以及最近 5 筆待處理案件(連往部門審核)。
+
+#### Scenario: 待處理摘要
+- **WHEN** 設計部有 3 筆待主管審核、1 筆待補件,今天 2026/11/22
+- **THEN** 主管區塊顯示待審 3、待補件 1、10 月的額度使用、距 10 月月結截止剩 3 天,並列出待審案件
+
+#### Scenario: 月結已提交
+- **WHEN** 設計部 10 月月結已提交
+- **THEN** 主管區塊顯示 10 月月結「已提交」,不再顯示其截止倒數
diff --git a/openspec/changes/rebase-headcount-snapshot/specs/headcount-snapshot/spec.md b/openspec/changes/rebase-headcount-snapshot/specs/headcount-snapshot/spec.md
new file mode 100644
index 0000000..8e04ed7
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/specs/headcount-snapshot/spec.md
@@ -0,0 +1,121 @@
+## MODIFIED Requirements
+
+### Requirement: 建立每月人數快照
+系統 SHALL 為每個部門、每個刷卡月份建立一筆計算人數快照。刷卡月份 M 的快照以**基準日**——M 的下個月 1 日 00:00(Asia/Taipei)——時隸屬該部門且在職的人數計算(使用者決定 2026-10-30:員工在刷卡月份的下個月申請,基準日前離職的人已無法申請)。在 HR Sync 能提供依日期的員工群組之前,系統 MUST NOT 依正職身分排除任何人。HR Sync 已設定時人數以 HR 名冊為準(見「由 HR 名冊自動建立與更新快照」)。快照 SHALL 在基準日之後首次需要時(查詢月上限或開啟設定頁)自動建立,管理者亦 SHALL 可手動觸發建立;基準日之前 MUST NOT 建立。在名冊同步之前建立時以本系統部門歷程計算,之後由名冊同步更新。無論何時建立,人數皆以基準日 00:00 的狀態計算。同一部門同一月份 MUST 只有一筆快照。
+
+#### Scenario: 月初後首次需要時自動建立
+- **WHEN** 2026/10/01 00:00 設計部有 20 位在職人員,2026/10/03 管理者首次開啟 2026/09 的人數快照
+- **THEN** 系統建立設計部 2026/09 快照,人數為 20
+
+#### Scenario: 月中到職不影響當月快照
+- **WHEN** 2026/10/10 有一位新人加入設計部
+- **THEN** 設計部 2026/09 快照人數仍為 20;這位新人計入 2026/10 快照(基準日 2026/11/01)
+
+#### Scenario: 非正職不計入
+- **WHEN** 2026/10/01 00:00 設計部的 20 位在職人員中有 2 位是工讀生,且系統已有正職身分歷程
+- **THEN** 暫行規則下工讀生也計入,設計部 2026/09 快照人數為 20(等 HR Sync 提供依日期的員工群組後另行恢復排除)
+
+#### Scenario: 刷卡月份最後一天離職
+- **WHEN** 設計部一位員工 2026/09/30 為最後工作日、10/01 起離職
+- **THEN** 他不計入設計部 2026/09 快照
+
+#### Scenario: 基準日之前不建立
+- **WHEN** 今天是 2026/09/20,管理者開啟 2026/09 的人數快照
+- **THEN** 系統不建立快照,說明「2026/10/01 名冊確定後計算」
+
+#### Scenario: 未設定 HR Sync
+- **WHEN** 開發環境沒有 HR Sync,2026/10/01 設計部有 5 位成員
+- **THEN** 設計部 2026/09 快照人數為 5
+
+#### Scenario: 重複建立
+- **WHEN** 管理者對已有快照的部門與月份再次觸發建立
+- **THEN** 系統不建立第二筆快照,並提示該月份快照已存在
+
+### Requirement: 部門月上限計算
+系統 SHALL 以「快照人數 × 該月生效之部門類型每人月額度」計算部門月上限:一般部門使用一般部門每人月額度,研發部使用研發部每人月額度(規格 §7.2)。快照不存在時 MUST NOT 回傳月上限:基準日已到時 SHALL 回傳「尚未建立人數快照」;基準日未到時 SHALL 回傳「YYYY/MM/01 名冊確定後計算」(YYYY/MM/01 為基準日),審核頁的部門額度試算與首頁額度顯示同一句說明。
+
+#### Scenario: 一般部門月上限
+- **WHEN** 設計部(一般部門)2026/10 快照人數為 20,每人額度 NT$500
+- **THEN** 部門月上限為 NT$10,000
+
+#### Scenario: 研發部月上限
+- **WHEN** 研發部 2026/10 快照人數為 2,每人額度 NT$1,000
+- **THEN** 部門月上限為 NT$2,000
+
+#### Scenario: 無快照
+- **WHEN** 查詢一個尚未建立 2026/10 快照之部門的月上限,今天是 2026/11/03
+- **THEN** 系統回傳「尚未建立人數快照」而非數值
+
+#### Scenario: 基準日未到
+- **WHEN** 今天是 2026/10/15,主管在審核頁看 2026/10 刷卡的案件
+- **THEN** 部門額度試算顯示「2026/11/01 名冊確定後計算」,不顯示月上限與超額
+
+### Requirement: 由 HR 名冊自動建立與更新快照
+名冊同步(見 hr-sync)SHALL 以 HR 本月 1 日的名冊(`GET /employees?date=YYYY-MM-01`)與該日的組織結構計算**上個刷卡月份**各部門的快照人數,並 SHALL 以上個月 1 日的名冊與組織結構重算上上個刷卡月份(該月快照尚未鎖定時)。某部門的人數為:基準日 HR 狀態為在職(ACTIVE)、且該日所屬單位依該日組織結構歸到該部門(見 hr-sync「HR 部門對應與自動建立」,部底下各組的人計入部)的人數,不依正職身分排除。系統 SHALL 依計算結果建立缺少的快照;已存在且未鎖定、也沒有人工調整的快照,人數不同時 SHALL 更新為 HR 人數,並寫入操作紀錄(操作者「系統(HR 同步)」,含前後人數)。已鎖定或有人工調整的快照 MUST NOT 被覆寫。基準日 HR 名冊中沒有任何人歸到的啟用部門(含手動建立、沒有代碼的部門)SHALL 照舊以本系統部門歷程計算。
+
+#### Scenario: 月初自動建立
+- **WHEN** 2026/10/01 HR 名冊中設計部在職的有 20 位正職與 2 位工讀生,2026/10/02 第一位員工登入觸發名冊同步
+- **THEN** 系統建立設計部 2026/09 快照,人數為 22,來源為 HR 名冊
+
+#### Scenario: 1 日之後到職或離職
+- **WHEN** 一位新人 2026/10/10 到職設計部、另一位設計部員工 2026/10/12 離職
+- **THEN** 設計部 2026/09 快照仍為 22;兩人只影響 2026/10 快照(基準日 2026/11/01)
+
+#### Scenario: HR 補登上個月的入職
+- **WHEN** 設計部 2026/09 快照為 18 且尚未鎖定、沒有人工調整,HR 在 11/03 補登一位 2026/09/25 到職的設計部員工
+- **THEN** 11/03 之後的名冊同步以 10/01 名冊把設計部 2026/09 快照更新為 19,操作紀錄有一筆 18 → 19
+
+#### Scenario: 規則變更後未鎖定快照依新規則更新
+- **WHEN** 設計部 2026/09 快照依舊規則(9/1 名冊、排除非正職)為 20、未鎖定、沒有人工調整,2026/10/01 名冊中設計部在職 22 人
+- **THEN** 下一次名冊同步把快照更新為 22,操作紀錄有一筆 20 → 22;已鎖定的快照不變
+
+#### Scenario: 已人工調整不覆寫
+- **WHEN** 管理者已把研發部 2026/10 快照由 20 調整為 21,之後名冊同步算出 20
+- **THEN** 快照維持 21
+
+#### Scenario: 各組人數計入部
+- **WHEN** 2026/11/01 研發部本身掛 1 位、前端組 8 位、後端組 11 位在職人員(兩組都屬研發部)
+- **THEN** 研發部 2026/10 快照人數為 20
+
+### Requirement: 快照人員名單
+管理者與系統管理員 SHALL 能在後台設定頁的人數快照中,展開每個部門某月的基準日名單(標示基準日,例如 2026/09 的「2026/10/01 名單」),看出快照人數由哪些人組成。名單每列顯示員工編號、姓名與名單狀態:
+
+- 「計入」:基準日在職,計入快照人數。
+- 「不計入(留停)」:基準日 HR 狀態為留停。
+- 「不計入(離職)」:基準日已離職,且離職生效日在基準日的上個月 1 日(含)之後。更早離職的人不列出。
+- 「不計入」:只出現在依舊規則(排除非正職)保存、之後未再更新的名單。MUST NOT 顯示原因。
+
+規則如下:
+
+- 「計入」的人數 MUST 等於快照的計算人數。人工調整後的人數另以調整紀錄說明。
+- 由 HR 名冊產生的快照,名單 SHALL 在名冊同步更新快照時一併保存。
+ - 部門歸屬與人數相同:依基準日所屬單位歸到部門。
+ - 留停或離職者在基準日名冊沒有所屬單位時,以上個月快照名單中的部門歸屬;仍找不到時不列出。
+- 名單與快照人數一起更新:快照已鎖定或有人工調整時,名單 MUST NOT 變動。
+- 本系統計算的快照(沒有 HR 名冊資料的部門),名單 SHALL 列出依部門歷程在基準日隸屬該部門的成員,全部為「計入」。不提供離職/留停原因。
+- 建立於名單功能上線前、之後也未再更新的 HR 快照,SHALL 顯示「此快照沒有名單紀錄」。
+- 名單 MUST NOT 出現在部門主管或員工可見的任何頁面或匯出。
+
+#### Scenario: 展開名單看到計入與不計入
+- **WHEN** 2026/10/01 HR 名冊中設計部有 20 位在職正職、1 位工讀生、1 位留停,另有 1 位 09/30 離職(離職生效日 10/01),管理者在 2026/09 的人數快照展開設計部
+- **THEN** 名單標示「2026/10/01 名單」,列出 21 位「計入」(含工讀生)、1 位「不計入(留停)」、1 位「不計入(離職)」,快照人數為 21
+
+#### Scenario: 早已離職的人不列出
+- **WHEN** 某人 2026/08/15 已離職,管理者展開 2026/09 設計部名單(基準日 2026/10/01)
+- **THEN** 名單沒有這個人
+
+#### Scenario: 鎖定後名單不變
+- **WHEN** 研發部 2026/10 月結已提交(快照鎖定),之後 HR 補登一位 10 月留停的研發部員工
+- **THEN** 2026/10 研發部的名單與人數都維持鎖定時的內容
+
+#### Scenario: 本系統計算的部門
+- **WHEN** 管理者展開一個沒有部門代碼、由本系統計算人數的部門
+- **THEN** 名單列出基準日隸屬該部門的成員,全部為「計入」,沒有離職或留停原因
+
+#### Scenario: 主管看不到名單
+- **WHEN** 部門主管直接請求後台設定頁的人數快照或其名單
+- **THEN** 系統拒絕存取
+
+#### Scenario: 舊規則的鎖定名單
+- **WHEN** 設計部 2026/08 快照在規則變更前已鎖定,名單有 2 位「不計入」
+- **THEN** 名單與人數維持原樣,「不計入」照舊不寫原因
diff --git a/openspec/changes/rebase-headcount-snapshot/specs/hr-sync/spec.md b/openspec/changes/rebase-headcount-snapshot/specs/hr-sync/spec.md
new file mode 100644
index 0000000..6c063c4
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/specs/hr-sync/spec.md
@@ -0,0 +1,24 @@
+## MODIFIED Requirements
+
+### Requirement: 以 HR 為準覆寫部門歸屬
+同步得到的所屬部門(依「HR 部門對應與自動建立」由 HR 所屬單位歸到的部)與系統紀錄不同時,系統 SHALL 以 HR 為準改變登入者的部門,並記錄調部門紀錄(供人數快照與申請歸屬使用)。同一部門內換單位(例如同一部內換組)MUST NOT 視為調部門。調部門紀錄的生效日 SHALL 取 HR 異動事件中最近一筆「由其他部門轉入新部門」的調動(`hr.employee.transferred`,前後單位各自歸到的部門不同)的生效日;查不到該事件、或生效日早於系統中此人最後一筆部門紀錄、或晚於當日時,以同步當日(Asia/Taipei)為生效日。既有申請的歸屬部門 MUST NOT 因調部門而改變。HR 回報登入者非在職(狀態不是 ACTIVE)或沒有組織歸屬時,或本次同步沒有取得 HR 組織結構而無法判斷所屬部門時,系統 MUST NOT 改變其部門。
+
+#### Scenario: HR 調部門
+- **WHEN** 王小明在系統中屬設計部,10/15 登入時 HR 所屬單位為研發部底下的前端組,HR 異動事件沒有這次調動
+- **THEN** 王小明改屬研發部,調部門自 10/15 起生效,他已建立的申請仍歸屬設計部
+
+#### Scenario: 以 HR 生效日記錄調部門
+- **WHEN** 王小明 9/15 由設計部調至研發部(HR 異動事件生效日 2026/09/15),10/03 才登入本系統
+- **THEN** 調部門自 2026/09/15 起生效,他之後補申請刷卡日期 2026/08/20 的訂閱時歸屬設計部(基準日 2026/09/01 的部門),刷卡日期 2026/09/20 的則歸屬研發部(基準日 2026/10/01 的部門)
+
+#### Scenario: 無組織歸屬
+- **WHEN** 登入者的 HR 狀態為 SUSPENDED,組織歸屬為空
+- **THEN** 系統不改變其部門,照常完成登入
+
+#### Scenario: 部內換組
+- **WHEN** 王小明屬研發部,HR 把他由前端組調到後端組(同屬研發部)
+- **THEN** 王小明仍屬研發部,系統不新增調部門紀錄
+
+#### Scenario: 組織結構查詢失敗
+- **WHEN** 王小明登入時 HR 組織結構查詢失敗,本人組織歸屬查詢成功
+- **THEN** 系統不改變其部門,照常完成登入並記錄同步失敗
diff --git a/openspec/changes/rebase-headcount-snapshot/specs/subsidy-application/spec.md b/openspec/changes/rebase-headcount-snapshot/specs/subsidy-application/spec.md
new file mode 100644
index 0000000..bb9e990
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/specs/subsidy-application/spec.md
@@ -0,0 +1,59 @@
+## MODIFIED Requirements
+
+### Requirement: 申請人資訊自動帶入
+系統 SHALL 在新增申請時以登入帳號自動帶入申請人姓名與歸屬部門,兩者 MUST 為唯讀,員工不得修改(規格 §9、介面規劃 §3.1)。歸屬部門 SHALL 為申請人在刷卡月份**下個月 1 日** 00:00(Asia/Taipei)時所屬的部門,與該月人數快照的基準日一致(使用者決定 2026-10-30);申請人當時不屬於任何部門(例如刷卡月份月底離職)時,改用刷卡日當天所屬的部門,仍沒有則用目前的部門。(刷卡月份當月不能送出申請,見「申請期限」,所以送出時基準日一定已到;草稿在基準日前以目前所屬的部門顯示。)尚未填刷卡日期時顯示目前的部門。可編輯的申請(草稿、待補件)變更刷卡日期時 SHALL 重新判斷歸屬部門;歸屬部門 MUST NOT 因送出後的調部門而改變。
+
+#### Scenario: 開啟新增申請頁
+- **WHEN** 員工王小明(設計部)開啟新增申請頁
+- **THEN** 申請人欄位顯示「王小明」、部門欄位顯示「設計部」,且兩者皆不可編輯
+
+#### Scenario: 竄改申請人資料的請求
+- **WHEN** 送出的申請資料中夾帶不同於登入者的申請人或部門
+- **THEN** 系統忽略該值,以登入帳號與基準日的所屬部門建立申請
+
+#### Scenario: 調部門後補申請調動前的月份
+- **WHEN** 王小明 2026/09/15 由設計部調至研發部,2026/10/05 新增一筆刷卡日期 2026/09/20 的申請
+- **THEN** 部門欄位顯示「研發部」(2026/10/01 所屬部門),送出後由研發部主管審核並計入研發部 2026/09 月結;他也計入研發部 2026/09 快照
+
+#### Scenario: 調部門後申請調動後的月份
+- **WHEN** 同上,王小明新增一筆刷卡日期 2026/10/02 的申請
+- **THEN** 部門欄位顯示「研發部」,申請歸屬研發部 2026/10
+
+#### Scenario: 月中到職
+- **WHEN** 陳小華 2026/09/10 到職加入設計部,2026/10/03 申請刷卡日期 2026/09/12 的訂閱
+- **THEN** 申請歸屬 10/01 所屬的設計部,她也計入設計部 2026/09 快照
+
+#### Scenario: 刷卡月份月底離職
+- **WHEN** 林小美 2026/09/30 後離職(10/01 不屬於任何部門),帳號仍可登入時於 10/01 送出刷卡日期 2026/09/05 的申請
+- **THEN** 申請歸屬刷卡日當天的部門
+
+#### Scenario: 草稿改刷卡日期
+- **WHEN** 王小明(2026/09/15 由設計部調至研發部)的草稿刷卡日期由 2026/10/02 改為 2026/08/20 並儲存
+- **THEN** 部門欄位改為「設計部」(2026/09/01 所屬部門),草稿的歸屬部門同步改為設計部
+
+#### Scenario: 送出後申請人調部門
+- **WHEN** 王小明 2026/11/03 以設計部身分送出刷卡日期 2026/10/05 的申請後,於 2026/11/20 被調至研發部
+- **THEN** 該申請的部門仍記為「設計部」,並計入設計部該月份的審核與月結,不隨人員調部門而移動
+
+### Requirement: 申請期限
+刷卡月份 M 的申請 SHALL 只能在 M 的下個月 1 日 00:00 起、到 M 的次月 20 日 23:59:59(Asia/Taipei,截止日取自後台截止日參數)之間送出(使用者決定 2026-10-30:員工不得申請當月補助,例如 10 月只能申請 9 月)。期限開始前 MUST 拒絕送出,期限後 MUST 拒絕送出與補件重送,且不提供逾期例外補登。草稿不受期限限制。期限(開始與截止)需在表單摘要中顯示。
+
+#### Scenario: 期限內送出
+- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/20 23:59:00 送出
+- **THEN** 系統接受送出
+
+#### Scenario: 當月不能送出
+- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/10/28 送出
+- **THEN** 系統拒絕送出,並顯示「此筆刷卡日期屬於 2026/10,2026/11/01 起才能送出。」;可以儲存草稿
+
+#### Scenario: 下個月 1 日起可送出
+- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/01 00:00:01 送出
+- **THEN** 系統接受送出
+
+#### Scenario: 逾期送出
+- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/21 00:00:01 送出
+- **THEN** 系統拒絕送出,並顯示「此筆刷卡日期屬於 2026/10,申請期限已於 2026/11/20 截止。」
+
+#### Scenario: 逾期案件仍可存草稿
+- **WHEN** 員工對已逾期月份的申請點擊「儲存草稿」
+- **THEN** 系統可儲存草稿,但頁面明確提示該筆已逾期、無法送出
diff --git a/openspec/changes/rebase-headcount-snapshot/tasks.md b/openspec/changes/rebase-headcount-snapshot/tasks.md
new file mode 100644
index 0000000..a2eb7fa
--- /dev/null
+++ b/openspec/changes/rebase-headcount-snapshot/tasks.md
@@ -0,0 +1,25 @@
+## 1. 基準日
+
+- [x] 1.1 `src/domain/` 新增 `snapshotBaseDate(month)`(下個月 1 日,跨年)與基準日已到的判斷;單元測試含 12 月 → 隔年 1/1。
+- [x] 1.2 `attributedDepartment` 改用基準日(退路不變);`attribution.test.ts` 與申請服務測試更新:9/15 調部門後 9 月刷卡歸新部門、8 月刷卡歸舊部門、月底離職退回刷卡日部門。
+- [x] 1.3 申請開始日:`deriveDeadlines` 回傳開始日(基準日 00:00);送出在開始日前被拒(訊息「此筆刷卡日期屬於 YYYY/MM,YYYY/MM/01 起才能送出。」),草稿可存;表單摘要顯示可送出期間、開始日前停用「送出」。服務與表單測試涵蓋 10/28 送 10 月被拒、11/01 可送。
+
+## 2. 人數快照
+
+- [x] 2.1 `headcount.ts`:`localMembers` / `localHeadcount`、`ensureMonthSnapshots` 用基準日;基準日前不建立並回傳「YYYY/MM/01 名冊確定後計算」;`getDepartmentCap` 基準日未到時回傳同一句。不再依正職排除(`fullTimeOn` / `hasEmploymentData` 不再使用)。
+- [x] 2.2 `syncSnapshotsFromHr`:基準日名冊在職者一律計入;離職名單截止日為刷卡月份 1 日;更新文件註解。
+- [x] 2.3 `roster.ts`:本月 1 日名冊 → 上個刷卡月份、上月 1 日名冊 → 上上個刷卡月份(先早後晚)。
+- [x] 2.4 啟動步驟 `rebaseHeadcountSnapshots`(`_meta` 旗標只跑一次):刪除基準日未到、未鎖定、未調整的快照與名單,寫 `headcount.snapshot_removed`(加入 `AUDIT_ACTIONS`)。
+- [x] 2.5 更新 `headcount*.test.ts`、`roster*.test.ts`、相關 settlement/review/dashboard 測試的快照月份與基準日;新增:基準日前不建立、工讀生計入、9/30 離職不計入 9 月、名冊同步月份對應、啟動清除只跑一次且不動鎖定或調整的快照。`npm test` 通過。
+
+## 3. 畫面與文件
+
+- [x] 3.1 審核頁額度試算、首頁 `QuotaCard`、月結頁遇到基準日未到時顯示「YYYY/MM/01 名冊確定後計算」;設定頁人數快照顯示基準日(「2026/10/01 名單」)、說明改為「在職人員」、基準日前不提供建立。
+- [x] 3.3 首頁員工與主管的額度卡改顯示上個刷卡月份(`quotaMonth`),標題標示該月份;`queries.test.ts` 涵蓋。
+- [x] 3.2 `/help` 與 CLAUDE.md(Applications 歸屬、Rule parameters & headcount、HR Sync snapshot/full-time、Department settlement)更新。
+
+## 4. 驗證
+
+- [x] 4.0 e2e 送出流程:表單送出改用前一個月的刷卡日期(`claimDate()`);新增 `pin-clock` setup project(含 teardown),在所有一般 e2e 前把系統時間固定在本月 10 日、結束後清除(實作時改為全體固定,取代只移出送出類 spec 的做法:審核、月結測試也依賴上個月的截止尚未到);CLAUDE.md 的 e2e 說明同步更新。
+- [ ] 4.1 e2e:依「本月快照」的測試改用基準日已到的月份(`monthsAgo(1)` 以前),設定頁人數快照顯示基準日;受影響的 spec(settings、review、settlement、company-settlement、dashboard、visibility)通過。
+- [ ] 4.2 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過。
diff --git a/playwright.config.ts b/playwright.config.ts
index 4273c49..6dc62fa 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -12,11 +12,15 @@ export default defineConfig({
trace: "on-first-retry",
},
// 無法下載 Playwright 內建瀏覽器時,可設 PLAYWRIGHT_CHANNEL=chrome(或 msedge)改用本機已安裝的瀏覽器。
- // 系統時間(clock.spec)會影響全站:其他測試跑完後才單獨執行。
+ // 系統時間會影響全站:一般測試前先固定在本月 10 日(pin-clock,申請可送出期間為次月 1–20 日),
+ // 跑完清除;clock.spec 在其他測試都跑完後才單獨執行。
projects: [
+ { name: "pin-clock", testMatch: /pin-clock\.setup\.ts$/, teardown: "unpin-clock" },
+ { name: "unpin-clock", testMatch: /pin-clock\.teardown\.ts$/ },
{
name: "chromium",
testIgnore: /clock\.spec\.ts$/,
+ dependencies: ["pin-clock"],
use: { ...devices["Desktop Chrome"], channel: process.env.PLAYWRIGHT_CHANNEL || undefined },
},
{
diff --git a/src/app/(app)/admin/settings/page.tsx b/src/app/(app)/admin/settings/page.tsx
index 1cbde5b..432317d 100644
--- a/src/app/(app)/admin/settings/page.tsx
+++ b/src/app/(app)/admin/settings/page.tsx
@@ -1,6 +1,11 @@
import Link from "next/link";
import { instantToLocalDateTime, localDate } from "@/domain/calendar";
-import { monthStart, nextMonth } from "@/domain/deadlines";
+import {
+ baseDateReached,
+ capPendingMessage,
+ nextMonth,
+ snapshotBaseDate,
+} from "@/domain/deadlines";
import { Card, PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { DataTable } from "@/components/ui/data-table";
@@ -8,7 +13,7 @@ import { inputClass } from "@/components/ui/field";
import { MoneyDisplay } from "@/components/ui/money-display";
import { ToneBadge } from "@/components/ui/status-badge";
import { DEPARTMENT_TYPE_LABELS } from "@/lib/department-types";
-import { formatDateTime, formatMonth } from "@/lib/format";
+import { formatDate, formatDateTime, formatMonth } from "@/lib/format";
import {
ATTACHMENT_FORMAT_LABELS,
ROUNDING_LABELS,
@@ -290,8 +295,10 @@ async function HeadcountTab({
user: { id: number; employeeNo: string; name: string | null };
}) {
const db = getDb();
- const started = now.getTime() >= monthStart(month, timeZone).getTime();
- // 懶建立:月份已開始時,首次開啟就以 1 日 00:00 的部門成員建立快照。
+ // 基準日:刷卡月份的下個月 1 日(rebase-headcount-snapshot)。
+ const started = baseDateReached(month, now, timeZone);
+ const baseDate = formatDate(snapshotBaseDate(month));
+ // 懶建立:基準日已到時,首次開啟就以基準日 00:00 的部門成員建立快照。
if (started) ensureMonthSnapshots(db, await auditContextFor(user), month, timeZone);
const rows = listMonthSnapshots(db, month, timeZone);
const missing = rows.some((r) => r.snapshotId === null);
@@ -329,13 +336,15 @@ async function HeadcountTab({
roster.lastSuccess ? formatDateTime(roster.lastSuccess.startedAt, timeZone) : "尚無"
}`}
。每天第一位以公司帳號登入的人會觸發同步;需要當天再同步時按「下次登入時重新同步名冊」。快照人數依
- HR 該月 1 日名冊的在職正職人員計算;展開「1 日名單」可看到計入與因留停、離職不計入的人。
+ HR 刷卡月份下個月 1
+ 日(基準日)名冊的在職人員計算,暫不區分正職;展開名單可看到計入與因留停、離職不計入的人。