add-app-shell, add-rule-settings: app frame, UI kit, versioned rule params, headcount snapshots
CI / build (push) Successful in 7m52s

- app-shell: (app) route group with topbar + role-based sidebar (collapsible,
  mobile drawer), Tailwind v4 design tokens, shared UI components (MoneyDisplay,
  StatusBadge, MonthPicker, ConfirmDialog, Field, ErrorSummary, Toast,
  EmptyState, DataTable), formatting helpers, /help and /faq, docs/ui-guide.md
- rule-settings: append-only versioned rule parameters with scheduled
  effective time, deadline derivation by card month, monthly headcount
  snapshots with audited adjustments and lock/unlock for settlement,
  /admin/settings params + headcount tabs; default version ensured on startup

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
pkgsp50777_楊舒諠
2026-10-08 11:07:40 +08:00
co-authored by Claude Opus 5.5
parent 09159aeba8
commit 326567f5b3
83 changed files with 8294 additions and 177 deletions
+16
View File
@@ -60,6 +60,22 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Tests: `seedAuditActor(db)` + `testAuditContext()` and `expectAudit(db, action, targetId)` / `auditRows(...)` from `src/server/testing/audit.ts`.
- `/admin/audit-log` is for sysadmins and admins with `users.can_view_audit_log` (granted on `/admin/accounts`); route rules support such flags via `grants` in `ROUTE_RULES`.
## Rule parameters & headcount (rule-settings)
- **Never hard-code rule values** (quota, 50% ratio, rounding, deadlines, platforms, attachment limits). 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`).
- 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.
## UI (app-shell)
- **Read `docs/ui-guide.md` before building pages.** Logged-in pages live under `src/app/(app)/` (shared frame: topbar, role-based sidebar); don't render `<main>`; start with `PageHeader`; one primary action per view.
- Styling: Tailwind CSS v4 with design tokens in `src/app/globals.css` (`@theme`) — use token classes (`bg-primary`, `text-muted`, `rounded-card`…), never hard-coded colors, never dynamically built class names.
- Formatting only via `src/lib/format.ts` / `MoneyDisplay` / `StatusBadge` (status labels from `src/lib/application-status.ts`); shared components in `src/components/ui/` (ConfirmDialog for irreversible actions, Field/ErrorSummary for forms, DataTable for lists).
- Component tests: `// @vitest-environment jsdom` + Testing Library.
## Code layout
- `src/app/` — Next.js routes (pages, Route Handlers).
+91
View File
@@ -0,0 +1,91 @@
# 介面開發指引(app-shell)
後續每個 change 的頁面都放在全站框架內,使用這裡的 tokens、元件與格式化工具。
**不要寫死色碼、不要自行格式化金額與日期、不要自己畫狀態標籤。**
視覺依據:`docs/風格2_首頁.png`、`docs/風格2_新增申請頁.png`;欄位與文案以規格文件與介面規劃為準
(差異處理見 `openspec/changes/plan-system-roadmap/design.md` D9)。開發登入模式下可開啟
`/design-tokens` 查看色彩、字級與元件範例表單。
## 頁面骨架
登入後的頁面放在 `src/app/(app)/` 底下,自動套用框架(頂部列、依角色側欄、主內容區)。
```tsx
import { Card, PageHeader, WithAside } from "@/components/page-header";
import { requireRouteAccess } from "@/server/auth/current-user";
export default async function Page() {
await requireRouteAccess("/applications"); // 每頁都要;路由須列在 src/lib/access.ts 的 ROUTE_RULES
return (
<div className="space-y-6">
<PageHeader title="我的申請" description="查看申請進度與補件需求。" actions={<主要按鈕 />} />
<WithAside aside={<Card title="截止日">…</Card>}>
<Card title="申請清單">…</Card>
</WithAside>
</div>
);
}
```
- **不要在頁面裡放 `<main>`**,框架已經提供。
- `PageHeader` 的 `actions`:一個頁面只有一個主要操作;手機寬度會自動變成畫面底部固定操作列。
表單底部的按鈕用 `StickyActions` 包起來,效果相同。
- 新增導覽項目:在 `src/lib/navigation.ts` 的 `NAV_ITEMS` 加一筆,並在 `ROUTE_RULES` 設定角色;側欄與權限檢查共用同一份設定。
## 設計 tokens
定義在 `src/app/globals.css` 的 `@theme`,以 Tailwind 類別使用:
| 用途 | 類別 |
|---|---|
| 頁面底色/卡片 | `bg-canvas`、`bg-surface` |
| 文字 | `text-ink`(主要)、`text-muted`(次要) |
| 主要按鈕 | `bg-primary hover:bg-primary-hover text-on-primary` |
| 強調、連結、導覽選中 | `text-accent`、`bg-accent-soft` |
| 語意色 | `success`、`warning`、`danger`、`info`、`violet`、`neutral`(各有 `-soft` 淺底) |
| 圓角、陰影 | `rounded-control`(輸入框、按鈕)、`rounded-card`、`shadow-card`、`shadow-overlay` |
Tailwind 只認得原始碼中**完整寫出**的類別名稱,不能用 `` `text-${tone}` `` 動態組合;需要依條件變化時,用對照表列出完整類別(參考 `src/components/ui/status-badge.tsx`)。
斷點:手機 < 768px(`md:` 以下)、平板 768–1279px、桌機 ≥ 1280px(`xl:`)。
## 格式化(`src/lib/format.ts`)
| 函式 | 輸出 | 說明 |
|---|---|---|
| `formatMoney(13000)` | `NT$13,000` | 尚無數值(`null`)顯示 `--` |
| `formatDate("2026-10-05")` | `2026/10/05` | 純日期直接轉換;時間點以 Asia/Taipei 換算 |
| `formatMonth("2026-10-05")` | `2026/10` | 也接受 `YYYY-MM` |
| `formatDateTime(iso)` | `2026/10/01 08:30:00` | 操作紀錄等 |
| `formatLongDate(date)` | `2026 年 10 月 1 日 星期四` | 頂部列 |
## 共用元件(`src/components/ui/`)
| 元件 | 用途 |
|---|---|
| `MoneyDisplay` | 金額。月結前用 `kind="estimate"`(顯示「預估」),月結後 `kind="final"`(「最終」);`emphasis` 為綠色強調 |
| `StatusBadge` | 案件狀態,文字依 `src/lib/application-status.ts`(例如 `pending_review` →「待審核」);其他狀態用 `ToneBadge` |
| `MonthPicker` | 月份選擇,值 `YYYY-MM`、顯示 `YYYY/MM` |
| `ConfirmDialog` | 不核准、提交月結、最終核定、標記已發放等重要操作;`description` 寫清楚後果;取消不執行 |
| `Field` + `inputClass` | 表單欄位:標籤永遠可見、必填標示、說明、inline 錯誤(自動帶 aria 屬性) |
| `ErrorSummary` | 送出時「尚有 N 項資料需完成」,並捲動到第一個錯誤欄位(`field` 對應 `Field` 的 `id`) |
| `Alert` | 頁面內提示(info/success/warning/danger) |
| `useToast()` | 系統層級的成功/失敗提示(框架已放好 `Toaster`) |
| `EmptyState` | 無資料時的說明與下一步 |
| `DataTable` | 資料表格;手機自動改為卡片,只顯示 `essential: true` 的欄位;無資料顯示空狀態 |
對話框、下拉選單用 Radix UI(`@radix-ui/react-dialog`、`@radix-ui/react-dropdown-menu`),已處理鍵盤操作與無障礙。
注意:Radix 選單關閉時會移除選單內容,選單裡不要放 `<form>`——把表單放在選單外,在 `onSelect` 呼叫 `requestSubmit()`(見 `src/components/shell/app-frame.tsx` 的登出)。
## 常見陷阱
- **不要依賴前端狀態決定欄位是否出現**(例如勾選某選項後才顯示輸入框):頁面尚未完成 hydration 時,使用者的點選不會觸發 React 的 `onChange`。改為一律顯示,由伺服器依選項決定是否採用。
- **Server Action 搭配 `revalidatePath` 時,帶 `key` 的元件會被重建**,元件內的 `useActionState` 狀態會遺失。成功提示等狀態放在不帶 key 的外層元件。
## 測試
- 元件測試:檔案開頭加 `// @vitest-environment jsdom`,用 `@testing-library/react`(參考 `src/components/ui/components.test.tsx`)。
- 版面與響應式:Playwright(`tests/e2e/shell.spec.ts`),用 `page.setViewportSize` 驗證 375/768/1280px。
- e2e 不要用 `getByRole("alert")`:Next.js 的路由播報元素 `#__next-route-announcer__` 也是 `role="alert"`,改用 `getByText` 比對訊息。
- `DataTable` 會同時輸出表格與卡片(依斷點顯示其一),定位元素時先限定在 `page.locator("table")` 內,避免同一個 testid 出現兩次。
+13 -13
View File
@@ -2,28 +2,28 @@
## 1. 設計 tokens 與基礎樣式
- [ ] 1.1 依風格稿定義 CSS 變數 tokens(色彩、字級、圓角、陰影、間距)並接入 Tailwind 設定,建立 tokens 展示頁確認與風格稿色調一致
- [ ] 1.2 安裝並設定 headless 元件套件(對話框、下拉選單),確認 `npm run build` 成功
- [x] 1.1 依風格稿定義 CSS 變數 tokens(色彩、字級、圓角、陰影、間距)並接入 Tailwind 設定,建立 tokens 展示頁確認與風格稿色調一致
- [x] 1.2 安裝並設定 headless 元件套件(對話框、下拉選單),確認 `npm run build` 成功
## 2. 格式化與狀態對照
- [ ] 2.1 實作 formatMoney(NT$+千分位、空值「--」)、formatDate(YYYY/MM/DD,Asia/Taipei)、formatMonth(YYYY/MM),以 Vitest 驗證 spec 中的範例
- [ ] 2.2 建立案件狀態代碼 → 標籤文字/語意色對照表(介面規劃 §9),以 Vitest 驗證「待主管審核」顯示「待審核」且每個狀態都有文字
- [x] 2.1 實作 formatMoney(NT$+千分位、空值「--」)、formatDate(YYYY/MM/DD,Asia/Taipei)、formatMonth(YYYY/MM),以 Vitest 驗證 spec 中的範例
- [x] 2.2 建立案件狀態代碼 → 標籤文字/語意色對照表(介面規劃 §9),以 Vitest 驗證「待主管審核」顯示「待審核」且每個狀態都有文字
## 3. 全站框架與導覽
- [ ] 3.1 建立登入後 layout(頂部列:系統名稱、今日日期含星期、通知入口、姓名/部門、使用者選單與登出;側欄;內容標題列;選用右側輔助區),以 Playwright 驗證登入後頂部列內容正確、未登入導向登入頁
- [ ] 3.2 建立角色 → 導覽項目設定表與側欄元件(聯集去重、目前頁高亮),以 Vitest 驗證各角色組合的項目清單,以 Playwright 驗證員工看不到部門審核
- [ ] 3.3 建立 `/dashboard` 佔位頁、`/help` 使用說明與 `/faq` 常見問題靜態頁(含「最終金額於月結後確認」說明),以 Playwright 驗證可開啟
- [x] 3.1 建立登入後 layout(頂部列:系統名稱、今日日期含星期、通知入口、姓名/部門、使用者選單與登出;側欄;內容標題列;選用右側輔助區),以 Playwright 驗證登入後頂部列內容正確、未登入導向登入頁
- [x] 3.2 建立角色 → 導覽項目設定表與側欄元件(聯集去重、目前頁高亮),以 Vitest 驗證各角色組合的項目清單,以 Playwright 驗證員工看不到部門審核
- [x] 3.3 建立 `/dashboard` 佔位頁、`/help` 使用說明與 `/faq` 常見問題靜態頁(含「最終金額於月結後確認」說明),以 Playwright 驗證可開啟
## 4. 共用元件
- [ ] 4.1 實作 MoneyDisplay、StatusBadge、MonthPicker,以元件測試驗證輸出格式與標籤文字
- [ ] 4.2 實作 ConfirmDialog(取消不執行、確認才回呼),以元件測試驗證取消時回呼未被呼叫
- [ ] 4.3 實作 ErrorSummary(錯誤數量、捲動至第一個錯誤欄位)、inline 欄位錯誤樣式與 Toast/Alert,以 Playwright 在範例表單驗證「尚有 3 項資料需完成」與捲動行為
- [ ] 4.4 實作 EmptyState 與可切換卡片模式的資料表格元件,以元件測試驗證無資料時顯示空狀態
- [x] 4.1 實作 MoneyDisplay、StatusBadge、MonthPicker,以元件測試驗證輸出格式與標籤文字
- [x] 4.2 實作 ConfirmDialog(取消不執行、確認才回呼),以元件測試驗證取消時回呼未被呼叫
- [x] 4.3 實作 ErrorSummary(錯誤數量、捲動至第一個錯誤欄位)、inline 欄位錯誤樣式與 Toast/Alert,以 Playwright 在範例表單驗證「尚有 3 項資料需完成」與捲動行為
- [x] 4.4 實作 EmptyState 與可切換卡片模式的資料表格元件,以元件測試驗證無資料時顯示空狀態
## 5. 響應式
- [ ] 5.1 實作手機漢堡選單、平板可收合側欄、手機底部固定操作列,以 Playwright 在 375px/768px/1280px 驗證無水平捲動、按鈕未被遮擋
- [ ] 5.2 在 `docs/` 或專案 README 記錄 tokens、共用元件與格式化規則的使用方式,確認後續 change 可依文件使用
- [x] 5.1 實作手機漢堡選單、平板可收合側欄、手機底部固定操作列,以 Playwright 在 375px/768px/1280px 驗證無水平捲動、按鈕未被遮擋
- [x] 5.2 在 `docs/` 或專案 README 記錄 tokens、共用元件與格式化規則的使用方式,確認後續 change 可依文件使用
+16 -16
View File
@@ -2,28 +2,28 @@
## 1. 資料模型與 migration
- [ ] 1.1 以 Drizzle 定義制度參數版本表(完整參數 JSON、effective_at、created_by、reason、created_at),執行 migration 並確認資料表建立成功
- [ ] 1.2 定義部門月人數快照表(部門、月份唯一鍵、人數、locked)與快照調整紀錄表,執行 migration 並以單元測試確認同一部門同月無法建立兩筆
- [ ] 1.3 撰寫 seed 建立初始參數版本(規格 §16 預設值、取整無條件捨去、無個人上限),執行 seed 後查詢確認內容正確
- [x] 1.1 以 Drizzle 定義制度參數版本表(完整參數 JSON、effective_at、created_by、reason、created_at),執行 migration 並確認資料表建立成功
- [x] 1.2 定義部門月人數快照表(部門、月份唯一鍵、人數、locked)與快照調整紀錄表,執行 migration 並以單元測試確認同一部門同月無法建立兩筆
- [x] 1.3 撰寫 seed 建立初始參數版本(規格 §16 預設值、取整無條件捨去、無個人上限),執行 seed 後查詢確認內容正確
## 2. 參數服務
- [ ] 2.1 以 Zod 定義參數 schema 與驗證規則(額度正整數、比例 1–100、截止日 1–28 且主管 > 員工、平台不重複且至少一項、附件 1–50 MB 與格式限 PDF/JPG/PNG),並以 Vitest 涵蓋 spec 中的錯誤情境
- [ ] 2.2 實作「儲存新版本」(原因必填、生效時間不得早於現在、寫入 audit-trail),以 Vitest 驗證舊版本不被修改且操作紀錄寫入
- [ ] 2.3 實作「取得某時間點生效參數」,以 Vitest 驗證變更前時間點與排定生效版本兩個情境
- [ ] 2.4 實作「推導截止日(刷卡日期)」使用刷卡月份結束時的版本與 Asia/Taipei,以 Vitest 驗證 2026/10/05 → 11/20、11/25 23:59:59 及 2026/12/31 → 2027/01/20
- [ ] 2.5 實作平台選項查詢(主要平台+固定「其他」),以 Vitest 驗證「其他」無法移除且移除平台不影響既有資料
- [x] 2.1 以 Zod 定義參數 schema 與驗證規則(額度正整數、比例 1–100、截止日 1–28 且主管 > 員工、平台不重複且至少一項、附件 1–50 MB 與格式限 PDF/JPG/PNG),並以 Vitest 涵蓋 spec 中的錯誤情境
- [x] 2.2 實作「儲存新版本」(原因必填、生效時間不得早於現在、寫入 audit-trail),以 Vitest 驗證舊版本不被修改且操作紀錄寫入
- [x] 2.3 實作「取得某時間點生效參數」,以 Vitest 驗證變更前時間點與排定生效版本兩個情境
- [x] 2.4 實作「推導截止日(刷卡日期)」使用刷卡月份結束時的版本與 Asia/Taipei,以 Vitest 驗證 2026/10/05 → 11/20、11/25 23:59:59 及 2026/12/31 → 2027/01/20
- [x] 2.5 實作平台選項查詢(主要平台+固定「其他」),以 Vitest 驗證「其他」無法移除且移除平台不影響既有資料
## 3. 人數快照服務
- [ ] 3.1 實作快照建立(以該月 1 日 00:00 Asia/Taipei 的部門人員計算;懶建立+手動觸發;重複建立回傳已存在),以 Vitest 驗證月中到職不影響當月快照
- [ ] 3.2 實作人工調整(非負整數、原因必填、保存前後值、寫 audit-trail、鎖定時拒絕),以 Vitest 驗證各情境
- [ ] 3.3 實作鎖定/解鎖介面供 change 9/10 呼叫,以 Vitest 驗證鎖定後調整被拒、解鎖後可調整
- [ ] 3.4 實作部門月上限查詢(一般/研發每人額度 × 快照人數;無快照回傳「尚未建立人數快照」),以 Vitest 驗證 20×500=10,000、2×1,000=2,000 與無快照情境
- [x] 3.1 實作快照建立(以該月 1 日 00:00 Asia/Taipei 的部門人員計算;懶建立+手動觸發;重複建立回傳已存在),以 Vitest 驗證月中到職不影響當月快照
- [x] 3.2 實作人工調整(非負整數、原因必填、保存前後值、寫 audit-trail、鎖定時拒絕),以 Vitest 驗證各情境
- [x] 3.3 實作鎖定/解鎖介面供 change 9/10 呼叫,以 Vitest 驗證鎖定後調整被拒、解鎖後可調整
- [x] 3.4 實作部門月上限查詢(一般/研發每人額度 × 快照人數;無快照回傳「尚未建立人數快照」),以 Vitest 驗證 20×500=10,000、2×1,000=2,000 與無快照情境
## 4. 後台設定頁 FE-09
- [ ] 4.1 建立 `/admin/settings` 頁面與伺服器端權限檢查(僅管理者、系統管理員),以 Playwright 驗證一般員工直接輸入網址被拒且無資料外洩
- [ ] 4.2 實作參數編輯表單(inline 錯誤、原因必填、生效時間選擇、儲存確認視窗),以 Playwright 驗證儲存後產生新版本並顯示於版本紀錄
- [ ] 4.3 實作版本紀錄清單(新到舊、操作者、原因、差異欄位、排定生效標示),以 Playwright 驗證排定生效版本正確標示
- [ ] 4.4 實作人數快照分頁(月份切換、人數、類型、月上限、鎖定狀態、調整紀錄展開、手動建立與調整),以 Playwright 驗證調整流程與鎖定時的錯誤提示
- [x] 4.1 建立 `/admin/settings` 頁面與伺服器端權限檢查(僅管理者、系統管理員),以 Playwright 驗證一般員工直接輸入網址被拒且無資料外洩
- [x] 4.2 實作參數編輯表單(inline 錯誤、原因必填、生效時間選擇、儲存確認視窗),以 Playwright 驗證儲存後產生新版本並顯示於版本紀錄
- [x] 4.3 實作版本紀錄清單(新到舊、操作者、原因、差異欄位、排定生效標示),以 Playwright 驗證排定生效版本正確標示
- [x] 4.4 實作人數快照分頁(月份切換、人數、類型、月上限、鎖定狀態、調整紀錄展開、手動建立與調整),以 Playwright 驗證調整流程與鎖定時的錯誤提示
+2031 -13
View File
File diff suppressed because it is too large Load Diff
+8
View File
@@ -20,16 +20,23 @@
"test:e2e:prepare": "tsx scripts/e2e-prepare.ts"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.2.0",
"@radix-ui/react-dropdown-menu": "^2.1.25",
"@tailwindcss/postcss": "^4.3.3",
"better-sqlite3": "^13.0.3",
"drizzle-orm": "^0.45.3",
"next": "16.3.8",
"openid-client": "^6.8.8",
"react": "19.2.8",
"react-dom": "19.2.8",
"tailwindcss": "^4.3.3",
"zod": "^4.6.5"
},
"devDependencies": {
"@playwright/test": "^1.63.0",
"@testing-library/dom": "^10.4.2",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.7",
"@types/better-sqlite3": "^9.6.0",
"@types/node": "^24.19.1",
"@types/react": "^19",
@@ -38,6 +45,7 @@
"eslint": "^9",
"eslint-config-next": "16.3.8",
"eslint-config-prettier": "^10.1.8",
"jsdom": "^30.1.2",
"prettier": "^3.9.9",
"tsx": "^4.23.15",
"typescript": "^5",
+8
View File
@@ -0,0 +1,8 @@
// Tailwind CSS v4 透過 PostCSS 外掛接入 Next.js。
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
@@ -1,3 +1,4 @@
import { PageHeader } from "@/components/page-header";
import Link from "next/link";
import { requireRouteAccess } from "@/server/auth/current-user";
import { ImportForm } from "./import-form";
@@ -5,8 +6,8 @@ import { ImportForm } from "./import-form";
export default async function ImportRosterPage() {
await requireRouteAccess("/admin/accounts/import");
return (
<main>
<h1>匯入名冊</h1>
<div className="space-y-6">
<PageHeader title="匯入名冊" />
<p>
欄位:員工編號(必填)、姓名、部門(部門代碼或名稱,必填)、角色(選填,多個以「、」分隔)。
以員工編號比對:已存在者更新部門與角色,不存在者建立尚未登入的人員。角色欄留空不變更既有角色。
@@ -20,6 +21,6 @@ export default async function ImportRosterPage() {
<Link href="/admin/accounts">回帳號與角色</Link>
</p>
<ImportForm />
</main>
</div>
);
}
@@ -1,3 +1,4 @@
import { PageHeader } from "@/components/page-header";
import Link from "next/link";
import { localDate } from "@/domain/calendar";
import { ROLES, ROLE_LABELS } from "@/lib/roles";
@@ -37,8 +38,11 @@ export default async function AccountsPage({
const back = `/admin/accounts?filter=${filter}`;
return (
<main>
<h1>帳號與角色</h1>
<div className="space-y-6">
<PageHeader
title="帳號與角色"
description="指派部門、角色與停用帳號;新進人員首次登入後會出現在「待指派部門」。"
/>
<p>
<Link href="/admin/accounts/import">匯入名冊 CSV</Link>
</p>
@@ -152,6 +156,6 @@ export default async function AccountsPage({
</tbody>
</table>
)}
</main>
</div>
);
}
@@ -1,3 +1,4 @@
import { PageHeader } from "@/components/page-header";
import Link from "next/link";
import {
AUDIT_ACTIONS,
@@ -13,6 +14,8 @@ import {
listAuditLogs,
type AuditFilters,
} from "@/server/audit/query";
import { Card } from "@/components/page-header";
import { DataTable } from "@/components/ui/data-table";
import { requireRouteAccess } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import { getEnv } from "@/server/env";
@@ -59,10 +62,18 @@ export default async function AuditLogPage({
const detail = Number.isInteger(detailId) && detailId > 0 ? getAuditLog(db, detailId) : null;
return (
<main>
<h1>操作紀錄</h1>
<div className="space-y-6">
<PageHeader
title="操作紀錄"
description="所有帳號、部門、登入與業務操作的紀錄,只能新增、不能修改或刪除。"
/>
<form method="get" action={PAGE} aria-label="篩選操作紀錄">
<form
method="get"
action={PAGE}
aria-label="篩選操作紀錄"
className="grid items-end gap-4 rounded-card bg-surface p-5 shadow-card sm:grid-cols-2 lg:grid-cols-4 [&_label]:flex [&_label]:flex-col [&_label]:gap-1.5 [&_label]:text-sm [&_label]:font-medium"
>
<label>
起日 <input type="date" name="from" defaultValue={filters.from} />
</label>
@@ -101,41 +112,54 @@ export default async function AuditLogPage({
<Link href={PAGE}>清除條件</Link>
</form>
{rows.length === 0 ? (
<p role="status">查無符合條件的操作紀錄</p>
) : (
<table>
<thead>
<tr>
<th>時間</th>
<th>操作者</th>
<th>動作</th>
<th>對象</th>
<th>意見</th>
<th>詳情</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id} data-testid={`audit-${row.id}`}>
<td>{formatDateTime(row.occurredAt, timeZone)}</td>
<td>{row.actorLabel}</td>
<td>{auditActionLabel(row.action)}</td>
<td>
{auditTargetTypeLabel(row.targetType)}
{row.targetId ? ` #${row.targetId}` : ""}
</td>
<td>{row.comment ?? ""}</td>
<td>
<Link href={hrefWith(filters, { cursor, detail: String(row.id) })} scroll={false}>
查看
</Link>
</td>
</tr>
))}
</tbody>
</table>
)}
<Card>
<DataTable
caption="操作紀錄"
rows={rows}
rowKey={(row) => row.id}
empty={{
title: "查無符合條件的操作紀錄",
description: "請調整時間區間或其他篩選條件。",
}}
columns={[
{
key: "time",
header: "時間",
essential: true,
render: (row) => formatDateTime(row.occurredAt, timeZone),
},
{ key: "actor", header: "操作者", render: (row) => row.actorLabel },
{
key: "action",
header: "動作",
essential: true,
render: (row) => auditActionLabel(row.action),
},
{
key: "target",
header: "對象",
essential: true,
render: (row) =>
`${auditTargetTypeLabel(row.targetType)}${row.targetId ? ` #${row.targetId}` : ""}`,
},
{ key: "comment", header: "意見", render: (row) => row.comment ?? "" },
{
key: "detail",
header: "詳情",
essential: true,
render: (row) => (
<Link
href={hrefWith(filters, { cursor, detail: String(row.id) })}
scroll={false}
className="text-accent underline underline-offset-2"
>
查看
</Link>
),
},
]}
/>
</Card>
<nav aria-label="分頁">
{cursor && <Link href={hrefWith(filters, {})}>回第一頁</Link>}
@@ -143,7 +167,11 @@ export default async function AuditLogPage({
</nav>
{detail && (
<aside aria-labelledby="audit-detail-title" role="dialog">
<aside
aria-labelledby="audit-detail-title"
role="dialog"
className="fixed inset-y-0 right-0 z-40 w-full max-w-md space-y-4 overflow-y-auto border-l border-border bg-surface p-6 shadow-overlay"
>
<h2 id="audit-detail-title">
{auditActionLabel(detail.action)}:{auditTargetTypeLabel(detail.targetType)}
{detail.targetId ? ` #${detail.targetId}` : ""}
@@ -185,6 +213,6 @@ export default async function AuditLogPage({
</Link>
</aside>
)}
</main>
</div>
);
}
@@ -1,3 +1,4 @@
import { PageHeader } from "@/components/page-header";
import { DEPARTMENT_TYPES, DEPARTMENT_TYPE_LABELS } from "@/lib/department-types";
import { requireRouteAccess } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
@@ -33,8 +34,11 @@ export default async function DepartmentsPage({
const departments = listDepartments(getDb());
return (
<main>
<h1>部門管理</h1>
<div className="space-y-6">
<PageHeader
title="部門管理"
description="維護部門代碼、類型(一般/研發)與部門主管。部門不能刪除,只能停用。"
/>
{error && <p role="alert">{error}</p>}
<section aria-labelledby="new-department">
@@ -111,6 +115,6 @@ export default async function DepartmentsPage({
</table>
)}
</section>
</main>
</div>
);
}
+112
View File
@@ -0,0 +1,112 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { localDateTimeToInstant } from "@/domain/calendar";
import { ATTACHMENT_FORMATS } from "@/lib/rule-params";
import { auditContextFor } from "@/server/audit/action-context";
import { requireRole } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import { getEnv } from "@/server/env";
import {
adjustHeadcount,
createDepartmentSnapshot,
ensureMonthSnapshots,
} from "@/server/rules/headcount";
import { saveRuleVersion } from "@/server/rules/params";
const PAGE = "/admin/settings";
export type SaveParamsState =
| { status: "idle" }
| { status: "saved"; scheduled: boolean }
| { status: "error"; message: string; fieldErrors: Record<string, string> };
const int = (form: FormData, key: string) => {
const raw = String(form.get(key) ?? "").trim();
return raw === "" ? Number.NaN : Number(raw);
};
/** 儲存制度參數新版本(管理者、系統管理員)。驗證錯誤以欄位回傳,表單就地顯示。 */
export async function saveParamsAction(
_prev: SaveParamsState,
form: FormData,
): Promise<SaveParamsState> {
const user = await requireRole("admin", "sysadmin");
const audit = await auditContextFor(user);
const timeZone = getEnv().TZ_APP;
let effectiveAt: string | null = null;
if (form.get("effectiveMode") === "scheduled") {
const instant = localDateTimeToInstant(String(form.get("effectiveAt") ?? ""), timeZone);
if (!instant) {
return {
status: "error",
message: "尚有 1 項資料需修正",
fieldErrors: { effectiveAt: "請選擇生效時間" },
};
}
effectiveAt = instant.toISOString();
}
const result = saveRuleVersion(getDb(), audit, {
params: {
perPersonQuota: { general: int(form, "general"), rnd: int(form, "rnd") },
subsidyRatePercent: int(form, "subsidyRatePercent"),
rounding: String(form.get("rounding") ?? ""),
employeeDeadlineDay: int(form, "employeeDeadlineDay"),
managerDeadlineDay: int(form, "managerDeadlineDay"),
platforms: String(form.get("platforms") ?? "")
.split(/\r?\n/)
.map((p) => p.trim())
.filter(Boolean),
attachment: {
maxSizeMb: int(form, "maxSizeMb"),
formats: ATTACHMENT_FORMATS.filter((f) => form.getAll("formats").includes(f)),
},
},
reason: String(form.get("reason") ?? ""),
effectiveAt,
});
if (!result.ok)
return { status: "error", message: result.error, fieldErrors: result.fieldErrors };
revalidatePath(PAGE);
return { status: "saved", scheduled: effectiveAt !== null };
}
function back(month: string, error?: string) {
const params = new URLSearchParams({ tab: "headcount", month });
if (error) params.set("error", error);
redirect(`${PAGE}?${params}`);
}
/** 手動建立某月份尚未建立的快照(全部部門,或指定單一部門)。 */
export async function createSnapshotsAction(form: FormData) {
const user = await requireRole("admin", "sysadmin");
const audit = await auditContextFor(user);
const month = String(form.get("month") ?? "");
const departmentId = Number(form.get("departmentId") ?? 0);
const timeZone = getEnv().TZ_APP;
const result = departmentId
? createDepartmentSnapshot(getDb(), audit, departmentId, month, timeZone)
: ensureMonthSnapshots(getDb(), audit, month, timeZone);
revalidatePath(PAGE);
back(month, result.ok ? undefined : result.error);
}
/** 人工調整快照人數(原因必填;鎖定時拒絕)。 */
export async function adjustHeadcountAction(form: FormData) {
const user = await requireRole("admin", "sysadmin");
const audit = await auditContextFor(user);
const month = String(form.get("month") ?? "");
const raw = String(form.get("headcount") ?? "").trim();
const result = adjustHeadcount(
getDb(),
audit,
Number(form.get("snapshotId")),
raw === "" ? Number.NaN : Number(raw),
String(form.get("reason") ?? ""),
);
revalidatePath(PAGE);
back(month, result.ok ? undefined : result.error);
}
@@ -0,0 +1,20 @@
"use client";
import { useRouter } from "next/navigation";
import { MonthPicker } from "@/components/ui/month-picker";
/** 人數快照分頁的月份切換:改變月份即導向該月份。 */
export function MonthNav({ month, min, max }: { month: string; min: string; max: string }) {
const router = useRouter();
return (
<div className="w-40">
<MonthPicker
label="月份"
value={month}
min={min}
max={max}
onChange={(next) => router.push(`/admin/settings?tab=headcount&month=${next}`)}
/>
</div>
);
}
+298
View File
@@ -0,0 +1,298 @@
import Link from "next/link";
import { instantToLocalDateTime, localDate } from "@/domain/calendar";
import { monthStart, nextMonth } from "@/domain/deadlines";
import { Card, PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { DataTable } from "@/components/ui/data-table";
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 {
ATTACHMENT_FORMAT_LABELS,
ROUNDING_LABELS,
RULE_PARAM_LABELS,
type RuleParams,
} from "@/lib/rule-params";
import { auditContextFor } from "@/server/audit/action-context";
import { requireRouteAccess } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import { getEnv } from "@/server/env";
import {
NO_SNAPSHOT_MESSAGE,
ensureMonthSnapshots,
listMonthSnapshots,
} from "@/server/rules/headcount";
import { listRuleVersions, type VersionStatus } from "@/server/rules/params";
import { adjustHeadcountAction, createSnapshotsAction } from "./actions";
import { MonthNav } from "./month-nav";
import { ParamsForm } from "./params-form";
const STATUS_BADGE: Record<VersionStatus, { label: string; tone: "success" | "info" | "neutral" }> =
{
current: { label: "目前生效", tone: "success" },
scheduled: { label: "排定生效", tone: "info" },
superseded: { label: "已取代", tone: "neutral" },
};
function formatParamValue(field: string, value: unknown): string {
if (field === "rounding")
return ROUNDING_LABELS[value as RuleParams["rounding"]] ?? String(value);
if (field === "attachment.formats") {
return (value as RuleParams["attachment"]["formats"])
.map((f) => ATTACHMENT_FORMAT_LABELS[f])
.join("、");
}
if (Array.isArray(value)) return value.join("、");
return String(value);
}
type SearchParams = Promise<{ tab?: string; month?: string; error?: string }>;
export default async function SettingsPage({ searchParams }: { searchParams: SearchParams }) {
const user = await requireRouteAccess("/admin/settings");
const { tab, month: rawMonth, error } = await searchParams;
const timeZone = getEnv().TZ_APP;
const now = new Date();
const currentMonth = localDate(now, timeZone).slice(0, 7);
const active = tab === "headcount" ? "headcount" : "params";
const tabs = [
{ key: "params", label: "制度參數", href: "/admin/settings" },
{ key: "headcount", label: "人數快照", href: "/admin/settings?tab=headcount" },
];
return (
<div className="space-y-6">
<PageHeader
title="後台設定"
description="制度參數的每次變更都會建立新版本並留下紀錄;部門月上限以每月人數快照計算。"
/>
<nav aria-label="設定分頁" className="flex gap-2 border-b border-border">
{tabs.map((t) => (
<Link
key={t.key}
href={t.href}
aria-current={t.key === active ? "page" : undefined}
className={`-mb-px border-b-2 px-4 py-2 ${
t.key === active
? "border-accent font-semibold text-ink"
: "border-transparent text-muted hover:text-ink"
}`}
>
{t.label}
</Link>
))}
</nav>
{error && <Alert tone="danger">{error}</Alert>}
{active === "params" ? (
<ParamsTab now={now} timeZone={timeZone} />
) : (
<HeadcountTab
month={/^\d{4}-\d{2}$/.test(rawMonth ?? "") ? rawMonth! : currentMonth}
currentMonth={currentMonth}
now={now}
timeZone={timeZone}
user={user}
/>
)}
</div>
);
}
function ParamsTab({ now, timeZone }: { now: Date; timeZone: string }) {
const versions = listRuleVersions(getDb(), now);
const current = versions.find((v) => v.status === "current")!;
const latestId = Math.max(...versions.map((v) => v.id));
return (
<>
<ParamsForm
versionKey={latestId}
params={current.params}
minDateTime={instantToLocalDateTime(now, timeZone)}
/>
<Card title="版本紀錄">
<DataTable
caption="制度參數版本紀錄"
rows={versions}
rowKey={(v) => v.id}
empty={{ title: "尚無版本" }}
columns={[
{
key: "effectiveAt",
header: "生效時間",
essential: true,
render: (v) => formatDateTime(v.effectiveAt, timeZone),
},
{
key: "status",
header: "狀態",
essential: true,
render: (v) => (
<ToneBadge tone={STATUS_BADGE[v.status].tone}>
{STATUS_BADGE[v.status].label}
</ToneBadge>
),
},
{ key: "operator", header: "操作者", render: (v) => v.createdByLabel },
{ key: "reason", header: "變更原因", essential: true, render: (v) => v.reason },
{
key: "changes",
header: "差異欄位",
render: (v) =>
v.changes ? (
<ul className="space-y-1 text-sm">
{Object.keys(v.changes.after).map((field) => (
<li key={field}>
{RULE_PARAM_LABELS[field] ?? field}:
{formatParamValue(field, v.changes!.before[field])} →{" "}
<strong>{formatParamValue(field, v.changes!.after[field])}</strong>
</li>
))}
</ul>
) : (
<span className="text-muted">初始版本</span>
),
},
]}
/>
</Card>
</>
);
}
async function HeadcountTab({
month,
currentMonth,
now,
timeZone,
user,
}: {
month: string;
currentMonth: string;
now: Date;
timeZone: string;
user: { id: number; employeeNo: string; name: string | null };
}) {
const db = getDb();
const started = now.getTime() >= monthStart(month, timeZone).getTime();
// 懶建立:月份已開始時,首次開啟就以 1 日 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);
return (
<Card>
<div className="mb-5 flex flex-wrap items-end justify-between gap-4">
<MonthNav month={month} min="2026-01" max={nextMonth(currentMonth)} />
{started && missing && (
<form action={createSnapshotsAction}>
<input type="hidden" name="month" value={month} />
<button
type="submit"
className="rounded-control border border-border-strong bg-surface px-4 py-2"
>
建立 {formatMonth(month)} 快照
</button>
</form>
)}
</div>
{!started && (
<div className="mb-4">
<Alert tone="info">
{formatMonth(month)} 尚未開始;快照會在該月 1 日之後以當日 00:00 的部門成員建立。
</Alert>
</div>
)}
<DataTable
caption={`${formatMonth(month)} 部門人數快照`}
rows={rows}
rowKey={(r) => r.departmentId}
empty={{ title: "尚無部門", description: "請先在部門管理建立部門。" }}
columns={[
{ key: "name", header: "部門", essential: true, render: (r) => r.departmentName },
{ key: "type", header: "類型", render: (r) => DEPARTMENT_TYPE_LABELS[r.departmentType] },
{
key: "headcount",
header: "計算人數",
essential: true,
align: "right",
render: (r) =>
r.headcount === null ? (
<span className="text-muted">{NO_SNAPSHOT_MESSAGE}</span>
) : (
r.headcount
),
},
{
key: "cap",
header: "部門月上限",
essential: true,
align: "right",
render: (r) => <MoneyDisplay amount={r.cap} />,
},
{
key: "locked",
header: "狀態",
render: (r) =>
r.snapshotId === null ? (
""
) : r.locked ? (
<ToneBadge tone="warning">已鎖定(月結已提交)</ToneBadge>
) : (
<ToneBadge tone="neutral">可調整</ToneBadge>
),
},
{
key: "actions",
header: "調整",
essential: true,
render: (r) =>
r.snapshotId === null ? null : (
<details className="text-left" data-testid={`adjust-${r.departmentName}`}>
<summary className="cursor-pointer text-accent">
調整人數{r.adjustments.length > 0 ? `(${r.adjustments.length} 筆紀錄)` : ""}
</summary>
<form action={adjustHeadcountAction} className="mt-3 space-y-2">
<input type="hidden" name="snapshotId" value={r.snapshotId} />
<input type="hidden" name="month" value={month} />
<label className="flex flex-col gap-1 text-sm">
調整後人數
<input
name="headcount"
inputMode="numeric"
defaultValue={r.headcount ?? ""}
className={inputClass}
/>
</label>
<label className="flex flex-col gap-1 text-sm">
調整原因
<textarea name="reason" rows={2} className={inputClass} />
</label>
<button
type="submit"
className="rounded-control bg-primary px-4 py-2 text-on-primary hover:bg-primary-hover"
>
儲存調整
</button>
</form>
{r.adjustments.length > 0 && (
<ul className="mt-3 space-y-1 text-sm text-muted">
{r.adjustments.map((a, i) => (
<li key={i}>
{formatDateTime(a.createdAt, timeZone)} {a.actorLabel}:{a.before} →{" "}
{a.after}({a.reason})
</li>
))}
</ul>
)}
</details>
),
},
]}
/>
</Card>
);
}
@@ -0,0 +1,298 @@
"use client";
import { useRouter } from "next/navigation";
import { useActionState, useEffect, useRef, useTransition } from "react";
import { Card } from "@/components/page-header";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { ErrorSummary } from "@/components/ui/error-summary";
import { Field, inputClass } from "@/components/ui/field";
import { useToast } from "@/components/ui/toast";
import {
ATTACHMENT_FORMATS,
ATTACHMENT_FORMAT_LABELS,
ROUNDING_LABELS,
ROUNDING_MODES,
type RuleParams,
} from "@/lib/rule-params";
import { saveParamsAction, type SaveParamsState } from "./actions";
// 參數路徑 → 表單欄位 id(錯誤摘要捲動、inline 錯誤對應)。
const FIELD_IDS: Record<string, string> = {
"perPersonQuota.general": "general",
"perPersonQuota.rnd": "rnd",
subsidyRatePercent: "subsidyRatePercent",
rounding: "rounding",
employeeDeadlineDay: "employeeDeadlineDay",
managerDeadlineDay: "managerDeadlineDay",
platforms: "platforms",
"attachment.maxSizeMb": "maxSizeMb",
"attachment.formats": "formats",
reason: "reason",
effectiveAt: "effectiveAt",
};
function fieldId(path: string): string {
if (FIELD_IDS[path]) return FIELD_IDS[path];
const prefix = Object.keys(FIELD_IDS).find((key) => path.startsWith(`${key}.`));
return prefix ? FIELD_IDS[prefix] : path;
}
/**
* 制度參數編輯表單:儲存前確認;成功後產生新版本並出現在版本紀錄。
* 儲存狀態與提示放在這一層(不隨版本重建);欄位以 `versionKey` 重建,儲存後顯示新版本的值。
*/
export function ParamsForm({
params,
minDateTime,
versionKey,
}: {
params: RuleParams;
minDateTime: string;
versionKey: number;
}) {
const [state, action] = useActionState<SaveParamsState, FormData>(saveParamsAction, {
status: "idle",
});
const toast = useToast();
const router = useRouter();
useEffect(() => {
if (state.status !== "saved") return;
toast(state.scheduled ? "已建立排定生效的新版本" : "已儲存,新版本立即生效");
router.refresh();
}, [state, toast, router]);
return (
<ParamsFields
key={versionKey}
params={params}
minDateTime={minDateTime}
state={state}
action={action}
/>
);
}
function ParamsFields({
params,
minDateTime,
state,
action,
}: {
params: RuleParams;
minDateTime: string;
state: SaveParamsState;
action: (data: FormData) => void;
}) {
const [, startTransition] = useTransition();
const formRef = useRef<HTMLFormElement>(null);
const errors =
state.status === "error"
? Object.entries(state.fieldErrors).reduce<Record<string, string>>((acc, [path, message]) => {
acc[fieldId(path)] ??= message;
return acc;
}, {})
: {};
const submit = () =>
new Promise<void>((resolve) => {
if (formRef.current) {
const data = new FormData(formRef.current);
startTransition(() => action(data));
}
resolve();
});
return (
<form ref={formRef} noValidate onSubmit={(e) => e.preventDefault()} className="space-y-6">
<ErrorSummary
errors={Object.entries(errors).map(([field, message]) => ({ field, message }))}
/>
<Card title="額度與比例">
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
<Field id="general" label="一般部門每人月額度(元)" required error={errors.general}>
<input
name="general"
inputMode="numeric"
defaultValue={params.perPersonQuota.general}
className={inputClass}
/>
</Field>
<Field id="rnd" label="研發部每人月額度(元)" required error={errors.rnd}>
<input
name="rnd"
inputMode="numeric"
defaultValue={params.perPersonQuota.rnd}
className={inputClass}
/>
</Field>
<Field
id="subsidyRatePercent"
label="個人補助比例(%)"
required
error={errors.subsidyRatePercent}
>
<input
name="subsidyRatePercent"
inputMode="numeric"
defaultValue={params.subsidyRatePercent}
className={inputClass}
/>
</Field>
<Field id="rounding" label="取整方式" required error={errors.rounding}>
<select name="rounding" defaultValue={params.rounding} className={inputClass}>
{ROUNDING_MODES.map((mode) => (
<option key={mode} value={mode}>
{ROUNDING_LABELS[mode]}
</option>
))}
</select>
</Field>
</div>
<p className="mt-4 text-sm text-muted">
本制度沒有個人月補助上限,只受部門月上限與比例分配限制。
</p>
</Card>
<Card title="截止日">
<div className="grid gap-5 sm:grid-cols-2">
<Field
id="employeeDeadlineDay"
label="員工申請截止日(刷卡月份次月幾日)"
required
hint="1 到 28 日,當日 23:59:59 截止"
error={errors.employeeDeadlineDay}
>
<input
name="employeeDeadlineDay"
inputMode="numeric"
defaultValue={params.employeeDeadlineDay}
className={inputClass}
/>
</Field>
<Field
id="managerDeadlineDay"
label="主管月結提交截止日(刷卡月份次月幾日)"
required
hint="必須晚於員工申請截止日"
error={errors.managerDeadlineDay}
>
<input
name="managerDeadlineDay"
inputMode="numeric"
defaultValue={params.managerDeadlineDay}
className={inputClass}
/>
</Field>
</div>
</Card>
<Card title="平台與附件">
<div className="grid gap-5 md:grid-cols-2">
<Field
id="platforms"
label="主要平台(每行一個)"
required
hint="申請表單會在最後固定附加「其他」選項"
error={errors.platforms}
>
<textarea
name="platforms"
rows={5}
defaultValue={params.platforms.join("\n")}
className={inputClass}
/>
</Field>
<div className="space-y-5">
<Field id="maxSizeMb" label="附件單檔上限(MB)" required error={errors.maxSizeMb}>
<input
name="maxSizeMb"
inputMode="numeric"
defaultValue={params.attachment.maxSizeMb}
className={inputClass}
/>
</Field>
<fieldset
id="formats"
tabIndex={-1}
aria-describedby={errors.formats ? "formats-error" : undefined}
>
<legend className="text-sm font-medium">
附件允許格式<span className="ml-0.5 text-danger">*</span>
</legend>
<div className="mt-2 flex gap-5">
{ATTACHMENT_FORMATS.map((f) => (
<label key={f} className="flex items-center gap-2">
<input
type="checkbox"
name="formats"
value={f}
defaultChecked={params.attachment.formats.includes(f)}
/>
{ATTACHMENT_FORMAT_LABELS[f]}
</label>
))}
</div>
{errors.formats && (
<p id="formats-error" className="mt-1 text-sm text-danger">
{errors.formats}
</p>
)}
</fieldset>
</div>
</div>
</Card>
<Card title="變更說明">
<div className="grid gap-5 md:grid-cols-2">
<Field id="reason" label="變更原因" required error={errors.reason}>
<textarea name="reason" rows={3} className={inputClass} />
</Field>
<fieldset className="space-y-2">
<legend className="text-sm font-medium">生效方式</legend>
<label className="flex items-center gap-2">
<input type="radio" name="effectiveMode" value="now" defaultChecked />
儲存後立即生效
</label>
<label className="flex items-center gap-2">
<input type="radio" name="effectiveMode" value="scheduled" />
指定生效時間(台北時間)
</label>
{/* 一律顯示,不依前端狀態切換(避免頁面尚未完成 hydration 時點選無效);只有選「指定生效時間」才採用 */}
<Field
id="effectiveAt"
label="生效時間"
hint="選擇「指定生效時間」時才會使用"
error={errors.effectiveAt}
>
<input
type="datetime-local"
name="effectiveAt"
min={minDateTime}
className={inputClass}
/>
</Field>
</fieldset>
</div>
</Card>
<div className="flex justify-end">
<ConfirmDialog
trigger={
<button
type="button"
className="rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover"
>
儲存變更
</button>
}
title="儲存制度參數?"
description="儲存後會建立新的參數版本;之後的申請試算、截止日與月結都會使用新版本,已提交的月結不受影響。"
confirmLabel="確定儲存"
onConfirm={submit}
/>
</div>
</form>
);
}
+33
View File
@@ -0,0 +1,33 @@
import Link from "next/link";
import { Card, PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { DEPARTMENT_REQUIRED_MESSAGE, requireRouteAccess } from "@/server/auth/current-user";
// 首頁佔位:依角色的首頁卡片(本月申請、待處理、部門額度參考值、時程提醒)由 add-role-dashboards 建立。
export default async function DashboardPage() {
const user = await requireRouteAccess("/dashboard");
const canApply = user.roles.includes("employee") && user.departmentId !== null;
return (
<div className="space-y-6">
<PageHeader
title={`您好,${user.name ?? user.employeeNo}`}
description="善用 AI 工具,提升工作效率,創造更多可能。"
actions={
canApply ? (
<Link
href="/applications/new"
className="inline-flex items-center justify-center rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover"
>
開始申請
</Link>
) : undefined
}
/>
{user.departmentId === null && <Alert tone="warning">{DEPARTMENT_REQUIRED_MESSAGE}。</Alert>}
<Card title="首頁">
<p className="text-muted">本月申請、待處理事項與重要時程將顯示在這裡。</p>
</Card>
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/page-header";
import { SampleForm } from "./sample-form";
import { requireRouteAccess } from "@/server/auth/current-user";
import { getEnv } from "@/server/env";
const COLORS = [
["canvas", "頁面底色"],
["surface", "卡片/側欄"],
["border", "框線"],
["ink", "主要文字"],
["muted", "次要文字"],
["primary", "主要按鈕"],
["accent", "強調/連結"],
["accent-soft", "導覽選中"],
["success", "金額/已通過"],
["success-soft", ""],
["warning", "待處理"],
["warning-soft", ""],
["danger", "錯誤/不核准"],
["danger-soft", ""],
["info", "資訊"],
["info-soft", ""],
["violet", "發放"],
["violet-soft", ""],
["neutral", "中性"],
["neutral-soft", ""],
] as const;
/** 設計 tokens 展示頁:開發時對照風格稿用,只在開發登入模式開放。 */
export default async function DesignTokensPage() {
await requireRouteAccess("/design-tokens");
if (getEnv().AUTH_MODE !== "dev") notFound();
return (
<div className="space-y-8">
<PageHeader title="設計 tokens" description="色彩、字級與共用元件範例(僅開發登入模式)。" />
<section className="rounded-card bg-surface p-6 shadow-card">
<h2 className="mb-4 text-lg font-semibold">色彩</h2>
<ul className="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-5">
{COLORS.map(([name, use]) => (
<li key={name} className="space-y-1">
<div
className="h-14 rounded-control border border-border"
style={{ background: `var(--color-${name})` }}
/>
<p className="text-sm font-medium">{name}</p>
<p className="text-xs text-muted">{use}</p>
</li>
))}
</ul>
</section>
<section className="rounded-card bg-surface p-6 shadow-card">
<h2 className="mb-4 text-lg font-semibold">字級與按鈕</h2>
<p className="text-display font-bold">新增 AI 補助申請</p>
<p className="text-muted">請填寫以下資訊並上傳相關證明文件。</p>
<p className="mt-4 text-3xl font-semibold text-success">NT$450</p>
<div className="mt-4 flex gap-3">
<button className="rounded-control bg-primary px-5 py-2.5 text-on-primary hover:bg-primary-hover">
主要操作
</button>
<button className="rounded-control border border-border-strong bg-surface px-5 py-2.5">
次要操作
</button>
</div>
</section>
<SampleForm />
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
"use client";
import { useState } from "react";
import { Card, StickyActions } from "@/components/page-header";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { ErrorSummary, type FieldError } from "@/components/ui/error-summary";
import { Field, inputClass } from "@/components/ui/field";
import { MoneyDisplay } from "@/components/ui/money-display";
import { MonthPicker } from "@/components/ui/month-picker";
import { useToast } from "@/components/ui/toast";
const REQUIRED = [
{ field: "sample-plan", message: "請填寫訂閱方案" },
{ field: "sample-amount", message: "請填寫支付金額(台幣)" },
{ field: "sample-purpose", message: "請填寫工作用途說明" },
];
/** 共用元件的範例表單:驗證錯誤摘要、inline 錯誤、確認視窗與提示訊息(開發用)。 */
export function SampleForm() {
const [errors, setErrors] = useState<FieldError[]>([]);
const [amount, setAmount] = useState<number | null>(null);
const toast = useToast();
const errorOf = (field: string) => errors.find((e) => e.field === field)?.message;
function submit(form: HTMLFormElement) {
const data = new FormData(form);
const missing = REQUIRED.filter((r) => !String(data.get(r.field) ?? "").trim());
setErrors(missing);
if (missing.length === 0) toast("已送出(範例)");
}
return (
<form
id="sample-form"
noValidate
className="space-y-6"
onSubmit={(e) => {
e.preventDefault();
submit(e.currentTarget);
}}
>
<ErrorSummary errors={errors} />
<Card title="範例表單">
<div className="grid gap-5 md:grid-cols-2">
<Field
id="sample-plan"
label="訂閱方案/項目名稱"
required
error={errorOf("sample-plan")}
>
<input name="sample-plan" className={inputClass} placeholder="例如 ChatGPT Plus" />
</Field>
<Field
id="sample-amount"
label="支付金額(台幣)"
required
hint={
<>
50% 補助試算:
<MoneyDisplay
amount={amount === null ? null : Math.floor(amount / 2)}
kind="estimate"
emphasis
/>
</>
}
error={errorOf("sample-amount")}
>
<input
name="sample-amount"
inputMode="numeric"
className={inputClass}
onChange={(e) => setAmount(e.target.value ? Number(e.target.value) : null)}
/>
</Field>
<MonthPicker
label="申請月份"
name="sample-month"
min="2026-01"
max="2026-12"
defaultValue="2026-10"
/>
<div className="md:col-span-2">
<Field
id="sample-purpose"
label="工作用途說明"
required
error={errorOf("sample-purpose")}
>
<textarea name="sample-purpose" rows={8} className={inputClass} />
</Field>
</div>
</div>
</Card>
{/* 讓表單足夠長,驗證手機的底部固定操作列 */}
<Card title="其他說明">
<div className="h-[60vh] text-muted">(長表單範例)</div>
</Card>
<StickyActions>
<ConfirmDialog
trigger={
<button
type="button"
className="rounded-control border border-border-strong bg-surface px-5 py-2.5"
>
不核准(範例)
</button>
}
title="不核准這筆申請?"
description="不核准後申請人無法再對此案件補件。"
confirmLabel="確定不核准"
destructive
onConfirm={() => toast("已不核准(範例)", "warning")}
/>
<button
type="submit"
className="rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover"
>
送出
</button>
</StickyActions>
</form>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { Card, PageHeader } from "@/components/page-header";
import { requireRouteAccess } from "@/server/auth/current-user";
const FAQ = [
[
"送出申請後,補助金額就確定了嗎?",
"不會。實際補助金額於月結後確認:部門當月所有已核准的申請會一起計算,超過部門月上限時依比例分配。月結前看到的金額都是預估。",
],
[
"部門額度是先申請先用嗎?",
"不是。額度在月結時依當月所有已核准的申請一起分配,與送出先後無關。",
],
[
"申請算哪一個月份?",
"依刷卡日期決定。例如 10/05 刷卡,就算 10 月份的申請,須在 11 月 20 日前送出(實際日期以系統設定為準)。",
],
["可以用外幣金額申請嗎?", "補助以刷卡帳單上的台幣金額計算;原幣金額只作參考。"],
[
"刷卡帳單有其他私人消費,可以遮起來嗎?",
"可以。請遮蔽與申請無關的交易,但要保留這筆交易的日期與台幣金額。",
],
["被退回補件怎麼辦?", "依主管的意見修改或補上附件後重新送出,案件會回到主管審核。"],
["為什麼我不能新增申請?", "若首頁顯示「尚未指派部門」,請洽人資為你指派部門後即可申請。"],
] as const;
export default async function FaqPage() {
await requireRouteAccess("/faq");
return (
<div className="space-y-6">
<PageHeader title="常見問題" description="補助計算、截止日與申請的常見疑問。" />
<Card>
<dl className="divide-y divide-border">
{FAQ.map(([q, a]) => (
<div key={q} className="py-4 first:pt-0 last:pb-0">
<dt className="font-semibold">{q}</dt>
<dd className="mt-1 text-muted">{a}</dd>
</div>
))}
</dl>
</Card>
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
import { Card, PageHeader } from "@/components/page-header";
import { requireRouteAccess } from "@/server/auth/current-user";
const STEPS = [
["新增申請", "填寫 AI 平台、方案、刷卡日期與台幣金額,說明工作用途,並上傳 Invoice 與刷卡帳單。"],
[
"主管審核",
"部門主管確認用途是否與工作相關,可能核准、退回補件或不核准。退回時請依意見補件後重新送出。",
],
["部門月結", "每月截止後,部長將當月所有已核准的申請一併提交月結;超過部門月上限時依比例分配。"],
["核定與發放", "管理端最終核定後,補助金額隨下一次薪資以「其他獎金」發放。"],
] as const;
export default async function HelpPage() {
await requireRouteAccess("/help");
return (
<div className="space-y-6">
<PageHeader title="使用說明" description="從申請到發放的流程與重要規則。" />
<Card title="申請流程">
<ol className="space-y-4">
{STEPS.map(([title, body], i) => (
<li key={title} className="flex gap-4">
<span className="grid size-8 shrink-0 place-items-center rounded-full bg-accent-soft font-semibold text-accent">
{i + 1}
</span>
<span>
<span className="block font-semibold">{title}</span>
<span className="block text-muted">{body}</span>
</span>
</li>
))}
</ol>
</Card>
<Card title="補助怎麼算">
<ul className="list-disc space-y-2 pl-5 text-ink/90">
<li>
個人可補助金額為當月已核准申請的台幣金額合計 × 補助比例(預設
50%),以刷卡帳單上的台幣金額為準。
</li>
<li>
每個部門每月有補助上限(依當月人數快照計算,研發部額度較高),未用完的額度不會累積到下個月。
</li>
<li>部門當月申請總額超過上限時,依每個人的可補助金額比例分配,合計不會超過上限。</li>
<li>
<strong>可以申請不代表一定獲得補助;實際補助金額於月結後確認。</strong>
月結前畫面上的金額都是「預估」。
</li>
</ul>
</Card>
<Card title="截止日">
<ul className="list-disc space-y-2 pl-5 text-ink/90">
<li>申請月份依「刷卡日期」決定,與發票日期、服務期間或送出日期無關。</li>
<li>
員工須在刷卡月份的次月 20 日前送出申請;部長須在次月 25
日前提交月結(實際日期以系統設定為準)。
</li>
<li>超過截止日的申請無法送出。</li>
</ul>
</Card>
</div>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { eq } from "drizzle-orm";
import { AppFrame } from "@/components/shell/app-frame";
import { formatLongDate } from "@/lib/format";
import { buildNavigation } from "@/lib/navigation";
import { ROLE_LABELS } from "@/lib/roles";
import { requireUser } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import { departments } from "@/server/db/schema";
import { getEnv } from "@/server/env";
/**
* 登入後所有頁面的框架。未登入時導向登入頁(proxy 會先帶上 returnTo)。
* 注意:layout 在同一框架內切換頁面時不會重新執行——各頁面仍必須自行呼叫 requireRouteAccess。
*/
export default async function AppLayout({ children }: LayoutProps<"/">) {
const user = await requireUser();
const department =
user.departmentId === null
? undefined
: getDb()
.select({ name: departments.name })
.from(departments)
.where(eq(departments.id, user.departmentId))
.get();
return (
<AppFrame
nav={buildNavigation(user.roles, user)}
user={{
name: user.name ?? user.employeeNo,
employeeNo: user.employeeNo,
department: department?.name ?? "待指派部門",
roleLabels: user.roles.map((role) => ROLE_LABELS[role]),
}}
today={formatLongDate(new Date(), getEnv().TZ_APP)}
>
{children}
</AppFrame>
);
}
-7
View File
@@ -1,7 +0,0 @@
import { RoutePlaceholder } from "@/components/route-placeholder";
import { requireRouteAccess } from "@/server/auth/current-user";
export default async function Page() {
await requireRouteAccess("/admin/settings");
return <RoutePlaceholder title="後台設定" change="add-rule-settings" />;
}
-32
View File
@@ -1,32 +0,0 @@
import Link from "next/link";
import { buildNavigation } from "@/lib/navigation";
import { ROLE_LABELS } from "@/lib/roles";
import { DEPARTMENT_REQUIRED_MESSAGE, requireRouteAccess } from "@/server/auth/current-user";
// 暫時首頁:全站框架(側欄、頂部列)與首頁卡片由 add-app-shell、add-role-dashboards 建立。
export default async function DashboardPage() {
const user = await requireRouteAccess("/dashboard");
const nav = buildNavigation(user.roles, user);
return (
<main>
<h1>AI 補助申請系統</h1>
<p>
{user.name ?? user.employeeNo}({user.roles.map((r) => ROLE_LABELS[r]).join("、")})
</p>
{user.departmentId === null && <p role="alert">{DEPARTMENT_REQUIRED_MESSAGE}。</p>}
<nav aria-label="主要導覽">
<ul>
{nav.map((item) => (
<li key={item.href}>
<Link href={item.href}>{item.label}</Link>
</li>
))}
</ul>
</nav>
<form action="/api/auth/logout" method="post">
<button type="submit">登出</button>
</form>
</main>
);
}
+111 -8
View File
@@ -1,11 +1,114 @@
/* 全站樣式與設計 tokens 由 add-app-shell 建立。 */
*,
*::before,
*::after {
box-sizing: border-box;
@import "tailwindcss";
/*
* 設計 tokens(依 docs/風格2_*.png):白底、淺灰分區、深藍黑主要按鈕、藍色強調、綠色金額、
* 暖色頁首。元件只能引用這些 tokens(Tailwind 的 bg-primary、text-muted…),不寫死色碼。
* 展示頁:/design-tokens(僅開發登入模式)。
*/
@theme {
/* 色彩 */
--color-canvas: #f6f7f9; /* 頁面底色(淺灰分區) */
--color-surface: #ffffff; /* 卡片、側欄、頂部列 */
--color-border: #e5e7eb;
--color-border-strong: #d1d5db;
--color-ink: #1d2330; /* 主要文字 */
--color-muted: #6b7280; /* 次要文字、說明 */
--color-primary: #1e2633; /* 深藍黑主要按鈕 */
--color-primary-hover: #111722;
--color-on-primary: #ffffff;
--color-accent: #3b7cf6; /* 藍色強調、連結、焦點框 */
--color-accent-soft: #e8f0fe; /* 導覽選中底色 */
--color-success: #16a34a; /* 金額強調、已通過 */
--color-success-soft: #e6f6ec;
--color-warning: #a16207;
--color-warning-soft: #fdf3d8;
--color-danger: #dc2626;
--color-danger-soft: #fde8e8;
--color-info: #2563eb;
--color-info-soft: #e5edfd;
--color-violet: #7c3aed;
--color-violet-soft: #efe9fd;
--color-neutral: #4b5563;
--color-neutral-soft: #eef0f3;
--color-hero-from: #fff6df; /* 頁首暖色漸層(取代風格稿的插圖) */
--color-hero-to: #f6f7f9;
/* 字型:系統中文字型,不從外部下載(CI 無法連外部字型服務) */
--font-sans:
system-ui, -apple-system, "PingFang TC", "Microsoft JhengHei", "Noto Sans TC", sans-serif;
/* 字級 */
--text-display: 2.25rem;
--text-display--line-height: 1.2;
/* 圓角 */
--radius-control: 0.625rem; /* 輸入框、按鈕 */
--radius-card: 1rem; /* 卡片 */
/* 陰影 */
--shadow-card: 0 1px 2px rgb(16 24 40 / 0.04), 0 2px 8px rgb(16 24 40 / 0.05);
--shadow-overlay: 0 12px 32px rgb(16 24 40 / 0.18);
/* 版面 */
--spacing-sidebar: 15rem;
--spacing-topbar: 3.75rem;
}
body {
margin: 0;
font-family: system-ui, "Noto Sans TC", "Microsoft JhengHei", sans-serif;
@layer base {
html {
color: var(--color-ink);
background: var(--color-canvas);
font-family: var(--font-sans);
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
min-height: 100dvh;
}
/* 尚未改用共用元件的表單與表格的預設樣式(工具類別會覆蓋這些設定) */
input:not([type="checkbox"], [type="radio"], [type="file"], [type="hidden"]),
select,
textarea {
border: 1px solid var(--color-border-strong);
border-radius: var(--radius-control);
background: var(--color-surface);
padding: 0.45rem 0.75rem;
}
button {
cursor: pointer;
}
table {
width: 100%;
border-collapse: collapse;
background: var(--color-surface);
}
th,
td {
border-bottom: 1px solid var(--color-border);
padding: 0.6rem 0.75rem;
text-align: left;
vertical-align: top;
}
th {
color: var(--color-muted);
font-weight: 500;
font-size: 0.875rem;
}
h2 {
font-size: 1.125rem;
font-weight: 600;
}
a:not([class]) {
color: var(--color-accent);
text-decoration: underline;
text-underline-offset: 2px;
}
/* 鍵盤操作時看得到焦點 */
:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
}
+5 -1
View File
@@ -9,7 +9,11 @@ export async function DevModeBanner() {
await connection();
if (getEnv().AUTH_MODE !== "dev") return null;
return (
<div role="status" data-testid="dev-mode-banner">
<div
role="status"
data-testid="dev-mode-banner"
className="bg-warning-soft px-4 py-1 text-center text-xs text-warning"
>
開發登入模式:可用員工編號直接登入,僅限非正式環境。
</div>
);
+68
View File
@@ -0,0 +1,68 @@
import type { SVGProps } from "react";
import type { NavIcon } from "@/lib/navigation";
// 線條圖示(currentColor),顏色由外層的 token 類別決定。裝飾用,一律 aria-hidden。
type IconName =
| NavIcon
| "bell"
| "menu"
| "close"
| "chevron-down"
| "sidebar"
| "logout"
| "info"
| "alert"
| "check"
| "inbox"
| "calendar";
const PATHS: Record<IconName, string> = {
home: "M3 10.5 12 3l9 7.5M5 9.5V21h5v-6h4v6h5V9.5",
new: "M9 11l3 3 8-8M20 12v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h9",
list: "M7 3h7l5 5v13H7zM14 3v5h5M10 13h6M10 17h6",
review: "M9 12l2 2 4-4M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z",
settlement: "M4 4h16v16H4zM4 9h16M9 9v11",
company: "M4 21V7l8-4 8 4v14M9 21v-6h6v6M9 10h.01M15 10h.01",
payout: "M3 7h18v10H3zM12 12m-2.5 0a2.5 2.5 0 1 0 5 0a2.5 2.5 0 1 0-5 0M6 10v4M18 10v4",
settings:
"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z",
accounts:
"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.9M16 3.1a4 4 0 0 1 0 7.8",
departments: "M3 21h18M5 21V5h8v16M13 9h6v12M8 9h2M8 13h2M8 17h2",
audit: "M12 8v4l3 2M21 12a9 9 0 1 1-3-6.7M21 4v5h-5",
help: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9.1 9a3 3 0 0 1 5.8 1c0 2-3 3-3 3M12 17h.01",
faq: "M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12zM9.5 10a2.5 2.5 0 0 1 4.9.8c0 1.7-2.4 2.2-2.4 2.2M12 16h.01",
bell: "M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.7 21a2 2 0 0 1-3.4 0",
menu: "M4 6h16M4 12h16M4 18h16",
close: "M6 6l12 12M18 6 6 18",
"chevron-down": "m6 9 6 6 6-6",
sidebar: "M3 4h18v16H3zM9 4v16",
logout: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9",
info: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 16v-4M12 8h.01",
alert:
"M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z",
check: "M20 6 9 17l-5-5",
inbox: "M22 12h-6l-2 3h-4l-2-3H2M5.5 5h13L22 12v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-6z",
calendar: "M3 5h18v16H3zM16 3v4M8 3v4M3 10h18",
};
export function Icon({ name, ...props }: { name: IconName } & SVGProps<SVGSVGElement>) {
return (
<svg
viewBox="0 0 24 24"
width="20"
height="20"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...props}
>
<path d={PATHS[name]} />
</svg>
);
}
+67
View File
@@ -0,0 +1,67 @@
import type { ReactNode } from "react";
/**
* 內容標題列(介面規劃 §2.1):頁面名稱+簡短說明+主要操作。
* 主要操作在手機寬度改為畫面底部固定操作列,長表單捲動時仍看得到(app-shell spec)。
*/
export function PageHeader({
title,
description,
actions,
}: {
title: string;
description?: ReactNode;
actions?: ReactNode;
}) {
return (
<header className="mb-6 rounded-card bg-gradient-to-br from-hero-from via-hero-from/60 to-hero-to px-5 py-6 md:flex md:items-end md:justify-between md:gap-6 md:px-8 md:py-8">
<div className="min-w-0">
<h1 className="text-2xl font-bold tracking-tight md:text-display">{title}</h1>
{description && <p className="mt-2 text-muted md:text-lg">{description}</p>}
</div>
{actions && <StickyActions>{actions}</StickyActions>}
</header>
);
}
/** 主要操作區:桌機與平板在原位,手機固定在畫面底部。 */
export function StickyActions({ children }: { children: ReactNode }) {
return (
<div
data-testid="primary-actions"
className="fixed inset-x-0 bottom-0 z-20 flex gap-3 border-t border-border bg-surface/95 px-4 py-3 backdrop-blur *:flex-1 md:static md:z-auto md:shrink-0 md:border-0 md:bg-transparent md:p-0 md:backdrop-blur-none md:*:flex-none"
>
{children}
</div>
);
}
/** 主內容+右側輔助區(規則摘要、截止日、試算…)。桌機並排,較窄時輔助區移到下方。 */
export function WithAside({ children, aside }: { children: ReactNode; aside: ReactNode }) {
return (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_20rem]">
<div className="min-w-0">{children}</div>
<aside aria-label="輔助資訊" className="space-y-6">
{aside}
</aside>
</div>
);
}
/** 白色圓角卡片。 */
export function Card({
title,
children,
className = "",
}: {
title?: string;
children: ReactNode;
className?: string;
}) {
return (
<section className={`rounded-card bg-surface p-5 shadow-card md:p-6 ${className}`}>
{title && <h2 className="mb-4 text-lg font-semibold">{title}</h2>}
{children}
</section>
);
}
+8 -4
View File
@@ -1,9 +1,13 @@
import { Card, PageHeader } from "@/components/page-header";
// 路由已受權限保護、但頁面內容尚未建立時的佔位畫面;由各功能 change 替換。
export function RoutePlaceholder({ title, change }: { title: string; change: string }) {
return (
<main>
<h1>{title}</h1>
<p>此頁面將於 {change} 建立。</p>
</main>
<div className="space-y-6">
<PageHeader title={title} />
<Card>
<p className="text-muted">此頁面將於 {change} 建立。</p>
</Card>
</div>
);
}
+271
View File
@@ -0,0 +1,271 @@
"use client";
import * as Dialog from "@radix-ui/react-dialog";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRef, useState, type ReactNode } from "react";
import { Icon } from "@/components/icons";
import { Toaster } from "@/components/ui/toast";
import { activeNavHref, type NavItem } from "@/lib/navigation";
export interface FrameUser {
name: string;
employeeNo: string;
department: string;
roleLabels: string[];
}
/**
* 登入後的全站框架(介面規劃 §2.1):左側導覽、頂部列、主內容區。
* 斷點:手機 < 768px 側欄改為漢堡選單(抽屜);平板 768–1279px 側欄可收合為圖示列;桌機 ≥ 1280px 完整側欄。
*/
export function AppFrame({
nav,
user,
today,
children,
}: {
nav: NavItem[];
user: FrameUser;
today: string;
children: ReactNode;
}) {
const pathname = usePathname();
const active = activeNavHref(pathname, nav);
const [drawerOpen, setDrawerOpen] = useState(false);
const [collapsed, setCollapsed] = useState(false);
return (
<div className="flex min-h-dvh">
{/* 平板/桌機側欄 */}
<aside
aria-label="側欄"
data-collapsed={collapsed}
className={`sticky top-0 hidden h-dvh shrink-0 flex-col border-r border-border bg-surface md:flex ${
collapsed ? "w-[4.5rem]" : "w-sidebar"
}`}
>
<SidebarContent nav={nav} active={active} collapsed={collapsed} />
</aside>
{/* 手機抽屜 */}
<Dialog.Root open={drawerOpen} onOpenChange={setDrawerOpen}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-40 bg-ink/40 md:hidden" />
<Dialog.Content
aria-describedby={undefined}
className="fixed inset-y-0 left-0 z-50 flex w-[17rem] max-w-[85vw] flex-col bg-surface shadow-overlay md:hidden"
>
<Dialog.Title className="sr-only">主要導覽</Dialog.Title>
<Dialog.Close
className="absolute top-3 right-3 rounded-control p-2 text-muted hover:bg-canvas"
aria-label="關閉選單"
>
<Icon name="close" />
</Dialog.Close>
<SidebarContent
nav={nav}
active={active}
collapsed={false}
onNavigate={() => setDrawerOpen(false)}
/>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
<div className="flex min-w-0 flex-1 flex-col">
<header className="sticky top-0 z-30 flex h-topbar items-center gap-2 border-b border-border bg-surface/95 px-3 backdrop-blur md:px-6">
<button
type="button"
className="rounded-control p-2 text-muted hover:bg-canvas md:hidden"
aria-label="開啟選單"
onClick={() => setDrawerOpen(true)}
>
<Icon name="menu" />
</button>
<button
type="button"
className="hidden rounded-control p-2 text-muted hover:bg-canvas md:inline-flex xl:hidden"
aria-label={collapsed ? "展開側欄" : "收合側欄"}
aria-pressed={collapsed}
onClick={() => setCollapsed((c) => !c)}
>
<Icon name="sidebar" />
</button>
<span className="truncate font-semibold md:hidden">AI 補助申請系統</span>
<span className="sr-only md:not-sr-only md:text-sm md:text-muted xl:sr-only">
AI 補助申請系統
</span>
<div className="ml-auto flex items-center gap-1 md:gap-3">
<time
className="hidden text-sm whitespace-nowrap text-ink sm:block"
data-testid="today"
>
{today}
</time>
<span className="hidden h-6 w-px bg-border sm:block" aria-hidden="true" />
<NotificationMenu />
<span className="hidden h-6 w-px bg-border sm:block" aria-hidden="true" />
<UserMenu user={user} today={today} />
</div>
</header>
<main id="main" className="flex-1 px-4 pt-5 pb-28 md:px-8 md:pt-6 md:pb-10">
<Toaster>{children}</Toaster>
</main>
</div>
</div>
);
}
function SidebarContent({
nav,
active,
collapsed,
onNavigate,
}: {
nav: NavItem[];
active: string | null;
collapsed: boolean;
onNavigate?: () => void;
}) {
const groups = [nav.filter((i) => i.group === "main"), nav.filter((i) => i.group === "support")];
return (
<>
<div
className={`flex items-center gap-3 px-5 pt-6 pb-5 ${collapsed ? "justify-center px-0" : ""}`}
>
<span
aria-hidden="true"
className="grid size-9 shrink-0 place-items-center rounded-full bg-gradient-to-br from-accent to-violet text-sm font-bold text-on-primary"
>
AI
</span>
{!collapsed && (
<span className="leading-tight">
<span className="block font-bold">AI 補助申請系統</span>
<span className="block text-xs text-muted">AI Subsidy Application System</span>
</span>
)}
</div>
<nav aria-label="主要導覽" className="flex-1 overflow-y-auto px-3">
{groups.map((items, index) =>
items.length === 0 ? null : (
<ul key={index} className={index > 0 ? "mt-4 border-t border-border pt-4" : ""}>
{items.map((item) => {
const current = item.href === active;
return (
<li key={item.href}>
<Link
href={item.href}
onClick={onNavigate}
aria-current={current ? "page" : undefined}
title={collapsed ? item.label : undefined}
className={`mb-1 flex items-center gap-3 rounded-control px-3 py-2.5 text-[0.95rem] ${
collapsed ? "justify-center" : ""
} ${
current
? "bg-accent-soft font-semibold text-ink"
: "text-ink/80 hover:bg-canvas hover:text-ink"
}`}
>
<Icon name={item.icon} className={current ? "text-accent" : "text-muted"} />
<span className={collapsed ? "sr-only" : ""}>{item.label}</span>
</Link>
</li>
);
})}
</ul>
),
)}
</nav>
{!collapsed && (
<div className="px-5 pt-4 pb-6 text-xs text-muted">
<p>Good People</p>
<p>Make a Brighter Tomorrow.</p>
<p className="mt-4">© 2026 AI 補助申請系統</p>
</div>
)}
</>
);
}
const menuContent = "z-50 min-w-56 rounded-card border border-border bg-surface p-2 shadow-overlay";
function NotificationMenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger
className="rounded-control p-2 text-muted hover:bg-canvas"
aria-label="通知"
>
<Icon name="bell" />
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content align="end" sideOffset={8} className={menuContent}>
<DropdownMenu.Label className="px-2 py-1.5 text-sm font-semibold">
通知
</DropdownMenu.Label>
<p className="flex items-center gap-2 px-2 py-4 text-sm text-muted">
<Icon name="inbox" />
目前沒有通知
</p>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
);
}
function UserMenu({ user, today }: { user: FrameUser; today: string }) {
const logoutForm = useRef<HTMLFormElement>(null);
return (
<>
<form ref={logoutForm} action="/api/auth/logout" method="post" hidden />
<DropdownMenu.Root>
<DropdownMenu.Trigger
className="flex items-center gap-2 rounded-control px-1.5 py-1 hover:bg-canvas md:px-2"
aria-label={`使用者選單:${user.name}`}
>
<span
aria-hidden="true"
className="grid size-9 place-items-center rounded-full bg-accent-soft font-semibold text-accent"
>
{user.name.slice(0, 1)}
</span>
<span className="hidden text-left leading-tight sm:block">
<span className="block text-sm font-semibold" data-testid="user-name">
{user.name}
</span>
<span className="block text-xs text-muted" data-testid="user-department">
{user.department}
</span>
</span>
<Icon name="chevron-down" className="hidden text-muted sm:block" />
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content align="end" sideOffset={8} className={menuContent}>
<div className="px-2 py-1.5">
<p className="font-semibold">
{user.name}({user.employeeNo})
</p>
<p className="text-sm text-muted">{user.department}</p>
<p className="mt-1 text-xs text-muted">{user.roleLabels.join("、")}</p>
<p className="mt-1 text-xs text-muted sm:hidden">{today}</p>
</div>
<DropdownMenu.Separator className="my-1 h-px bg-border" />
{/* 表單放在選單外:選單關閉時會移除選單內容,放在裡面的表單會來不及送出 */}
<DropdownMenu.Item
onSelect={() => logoutForm.current?.requestSubmit()}
className="flex w-full cursor-pointer items-center gap-2 rounded-control px-2 py-2 text-left text-sm outline-none data-[highlighted]:bg-canvas"
>
<Icon name="logout" />
登出
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
</>
);
}
+40
View File
@@ -0,0 +1,40 @@
import type { ReactNode } from "react";
import { Icon } from "@/components/icons";
export type AlertTone = "info" | "success" | "warning" | "danger";
// 類別名稱必須完整寫出,Tailwind 才掃描得到(不可用 `text-${tone}` 動態組合)。
const TONES: Record<
AlertTone,
{ box: string; iconClass: string; icon: "info" | "check" | "alert" }
> = {
info: { box: "border-info/30 bg-info-soft", iconClass: "text-info", icon: "info" },
success: { box: "border-success/30 bg-success-soft", iconClass: "text-success", icon: "check" },
warning: { box: "border-warning/30 bg-warning-soft", iconClass: "text-warning", icon: "alert" },
danger: { box: "border-danger/30 bg-danger-soft", iconClass: "text-danger", icon: "alert" },
};
/** 頁面內的提示訊息。危險訊息以 role="alert" 讓螢幕閱讀器立即唸出,其餘為 role="status"。 */
export function Alert({
tone = "info",
title,
children,
}: {
tone?: AlertTone;
title?: string;
children: ReactNode;
}) {
const t = TONES[tone];
return (
<div
role={tone === "danger" ? "alert" : "status"}
className={`flex gap-3 rounded-control border px-4 py-3 text-ink ${t.box}`}
>
<Icon name={t.icon} className={`mt-0.5 shrink-0 ${t.iconClass}`} />
<div>
{title && <p className="font-semibold">{title}</p>}
<div>{children}</div>
</div>
</div>
);
}
+178
View File
@@ -0,0 +1,178 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { APPLICATION_STATUSES, APPLICATION_STATUS_DISPLAY } from "@/lib/application-status";
import { ConfirmDialog } from "./confirm-dialog";
import { DataTable } from "./data-table";
import { EmptyState } from "./empty-state";
import { MoneyDisplay } from "./money-display";
import { MonthPicker } from "./month-picker";
import { StatusBadge } from "./status-badge";
afterEach(cleanup);
describe("MoneyDisplay", () => {
it("NT$+千分位;尚無數值顯示「--」", () => {
render(
<>
<MoneyDisplay amount={13000} />
<MoneyDisplay amount={null} />
</>,
);
expect(screen.getByText("NT$13,000")).toBeTruthy();
expect(screen.getByText("--")).toBeTruthy();
});
it("月結前標示「預估」、月結後標示「最終」", () => {
render(
<>
<MoneyDisplay amount={450} kind="estimate" />
<MoneyDisplay amount={346} kind="final" />
</>,
);
expect(screen.getByText("預估")).toBeTruthy();
expect(screen.getByText("最終")).toBeTruthy();
});
});
describe("StatusBadge", () => {
it("待主管審核顯示「待審核」", () => {
render(<StatusBadge status="pending_review" />);
expect(screen.getByText("待審核")).toBeTruthy();
expect(screen.queryByText("審核中")).toBeNull();
});
it("每個狀態都以文字呈現", () => {
render(
<>
{APPLICATION_STATUSES.map((s) => (
<StatusBadge key={s} status={s} />
))}
</>,
);
for (const s of APPLICATION_STATUSES) {
expect(screen.getByText(APPLICATION_STATUS_DISPLAY[s].label)).toBeTruthy();
}
});
});
describe("MonthPicker", () => {
it("選項顯示為 YYYY/MM,由新到舊,值為 YYYY-MM", () => {
const onChange = vi.fn();
render(
<MonthPicker
label="申請月份"
min="2026-11"
max="2027-01"
value="2027-01"
onChange={onChange}
/>,
);
const select = screen.getByLabelText("申請月份") as HTMLSelectElement;
expect([...select.options].map((o) => o.textContent)).toEqual([
"2027/01",
"2026/12",
"2026/11",
]);
fireEvent.change(select, { target: { value: "2026-12" } });
expect(onChange).toHaveBeenCalledWith("2026-12");
});
});
describe("ConfirmDialog", () => {
const setup = () => {
const onConfirm = vi.fn();
render(
<ConfirmDialog
trigger={<button type="button">確認並提交</button>}
title="提交月結"
description="提交後本月份名單將鎖定,如需更正須由管理者退回。確定提交?"
confirmLabel="確定提交"
onConfirm={onConfirm}
/>,
);
return onConfirm;
};
it("顯示操作後果;按取消時不執行", async () => {
const user = userEvent.setup();
const onConfirm = setup();
await user.click(screen.getByRole("button", { name: "確認並提交" }));
expect(screen.getByText(/提交後本月份名單將鎖定/)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "取消" }));
expect(onConfirm).not.toHaveBeenCalled();
expect(screen.queryByText(/提交後本月份名單將鎖定/)).toBeNull();
});
it("按 Esc 關閉也不執行", async () => {
const user = userEvent.setup();
const onConfirm = setup();
await user.click(screen.getByRole("button", { name: "確認並提交" }));
await user.keyboard("{Escape}");
expect(onConfirm).not.toHaveBeenCalled();
});
it("按確認才執行", async () => {
const user = userEvent.setup();
const onConfirm = setup();
await user.click(screen.getByRole("button", { name: "確認並提交" }));
await user.click(screen.getByRole("button", { name: "確定提交" }));
expect(onConfirm).toHaveBeenCalledTimes(1);
});
});
describe("EmptyState/DataTable", () => {
const columns = [
{ key: "name", header: "名稱", render: (r: { name: string }) => r.name, essential: true },
];
it("無資料時顯示空狀態與下一步,而非空白表格", () => {
render(
<DataTable
caption="我的申請"
columns={columns}
rows={[]}
rowKey={(r) => r.name}
empty={{ title: "還沒有申請", action: <button type="button">新增申請</button> }}
/>,
);
expect(screen.getByText("還沒有申請")).toBeTruthy();
expect(screen.getByRole("button", { name: "新增申請" })).toBeTruthy();
expect(screen.queryByRole("table")).toBeNull();
});
it("有資料時同時輸出表格與卡片清單(由斷點切換顯示)", () => {
render(
<DataTable
caption="清單"
columns={columns}
rows={[{ name: "ChatGPT Plus" }]}
rowKey={(r) => r.name}
empty={{ title: "空" }}
/>,
);
expect(screen.getByRole("table")).toBeTruthy();
expect(screen.getAllByText("ChatGPT Plus")).toHaveLength(2);
});
it("可強制卡片模式", () => {
render(
<DataTable
caption="清單"
columns={columns}
rows={[{ name: "A" }]}
rowKey={(r) => r.name}
empty={{ title: "空" }}
mode="cards"
/>,
);
expect(screen.getByTestId("table-mode").className).toContain("hidden");
expect(screen.getByTestId("card-mode").className).not.toContain("hidden");
});
it("EmptyState 單獨使用", () => {
render(<EmptyState title="查無資料" description="請調整篩選條件" />);
expect(screen.getByRole("status").textContent).toContain("請調整篩選條件");
});
});
+77
View File
@@ -0,0 +1,77 @@
"use client";
import * as Dialog from "@radix-ui/react-dialog";
import { useState, type ReactNode } from "react";
/**
* 重要或不可逆操作的確認視窗(不核准、提交月結、最終核定、標記已發放…)。
* 說明操作後果;按「取消」或關閉視窗都不執行,只有按確認才呼叫 onConfirm。
*/
export function ConfirmDialog({
trigger,
title,
description,
confirmLabel = "確定",
cancelLabel = "取消",
destructive = false,
onConfirm,
}: {
/** 開啟確認視窗的按鈕(會以 asChild 套用)。 */
trigger: ReactNode;
title: string;
description: ReactNode;
confirmLabel?: string;
cancelLabel?: string;
destructive?: boolean;
onConfirm: () => void | Promise<void>;
}) {
const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
async function confirm() {
setPending(true);
try {
await onConfirm();
setOpen(false);
} finally {
setPending(false);
}
}
return (
<Dialog.Root open={open} onOpenChange={(next) => !pending && setOpen(next)}>
<Dialog.Trigger asChild>{trigger}</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-50 bg-ink/40" />
<Dialog.Content
role="alertdialog"
className="fixed top-1/2 left-1/2 z-50 w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 rounded-card bg-surface p-6 shadow-overlay"
>
<Dialog.Title className="text-lg font-semibold">{title}</Dialog.Title>
<Dialog.Description className="mt-2 text-muted">{description}</Dialog.Description>
<div className="mt-6 flex justify-end gap-3">
<Dialog.Close asChild>
<button
type="button"
disabled={pending}
className="rounded-control border border-border-strong bg-surface px-4 py-2"
>
{cancelLabel}
</button>
</Dialog.Close>
<button
type="button"
disabled={pending}
onClick={confirm}
className={`rounded-control px-4 py-2 font-medium text-on-primary disabled:opacity-60 ${
destructive ? "bg-danger" : "bg-primary hover:bg-primary-hover"
}`}
>
{pending ? "處理中…" : confirmLabel}
</button>
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}
+88
View File
@@ -0,0 +1,88 @@
import type { ReactNode } from "react";
import { EmptyState } from "./empty-state";
export interface Column<T> {
key: string;
header: string;
render: (row: T) => ReactNode;
/** 手機卡片模式也要顯示的關鍵欄位(都未指定時取前三欄)。 */
essential?: boolean;
align?: "left" | "right";
}
/**
* 資料表格:平板與桌機為表格;手機寬度(< 768px)改為只保留關鍵欄位的卡片清單,避免水平捲動。
* `mode` 可強制指定(例如窄欄位的輔助區)。沒有資料時顯示空狀態。
*/
export function DataTable<T>({
caption,
columns,
rows,
rowKey,
empty,
mode = "responsive",
}: {
caption: string;
columns: Column<T>[];
rows: T[];
rowKey: (row: T) => string | number;
empty: { title: string; description?: ReactNode; action?: ReactNode };
mode?: "responsive" | "table" | "cards";
}) {
if (rows.length === 0) return <EmptyState {...empty} />;
const essential = columns.filter((c) => c.essential);
const cardColumns = essential.length > 0 ? essential : columns.slice(0, 3);
const tableClass = mode === "cards" ? "hidden" : mode === "table" ? "block" : "hidden md:block";
const cardsClass = mode === "table" ? "hidden" : mode === "cards" ? "" : "md:hidden";
return (
<>
<div className={`overflow-x-auto ${tableClass}`} data-testid="table-mode">
<table className="w-full border-collapse text-left">
<caption className="sr-only">{caption}</caption>
<thead>
<tr className="border-b border-border text-sm text-muted">
{columns.map((c) => (
<th
key={c.key}
scope="col"
className={`px-3 py-2.5 font-medium ${c.align === "right" ? "text-right" : ""}`}
>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={rowKey(row)} className="border-b border-border last:border-0">
{columns.map((c) => (
<td
key={c.key}
className={`px-3 py-3 align-top ${c.align === "right" ? "text-right" : ""}`}
>
{c.render(row)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
<ul className={`space-y-3 ${cardsClass}`} aria-label={caption} data-testid="card-mode">
{rows.map((row) => (
<li key={rowKey(row)} className="rounded-card border border-border bg-surface p-4">
<dl className="space-y-1.5">
{cardColumns.map((c) => (
<div key={c.key} className="flex justify-between gap-4">
<dt className="shrink-0 text-sm text-muted">{c.header}</dt>
<dd className="min-w-0 text-right">{c.render(row)}</dd>
</div>
))}
</dl>
</li>
))}
</ul>
</>
);
}
+25
View File
@@ -0,0 +1,25 @@
import type { ReactNode } from "react";
import { Icon } from "@/components/icons";
/** 沒有資料時的空狀態:說明+可執行的下一步,而不是空白表格。 */
export function EmptyState({
title,
description,
action,
}: {
title: string;
description?: ReactNode;
action?: ReactNode;
}) {
return (
<div
role="status"
className="flex flex-col items-center gap-2 rounded-card border border-dashed border-border-strong px-6 py-10 text-center"
>
<Icon name="inbox" width={32} height={32} className="text-muted" />
<p className="font-semibold">{title}</p>
{description && <p className="max-w-md text-sm text-muted">{description}</p>}
{action && <div className="mt-2">{action}</div>}
</div>
);
}
+53
View File
@@ -0,0 +1,53 @@
"use client";
import { useEffect, useRef } from "react";
export interface FieldError {
/** 對應欄位的 id(Field 的 id)。 */
field: string;
message: string;
}
/**
* 送出時的錯誤摘要:頁首顯示「尚有 N 項資料需完成」並列出各項,出現時捲動到第一個錯誤欄位並移入焦點。
* 每個欄位旁另以 Field 的 error 顯示 inline 錯誤。
*/
export function ErrorSummary({ errors }: { errors: FieldError[] }) {
const ref = useRef<HTMLDivElement>(null);
const key = errors.map((e) => e.field).join("|");
useEffect(() => {
if (key === "") return;
const first = document.getElementById(key.split("|")[0]);
if (first) {
first.scrollIntoView({ block: "center", behavior: "smooth" });
first.focus({ preventScroll: true });
} else {
ref.current?.focus();
}
}, [key]);
if (errors.length === 0) return null;
return (
<div
ref={ref}
tabIndex={-1}
role="alert"
aria-labelledby="error-summary-title"
className="rounded-control border border-danger/30 bg-danger-soft px-4 py-3"
>
<p id="error-summary-title" className="font-semibold text-danger">
尚有 {errors.length} 項資料需完成
</p>
<ul className="mt-1 list-disc pl-5 text-sm">
{errors.map((e) => (
<li key={e.field}>
<a href={`#${e.field}`} className="underline underline-offset-2">
{e.message}
</a>
</li>
))}
</ul>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { cloneElement, isValidElement, type ReactElement, type ReactNode } from "react";
/**
* 表單欄位:標籤永遠可見(不以 placeholder 取代)、必填標示、說明與 inline 錯誤。
* 子元素需為單一輸入元件;會自動帶上 id、aria-invalid 與 aria-describedby。
*/
export function Field({
id,
label,
required = false,
hint,
error,
children,
}: {
id: string;
label: string;
required?: boolean;
hint?: ReactNode;
error?: string;
children: ReactElement<Record<string, unknown>>;
}) {
const hintId = hint ? `${id}-hint` : undefined;
const errorId = error ? `${id}-error` : undefined;
const control = isValidElement(children)
? cloneElement(children, {
id,
"aria-invalid": error ? true : undefined,
"aria-describedby": [hintId, errorId].filter(Boolean).join(" ") || undefined,
className:
`${String(children.props.className ?? "")} ${error ? "border-danger" : ""}`.trim(),
})
: children;
return (
<div className="flex flex-col gap-1.5" data-field={id}>
<label htmlFor={id} className="text-sm font-medium">
{label}
{required && (
<span className="ml-0.5 text-danger" aria-hidden="true">
*
</span>
)}
{required && <span className="sr-only">(必填)</span>}
</label>
{control}
{hint && (
<p id={hintId} className="text-sm text-muted">
{hint}
</p>
)}
{error && (
<p id={errorId} className="text-sm text-danger">
{error}
</p>
)}
</div>
);
}
/** 輸入框的共用樣式。 */
export const inputClass =
"w-full rounded-control border border-border-strong bg-surface px-3 py-2 text-ink placeholder:text-muted/70";
+28
View File
@@ -0,0 +1,28 @@
import { formatMoney } from "@/lib/format";
/**
* 金額:NT$+千分位;尚無數值顯示「--」。月結前的金額以 kind="estimate" 標示「預估」,
* 月結後的金額以 kind="final" 標示「最終」,避免讓人以為月結前的數字已確定。
*/
export function MoneyDisplay({
amount,
kind,
emphasis = false,
className = "",
}: {
amount: number | null | undefined;
kind?: "estimate" | "final";
emphasis?: boolean;
className?: string;
}) {
return (
<span className={`inline-flex items-baseline gap-1.5 tabular-nums ${className}`}>
<span className={emphasis ? "font-semibold text-success" : ""}>{formatMoney(amount)}</span>
{kind && (
<span className="rounded-full bg-neutral-soft px-1.5 text-xs font-medium text-neutral">
{kind === "estimate" ? "預估" : "最終"}
</span>
)}
</span>
);
}
+64
View File
@@ -0,0 +1,64 @@
"use client";
import { useId } from "react";
import { formatMonth } from "@/lib/format";
function monthsBetween(min: string, max: string): string[] {
const result: string[] = [];
let [y, m] = max.split("-").map(Number);
const [minY, minM] = min.split("-").map(Number);
while (y > minY || (y === minY && m >= minM)) {
result.push(`${y}-${String(m).padStart(2, "0")}`);
m -= 1;
if (m === 0) {
m = 12;
y -= 1;
}
}
return result;
}
/**
* 月份選擇(值為 `YYYY-MM`,顯示為 YYYY/MM,由新到舊)。不用 `<input type="month">`:
* 部分桌機瀏覽器不支援,顯示格式也無法統一。
*/
export function MonthPicker({
label,
name,
value,
defaultValue,
min,
max,
onChange,
}: {
label: string;
name?: string;
value?: string;
defaultValue?: string;
min: string;
max: string;
onChange?: (month: string) => void;
}) {
const id = useId();
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={id} className="text-sm font-medium">
{label}
</label>
<select
id={id}
name={name}
value={value}
defaultValue={value === undefined ? defaultValue : undefined}
onChange={(e) => onChange?.(e.target.value)}
className="rounded-control border border-border-strong bg-surface px-3 py-2"
>
{monthsBetween(min, max).map((month) => (
<option key={month} value={month}>
{formatMonth(month)}
</option>
))}
</select>
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
import {
applicationStatusDisplay,
type ApplicationStatus,
type StatusTone,
} from "@/lib/application-status";
const TONE_CLASSES: Record<StatusTone, string> = {
neutral: "bg-neutral-soft text-neutral",
warning: "bg-warning-soft text-warning",
danger: "bg-danger-soft text-danger",
success: "bg-success-soft text-success",
info: "bg-info-soft text-info",
violet: "bg-violet-soft text-violet",
};
/** 狀態標籤:一律顯示文字(介面規劃 §9),顏色只是輔助,灰階時仍可辨識。 */
export function StatusBadge({ status }: { status: ApplicationStatus }) {
const { label, tone } = applicationStatusDisplay(status);
return <ToneBadge tone={tone}>{label}</ToneBadge>;
}
/** 任意文字的語意色標籤(月結、發放等其他狀態用)。 */
export function ToneBadge({ tone, children }: { tone: StatusTone; children: string }) {
return (
<span
data-tone={tone}
className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-sm font-medium whitespace-nowrap ${TONE_CLASSES[tone]}`}
>
{children}
</span>
);
}
+52
View File
@@ -0,0 +1,52 @@
"use client";
import { createContext, useCallback, useContext, useState, type ReactNode } from "react";
import type { AlertTone } from "./alert";
interface ToastMessage {
id: number;
tone: AlertTone;
text: string;
}
const ToastContext = createContext<(text: string, tone?: AlertTone) => void>(() => {});
const TONE_CLASSES: Record<AlertTone, string> = {
info: "bg-primary",
success: "bg-primary",
warning: "bg-warning",
danger: "bg-danger",
};
/** 系統層級的成功/失敗提示。放在框架最外層;頁面以 useToast() 顯示訊息。 */
export function Toaster({ children }: { children: ReactNode }) {
const [messages, setMessages] = useState<ToastMessage[]>([]);
const show = useCallback((text: string, tone: AlertTone = "success") => {
const id = Date.now() + Math.random();
setMessages((m) => [...m, { id, tone, text }]);
setTimeout(() => setMessages((m) => m.filter((x) => x.id !== id)), 5000);
}, []);
return (
<ToastContext.Provider value={show}>
{children}
<div
aria-live="polite"
className="pointer-events-none fixed inset-x-4 top-4 z-[60] flex flex-col items-end gap-2 md:inset-x-auto md:right-6"
>
{messages.map((m) => (
<p
key={m.id}
role={m.tone === "danger" ? "alert" : "status"}
className={`pointer-events-auto rounded-control px-4 py-3 text-sm text-on-primary shadow-overlay ${TONE_CLASSES[m.tone]}`}
>
{m.text}
</p>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast() {
return useContext(ToastContext);
}
+20 -1
View File
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
import { localDate, nextDate, startOfLocalDay } from "./calendar";
import {
instantToLocalDateTime,
localDate,
localDateTimeToInstant,
nextDate,
startOfLocalDay,
} from "./calendar";
describe("localDate", () => {
it("以指定時區決定日期", () => {
@@ -28,3 +34,16 @@ describe("nextDate", () => {
expect(nextDate("2026-12-31")).toBe("2027-01-01");
});
});
describe("localDateTimeToInstant/instantToLocalDateTime", () => {
it("台北 2026-12-01 00:00 = UTC 11/30 16:00,可來回轉換", () => {
const instant = localDateTimeToInstant("2026-12-01T00:00", "Asia/Taipei")!;
expect(instant.toISOString()).toBe("2026-11-30T16:00:00.000Z");
expect(instantToLocalDateTime(instant, "Asia/Taipei")).toBe("2026-12-01T00:00");
});
it("格式不正確時回傳 null", () => {
expect(localDateTimeToInstant("2026-12-01", "Asia/Taipei")).toBeNull();
expect(localDateTimeToInstant("2026-12-01T25:00", "Asia/Taipei")).toBeNull();
});
});
+19
View File
@@ -55,3 +55,22 @@ export function nextDate(date: string): string {
d.setUTCDate(d.getUTCDate() + 1);
return d.toISOString().slice(0, 10);
}
/** 指定時區的「日期+時分」(`YYYY-MM-DDTHH:mm`,表單的 datetime-local 值)對應的時間點。 */
export function localDateTimeToInstant(value: string, timeZone: string): Date | null {
const m = value.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})$/);
if (!m) return null;
const [, date, hh, mm] = m;
if (Number(hh) > 23 || Number(mm) > 59) return null;
return new Date(
startOfLocalDay(date, timeZone).getTime() + (Number(hh) * 60 + Number(mm)) * 60_000,
);
}
/** 時間點在指定時區的「日期+時分」(`YYYY-MM-DDTHH:mm`)。 */
export function instantToLocalDateTime(instant: Date, timeZone: string): string {
const offset = zoneOffsetMs(instant, timeZone);
return new Date(Math.floor(instant.getTime() / 60_000) * 60_000 + offset)
.toISOString()
.slice(0, 16);
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { cardMonth, deadlinesFor, monthEnd, monthStart, nextMonth } from "./deadlines";
const TZ = "Asia/Taipei";
const days = { employeeDeadlineDay: 20, managerDeadlineDay: 25 };
describe("deadlinesFor", () => {
it("10 月刷卡:員工 11/20 23:59:59、主管 11/25 23:59:59(台北)", () => {
const d = deadlinesFor("2026-10-05", days, TZ);
expect(d.month).toBe("2026-10");
// 台北 23:59:59 = UTC 15:59:59
expect(d.employee.toISOString()).toBe("2026-11-20T15:59:59.000Z");
expect(d.manager.toISOString()).toBe("2026-11-25T15:59:59.000Z");
});
it("跨年:12/31 刷卡 → 2027/01/20 23:59:59", () => {
expect(deadlinesFor("2026-12-31", days, TZ).employee.toISOString()).toBe(
"2027-01-20T15:59:59.000Z",
);
});
it("月份只由刷卡日期決定", () => {
expect(cardMonth("2026-10-31")).toBe("2026-10");
expect(() => cardMonth("2026/10/31")).toThrow();
});
});
describe("月份邊界", () => {
it("nextMonth 跨年", () => {
expect(nextMonth("2026-12")).toBe("2027-01");
expect(nextMonth("2026-01")).toBe("2026-02");
});
it("台北 11 月的開始與結束", () => {
expect(monthStart("2026-11", TZ).toISOString()).toBe("2026-10-31T16:00:00.000Z");
expect(monthEnd("2026-11", TZ).toISOString()).toBe("2026-11-30T15:59:59.999Z");
});
});
+47
View File
@@ -0,0 +1,47 @@
import { nextDate, startOfLocalDay } from "./calendar";
/** 刷卡日期(`YYYY-MM-DD`)所屬的申請月份(`YYYY-MM`)。月份只由刷卡日期決定。 */
export function cardMonth(cardDate: string): string {
if (!/^\d{4}-\d{2}-\d{2}$/.test(cardDate)) throw new Error(`不合法的刷卡日期:${cardDate}`);
return cardDate.slice(0, 7);
}
/** 某月份(`YYYY-MM`)的下一個月份。 */
export function nextMonth(month: string): string {
const [y, m] = month.split("-").map(Number);
return m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`;
}
/** 某月份在指定時區的開始時間點(1 日 00:00)。 */
export function monthStart(month: string, timeZone: string): Date {
return startOfLocalDay(`${month}-01`, timeZone);
}
/** 某月份在指定時區的最後一刻(下個月 1 日 00:00 前 1 毫秒),用於取「該月結束時生效」的參數。 */
export function monthEnd(month: string, timeZone: string): Date {
return new Date(monthStart(nextMonth(month), timeZone).getTime() - 1);
}
/** 某月份某日在指定時區的 23:59:59。 */
function endOfDay(date: string, timeZone: string): Date {
return new Date(startOfLocalDay(nextDate(date), timeZone).getTime() - 1000);
}
/**
* 截止時刻:員工申請截止為刷卡月份次月「員工截止日」23:59:59,主管月結提交截止為
* 次月「主管截止日」23:59:59(皆為指定時區)。
*/
export function deadlinesFor(
cardDate: string,
days: { employeeDeadlineDay: number; managerDeadlineDay: number },
timeZone: string,
): { month: string; employee: Date; manager: Date } {
const month = cardMonth(cardDate);
const due = nextMonth(month);
const day = (d: number) => `${due}-${String(d).padStart(2, "0")}`;
return {
month,
employee: endOfDay(day(days.employeeDeadlineDay), timeZone),
manager: endOfDay(day(days.managerDeadlineDay), timeZone),
};
}
+4
View File
@@ -20,6 +20,10 @@ interface RouteRule {
export const ROUTE_RULES: readonly RouteRule[] = [
{ pattern: "/", roles: ["employee", "manager", "admin", "sysadmin"] },
{ pattern: "/dashboard", roles: ["employee", "manager", "admin", "sysadmin"] },
{ pattern: "/help", roles: ["employee", "manager", "admin", "sysadmin"] },
{ pattern: "/faq", roles: ["employee", "manager", "admin", "sysadmin"] },
// 設計 tokens 展示頁:頁面本身只在開發登入模式開放。
{ pattern: "/design-tokens", roles: ["employee", "manager", "admin", "sysadmin"] },
{ pattern: "/applications", roles: ["employee"] },
{ pattern: "/applications/new", roles: ["employee"] },
// 詳情頁的資料範圍另由 scopeApplications 檢查。
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { APPLICATION_STATUSES, APPLICATION_STATUS_DISPLAY } from "./application-status";
describe("案件狀態標籤", () => {
it("待主管審核顯示「待審核」而非「審核中」", () => {
expect(APPLICATION_STATUS_DISPLAY.pending_review.label).toBe("待審核");
});
it("每個狀態都有文字標籤與語意色,且文字互不重複(灰階時仍可區分)", () => {
const labels = APPLICATION_STATUSES.map((s) => APPLICATION_STATUS_DISPLAY[s].label);
expect(labels).toEqual([
"草稿",
"待審核",
"待補件",
"已通過",
"不核准",
"待月結",
"已提交",
"已核定",
"已發放",
"已撤回",
]);
expect(new Set(labels).size).toBe(labels.length);
for (const s of APPLICATION_STATUSES) expect(APPLICATION_STATUS_DISPLAY[s].tone).toBeTruthy();
});
});
+40
View File
@@ -0,0 +1,40 @@
// 案件狀態代碼 → 顯示文字與語意色(介面規劃 §9)。內部代碼不等於顯示文字:
// 例如「待主管審核」顯示為「待審核」。標籤一律同時有文字與顏色,不只靠顏色區分。
export const APPLICATION_STATUSES = [
"draft",
"pending_review",
"needs_revision",
"approved",
"rejected",
"pending_settlement",
"submitted",
"finalized",
"paid",
"withdrawn",
] as const;
export type ApplicationStatus = (typeof APPLICATION_STATUSES)[number];
export type StatusTone = "neutral" | "warning" | "danger" | "success" | "info" | "violet";
export const APPLICATION_STATUS_DISPLAY: Record<
ApplicationStatus,
{ label: string; tone: StatusTone }
> = {
draft: { label: "草稿", tone: "neutral" },
pending_review: { label: "待審核", tone: "warning" },
needs_revision: { label: "待補件", tone: "danger" },
approved: { label: "已通過", tone: "success" },
rejected: { label: "不核准", tone: "danger" },
pending_settlement: { label: "待月結", tone: "info" },
submitted: { label: "已提交", tone: "info" },
finalized: { label: "已核定", tone: "success" },
paid: { label: "已發放", tone: "violet" },
// 撤回在狀態機中是轉移事件(案件回到草稿),保留標籤供時間軸事件顯示。
withdrawn: { label: "已撤回", tone: "neutral" },
};
export function applicationStatusDisplay(status: ApplicationStatus) {
return APPLICATION_STATUS_DISPLAY[status];
}
+7
View File
@@ -20,6 +20,11 @@ export const AUDIT_ACTIONS = {
"department.manager_assigned": "指派部門主管",
"department.manager_removed": "移除部門主管",
"roster.imported": "匯入名冊",
"settings.updated": "變更制度參數",
"headcount.snapshot_created": "建立人數快照",
"headcount.adjusted": "調整快照人數",
"headcount.locked": "鎖定人數快照",
"headcount.unlocked": "解除人數快照鎖定",
} as const;
export type AuditAction = keyof typeof AUDIT_ACTIONS;
@@ -28,6 +33,8 @@ export const AUDIT_TARGET_TYPES = {
user: "帳號",
department: "部門",
roster: "名冊匯入",
rule_version: "制度參數版本",
headcount_snapshot: "人數快照",
} as const;
export type AuditTargetType = keyof typeof AUDIT_TARGET_TYPES;
+44 -1
View File
@@ -1,8 +1,51 @@
import { describe, expect, it } from "vitest";
import { formatDateTime } from "./format";
import { formatDate, formatDateTime, formatLongDate, formatMoney, formatMonth } from "./format";
describe("formatMoney", () => {
it("NT$ 加千分位整數", () => {
expect(formatMoney(13000)).toBe("NT$13,000");
expect(formatMoney(1700)).toBe("NT$1,700");
expect(formatMoney(0)).toBe("NT$0");
expect(formatMoney(1234567)).toBe("NT$1,234,567");
});
it("尚無數值時顯示「--」", () => {
expect(formatMoney(null)).toBe("--");
expect(formatMoney(undefined)).toBe("--");
});
it("負數(更正差額)帶負號", () => {
expect(formatMoney(-450)).toBe("-NT$450");
});
});
describe("formatDate/formatMonth", () => {
it("刷卡日期 2026-10-05 → 2026/10/05,所屬月份 → 2026/10", () => {
expect(formatDate("2026-10-05")).toBe("2026/10/05");
expect(formatMonth("2026-10-05")).toBe("2026/10");
expect(formatMonth("2026-10")).toBe("2026/10");
});
it("時間點以台北日期顯示", () => {
// UTC 9/30 16:30 = 台北 10/01 00:30
expect(formatDate("2026-09-30T16:30:00.000Z")).toBe("2026/10/01");
expect(formatMonth(new Date("2026-09-30T16:30:00.000Z"))).toBe("2026/10");
});
it("沒有值時顯示「--」", () => {
expect(formatDate(null)).toBe("--");
expect(formatMonth(undefined)).toBe("--");
});
});
describe("formatDateTime", () => {
it("以指定時區顯示 YYYY/MM/DD HH:mm:ss", () => {
expect(formatDateTime("2026-10-31T16:05:09.000Z", "Asia/Taipei")).toBe("2026/11/01 00:05:09");
});
});
describe("formatLongDate", () => {
it("頂部列日期含星期", () => {
expect(formatLongDate(new Date("2026-10-01T02:00:00Z"))).toBe("2026 年 10 月 1 日 星期四");
});
});
+74 -6
View File
@@ -1,7 +1,21 @@
// 顯示格式(前端規劃):日期 YYYY/MM/DD、時間 YYYY/MM/DD HH:mm:ss,一律以業務時區顯示。
// 顯示格式的唯一來源(介面規劃 §10):頁面與元件一律透過這裡或 MoneyDisplay/StatusBadge 呈現,
// 不自行格式化。日期時間一律以業務時區(Asia/Taipei)顯示。
export function formatDateTime(iso: string, timeZone: string): string {
const parts = Object.fromEntries(
export const APP_TIME_ZONE = "Asia/Taipei";
/** 尚無數值(例如月結前的最終補助)時顯示的文字。 */
export const EMPTY_VALUE = "--";
const moneyFormatter = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });
/** 金額:NT$ + 千分位整數(例如 NT$13,000);null/undefined 顯示「--」。 */
export function formatMoney(amount: number | null | undefined): string {
if (amount === null || amount === undefined || Number.isNaN(amount)) return EMPTY_VALUE;
const sign = amount < 0 ? "-" : "";
return `${sign}NT$${moneyFormatter.format(Math.abs(Math.round(amount)))}`;
}
function zonedParts(instant: Date, timeZone: string) {
return Object.fromEntries(
new Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
@@ -11,9 +25,63 @@ export function formatDateTime(iso: string, timeZone: string): string {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
weekday: "short",
})
.formatToParts(new Date(iso))
.formatToParts(instant)
.map((p) => [p.type, p.value]),
);
return `${parts.year}/${parts.month}/${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`;
) as Record<"year" | "month" | "day" | "hour" | "minute" | "second" | "weekday", string>;
}
const PLAIN_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
/**
* 日期:YYYY/MM/DD。`YYYY-MM-DD`(刷卡日期等純日期)直接轉換、不經時區;
* 時間點(ISO 字串或 Date)以業務時區換算當地日期。
*/
export function formatDate(
value: string | Date | null | undefined,
timeZone = APP_TIME_ZONE,
): string {
if (!value) return EMPTY_VALUE;
if (typeof value === "string") {
const plain = value.match(PLAIN_DATE);
if (plain) return `${plain[1]}/${plain[2]}/${plain[3]}`;
}
const p = zonedParts(new Date(value), timeZone);
return `${p.year}/${p.month}/${p.day}`;
}
/** 月份:YYYY/MM。接受 `YYYY-MM`、`YYYY-MM-DD` 或時間點。 */
export function formatMonth(
value: string | Date | null | undefined,
timeZone = APP_TIME_ZONE,
): string {
if (!value) return EMPTY_VALUE;
if (typeof value === "string") {
const month = value.match(/^(\d{4})-(\d{2})(?:-\d{2})?$/);
if (month) return `${month[1]}/${month[2]}`;
}
return formatDate(value, timeZone).slice(0, 7);
}
/** 時間:YYYY/MM/DD HH:mm:ss(操作紀錄等)。 */
export function formatDateTime(value: string | Date, timeZone = APP_TIME_ZONE): string {
const p = zonedParts(new Date(value), timeZone);
return `${p.year}/${p.month}/${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
const WEEKDAYS: Record<string, string> = {
Sun: "日",
Mon: "一",
Tue: "二",
Wed: "三",
Thu: "四",
Fri: "五",
Sat: "六",
};
/** 頂部列的今日日期:「2026 年 10 月 1 日 星期四」。 */
export function formatLongDate(value: Date, timeZone = APP_TIME_ZONE): string {
const p = zonedParts(value, timeZone);
return `${Number(p.year)} 年 ${Number(p.month)} 月 ${Number(p.day)} 日 星期${WEEKDAYS[p.weekday]}`;
}
+35 -7
View File
@@ -1,12 +1,12 @@
import { describe, expect, it } from "vitest";
import { buildNavigation } from "./navigation";
import { activeNavHref, buildNavigation } from "./navigation";
import type { Role } from "./roles";
const labels = (roles: Role[]) => buildNavigation(roles).map((item) => item.label);
const labels = (roles: Role[], flags = {}) => buildNavigation(roles, flags).map((i) => i.label);
describe("buildNavigation", () => {
it("員工:首頁、新增申請、我的申請", () => {
expect(labels(["employee"])).toEqual(["首頁", "新增申請", "我的申請"]);
it("一般員工:首頁、新增申請、我的申請、使用說明、常見問題", () => {
expect(labels(["employee"])).toEqual(["首頁", "新增申請", "我的申請", "使用說明", "常見問題"]);
});
it("員工看不到部門審核、全公司月結、後台設定等管理項目", () => {
@@ -23,13 +23,15 @@ describe("buildNavigation", () => {
}
});
it("主管(兼員工):加上部門審核、部門月結", () => {
it("兼任主管的員工:加上部門審核、部門月結", () => {
expect(labels(["employee", "manager"])).toEqual([
"首頁",
"新增申請",
"我的申請",
"部門審核",
"部門月結",
"使用說明",
"常見問題",
]);
});
@@ -41,6 +43,8 @@ describe("buildNavigation", () => {
"全公司月結",
"發放管理",
"後台設定",
"使用說明",
"常見問題",
]);
});
@@ -53,12 +57,36 @@ describe("buildNavigation", () => {
"帳號與角色",
"部門管理",
"操作紀錄",
"使用說明",
"常見問題",
]);
});
it("同時兼任多個角色時取聯集且不重複", () => {
it("同時兼任所有角色時取聯集且不重複;後台設定只出現一次", () => {
const items = labels(["employee", "manager", "admin", "sysadmin"]);
expect(items).toHaveLength(11);
expect(items).toHaveLength(13);
expect(new Set(items).size).toBe(items.length);
});
it("使用說明與常見問題屬於 support 群組", () => {
const support = buildNavigation(["employee"]).filter((i) => i.group === "support");
expect(support.map((i) => i.href)).toEqual(["/help", "/faq"]);
});
});
describe("activeNavHref", () => {
const items = buildNavigation(["employee", "manager"]);
it("目前頁面高亮:我的申請頁只高亮「我的申請」", () => {
expect(activeNavHref("/applications", items)).toBe("/applications");
});
it("子頁面歸屬最接近的項目", () => {
expect(activeNavHref("/applications/42", items)).toBe("/applications");
expect(activeNavHref("/applications/new", items)).toBe("/applications/new");
});
it("沒有對應項目時不高亮", () => {
expect(activeNavHref("/somewhere", items)).toBeNull();
});
});
+47 -13
View File
@@ -1,27 +1,61 @@
import { canAccessRoute, type AccessFlags } from "./access";
import type { Role } from "./roles";
export type NavIcon =
| "home"
| "new"
| "list"
| "review"
| "settlement"
| "company"
| "payout"
| "settings"
| "accounts"
| "departments"
| "audit"
| "help"
| "faq";
export interface NavItem {
label: string;
href: string;
icon: NavIcon;
/** main = 功能;support = 使用說明、常見問題(側欄下方,以分隔線區隔)。 */
group: "main" | "support";
}
/** 側欄項目(前端規劃 §11)。顯示與否完全由 ROUTE_RULES 決定,與伺服器端路由檢查同源。 */
/**
* 側欄項目(介面規劃 §2、app-shell spec)。顯示與否完全由 ROUTE_RULES 決定,
* 與伺服器端路由檢查同源;順序固定,兼任角色時自然去重。
*/
const NAV_ITEMS: readonly NavItem[] = [
{ label: "首頁", href: "/dashboard" },
{ label: "新增申請", href: "/applications/new" },
{ label: "我的申請", href: "/applications" },
{ label: "部門審核", href: "/department/review" },
{ label: "部門月結", href: "/department/settlement" },
{ label: "全公司月結", href: "/admin/settlements" },
{ label: "發放管理", href: "/admin/payments" },
{ label: "後台設定", href: "/admin/settings" },
{ label: "帳號與角色", href: "/admin/accounts" },
{ label: "部門管理", href: "/admin/departments" },
{ label: "操作紀錄", href: "/admin/audit-log" },
{ label: "首頁", href: "/dashboard", icon: "home", group: "main" },
{ label: "新增申請", href: "/applications/new", icon: "new", group: "main" },
{ label: "我的申請", href: "/applications", icon: "list", group: "main" },
{ label: "部門審核", href: "/department/review", icon: "review", group: "main" },
{ label: "部門月結", href: "/department/settlement", icon: "settlement", group: "main" },
{ label: "全公司月結", href: "/admin/settlements", icon: "company", group: "main" },
{ label: "發放管理", href: "/admin/payments", icon: "payout", group: "main" },
{ label: "後台設定", href: "/admin/settings", icon: "settings", group: "main" },
{ label: "帳號與角色", href: "/admin/accounts", icon: "accounts", group: "main" },
{ label: "部門管理", href: "/admin/departments", icon: "departments", group: "main" },
{ label: "操作紀錄", href: "/admin/audit-log", icon: "audit", group: "main" },
{ label: "使用說明", href: "/help", icon: "help", group: "support" },
{ label: "常見問題", href: "/faq", icon: "faq", group: "support" },
];
/** 依角色產生側欄導覽資料(供 add-app-shell 使用)。兼任角色取聯集。 */
/** 依角色產生側欄導覽資料。兼任角色取聯集。 */
export function buildNavigation(roles: readonly Role[], flags: AccessFlags = {}): NavItem[] {
return NAV_ITEMS.filter((item) => canAccessRoute(item.href, roles, flags));
}
/**
* 目前頁面對應的導覽項目:最長前綴相符者(`/applications/42` → 我的申請,
* `/applications/new` → 新增申請)。
*/
export function activeNavHref(pathname: string, items: readonly Pick<NavItem, "href">[]) {
const matches = items.filter(
(item) => pathname === item.href || pathname.startsWith(`${item.href}/`),
);
return matches.sort((a, b) => b.href.length - a.href.length)[0]?.href ?? null;
}
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_RULE_PARAMS,
OTHER_PLATFORM,
platformOptions,
ruleParamsSchema,
type RuleParams,
} from "./rule-params";
const withChange = (patch: (p: RuleParams) => void): unknown => {
const p = structuredClone(DEFAULT_RULE_PARAMS);
patch(p);
return p;
};
const errors = (input: unknown) => {
const r = ruleParamsSchema.safeParse(input);
return r.success
? {}
: Object.fromEntries(r.error.issues.map((i) => [i.path.join("."), i.message]));
};
describe("制度參數驗證", () => {
it("預設值通過驗證,且沒有個人月補助上限", () => {
expect(ruleParamsSchema.safeParse(DEFAULT_RULE_PARAMS).success).toBe(true);
expect(Object.keys(DEFAULT_RULE_PARAMS)).not.toContain("personalMonthlyCap");
expect(JSON.stringify(DEFAULT_RULE_PARAMS)).not.toMatch(/personal|個人/i);
});
it("預設值符合規格 §16", () => {
expect(DEFAULT_RULE_PARAMS).toEqual({
perPersonQuota: { general: 500, rnd: 1000 },
subsidyRatePercent: 50,
rounding: "floor",
employeeDeadlineDay: 20,
managerDeadlineDay: 25,
platforms: ["ChatGPT", "Claude", "Gemini"],
attachment: { maxSizeMb: 10, formats: ["pdf", "jpg", "png"] },
});
});
it("主管截止日不晚於員工截止日時拒絕", () => {
expect(errors(withChange((p) => (p.managerDeadlineDay = 18)))).toEqual({
managerDeadlineDay: "主管提交截止日必須晚於員工申請截止日",
});
expect(errors(withChange((p) => (p.managerDeadlineDay = 20)))).toHaveProperty(
"managerDeadlineDay",
);
});
it("額度須為正整數(500.5、0 都拒絕)", () => {
expect(errors(withChange((p) => (p.perPersonQuota.general = 500.5)))).toEqual({
"perPersonQuota.general": "一般部門每人月額度須為正整數",
});
expect(errors(withChange((p) => (p.perPersonQuota.rnd = 0)))).toHaveProperty(
"perPersonQuota.rnd",
);
});
it("比例 1–100、截止日 1–28、附件 1–50 MB", () => {
expect(errors(withChange((p) => (p.subsidyRatePercent = 0)))).toHaveProperty(
"subsidyRatePercent",
);
expect(errors(withChange((p) => (p.subsidyRatePercent = 101)))).toHaveProperty(
"subsidyRatePercent",
);
expect(
errors(withChange((p) => ((p.employeeDeadlineDay = 29), (p.managerDeadlineDay = 30)))),
).toHaveProperty("employeeDeadlineDay");
expect(errors(withChange((p) => (p.attachment.maxSizeMb = 51)))).toHaveProperty(
"attachment.maxSizeMb",
);
});
it("取整方式只能是無條件捨去或四捨五入", () => {
expect(
errors(withChange((p) => ((p as { rounding: string }).rounding = "ceil"))),
).toHaveProperty("rounding");
});
it("平台清單至少一項、不重複(不分大小寫),且不能自行加入「其他」", () => {
expect(errors(withChange((p) => (p.platforms = [])))).toHaveProperty("platforms");
expect(errors(withChange((p) => (p.platforms = ["ChatGPT", "chatgpt"])))).toEqual({
"platforms.1": "平台「chatgpt」重複",
});
expect(errors(withChange((p) => (p.platforms = ["ChatGPT", OTHER_PLATFORM])))).toHaveProperty(
"platforms.1",
);
});
it("附件格式至少一項,且只能從 PDF/JPG/PNG 選擇", () => {
expect(errors(withChange((p) => (p.attachment.formats = [])))).toHaveProperty(
"attachment.formats",
);
expect(
errors(
withChange((p) => ((p.attachment as { formats: string[] }).formats = ["pdf", "docx"])),
),
).toHaveProperty("attachment.formats.1");
});
});
describe("platformOptions", () => {
it("主要平台+固定的「其他」", () => {
expect(platformOptions({ platforms: ["ChatGPT", "Claude", "Gemini", "Perplexity"] })).toEqual([
"ChatGPT",
"Claude",
"Gemini",
"Perplexity",
"其他",
]);
});
it("「其他」無法被移除:即使清單只剩一項也會附加", () => {
expect(platformOptions({ platforms: ["Claude"] })).toEqual(["Claude", "其他"]);
});
});
+133
View File
@@ -0,0 +1,133 @@
import { z } from "zod";
// 制度參數(規格 §16):前端表單與伺服器共用同一份 schema 與預設值。
// 不提供個人月補助上限參數(使用者決定:無個人上限)。
export const ATTACHMENT_FORMATS = ["pdf", "jpg", "png"] as const;
export const ATTACHMENT_FORMAT_LABELS: Record<(typeof ATTACHMENT_FORMATS)[number], string> = {
pdf: "PDF",
jpg: "JPG",
png: "PNG",
};
export const ROUNDING_MODES = ["floor", "half_up"] as const;
export const ROUNDING_LABELS: Record<(typeof ROUNDING_MODES)[number], string> = {
floor: "無條件捨去",
half_up: "四捨五入",
};
/** 申請表單一定附加的平台選項,不在參數清單內、不可移除。 */
export const OTHER_PLATFORM = "其他";
const positiveInt = (label: string) =>
z
.number({ error: `${label}須為正整數` })
.int(`${label}須為正整數`)
.positive(`${label}須為正整數`);
export const ruleParamsSchema = z
.object({
perPersonQuota: z.object({
general: positiveInt("一般部門每人月額度"),
rnd: positiveInt("研發部每人月額度"),
}),
subsidyRatePercent: z
.number({ error: "補助比例須為 1 到 100 的整數" })
.int("補助比例須為 1 到 100 的整數")
.min(1, "補助比例須為 1 到 100 的整數")
.max(100, "補助比例須為 1 到 100 的整數"),
rounding: z.enum(ROUNDING_MODES, { error: "取整方式須為無條件捨去或四捨五入" }),
employeeDeadlineDay: z
.number({ error: "員工申請截止日須為 1 到 28 日" })
.int("員工申請截止日須為 1 到 28 日")
.min(1, "員工申請截止日須為 1 到 28 日")
.max(28, "員工申請截止日須為 1 到 28 日"),
managerDeadlineDay: z
.number({ error: "主管提交截止日須為 1 到 28 日" })
.int("主管提交截止日須為 1 到 28 日")
.min(1, "主管提交截止日須為 1 到 28 日")
.max(28, "主管提交截止日須為 1 到 28 日"),
platforms: z
.array(z.string().trim().min(1, "平台名稱不可空白").max(30, "平台名稱最多 30 字"))
.min(1, "平台清單至少需要一項"),
attachment: z.object({
maxSizeMb: z
.number({ error: "附件單檔上限須為 1 到 50 MB 的整數" })
.int("附件單檔上限須為 1 到 50 MB 的整數")
.min(1, "附件單檔上限須為 1 到 50 MB 的整數")
.max(50, "附件單檔上限須為 1 到 50 MB 的整數"),
formats: z
.array(z.enum(ATTACHMENT_FORMATS, { error: "附件格式只能是 PDF、JPG、PNG" }))
.min(1, "允許格式至少需要一項"),
}),
})
.superRefine((p, ctx) => {
if (p.managerDeadlineDay <= p.employeeDeadlineDay) {
ctx.addIssue({
code: "custom",
path: ["managerDeadlineDay"],
message: "主管提交截止日必須晚於員工申請截止日",
});
}
const seen = new Set<string>();
p.platforms.forEach((name, i) => {
const key = name.trim().toLowerCase();
if (name.trim() === OTHER_PLATFORM) {
ctx.addIssue({
code: "custom",
path: ["platforms", i],
message: "「其他」會自動附加在選項最後,不需加入清單",
});
} else if (seen.has(key)) {
ctx.addIssue({ code: "custom", path: ["platforms", i], message: `平台「${name}」重複` });
}
seen.add(key);
});
if (new Set(p.attachment.formats).size !== p.attachment.formats.length) {
ctx.addIssue({ code: "custom", path: ["attachment", "formats"], message: "允許格式重複" });
}
});
export type RuleParams = z.infer<typeof ruleParamsSchema>;
/** 規格 §16 預設值(取整為無條件捨去)。 */
export const DEFAULT_RULE_PARAMS: RuleParams = {
perPersonQuota: { general: 500, rnd: 1000 },
subsidyRatePercent: 50,
rounding: "floor",
employeeDeadlineDay: 20,
managerDeadlineDay: 25,
platforms: ["ChatGPT", "Claude", "Gemini"],
attachment: { maxSizeMb: 10, formats: ["pdf", "jpg", "png"] },
};
/** 申請表單的平台選項:參數中的主要平台+固定的「其他」。 */
export function platformOptions(params: Pick<RuleParams, "platforms">): string[] {
return [...params.platforms.map((p) => p.trim()), OTHER_PLATFORM];
}
/** 參數欄位的中文名稱(版本差異、操作紀錄顯示用)。 */
export const RULE_PARAM_LABELS: Record<string, string> = {
"perPersonQuota.general": "一般部門每人月額度",
"perPersonQuota.rnd": "研發部每人月額度",
subsidyRatePercent: "補助比例(%)",
rounding: "取整方式",
employeeDeadlineDay: "員工申請截止日",
managerDeadlineDay: "主管提交截止日",
platforms: "主要平台",
"attachment.maxSizeMb": "附件單檔上限(MB)",
"attachment.formats": "附件允許格式",
};
/** 攤平成「欄位路徑 → 值」,用於比較兩個版本的差異。 */
export function flattenParams(params: RuleParams): Record<string, unknown> {
return {
"perPersonQuota.general": params.perPersonQuota.general,
"perPersonQuota.rnd": params.perPersonQuota.rnd,
subsidyRatePercent: params.subsidyRatePercent,
rounding: params.rounding,
employeeDeadlineDay: params.employeeDeadlineDay,
managerDeadlineDay: params.managerDeadlineDay,
platforms: params.platforms,
"attachment.maxSizeMb": params.attachment.maxSizeMb,
"attachment.formats": params.attachment.formats,
};
}
@@ -0,0 +1,39 @@
CREATE TABLE `headcount_adjustments` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`snapshot_id` integer NOT NULL,
`before` integer NOT NULL,
`after` integer NOT NULL,
`reason` text NOT NULL,
`actor_user_id` integer,
`actor_label` text NOT NULL,
`created_at` text NOT NULL,
FOREIGN KEY (`snapshot_id`) REFERENCES `headcount_snapshots`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `headcount_adjustments_snapshot_idx` ON `headcount_adjustments` (`snapshot_id`);--> statement-breakpoint
CREATE TABLE `headcount_snapshots` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`department_id` integer NOT NULL,
`month` text NOT NULL,
`headcount` integer NOT NULL,
`computed_headcount` integer NOT NULL,
`locked` integer DEFAULT false NOT NULL,
`created_by_label` text NOT NULL,
`created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) NOT NULL,
FOREIGN KEY (`department_id`) REFERENCES `departments`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE UNIQUE INDEX `headcount_snapshots_department_month_unique` ON `headcount_snapshots` (`department_id`,`month`);--> statement-breakpoint
CREATE TABLE `rule_versions` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`params_json` text NOT NULL,
`effective_at` text NOT NULL,
`created_by` integer,
`created_by_label` text NOT NULL,
`reason` text NOT NULL,
`created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) NOT NULL,
FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `rule_versions_effective_idx` ON `rule_versions` (`effective_at`,`id`);
@@ -0,0 +1,20 @@
-- 制度參數版本與人數調整紀錄只新增不修改(add-rule-settings design)。
CREATE TRIGGER `rule_versions_no_update` BEFORE UPDATE ON `rule_versions`
BEGIN
SELECT RAISE(ABORT, 'rule_versions is append-only');
END;
--> statement-breakpoint
CREATE TRIGGER `rule_versions_no_delete` BEFORE DELETE ON `rule_versions`
BEGIN
SELECT RAISE(ABORT, 'rule_versions is append-only');
END;
--> statement-breakpoint
CREATE TRIGGER `headcount_adjustments_no_update` BEFORE UPDATE ON `headcount_adjustments`
BEGIN
SELECT RAISE(ABORT, 'headcount_adjustments is append-only');
END;
--> statement-breakpoint
CREATE TRIGGER `headcount_adjustments_no_delete` BEFORE DELETE ON `headcount_adjustments`
BEGIN
SELECT RAISE(ABORT, 'headcount_adjustments is append-only');
END;
@@ -0,0 +1,879 @@
{
"version": "6",
"dialect": "sqlite",
"id": "b16d5ee9-2693-4950-95f9-978d3874e424",
"prevId": "caf08cc3-215c-4ddd-a155-298326c6907d",
"tables": {
"_meta": {
"name": "_meta",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"department_managers": {
"name": "department_managers",
"columns": {
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"department_managers_user_idx": {
"name": "department_managers_user_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"department_managers_department_id_departments_id_fk": {
"name": "department_managers_department_id_departments_id_fk",
"tableFrom": "department_managers",
"tableTo": "departments",
"columnsFrom": [
"department_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"department_managers_user_id_users_id_fk": {
"name": "department_managers_user_id_users_id_fk",
"tableFrom": "department_managers",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"department_managers_department_id_user_id_pk": {
"columns": [
"department_id",
"user_id"
],
"name": "department_managers_department_id_user_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"departments": {
"name": "departments",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"code": {
"name": "code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"active": {
"name": "active",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"departments_code_unique": {
"name": "departments_code_unique",
"columns": [
"code"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_department_history": {
"name": "user_department_history",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"effective_from": {
"name": "effective_from",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"user_department_history_user_idx": {
"name": "user_department_history_user_idx",
"columns": [
"user_id",
"effective_from"
],
"isUnique": false
}
},
"foreignKeys": {
"user_department_history_user_id_users_id_fk": {
"name": "user_department_history_user_id_users_id_fk",
"tableFrom": "user_department_history",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"user_department_history_department_id_departments_id_fk": {
"name": "user_department_history_department_id_departments_id_fk",
"tableFrom": "user_department_history",
"tableTo": "departments",
"columnsFrom": [
"department_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"employee_no": {
"name": "employee_no",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"active": {
"name": "active",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"first_login_at": {
"name": "first_login_at",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_login_at": {
"name": "last_login_at",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"can_view_audit_log": {
"name": "can_view_audit_log",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"users_employee_no_unique": {
"name": "users_employee_no_unique",
"columns": [
"employee_no"
],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
"columns": [
"email"
],
"isUnique": true
}
},
"foreignKeys": {
"users_department_id_departments_id_fk": {
"name": "users_department_id_departments_id_fk",
"tableFrom": "users",
"tableTo": "departments",
"columnsFrom": [
"department_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"token_hash": {
"name": "token_hash",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
},
"last_seen_at": {
"name": "last_seen_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"sessions_user_idx": {
"name": "sessions_user_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk",
"tableFrom": "sessions",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_roles": {
"name": "user_roles",
"columns": {
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"role": {
"name": "role",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"user_roles_user_id_users_id_fk": {
"name": "user_roles_user_id_users_id_fk",
"tableFrom": "user_roles",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"user_roles_user_id_role_pk": {
"columns": [
"user_id",
"role"
],
"name": "user_roles_user_id_role_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"audit_logs": {
"name": "audit_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"occurred_at": {
"name": "occurred_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"actor_user_id": {
"name": "actor_user_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"actor_label": {
"name": "actor_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"action": {
"name": "action",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"target_type": {
"name": "target_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"target_id": {
"name": "target_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"before_json": {
"name": "before_json",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"after_json": {
"name": "after_json",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"comment": {
"name": "comment",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"ip": {
"name": "ip",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"audit_logs_target_idx": {
"name": "audit_logs_target_idx",
"columns": [
"target_type",
"target_id"
],
"isUnique": false
},
"audit_logs_occurred_idx": {
"name": "audit_logs_occurred_idx",
"columns": [
"occurred_at",
"id"
],
"isUnique": false
},
"audit_logs_actor_idx": {
"name": "audit_logs_actor_idx",
"columns": [
"actor_user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"audit_logs_actor_user_id_users_id_fk": {
"name": "audit_logs_actor_user_id_users_id_fk",
"tableFrom": "audit_logs",
"tableTo": "users",
"columnsFrom": [
"actor_user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"headcount_adjustments": {
"name": "headcount_adjustments",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"snapshot_id": {
"name": "snapshot_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"before": {
"name": "before",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"after": {
"name": "after",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"reason": {
"name": "reason",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"actor_user_id": {
"name": "actor_user_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"actor_label": {
"name": "actor_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"headcount_adjustments_snapshot_idx": {
"name": "headcount_adjustments_snapshot_idx",
"columns": [
"snapshot_id"
],
"isUnique": false
}
},
"foreignKeys": {
"headcount_adjustments_snapshot_id_headcount_snapshots_id_fk": {
"name": "headcount_adjustments_snapshot_id_headcount_snapshots_id_fk",
"tableFrom": "headcount_adjustments",
"tableTo": "headcount_snapshots",
"columnsFrom": [
"snapshot_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"headcount_adjustments_actor_user_id_users_id_fk": {
"name": "headcount_adjustments_actor_user_id_users_id_fk",
"tableFrom": "headcount_adjustments",
"tableTo": "users",
"columnsFrom": [
"actor_user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"headcount_snapshots": {
"name": "headcount_snapshots",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"month": {
"name": "month",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"headcount": {
"name": "headcount",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"computed_headcount": {
"name": "computed_headcount",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"locked": {
"name": "locked",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_by_label": {
"name": "created_by_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"headcount_snapshots_department_month_unique": {
"name": "headcount_snapshots_department_month_unique",
"columns": [
"department_id",
"month"
],
"isUnique": true
}
},
"foreignKeys": {
"headcount_snapshots_department_id_departments_id_fk": {
"name": "headcount_snapshots_department_id_departments_id_fk",
"tableFrom": "headcount_snapshots",
"tableTo": "departments",
"columnsFrom": [
"department_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"rule_versions": {
"name": "rule_versions",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"params_json": {
"name": "params_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"effective_at": {
"name": "effective_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_by": {
"name": "created_by",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_by_label": {
"name": "created_by_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"reason": {
"name": "reason",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"rule_versions_effective_idx": {
"name": "rule_versions_effective_idx",
"columns": [
"effective_at",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"rule_versions_created_by_users_id_fk": {
"name": "rule_versions_created_by_users_id_fk",
"tableFrom": "rule_versions",
"tableTo": "users",
"columnsFrom": [
"created_by"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
@@ -0,0 +1,879 @@
{
"id": "e912c99b-00c9-47d4-a403-8bc018e66ab5",
"prevId": "b16d5ee9-2693-4950-95f9-978d3874e424",
"version": "6",
"dialect": "sqlite",
"tables": {
"_meta": {
"name": "_meta",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"department_managers": {
"name": "department_managers",
"columns": {
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"department_managers_user_idx": {
"name": "department_managers_user_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"department_managers_department_id_departments_id_fk": {
"name": "department_managers_department_id_departments_id_fk",
"tableFrom": "department_managers",
"columnsFrom": [
"department_id"
],
"tableTo": "departments",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"department_managers_user_id_users_id_fk": {
"name": "department_managers_user_id_users_id_fk",
"tableFrom": "department_managers",
"columnsFrom": [
"user_id"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {
"department_managers_department_id_user_id_pk": {
"columns": [
"department_id",
"user_id"
],
"name": "department_managers_department_id_user_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"departments": {
"name": "departments",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"code": {
"name": "code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"active": {
"name": "active",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"departments_code_unique": {
"name": "departments_code_unique",
"columns": [
"code"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_department_history": {
"name": "user_department_history",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"effective_from": {
"name": "effective_from",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"user_department_history_user_idx": {
"name": "user_department_history_user_idx",
"columns": [
"user_id",
"effective_from"
],
"isUnique": false
}
},
"foreignKeys": {
"user_department_history_user_id_users_id_fk": {
"name": "user_department_history_user_id_users_id_fk",
"tableFrom": "user_department_history",
"columnsFrom": [
"user_id"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"user_department_history_department_id_departments_id_fk": {
"name": "user_department_history_department_id_departments_id_fk",
"tableFrom": "user_department_history",
"columnsFrom": [
"department_id"
],
"tableTo": "departments",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"employee_no": {
"name": "employee_no",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"active": {
"name": "active",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"first_login_at": {
"name": "first_login_at",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_login_at": {
"name": "last_login_at",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"can_view_audit_log": {
"name": "can_view_audit_log",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"users_employee_no_unique": {
"name": "users_employee_no_unique",
"columns": [
"employee_no"
],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
"columns": [
"email"
],
"isUnique": true
}
},
"foreignKeys": {
"users_department_id_departments_id_fk": {
"name": "users_department_id_departments_id_fk",
"tableFrom": "users",
"columnsFrom": [
"department_id"
],
"tableTo": "departments",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"token_hash": {
"name": "token_hash",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
},
"last_seen_at": {
"name": "last_seen_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"sessions_user_idx": {
"name": "sessions_user_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk",
"tableFrom": "sessions",
"columnsFrom": [
"user_id"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_roles": {
"name": "user_roles",
"columns": {
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"role": {
"name": "role",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"user_roles_user_id_users_id_fk": {
"name": "user_roles_user_id_users_id_fk",
"tableFrom": "user_roles",
"columnsFrom": [
"user_id"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {
"user_roles_user_id_role_pk": {
"columns": [
"user_id",
"role"
],
"name": "user_roles_user_id_role_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"audit_logs": {
"name": "audit_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"occurred_at": {
"name": "occurred_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"actor_user_id": {
"name": "actor_user_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"actor_label": {
"name": "actor_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"action": {
"name": "action",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"target_type": {
"name": "target_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"target_id": {
"name": "target_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"before_json": {
"name": "before_json",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"after_json": {
"name": "after_json",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"comment": {
"name": "comment",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"ip": {
"name": "ip",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"audit_logs_target_idx": {
"name": "audit_logs_target_idx",
"columns": [
"target_type",
"target_id"
],
"isUnique": false
},
"audit_logs_occurred_idx": {
"name": "audit_logs_occurred_idx",
"columns": [
"occurred_at",
"id"
],
"isUnique": false
},
"audit_logs_actor_idx": {
"name": "audit_logs_actor_idx",
"columns": [
"actor_user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"audit_logs_actor_user_id_users_id_fk": {
"name": "audit_logs_actor_user_id_users_id_fk",
"tableFrom": "audit_logs",
"columnsFrom": [
"actor_user_id"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"headcount_adjustments": {
"name": "headcount_adjustments",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"snapshot_id": {
"name": "snapshot_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"before": {
"name": "before",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"after": {
"name": "after",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"reason": {
"name": "reason",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"actor_user_id": {
"name": "actor_user_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"actor_label": {
"name": "actor_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"headcount_adjustments_snapshot_idx": {
"name": "headcount_adjustments_snapshot_idx",
"columns": [
"snapshot_id"
],
"isUnique": false
}
},
"foreignKeys": {
"headcount_adjustments_snapshot_id_headcount_snapshots_id_fk": {
"name": "headcount_adjustments_snapshot_id_headcount_snapshots_id_fk",
"tableFrom": "headcount_adjustments",
"columnsFrom": [
"snapshot_id"
],
"tableTo": "headcount_snapshots",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
},
"headcount_adjustments_actor_user_id_users_id_fk": {
"name": "headcount_adjustments_actor_user_id_users_id_fk",
"tableFrom": "headcount_adjustments",
"columnsFrom": [
"actor_user_id"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"headcount_snapshots": {
"name": "headcount_snapshots",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"department_id": {
"name": "department_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"month": {
"name": "month",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"headcount": {
"name": "headcount",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"computed_headcount": {
"name": "computed_headcount",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"locked": {
"name": "locked",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_by_label": {
"name": "created_by_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"headcount_snapshots_department_month_unique": {
"name": "headcount_snapshots_department_month_unique",
"columns": [
"department_id",
"month"
],
"isUnique": true
}
},
"foreignKeys": {
"headcount_snapshots_department_id_departments_id_fk": {
"name": "headcount_snapshots_department_id_departments_id_fk",
"tableFrom": "headcount_snapshots",
"columnsFrom": [
"department_id"
],
"tableTo": "departments",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"rule_versions": {
"name": "rule_versions",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"params_json": {
"name": "params_json",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"effective_at": {
"name": "effective_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_by": {
"name": "created_by",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_by_label": {
"name": "created_by_label",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"reason": {
"name": "reason",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
}
},
"indexes": {
"rule_versions_effective_idx": {
"name": "rule_versions_effective_idx",
"columns": [
"effective_at",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"rule_versions_created_by_users_id_fk": {
"name": "rule_versions_created_by_users_id_fk",
"tableFrom": "rule_versions",
"columnsFrom": [
"created_by"
],
"tableTo": "users",
"columnsTo": [
"id"
],
"onUpdate": "no action",
"onDelete": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
},
"internal": {
"indexes": {}
}
}
@@ -29,6 +29,20 @@
"when": 1791372340074,
"tag": "0003_audit_logs_append_only",
"breakpoints": true
},
{
"idx": 4,
"version": "6",
"when": 1791376189175,
"tag": "0004_elite_black_cat",
"breakpoints": true
},
{
"idx": 5,
"version": "6",
"when": 1791376191006,
"tag": "0005_rule_history_append_only",
"breakpoints": true
}
]
}
+1
View File
@@ -3,3 +3,4 @@ export * from "./meta";
export * from "./org-directory";
export * from "./identity-access";
export * from "./audit-trail";
export * from "./rule-settings";
+66
View File
@@ -0,0 +1,66 @@
import { sql } from "drizzle-orm";
import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
import { departments, users } from "./org-directory";
const createdAt = () =>
text("created_at")
.notNull()
.default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`);
/**
* 制度參數版本:每個版本存一份完整參數(JSON,經 ruleParamsSchema 驗證)。
* 只新增不修改;某時間點的生效參數 = effective_at <= t 的最新一筆。
*/
export const ruleVersions = sqliteTable(
"rule_versions",
{
id: integer("id").primaryKey({ autoIncrement: true }),
paramsJson: text("params_json").notNull(),
/** 生效時間(UTC ISO)。 */
effectiveAt: text("effective_at").notNull(),
/** NULL = 系統建立(初始版本)。 */
createdBy: integer("created_by").references(() => users.id),
createdByLabel: text("created_by_label").notNull(),
reason: text("reason").notNull(),
createdAt: createdAt(),
},
(t) => [index("rule_versions_effective_idx").on(t.effectiveAt, t.id)],
);
/** 部門每月計算人數快照:同一部門同一月份只有一筆。月結提交後鎖定。 */
export const headcountSnapshots = sqliteTable(
"headcount_snapshots",
{
id: integer("id").primaryKey({ autoIncrement: true }),
departmentId: integer("department_id")
.notNull()
.references(() => departments.id),
/** `YYYY-MM`。 */
month: text("month").notNull(),
headcount: integer("headcount").notNull(),
/** 建立時依 1 日 00:00 部門成員算出的人數(之後人工調整不改變此值)。 */
computedHeadcount: integer("computed_headcount").notNull(),
locked: integer("locked", { mode: "boolean" }).notNull().default(false),
createdByLabel: text("created_by_label").notNull(),
createdAt: createdAt(),
},
(t) => [uniqueIndex("headcount_snapshots_department_month_unique").on(t.departmentId, t.month)],
);
/** 快照人數的人工調整紀錄(只新增,保留前後值與原因)。 */
export const headcountAdjustments = sqliteTable(
"headcount_adjustments",
{
id: integer("id").primaryKey({ autoIncrement: true }),
snapshotId: integer("snapshot_id")
.notNull()
.references(() => headcountSnapshots.id),
before: integer("before").notNull(),
after: integer("after").notNull(),
reason: text("reason").notNull(),
actorUserId: integer("actor_user_id").references(() => users.id),
actorLabel: text("actor_label").notNull(),
createdAt: text("created_at").notNull(),
},
(t) => [index("headcount_adjustments_snapshot_idx").on(t.snapshotId)],
);
+2
View File
@@ -10,6 +10,7 @@ import {
type DepartmentType,
type Role,
} from "./schema";
import { ensureDefaultRuleVersion } from "@/server/rules/params";
import { withTransaction, type Tx } from "./transaction";
import type { Db } from "./client";
@@ -36,6 +37,7 @@ export function seed(db: Db, now: Date = new Date(), options: SeedOptions = {}):
seedDemoData(tx, localDate(now, options.timeZone ?? "Asia/Taipei"));
}
});
ensureDefaultRuleVersion(db);
}
const DEMO_DEPARTMENTS: { code: string; name: string; type: DepartmentType }[] = [
+1 -1
View File
@@ -225,7 +225,7 @@ export function setAuditLogAccess(
* 某部門在某日(Asia/Taipei 日期,自 00:00 起)的在職成員,供每月人數快照使用。
* 依每位人員在該日之前最後一筆部門生效紀錄判斷;名冊匯入而從未登入的人也包含在內。
*/
export function departmentMembersAt(db: Db, departmentId: number, date: string) {
export function departmentMembersAt(db: Db | Tx, departmentId: number, date: string) {
const latest = sql`(
select h2.id from ${userDepartmentHistory} h2
where h2.user_id = ${users.id} and h2.effective_from <= ${date}
+246
View File
@@ -0,0 +1,246 @@
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 { withTransaction } from "@/server/db/transaction";
import { assignDepartment } from "@/server/org/accounts";
import { auditRows, expectAudit, seedAuditActor, testAuditContext } from "@/server/testing/audit";
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
import {
NO_SNAPSHOT_MESSAGE,
SNAPSHOT_LOCKED_MESSAGE,
adjustHeadcount,
createDepartmentSnapshot,
ensureMonthSnapshots,
getDepartmentCap,
listMonthSnapshots,
setSnapshotLocked,
} from "./headcount";
import { ensureDefaultRuleVersion, saveRuleVersion } from "./params";
const TZ = "Asia/Taipei";
/** 2026/11/03 台北上午 */
const NOV3 = testAuditContext({ now: new Date("2026-11-03T02:00:00.000Z") });
describe("人數快照", () => {
let t: TestDatabase;
let design: number;
let rnd: number;
beforeEach(() => {
t = createTestDatabase();
seedAuditActor(t.db);
ensureDefaultRuleVersion(t.db);
design = t.db
.insert(departments)
.values({ name: "設計部", type: "general" })
.returning()
.get().id;
rnd = t.db.insert(departments).values({ name: "研發部", type: "rnd" }).returning().get().id;
});
afterEach(() => t.cleanup());
/** 建立 n 位自某日起屬於某部門的人員。 */
const hire = (n: number, departmentId: number, from: string, prefix: string) => {
for (let i = 0; i < n; i++) {
const id = t.db
.insert(users)
.values({ employeeNo: `${prefix}${i}` })
.returning()
.get().id;
assignDepartment(t.db, NOV3, id, departmentId, from, "2026-12-31");
}
};
const snapshot = (departmentId: number, month: string) =>
t.db
.select()
.from(headcountSnapshots)
.all()
.find((s) => s.departmentId === departmentId && s.month === month);
describe("建立", () => {
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({
ok: true,
value: { created: 2 },
});
expect(snapshot(design, "2026-11")).toMatchObject({ headcount: 20, computedHeadcount: 20 });
expect(snapshot(rnd, "2026-11")?.headcount).toBe(0);
expect(auditRows(t.db, "headcount.snapshot_created")).toHaveLength(2);
});
it("之後才建立(懶建立)也以 1 日當時計算,轉調不改變已存在的快照", () => {
hire(3, design, "2026-10-01", "D");
ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ);
// 12 月轉調一位到研發部
const moved = t.db
.select()
.from(users)
.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);
});
it("重複建立:不建立第二筆並提示已存在", () => {
ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ);
expect(ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ)).toEqual({
ok: true,
value: { created: 0 },
});
expect(createDepartmentSnapshot(t.db, NOV3, design, "2026-11", TZ)).toEqual({
ok: false,
error: "該月份快照已存在",
});
expect(t.db.select().from(headcountSnapshots).all()).toHaveLength(2);
});
it("資料庫唯一鍵:同一部門同月無法建立兩筆", () => {
t.db
.insert(headcountSnapshots)
.values({
departmentId: design,
month: "2026-10",
headcount: 1,
computedHeadcount: 1,
createdByLabel: "x",
})
.run();
expect(() =>
t.db
.insert(headcountSnapshots)
.values({
departmentId: design,
month: "2026-10",
headcount: 2,
computedHeadcount: 2,
createdByLabel: "x",
})
.run(),
).toThrow(/UNIQUE/);
});
it("月份尚未開始時不建立", () => {
expect(ensureMonthSnapshots(t.db, NOV3, "2026-12", TZ)).toEqual({
ok: false,
error: "該月份尚未開始,無法建立人數快照",
});
});
});
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;
});
it("調整人數:保留前後值、原因、操作者與時間,並寫操作紀錄", () => {
expect(adjustHeadcount(t.db, NOV3, snapshotId, 21, "11/01 到職者系統晚建檔").ok).toBe(true);
expect(snapshot(rnd, "2026-11")).toMatchObject({ headcount: 21, computedHeadcount: 20 });
expect(t.db.select().from(headcountAdjustments).all()).toEqual([
expect.objectContaining({
before: 20,
after: 21,
reason: "11/01 到職者系統晚建檔",
actorUserId: 1,
actorLabel: "測試管理員(T0001)",
createdAt: NOV3.now.toISOString(),
}),
]);
expect(expectAudit(t.db, "headcount.adjusted", snapshotId)).toMatchObject({
before: { headcount: 20 },
after: { headcount: 21 },
comment: "11/01 到職者系統晚建檔",
});
});
it("原因必填、人數須為非負整數", () => {
expect(adjustHeadcount(t.db, NOV3, snapshotId, 21, " ")).toEqual({
ok: false,
error: "請填寫調整原因",
});
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);
});
it("鎖定後調整被拒;解鎖後可調整;鎖定與解鎖都留紀錄", () => {
withTransaction(t.db, (tx) => setSnapshotLocked(tx, NOV3, rnd, "2026-11", 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));
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 });
});
it("調整紀錄無法刪除", () => {
adjustHeadcount(t.db, NOV3, snapshotId, 21, "x");
expect(() => t.sqlite.exec("DELETE FROM headcount_adjustments")).toThrow(/append-only/);
});
});
describe("部門月上限", () => {
it("一般部門 20 × 500 = 10,000;研發部 2 × 1,000 = 2,000", () => {
hire(20, design, "2026-09-01", "D");
hire(2, rnd, "2026-09-01", "R");
ensureMonthSnapshots(
t.db,
testAuditContext({ now: new Date("2026-10-02T00:00:00Z") }),
"2026-10",
TZ,
);
expect(getDepartmentCap(t.db, design, "2026-10", TZ)).toMatchObject({
ok: true,
cap: 10000,
headcount: 20,
perPerson: 500,
});
expect(getDepartmentCap(t.db, rnd, "2026-10", TZ)).toMatchObject({
ok: true,
cap: 2000,
perPerson: 1000,
});
});
it("沒有快照時回傳「尚未建立人數快照」而非數值", () => {
expect(getDepartmentCap(t.db, design, "2026-10", TZ)).toEqual({
ok: false,
error: NO_SNAPSHOT_MESSAGE,
});
});
it("使用該月結束時生效的每人額度", () => {
hire(10, design, "2026-09-01", "D");
ensureMonthSnapshots(t.db, NOV3, "2026-11", TZ);
saveRuleVersion(t.db, NOV3, {
params: { ...DEFAULT_RULE_PARAMS, perPersonQuota: { general: 600, rnd: 1000 } },
reason: "11/15 起調高",
effectiveAt: "2026-11-15T00:00:00.000Z",
});
expect(getDepartmentCap(t.db, design, "2026-11", 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;
adjustHeadcount(t.db, NOV3, id, 4, "補登");
expect(listMonthSnapshots(t.db, "2026-11", TZ)).toEqual([
expect.objectContaining({ departmentName: "研發部", headcount: 0, cap: 0, locked: false }),
expect.objectContaining({
departmentName: "設計部",
departmentType: "general",
headcount: 4,
cap: 2000,
adjustments: [expect.objectContaining({ before: 3, after: 4, reason: "補登" })],
}),
]);
});
});
});
+283
View File
@@ -0,0 +1,283 @@
import { and, asc, desc, eq } from "drizzle-orm";
import { monthEnd, monthStart } from "@/domain/deadlines";
import { recordAudit, type AuditContext } from "@/server/audit/record";
import type { Db } from "@/server/db/client";
import { departments, headcountAdjustments, headcountSnapshots } from "@/server/db/schema";
import { withTransaction, type Tx } from "@/server/db/transaction";
import { departmentMembersAt } from "@/server/org/accounts";
import { fail, ok, type Result } from "@/server/org/result";
import { requireEffectiveRuleVersion } from "./params";
export const NO_SNAPSHOT_MESSAGE = "尚未建立人數快照";
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();
}
function createSnapshot(tx: Tx, audit: AuditContext, departmentId: number, month: string) {
// 以該月 1 日 00:00 的所屬部門計算:月中到職、離職、轉調都不影響當月快照。
const headcount = departmentMembersAt(tx, departmentId, `${month}-01`).length;
const { id } = tx
.insert(headcountSnapshots)
.values({
departmentId,
month,
headcount,
computedHeadcount: headcount,
createdByLabel: audit.actor?.label ?? audit.actorLabel ?? "系統",
})
.returning({ id: headcountSnapshots.id })
.get();
recordAudit(tx, audit, {
action: "headcount.snapshot_created",
targetType: "headcount_snapshot",
targetId: id,
after: { departmentId, month, headcount },
});
return id;
}
/**
* 為某月份所有啟用中的部門建立尚未存在的快照(懶建立:該月 1 日之後首次需要時呼叫,例如開啟設定頁)。
* 已存在的快照不變。月份尚未開始時不建立。
*/
export function ensureMonthSnapshots(
db: Db,
audit: AuditContext,
month: string,
timeZone: string,
): Result<{ created: number }> {
if (!MONTH.test(month)) return fail("月份格式不正確");
if (!monthStarted(month, audit.now, timeZone)) return fail("該月份尚未開始,無法建立人數快照");
return withTransaction(db, (tx) => {
const existing = new Set(
tx
.select({ departmentId: headcountSnapshots.departmentId })
.from(headcountSnapshots)
.where(eq(headcountSnapshots.month, month))
.all()
.map((r) => r.departmentId),
);
const targets = tx
.select({ id: departments.id })
.from(departments)
.where(eq(departments.active, true))
.all()
.filter((d) => !existing.has(d.id));
for (const d of targets) createSnapshot(tx, audit, d.id, month);
return ok({ created: targets.length });
});
}
/** 手動建立單一部門某月的快照;已存在時不建立第二筆並提示。 */
export function createDepartmentSnapshot(
db: Db,
audit: AuditContext,
departmentId: number,
month: string,
timeZone: string,
): Result<number> {
if (!MONTH.test(month)) return fail("月份格式不正確");
if (!monthStarted(month, audit.now, timeZone)) return fail("該月份尚未開始,無法建立人數快照");
return withTransaction(db, (tx) => {
const dept = tx.select().from(departments).where(eq(departments.id, departmentId)).get();
if (!dept) return fail("部門不存在");
const existing = tx
.select({ id: headcountSnapshots.id })
.from(headcountSnapshots)
.where(
and(eq(headcountSnapshots.departmentId, departmentId), eq(headcountSnapshots.month, month)),
)
.get();
if (existing) return fail("該月份快照已存在");
return ok(createSnapshot(tx, audit, departmentId, month));
});
}
/**
* 人工調整快照人數:非負整數、原因必填、鎖定時拒絕。保留前後值、原因、操作者與時間,並寫操作紀錄。
*/
export function adjustHeadcount(
db: Db,
audit: AuditContext,
snapshotId: number,
headcount: number,
reason: string,
): Result {
if (!Number.isInteger(headcount) || headcount < 0) return fail("人數須為非負整數");
const why = reason.trim();
if (!why) return fail("請填寫調整原因");
return withTransaction(db, (tx) => {
const snapshot = tx
.select()
.from(headcountSnapshots)
.where(eq(headcountSnapshots.id, snapshotId))
.get();
if (!snapshot) return fail("快照不存在");
if (snapshot.locked) return fail(SNAPSHOT_LOCKED_MESSAGE);
if (snapshot.headcount === headcount) return fail("人數未變更");
tx.update(headcountSnapshots)
.set({ headcount })
.where(eq(headcountSnapshots.id, snapshotId))
.run();
tx.insert(headcountAdjustments)
.values({
snapshotId,
before: snapshot.headcount,
after: headcount,
reason: why,
actorUserId: audit.actor?.id ?? null,
actorLabel: audit.actor?.label ?? "系統",
createdAt: audit.now.toISOString(),
})
.run();
recordAudit(tx, audit, {
action: "headcount.adjusted",
targetType: "headcount_snapshot",
targetId: snapshotId,
before: { headcount: snapshot.headcount },
after: { headcount },
comment: why,
});
return ok(undefined);
});
}
/**
* 鎖定/解鎖某部門某月的快照。由月結提交(change 9,鎖定)與管理者退回月結(change 10,解鎖)
* 在其交易內呼叫,與月結狀態同時成立。快照不存在時回傳錯誤(月結前應已建立)。
*/
export function setSnapshotLocked(
tx: Tx,
audit: AuditContext,
departmentId: number,
month: string,
locked: boolean,
): Result {
const snapshot = tx
.select()
.from(headcountSnapshots)
.where(
and(eq(headcountSnapshots.departmentId, departmentId), eq(headcountSnapshots.month, month)),
)
.get();
if (!snapshot) return fail(NO_SNAPSHOT_MESSAGE);
if (snapshot.locked === locked) return ok(undefined);
tx.update(headcountSnapshots).set({ locked }).where(eq(headcountSnapshots.id, snapshot.id)).run();
recordAudit(tx, audit, {
action: locked ? "headcount.locked" : "headcount.unlocked",
targetType: "headcount_snapshot",
targetId: snapshot.id,
before: { locked: snapshot.locked },
after: { locked },
});
return ok(undefined);
}
export type DepartmentCap =
| {
ok: true;
cap: number;
headcount: number;
perPerson: number;
departmentType: "general" | "rnd";
ruleVersionId: number;
snapshotId: number;
}
| { ok: false; error: typeof NO_SNAPSHOT_MESSAGE };
/**
* 部門月上限 = 快照人數 × 該月生效之部門類型每人月額度(月份結束時的參數版本)。
* 只讀:快照不存在時回傳「尚未建立人數快照」,不自動建立(需要時先呼叫 ensureMonthSnapshots)。
*/
export function getDepartmentCap(
db: Db | Tx,
departmentId: number,
month: string,
timeZone: string,
): DepartmentCap {
const row = db
.select({ snapshot: headcountSnapshots, type: departments.type })
.from(headcountSnapshots)
.innerJoin(departments, eq(departments.id, headcountSnapshots.departmentId))
.where(
and(eq(headcountSnapshots.departmentId, departmentId), eq(headcountSnapshots.month, month)),
)
.get();
if (!row) return { ok: false, error: NO_SNAPSHOT_MESSAGE };
const version = requireEffectiveRuleVersion(db, monthEnd(month, timeZone));
const perPerson = version.params.perPersonQuota[row.type];
return {
ok: true,
cap: row.snapshot.headcount * perPerson,
headcount: row.snapshot.headcount,
perPerson,
departmentType: row.type,
ruleVersionId: version.id,
snapshotId: row.snapshot.id,
};
}
export interface MonthSnapshotRow {
snapshotId: number | null;
departmentId: number;
departmentName: string;
departmentType: "general" | "rnd";
headcount: number | null;
cap: number | null;
locked: boolean;
adjustments: {
before: number;
after: number;
reason: string;
actorLabel: string;
createdAt: string;
}[];
}
/** 設定頁用:某月份每個部門的快照、類型、月上限、鎖定狀態與調整紀錄(沒有快照的啟用部門也列出)。 */
export function listMonthSnapshots(db: Db, month: string, timeZone: string): MonthSnapshotRow[] {
const snapshots = db
.select()
.from(headcountSnapshots)
.where(eq(headcountSnapshots.month, month))
.all();
const depts = db.select().from(departments).orderBy(asc(departments.name)).all();
const adjustments = db
.select()
.from(headcountAdjustments)
.orderBy(desc(headcountAdjustments.createdAt), desc(headcountAdjustments.id))
.all();
const version =
snapshots.length > 0 ? requireEffectiveRuleVersion(db, monthEnd(month, timeZone)) : null;
return depts
.filter((d) => d.active || snapshots.some((s) => s.departmentId === d.id))
.map((d) => {
const s = snapshots.find((x) => x.departmentId === d.id);
return {
snapshotId: s?.id ?? null,
departmentId: d.id,
departmentName: d.name,
departmentType: d.type,
headcount: s?.headcount ?? null,
cap: s && version ? s.headcount * version.params.perPersonQuota[d.type] : null,
locked: s?.locked ?? false,
adjustments: s
? adjustments
.filter((a) => a.snapshotId === s.id)
.map(({ before, after, reason, actorLabel, createdAt }) => ({
before,
after,
reason,
actorLabel,
createdAt,
}))
: [],
};
});
}
+164
View File
@@ -0,0 +1,164 @@
import { eq } from "drizzle-orm";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { DEFAULT_RULE_PARAMS, platformOptions, type RuleParams } from "@/lib/rule-params";
import { ruleVersions } from "@/server/db/schema";
import { expectAudit, seedAuditActor, testAuditContext } from "@/server/testing/audit";
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
import {
deriveDeadlines,
ensureDefaultRuleVersion,
getEffectiveRuleVersion,
listRuleVersions,
saveRuleVersion,
} from "./params";
const TZ = "Asia/Taipei";
const NOW = new Date("2026-11-10T02:00:00.000Z");
const ctx = testAuditContext({ now: NOW });
const params = (patch: Partial<RuleParams> = {}): RuleParams => ({
...structuredClone(DEFAULT_RULE_PARAMS),
...patch,
});
describe("制度參數版本", () => {
let t: TestDatabase;
beforeEach(() => {
t = createTestDatabase();
seedAuditActor(t.db);
ensureDefaultRuleVersion(t.db);
});
afterEach(() => t.cleanup());
it("初始化建立一個預設版本;重複執行不重複建立", () => {
ensureDefaultRuleVersion(t.db);
const rows = t.db.select().from(ruleVersions).all();
expect(rows).toHaveLength(1);
expect(JSON.parse(rows[0].paramsJson)).toEqual(DEFAULT_RULE_PARAMS);
expect(rows[0].createdByLabel).toBe("系統");
});
it("儲存變更產生新版本並立即生效;舊版本不變;操作紀錄記前後值與原因", () => {
const before = t.db.select().from(ruleVersions).get()!;
const r = saveRuleVersion(t.db, ctx, {
params: params({ rounding: "half_up" }),
reason: "改為四捨五入",
});
if (!r.ok) throw new Error(r.error);
expect(getEffectiveRuleVersion(t.db, NOW)?.params.rounding).toBe("half_up");
expect(t.db.select().from(ruleVersions).where(eq(ruleVersions.id, before.id)).get()).toEqual(
before,
);
expect(expectAudit(t.db, "settings.updated", r.versionId)).toMatchObject({
actorUserId: 1,
before: { rounding: "floor" },
after: { rounding: "half_up", effectiveAt: NOW.toISOString() },
comment: "改為四捨五入",
});
});
it("原因必填;生效時間不得早於現在;參數不合法時不產生版本", () => {
expect(saveRuleVersion(t.db, ctx, { params: params(), reason: " " })).toMatchObject({
ok: false,
fieldErrors: { reason: "請填寫變更原因" },
});
expect(
saveRuleVersion(t.db, ctx, {
params: params(),
reason: "x",
effectiveAt: "2026-11-09T02:00:00.000Z",
}),
).toMatchObject({ ok: false, fieldErrors: { effectiveAt: "生效時間不得早於現在" } });
expect(
saveRuleVersion(t.db, ctx, {
params: params({ managerDeadlineDay: 18 }),
reason: "x",
}),
).toMatchObject({
ok: false,
fieldErrors: { managerDeadlineDay: "主管提交截止日必須晚於員工申請截止日" },
});
expect(t.db.select().from(ruleVersions).all()).toHaveLength(1);
});
it("查詢變更前的時間點回傳舊版本", () => {
// 比例於 11/01 00:00(台北)改為 40%
const at = new Date("2026-10-31T16:00:00.000Z");
const r = saveRuleVersion(t.db, testAuditContext({ now: new Date("2026-10-20T00:00:00Z") }), {
params: params({ subsidyRatePercent: 40 }),
reason: "調整比例",
effectiveAt: at.toISOString(),
});
expect(r.ok).toBe(true);
expect(
getEffectiveRuleVersion(t.db, new Date("2026-10-15T00:00:00Z"))?.params.subsidyRatePercent,
).toBe(50);
expect(getEffectiveRuleVersion(t.db, at)?.params.subsidyRatePercent).toBe(40);
});
it("排定生效的版本尚未生效;版本紀錄標示「排定生效」與差異欄位", () => {
const scheduled = saveRuleVersion(t.db, ctx, {
params: params({ perPersonQuota: { general: 600, rnd: 1000 } }),
reason: "明年起調整",
effectiveAt: "2026-11-30T16:00:00.000Z",
});
if (!scheduled.ok) throw new Error(scheduled.error);
expect(getEffectiveRuleVersion(t.db, NOW)?.params.perPersonQuota.general).toBe(500);
const list = listRuleVersions(t.db, NOW);
expect(list.map((v) => v.status)).toEqual(["scheduled", "current"]);
expect(list[0].changes).toEqual({
before: { "perPersonQuota.general": 500 },
after: { "perPersonQuota.general": 600 },
});
expect(list[1].changes).toBeNull();
});
it("截止日:10/05 刷卡 → 11/20、11/25 23:59:59;12/31 → 2027/01/20", () => {
const oct = deriveDeadlines(t.db, "2026-10-05", TZ);
expect(oct.employee.toISOString()).toBe("2026-11-20T15:59:59.000Z");
expect(oct.manager.toISOString()).toBe("2026-11-25T15:59:59.000Z");
expect(deriveDeadlines(t.db, "2026-12-31", TZ).employee.toISOString()).toBe(
"2027-01-20T15:59:59.000Z",
);
});
it("截止日使用刷卡月份結束時的版本:月中改參數,同月案件截止日一致", () => {
// 10/15 起員工截止日改為 18 日 → 10 月刷卡的案件都用 18 日(10 月結束時生效的版本)
saveRuleVersion(t.db, testAuditContext({ now: new Date("2026-10-01T00:00:00Z") }), {
params: params({ employeeDeadlineDay: 18 }),
reason: "提前截止",
effectiveAt: "2026-10-15T00:00:00.000Z",
});
expect(deriveDeadlines(t.db, "2026-10-02", TZ).employee.toISOString()).toBe(
"2026-11-18T15:59:59.000Z",
);
expect(deriveDeadlines(t.db, "2026-10-30", TZ).employee.toISOString()).toBe(
"2026-11-18T15:59:59.000Z",
);
expect(deriveDeadlines(t.db, "2026-09-30", TZ).employee.toISOString()).toBe(
"2026-10-20T15:59:59.000Z",
);
});
it("移除平台只影響新版本的選項,舊版本內容不變", () => {
const before = getEffectiveRuleVersion(t.db, NOW)!;
saveRuleVersion(t.db, ctx, {
params: params({ platforms: ["ChatGPT", "Claude"] }),
reason: "移除 Gemini",
});
expect(platformOptions(getEffectiveRuleVersion(t.db, NOW)!.params)).toEqual([
"ChatGPT",
"Claude",
"其他",
]);
// 舊版本(既有申請引用的版本)仍保有 Gemini;申請本身另存平台名稱(change 7)
expect(
t.db.select().from(ruleVersions).where(eq(ruleVersions.id, before.id)).get()!.paramsJson,
).toContain("Gemini");
});
it("資料庫層拒絕修改或刪除版本", () => {
expect(() => t.sqlite.exec("UPDATE rule_versions SET reason = 'x'")).toThrow(/append-only/);
expect(() => t.sqlite.exec("DELETE FROM rule_versions")).toThrow(/append-only/);
});
});
+190
View File
@@ -0,0 +1,190 @@
import { asc, desc, lte } from "drizzle-orm";
import { deadlinesFor, monthEnd } from "@/domain/deadlines";
import {
DEFAULT_RULE_PARAMS,
flattenParams,
ruleParamsSchema,
type RuleParams,
} from "@/lib/rule-params";
import { recordAudit, type AuditContext } from "@/server/audit/record";
import type { Db } from "@/server/db/client";
import { ruleVersions } from "@/server/db/schema";
import { withTransaction, type Tx } from "@/server/db/transaction";
import { changedFields } from "@/server/org/diff";
/** 初始版本的生效時間:早於任何業務資料,查詢任何時間點都有參數。 */
export const INITIAL_EFFECTIVE_AT = "2000-01-01T00:00:00.000Z";
/** 生效時間允許的誤差:表單只到分鐘,送出時可能已過了幾秒。 */
const EFFECTIVE_AT_TOLERANCE_MS = 60_000;
export interface RuleVersion {
id: number;
effectiveAt: string;
createdByLabel: string;
reason: string;
createdAt: string;
params: RuleParams;
}
function toVersion(row: typeof ruleVersions.$inferSelect): RuleVersion {
return {
id: row.id,
effectiveAt: row.effectiveAt,
createdByLabel: row.createdByLabel,
reason: row.reason,
createdAt: row.createdAt,
// 寫入時已驗證;讀取時再驗證一次,資料損壞時立即失敗而不是算錯錢。
params: ruleParamsSchema.parse(JSON.parse(row.paramsJson)),
};
}
/**
* 確保有初始參數版本(規格 §16 預設值)。冪等:已有任何版本時不動作。
* 由 seed 與伺服器啟動時呼叫——正式環境不跑 seed,必須在啟動時建立。
*/
export function ensureDefaultRuleVersion(db: Db): void {
withTransaction(db, (tx) => {
if (tx.select({ id: ruleVersions.id }).from(ruleVersions).limit(1).get()) return;
tx.insert(ruleVersions)
.values({
paramsJson: JSON.stringify(DEFAULT_RULE_PARAMS),
effectiveAt: INITIAL_EFFECTIVE_AT,
createdBy: null,
createdByLabel: "系統",
reason: "系統初始化預設值",
})
.run();
});
}
/** 某時間點生效的參數版本:生效時間不晚於該時間點的最新版本。 */
export function getEffectiveRuleVersion(db: Db | Tx, at: Date): RuleVersion | null {
const row = db
.select()
.from(ruleVersions)
.where(lte(ruleVersions.effectiveAt, at.toISOString()))
.orderBy(desc(ruleVersions.effectiveAt), desc(ruleVersions.id))
.limit(1)
.get();
return row ? toVersion(row) : null;
}
/** 同 getEffectiveRuleVersion,但沒有任何版本時視為系統錯誤(初始化應已建立)。 */
export function requireEffectiveRuleVersion(db: Db | Tx, at: Date): RuleVersion {
const version = getEffectiveRuleVersion(db, at);
if (!version) throw new Error("尚未建立制度參數版本(系統未初始化)");
return version;
}
export type VersionStatus = "current" | "scheduled" | "superseded";
export interface RuleVersionEntry extends RuleVersion {
status: VersionStatus;
/** 與前一個版本(依生效時間)相比有變動的欄位。初始版本為 null。 */
changes: { before: Record<string, unknown>; after: Record<string, unknown> } | null;
}
/** 版本紀錄:依生效時間由新到舊,標示目前生效、排定生效、已被取代。 */
export function listRuleVersions(db: Db, now: Date): RuleVersionEntry[] {
const rows = db
.select()
.from(ruleVersions)
.orderBy(asc(ruleVersions.effectiveAt), asc(ruleVersions.id))
.all()
.map(toVersion);
const current = getEffectiveRuleVersion(db, now)?.id;
const nowIso = now.toISOString();
return rows
.map((version, i) => ({
...version,
status: (version.id === current
? "current"
: version.effectiveAt > nowIso
? "scheduled"
: "superseded") as VersionStatus,
changes:
i === 0
? null
: changedFields(flattenParams(rows[i - 1].params), flattenParams(version.params)),
}))
.reverse();
}
export type SaveVersionResult =
| { ok: true; versionId: number }
| { ok: false; error: string; fieldErrors: Record<string, string> };
/**
* 儲存新的參數版本:驗證參數、原因必填、生效時間不得早於現在(未指定為立即生效)。
* 只新增版本,不修改既有版本;同一交易內寫入操作紀錄(與前一版本相比的前後值)。
*/
export function saveRuleVersion(
db: Db,
audit: AuditContext,
input: { params: unknown; reason: string; effectiveAt?: string | null },
): SaveVersionResult {
const fieldErrors: Record<string, string> = {};
const parsed = ruleParamsSchema.safeParse(input.params);
if (!parsed.success) {
for (const issue of parsed.error.issues) {
const key = issue.path.join(".");
fieldErrors[key] ??= issue.message;
}
}
const reason = input.reason.trim();
if (!reason) fieldErrors.reason = "請填寫變更原因";
const now = audit.now;
let effectiveAt = now;
if (input.effectiveAt) {
const requested = new Date(input.effectiveAt);
if (Number.isNaN(requested.getTime())) {
fieldErrors.effectiveAt = "生效時間格式不正確";
} else if (requested.getTime() < now.getTime() - EFFECTIVE_AT_TOLERANCE_MS) {
fieldErrors.effectiveAt = "生效時間不得早於現在";
} else {
effectiveAt = requested;
}
}
if (Object.keys(fieldErrors).length > 0 || !parsed.success) {
return {
ok: false,
error: `尚有 ${Object.keys(fieldErrors).length} 項資料需修正`,
fieldErrors,
};
}
return withTransaction(db, (tx): SaveVersionResult => {
const predecessor = requireEffectiveRuleVersion(tx, effectiveAt);
const { id } = tx
.insert(ruleVersions)
.values({
paramsJson: JSON.stringify(parsed.data),
effectiveAt: effectiveAt.toISOString(),
createdBy: audit.actor?.id ?? null,
createdByLabel: audit.actor?.label ?? "系統",
reason,
})
.returning({ id: ruleVersions.id })
.get();
const diff = changedFields(flattenParams(predecessor.params), flattenParams(parsed.data));
recordAudit(tx, audit, {
action: "settings.updated",
targetType: "rule_version",
targetId: id,
before: diff?.before ?? {},
after: { ...(diff?.after ?? {}), effectiveAt: effectiveAt.toISOString() },
comment: reason,
});
return { ok: true, versionId: id };
});
}
/**
* 推導截止時刻:使用「刷卡月份結束時」生效的參數版本,同一刷卡月份的案件截止日一致。
*/
export function deriveDeadlines(db: Db | Tx, cardDate: string, timeZone: string) {
const month = cardDate.slice(0, 7);
const version = requireEffectiveRuleVersion(db, monthEnd(month, timeZone));
return { ...deadlinesFor(cardDate, version.params, timeZone), versionId: version.id };
}
+8 -2
View File
@@ -3,6 +3,7 @@ import path from "node:path";
import { getDatabase } from "@/server/db/client";
import { runMigrations } from "@/server/db/migrate";
import { getEnv } from "@/server/env";
import { ensureDefaultRuleVersion } from "@/server/rules/params";
/**
* 伺服器啟動檢查:驗證環境變數、建立附件目錄。設定錯誤讓伺服器無法啟動,
@@ -15,7 +16,12 @@ export function runStartupChecks(): void {
fs.mkdirSync(path.resolve(env.ATTACHMENTS_DIR), { recursive: true });
}
/** 啟動時套用尚未執行的 migration(容器內沒有 tsx,無法另外跑 `npm run db:migrate`)。 */
/**
* 啟動時套用尚未執行的 migration(容器內沒有 tsx,無法另外跑 `npm run db:migrate`),
* 並確保有初始制度參數版本(正式環境不跑 seed)。
*/
export function migrateOnStartup(): void {
runMigrations(getDatabase().db);
const { db } = getDatabase();
runMigrations(db);
ensureDefaultRuleVersion(db);
}
+10 -3
View File
@@ -20,10 +20,16 @@ test("員工直接輸入 /admin/settlements 看到無權限頁,不回傳管理
await expect(page.getByText("全公司月結")).toHaveCount(0);
});
test("員工的導覽只有首頁、新增申請、我的申請", async ({ page }) => {
test("員工的導覽只有首頁、新增申請、我的申請與說明頁", async ({ page }) => {
await loginAs(page, DEMO.employee);
const nav = page.getByRole("navigation", { name: "主要導覽" });
await expect(nav.getByRole("link")).toHaveText(["首頁", "新增申請", "我的申請"]);
await expect(nav.getByRole("link")).toHaveText([
"首頁",
"新增申請",
"我的申請",
"使用說明",
"常見問題",
]);
});
test("主管可進入部門審核,但不能進入全公司月結", async ({ page }) => {
@@ -42,7 +48,8 @@ test("待指派部門者在首頁看到提示", async ({ page }) => {
test("登出後回到登入頁,再開首頁需重新登入", async ({ page }) => {
await loginAs(page, DEMO.employee);
await page.getByRole("button", { name: "登出" }).click();
await page.getByRole("button", { name: /使用者選單/ }).click();
await page.getByRole("menuitem", { name: "登出" }).click();
await expect(page).toHaveURL(/\/login/);
await page.goto("/dashboard");
await expect(page).toHaveURL(/\/login/);
+102
View File
@@ -0,0 +1,102 @@
import Database from "better-sqlite3";
import { expect, test, type Page } from "@playwright/test";
import { e2eEnv } from "./env";
import { DEMO, loginAs } from "./helpers";
// 這些測試會累積建立參數版本;以相對數量判斷,不假設資料庫是空的。
const history = (page: Page) =>
page.locator("table", { has: page.getByText("差異欄位") }).locator("tbody tr");
async function saveWithConfirm(page: Page) {
await page.getByRole("button", { name: "儲存變更" }).click();
await page.getByRole("button", { name: "確定儲存" }).click();
}
test("一般員工直接輸入 /admin/settings 被拒,且不回傳參數資料", async ({ page }) => {
await loginAs(page, DEMO.employee);
const response = await page.goto("/admin/settings");
expect(response?.status()).toBe(403);
await expect(page.getByText("研發部每人月額度")).toHaveCount(0);
const html = await response!.text();
expect(html).not.toContain("perPersonQuota");
});
test("不合法的參數不產生新版本;合法變更產生新版本並出現在版本紀錄", async ({ page }) => {
await loginAs(page, DEMO.admin, "/admin/settings");
const before = await history(page).count();
await page.getByLabel("主管月結提交截止日(刷卡月份次月幾日)").fill("18");
await page.getByLabel("變更原因").fill("測試錯誤");
await saveWithConfirm(page);
await expect(page.getByText(/尚有 \d+ 項資料需完成/)).toBeVisible();
await expect(page.getByText("主管提交截止日必須晚於員工申請截止日")).toHaveCount(2);
await expect(history(page)).toHaveCount(before);
await page.getByLabel("主管月結提交截止日(刷卡月份次月幾日)").fill("25");
await page.getByLabel("取整方式").selectOption({ label: "四捨五入" });
await page.getByLabel("變更原因").fill("改為四捨五入(e2e)");
await saveWithConfirm(page);
await expect(page.getByText("已儲存,新版本立即生效")).toBeVisible();
await expect(history(page)).toHaveCount(before + 1);
const newest = history(page).filter({ hasText: "改為四捨五入(e2e)" });
await expect(newest).toContainText("目前生效");
await expect(newest).toContainText("取整方式");
await expect(newest).toContainText("四捨五入");
await expect(newest).toContainText("林人資(D0004)");
});
test("排定生效的版本在版本紀錄標示「排定生效」", async ({ page }) => {
await loginAs(page, DEMO.admin, "/admin/settings");
await page.getByLabel("一般部門每人月額度(元)").fill("600");
await page.getByLabel("變更原因").fill("明年起調高(e2e)");
await page.getByLabel("指定生效時間(台北時間)").check();
await page.getByLabel("生效時間", { exact: true }).fill("2030-01-01T00:00");
await saveWithConfirm(page);
await expect(page.getByText("已建立排定生效的新版本")).toBeVisible();
const scheduled = history(page).filter({ hasText: "明年起調高(e2e)" });
await expect(scheduled).toContainText("排定生效");
await expect(scheduled).toContainText("2030/01/01 00:00:00");
// 目前生效的版本仍是原本的額度
await expect(page.getByLabel("一般部門每人月額度(元)")).toHaveValue("500");
});
test("人數快照:調整需填原因、保留紀錄;鎖定後拒絕調整", async ({ page }) => {
await loginAs(page, DEMO.admin, "/admin/settings?tab=headcount");
const row = page.locator("table").getByTestId("adjust-設計部(示範)");
await expect(row).toBeVisible();
// 未填原因
await row.locator("summary").click();
await row.getByLabel("調整後人數").fill("3");
await row.getByRole("button", { name: "儲存調整" }).click();
// 不用 getByRole("alert"):Next.js 的路由播報元素也是 role="alert"
await expect(page.getByText("請填寫調整原因")).toBeVisible();
// 正常調整
const row2 = page.locator("table").getByTestId("adjust-設計部(示範)");
await row2.locator("summary").click();
await row2.getByLabel("調整後人數").fill("3");
await row2.getByLabel("調整原因").fill("到職者系統晚建檔(e2e)");
await row2.getByRole("button", { name: "儲存調整" }).click();
const after = page.locator("table").getByTestId("adjust-設計部(示範)");
await expect(after.locator("summary")).toContainText("筆紀錄");
await after.locator("summary").click();
await expect(after).toContainText(/→ 3(到職者系統晚建檔(e2e))/);
// 模擬部長已提交月結(鎖定由 add-department-settlement 呼叫 setSnapshotLocked)
const db = new Database(e2eEnv.DATABASE_PATH);
db.prepare(
"update headcount_snapshots set locked = 1 where department_id = (select id from departments where code = 'DEMO-DSN')",
).run();
db.close();
await page.reload();
const locked = page.locator("table").getByTestId("adjust-設計部(示範)");
await expect(page.locator("table tr", { hasText: "設計部(示範)" })).toContainText("已鎖定");
await locked.locator("summary").click();
await locked.getByLabel("調整後人數").fill("4");
await locked.getByLabel("調整原因").fill("鎖定後嘗試");
await locked.getByRole("button", { name: "儲存調整" }).click();
await expect(page.getByText("該月份月結已提交,需先退回月結")).toBeVisible();
});
+144
View File
@@ -0,0 +1,144 @@
import { expect, test, type Page } from "@playwright/test";
import { DEMO, loginAs } from "./helpers";
const noHorizontalScroll = (page: Page) =>
page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth);
test.describe("全站框架", () => {
test("登入後頂部列顯示今日日期(含星期)、通知、姓名與部門", async ({ page }) => {
await loginAs(page, DEMO.employee);
await expect(page.getByTestId("today")).toHaveText(
/^\d{4} 年 \d{1,2} 月 \d{1,2} 日 星期[日一二三四五六]$/,
);
await expect(page.getByRole("button", { name: "通知" })).toBeVisible();
await expect(page.getByTestId("user-name")).toHaveText("王小明");
await expect(page.getByTestId("user-department")).toHaveText("設計部(示範)");
await expect(page.getByRole("heading", { level: 1 })).toHaveText("您好,王小明");
await page.getByRole("button", { name: "通知" }).click();
await expect(page.getByText("目前沒有通知")).toBeVisible();
});
test("未登入開啟 /applications 時導向登入頁", async ({ page }) => {
await page.goto("/applications");
await expect(page).toHaveURL(/\/login\?returnTo=%2Fapplications$/);
});
test("導覽高亮目前頁面;員工看不到部門審核", async ({ page }) => {
await loginAs(page, DEMO.employee, "/applications");
const nav = page.getByRole("navigation", { name: "主要導覽" });
await expect(nav.getByRole("link", { name: "我的申請" })).toHaveAttribute(
"aria-current",
"page",
);
await expect(nav.locator('[aria-current="page"]')).toHaveCount(1);
await expect(nav.getByRole("link", { name: "部門審核" })).toHaveCount(0);
});
test("兼任主管看到部門審核與部門月結", async ({ page }) => {
await loginAs(page, DEMO.manager);
const nav = page.getByRole("navigation", { name: "主要導覽" });
await expect(nav.getByRole("link")).toHaveText([
"首頁",
"新增申請",
"我的申請",
"部門審核",
"部門月結",
"使用說明",
"常見問題",
]);
});
test("首頁、使用說明、常見問題可開啟;常見問題說明實際補助於月結後確認", async ({ page }) => {
await loginAs(page, DEMO.employee);
await expect(page.getByRole("heading", { level: 1 })).toHaveText("您好,王小明");
await page
.getByRole("navigation", { name: "主要導覽" })
.getByRole("link", { name: "使用說明" })
.click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("使用說明");
await expect(page.getByText(/實際補助金額於月結後確認/)).toBeVisible();
await page
.getByRole("navigation", { name: "主要導覽" })
.getByRole("link", { name: "常見問題" })
.click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("常見問題");
await expect(page.getByText(/實際補助金額於月結後確認/)).toBeVisible();
});
});
test.describe("錯誤與回饋", () => {
test("送出缺 3 項必填的表單:頁首顯示錯誤摘要並捲動到第一個錯誤欄位", async ({ page }) => {
await loginAs(page, DEMO.employee, "/design-tokens");
await page.getByRole("button", { name: "送出" }).click();
await expect(page.getByText("尚有 3 項資料需完成")).toBeVisible();
await expect(page.locator("#sample-plan")).toBeFocused();
await expect(page.locator("#sample-plan")).toBeInViewport();
for (const message of ["請填寫訂閱方案", "請填寫支付金額(台幣)", "請填寫工作用途說明"]) {
// 錯誤摘要一次、欄位旁 inline 一次
await expect(page.getByText(message)).toHaveCount(2);
}
});
test("補齊後送出顯示提示訊息;確認視窗按取消不執行", async ({ page }) => {
await loginAs(page, DEMO.employee, "/design-tokens");
await page.getByRole("button", { name: "不核准(範例)" }).click();
await expect(page.getByRole("alertdialog")).toContainText("不核准後申請人無法再對此案件補件");
await page.getByRole("button", { name: "取消" }).click();
await expect(page.getByText("已不核准(範例)")).toHaveCount(0);
await page.getByLabel("訂閱方案/項目名稱").fill("ChatGPT Plus");
await page.getByLabel("支付金額(台幣)").fill("899");
await expect(page.getByText("NT$449")).toBeVisible();
await page.getByLabel("工作用途說明").fill("提案發想與資料整理");
await page.getByRole("button", { name: "送出" }).click();
await expect(page.getByText("已送出(範例)")).toBeVisible();
});
});
test.describe("響應式版面", () => {
for (const width of [375, 768, 1280]) {
test(`${width}px:無水平捲動,主要按鈕未被遮擋`, async ({ page }) => {
await page.setViewportSize({ width, height: 800 });
await loginAs(page, DEMO.employee, "/design-tokens");
expect(await noHorizontalScroll(page)).toBe(true);
const submit = page.getByRole("button", { name: "送出" });
// 手機固定在底部(一開始就看得到);平板與桌機在長表單底部,捲動到即可
if (width >= 768) await submit.scrollIntoViewIfNeeded();
await expect(submit).toBeInViewport({ ratio: 1 });
await submit.click({ trial: true }); // 確認按鈕可點擊、未被其他元素遮住
});
}
test("375px:側欄收合為漢堡選單;長表單捲動後主要按鈕固定在底部", async ({ page }) => {
await page.setViewportSize({ width: 375, height: 700 });
await loginAs(page, DEMO.employee, "/design-tokens");
await expect(page.getByRole("complementary", { name: "側欄" })).toBeHidden();
await page.getByRole("button", { name: "開啟選單" }).click();
const drawer = page.getByRole("dialog");
await expect(drawer.getByRole("link", { name: "我的申請" })).toBeVisible();
await page.getByRole("button", { name: "關閉選單" }).click();
await page.mouse.wheel(0, 2000);
const actions = page.getByTestId("primary-actions");
const box = await actions.boundingBox();
expect(box).not.toBeNull();
expect(Math.round(box!.y + box!.height)).toBe(700);
});
test("768px:保留側欄並可收合", async ({ page }) => {
await page.setViewportSize({ width: 768, height: 900 });
await loginAs(page, DEMO.employee);
const sidebar = page.getByRole("complementary", { name: "側欄" });
await expect(sidebar).toBeVisible();
await page.getByRole("button", { name: "收合側欄" }).click();
await expect(sidebar).toHaveAttribute("data-collapsed", "true");
expect(await noHorizontalScroll(page)).toBe(true);
});
test("375px:資料表格改為卡片清單", async ({ page }) => {
await page.setViewportSize({ width: 375, height: 800 });
await loginAs(page, DEMO.sysadmin, "/admin/audit-log");
expect(await noHorizontalScroll(page)).toBe(true);
});
});