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 + 日(基準日)名冊的在職人員計算,暫不區分正職;展開名單可看到計入與因留停、離職不計入的人。

)} {!started && (
- {formatMonth(month)} 尚未開始;快照會在該月 1 日之後以當日 00:00 的部門成員建立。 + {formatMonth(month)} 的人數快照以 {baseDate} 名冊計算({capPendingMessage(month)} + );之後會以當日 00:00 的部門成員建立。
)} @@ -380,7 +389,7 @@ async function HeadcountTab({ }, { key: "members", - header: "1 日名單", + header: `${baseDate} 名單`, render: (r) => r.snapshotId === null ? null : ( diff --git a/src/app/(app)/admin/settings/snapshot-members.tsx b/src/app/(app)/admin/settings/snapshot-members.tsx index 5469854..2c04174 100644 --- a/src/app/(app)/admin/settings/snapshot-members.tsx +++ b/src/app/(app)/admin/settings/snapshot-members.tsx @@ -1,8 +1,8 @@ import type { SnapshotMember, SnapshotMemberStatus } from "@/server/rules/headcount"; /** - * 名單狀態的文字(headcount-snapshot「快照人員名單」)。非正職只寫「不計入」不寫原因: - * 逐人正職身分不公開(identity-access「資料範圍控制」)。 + * 名單狀態的文字(headcount-snapshot「快照人員名單」)。「不計入」只出現在排除非正職的舊名單 + * (rebase-headcount-snapshot 之前),不寫原因:逐人正職身分不公開(identity-access「資料範圍控制」)。 */ export const SNAPSHOT_MEMBER_LABELS: Record = { counted: "計入", @@ -13,7 +13,7 @@ export const SNAPSHOT_MEMBER_LABELS: Record = { const ORDER: SnapshotMemberStatus[] = ["counted", "suspended", "offboarded", "excluded"]; -/** 人數快照的 1 日名單(展開)。`members` 為 null 表示沒有名單紀錄。 */ +/** 人數快照的基準日名單(展開)。`members` 為 null 表示沒有名單紀錄。 */ export function SnapshotMembers({ departmentName, members, @@ -34,7 +34,7 @@ export function SnapshotMembers({ 名單({counts.map((c) => `${SNAPSHOT_MEMBER_LABELS[c.status]} ${c.n}`).join("・")}) {members.length === 0 ? ( -

1 日沒有成員。

+

基準日沒有成員。

) : (
    {members.map((m) => ( diff --git a/src/app/(app)/applications/application-form.tsx b/src/app/(app)/applications/application-form.tsx index 54c9fdf..c3db796 100644 --- a/src/app/(app)/applications/application-form.tsx +++ b/src/app/(app)/applications/application-form.tsx @@ -21,7 +21,13 @@ import { FileUploader, type UploadedFile } from "@/components/ui/file-uploader"; import { MoneyDisplay } from "@/components/ui/money-display"; import { PlatformIcon } from "@/components/ui/platform-icon"; import { useToast } from "@/components/ui/toast"; -import { applicationMonth, isPastDeadline, submissionDeadline } from "@/domain/application"; +import { + applicationMonth, + isBeforeSubmissionStart, + isPastDeadline, + submissionDeadline, + submissionOpensAt, +} from "@/domain/application"; import { attributedDepartment, type DepartmentHistoryEntry } from "@/domain/attribution"; import { localDate } from "@/domain/calendar"; import { @@ -162,6 +168,9 @@ export function ApplicationForm(props: ApplicationFormProps) { ? submissionDeadline(values.cardDate, rule.employeeDeadlineDay, timeZone) : null; const overdue = deadline !== null && isPastDeadline(deadline, new Date(props.now)); + // 不得申請當月補助:刷卡月份的下個月 1 日起才能送出(草稿可存)。 + const opensAt = validDate ? submissionOpensAt(values.cardDate, timeZone) : null; + const notYetOpen = opensAt !== null && isBeforeSubmissionStart(opensAt, new Date(props.now)); const twd = /^\d+$/.test(values.twdAmount.trim()) ? Number(values.twdAmount.trim()) : null; const departmentId = attributedDepartment( props.applicant.departmentHistory, @@ -237,8 +246,12 @@ export function ApplicationForm(props: ApplicationFormProps) { } /> @@ -290,6 +303,14 @@ export function ApplicationForm(props: ApplicationFormProps) { {state.status === "error" && state.message && ( {state.message} )} + {notYetOpen && month && opensAt && ( +
    + + 此筆刷卡日期屬於 {formatMonth(month)},{formatDate(localDate(opensAt, timeZone))}{" "} + 起才能送出(不得申請當月補助)。可以先儲存草稿。 + +
    + )} {overdue && month && deadline && ( 此筆刷卡日期屬於 {formatMonth(month)},申請期限已於{" "} @@ -568,7 +589,13 @@ export function ApplicationForm(props: ApplicationFormProps) { > 儲存草稿 - diff --git a/src/app/(app)/dashboard/employee-section.tsx b/src/app/(app)/dashboard/employee-section.tsx index 963db7b..617cb2e 100644 --- a/src/app/(app)/dashboard/employee-section.tsx +++ b/src/app/(app)/dashboard/employee-section.tsx @@ -88,7 +88,7 @@ export function EmployeeSection({ data, timeZone }: { data: EmployeeDashboard; t
    {data.quota ? ( diff --git a/src/app/(app)/dashboard/manager-section.tsx b/src/app/(app)/dashboard/manager-section.tsx index feed183..b266d58 100644 --- a/src/app/(app)/dashboard/manager-section.tsx +++ b/src/app/(app)/dashboard/manager-section.tsx @@ -60,7 +60,7 @@ export function ManagerSection({ data, timeZone }: { data: ManagerDashboard; tim

    diff --git a/src/app/(app)/help/page.tsx b/src/app/(app)/help/page.tsx index 0baeaaa..ab10f61 100644 --- a/src/app/(app)/help/page.tsx +++ b/src/app/(app)/help/page.tsx @@ -50,15 +50,16 @@ export default async function HelpPage() { 元捨去)後加總,以刷卡帳單上的台幣金額為準。
  • - 每個部門每月有補助上限(依當月人數快照計算,研發部額度較高),未用完的額度不會累積到下個月。 + 每個部門每月有補助上限(依人數快照計算,研發部額度較高),未用完的額度不會累積到下個月。人數快照以刷卡月份的下個月 + 1 日名冊上在職的人計算,例如 9 月的額度看 10/1 的名冊,9/30 前離職的人不計入。
  • 部門當月每人上限的合計超過部門月上限時,由申請人平分月上限(每人不超過自己的 50% 上限),合計不會超過上限。
  • - 申請歸屬刷卡月份 1 - 日時你所屬的部門;調部門後補申請調動前月份的訂閱,仍由原部門審核與月結。 + 申請歸屬刷卡月份的下個月 1 日你所屬的部門(與人數快照同一天),例如 9/15 調部門,9 + 月刷卡的申請歸新部門審核與月結。
  • 可以申請不代表一定獲得補助;實際補助金額於月結後確認。 @@ -69,6 +70,10 @@ export default async function HelpPage() {
    • 申請月份依「刷卡日期」決定,與發票日期、服務期間或送出日期無關。
    • +
    • + 不能申請當月補助:刷卡月份的次月 1 日起才能送出,例如 10 月申請 9 月的補助,11 + 月隨薪資發放。草稿可以先存。 +
    • 員工須在刷卡月份的次月 20 日前送出申請;部長須在次月 25 日前提交月結(實際日期以系統設定為準)。 @@ -89,7 +94,7 @@ export default async function HelpPage() {
    • 支付金額=同一人當月已通過申請的台幣金額合計(多筆加總)。
    • 個人上限=同一人當月每筆已通過申請台幣金額的 50%(不足 1 元捨去)加總。
    • - 部門月上限=當月人數快照 × + 部門月上限=人數快照(刷卡月份下個月 1 日名冊上在職的人)× 部門類型每人額度。個人上限合計未超過月上限時,每人照個人上限發放。
    • diff --git a/src/components/ui/quota-card.tsx b/src/components/ui/quota-card.tsx index 5984d54..f294d27 100644 --- a/src/components/ui/quota-card.tsx +++ b/src/components/ui/quota-card.tsx @@ -87,7 +87,7 @@ export function QuotaCard({ )} ) : ( -

      本月額度尚未設定

      +

      {quota.message ?? "本月額度尚未設定"}

      )}

      {QUOTA_REFERENCE_NOTE}

      diff --git a/src/domain/application.ts b/src/domain/application.ts index b29d4b0..184e5c9 100644 --- a/src/domain/application.ts +++ b/src/domain/application.ts @@ -1,4 +1,4 @@ -import { cardMonth, deadlinesFor } from "./deadlines"; +import { cardMonth, deadlinesFor, submissionStart } from "./deadlines"; /** 申請月份(`YYYY-MM`):只由刷卡日期決定(規格 §6),不看 Invoice 日期、服務期間或送出日期。 */ export function applicationMonth(cardDate: string): string { @@ -15,6 +15,16 @@ export function submissionDeadline(cardDate: string, deadlineDay: number, timeZo ).employee; } +/** 申請開始:刷卡月份的下個月 1 日 00:00(指定時區);之前不能送出(不得申請當月補助)。 */ +export function submissionOpensAt(cardDate: string, timeZone: string): Date { + return submissionStart(cardMonth(cardDate), timeZone); +} + +/** 是否尚未到申請開始時刻。 */ +export function isBeforeSubmissionStart(start: Date, now: Date): boolean { + return now.getTime() < start.getTime(); +} + /** 是否已超過期限(期限當秒仍可送出)。 */ export function isPastDeadline(deadline: Date, now: Date): boolean { return now.getTime() > deadline.getTime(); diff --git a/src/domain/attribution.test.ts b/src/domain/attribution.test.ts index de838bf..87adeec 100644 --- a/src/domain/attribution.test.ts +++ b/src/domain/attribution.test.ts @@ -11,22 +11,36 @@ describe("attributedDepartment", () => { { departmentId: RND, effectiveFrom: "2026-09-15" }, ]; - it("調部門後補申請調動前的月份:歸屬刷卡月份 1 日的原部門", () => { - expect(attributedDepartment(transferred, "2026-09-20", RND)).toBe(DESIGN); + // 基準日是刷卡月份的下個月 1 日(rebase-headcount-snapshot)。 + it("調動當月的刷卡歸屬新部門(基準日 10/01 已在研發部)", () => { + expect(attributedDepartment(transferred, "2026-09-20", RND)).toBe(RND); + expect(attributedDepartment(transferred, "2026-09-02", RND)).toBe(RND); + }); + + it("調動前一個月的刷卡歸屬原部門(基準日 09/01 仍在設計部)", () => { + expect(attributedDepartment(transferred, "2026-08-20", RND)).toBe(DESIGN); }); it("調動後的月份歸屬新部門", () => { expect(attributedDepartment(transferred, "2026-10-02", RND)).toBe(RND); }); - it("月中到職:1 日還沒有部門,改用刷卡日當天的部門", () => { + it("月中到職:基準日(下個月 1 日)已在部門", () => { const joined = [{ departmentId: DESIGN, effectiveFrom: "2026-09-10" }]; - expect(attributedDepartment(joined, "2026-09-12", DESIGN)).toBe(DESIGN); + expect(attributedDepartment(joined, "2026-09-12", RND)).toBe(DESIGN); }); - it("刷卡日也還沒有部門時用目前的部門", () => { - const joined = [{ departmentId: DESIGN, effectiveFrom: "2026-09-10" }]; - expect(attributedDepartment(joined, "2026-09-05", RND)).toBe(RND); + it("刷卡月份月底離職:基準日沒有部門,改用刷卡日當天的部門", () => { + const left = [ + { departmentId: DESIGN, effectiveFrom: "2026-01-01" }, + { departmentId: null, effectiveFrom: "2026-10-01" }, + ]; + expect(attributedDepartment(left, "2026-09-05", RND)).toBe(DESIGN); + }); + + it("基準日與刷卡日都沒有部門時用目前的部門", () => { + const history = [{ departmentId: null, effectiveFrom: "2026-01-01" }]; + expect(attributedDepartment(history, "2026-09-05", RND)).toBe(RND); }); it("沒有部門歷程或沒填刷卡日期時用目前的部門", () => { @@ -35,13 +49,13 @@ describe("attributedDepartment", () => { expect(attributedDepartment(transferred, "2026-09", RND)).toBe(RND); }); - it("1 日當天曾被移出部門(null)時改看刷卡日", () => { + it("基準日當天曾被移出部門(null)時改看刷卡日", () => { const history = [ { departmentId: DESIGN, effectiveFrom: "2026-01-01" }, + { departmentId: RND, effectiveFrom: "2026-08-03" }, { departmentId: null, effectiveFrom: "2026-08-20" }, - { departmentId: RND, effectiveFrom: "2026-09-03" }, ]; - expect(attributedDepartment(history, "2026-09-10", null)).toBe(RND); + expect(attributedDepartment(history, "2026-08-10", null)).toBe(RND); }); }); diff --git a/src/domain/attribution.ts b/src/domain/attribution.ts index 8ed9c96..d58e4af 100644 --- a/src/domain/attribution.ts +++ b/src/domain/attribution.ts @@ -1,5 +1,7 @@ +import { snapshotBaseDate } from "./deadlines"; + // 申請的歸屬部門(subsidy-application「申請人資訊自動帶入」):與人數快照同一個基準日, -// 也就是刷卡月份 1 日 00:00(Asia/Taipei)時所屬的部門。 +// 也就是刷卡月份的下個月 1 日 00:00(Asia/Taipei)時所屬的部門(rebase-headcount-snapshot)。 /** 一筆部門歷程:自 `effectiveFrom`(`YYYY-MM-DD`)起屬於 `departmentId`(null 為沒有部門)。 */ export interface DepartmentHistoryEntry { @@ -24,8 +26,9 @@ export function departmentOn( } /** - * 申請的歸屬部門:刷卡月份 1 日所屬的部門;當天不屬於任何部門(例如月中到職)時用刷卡日當天的部門, - * 仍沒有則用目前的部門。還沒填刷卡日期時也用目前的部門。 + * 申請的歸屬部門:基準日(刷卡月份的下個月 1 日)所屬的部門;當天不屬於任何部門(例如刷卡月份 + * 月底離職)時用刷卡日當天的部門,仍沒有則用目前的部門。還沒填刷卡日期時也用目前的部門。 + * 基準日還沒到(草稿)時,歷程取到今天為止,也就是目前所屬的部門。 */ export function attributedDepartment( history: readonly DepartmentHistoryEntry[], @@ -34,7 +37,7 @@ export function attributedDepartment( ): number | null { if (!cardDate || !/^\d{4}-\d{2}-\d{2}$/.test(cardDate)) return currentDepartmentId; return ( - departmentOn(history, `${cardDate.slice(0, 7)}-01`) ?? + departmentOn(history, snapshotBaseDate(cardDate.slice(0, 7))) ?? departmentOn(history, cardDate) ?? currentDepartmentId ); diff --git a/src/domain/dashboard.ts b/src/domain/dashboard.ts index d757267..2193173 100644 --- a/src/domain/dashboard.ts +++ b/src/domain/dashboard.ts @@ -50,7 +50,7 @@ export function daysUntil(from: string, to: string): number { } export type QuotaReference = - | { configured: false } + | { configured: false; message?: string } | { configured: true; approvedTotal: number; diff --git a/src/domain/deadlines.test.ts b/src/domain/deadlines.test.ts index 94ca440..b20d0e9 100644 --- a/src/domain/deadlines.test.ts +++ b/src/domain/deadlines.test.ts @@ -1,5 +1,14 @@ import { describe, expect, it } from "vitest"; -import { cardMonth, deadlinesFor, monthEnd, monthStart, nextMonth } from "./deadlines"; +import { + baseDateReached, + cardMonth, + deadlinesFor, + monthEnd, + monthStart, + nextMonth, + snapshotBaseDate, + submissionStart, +} from "./deadlines"; const TZ = "Asia/Taipei"; const days = { employeeDeadlineDay: 20, managerDeadlineDay: 25 }; @@ -36,3 +45,25 @@ describe("月份邊界", () => { expect(monthEnd("2026-11", TZ).toISOString()).toBe("2026-11-30T15:59:59.999Z"); }); }); + +describe("人數快照基準日與申請開始(rebase-headcount-snapshot)", () => { + it("基準日為刷卡月份的下個月 1 日,跨年", () => { + expect(snapshotBaseDate("2026-09")).toBe("2026-10-01"); + expect(snapshotBaseDate("2026-12")).toBe("2027-01-01"); + }); + + it("申請開始為基準日 00:00(台北);基準日當刻起算已到", () => { + expect(submissionStart("2026-10", "Asia/Taipei").toISOString()).toBe( + "2026-10-31T16:00:00.000Z", + ); + expect(deadlinesFor("2026-10-05", days, "Asia/Taipei").start.toISOString()).toBe( + "2026-10-31T16:00:00.000Z", + ); + expect(baseDateReached("2026-10", new Date("2026-10-31T15:59:59.999Z"), "Asia/Taipei")).toBe( + false, + ); + expect(baseDateReached("2026-10", new Date("2026-10-31T16:00:00.000Z"), "Asia/Taipei")).toBe( + true, + ); + }); +}); diff --git a/src/domain/deadlines.ts b/src/domain/deadlines.ts index 30546b6..a5d7172 100644 --- a/src/domain/deadlines.ts +++ b/src/domain/deadlines.ts @@ -23,6 +23,29 @@ export function monthStart(month: string, timeZone: string): Date { return startOfLocalDay(`${month}-01`, timeZone); } +/** + * 人數快照與申請歸屬的基準日(rebase-headcount-snapshot,使用者決定 2026-10-30):刷卡月份的 + * 下個月 1 日(`YYYY-MM-DD`)。員工在刷卡月份的下個月才申請,基準日前離職的人已無法申請。 + */ +export function snapshotBaseDate(month: string): string { + return `${nextMonth(month)}-01`; +} + +/** 刷卡月份的申請開始時刻(= 基準日 00:00):刷卡月份當月不能送出申請。 */ +export function submissionStart(month: string, timeZone: string): Date { + return monthStart(nextMonth(month), timeZone); +} + +/** 某刷卡月份的基準日 00:00 是否已到(之後才能建立人數快照、計算月上限)。 */ +export function baseDateReached(month: string, now: Date, timeZone: string): boolean { + return now.getTime() >= submissionStart(month, timeZone).getTime(); +} + +/** 基準日未到時的月上限說明,例如「2026/11/01 名冊確定後計算」。 */ +export function capPendingMessage(month: string): string { + return `${snapshotBaseDate(month).replaceAll("-", "/")} 名冊確定後計算`; +} + /** 某月份在指定時區的最後一刻(下個月 1 日 00:00 前 1 毫秒),用於取「該月結束時生效」的參數。 */ export function monthEnd(month: string, timeZone: string): Date { return new Date(monthStart(nextMonth(month), timeZone).getTime() - 1); @@ -34,19 +57,20 @@ function endOfDay(date: string, timeZone: string): Date { } /** - * 截止時刻:員工申請截止為刷卡月份次月「員工截止日」23:59:59,主管月結提交截止為 - * 次月「主管截止日」23:59:59(皆為指定時區)。 + * 期限:員工自刷卡月份次月 1 日 00:00 起可送出(`start`),申請截止為次月「員工截止日」23:59:59, + * 主管月結提交截止為次月「主管截止日」23:59:59(皆為指定時區)。 */ export function deadlinesFor( cardDate: string, days: { employeeDeadlineDay: number; managerDeadlineDay: number }, timeZone: string, -): { month: string; employee: Date; manager: Date } { +): { month: string; start: Date; employee: Date; manager: Date } { const month = cardMonth(cardDate); const due = nextMonth(month); const day = (d: number) => `${due}-${String(d).padStart(2, "0")}`; return { month, + start: submissionStart(month, timeZone), employee: endOfDay(day(days.employeeDeadlineDay), timeZone), manager: endOfDay(day(days.managerDeadlineDay), timeZone), }; diff --git a/src/lib/audit-actions.ts b/src/lib/audit-actions.ts index dc014f9..723e363 100644 --- a/src/lib/audit-actions.ts +++ b/src/lib/audit-actions.ts @@ -37,6 +37,7 @@ export const AUDIT_ACTIONS = { "headcount.snapshot_created": "建立人數快照", "headcount.snapshot_synced": "依 HR 名冊更新快照", "headcount.snapshot_members_updated": "依 HR 名冊更新快照名單", + "headcount.snapshot_removed": "移除人數快照(基準日變更)", "headcount.adjusted": "調整快照人數", "headcount.locked": "鎖定人數快照", "headcount.unlocked": "解除人數快照鎖定", diff --git a/src/server/applications/duplicates.test.ts b/src/server/applications/duplicates.test.ts index f5e145b..2dea879 100644 --- a/src/server/applications/duplicates.test.ts +++ b/src/server/applications/duplicates.test.ts @@ -121,9 +121,9 @@ describe("送出時的疑似重複", () => { it("Invoice 內容相同(雜湊相同)即使欄位不同也警示,原因為 invoice", () => { const a = draft(); expect(submit(a).ok).toBe(true); - const b = draft({ ...COMPLETE_FORM, twdAmount: "500", cardDate: "2026-10-01" }); + const b = draft({ ...COMPLETE_FORM, twdAmount: "500", cardDate: "2026-09-01" }); setHash(b, "invoice", hashOf(a, "invoice")); - const result = submit(b, { ...COMPLETE_FORM, twdAmount: "500", cardDate: "2026-10-01" }); + const result = submit(b, { ...COMPLETE_FORM, twdAmount: "500", cardDate: "2026-09-01" }); expect(!result.ok && result.duplicates?.[0]).toMatchObject({ id: a, reasons: ["invoice"] }); }); @@ -138,7 +138,7 @@ describe("送出時的疑似重複", () => { ...COMPLETE_FORM, platform: "Claude", twdAmount: "3300", - cardDate: "2026-10-01", + cardDate: "2026-09-01", }; const c = draft(other); setHash(c, "card_statement", hashOf(a, "card_statement")); diff --git a/src/server/applications/review.test.ts b/src/server/applications/review.test.ts index 21906b3..e4ab834 100644 --- a/src/server/applications/review.test.ts +++ b/src/server/applications/review.test.ts @@ -189,10 +189,10 @@ describe("審核轉移", () => { }); it("申請截止後不可退回補件,只能核准或不核准;截止前可以退回", () => { - // 刷卡日期 2026/10/05 → 員工申請截止 2026/11/20 23:59(台北) + // 刷卡日期 2026/09/25 → 員工申請截止 2026/10/20 23:59(台北) const before = submittedBy(f.applicant); expect( - reviewApplication(t.db, at("2026-11-20T15:59:00Z"), { + reviewApplication(t.db, at("2026-10-20T15:59:00Z"), { actor: actor(f.designManager), applicationId: before, action: "return", @@ -201,13 +201,13 @@ describe("審核轉移", () => { ).toBe(true); const after = submittedBy(f.colleague); - const blocked = "已過申請截止(2026/11/20),員工無法補件重送,請核准或不核准"; - expect(returnBlockedReason(t.db, "2026-10", new Date("2026-11-21T01:00:00Z"), TZ)).toBe( + const blocked = "已過申請截止(2026/10/20),員工無法補件重送,請核准或不核准"; + expect(returnBlockedReason(t.db, "2026-09", new Date("2026-10-21T01:00:00Z"), TZ)).toBe( blocked, ); - expect(returnBlockedReason(t.db, "2026-10", new Date("2026-11-20T15:59:00Z"), TZ)).toBeNull(); + expect(returnBlockedReason(t.db, "2026-09", new Date("2026-10-20T15:59:00Z"), TZ)).toBeNull(); expect( - reviewApplication(t.db, at("2026-11-21T01:00:00Z"), { + reviewApplication(t.db, at("2026-10-21T01:00:00Z"), { actor: actor(f.designManager), applicationId: after, action: "return", @@ -216,7 +216,7 @@ describe("審核轉移", () => { ).toEqual({ ok: false, error: blocked }); expect(statusOf(after)).toBe("pending_review"); expect( - reviewApplication(t.db, at("2026-11-21T01:00:00Z"), { + reviewApplication(t.db, at("2026-10-21T01:00:00Z"), { actor: actor(f.designManager), applicationId: after, action: "reject", @@ -379,7 +379,7 @@ describe("審核清單", () => { applicantName: "王小明", platform: "ChatGPT", twdAmount: 899, - applicationMonth: "2026-10", + applicationMonth: "2026-09", status: "pending_review", }); expect(queue[0]).not.toHaveProperty("estimate"); @@ -446,7 +446,7 @@ describe("條列檢視的清單資料", () => { expect(row).toMatchObject({ departmentId: f.design, planName: "ChatGPT Plus", - cardDate: "2026-10-05", + cardDate: "2026-09-25", outcome: "完成 10 月份 12 場訪談摘要", foreignAmountCents: 2000, currency: "USD", @@ -471,7 +471,8 @@ describe("條列檢視的清單資料", () => { describe("部門額度試算", () => { const MONTH = "2026-10"; - const audit = at("2026-10-08T00:00:00Z"); + // 10 月刷卡的基準日是 11/01(rebase-headcount-snapshot),11 月才有快照與試算。 + const audit = at("2026-11-08T00:00:00Z"); function caseIn(user: TestUser, amount: number, status: ApplicationStatus, month = MONTH) { const id = insertApplication(t.db, { applicantId: user.id, @@ -619,7 +620,7 @@ describe("部門額度試算", () => { }); }); - it("月份已開始但沒有快照時先建立;尚未開始的月份顯示尚未建立人數快照", () => { + it("基準日已到但沒有快照時先建立;基準日未到的月份顯示名冊確定日", () => { caseIn(f.applicant, 450, "pending_review"); const started = reviewCapPreview(t.db, audit, f.design, MONTH, TZ); expect(started).toMatchObject({ status: "preview" }); @@ -630,13 +631,21 @@ describe("部門額度試算", () => { .all() .some((s) => s.departmentId === f.design), ).toBe(true); - expect(reviewCapPreview(t.db, audit, f.design, "2026-12", TZ)).toEqual({ + caseIn(f.applicant, 450, "pending_review", "2026-11"); + expect(reviewCapPreview(t.db, audit, f.design, "2026-11", TZ)).toEqual({ departmentId: f.design, departmentName: "設計部", - month: "2026-12", + month: "2026-11", status: "no_snapshot", - message: "尚未建立人數快照", + message: "2026/12/01 名冊確定後計算", }); + expect( + t.db + .select() + .from(headcountSnapshots) + .all() + .some((s) => s.month === "2026-11"), + ).toBe(false); }); it("月結已提交:改顯示最終補助", () => { diff --git a/src/server/applications/review.ts b/src/server/applications/review.ts index 1c8d9da..2d7aeab 100644 --- a/src/server/applications/review.ts +++ b/src/server/applications/review.ts @@ -1,6 +1,6 @@ import { and, asc, count, desc, eq, inArray, isNotNull, isNull } from "drizzle-orm"; import { localDate } from "@/domain/calendar"; -import { monthStart } from "@/domain/deadlines"; +import { baseDateReached, capPendingMessage } from "@/domain/deadlines"; import { NO_SNAPSHOT_MESSAGE, calculateSettlement, @@ -266,9 +266,11 @@ export function reviewCapPreview( }; } - if (audit.now.getTime() >= monthStart(month, timeZone).getTime()) { - ensureMonthSnapshots(db, audit, month, timeZone); + // 基準日(刷卡月份的下個月 1 日)前還沒有人數快照,月上限尚未確定。 + if (!baseDateReached(month, audit.now, timeZone)) { + return { ...base, status: "no_snapshot", message: capPendingMessage(month) }; } + ensureMonthSnapshots(db, audit, month, timeZone); const cap = getDepartmentCap(db, departmentId, month, timeZone); if (!cap.ok) return { ...base, status: "no_snapshot", message: NO_SNAPSHOT_MESSAGE }; diff --git a/src/server/applications/service.test.ts b/src/server/applications/service.test.ts index 704e6a2..95416e6 100644 --- a/src/server/applications/service.test.ts +++ b/src/server/applications/service.test.ts @@ -106,18 +106,18 @@ describe("儲存草稿", () => { it("更新草稿:申請月份由刷卡日期重新計算,變更寫入操作紀錄", () => { const id = draft(); - expect(row(id).applicationMonth).toBe("2026-10"); + expect(row(id).applicationMonth).toBe("2026-09"); const result = saveDraft(t.db, at("2026-10-07T03:00:00Z"), { user: { id: f.applicant.id, departmentId: f.design }, applicationId: id, - values: { ...COMPLETE_FORM, cardDate: "2026-09-28" }, + values: { ...COMPLETE_FORM, cardDate: "2026-08-28" }, timeZone: TZ, }); expect(result).toEqual({ ok: true, id }); - expect(row(id).applicationMonth).toBe("2026-09"); + expect(row(id).applicationMonth).toBe("2026-08"); const log = expectAudit(t.db, "application.updated", id); - expect(log.before).toEqual({ cardDate: "2026-10-05" }); - expect(log.after).toEqual({ cardDate: "2026-09-28" }); + expect(log.before).toEqual({ cardDate: "2026-09-25" }); + expect(log.after).toEqual({ cardDate: "2026-08-28" }); }); it("他人的申請:視為不存在", () => { @@ -164,21 +164,41 @@ describe("送出", () => { }); it("期限內(11/20 23:59:00)可送出;逾期(11/21 00:00:01)拒絕並說明", () => { - const late = draft(); + const october = { ...COMPLETE_FORM, cardDate: "2026-10-05" }; + const late = draft(october); attachFiles(t.db, late, f.applicant.id); - expect(submit(late, "2026-11-20T16:00:01Z")).toEqual({ + expect(submit(late, "2026-11-20T16:00:01Z", f.applicant, october)).toEqual({ ok: false, errors: [], message: "此筆刷卡日期屬於 2026/10,申請期限已於 2026/11/20 截止。", }); expect(row(late).status).toBe("draft"); - const onTime = draft(); + const onTime = draft(october); attachFiles(t.db, onTime, f.applicant.id); - expect(submit(onTime, "2026-11-20T15:59:00Z")).toEqual({ ok: true, id: onTime }); + expect(submit(onTime, "2026-11-20T15:59:00Z", f.applicant, october)).toEqual({ + ok: true, + id: onTime, + }); expect(row(onTime)).toMatchObject({ status: "pending_review", everSubmitted: true }); }); + it("不得申請當月補助:10/28 送 10 月刷卡被拒(草稿可存);11/01 00:00 起可送出", () => { + const october = { ...COMPLETE_FORM, cardDate: "2026-10-05" }; + const id = draft(october, f.applicant, "2026-10-28T02:00:00Z"); + attachFiles(t.db, id, f.applicant.id); + expect(submit(id, "2026-10-28T02:00:00Z", f.applicant, october)).toEqual({ + ok: false, + errors: [], + message: "此筆刷卡日期屬於 2026/10,2026/11/01 起才能送出。", + }); + expect(row(id).status).toBe("draft"); + expect(listTimeline(t.db, id)).toEqual([]); + // 11/01 00:00(台北)= 10/31 16:00 UTC + expect(submit(id, "2026-10-31T15:59:59Z", f.applicant, october).ok).toBe(false); + expect(submit(id, "2026-10-31T16:00:00Z", f.applicant, october)).toEqual({ ok: true, id }); + }); + it("補件逾期:拒絕重送,仍為待補件", () => { const id = draft(); attachFiles(t.db, id, f.applicant.id); @@ -229,7 +249,7 @@ describe("送出", () => { }); }); -describe("歸屬部門(刷卡月份 1 日的部門)", () => { +describe("歸屬部門(基準日:刷卡月份的下個月 1 日的部門)", () => { /** 王小明 2026/09/15 由設計部調至研發部。 */ function transferToRnd() { t.db @@ -241,12 +261,17 @@ describe("歸屬部門(刷卡月份 1 日的部門)", () => { } const card = (cardDate: string) => ({ ...COMPLETE_FORM, cardDate }); - it("調部門後補申請調動前的月份:歸屬原部門,由原部門主管審核並通知原部門主管", () => { + it("調動當月的刷卡歸屬新部門(基準日 10/01)", () => { const moved = transferToRnd(); - const id = draft(card("2026-09-20"), moved); + expect(row(draft(card("2026-09-20"), moved)).departmentId).toBe(f.rnd); + }); + + it("調部門後補申請調動前一個月:歸屬原部門,由原部門主管審核並通知原部門主管", () => { + const moved = transferToRnd(); + const id = draft(card("2026-08-20"), moved, "2026-09-10T02:00:00Z"); expect(row(id).departmentId).toBe(f.design); attachFiles(t.db, id, f.applicant.id); - expect(submit(id, "2026-10-08T02:00:00Z", moved, card("2026-09-20")).ok).toBe(true); + expect(submit(id, "2026-09-10T02:00:00Z", moved, card("2026-08-20")).ok).toBe(true); expect(row(id)).toMatchObject({ departmentId: f.design, status: "pending_review" }); expect(reviewDecision(t.db, f.designManager, row(id))).toMatchObject({ allowed: true }); expect(reviewDecision(t.db, f.rndManager, row(id))).toEqual({ allowed: false }); @@ -270,7 +295,7 @@ describe("歸屬部門(刷卡月份 1 日的部門)", () => { const saved = saveDraft(t.db, at("2026-10-07T03:00:00Z"), { user: { id: moved.id, departmentId: f.rnd }, applicationId: id, - values: card("2026-09-20"), + values: card("2026-08-20"), timeZone: TZ, }); expect(saved.ok).toBe(true); @@ -278,7 +303,7 @@ describe("歸屬部門(刷卡月份 1 日的部門)", () => { const [updated] = auditRows(t.db, "application.updated", id); expect(updated).toMatchObject({ before: { departmentId: f.rnd, cardDate: "2026-10-02" }, - after: { departmentId: f.design, cardDate: "2026-09-20" }, + after: { departmentId: f.design, cardDate: "2026-08-20" }, }); }); @@ -356,7 +381,7 @@ describe("我的申請", () => { expect( listMyApplications(t.db, f.applicant.id, { fromMonth: "2026-04", toMonth: "2026-04" }), ).toEqual([]); - expect(mySummary(t.db, f.applicant.id, "2026-10")).toEqual({ + expect(mySummary(t.db, f.applicant.id, "2026-09")).toEqual({ thisMonth: 2, needsRevision: 1, passed: 0, diff --git a/src/server/applications/service.ts b/src/server/applications/service.ts index 42b0a05..7abaa01 100644 --- a/src/server/applications/service.ts +++ b/src/server/applications/service.ts @@ -1,5 +1,5 @@ import { and, count, desc, eq, inArray, isNull, like, sql, sum } from "drizzle-orm"; -import { applicationMonth, isPastDeadline } from "@/domain/application"; +import { applicationMonth, isBeforeSubmissionStart, isPastDeadline } from "@/domain/application"; import { attributedDepartment } from "@/domain/attribution"; import { localDate } from "@/domain/calendar"; import { @@ -36,6 +36,11 @@ export function platformDisplay(row: { platform: string | null; platformOther: s return row.platform === OTHER_PLATFORM ? (row.platformOther ?? OTHER_PLATFORM) : row.platform; } +/** 刷卡月份當月送出:下個月 1 日起才能送出(rebase-headcount-snapshot)。 */ +export function notYetOpenMessage(cardDate: string, start: Date, timeZone: string): string { + return `此筆刷卡日期屬於 ${formatMonth(cardDate)},${formatDate(localDate(start, timeZone))} 起才能送出。`; +} + export function deadlineMessage(cardDate: string, deadline: Date, timeZone: string): string { return `此筆刷卡日期屬於 ${formatMonth(cardDate)},申請期限已於 ${formatDate(localDate(deadline, timeZone))} 截止。`; } @@ -285,7 +290,14 @@ export function submitApplication( if (!row) return { ok: false, errors: [], message: NOT_FOUND_MESSAGE }; const cardDate = result.fields.cardDate!; - const deadline = deriveDeadlines(tx, cardDate, input.timeZone).employee; + const { start, employee: deadline } = deriveDeadlines(tx, cardDate, input.timeZone); + if (isBeforeSubmissionStart(start, audit.now)) { + return { + ok: false, + errors: [], + message: notYetOpenMessage(cardDate, start, input.timeZone), + }; + } if (isPastDeadline(deadline, audit.now)) { return { ok: false, diff --git a/src/server/dashboard/queries.test.ts b/src/server/dashboard/queries.test.ts index 76d9150..dff11fd 100644 --- a/src/server/dashboard/queries.test.ts +++ b/src/server/dashboard/queries.test.ts @@ -16,7 +16,12 @@ import { type TestUser, } from "@/server/testing/applications"; import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db"; -import { getAdminDashboard, getEmployeeDashboard, getManagerDashboards } from "./queries"; +import { + departmentQuota, + getAdminDashboard, + getEmployeeDashboard, + getManagerDashboards, +} from "./queries"; const TZ = "Asia/Taipei"; let t: TestDatabase; @@ -136,8 +141,16 @@ describe("員工區塊", () => { expect(d.recent.some((r) => r.id === a)).toBe(false); // 最舊的一筆不在最近 3 筆 // 同事的案件只計入部門額度參考值,不出現在個人資料 expect(d.recent.every((r) => r.platform === "ChatGPT")).toBe(true); - // 每人上限 50%:本人 6,000 → 3,000、同事 9,999 → 4,999,未超過月上限(參考值)。 - expect(d.quota).toEqual({ + // 額度卡顯示上個刷卡月份(9 月,本月正在申請的月份);這裡沒有 9 月快照。 + expect(d.quotaMonth).toBe("2026-09"); + expect(d.quota).toEqual({ configured: false }); + // 本月(10 月)的人數快照基準日是 11/01(rebase-headcount-snapshot),額度尚未確定。 + expect(departmentQuota(t.db, f.design, "2026-10", instant("2026-10-08"), TZ)).toEqual({ + configured: false, + message: "2026/11/01 名冊確定後計算", + }); + // 基準日之後:每人上限 50%:本人 6,000 → 3,000、同事 9,999 → 4,999,未超過月上限(參考值)。 + expect(departmentQuota(t.db, f.design, "2026-10", instant("2026-11-02"), TZ)).toEqual({ configured: true, approvedTotal: 3000 + 4999, cap: 10_000, diff --git a/src/server/dashboard/queries.ts b/src/server/dashboard/queries.ts index c0cfc08..bca80f5 100644 --- a/src/server/dashboard/queries.ts +++ b/src/server/dashboard/queries.ts @@ -1,5 +1,6 @@ import { and, asc, count, desc, eq, inArray, isNull } from "drizzle-orm"; import { localDate } from "@/domain/calendar"; +import { baseDateReached, capPendingMessage } from "@/domain/deadlines"; import { daysUntil, quotaReference, @@ -47,6 +48,10 @@ export function departmentQuota( now: Date, timeZone: string, ): QuotaReference { + // 基準日(刷卡月份的下個月 1 日)前還沒有人數快照(rebase-headcount-snapshot)。 + if (!baseDateReached(month, now, timeZone)) { + return { configured: false, message: capPendingMessage(month) }; + } const cap = getDepartmentCap(db, departmentId, month, timeZone); const version = requireEffectiveRuleVersion(db, now); const amounts = new Map(); @@ -112,6 +117,8 @@ export interface EmployeeDashboard { recent: RecentApplication[]; total: number; quota: QuotaReference | null; + /** 額度卡的刷卡月份(上個月:本月正在申請的月份)。 */ + quotaMonth: string; departmentName: string | null; platforms: string[]; } @@ -196,7 +203,9 @@ export function getEmployeeDashboard( quota: user.departmentId === null ? null - : departmentQuota(db, user.departmentId, current.month, now, timeZone), + : departmentQuota(db, user.departmentId, previous.month, now, timeZone), + // 額度卡顯示上個刷卡月份(本月正在申請的月份;本月的月上限要到下個月 1 日才確定)。 + quotaMonth: previous.month, departmentName: dept?.name ?? null, platforms: platformOptions(requireEffectiveRuleVersion(db, now).params), }; @@ -211,6 +220,7 @@ export interface ManagerDashboard { pendingReview: number; needsRevision: number; quota: QuotaReference; + quotaMonth: string; currentMonth: string; /** 目前月結週期(上個月刷卡)的月份、狀態與截止倒數(已提交時為 null)。 */ settlementMonth: string; @@ -262,7 +272,8 @@ export function getManagerDashboards( departmentName: dept.name, pendingReview: statusCount("pending_review"), needsRevision: statusCount("needs_revision"), - quota: departmentQuota(db, dept.id, current.month, now, timeZone), + quota: departmentQuota(db, dept.id, previous.month, now, timeZone), + quotaMonth: previous.month, currentMonth: current.month, settlementMonth: previous.month, settlementStatus: status, diff --git a/src/server/hr-sync/roster.test.ts b/src/server/hr-sync/roster.test.ts index 12fdc98..daba1ea 100644 --- a/src/server/hr-sync/roster.test.ts +++ b/src/server/hr-sync/roster.test.ts @@ -90,7 +90,7 @@ describe("名冊同步", () => { const snapshots = () => t.db.select().from(headcountSnapshots).all(); const syncs = () => t.db.select().from(hrRosterSyncs).all(); - it("寫正職身分、建立本月與上月快照,並留下成功紀錄", async () => { + it("寫正職身分、以本月與上月 1 日名冊建立上月與上上月快照(基準日),並留下成功紀錄", async () => { const { hr, asked } = source(); const outcome = await runRosterSyncIfDue(t.db, hr, options()); expect(outcome).toMatchObject({ @@ -102,13 +102,15 @@ describe("名冊同步", () => { }); expect(asked.sort()).toEqual(["2026-10-01", "2026-11-01", null].sort()); expect(t.db.select().from(hrEmploymentHistory).all()).toHaveLength(4); + // 11/01 名冊 → 2026/10 快照;暫不依正職排除,工讀 P1 也計入 expect( - snapshots().find((s) => s.departmentId === design && s.month === "2026-11"), + snapshots().find((s) => s.departmentId === design && s.month === "2026-10"), ).toMatchObject({ - headcount: 2, + headcount: 3, source: "hr", }); - expect(snapshots().filter((s) => s.month === "2026-10")).toHaveLength(2); + expect(snapshots().filter((s) => s.month === "2026-09")).toHaveLength(2); + expect(snapshots().filter((s) => s.month === "2026-11")).toHaveLength(0); expect(syncs()).toEqual([ expect.objectContaining({ status: "succeeded", @@ -176,7 +178,7 @@ describe("名冊同步", () => { .find((d) => d.code === "D310"), ).toBeUndefined(); expect( - snapshots().find((s) => s.departmentId === anim.id && s.month === "2026-11")?.headcount, + snapshots().find((s) => s.departmentId === anim.id && s.month === "2026-10")?.headcount, ).toBe(2); const managers = auditRows(t.db, "department.manager_assigned", anim.id); expect(managers.map((m) => (m.after as { employeeNo: string }).employeeNo)).toEqual(["E0500"]); @@ -342,8 +344,8 @@ describe("名冊同步", () => { failure: { stage: "roster_on_date", reason: "http_500" }, }); expect(t.db.select().from(hrEmploymentHistory).all()).toHaveLength(4); - // 上個月先處理(本月名單以上個月名單為退路):本月 1 日名冊失敗時只有上個月的快照 - expect(snapshots().every((s) => s.month === "2026-10")).toBe(true); + // 較早的月份先處理(較晚月份的名單以它為退路):本月 1 日名冊失敗時只有上上個月的快照 + expect(snapshots().every((s) => s.month === "2026-09")).toBe(true); expect(auditRows(t.db, "hr_sync.roster_synced")).toHaveLength(0); expect(syncs()[0]).toMatchObject({ status: "failed", failureStage: "roster_on_date" }); }); diff --git a/src/server/hr-sync/roster.ts b/src/server/hr-sync/roster.ts index 8b0c2ef..e15c195 100644 --- a/src/server/hr-sync/roster.ts +++ b/src/server/hr-sync/roster.ts @@ -242,13 +242,16 @@ async function run( withTransaction(db, (tx) => recordEmployment(tx, roster, today, timeZone)), ); - // 先上個月再本月:本月名單以上個月名單為留停/離職者部門歸屬的退路。 + // 名冊日期是快照的基準日(刷卡月份的下個月 1 日,rebase-headcount-snapshot):本月 1 日名冊 + // 算上個刷卡月份、上月 1 日名冊算上上個刷卡月份。先早後晚:較晚月份的名單以較早月份為留停/ + // 離職者部門歸屬的退路。 let snapshotChanges = 0; - for (const [i, month] of [...months.entries()].reverse()) { + for (const [i, rosterMonth] of [...months.entries()].reverse()) { const { roster: rosterOnFirst, tree } = onFirst(i); + const cardMonth = previousMonth(rosterMonth); snapshotChanges += step("snapshots", () => withTransaction(db, (tx) => - syncSnapshotsFromHr(tx, audit, month, rosterOnFirst, tree, timeZone), + syncSnapshotsFromHr(tx, audit, cardMonth, rosterOnFirst, tree, timeZone), ), ); } diff --git a/src/server/rules/headcount-hr.test.ts b/src/server/rules/headcount-hr.test.ts index e9d5bba..e5bf388 100644 --- a/src/server/rules/headcount-hr.test.ts +++ b/src/server/rules/headcount-hr.test.ts @@ -103,11 +103,12 @@ describe("依 HR 名冊的人數快照", () => { return roster; }; - it("月初自動建立:只計當日在職的正職,來源為 HR 名冊", () => { - expect(sync("2026-11", novRoster())).toBe(2); - expect(snapshot(design, "2026-11")).toMatchObject({ headcount: 20, source: "hr" }); - expect(snapshot(rnd, "2026-11")).toMatchObject({ headcount: 2, source: "hr" }); - expect(snapshot(manual, "2026-11")).toBeUndefined(); + // 名冊是基準日(刷卡月份的下個月 1 日)的名冊:11/01 名冊算 2026/10 的快照。 + it("月初自動建立:計入基準日所有在職者(暫不依正職排除),來源為 HR 名冊", () => { + expect(sync("2026-10", novRoster())).toBe(2); + expect(snapshot(design, "2026-10")).toMatchObject({ headcount: 22, source: "hr" }); + expect(snapshot(rnd, "2026-10")).toMatchObject({ headcount: 2, source: "hr" }); + expect(snapshot(manual, "2026-10")).toBeUndefined(); expect(auditRows(t.db, "headcount.snapshot_created")).toHaveLength(2); }); @@ -126,83 +127,83 @@ describe("依 HR 名冊的人數快照", () => { .values({ code: "D110", name: "前端組", type: "general", hrManaged: true, active: false }) .returning() .get().id; - sync("2026-11", roster); - expect(snapshot(rnd, "2026-11")?.headcount).toBe(5); - expect(snapshot(fe, "2026-11")).toBeUndefined(); + sync("2026-10", roster); + expect(snapshot(rnd, "2026-10")?.headcount).toBe(5); + expect(snapshot(fe, "2026-10")).toBeUndefined(); }); it("單位不在當日組織結構中時以單位代碼本身計", () => { - sync("2026-11", novRoster(), []); - expect(snapshot(design, "2026-11")?.headcount).toBe(20); + sync("2026-10", novRoster(), []); + expect(snapshot(design, "2026-10")?.headcount).toBe(22); }); - it("1 日之後到職或離職的人不影響(1 日名冊裡的狀態才算);留停與沒有正職紀錄的人不計", () => { + it("基準日之後到職或離職的人不影響(基準日名冊裡的狀態才算);留停不計、沒有正職紀錄的人計入", () => { const roster = novRoster(); roster.push(person("N1", "D200", "NOT_YET_HIRED")); // 11/10 才到職 roster.push(person("S1", "D200", "SUSPENDED")); employment("S1", true, "2020-01-01"); roster.push(person("U1", "D200")); // 沒有正職紀錄 - sync("2026-11", roster); - expect(snapshot(design, "2026-11")?.headcount).toBe(20); + sync("2026-10", roster); + expect(snapshot(design, "2026-10")?.headcount).toBe(23); }); - it("月中轉正:當月不計、下月計", () => { + it("正職身分歷程不影響人數(等 HR Sync 提供依日期的員工群組)", () => { const roster = novRoster(); t.db .insert(hrEmploymentHistory) .values({ employeeNo: "P0", isFullTime: true, effectiveFrom: "2026-11-15" }) .run(); + sync("2026-10", roster); sync("2026-11", roster); - sync("2026-12", roster); - expect(snapshot(design, "2026-11")?.headcount).toBe(20); - expect(snapshot(design, "2026-12")?.headcount).toBe(21); + expect(snapshot(design, "2026-10")?.headcount).toBe(22); + expect(snapshot(design, "2026-11")?.headcount).toBe(22); }); it("HR 補登:未鎖定且未人工調整的快照更新並留紀錄;人數相同不寫", () => { - sync("2026-11", novRoster()); - expect(sync("2026-11", novRoster())).toBe(0); + sync("2026-10", novRoster()); + expect(sync("2026-10", novRoster())).toBe(0); employment("L1", true, "2026-09-25"); - expect(sync("2026-11", [...novRoster(), person("L1", "D200")])).toBe(1); - expect(snapshot(design, "2026-11")).toMatchObject({ headcount: 21, computedHeadcount: 21 }); + expect(sync("2026-10", [...novRoster(), person("L1", "D200")])).toBe(1); + expect(snapshot(design, "2026-10")).toMatchObject({ headcount: 23, computedHeadcount: 23 }); const [row] = auditRows(t.db, "headcount.snapshot_synced"); - expect(row.before).toEqual({ headcount: 20, source: "hr" }); + expect(row.before).toEqual({ headcount: 22, source: "hr" }); expect(row.after).toEqual({ - headcount: 21, + headcount: 23, source: "hr", - members: { counted: 21, excluded: 2, offboarded: 0, suspended: 0 }, + members: { counted: 23, excluded: 0, offboarded: 0, suspended: 0 }, }); expect(row.actorLabel).toBe("系統(HR 同步)"); }); it("系統先算出的快照被 HR 名冊取代", () => { - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - expect(snapshot(design, "2026-11")).toMatchObject({ headcount: 0, source: "local" }); - sync("2026-11", novRoster()); - expect(snapshot(design, "2026-11")).toMatchObject({ headcount: 20, source: "hr" }); + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + expect(snapshot(design, "2026-10")).toMatchObject({ headcount: 0, source: "local" }); + sync("2026-10", novRoster()); + expect(snapshot(design, "2026-10")).toMatchObject({ headcount: 22, source: "hr" }); expect( - listMonthSnapshots(t.db, "2026-11", TZ).find((r) => r.departmentId === design)?.source, + listMonthSnapshots(t.db, "2026-10", TZ).find((r) => r.departmentId === design)?.source, ).toBe("hr"); }); it("已人工調整或已鎖定的快照不覆寫", () => { - sync("2026-11", novRoster()); - const designSnapshot = snapshot(design, "2026-11")!; + sync("2026-10", novRoster()); + const designSnapshot = snapshot(design, "2026-10")!; expect(adjustHeadcount(t.db, NOV3, designSnapshot.id, 21, "晚建檔").ok).toBe(true); - withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-11", true)); + withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-10", true)); const roster = novRoster().filter( (e) => e.employeeNumber !== "F0" && e.employeeNumber !== "R0", ); - expect(sync("2026-11", roster)).toBe(0); - expect(snapshot(design, "2026-11")?.headcount).toBe(21); - expect(snapshot(rnd, "2026-11")?.headcount).toBe(2); + expect(sync("2026-10", roster)).toBe(0); + expect(snapshot(design, "2026-10")?.headcount).toBe(21); + expect(snapshot(rnd, "2026-10")?.headcount).toBe(2); }); - const membersOf = (departmentId: number, month = "2026-11") => + const membersOf = (departmentId: number, month = "2026-10") => listMonthSnapshots(t.db, month, TZ).find((r) => r.departmentId === departmentId)?.members; const statusCount = (departmentId: number, status: string) => membersOf(departmentId)?.filter((m) => m.status === status).length; - it("1 日名單:計入、非正職(不計入)、留停、近期離職;早已離職不列;計入筆數等於人數", () => { + it("基準日名單:計入(含非正職)、留停、近期離職;早已離職不列;計入筆數等於人數", () => { const roster = novRoster(); roster[0] = { ...roster[0], name: "王小明" }; roster.push( @@ -214,26 +215,26 @@ describe("依 HR 名冊的人數快照", () => { { ...person("O2", "D200", "OFFBOARDED"), leaveDate: "2026-08-15T00:00:00.000Z" }, person("N1", "D200", "NOT_YET_HIRED"), ); - sync("2026-11", roster); - expect(statusCount(design, "counted")).toBe(20); - expect(statusCount(design, "excluded")).toBe(2); + sync("2026-10", roster); + expect(statusCount(design, "counted")).toBe(22); + expect(statusCount(design, "excluded")).toBe(0); expect(statusCount(design, "suspended")).toBe(1); expect(statusCount(design, "offboarded")).toBe(1); expect(membersOf(design)?.map((m) => m.employeeNo)).not.toContain("O2"); expect(membersOf(design)?.map((m) => m.employeeNo)).not.toContain("N1"); - expect(snapshot(design, "2026-11")?.headcount).toBe(20); + expect(snapshot(design, "2026-10")?.headcount).toBe(22); expect(membersOf(design)?.[0]).toEqual({ employeeNo: "F0", name: "王小明", status: "counted" }); - expect(membersOf(design)?.at(-1)?.status).toBe("excluded"); // 計入 → 留停 → 離職 → 不計入 + expect(membersOf(design)?.at(-1)?.status).toBe("offboarded"); // 計入 → 留停 → 離職 const [created] = auditRows(t.db, "headcount.snapshot_created").filter( - (r) => r.targetId === String(snapshot(design, "2026-11")?.id), + (r) => r.targetId === String(snapshot(design, "2026-10")?.id), ); expect(created.after).toMatchObject({ - members: { counted: 20, excluded: 2, suspended: 1, offboarded: 1 }, + members: { counted: 22, excluded: 0, suspended: 1, offboarded: 1 }, }); }); it("沒有單位的留停或離職者以上個月名單的部門歸屬;找不到時不列", () => { - sync("2026-10", [...novRoster()]); + sync("2026-09", [...novRoster()]); const roster = novRoster().filter( (e) => e.employeeNumber !== "F1" && e.employeeNumber !== "R1", ); @@ -242,30 +243,30 @@ describe("依 HR 名冊的人數快照", () => { { ...person("R1", null, "OFFBOARDED"), leaveDate: "2026-10-20T00:00:00.000Z" }, { ...person("X1", null, "SUSPENDED") }, ); - sync("2026-11", roster); + sync("2026-10", roster); expect(membersOf(design)?.find((m) => m.employeeNo === "F1")?.status).toBe("suspended"); expect(membersOf(rnd)?.find((m) => m.employeeNo === "R1")?.status).toBe("offboarded"); expect(membersOf(design)?.some((m) => m.employeeNo === "X1")).toBe(false); - expect(snapshot(design, "2026-11")?.headcount).toBe(19); + expect(snapshot(design, "2026-10")?.headcount).toBe(21); }); it("人數不變但名單變動:替換名單並記錄;鎖定或人工調整後名單不變;觸發器擋下鎖定快照", () => { - sync("2026-11", novRoster()); + sync("2026-10", novRoster()); const renamed = novRoster().map((e) => e.employeeNumber === "F0" ? { ...e, name: "新名" } : e, ); - expect(sync("2026-11", renamed)).toBe(1); // 只有設計部的名單變了 + expect(sync("2026-10", renamed)).toBe(1); // 只有設計部的名單變了 expect(auditRows(t.db, "headcount.snapshot_members_updated").length).toBeGreaterThan(0); expect(membersOf(design)?.find((m) => m.employeeNo === "F0")?.name).toBe("新名"); - expect(sync("2026-11", renamed)).toBe(0); + expect(sync("2026-10", renamed)).toBe(0); - withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, design, "2026-11", true)); + withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, design, "2026-10", true)); const suspended = renamed.map((e) => e.employeeNumber === "F2" ? { ...e, status: "SUSPENDED" } : e, ); - expect(sync("2026-11", suspended)).toBe(0); + expect(sync("2026-10", suspended)).toBe(0); expect(membersOf(design)?.find((m) => m.employeeNo === "F2")?.status).toBe("counted"); - const id = snapshot(design, "2026-11")!.id; + const id = snapshot(design, "2026-10")!.id; expect(() => t.db .insert(headcountSnapshotMembers) @@ -279,30 +280,30 @@ describe("依 HR 名冊的人數快照", () => { .run(), ).toThrow(/locked/); - const rndSnapshot = snapshot(rnd, "2026-11")!; + const rndSnapshot = snapshot(rnd, "2026-10")!; expect(adjustHeadcount(t.db, NOV3, rndSnapshot.id, 3, "晚建檔").ok).toBe(true); sync( - "2026-11", + "2026-10", suspended.filter((e) => e.employeeNumber !== "R0"), ); expect(membersOf(rnd)?.map((m) => m.employeeNo)).toContain("R0"); }); it("HR 快照沒有名單紀錄時為 null;本系統計算的部門即時列出成員", () => { - sync("2026-11", novRoster()); - const id = snapshot(design, "2026-11")!.id; + sync("2026-10", novRoster()); + const id = snapshot(design, "2026-10")!.id; t.db.delete(headcountSnapshotMembers).where(eq(headcountSnapshotMembers.snapshotId, id)).run(); expect(membersOf(design)).toBeNull(); const userId = t.db.insert(users).values({ employeeNo: "L1", name: "林" }).returning().get().id; assignDepartment(t.db, NOV3, userId, manual, "2026-10-01", "2026-10-01"); - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - // 有正職資料(novRoster 寫入)但 L1 沒有紀錄:不計入 - expect(membersOf(manual)).toEqual([{ employeeNo: "L1", name: "林", status: "excluded" }]); - expect(snapshot(manual, "2026-11")?.headcount).toBe(0); + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + // 有正職資料(novRoster 寫入)但 L1 沒有紀錄:暫不依正職排除,仍計入 + expect(membersOf(manual)).toEqual([{ employeeNo: "L1", name: "林", status: "counted" }]); + expect(snapshot(manual, "2026-10")?.headcount).toBe(1); }); }); -describe("本系統計算的人數(正職條件)", () => { +describe("本系統計算的人數(暫不依正職排除)", () => { let t: TestDatabase; let design: number; beforeEach(() => { @@ -326,11 +327,11 @@ describe("本系統計算的人數(正職條件)", () => { ?.headcount; it("沒有正職資料(開發、e2e、尚未同步)時計入所有成員", () => { - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); expect(headcount()).toBe(3); }); - it("有正職資料後只計當日為正職的成員,沒有紀錄的不計", () => { + it("有正職資料也計入所有成員(等 HR Sync 提供依日期的員工群組)", () => { t.db .insert(hrEmploymentHistory) .values([ @@ -338,7 +339,7 @@ describe("本系統計算的人數(正職條件)", () => { { employeeNo: "B", isFullTime: false, effectiveFrom: "2020-01-01" }, ]) .run(); - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - expect(headcount()).toBe(1); + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + expect(headcount()).toBe(3); }); }); diff --git a/src/server/rules/headcount.test.ts b/src/server/rules/headcount.test.ts index b9b9111..54bcf03 100644 --- a/src/server/rules/headcount.test.ts +++ b/src/server/rules/headcount.test.ts @@ -1,6 +1,13 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { DEFAULT_RULE_PARAMS } from "@/lib/rule-params"; -import { departments, headcountAdjustments, headcountSnapshots, users } from "@/server/db/schema"; +import { + departments, + headcountAdjustments, + headcountSnapshots, + hrEmploymentHistory, + userDepartmentHistory, + users, +} from "@/server/db/schema"; import { withTransaction } from "@/server/db/transaction"; import { assignDepartment } from "@/server/org/accounts"; import { auditRows, expectAudit, seedAuditActor, testAuditContext } from "@/server/testing/audit"; @@ -57,21 +64,21 @@ describe("人數快照", () => { .find((s) => s.departmentId === departmentId && s.month === month); describe("建立", () => { - it("以該月 1 日 00:00 的部門成員計算;月中到職不影響當月快照", () => { + it("以基準日(刷卡月份的下個月 1 日)00:00 的部門成員計算;基準日之後到職不影響", () => { hire(20, design, "2026-10-15", "D"); - hire(1, design, "2026-11-10", "N"); // 11/10 到職 - expect(ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ)).toEqual({ + hire(1, design, "2026-11-10", "N"); // 11/10 到職:不計入 10 月(基準日 11/01) + expect(ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ)).toEqual({ ok: true, value: { created: 2 }, }); - expect(snapshot(design, "2026-11")).toMatchObject({ headcount: 20, computedHeadcount: 20 }); - expect(snapshot(rnd, "2026-11")?.headcount).toBe(0); + expect(snapshot(design, "2026-10")).toMatchObject({ headcount: 20, computedHeadcount: 20 }); + expect(snapshot(rnd, "2026-10")?.headcount).toBe(0); expect(auditRows(t.db, "headcount.snapshot_created")).toHaveLength(2); }); - it("之後才建立(懶建立)也以 1 日當時計算,轉調不改變已存在的快照", () => { + it("之後才建立(懶建立)也以基準日當時計算,轉調不改變已存在的快照", () => { hire(3, design, "2026-10-01", "D"); - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); // 12 月轉調一位到研發部 const moved = t.db .select() @@ -79,17 +86,17 @@ describe("人數快照", () => { .all() .find((u) => u.employeeNo === "D0")!; assignDepartment(t.db, NOV3, moved.id, rnd, "2026-12-01", "2026-12-31"); - expect(snapshot(design, "2026-11")?.headcount).toBe(3); - expect(snapshot(rnd, "2026-11")?.headcount).toBe(0); + expect(snapshot(design, "2026-10")?.headcount).toBe(3); + expect(snapshot(rnd, "2026-10")?.headcount).toBe(0); }); it("重複建立:不建立第二筆並提示已存在", () => { - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - expect(ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ)).toEqual({ + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + expect(ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ)).toEqual({ ok: true, value: { created: 0 }, }); - expect(createDepartmentSnapshot(t.db, NOV3, design, "2026-11", TZ)).toEqual({ + expect(createDepartmentSnapshot(t.db, NOV3, design, "2026-10", TZ)).toEqual({ ok: false, error: "該月份快照已存在", }); @@ -121,11 +128,43 @@ describe("人數快照", () => { ).toThrow(/UNIQUE/); }); - it("月份尚未開始時不建立", () => { - expect(ensureMonthSnapshots(t.db, NOV3, "2026-12", TZ)).toEqual({ + it("基準日未到時不建立(11 月刷卡要到 12/01)", () => { + expect(ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ)).toEqual({ ok: false, - error: "該月份尚未開始,無法建立人數快照", + error: "2026/12/01 名冊確定後計算", }); + expect(createDepartmentSnapshot(t.db, NOV3, design, "2026-11", TZ)).toEqual({ + ok: false, + error: "2026/12/01 名冊確定後計算", + }); + }); + + it("刷卡月份最後一天離職的人不計入;暫不依正職身分排除", () => { + hire(2, design, "2026-01-01", "D"); + const leaver = t.db.insert(users).values({ employeeNo: "L0" }).returning().get().id; + assignDepartment(t.db, NOV3, leaver, design, "2026-01-01", "2026-12-31"); + t.db + .insert(userDepartmentHistory) + .values({ userId: leaver, departmentId: null, effectiveFrom: "2026-11-01" }) + .run(); + // 有正職身分歷程(D1 非正職)也照樣計入 + t.db + .insert(hrEmploymentHistory) + .values([ + { employeeNo: "D0", isFullTime: true, effectiveFrom: "2026-01-01" }, + { employeeNo: "D1", isFullTime: false, effectiveFrom: "2026-01-01" }, + ]) + .run(); + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + expect(snapshot(design, "2026-10")?.headcount).toBe(2); + expect( + listMonthSnapshots(t.db, "2026-10", TZ) + .find((r) => r.departmentId === design) + ?.members?.map((m) => [m.employeeNo, m.status]), + ).toEqual([ + ["D0", "counted"], + ["D1", "counted"], + ]); }); }); @@ -133,13 +172,13 @@ describe("人數快照", () => { let snapshotId: number; beforeEach(() => { hire(20, rnd, "2026-10-01", "R"); - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - snapshotId = snapshot(rnd, "2026-11")!.id; + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + snapshotId = snapshot(rnd, "2026-10")!.id; }); it("調整人數:保留前後值、原因、操作者與時間,並寫操作紀錄", () => { expect(adjustHeadcount(t.db, NOV3, snapshotId, 21, "11/01 到職者系統晚建檔").ok).toBe(true); - expect(snapshot(rnd, "2026-11")).toMatchObject({ headcount: 21, computedHeadcount: 20 }); + expect(snapshot(rnd, "2026-10")).toMatchObject({ headcount: 21, computedHeadcount: 20 }); expect(t.db.select().from(headcountAdjustments).all()).toEqual([ expect.objectContaining({ before: 20, @@ -164,16 +203,16 @@ describe("人數快照", () => { }); expect(adjustHeadcount(t.db, NOV3, snapshotId, -1, "x")).toMatchObject({ ok: false }); expect(adjustHeadcount(t.db, NOV3, snapshotId, 1.5, "x")).toMatchObject({ ok: false }); - expect(snapshot(rnd, "2026-11")?.headcount).toBe(20); + expect(snapshot(rnd, "2026-10")?.headcount).toBe(20); }); it("鎖定後調整被拒;解鎖後可調整;鎖定與解鎖都留紀錄", () => { - withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-11", true)); + withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-10", true)); expect(adjustHeadcount(t.db, NOV3, snapshotId, 21, "x")).toEqual({ ok: false, error: SNAPSHOT_LOCKED_MESSAGE, }); - withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-11", false)); + withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-10", false)); expect(adjustHeadcount(t.db, NOV3, snapshotId, 21, "x").ok).toBe(true); expect(expectAudit(t.db, "headcount.locked", snapshotId).after).toEqual({ locked: true }); expect(expectAudit(t.db, "headcount.unlocked", snapshotId).after).toEqual({ locked: false }); @@ -191,7 +230,7 @@ describe("人數快照", () => { hire(2, rnd, "2026-09-01", "R"); ensureMonthSnapshots( t.db, - testAuditContext({ now: new Date("2026-10-02T00:00:00Z") }), + testAuditContext({ now: new Date("2026-11-02T00:00:00Z") }), "2026-10", TZ, ); @@ -217,21 +256,21 @@ describe("人數快照", () => { it("使用該月結束時生效的每人額度", () => { hire(10, design, "2026-09-01", "D"); - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - saveRuleVersion(t.db, NOV3, { + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + saveRuleVersion(t.db, testAuditContext({ now: new Date("2026-10-01T00:00:00Z") }), { params: { ...DEFAULT_RULE_PARAMS, perPersonQuota: { general: 600, rnd: 1000 } }, - reason: "11/15 起調高", - effectiveAt: "2026-11-15T00:00:00.000Z", + reason: "10/15 起調高", + effectiveAt: "2026-10-15T00:00:00.000Z", }); - expect(getDepartmentCap(t.db, design, "2026-11", TZ)).toMatchObject({ cap: 6000 }); + expect(getDepartmentCap(t.db, design, "2026-10", TZ)).toMatchObject({ cap: 6000 }); }); it("設定頁清單:各部門人數、類型、月上限、鎖定與調整紀錄", () => { hire(3, design, "2026-10-01", "D"); - ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ); - const id = snapshot(design, "2026-11")!.id; + ensureMonthSnapshots(t.db, NOV3, "2026-10", TZ); + const id = snapshot(design, "2026-10")!.id; adjustHeadcount(t.db, NOV3, id, 4, "補登"); - expect(listMonthSnapshots(t.db, "2026-11", TZ)).toEqual([ + expect(listMonthSnapshots(t.db, "2026-10", TZ)).toEqual([ expect.objectContaining({ departmentName: "研發部", headcount: 0, cap: 0, locked: false }), expect.objectContaining({ departmentName: "設計部", diff --git a/src/server/rules/headcount.ts b/src/server/rules/headcount.ts index 834fd82..2eec58b 100644 --- a/src/server/rules/headcount.ts +++ b/src/server/rules/headcount.ts @@ -1,5 +1,11 @@ import { and, asc, desc, eq, inArray } from "drizzle-orm"; -import { monthEnd, monthStart, previousMonth } from "@/domain/deadlines"; +import { + baseDateReached, + capPendingMessage, + monthEnd, + previousMonth, + snapshotBaseDate, +} from "@/domain/deadlines"; import { recordAudit, type AuditContext } from "@/server/audit/record"; import type { Db } from "@/server/db/client"; import { @@ -12,7 +18,6 @@ import { import { withTransaction, type Tx } from "@/server/db/transaction"; import type { HrOrganization, HrRosterEntry } from "@/server/hr-sync/client"; import { indexOrganizations, resolveDivision } from "@/server/hr-sync/divisions"; -import { fullTimeOn, hasEmploymentData } from "@/server/hr-sync/employment"; import { hrDate } from "@/server/hr-sync/employment-status"; import { departmentMembersAt } from "@/server/org/accounts"; import { fail, ok, type Result } from "@/server/org/result"; @@ -23,14 +28,16 @@ export const SNAPSHOT_LOCKED_MESSAGE = "該月份月結已提交,需先退回 const MONTH = /^\d{4}-(0[1-9]|1[0-2])$/; -/** 該月 1 日 00:00 是否已到(未到的月份不能建立快照)。 */ -function monthStarted(month: string, now: Date, timeZone: string): boolean { - return now.getTime() >= monthStart(month, timeZone).getTime(); +/** + * 基準日(刷卡月份的下個月 1 日,rebase-headcount-snapshot)00:00 是否已到;未到的月份不能建立快照。 + */ +function baseReached(month: string, now: Date, timeZone: string): boolean { + return baseDateReached(month, now, timeZone); } /** - * 本系統計算的人數:該月 1 日 00:00 隸屬該部門的成員(月中到職、離職、轉調都不影響當月快照)。 - * 已有正職身分資料(名冊同步過)時只計當日為正職的人;沒有資料的環境(開發、e2e、尚未同步)計入全部。 + * 本系統計算的人數:基準日 00:00 隸屬該部門的成員(基準日之後的到職、離職、轉調不影響該月快照)。 + * 在 HR Sync 提供依日期的員工群組之前,不依正職身分排除(使用者決定 2026-10-30)。 */ function localHeadcount(tx: Tx, departmentId: number, month: string): number { return localMembers(tx, departmentId, month).filter((m) => m.status === "counted").length; @@ -69,7 +76,7 @@ export function ensureMonthSnapshots( timeZone: string, ): Result<{ created: number }> { if (!MONTH.test(month)) return fail("月份格式不正確"); - if (!monthStarted(month, audit.now, timeZone)) return fail("該月份尚未開始,無法建立人數快照"); + if (!baseReached(month, audit.now, timeZone)) return fail(capPendingMessage(month)); return withTransaction(db, (tx) => { const existing = new Set( tx @@ -110,8 +117,8 @@ export function syncSnapshotsFromHr( timeZone = "Asia/Taipei", ): number { if (!MONTH.test(month)) throw new Error(`月份格式不正確:${month}`); - const date = `${month}-01`; - const recentLeaveFrom = `${previousMonth(month)}-01`; + // 基準日名冊;離職名單列出基準日上個月 1 日(= 刷卡月份 1 日)之後離職的人。 + const recentLeaveFrom = `${month}-01`; const index = indexOrganizations(organizationsOnFirst); const divisionOf = new Map(); const division = (code: string) => { @@ -125,12 +132,6 @@ export function syncSnapshotsFromHr( const codes = new Set( rosterOnFirst.flatMap((e) => (e.departmentCode ? [division(e.departmentCode)] : [])), ); - const active = rosterOnFirst.filter((e) => e.status === "ACTIVE" && e.departmentCode); - const fullTime = fullTimeOn( - tx, - active.map((e) => e.employeeNumber), - date, - ); const depts = tx.select().from(departments).where(eq(departments.active, true)).all(); const deptByCode = new Map(depts.flatMap((d) => (d.code ? [[d.code, d.id] as const] : []))); @@ -140,7 +141,8 @@ export function syncSnapshotsFromHr( let status: SnapshotMemberStatus; if (e.status === "ACTIVE") { if (!e.departmentCode) continue; - status = fullTime.has(e.employeeNumber) ? "counted" : "excluded"; + // 暫不依正職排除:HR Sync 依日期查詢時員工群組是現況值(rebase-headcount-snapshot)。 + status = "counted"; } else if (e.status === "SUSPENDED") { status = "suspended"; } else if (e.status === "OFFBOARDED") { @@ -298,7 +300,7 @@ export function createDepartmentSnapshot( timeZone: string, ): Result { if (!MONTH.test(month)) return fail("月份格式不正確"); - if (!monthStarted(month, audit.now, timeZone)) return fail("該月份尚未開始,無法建立人數快照"); + if (!baseReached(month, audit.now, timeZone)) return fail(capPendingMessage(month)); return withTransaction(db, (tx) => { const dept = tx.select().from(departments).where(eq(departments.id, departmentId)).get(); if (!dept) return fail("部門不存在"); @@ -477,21 +479,12 @@ function sortMembers(members: SnapshotMember[]): SnapshotMember[] { ); } -/** 本系統計算的名單:1 日隸屬部門的成員;有正職資料時非正職為「不計入」(與 `localHeadcount` 同一套)。 */ +/** 本系統計算的名單:基準日隸屬部門的成員,全部計入(與 `localHeadcount` 同一套)。 */ function localMembers(db: Db | Tx, departmentId: number, month: string): SnapshotMember[] { - const date = `${month}-01`; - const members = departmentMembersAt(db, departmentId, date); - const fullTime = hasEmploymentData(db) - ? fullTimeOn( - db, - members.map((m) => m.employeeNo), - date, - ) - : null; - return members.map((m) => ({ + return departmentMembersAt(db, departmentId, snapshotBaseDate(month)).map((m) => ({ employeeNo: m.employeeNo, name: m.name, - status: fullTime === null || fullTime.has(m.employeeNo) ? "counted" : "excluded", + status: "counted", })); } diff --git a/src/server/rules/rebase-snapshots.test.ts b/src/server/rules/rebase-snapshots.test.ts new file mode 100644 index 0000000..e39736f --- /dev/null +++ b/src/server/rules/rebase-snapshots.test.ts @@ -0,0 +1,91 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + departments, + headcountSnapshotMembers, + headcountSnapshots, + meta, +} from "@/server/db/schema"; +import { withTransaction } from "@/server/db/transaction"; +import { auditRows, seedAuditActor, testAuditContext } from "@/server/testing/audit"; +import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db"; +import { adjustHeadcount, setSnapshotLocked } from "./headcount"; +import { ensureDefaultRuleVersion } from "./params"; +import { REBASE_META_KEY, REBASE_REASON, rebaseHeadcountSnapshots } from "./rebase-snapshots"; + +const TZ = "Asia/Taipei"; +/** 部署當下:2026/10/30(台北),10 月刷卡的基準日 11/01 還沒到。 */ +const OCT30 = testAuditContext({ now: new Date("2026-10-30T02:00:00.000Z") }); + +describe("人數快照基準日變更的一次性清理", () => { + let t: TestDatabase; + let design: number; + let rnd: number; + let ops: number; + beforeEach(() => { + t = createTestDatabase(); + seedAuditActor(t.db); + ensureDefaultRuleVersion(t.db); + const dept = (name: string) => + t.db.insert(departments).values({ name, type: "general" }).returning().get().id; + design = dept("設計部"); + rnd = dept("研發部"); + ops = dept("營運部"); + }); + afterEach(() => t.cleanup()); + + const insert = (departmentId: number, month: string, headcount = 5) => + t.db + .insert(headcountSnapshots) + .values({ + departmentId, + month, + headcount, + computedHeadcount: headcount, + source: "hr", + createdByLabel: "系統", + }) + .returning() + .get().id; + const months = () => + t.db + .select() + .from(headcountSnapshots) + .all() + .map((s) => `${s.departmentId}:${s.month}`) + .sort(); + + it("只刪基準日未到、未鎖定、未調整的快照與名單;寫操作紀錄;只執行一次", () => { + const octDesign = insert(design, "2026-10"); + t.db + .insert(headcountSnapshotMembers) + .values({ snapshotId: octDesign, employeeNo: "F0", status: "counted" }) + .run(); + const octRnd = insert(rnd, "2026-10"); + adjustHeadcount(t.db, OCT30, octRnd, 6, "晚建檔"); + insert(ops, "2026-10"); + withTransaction(t.db, (tx) => setSnapshotLocked(tx, OCT30, ops, "2026-10", true)); + insert(design, "2026-09"); // 基準日 10/01 已過:保留 + + expect(rebaseHeadcountSnapshots(t.db, OCT30, TZ)).toBe(1); + expect(months()).toEqual([`${design}:2026-09`, `${ops}:2026-10`, `${rnd}:2026-10`].sort()); + expect(t.db.select().from(headcountSnapshotMembers).all()).toEqual([]); + const [row] = auditRows(t.db, "headcount.snapshot_removed"); + expect(row).toMatchObject({ + targetId: String(octDesign), + before: { departmentId: design, month: "2026-10", headcount: 5, source: "hr" }, + comment: REBASE_REASON, + }); + expect( + t.db + .select() + .from(meta) + .all() + .map((m) => m.key), + ).toContain(REBASE_META_KEY); + + // 再次啟動不再執行 + insert(design, "2026-10"); + expect(rebaseHeadcountSnapshots(t.db, OCT30, TZ)).toBeNull(); + expect(months()).toContain(`${design}:2026-10`); + }); +}); diff --git a/src/server/rules/rebase-snapshots.ts b/src/server/rules/rebase-snapshots.ts new file mode 100644 index 0000000..f3ec2b7 --- /dev/null +++ b/src/server/rules/rebase-snapshots.ts @@ -0,0 +1,73 @@ +import { and, eq, inArray } from "drizzle-orm"; +import { baseDateReached } from "@/domain/deadlines"; +import { recordAudit, type AuditContext } from "@/server/audit/record"; +import type { Db } from "@/server/db/client"; +import { + headcountAdjustments, + headcountSnapshotMembers, + headcountSnapshots, + meta, +} from "@/server/db/schema"; +import { withTransaction } from "@/server/db/transaction"; + +// 人數快照基準日改為刷卡月份的下個月 1 日(rebase-headcount-snapshot design D6):部署後執行一次, +// 刪除基準日還沒到、未鎖定、沒有人工調整的快照(就是部署當下的刷卡月份,舊規則以當月 1 日建立), +// 讓它們在基準日之後依新規則重新建立。其他快照不動。 + +export const REBASE_META_KEY = "headcount_base_next_month"; +export const REBASE_REASON = "人數快照基準日改為刷卡月份的下個月 1 日"; + +/** 執行一次(`_meta` 有紀錄時不再執行),回傳刪除的快照數;已執行過時回傳 null。 */ +export function rebaseHeadcountSnapshots( + db: Db, + audit: AuditContext, + timeZone: string, +): number | null { + return withTransaction(db, (tx) => { + if (tx.select().from(meta).where(eq(meta.key, REBASE_META_KEY)).get()) return null; + const adjusted = new Set( + tx + .selectDistinct({ snapshotId: headcountAdjustments.snapshotId }) + .from(headcountAdjustments) + .all() + .map((r) => r.snapshotId), + ); + const targets = tx + .select() + .from(headcountSnapshots) + .where(eq(headcountSnapshots.locked, false)) + .all() + .filter((s) => !adjusted.has(s.id) && !baseDateReached(s.month, audit.now, timeZone)); + const ids = targets.map((s) => s.id); + if (ids.length > 0) { + tx.delete(headcountSnapshotMembers) + .where(inArray(headcountSnapshotMembers.snapshotId, ids)) + .run(); + tx.delete(headcountSnapshots) + .where(and(inArray(headcountSnapshots.id, ids), eq(headcountSnapshots.locked, false))) + .run(); + } + for (const s of targets) { + recordAudit(tx, audit, { + action: "headcount.snapshot_removed", + targetType: "headcount_snapshot", + targetId: s.id, + before: { + departmentId: s.departmentId, + month: s.month, + headcount: s.headcount, + source: s.source, + }, + comment: REBASE_REASON, + }); + } + tx.insert(meta) + .values({ + key: REBASE_META_KEY, + value: JSON.stringify({ removed: ids.length }), + updatedAt: audit.now.toISOString(), + }) + .run(); + return ids.length; + }); +} diff --git a/src/server/settlement/service.ts b/src/server/settlement/service.ts index 7e0b1c7..c37b201 100644 --- a/src/server/settlement/service.ts +++ b/src/server/settlement/service.ts @@ -1,12 +1,13 @@ import { and, asc, eq, inArray, isNull, max, ne } from "drizzle-orm"; import { localDate } from "@/domain/calendar"; +import { baseDateReached, capPendingMessage } from "@/domain/deadlines"; import { calculateSettlement, splitAcrossApplications, type SettlementResult, } from "@/domain/settlement"; import type { ApplicationStatus } from "@/lib/application-status"; -import { formatMoney } from "@/lib/format"; +import { APP_TIME_ZONE, formatMoney } from "@/lib/format"; import type { Role } from "@/lib/roles"; import type { AuditAction } from "@/lib/audit-actions"; import { @@ -303,7 +304,14 @@ function calculate( headcount: snapshot?.headcount ?? null, }, ); - if (!computed.ok) return fail(NO_SNAPSHOT_SETTLEMENT_MESSAGE); + if (!computed.ok) { + // 基準日(刷卡月份的下個月 1 日)前還沒有人數快照(rebase-headcount-snapshot)。 + return fail( + baseDateReached(month, now, APP_TIME_ZONE) + ? NO_SNAPSHOT_SETTLEMENT_MESSAGE + : capPendingMessage(month), + ); + } return ok({ result: computed.value, ruleVersionId: version.id, diff --git a/src/server/startup.ts b/src/server/startup.ts index f502358..372a766 100644 --- a/src/server/startup.ts +++ b/src/server/startup.ts @@ -4,10 +4,11 @@ import { getDatabase } from "@/server/db/client"; import { runMigrations } from "@/server/db/migrate"; import { getEnv } from "@/server/env"; import { ensureDefaultRuleVersion, ensureHalfSubsidyVersion } from "@/server/rules/params"; +import { rebaseHeadcountSnapshots } from "@/server/rules/rebase-snapshots"; import { startReminderScheduler } from "@/server/notifications/scheduler"; import { clearStalePendingReviews } from "@/server/notifications/service"; import { startSettlementScheduler } from "@/server/settlement/scheduler"; -import { appNow } from "@/server/clock"; +import { appNow, realNow, systemTimeAt } from "@/server/clock"; /** * 伺服器啟動檢查:驗證環境變數、建立附件目錄。設定錯誤讓伺服器無法啟動, @@ -29,6 +30,14 @@ export function migrateOnStartup(): void { runMigrations(db); ensureDefaultRuleVersion(db); ensureHalfSubsidyVersion(db); + // 人數快照基準日改為刷卡月份的下個月 1 日:一次性清掉基準日未到的舊快照(rebase-headcount-snapshot)。 + const real = realNow(); + const removed = rebaseHeadcountSnapshots( + db, + { actor: null, actorLabel: "系統", ip: null, now: systemTimeAt(real, db), realNow: real }, + getEnv().TZ_APP, + ); + if (removed) console.info(`[startup] 人數快照基準日變更:移除 ${removed} 筆基準日未到的快照`); } /** diff --git a/src/server/testing/applications.ts b/src/server/testing/applications.ts index 5adb7b8..53c0a3d 100644 --- a/src/server/testing/applications.ts +++ b/src/server/testing/applications.ts @@ -153,7 +153,7 @@ export const COMPLETE_FORM: ApplicationFormValues = { twdAmount: "899", foreignAmount: "20.00", currency: "USD", - cardDate: "2026-10-05", + cardDate: "2026-09-25", purpose: "整理客戶訪談逐字稿並產出會議摘要,每週節省約三小時", outcome: "完成 10 月份 12 場訪談摘要", outcomeUrl: "", diff --git a/tests/e2e/application-helpers.ts b/tests/e2e/application-helpers.ts index 62a1112..bccb481 100644 --- a/tests/e2e/application-helpers.ts +++ b/tests/e2e/application-helpers.ts @@ -1,4 +1,5 @@ import { expect, type Page } from "@playwright/test"; +import { claimDate } from "./db"; // 申請表單的共用操作(applications.spec、review.spec)。 @@ -13,9 +14,11 @@ export const CARD = { buffer: Buffer.from("%PDF-1.7\ncard"), }; -/** 今日(台北)`YYYY-MM-DD`:送出要在期限內,刷卡日期用今天。 */ -export const today = () => - new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Taipei" }).format(new Date()); +/** + * 系統時間的今天與可送出的刷卡日期(見 db.ts:e2e 期間系統時間固定在本月 10 日)。 + * 刷卡月份的下個月 1 日起才能送出,所以送出用上個月的日期。 + */ +export { claimDate, today } from "./db"; /** 平台以圖示卡片(radio)選擇;點選卡片文字所在的 label。 */ export async function choosePlatform(page: Page, name: string) { @@ -32,7 +35,7 @@ export async function fillComplete(page: Page) { await choosePlatform(page, "ChatGPT"); await page.getByLabel("訂閱方案/項目").fill("ChatGPT Plus"); await page.getByLabel("實際台幣支付金額").fill("898"); - await page.getByLabel("刷卡日期").fill(today()); + await page.getByLabel("刷卡日期").fill(claimDate()); await page.getByLabel("工作用途說明").fill("整理客戶訪談逐字稿並產出會議摘要,每週節省約三小時"); await page.getByLabel("成果產出").fill("完成本月 12 場訪談摘要"); await page.getByLabel("我確認以上資料真實,且訂閱用途符合工作需求。").check(); diff --git a/tests/e2e/applications.spec.ts b/tests/e2e/applications.spec.ts index 9f88c55..b4f175b 100644 --- a/tests/e2e/applications.spec.ts +++ b/tests/e2e/applications.spec.ts @@ -4,6 +4,7 @@ import { createEmployee, createTeam, simulateApproved, + monthsAgo, simulateReturnForRevision, transferEmployee, } from "./db"; @@ -11,6 +12,7 @@ import { PDF, choosePlatform, fillComplete, + claimDate, submitNew, today, uploadBoth, @@ -51,12 +53,16 @@ test.describe("新增申請頁", () => { await loginAs(page, createEmployee(), "/applications/new"); await page.getByLabel("刷卡日期").fill("2026-10-05"); await expect(aside(page).getByTestId("summary-month")).toHaveText("2026/10"); - await expect(aside(page).getByTestId("summary-deadline")).toHaveText("2026/11/20 23:59"); + await expect(aside(page).getByTestId("summary-deadline")).toHaveText( + "2026/11/01 – 2026/11/20 23:59", + ); await expect(page.getByLabel("申請月份")).toHaveValue("2026/10"); await page.getByLabel("刷卡日期").fill("2026-09-28"); await expect(aside(page).getByTestId("summary-month")).toHaveText("2026/09"); - await expect(aside(page).getByTestId("summary-deadline")).toHaveText("2026/10/20 23:59"); + await expect(aside(page).getByTestId("summary-deadline")).toHaveText( + "2026/10/01 – 2026/10/20 23:59", + ); await page.getByLabel("實際台幣支付金額").fill("898"); await expect(aside(page)).toContainText("NT$898"); @@ -70,18 +76,34 @@ test.describe("新增申請頁", () => { await expect(page.getByText("年度預算")).toHaveCount(0); }); - test("調部門後:部門欄位依刷卡月份 1 日的部門顯示", async ({ page }) => { + test("調部門後:部門欄位依基準日(刷卡月份的下個月 1 日)的部門顯示", async ({ page }) => { const before = createTeam(); const after = createTeam(); const employee = before.member("調動測試員"); - transferEmployee(employee, after.departmentId, `${today().slice(0, 7)}-02`); + transferEmployee(employee, after.departmentId, `${monthsAgo(0)}-02`); await loginAs(page, employee, "/applications/new"); // 還沒填刷卡日期:目前的部門 await expect(page.getByLabel("部門")).toHaveValue(after.departmentName); - // 本月 1 日還在原部門 - await page.getByLabel("刷卡日期").fill(`${today().slice(0, 7)}-01`); + // 上個月刷卡:基準日是本月 1 日,當天還在原部門 + await page.getByLabel("刷卡日期").fill(claimDate(20)); await expect(page.getByLabel("部門")).toHaveValue(before.departmentName); await expect(aside(page).getByTestId("summary-department")).toHaveText(before.departmentName); + // 本月刷卡:基準日是下個月 1 日,已在新部門 + await page.getByLabel("刷卡日期").fill(`${monthsAgo(0)}-01`); + await expect(page.getByLabel("部門")).toHaveValue(after.departmentName); + }); + + test("不得申請當月補助:本月刷卡只能存草稿,下個月 1 日起才能送出", async ({ page }) => { + await loginAs(page, createEmployee(), "/applications/new"); + await fillComplete(page); + await page.getByLabel("刷卡日期").fill(today()); + const [y, m] = monthsAgo(0).split("-"); + const next = + m === "12" ? `${Number(y) + 1}/01` : `${y}/${String(Number(m) + 1).padStart(2, "0")}`; + await expect(page.getByTestId("not-yet-open")).toContainText(`${next}/01 起才能送出`); + await expect(page.getByRole("button", { name: "送出申請" })).toBeDisabled(); + await page.getByRole("button", { name: "儲存草稿" }).click(); + await expect(page.getByText("已儲存草稿")).toBeVisible(); }); test("三項缺漏:頁首「尚有 3 項資料需完成」並聚焦工作用途說明", async ({ page }) => { @@ -89,7 +111,7 @@ test.describe("新增申請頁", () => { await choosePlatform(page, "ChatGPT"); await page.getByLabel("訂閱方案/項目").fill("ChatGPT Plus"); await page.getByLabel("實際台幣支付金額").fill("898"); - await page.getByLabel("刷卡日期").fill(today()); + await page.getByLabel("刷卡日期").fill(claimDate()); await page.getByLabel("成果產出").fill("完成本月訪談摘要"); await page.getByTestId("uploader-invoice").locator("input[type=file]").setInputFiles(PDF); await expect(page.getByTestId("uploaded-invoice")).toBeVisible(); diff --git a/tests/e2e/company-settlement.spec.ts b/tests/e2e/company-settlement.spec.ts index 101e727..a8de91e 100644 --- a/tests/e2e/company-settlement.spec.ts +++ b/tests/e2e/company-settlement.spec.ts @@ -250,7 +250,7 @@ test("代為提交逾期月結:總覽「逾期未提交」旁的按鈕;截 const row = overviewRow(page, t.departmentName); await expect(row).toContainText("逾期未提交"); await forceButton(t.departmentName).click(); - const dialog = page.getByRole("dialog"); + const dialog = page.getByRole("alertdialog"); await expect(dialog).toContainText("1 筆待審核、0 筆待補件案件將改為不核准"); await dialog.getByRole("button", { name: "下一步" }).click(); await expect(dialog.getByText("請填寫代提交原因")).toBeVisible(); diff --git a/tests/e2e/db.ts b/tests/e2e/db.ts index 9d76542..ecf6f07 100644 --- a/tests/e2e/db.ts +++ b/tests/e2e/db.ts @@ -108,9 +108,42 @@ export function createHrSyncedTeam(): Team & { hrMemberNo: string } { return { ...team, hrMemberNo }; } -const today = () => +/** 真實的今天(台北)`YYYY-MM-DD`。 */ +const realToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Taipei" }).format(new Date()); +/** + * e2e 期間伺服器的系統時間固定在本月 10 日 12:00(台北)附近(`pin-clock` setup project, + * rebase-headcount-snapshot):上個月刷卡的申請一定在可送出期間(本月 1–20 日)內, + * 上上個月的申請截止一定已過,本月刷卡的申請還不能送出。月份不變,`monthsAgo` 照真實月份算。 + */ +export const SYSTEM_DAY = 10; + +/** 系統時間的今天(台北)`YYYY-MM-DD`:本月 10 日。 */ +export const today = () => `${realToday().slice(0, 7)}-${String(SYSTEM_DAY).padStart(2, "0")}`; + +/** 可送出的刷卡日期:上個月的某一天(預設 15 日)。 */ +export const claimDate = (day = 15) => `${monthsAgo(1)}-${String(day).padStart(2, "0")}`; + +/** 把系統時間設為本月 10 日 12:00(台北),寫法與 `setClock` 相同(`_meta` 的 `clock_offset`)。 */ +export function pinSystemClock(): void { + const target = new Date(`${today()}T12:00:00+08:00`); + const now = new Date(); + const value = JSON.stringify({ + offsetMs: target.getTime() - now.getTime(), + setAt: now.toISOString(), + setBy: "e2e", + }); + withDb((db) => + db + .prepare( + `insert into _meta (key, value, updated_at) values ('clock_offset', ?, ?) + on conflict(key) do update set value = excluded.value, updated_at = excluded.updated_at`, + ) + .run(value, now.toISOString()), + ); +} + /** * 直接建立一筆待主管審核的申請(含送出的時間軸紀錄與實際附件檔),回傳申請 id。 * `attachments` 可只給部分類別,模擬資料不完整的案件。`cardDate`/`twdAmount`/`status` @@ -135,7 +168,7 @@ export function insertPendingApplication( const version = db.prepare("select id from rule_versions order by id desc limit 1").get() as { id: number; }; - const cardDate = opts.cardDate ?? today(); + const cardDate = opts.cardDate ?? claimDate(5); const now = new Date().toISOString(); const id = Number( db @@ -234,7 +267,7 @@ export function auditActionsFor(applicationId: number): string[] { /** 今天往前 `n` 個月的月份(`YYYY-MM`,台北時區)。往前 2 個月的申請截止一定已過。 */ export function monthsAgo(n: number): string { - const [y, m] = today().split("-").map(Number); + const [y, m] = realToday().split("-").map(Number); const index = y * 12 + (m - 1) - n; return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, "0")}`; } diff --git a/tests/e2e/mobile-layout.spec.ts b/tests/e2e/mobile-layout.spec.ts index 63930a5..7b5b212 100644 --- a/tests/e2e/mobile-layout.spec.ts +++ b/tests/e2e/mobile-layout.spec.ts @@ -59,7 +59,7 @@ for (const [user, paths] of PAGES) { test("360px:首頁額度卡的五位數月額度完整顯示在卡片內", async ({ page }) => { const team = createTeam(); const employee = team.member("額度卡員工"); - setHeadcount(team.departmentId, monthsAgo(0), 60); // 60 × 500 = NT$30,000 + setHeadcount(team.departmentId, monthsAgo(1), 60); // 60 × 500 = NT$30,000 await page.setViewportSize(MOBILE); await loginAs(page, employee, "/dashboard"); const card = page.getByTestId("quota-card"); @@ -69,7 +69,7 @@ test("360px:首頁額度卡的五位數月額度完整顯示在卡片內", asy test("桌面三欄:主管首頁的窄額度卡,六位數金額與分隔線、卡片邊框保持距離", async ({ page }) => { const team = createTeam(); - setHeadcount(team.departmentId, monthsAgo(0), 250); // 250 × 500 = NT$125,000 + setHeadcount(team.departmentId, monthsAgo(1), 250); // 250 × 500 = NT$125,000 await page.setViewportSize({ width: 1280, height: 900 }); await loginAs(page, team.managerNo!, "/dashboard"); const card = page.getByTestId("quota-card").first(); diff --git a/tests/e2e/pin-clock.setup.ts b/tests/e2e/pin-clock.setup.ts new file mode 100644 index 0000000..412d553 --- /dev/null +++ b/tests/e2e/pin-clock.setup.ts @@ -0,0 +1,8 @@ +import { test as setup } from "@playwright/test"; +import { pinSystemClock } from "./db"; + +// 所有 e2e(clock.spec 以外)執行前,把伺服器的系統時間固定在本月 10 日(見 db.ts 的 SYSTEM_DAY)。 +// 結束後由 pin-clock.teardown.ts 清除;clock.spec 自己再清除與設定。 +setup("系統時間固定在本月 10 日", () => { + pinSystemClock(); +}); diff --git a/tests/e2e/pin-clock.teardown.ts b/tests/e2e/pin-clock.teardown.ts new file mode 100644 index 0000000..f1627f5 --- /dev/null +++ b/tests/e2e/pin-clock.teardown.ts @@ -0,0 +1,6 @@ +import { test as teardown } from "@playwright/test"; +import { clearClockOffset } from "./db"; + +teardown("清除系統時間", () => { + clearClockOffset(); +}); diff --git a/tests/e2e/review-list.spec.ts b/tests/e2e/review-list.spec.ts index 74e47eb..0e80a1f 100644 --- a/tests/e2e/review-list.spec.ts +++ b/tests/e2e/review-list.spec.ts @@ -12,7 +12,8 @@ import { loginAs } from "./helpers"; // 部門審核的條列檢視與部門額度試算(application-review「條列審核檢視」「部門額度試算」)。 // 每個測試建立自己的部門與主管,表格只會出現該測試的案件。 -const MONTH = monthsAgo(0); +// 預設案件是上個月刷卡(可送出、基準日已到,有人數快照)。 +const MONTH = monthsAgo(1); const row = (page: Page, id: number) => page.getByTestId(`review-row-${id}`); const summary = (page: Page) => page.getByTestId("cap-summary"); diff --git a/tests/e2e/review-month-and-help.spec.ts b/tests/e2e/review-month-and-help.spec.ts index 9e0ebe7..54ef1ec 100644 --- a/tests/e2e/review-month-and-help.spec.ts +++ b/tests/e2e/review-month-and-help.spec.ts @@ -18,8 +18,15 @@ function twoMonthTeam() { const older = [1, 2].map((i) => insertPendingApplication(team.member(`上月${i}`), { cardDate: `${prev}-0${i}` }), ); - const current = [1, 2, 3].map((i) => insertPendingApplication(team.member(`本月${i}`))); - insertPendingApplication(team.member("本月已通過"), { status: "approved" }); + // 本月刷卡(直接寫入資料庫;畫面上本月還不能送出) + const now = monthsAgo(0); + const current = [1, 2, 3].map((i) => + insertPendingApplication(team.member(`本月${i}`), { cardDate: `${now}-0${i}` }), + ); + insertPendingApplication(team.member("本月已通過"), { + status: "approved", + cardDate: `${now}-04`, + }); return { team, prev, older, current }; } @@ -71,7 +78,7 @@ test("批次核准只含所選月份;首頁 ?id= 連結自動選該案件的 await table.getByRole("checkbox", { name: /選取/ }).nth(1).check(); await page.getByRole("button", { name: "批次核准" }).click(); await expect(page.getByText("已核准 2 筆")).toBeVisible(); - // 上個月過了員工截止日(每月 20 日後)核准會直接轉待月結 + // e2e 的系統時間在本月 10 日,上個月的員工截止(本月 20 日)還沒過;保留兩種狀態以防截止日參數變動 for (const status of older.map(applicationStatus)) { expect(["approved", "pending_settlement"]).toContain(status); } diff --git a/tests/e2e/settlement.spec.ts b/tests/e2e/settlement.spec.ts index 798c98e..af5ee38 100644 --- a/tests/e2e/settlement.spec.ts +++ b/tests/e2e/settlement.spec.ts @@ -13,10 +13,10 @@ import { import { DEMO, loginAs } from "./helpers"; // 每個測試建立自己的部門(createTeam)。往前 2 個月的申請截止一定已過,可以提交月結; -// 本月的申請截止一定未到。 +// 上個月的申請截止一定未到(e2e 系統時間固定在本月 10 日,見 db.ts)。 const MONTH = monthsAgo(2); -const CURRENT = monthsAgo(0); +const CURRENT = monthsAgo(1); const display = (month: string) => month.replace("-", "/"); // 匯出預覽最前面的刷卡月份與預計發放月份(刷卡月份 + 2) const MONTHS = `${display(MONTH)},${display(monthsAgo(0))}`;