restyle-ui-to-mockup: restyle every page to the chosen mockups (hero headers, illustrations, platform icons, shared Button, three-column application form)

Also: copy public/ into the runtime image, exclude /images from the login
redirect, and fix 768px horizontal overflow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
pkgsp50777_楊舒諠
2026-10-13 11:21:27 +08:00
co-authored by Claude Opus 5.5
parent 7d2aa66517
commit 2f3044e763
79 changed files with 2250 additions and 932 deletions
+8
View File
@@ -154,6 +154,14 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- **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).
- Visual style follows the two mockups (`docs/風格2_*.png`):
- Buttons: always `Button` / `ButtonLink` / `buttonClass()` (`src/components/ui/button.tsx`). Never hand-write button classes. Filter toggles use `pillClass(active)`.
- Page headers: `PageHeader size="hero"` + `illustration` only for the dashboard and the application form. Other pages use the default size.
- Platform names: show them with `PlatformIcon` (`src/components/ui/platform-icon.tsx`; display info in `src/lib/platform-display.ts`), always next to the text name.
- Decorative images:
- Cropped from the mockups by `scripts/crop-mockup-images.ts` into `public/images/`, shown via `Illustration`. To upgrade, replace the files with higher-resolution ones under the same names.
- `public/images/` is excluded from the login redirect in `src/proxy.ts`. The Dockerfile copies `public/` into the runtime image (standalone output doesn't).
- Login, dev login and 403 pages use `AuthShell` (`src/components/auth-shell.tsx`).
- Component tests: `// @vitest-environment jsdom` + Testing Library.
## Code layout
+2
View File
@@ -29,6 +29,8 @@ ENV NODE_ENV=production \
# 正式環境的 /app/data 是 bind mount,擁有者為 1000:1000;node 使用者正是 UID/GID 1000。
COPY --from=build --chown=node:node /app/.next/standalone ./
COPY --from=build --chown=node:node /app/.next/static ./.next/static
# standalone 輸出不含 public/(插圖等靜態檔),要另外複製。
COPY --from=build --chown=node:node /app/public ./public
# migration 在啟動時由 src/instrumentation.ts 套用,standalone 不會自動帶上這些 SQL 檔。
COPY --from=build --chown=node:node /app/src/server/db/migrations ./src/server/db/migrations
RUN mkdir -p /app/data && chown node:node /app/data
+10 -2
View File
@@ -31,6 +31,9 @@ export default async function Page() {
- **不要在頁面裡放 `<main>`**,框架已經提供。
- `PageHeader` 的 `actions`:一個頁面只有一個主要操作;手機寬度會自動變成畫面底部固定操作列。
表單底部的按鈕用 `StickyActions` 包起來,效果相同。
- `PageHeader size="hero"`:首頁與新增申請的大標題,主要操作放在說明下方;`illustration` 加右側插圖
(寬度 ≥ 1024px 才顯示,左緣淡入),`aside` 放標題列右側的輔助內容(例如完成進度)。
- `Card` 的 `icon` 放在標題前,`link={{ href, label }}` 是標題列右側的「查看詳情 →」。
- 新增導覽項目:在 `src/lib/navigation.ts` 的 `NAV_ITEMS` 加一筆,並在 `ROUTE_RULES` 設定角色;側欄與權限檢查共用同一份設定。
## 設計 tokens
@@ -41,10 +44,12 @@ export default async function Page() {
|---|---|
| 頁面底色/卡片 | `bg-canvas`、`bg-surface` |
| 文字 | `text-ink`(主要)、`text-muted`(次要) |
| 主要按鈕 | `bg-primary hover:bg-primary-hover text-on-primary` |
| 主要按鈕 | 用 `Button`/`ButtonLink`/`buttonClass()`(見下方),不要自己組按鈕類別 |
| 強調、連結、導覽選中 | `text-accent`、`bg-accent-soft` |
| 語意色 | `success`、`warning`、`danger`、`info`、`violet`、`neutral`(各有 `-soft` 淺底) |
| 圓角、陰影 | `rounded-control`(輸入框、按鈕)、`rounded-card`、`shadow-card`、`shadow-overlay` |
| 字級 | `text-hero`(頁首大標題)、`text-display`(頁面標題)、`text-figure`(卡片大數字) |
| 裝飾 | `deco-blue`、`deco-yellow`(含 `-strong`):側欄波浪與 Logo;`brand-*` 只給 `PlatformIcon` 用 |
Tailwind 只認得原始碼中**完整寫出**的類別名稱,不能用 `` `text-${tone}` `` 動態組合;需要依條件變化時,用對照表列出完整類別(參考 `src/components/ui/status-badge.tsx`)。
@@ -64,7 +69,10 @@ Tailwind 只認得原始碼中**完整寫出**的類別名稱,不能用 `` `te
| 元件 | 用途 |
|---|---|
| `MoneyDisplay` | 金額。月結前用 `kind="estimate"`(顯示「預估」),月結後 `kind="final"`(「最終」);`emphasis` 為綠色強調 |
| `Button`/`ButtonLink` | 按鈕與按鈕樣式的連結:`variant`(primary、secondary、ghost、danger、danger-outline)、`size`(sm、md、lg)、`icon` 前置圖示、`arrow` 尾端箭頭。交給其他元件的觸發按鈕用 `buttonClass(variant, size)` |
| `PlatformIcon` | AI 平台圖示(ChatGPT、Claude、Gemini 專屬,其他平台通用「…」),一定要搭配平台名稱文字;顯示資訊(廠商、用途)在 `src/lib/platform-display.ts` |
| `Illustration` | 裝飾插圖(`src/components/illustration.tsx`,檔案在 `public/images/`,自風格稿以 `scripts/crop-mockup-images.ts` 裁切)。純裝飾、對輔助技術隱藏;換高解析素材時直接取代同名檔案 |
| `MoneyDisplay` | 金額。月結前用 `kind="estimate"`(顯示「預估」),月結後 `kind="final"`(「最終」);`emphasis` 為綠色強調;`size="figure"` 為卡片大字 |
| `StatusBadge` | 案件狀態,文字依 `src/lib/application-status.ts`(例如 `pending_review` →「待審核」);其他狀態用 `ToneBadge` |
| `MonthPicker` | 月份選擇,值 `YYYY-MM`、顯示 `YYYY/MM` |
| `ConfirmDialog` | 不核准、提交月結、最終核定、標記已發放等重要操作;`description` 寫清楚後果;取消不執行 |
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+66
View File
@@ -0,0 +1,66 @@
/**
* 一次性工具:從風格稿裁出頁面的裝飾插圖,輸出到 public/images/(WebP)。
* 執行:npx tsx scripts/crop-mockup-images.ts
*
* 風格稿是 1672×941 的點陣圖,裁出來的圖解析度有限;之後若有高解析素材,
* 直接以同名檔案取代 public/images/ 裡的檔案即可,程式不用改。
* sharp 是 Next.js 的相依套件,這支腳本不進正式流程。
*/
import { mkdirSync } from "node:fs";
import path from "node:path";
import sharp from "sharp";
const HOME = "docs/風格2_首頁.png";
const NEW_APPLICATION = "docs/風格2_新增申請頁.png";
const OUT = "public/images";
interface Crop {
source: string;
file: string;
left: number;
top: number;
width: number;
height: number;
}
const CROPS: Crop[] = [
// 首頁頁首右側:便利貼、書本與標語
{ source: HOME, file: "hero-home.webp", left: 1100, top: 62, width: 572, height: 258 },
// 首頁右下:「Good Ideas Deserve Support.」圖卡
{ source: HOME, file: "good-ideas.webp", left: 1180, top: 637, width: 469, height: 278 },
// 新增申請頁首右側:「Good Ideas Better Tomorrow」便利貼
{
source: NEW_APPLICATION,
file: "hero-application.webp",
left: 1296,
top: 62,
width: 376,
height: 180,
},
// 新增申請注意事項底部:手寫標語、書本與馬克杯
{
source: NEW_APPLICATION,
file: "notes-books.webp",
left: 1340,
top: 722,
width: 332,
height: 219,
},
];
async function main() {
mkdirSync(OUT, { recursive: true });
for (const c of CROPS) {
const target = path.join(OUT, c.file);
await sharp(c.source)
.extract({ left: c.left, top: c.top, width: c.width, height: c.height })
.webp({ quality: 88 })
.toFile(target);
console.log(`${target}(${c.width}×${c.height})`);
}
}
main().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
@@ -2,8 +2,11 @@
import { useActionState } from "react";
import { commitRosterAction, previewRosterAction, type ImportState } from "./actions";
import { buttonClass } from "@/components/ui/button";
import { Card } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
// 暫時樣式:FileUploader、ErrorSummary 等共用元件由 add-app-shell 建立。
/** 名冊 CSV 匯入:先上傳檢查,全部列正確才能確認匯入(有錯誤時不寫入任何資料)。 */
export function ImportForm() {
const [previewState, preview, previewing] = useActionState<ImportState, FormData>(
previewRosterAction,
@@ -18,22 +21,49 @@ export function ImportForm() {
return (
<>
<form action={preview}>
<label htmlFor="roster-file">名冊檔案(CSV,UTF-8)</label>
<input id="roster-file" name="file" type="file" accept=".csv,text/csv" required />
<button type="submit" disabled={previewing}>
{previewing ? "檢查中…" : "上傳並檢查"}
</button>
</form>
{state.step === "upload" && state.error && <p role="alert">{state.error}</p>}
<Card title="上傳名冊" icon="upload">
<form action={preview} className="flex flex-wrap items-end gap-4">
<div className="flex flex-col gap-2">
<label htmlFor="roster-file" className="font-medium">
名冊檔案(CSV,UTF-8)
</label>
<input
id="roster-file"
name="file"
type="file"
accept=".csv,text/csv"
required
className="rounded-control border border-dashed border-border-strong bg-canvas/60 px-4 py-3 text-sm"
/>
</div>
<button type="submit" disabled={previewing} className={buttonClass("primary")}>
{previewing ? "檢查中…" : "上傳並檢查"}
</button>
</form>
{state.step === "upload" && state.error && (
<div className="mt-4">
<Alert tone="danger">{state.error}</Alert>
</div>
)}
</Card>
{state.step === "preview" && (
<section aria-labelledby="preview-title">
<h2 id="preview-title">檢查結果:{state.fileName}</h2>
<section
aria-labelledby="preview-title"
className="mt-6 rounded-card bg-surface p-5 shadow-card md:p-7"
>
<h2 id="preview-title" className="mb-4 text-xl font-bold">
檢查結果:{state.fileName}
</h2>
{state.errors.length > 0 ? (
<div role="alert">
<p>有 {state.errors.length} 列錯誤,未匯入任何資料。請修正後重新上傳。</p>
<ul>
<div
role="alert"
className="rounded-card border border-danger/30 bg-danger-soft px-5 py-4"
>
<p className="font-semibold">
有 {state.errors.length} 列錯誤,未匯入任何資料。請修正後重新上傳。
</p>
<ul className="mt-2 list-disc space-y-1 pl-5">
{state.errors.map((e) => (
<li key={e.line}>
第 {e.line} 列:{e.message}
@@ -42,13 +72,13 @@ export function ImportForm() {
</ul>
</div>
) : (
<form action={commit}>
<p>
<form action={commit} className="flex flex-wrap items-center gap-4">
<p className="text-lg">
將新增 {state.create} 筆、更新 {state.update} 筆人員資料。
</p>
<input type="hidden" name="csvText" value={state.csvText} />
<input type="hidden" name="fileName" value={state.fileName} />
<button type="submit" disabled={committing}>
<button type="submit" disabled={committing} className={buttonClass("primary")}>
{committing ? "匯入中…" : "確認匯入"}
</button>
</form>
+146 -111
View File
@@ -1,5 +1,9 @@
import { PageHeader } from "@/components/page-header";
import Link from "next/link";
import { Card, PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { buttonClass, ButtonLink, pillClass } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { ToneBadge } from "@/components/ui/status-badge";
import { localDate } from "@/domain/calendar";
import { ROLES, ROLE_LABELS } from "@/lib/roles";
import { requireRouteAccess } from "@/server/auth/current-user";
@@ -20,7 +24,6 @@ const FILTERS: { value: AccountFilter; label: string }[] = [
{ value: "inactive", label: "已停用" },
];
// 暫時樣式:表格、表單元件與確認視窗由 add-app-shell 統一。
export default async function AccountsPage({
searchParams,
}: {
@@ -42,120 +45,152 @@ export default async function AccountsPage({
<PageHeader
title="帳號與角色"
description="指派部門、角色與停用帳號;新進人員首次登入後會出現在「待指派部門」。"
actions={
<ButtonLink href="/admin/accounts/import" variant="secondary" icon="upload">
匯入名冊 CSV
</ButtonLink>
}
/>
<p>
<Link href="/admin/accounts/import">匯入名冊 CSV</Link>
</p>
{error && <p role="alert">{error}</p>}
{notice && <p role="status">{notice}</p>}
<nav aria-label="帳號篩選">
{FILTERS.map((f) =>
f.value === filter ? (
<strong key={f.value}>{f.label}</strong>
) : (
<Link key={f.value} href={`/admin/accounts?filter=${f.value}`}>
{error && <Alert tone="danger">{error}</Alert>}
{notice && <Alert tone="success">{notice}</Alert>}
<Card title="帳號清單" icon="accounts">
<nav aria-label="帳號篩選" className="mb-5 flex flex-wrap gap-2">
{FILTERS.map((f) => (
<Link
key={f.value}
href={`/admin/accounts?filter=${f.value}`}
aria-current={f.value === filter ? "true" : undefined}
className={pillClass(f.value === filter)}
>
{f.label}
</Link>
),
)}
</nav>
))}
</nav>
{accounts.length === 0 ? (
<p>沒有符合條件的帳號。</p>
) : (
<table>
<thead>
<tr>
<th>員工編號</th>
<th>姓名/Email</th>
<th>部門</th>
<th>角色</th>
<th>狀態</th>
</tr>
</thead>
<tbody>
{accounts.map((a) => (
<tr key={a.id} data-testid={`account-${a.employeeNo}`}>
<td>{a.employeeNo}</td>
<td>
{a.name ?? "(尚未登入)"}
<br />
{a.email ?? ""}
</td>
<td>
{a.departmentName ?? "待指派部門"}
{a.active && (
<form action={assignDepartmentAction}>
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
<select
name="departmentId"
defaultValue={a.departmentId ?? ""}
aria-label="所屬部門"
required
>
<option value="" disabled>
選擇部門
</option>
{departmentOptions.map((d) => (
<option key={d.id} value={d.id}>
{d.name}
</option>
{accounts.length === 0 ? (
<EmptyState title="沒有符合條件的帳號" description="切換上方篩選條件後再試一次。" />
) : (
<div className="relative overflow-x-auto">
<table className="min-w-[64rem]">
<thead>
<tr>
<th>員工編號</th>
<th>姓名/Email</th>
<th>部門</th>
<th>角色</th>
<th>狀態</th>
</tr>
</thead>
<tbody>
{accounts.map((a) => (
<tr key={a.id} data-testid={`account-${a.employeeNo}`} className="align-top">
<td className="font-medium whitespace-nowrap">{a.employeeNo}</td>
<td>
<span className="block font-medium">{a.name ?? "(尚未登入)"}</span>
<span className="block text-sm break-all text-muted">{a.email ?? ""}</span>
</td>
<td>
<span className="block font-medium">{a.departmentName ?? "待指派部門"}</span>
{a.active && (
<form
action={assignDepartmentAction}
className="mt-2 flex flex-wrap items-center gap-2"
>
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
<select
name="departmentId"
defaultValue={a.departmentId ?? ""}
aria-label="所屬部門"
required
className="max-w-48 py-1.5 text-sm"
>
<option value="" disabled>
選擇部門
</option>
{departmentOptions.map((d) => (
<option key={d.id} value={d.id}>
{d.name}
</option>
))}
</select>
<input
type="date"
name="effectiveFrom"
defaultValue={today}
max={today}
aria-label="生效日"
className="py-1.5 text-sm"
/>
<button type="submit" className={buttonClass("secondary", "sm")}>
指派部門
</button>
</form>
)}
</td>
<td>
<form action={setRolesAction} className="flex flex-wrap items-center gap-2">
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
{ROLES.map((role) => (
<label
key={role}
className="inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 text-sm whitespace-nowrap has-[:checked]:border-accent has-[:checked]:bg-accent-soft"
>
<input
type="checkbox"
name="roles"
value={role}
defaultChecked={a.roles.includes(role)}
disabled={role === "employee"}
className="accent-primary"
/>
{ROLE_LABELS[role]}
</label>
))}
</select>
<input
type="date"
name="effectiveFrom"
defaultValue={today}
max={today}
aria-label="生效日"
/>
<button type="submit">指派部門</button>
</form>
)}
</td>
<td>
<form action={setRolesAction}>
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
{ROLES.map((role) => (
<label key={role}>
<input
type="checkbox"
name="roles"
value={role}
defaultChecked={a.roles.includes(role)}
disabled={role === "employee"}
/>
{ROLE_LABELS[role]}
</label>
))}
<button type="submit">更新角色</button>
</form>
{a.roles.includes("admin") && (
<form action={setAuditLogAccessAction}>
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
<input type="hidden" name="allow" value={String(!a.canViewAuditLog)} />
檢視操作紀錄:{a.canViewAuditLog ? "已授權" : "未授權"}
<button type="submit">{a.canViewAuditLog ? "撤銷" : "授予"}</button>
</form>
)}
</td>
<td>
{a.active ? "在職" : "已停用"}
<form action={setAccountActiveAction}>
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
<input type="hidden" name="active" value={String(!a.active)} />
<button type="submit">{a.active ? "停用" : "啟用"}</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
)}
<button type="submit" className={buttonClass("secondary", "sm")}>
更新角色
</button>
</form>
{a.roles.includes("admin") && (
<form
action={setAuditLogAccessAction}
className="mt-2 flex flex-wrap items-center gap-2 text-sm"
>
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
<input type="hidden" name="allow" value={String(!a.canViewAuditLog)} />
檢視操作紀錄:{a.canViewAuditLog ? "已授權" : "未授權"}
<button type="submit" className={buttonClass("ghost", "sm")}>
{a.canViewAuditLog ? "撤銷" : "授予"}
</button>
</form>
)}
</td>
<td className="whitespace-nowrap">
<ToneBadge tone={a.active ? "success" : "neutral"}>
{a.active ? "在職" : "已停用"}
</ToneBadge>
<form action={setAccountActiveAction} className="mt-2">
<input type="hidden" name="userId" value={a.id} />
<input type="hidden" name="back" value={back} />
<input type="hidden" name="active" value={String(!a.active)} />
<button
type="submit"
className={buttonClass(a.active ? "danger-outline" : "secondary", "sm")}
>
{a.active ? "停用" : "啟用"}
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Card>
</div>
);
}
+10 -4
View File
@@ -19,6 +19,7 @@ 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";
import { buttonClass } from "@/components/ui/button";
const PAGE = "/admin/audit-log";
@@ -43,7 +44,6 @@ function formatValue(value: unknown): string {
return JSON.stringify(value);
}
// 暫時樣式:表格、抽屜與 EmptyState 等共用元件由 add-app-shell 統一。
export default async function AuditLogPage({
searchParams,
}: {
@@ -72,7 +72,7 @@ export default async function AuditLogPage({
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"
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-2 [&_label]:font-medium md:p-7"
>
<label>
起日 <input type="date" name="from" defaultValue={filters.from} />
@@ -108,8 +108,14 @@ export default async function AuditLogPage({
<label>
對象 ID <input name="targetId" defaultValue={filters.targetId} />
</label>
<button type="submit">查詢</button>
<Link href={PAGE}>清除條件</Link>
<div className="flex gap-2">
<button type="submit" className={buttonClass("primary")}>
查詢
</button>
<Link href={PAGE} className={buttonClass("ghost")}>
清除條件
</Link>
</div>
</form>
<Card>
+145 -70
View File
@@ -1,5 +1,10 @@
import { Icon } from "@/components/icons";
import { PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { buttonClass } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { Field, inputClass } from "@/components/ui/field";
import { ToneBadge } from "@/components/ui/status-badge";
import { DEPARTMENT_TYPES, DEPARTMENT_TYPE_LABELS } from "@/lib/department-types";
import { listUnassignedReviewDepartments } from "@/server/applications/review";
import { requireRouteAccess } from "@/server/auth/current-user";
@@ -13,9 +18,23 @@ import {
updateDepartmentAction,
} from "./actions";
function TypeSelect({ defaultValue }: { defaultValue?: string }) {
function TypeSelect({
defaultValue,
className,
id,
}: {
defaultValue?: string;
className?: string;
id?: string;
}) {
return (
<select name="type" defaultValue={defaultValue ?? "general"} aria-label="部門類型">
<select
id={id}
name="type"
defaultValue={defaultValue ?? "general"}
aria-label={id ? undefined : "部門類型"}
className={className}
>
{DEPARTMENT_TYPES.map((type) => (
<option key={type} value={type}>
{DEPARTMENT_TYPE_LABELS[type]}
@@ -25,7 +44,6 @@ function TypeSelect({ defaultValue }: { defaultValue?: string }) {
);
}
// 暫時樣式:表格、表單元件與確認視窗由 add-app-shell 統一。
export default async function DepartmentsPage({
searchParams,
}: {
@@ -43,7 +61,7 @@ export default async function DepartmentsPage({
title="部門管理"
description="維護部門代碼、類型(一般/研發)與部門主管。部門不能刪除,只能停用。"
/>
{error && <p role="alert">{error}</p>}
{error && <Alert tone="danger">{error}</Alert>}
{unassigned.length > 0 && (
<Alert tone="warning" title="有待審申請的部門尚未設定主管">
<ul data-testid="unassigned-review">
@@ -56,78 +74,135 @@ export default async function DepartmentsPage({
</Alert>
)}
<section aria-labelledby="new-department">
<h2 id="new-department">新增部門</h2>
<form action={createDepartmentAction}>
<label>
部門名稱 <input name="name" required />
</label>
<label>
部門代碼(選填) <input name="code" />
</label>
<label>
部門類型 <TypeSelect />
</label>
<button type="submit">新增</button>
<section
aria-labelledby="new-department"
className="rounded-card bg-surface p-5 shadow-card md:p-7"
>
<h2 id="new-department" className="mb-5 flex items-center gap-2.5 text-xl font-bold">
<Icon name="departments" className="size-6" />
新增部門
</h2>
<form
action={createDepartmentAction}
className="grid gap-4 sm:grid-cols-2 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_12rem_auto] lg:items-end"
>
<Field id="new-department-name" label="部門名稱" required>
<input name="name" required className={inputClass} />
</Field>
<Field id="new-department-code" label="部門代碼(選填)">
<input name="code" className={inputClass} />
</Field>
<Field id="new-department-type" label="部門類型">
<TypeSelect className={inputClass} />
</Field>
<button type="submit" className={buttonClass("primary")}>
新增
</button>
</form>
</section>
<section aria-labelledby="department-list">
<h2 id="department-list">部門清單</h2>
<section
aria-labelledby="department-list"
className="rounded-card bg-surface p-5 shadow-card md:p-7"
>
<h2 id="department-list" className="mb-5 flex items-center gap-2.5 text-xl font-bold">
<Icon name="list" className="size-6" />
部門清單
</h2>
{departments.length === 0 ? (
<p>尚未建立部門。</p>
<EmptyState title="尚未建立部門" description="用上方表單新增第一個部門。" />
) : (
<table>
<thead>
<tr>
<th>部門</th>
<th>狀態</th>
<th>部門主管</th>
</tr>
</thead>
<tbody>
{departments.map((d) => (
<tr key={d.id} data-testid={`department-${d.id}`}>
<td>
<form action={updateDepartmentAction}>
<input type="hidden" name="id" value={d.id} />
<input name="name" defaultValue={d.name} aria-label="部門名稱" required />
<input name="code" defaultValue={d.code ?? ""} aria-label="部門代碼" />
<TypeSelect defaultValue={d.type} />
<button type="submit">儲存</button>
</form>
</td>
<td>
{d.active ? "啟用" : "已停用"}
<form action={setDepartmentActiveAction}>
<input type="hidden" name="id" value={d.id} />
<input type="hidden" name="active" value={String(!d.active)} />
<button type="submit">{d.active ? "停用" : "啟用"}</button>
</form>
</td>
<td>
<ul>
{d.managers.map((m) => (
<li key={m.userId}>
{m.name ?? ""}({m.employeeNo})
<form action={removeManagerAction}>
<input type="hidden" name="departmentId" value={d.id} />
<input type="hidden" name="userId" value={m.userId} />
<button type="submit">移除</button>
</form>
</li>
))}
</ul>
<form action={assignManagerAction}>
<input type="hidden" name="departmentId" value={d.id} />
<input name="employeeNo" aria-label="主管員工編號" required />
<button type="submit">指派主管</button>
</form>
</td>
<div className="relative overflow-x-auto">
<table className="min-w-[56rem]">
<thead>
<tr>
<th>部門</th>
<th>狀態</th>
<th>部門主管</th>
</tr>
))}
</tbody>
</table>
</thead>
<tbody>
{departments.map((d) => (
<tr key={d.id} data-testid={`department-${d.id}`} className="align-top">
<td>
<form
action={updateDepartmentAction}
className="flex flex-wrap items-center gap-2"
>
<input type="hidden" name="id" value={d.id} />
<input
name="name"
defaultValue={d.name}
aria-label="部門名稱"
required
className="w-40 py-1.5 text-sm"
/>
<input
name="code"
defaultValue={d.code ?? ""}
aria-label="部門代碼"
className="w-28 py-1.5 text-sm"
/>
<TypeSelect defaultValue={d.type} className="py-1.5 text-sm" />
<button type="submit" className={buttonClass("secondary", "sm")}>
儲存
</button>
</form>
</td>
<td className="whitespace-nowrap">
<ToneBadge tone={d.active ? "success" : "neutral"}>
{d.active ? "啟用" : "已停用"}
</ToneBadge>
<form action={setDepartmentActiveAction} className="mt-2">
<input type="hidden" name="id" value={d.id} />
<input type="hidden" name="active" value={String(!d.active)} />
<button
type="submit"
className={buttonClass(d.active ? "danger-outline" : "secondary", "sm")}
>
{d.active ? "停用" : "啟用"}
</button>
</form>
</td>
<td>
<ul className="space-y-1.5">
{d.managers.map((m) => (
<li key={m.userId} className="flex flex-wrap items-center gap-2">
<span className="font-medium">
{m.name ?? ""}({m.employeeNo})
</span>
<form action={removeManagerAction}>
<input type="hidden" name="departmentId" value={d.id} />
<input type="hidden" name="userId" value={m.userId} />
<button type="submit" className={buttonClass("ghost", "sm")}>
移除
</button>
</form>
</li>
))}
</ul>
<form
action={assignManagerAction}
className="mt-2 flex flex-wrap items-center gap-2"
>
<input type="hidden" name="departmentId" value={d.id} />
<input
name="employeeNo"
aria-label="主管員工編號"
placeholder="員工編號"
required
className="w-32 py-1.5 text-sm"
/>
<button type="submit" className={buttonClass("secondary", "sm")}>
指派主管
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</div>
+1 -1
View File
@@ -27,7 +27,7 @@ export function MonthSelect({
id={id}
value={value}
onChange={(e) => router.push(`${basePath}?month=${e.target.value}`)}
className="rounded-control border border-border-strong bg-surface px-3 py-2"
className="rounded-control border border-border-strong bg-surface px-4 py-2.5"
>
{months.map((m) => (
<option key={m} value={m}>
+9 -9
View File
@@ -17,6 +17,8 @@ import {
} from "@/server/settlement/payouts";
import { MonthSelect } from "../month-select";
import { PayoutTable } from "./payout-table";
import { buttonClass } from "@/components/ui/button";
import { pillClass } from "@/components/ui/button";
const FILTERS: { key: PayoutFilter; label: string }[] = [
{ key: "all", label: "全部" },
@@ -25,8 +27,7 @@ const FILTERS: { key: PayoutFilter; label: string }[] = [
{ key: "failed", label: "發放失敗" },
];
const button =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-4 py-2 font-medium";
const button = buttonClass("secondary");
export default async function AdminPaymentsPage({
searchParams,
@@ -88,20 +89,19 @@ export default async function AdminPaymentsPage({
key={f.key}
href={`/admin/payments?month=${month}&status=${f.key}`}
aria-current={f.key === filter ? "page" : undefined}
className={`rounded-control border px-4 py-2 font-medium ${
f.key === filter
? "border-primary bg-primary text-on-primary"
: "border-border-strong bg-surface"
}`}
className={pillClass(f.key === filter)}
>
{f.label}
</Link>
))}
</nav>
<section className="rounded-card bg-surface p-5 shadow-card md:p-6" aria-label="發放名單">
<section
className="min-w-0 rounded-card bg-surface p-5 shadow-card md:p-7"
aria-label="發放名單"
>
<div className="mb-4 flex flex-wrap items-baseline justify-between gap-3">
<h2 className="text-lg font-semibold">{formatMonth(month)} 發放名單</h2>
<h2 className="text-xl font-bold">{formatMonth(month)} 發放名單</h2>
<p data-testid="payout-total">
合計 {people} 人、
<MoneyDisplay amount={total} kind="final" />
@@ -17,6 +17,7 @@ import {
type PayoutStatus,
} from "@/lib/settlement";
import { markFailedAction, markPaidAction, rescheduleAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
export interface PayoutItem {
id: number;
@@ -43,8 +44,8 @@ const STATUS_TONES: Record<PayoutStatus, StatusTone> = {
cancelled: "neutral",
};
const small =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-3 py-1.5 text-sm font-medium whitespace-nowrap";
const small = buttonClass("secondary", "sm");
const dangerSmall = buttonClass("danger-outline", "sm");
const th = "px-3 py-2.5 font-medium";
const td = "px-3 py-3";
@@ -116,7 +117,7 @@ export function PayoutTable({ items }: { items: PayoutItem[] }) {
<ReasonDialog
triggerLabel="標記發放失敗"
triggerAriaLabel={`標記發放失敗:${item.name}`}
triggerClassName={`${small} text-danger`}
triggerClassName={dangerSmall}
title={`${item.name} 這筆發放失敗?`}
description={`${formatMonth(item.chargeMonth)} 刷卡、${formatMoney(item.amount)}。標記後不計入已發放與合計,可再改期至下一個發放月份。`}
reasonLabel="失敗原因"
@@ -171,7 +172,7 @@ export function PayoutTable({ items }: { items: PayoutItem[] }) {
<button
type="button"
disabled={chosen.length === 0}
className="rounded-control bg-primary px-4 py-2 font-medium text-on-primary disabled:opacity-50"
className={buttonClass("primary")}
>
標記已發放
</button>
@@ -184,7 +185,7 @@ export function PayoutTable({ items }: { items: PayoutItem[] }) {
</div>
</div>
<div className="hidden overflow-x-auto md:block" data-testid="table-mode">
<div className="relative hidden overflow-x-auto md:block" data-testid="table-mode">
<table className="w-full border-collapse text-left">
<caption className="sr-only">發放名單</caption>
<thead>
+3 -8
View File
@@ -28,6 +28,7 @@ import { listRuleVersions, type VersionStatus } from "@/server/rules/params";
import { adjustHeadcountAction, createSnapshotsAction } from "./actions";
import { MonthNav } from "./month-nav";
import { ParamsForm } from "./params-form";
import { buttonClass } from "@/components/ui/button";
const STATUS_BADGE: Record<VersionStatus, { label: string; tone: "success" | "info" | "neutral" }> =
{
@@ -190,10 +191,7 @@ async function HeadcountTab({
{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"
>
<button type="submit" className={buttonClass("secondary")}>
建立 {formatMonth(month)} 快照
</button>
</form>
@@ -271,10 +269,7 @@ async function HeadcountTab({
調整原因
<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 type="submit" className={buttonClass("primary")}>
儲存調整
</button>
</form>
+2 -4
View File
@@ -15,6 +15,7 @@ import {
type RuleParams,
} from "@/lib/rule-params";
import { saveParamsAction, type SaveParamsState } from "./actions";
import { buttonClass } from "@/components/ui/button";
// 參數路徑 → 表單欄位 id(錯誤摘要捲動、inline 錯誤對應)。
const FIELD_IDS: Record<string, string> = {
@@ -280,10 +281,7 @@ function ParamsFields({
<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 type="button" className={buttonClass("primary")}>
儲存變更
</button>
}
@@ -7,11 +7,10 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { Field, inputClass } from "@/components/ui/field";
import { useToast } from "@/components/ui/toast";
import { finalizeAction, returnAction } from "../../actions";
import { buttonClass } from "@/components/ui/button";
const primary =
"inline-flex items-center justify-center rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover disabled:opacity-60";
const secondary =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-5 py-2.5 font-medium text-danger disabled:opacity-60";
const primary = buttonClass("primary");
const secondary = buttonClass("danger-outline");
export const RETURN_REASON_HINT = "請填寫退回原因";
@@ -7,10 +7,10 @@ import { ReasonDialog } from "@/components/ui/reason-dialog";
import { useToast } from "@/components/ui/toast";
import { formatMoney, formatMonth } from "@/lib/format";
import { cancelCorrectionAction, createAdjustmentAction, revokeAction } from "../../actions";
import { buttonClass } from "@/components/ui/button";
const button =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-3 py-1.5 text-sm font-medium";
const dangerButton = `${button} text-danger`;
const button = buttonClass("secondary", "sm");
const dangerButton = buttonClass("danger-outline", "sm");
function useRun() {
const router = useRouter();
+3 -3
View File
@@ -34,7 +34,7 @@ function StatCard({
testId: string;
}) {
return (
<div className="rounded-card bg-surface p-5 shadow-card" data-testid={testId}>
<div className="rounded-card bg-surface p-5 shadow-card md:p-6" data-testid={testId}>
<p className="text-sm text-muted">{label}</p>
<p className="mt-2 text-2xl font-semibold">{value}</p>
</div>
@@ -103,8 +103,8 @@ export default async function AdminSettlementsPage({
/>
</div>
<section className="rounded-card bg-surface p-5 shadow-card md:p-6" aria-label="各部門月結">
<h2 className="mb-4 text-lg font-semibold">{formatMonth(month)} 各部門月結</h2>
<section className="rounded-card bg-surface p-5 shadow-card md:p-7" aria-label="各部門月結">
<h2 className="mb-5 text-xl font-bold">{formatMonth(month)} 各部門月結</h2>
<DataTable<CompanyRow>
caption="各部門月結"
rows={overview.rows}
@@ -5,11 +5,10 @@ import { useRouter } from "next/navigation";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { useToast } from "@/components/ui/toast";
import { deleteDraftAction, withdrawAction } from "../actions";
import { buttonClass } from "@/components/ui/button";
const primary =
"inline-flex items-center justify-center rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover";
const secondary =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-5 py-2.5 font-medium";
const primary = buttonClass("primary");
const secondary = buttonClass("secondary");
/** 申請詳情的操作(依狀態只顯示允許的操作):編輯、刪除草稿、補件重送、撤回。 */
export function DetailActions({
+11 -12
View File
@@ -1,5 +1,4 @@
import { notFound, redirect } from "next/navigation";
import { PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { isEditableStatus } from "@/lib/attachments";
import { getApplicationDetail } from "@/server/applications/service";
@@ -19,19 +18,19 @@ export default async function EditApplicationPage({ params }: { params: Promise<
const comment =
app.status === "needs_revision" ? latestReviewComment(getDb(), app.id, "needs_revision") : null;
return (
<div>
<PageHeader
title={app.status === "needs_revision" ? "補件並重新送出" : "編輯申請草稿"}
description={`申請編號 ${app.applicationNo ?? "--"}`}
/>
{comment && (
<div className="mb-6">
<ApplicationForm
{...buildFormProps(user, app.departmentName, app)}
header={{
title: app.status === "needs_revision" ? "補件並重新送出" : "編輯申請草稿",
description: `申請編號 ${app.applicationNo ?? "--"}`,
}}
notice={
comment ? (
<Alert tone="warning" title="主管意見">
{comment}
</Alert>
</div>
)}
<ApplicationForm {...buildFormProps(user, app.departmentName, app)} />
</div>
) : undefined
}
/>
);
}
+7 -5
View File
@@ -4,6 +4,7 @@ import { Card, PageHeader } from "@/components/page-header";
import { CorrectionAmounts, CorrectionList } from "@/components/settlement/correction-list";
import { Alert } from "@/components/ui/alert";
import { MoneyDisplay } from "@/components/ui/money-display";
import { PlatformIcon } from "@/components/ui/platform-icon";
import { StatusBadge } from "@/components/ui/status-badge";
import { payoutMonth } from "@/domain/settlement";
import type { ApplicationStatus } from "@/lib/application-status";
@@ -71,6 +72,7 @@ export default async function ApplicationDetailPage({
description={
<span className="inline-flex flex-wrap items-center gap-2">
<StatusBadge status={app.status} />
<PlatformIcon platform={app.platform} size={26} />
<span>{platformDisplay(app) ?? "尚未選擇平台"}</span>
{app.planName && <span>· {app.planName}</span>}
</span>
@@ -110,7 +112,7 @@ export default async function ApplicationDetailPage({
)}
{corrections && (
<section data-testid="application-corrections">
<Card title="補助更正">
<Card title="補助更正" icon="settlement">
<p className="mb-4 text-sm text-muted">
核定後的更正以申請人 {formatMonth(app.applicationMonth)}{" "}
的補助合計計算,原核定結果不變。
@@ -130,7 +132,7 @@ export default async function ApplicationDetailPage({
</div>
<aside aria-label="金額摘要" className="space-y-6">
<Card title="金額摘要">
<Card title="金額摘要" icon="calculator">
<dl className="space-y-3">
<Row label="實際支付">
<MoneyDisplay amount={app.twdAmount} />
@@ -149,7 +151,7 @@ export default async function ApplicationDetailPage({
</dl>
<p className="mt-4 text-sm text-muted">實際補助於月結後確認</p>
</Card>
<Card title="月結與發放">
<Card title="月結與發放" icon="payout">
<p className="text-muted" data-testid="payout-info">
{corrections?.revoked
? "此月補助已撤銷,不會發放(原因見「補助更正」)。"
@@ -182,8 +184,8 @@ function payoutText(status: ApplicationStatus, finalAmount: number | null, month
function Row({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="flex items-baseline justify-between gap-4">
<dt className="text-sm text-muted">{label}</dt>
<dd>{children}</dd>
<dt className="text-muted">{label}</dt>
<dd className="font-medium">{children}</dd>
</div>
);
}
+24 -15
View File
@@ -11,6 +11,7 @@ import type { ApplicationDetail } from "@/server/applications/service";
import { platformDisplay } from "@/server/applications/service";
import type { listActiveAttachments } from "@/server/attachments/service";
import { SELF_REVIEW_LABEL } from "@/server/auth/scope";
import { PlatformIcon } from "@/components/ui/platform-icon";
// 申請詳情(申請人)與審核詳情(主管)共用的區塊。
@@ -25,15 +26,20 @@ export function ApplicationInfoCard({
estimate?: number | null;
}) {
return (
<Card title="申請資料">
<dl className="grid gap-x-6 gap-y-3 sm:grid-cols-2">
<Card title="申請資料" icon="clipboard">
<dl className="grid gap-x-8 gap-y-5 sm:grid-cols-2">
<Item label="申請人">{app.applicantName ?? app.applicantEmployeeNo}</Item>
<Item label="部門">{app.departmentName}</Item>
<Item label="申請月份">
{app.applicationMonth ? formatMonth(app.applicationMonth) : "--"}
</Item>
<Item label="刷卡日期">{app.cardDate ? formatDate(app.cardDate) : "--"}</Item>
<Item label="AI 平台">{platformDisplay(app) ?? "--"}</Item>
<Item label="AI 平台">
<span className="inline-flex items-center gap-2">
<PlatformIcon platform={app.platform} size={24} />
{platformDisplay(app) ?? "--"}
</span>
</Item>
<Item label="訂閱方案/項目">{app.planName ?? "--"}</Item>
<Item label="實際台幣支付金額">
<MoneyDisplay amount={app.twdAmount} />
@@ -58,7 +64,7 @@ export function ApplicationInfoCard({
export function PurposeCard({ app }: { app: ApplicationDetail }) {
return (
<Card title="工作用途與成果">
<Card title="工作用途與成果" icon="file">
<dl className="space-y-4">
<Item label="工作用途說明">
<span className="whitespace-pre-wrap">{app.purpose ?? "--"}</span>
@@ -85,16 +91,19 @@ export function PurposeCard({ app }: { app: ApplicationDetail }) {
export function AttachmentsCard({ files }: { files: ReturnType<typeof listActiveAttachments> }) {
return (
<Card title="憑證附件">
<Card title="憑證附件" icon="upload">
<ul className="space-y-3">
{ATTACHMENT_KINDS.map((kind) => {
const file = files.find((f) => f.kind === kind);
return (
<li key={kind} className="flex flex-wrap items-center justify-between gap-3">
<span>
<span className="font-medium">{ATTACHMENT_KIND_LABELS[kind]}</span>
<span className="ml-2 text-sm text-muted">
{file ? `${file.originalName} ${formatFileSize(file.sizeBytes)}` : "未上傳"}
<li
key={kind}
className="flex flex-wrap items-center justify-between gap-3 rounded-control border border-border px-4 py-3"
>
<span className="min-w-0">
<span className="block font-medium">{ATTACHMENT_KIND_LABELS[kind]}</span>
<span className="block text-sm break-all text-muted">
{file ? `${file.originalName}・${formatFileSize(file.sizeBytes)}` : "未上傳"}
</span>
</span>
{file && <FilePreview file={file} label={ATTACHMENT_KIND_LABELS[kind]} />}
@@ -114,14 +123,14 @@ export function TimelineCard({
timeZone: string;
}) {
return (
<Card title="審核時間軸">
<Card title="審核時間軸" icon="audit">
{timeline.length === 0 ? (
<p className="text-muted">尚未送出。</p>
) : (
<ol className="space-y-4 border-l-2 border-border pl-5" data-testid="timeline">
<ol className="space-y-5 border-l-2 border-border pl-6" data-testid="timeline">
{timeline.map((entry) => (
<li key={entry.id} className="relative">
<span className="absolute top-1.5 -left-[1.6rem] size-2.5 rounded-full bg-accent" />
<span className="absolute top-1 -left-[2.05rem] size-4 rounded-full border-4 border-accent-soft bg-accent" />
<p className="font-medium">
{formatDateTime(entry.occurredAt, timeZone)} {entry.label}
</p>
@@ -141,8 +150,8 @@ export function TimelineCard({
export function Item({ label, children }: { label: string; children: ReactNode }) {
return (
<div>
<dt className="text-sm text-muted">{label}</dt>
<dd className="mt-0.5">{children}</dd>
<dt className="text-muted">{label}</dt>
<dd className="mt-1 font-medium">{children}</dd>
</div>
);
}
+387 -233
View File
@@ -10,12 +10,16 @@ import {
type FormEvent,
type ReactNode,
} from "react";
import { Card, StickyActions } from "@/components/page-header";
import { Icon } from "@/components/icons";
import { Illustration } from "@/components/illustration";
import { Card, PageHeader, StickyActions } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { ErrorSummary } from "@/components/ui/error-summary";
import { Field, inputClass } from "@/components/ui/field";
import { FileUploader, type UploadedFile } from "@/components/ui/file-uploader";
import { MoneyDisplay } from "@/components/ui/money-display";
import { PlatformIcon } from "@/components/ui/platform-icon";
import { useToast } from "@/components/ui/toast";
import {
applicationMonth,
@@ -30,8 +34,9 @@ import {
PURPOSE_SUGGESTED_MIN,
TEXT_MAX,
charCount,
sectionProgress,
stepProgress,
validateApplication,
type StepState,
type ApplicationFormValues,
type FieldError,
} from "@/lib/application-form";
@@ -43,6 +48,10 @@ import { ensureDraftAction, saveApplicationAction, type ApplicationFormState } f
import { DuplicateDialog } from "./duplicate-dialog";
export interface ApplicationFormProps {
/** 頁首標題與說明(頁首右側的完成進度由表單即時計算)。 */
header: { title: string; description?: ReactNode };
/** 頁首下方的提示(例如待補件的主管意見)。 */
notice?: ReactNode;
applicationId: number | null;
/** 待補件時為「重新送出」。 */
resubmit: boolean;
@@ -84,7 +93,7 @@ function readForm(form: HTMLFormElement): ApplicationFormValues {
}
/**
* 新增/編輯申請表單(單頁分區+即時摘要)。欄位不受控(defaultValue),摘要與驗證從表單讀值:
* 新增/編輯申請表單(單頁三欄:申請資料|補助試算與證明文件|注意事項;頁首顯示完成進度)。欄位不受控(defaultValue),摘要與驗證從表單讀值:
* 頁面完成 hydration 前輸入的內容也不會被覆蓋。「其他平台名稱」以 CSS 依選項顯示,不依賴 JavaScript。
*/
export function ApplicationForm(props: ApplicationFormProps) {
@@ -144,7 +153,6 @@ export function ApplicationForm(props: ApplicationFormProps) {
const twd = /^\d+$/.test(values.twdAmount.trim()) ? Number(values.twdAmount.trim()) : null;
const estimate =
twd !== null && twd > 0 ? estimateSubsidy(twd, rule.subsidyRatePercent, rule.rounding) : null;
const progress = sectionProgress(values, present);
const purposeLength = charCount(values.purpose.trim());
// 自行送出 action,而不是交給 <form action>:React 會在 form action 完成後自動清空不受控欄位,
@@ -203,7 +211,12 @@ export function ApplicationForm(props: ApplicationFormProps) {
/>
</dl>
);
const settleNote = <p className="text-sm text-muted">實際補助於月結後確認</p>;
const settleNote = (
<p className="flex gap-2 text-sm text-muted">
<Icon name="info" className="mt-0.5 size-4 shrink-0" />
實際補助於月結後確認
</p>
);
return (
<form
@@ -217,9 +230,18 @@ export function ApplicationForm(props: ApplicationFormProps) {
>
<input type="hidden" name="applicationId" value={applicationId ?? ""} />
<PageHeader
size="hero"
illustration="heroApplication"
title={props.header.title}
description={props.header.description}
aside={<StepIndicator steps={stepProgress(values, present)} />}
/>
{props.notice && <div className="mb-6">{props.notice}</div>}
{/* 手機與平板:頂部可收合摘要 */}
<details
className="mb-4 rounded-card bg-surface p-4 shadow-card xl:hidden"
className="mb-4 rounded-card bg-surface p-4 shadow-card lg:hidden"
data-testid="summary-mobile"
>
<summary className="cursor-pointer font-semibold">
@@ -232,7 +254,8 @@ export function ApplicationForm(props: ApplicationFormProps) {
</div>
</details>
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_20rem]">
<div className="grid items-start gap-6 lg:grid-cols-2 xl:grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)_minmax(0,0.8fr)]">
{/* 左欄:申請資料 */}
<div className="min-w-0 space-y-6">
{errors.length > 0 && <ErrorSummary errors={errors} />}
{state.status === "error" && state.message && (
@@ -245,60 +268,43 @@ export function ApplicationForm(props: ApplicationFormProps) {
</Alert>
)}
<Card title="申請人資訊">
<div className="grid gap-4 md:grid-cols-3">
<ReadOnly label="申請人" value={props.applicant.name} id="applicantName" />
<ReadOnly label="部門" value={props.applicant.department} id="departmentName" />
<ReadOnly
label="申請月份"
value={month ? formatMonth(month) : "--"}
id="applicationMonth"
/>
</div>
</Card>
<Card title="訂閱資訊">
<div className="group grid gap-4 md:grid-cols-2">
<Field id="platform" label="AI 平台" required error={errorFor("platform")}>
<select
name="platform"
defaultValue={props.initial.platform}
className={inputClass}
>
<option value="">請選擇平台</option>
{props.platforms.map((p) =>
p === OTHER_PLATFORM ? (
<option key={p} value={p} data-other="">
{p}
</option>
) : (
<option key={p} value={p}>
{p}
</option>
),
)}
</select>
</Field>
<div
className="hidden group-has-[option[data-other]:checked]:block"
data-testid="platform-other"
>
<Field
id="platformOther"
label="其他平台名稱"
required
hint="2–60 字"
error={errorFor("platformOther")}
>
<input
name="platformOther"
defaultValue={props.initial.platformOther}
maxLength={60}
className={inputClass}
/>
</Field>
<Card title="申請資料" icon="clipboard">
<div className="space-y-6">
<div className="grid gap-4 sm:grid-cols-3">
<ReadOnly label="申請人" value={props.applicant.name} id="applicantName" />
<ReadOnly label="部門" value={props.applicant.department} id="departmentName" />
<ReadOnly
label="申請月份"
value={month ? formatMonth(month) : "--"}
id="applicationMonth"
/>
</div>
<div className="md:col-span-2">
<div className="group space-y-4">
<PlatformPicker
platforms={props.platforms}
initial={props.initial.platform}
error={errorFor("platform")}
/>
<div
className="hidden group-has-[input[data-other]:checked]:block"
data-testid="platform-other"
>
<Field
id="platformOther"
label="其他平台名稱"
required
hint="2–60 字"
error={errorFor("platformOther")}
>
<input
name="platformOther"
defaultValue={props.initial.platformOther}
maxLength={60}
className={inputClass}
/>
</Field>
</div>
<Field
id="planName"
label="訂閱方案/項目"
@@ -314,140 +320,163 @@ export function ApplicationForm(props: ApplicationFormProps) {
/>
</Field>
</div>
</div>
</Card>
<Card title="金額與日期">
<div className="grid gap-4 md:grid-cols-2">
<Field
id="twdAmount"
label="實際台幣支付金額"
required
hint="以刷卡帳單上的台幣金額為準,補助依此計算"
error={errorFor("twdAmount")}
>
<input
name="twdAmount"
inputMode="numeric"
defaultValue={props.initial.twdAmount}
className={inputClass}
/>
</Field>
<Field
id="cardDate"
label="刷卡日期"
required
hint="申請月份依刷卡日期決定"
error={errorFor("cardDate")}
>
<input
name="cardDate"
type="date"
max={props.today}
defaultValue={props.initial.cardDate}
className={inputClass}
/>
</Field>
<Field
id="foreignAmount"
label="原幣金額(選填)"
hint="僅供參考,不參與補助計算"
error={errorFor("foreignAmount")}
>
<input
name="foreignAmount"
inputMode="decimal"
defaultValue={props.initial.foreignAmount}
className={inputClass}
/>
</Field>
<Field
id="currency"
label="幣別"
hint="填寫原幣金額時必填"
error={errorFor("currency")}
>
<select
name="currency"
defaultValue={props.initial.currency}
className={inputClass}
<div className="grid gap-4 sm:grid-cols-2">
<Field
id="twdAmount"
label="實際台幣支付金額"
required
hint="以刷卡帳單上的台幣金額為準,補助依此計算"
error={errorFor("twdAmount")}
>
<option value="">請選擇幣別</option>
{CURRENCIES.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
</Field>
<input
name="twdAmount"
inputMode="numeric"
defaultValue={props.initial.twdAmount}
className={inputClass}
/>
</Field>
<Field
id="cardDate"
label="刷卡日期"
required
hint="申請月份依刷卡日期決定"
error={errorFor("cardDate")}
>
<input
name="cardDate"
type="date"
max={props.today}
defaultValue={props.initial.cardDate}
className={inputClass}
/>
</Field>
<Field
id="foreignAmount"
label="原幣金額(選填)"
hint="僅供參考,不參與補助計算"
error={errorFor("foreignAmount")}
>
<input
name="foreignAmount"
inputMode="decimal"
defaultValue={props.initial.foreignAmount}
className={inputClass}
/>
</Field>
<Field
id="currency"
label="幣別"
hint="填寫原幣金額時必填"
error={errorFor("currency")}
>
<select
name="currency"
defaultValue={props.initial.currency}
className={inputClass}
>
<option value="">請選擇幣別</option>
{CURRENCIES.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
</Field>
</div>
<div className="space-y-4">
<Field
id="purpose"
label="工作用途說明"
required
hint={
<>
{PURPOSE_EXAMPLE}
<span className="mt-1 flex justify-between gap-3">
<span className="text-warning">
{purposeLength > 0 && purposeLength < PURPOSE_SUGGESTED_MIN
? PURPOSE_SHORT_HINT
: ""}
</span>
<span className="tabular-nums" data-testid="purpose-count">
{purposeLength} / {TEXT_MAX}
</span>
</span>
</>
}
error={errorFor("purpose")}
>
<textarea
name="purpose"
rows={4}
defaultValue={props.initial.purpose}
className={inputClass}
/>
</Field>
<Field
id="outcome"
label="成果產出"
required
hint={
<>
{OUTCOME_EXAMPLE}
<span className="mt-1 block text-right tabular-nums">
{charCount(values.outcome.trim())} / {TEXT_MAX}
</span>
</>
}
error={errorFor("outcome")}
>
<textarea
name="outcome"
rows={3}
defaultValue={props.initial.outcome}
className={inputClass}
/>
</Field>
<Field id="outcomeUrl" label="成果連結(選填)" error={errorFor("outcomeUrl")}>
<input
name="outcomeUrl"
type="url"
defaultValue={props.initial.outcomeUrl}
placeholder="https://"
className={inputClass}
/>
</Field>
</div>
</div>
</Card>
</div>
<Card title="工作用途與成果">
<div className="space-y-4">
<Field
id="purpose"
label="工作用途說明"
required
hint={
<>
{PURPOSE_EXAMPLE}
<span className="mt-1 flex justify-between gap-3">
<span className="text-warning">
{purposeLength > 0 && purposeLength < PURPOSE_SUGGESTED_MIN
? PURPOSE_SHORT_HINT
: ""}
</span>
<span className="tabular-nums" data-testid="purpose-count">
{purposeLength} / {TEXT_MAX}
</span>
</span>
</>
}
error={errorFor("purpose")}
>
<textarea
name="purpose"
rows={4}
defaultValue={props.initial.purpose}
className={inputClass}
/>
</Field>
<Field
id="outcome"
label="成果產出"
required
hint={
<>
{OUTCOME_EXAMPLE}
<span className="mt-1 block text-right tabular-nums">
{charCount(values.outcome.trim())} / {TEXT_MAX}
</span>
</>
}
error={errorFor("outcome")}
>
<textarea
name="outcome"
rows={3}
defaultValue={props.initial.outcome}
className={inputClass}
/>
</Field>
<Field id="outcomeUrl" label="成果連結(選填)" error={errorFor("outcomeUrl")}>
<input
name="outcomeUrl"
type="url"
defaultValue={props.initial.outcomeUrl}
placeholder="https://"
className={inputClass}
/>
</Field>
{/* 中欄:補助試算、證明文件、聲明 */}
<div className="min-w-0 space-y-6">
<aside
aria-label="補助摘要"
className="hidden rounded-card bg-surface p-5 shadow-card md:p-7 lg:block"
>
<h2 className="mb-5 flex items-center gap-2.5 text-xl font-bold">
<Icon name="calculator" className="size-6" />
補助試算
</h2>
<div className="grid grid-cols-2 divide-x divide-border rounded-control bg-canvas/70 px-4 py-4">
<div className="pr-4">
<p className="text-muted">支付金額</p>
<MoneyDisplay amount={twd} size="figure" />
</div>
<div className="pl-4">
<p className="text-muted">{rule.subsidyRatePercent}% 補助試算</p>
<MoneyDisplay amount={estimate} size="figure" emphasis />
</div>
</div>
</Card>
<div className="mt-5 space-y-4">
{summary}
{settleNote}
</div>
</aside>
<Card title="憑證附件">
<div className="grid gap-6 md:grid-cols-2">
<Card title="上傳證明文件" icon="file">
<div className="space-y-6">
{ATTACHMENT_KINDS.map((kind) => (
<FileUploader
key={kind}
@@ -469,7 +498,7 @@ export function ApplicationForm(props: ApplicationFormProps) {
</div>
</Card>
<Card title="聲明確認">
<Card title="聲明確認" icon="check">
<label className="flex items-start gap-3">
<input
id="declared"
@@ -478,7 +507,7 @@ export function ApplicationForm(props: ApplicationFormProps) {
defaultChecked={props.initial.declared}
aria-invalid={errorFor("declared") ? true : undefined}
aria-describedby={errorFor("declared") ? "declared-error" : undefined}
className="mt-1 size-4"
className="mt-1 size-4 accent-primary"
/>
<span>我確認以上資料真實,且訂閱用途符合工作需求。</span>
</label>
@@ -488,50 +517,28 @@ export function ApplicationForm(props: ApplicationFormProps) {
</p>
)}
</Card>
<StickyActions>
<button
type="submit"
name="intent"
value="draft"
disabled={pending}
className="rounded-control border border-border-strong bg-surface px-5 py-2.5 font-medium disabled:opacity-60"
>
儲存草稿
</button>
<button
type="submit"
name="intent"
value="submit"
disabled={pending}
className="rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover disabled:opacity-60"
>
{props.resubmit ? "重新送出" : "送出申請"}
</button>
</StickyActions>
</div>
<aside aria-label="補助摘要" className="hidden xl:block">
<div className="sticky top-6 space-y-4 rounded-card bg-surface p-5 shadow-card">
<h2 className="text-lg font-semibold">補助摘要</h2>
{summary}
{settleNote}
<div>
<p className="flex justify-between text-sm">
<span>完成進度</span>
<span data-testid="progress">
{progress.done} / {progress.total}
</span>
</p>
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-border">
<div
className="h-full bg-accent transition-[width]"
style={{ width: `${(progress.done / progress.total) * 100}%` }}
/>
</div>
</div>
</div>
</aside>
{/* 右欄:申請注意事項 */}
<ApplicationNotes ratePercent={rule.subsidyRatePercent} />
</div>
<div className="mt-6">
<StickyActions className="md:justify-between">
<Button
type="submit"
name="intent"
value="draft"
variant="secondary"
icon="save"
disabled={pending}
>
儲存草稿
</Button>
<Button type="submit" name="intent" value="submit" arrow disabled={pending}>
{props.resubmit ? "重新送出" : "送出申請"}
</Button>
</StickyActions>
</div>
<DuplicateDialog
cases={duplicates}
@@ -550,6 +557,153 @@ export function ApplicationForm(props: ApplicationFormProps) {
);
}
/**
* AI 平台選擇:原生 radio 做成圖示卡片(鍵盤方向鍵切換、hydration 前也能選、送出的值與下拉選單相同)。
* 第一個選項帶 id="platform",錯誤摘要可以聚焦到這一組。
*/
function PlatformPicker({
platforms,
initial,
error,
}: {
platforms: string[];
initial: string;
error?: string;
}) {
return (
<div
role="radiogroup"
aria-labelledby="platform-label"
aria-describedby={error ? "platform-error" : undefined}
aria-invalid={error ? true : undefined}
data-field="platform"
className="flex flex-col gap-2"
>
<p id="platform-label" className="font-medium">
選擇 AI 平台
<span className="ml-0.5 text-danger" aria-hidden="true">
*
</span>
<span className="sr-only">(必填)</span>
</p>
<div className="grid grid-cols-[repeat(auto-fill,minmax(8.5rem,1fr))] gap-3">
{platforms.map((p, i) => (
<label
key={p}
className={`flex cursor-pointer items-center gap-2.5 rounded-control border bg-surface px-3 py-3 transition-colors hover:bg-canvas has-[:checked]:border-accent has-[:checked]:bg-accent-soft has-[:checked]:ring-1 has-[:checked]:ring-accent has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-accent ${
error ? "border-danger" : "border-border-strong"
}`}
>
<input
type="radio"
name="platform"
value={p}
id={i === 0 ? "platform" : undefined}
defaultChecked={initial === p}
data-other={p === OTHER_PLATFORM ? "" : undefined}
className="sr-only"
/>
<PlatformIcon platform={p} size={30} />
<span className="min-w-0 font-medium break-words">{p}</span>
</label>
))}
</div>
{error && (
<p id="platform-error" className="text-sm text-danger">
{error}
</p>
)}
</div>
);
}
const STEP_CIRCLE: Record<StepState, string> = {
done: "bg-accent text-on-primary",
current: "bg-accent text-on-primary ring-4 ring-accent-soft",
todo: "bg-border text-muted",
};
const STEP_STATE_TEXT: Record<StepState, string> = {
done: "已完成",
current: "進行中",
todo: "未完成",
};
/** 頁首的完成進度(三段)。只反映填寫進度,不能點擊切換頁面。 */
function StepIndicator({ steps }: { steps: ReturnType<typeof stepProgress> }) {
return (
<ol aria-label="完成進度" data-testid="progress-steps" className="flex items-start">
{steps.map((step, i) => (
<li
key={step.label}
data-state={step.state}
className="relative flex w-24 flex-col items-center gap-2 text-center md:w-28"
>
{i > 0 && (
<span
aria-hidden="true"
className={`absolute top-5 right-1/2 h-0.5 w-full ${
step.state === "todo" ? "bg-border" : "bg-accent"
}`}
/>
)}
<span
className={`relative z-10 grid size-10 place-items-center rounded-full text-lg font-semibold ${STEP_CIRCLE[step.state]}`}
>
{step.state === "done" ? <Icon name="check" /> : i + 1}
</span>
<span
className={`text-sm ${step.state === "todo" ? "text-muted" : "font-semibold text-accent"}`}
>
{step.label}
<span className="sr-only">({STEP_STATE_TEXT[step.state]})</span>
</span>
</li>
))}
</ol>
);
}
/** 右欄的申請注意事項(文案依規格;補助比例取自制度參數)。 */
function ApplicationNotes({ ratePercent }: { ratePercent: number }) {
const notes: [string, string][] = [
["僅限與工作相關之用途", "個人娛樂、非工作目的之使用不在補助範圍內。"],
["須提供有效的訂閱證明與刷卡帳單", "請上傳清晰、完整的文件。"],
[`補助比例為 ${ratePercent}%`, "依刷卡帳單的台幣金額計算,各部門每月有補助上限。"],
["所有申請需經主管審核", "實際補助於月結後確認,結果將另行通知。"],
["如有任何問題", "請聯繫行政管理單位。"],
];
return (
<section
aria-label="申請注意事項"
className="overflow-hidden rounded-card bg-surface shadow-card lg:col-span-2 xl:col-span-1"
>
<div className="p-5 md:p-7">
<h2 className="mb-5 flex items-center gap-2.5 text-xl font-bold">
<Icon name="lightbulb" className="size-6" />
申請注意事項
</h2>
<ol className="space-y-5">
{notes.map(([title, body], i) => (
<li key={title} className="flex gap-3">
<span
aria-hidden="true"
className="grid size-9 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-sm text-muted">{body}</span>
</span>
</li>
))}
</ol>
</div>
<Illustration name="notesBooks" className="hidden h-auto w-full xl:block" />
</section>
);
}
function SummaryRow({
label,
value,
@@ -571,8 +725,8 @@ function SummaryRow({
function ReadOnly({ label, value, id }: { label: string; value: string; id: string }) {
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={id} className="text-sm font-medium">
<div className="flex flex-col gap-2">
<label htmlFor={id} className="font-medium">
{label}
</label>
<input id={id} value={value} readOnly className={`${inputClass} bg-canvas text-muted`} />
@@ -7,6 +7,7 @@ import { MoneyDisplay } from "@/components/ui/money-display";
import { StatusBadge } from "@/components/ui/status-badge";
import { formatDate } from "@/lib/format";
import type { DuplicateCase } from "@/server/applications/duplicates";
import { buttonClass } from "@/components/ui/button";
export const DUPLICATE_WARNING_TEXT = "系統發現相同日期、平台與金額的申請,請確認是否重複送件。";
@@ -39,7 +40,7 @@ export function DuplicateDialog({
role="alertdialog"
className="fixed top-1/2 left-1/2 z-50 max-h-[calc(100vh-2rem)] w-[min(32rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-card bg-surface p-6 shadow-overlay"
>
<Dialog.Title className="text-lg font-semibold">疑似重複送件</Dialog.Title>
<Dialog.Title className="text-xl font-bold">疑似重複送件</Dialog.Title>
<Dialog.Description className="mt-2">{DUPLICATE_WARNING_TEXT}</Dialog.Description>
<ul className="mt-4 space-y-2" data-testid="duplicate-cases">
{(cases ?? []).map((c) => (
@@ -76,7 +77,7 @@ export function DuplicateDialog({
type="button"
disabled={pending}
onClick={close}
className="rounded-control border border-border-strong bg-surface px-4 py-2"
className={buttonClass("secondary")}
>
取消
</button>
@@ -87,7 +88,7 @@ export function DuplicateDialog({
setChecked(false);
onConfirm();
}}
className="rounded-control bg-primary px-4 py-2 font-medium text-on-primary disabled:opacity-60"
className={buttonClass("primary")}
>
{pending ? "處理中…" : "確認送出"}
</button>
+1 -1
View File
@@ -18,7 +18,7 @@ export function buildFormProps(
user: CurrentUser,
departmentName: string,
app: ApplicationDetail | null,
): ApplicationFormProps {
): Omit<ApplicationFormProps, "header" | "notice"> {
const db = getDb();
const timeZone = getEnv().TZ_APP;
const now = new Date();
+10 -7
View File
@@ -1,7 +1,7 @@
import { eq } from "drizzle-orm";
import Link from "next/link";
import { PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { ButtonLink } from "@/components/ui/button";
import { DEPARTMENT_REQUIRED_MESSAGE, requireRouteAccess } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import { departments } from "@/server/db/schema";
@@ -15,9 +15,9 @@ export default async function NewApplicationPage() {
<div className="space-y-6">
<PageHeader title="新增 AI 補助申請" />
<Alert tone="warning">{DEPARTMENT_REQUIRED_MESSAGE},指派部門後才能提出申請。</Alert>
<Link href="/dashboard" className="text-accent underline underline-offset-2">
<ButtonLink href="/dashboard" variant="secondary">
回首頁
</Link>
</ButtonLink>
</div>
);
}
@@ -27,9 +27,12 @@ export default async function NewApplicationPage() {
.where(eq(departments.id, user.departmentId))
.get();
return (
<div>
<PageHeader title="新增 AI 補助申請" description="請填寫以下資訊並上傳相關證明文件。" />
<ApplicationForm {...buildFormProps(user, department?.name ?? "", null)} />
</div>
<ApplicationForm
{...buildFormProps(user, department?.name ?? "", null)}
header={{
title: "新增 AI 補助申請",
description: "請填寫以下資訊並上傳相關證明文件,所有申請仍須經主管審核。",
}}
/>
);
}
+51 -27
View File
@@ -2,9 +2,11 @@ import Link from "next/link";
import type { ReactNode } from "react";
import { Card, PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { Button, ButtonLink, pillClass } from "@/components/ui/button";
import { DataTable } from "@/components/ui/data-table";
import { inputClass } from "@/components/ui/field";
import { MoneyDisplay } from "@/components/ui/money-display";
import { PlatformIcon } from "@/components/ui/platform-icon";
import { StatusBadge } from "@/components/ui/status-badge";
import { localDate } from "@/domain/calendar";
import {
@@ -79,13 +81,18 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
const summary = mySummary(db, user.id, today.slice(0, 7));
const canApply = user.departmentId !== null;
const newButton = 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"
>
<ButtonLink href="/applications/new" arrow>
新增申請
</Link>
</ButtonLink>
) : undefined;
const statusHref = (next: ApplicationStatus | undefined) => {
const query = new URLSearchParams();
if (month !== RECENT) query.set("month", month);
if (next) query.set("status", next);
if (platform) query.set("platform", platform);
const qs = query.toString();
return qs ? `/applications?${qs}` : "/applications";
};
return (
<div className="space-y-6">
@@ -96,18 +103,37 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
/>
{params.deleted && <Alert tone="success">已刪除草稿。</Alert>}
<ul className="grid grid-cols-2 gap-4 lg:grid-cols-4" aria-label="申請摘要">
<ul className="grid grid-cols-2 gap-4 lg:grid-cols-4 lg:gap-6" aria-label="申請摘要">
<SummaryCard label="本月案件" value={`${summary.thisMonth} 件`} />
<SummaryCard label="待補件" value={`${summary.needsRevision} 件`} />
<SummaryCard label="審核通過" value={`${summary.passed} 件`} />
<SummaryCard label="已發放總額" value={<MoneyDisplay amount={summary.paidTotal} />} />
</ul>
<Card>
<Card title="申請清單" icon="list">
<nav aria-label="依狀態篩選" className="relative -mx-1 mb-5 overflow-x-auto px-1">
<ul className="flex gap-2 pb-1">
{[undefined, ...FILTER_STATUSES].map((s) => {
const active = s === status;
return (
<li key={s ?? "all"} className="shrink-0">
<Link
href={statusHref(s)}
aria-current={active ? "true" : undefined}
className={pillClass(active)}
>
{s ? APPLICATION_STATUS_DISPLAY[s].label : "全部狀態"}
</Link>
</li>
);
})}
</ul>
</nav>
<form
method="get"
className="mb-5 grid gap-4 sm:grid-cols-2 lg:grid-cols-[repeat(3,minmax(0,12rem))_auto] lg:items-end"
className="mb-6 grid gap-4 rounded-control bg-canvas/70 p-4 sm:grid-cols-2 lg:grid-cols-[repeat(2,minmax(0,14rem))_auto] lg:items-end"
>
{status && <input type="hidden" name="status" value={status} />}
<Filter label="刷卡月份" name="month" value={month}>
<option value={RECENT}>最近 6 個月</option>
{months.map((m) => (
@@ -116,14 +142,6 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
</option>
))}
</Filter>
<Filter label="狀態" name="status" value={status ?? ""}>
<option value="">全部狀態</option>
{FILTER_STATUSES.map((s) => (
<option key={s} value={s}>
{APPLICATION_STATUS_DISPLAY[s].label}
</option>
))}
</Filter>
<Filter label="AI 平台" name="platform" value={platform ?? ""}>
<option value="">全部平台</option>
{platforms.map((p) => (
@@ -132,12 +150,9 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
</option>
))}
</Filter>
<button
type="submit"
className="rounded-control border border-border-strong bg-surface px-4 py-2 font-medium"
>
<Button type="submit" variant="secondary" className="lg:justify-self-start">
篩選
</button>
</Button>
</form>
<DataTable
@@ -157,7 +172,7 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
render: (r) => (
<Link
href={`/applications/${r.id}`}
className="text-accent underline underline-offset-2"
className="font-medium text-accent underline-offset-2 hover:underline"
>
{r.applicationNo ?? `#${r.id}`}
</Link>
@@ -168,7 +183,16 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
header: "刷卡日期",
render: (r) => (r.cardDate ? formatDate(r.cardDate) : "--"),
},
{ key: "platform", header: "平台", render: (r) => r.platform ?? "--" },
{
key: "platform",
header: "平台",
render: (r) => (
<span className="flex items-center gap-2">
<PlatformIcon platform={r.platform} size={26} />
{r.platform ?? "--"}
</span>
),
},
{
key: "twd",
header: "台幣金額",
@@ -208,9 +232,9 @@ export default async function MyApplicationsPage({ searchParams }: { searchParam
function SummaryCard({ label, value }: { label: string; value: React.ReactNode }) {
return (
<li className="rounded-card bg-surface p-4 shadow-card">
<p className="text-sm text-muted">{label}</p>
<p className="mt-1 text-xl font-semibold">{value}</p>
<li className="rounded-card bg-surface p-5 shadow-card md:p-6">
<p className="text-muted">{label}</p>
<p className="mt-2 text-2xl font-bold tracking-tight">{value}</p>
</li>
);
}
@@ -227,7 +251,7 @@ function Filter({
children: ReactNode;
}) {
return (
<label className="flex flex-col gap-1.5 text-sm font-medium">
<label className="flex flex-col gap-2 font-medium">
{label}
<select name={name} defaultValue={value} className={`${inputClass} font-normal`}>
{children}
+6 -5
View File
@@ -1,5 +1,6 @@
import Link from "next/link";
import { Card } from "@/components/page-header";
import { buttonClass } from "@/components/ui/button";
import { MoneyDisplay } from "@/components/ui/money-display";
import { formatMonth } from "@/lib/format";
import type { AdminDashboard } from "@/server/dashboard/queries";
@@ -15,8 +16,8 @@ function Stat({
}) {
return (
<div>
<dt className="text-sm text-muted">{label}</dt>
<dd className="mt-1 text-xl font-semibold" data-testid={testId}>
<dt className="text-muted">{label}</dt>
<dd className="mt-1 text-figure font-bold" data-testid={testId}>
{children}
</dd>
</div>
@@ -27,7 +28,7 @@ function Stat({
export function AdminSection({ data }: { data: AdminDashboard }) {
return (
<section aria-label="全公司月結" className="space-y-6" data-testid="admin-section">
<h2 className="text-xl font-semibold">全公司|{formatMonth(data.month)} 月結</h2>
<h2 className="text-2xl font-bold tracking-tight">全公司|{formatMonth(data.month)} 月結</h2>
<div className="grid gap-6 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Card title="月結進度">
<dl className="grid grid-cols-2 gap-4 md:grid-cols-3">
@@ -54,11 +55,11 @@ export function AdminSection({ data }: { data: AdminDashboard }) {
<p className="mt-4 flex flex-wrap gap-4">
<Link
href={`/admin/settlements?month=${data.month}`}
className="font-medium text-primary"
className={buttonClass("secondary", "sm")}
>
前往全公司月結
</Link>
<Link href="/admin/payments" className="font-medium text-primary">
<Link href="/admin/payments" className={buttonClass("secondary", "sm")}>
前往發放管理
</Link>
</p>
+193 -116
View File
@@ -1,23 +1,59 @@
import Link from "next/link";
import { Illustration } from "@/components/illustration";
import { Card } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { buttonClass, ButtonLink } from "@/components/ui/button";
import { DataTable } from "@/components/ui/data-table";
import { EmptyState } from "@/components/ui/empty-state";
import { MoneyDisplay } from "@/components/ui/money-display";
import { PlatformIcon } from "@/components/ui/platform-icon";
import { QuotaCard } from "@/components/ui/quota-card";
import { StatusBadge } from "@/components/ui/status-badge";
import { SubsidyAmount } from "@/components/ui/subsidy-amount";
import { formatDate, formatDateWithWeekday, formatMonth } from "@/lib/format";
import { platformDisplay } from "@/lib/platform-display";
import type { EmployeeDashboard, RecentApplication } from "@/server/dashboard/queries";
import { summarize } from "@/server/notifications/service";
const monthLabel = (month: string) => `${Number(month.slice(5, 7))} 月`;
function TimeRow({ label, value, testId }: { label: string; value: string; testId?: string }) {
type Dot = "warning" | "info" | "violet" | "neutral";
// 類別名稱必須完整寫出,Tailwind 才掃描得到。
const DOTS: Record<Dot, string> = {
warning: "bg-deco-yellow-strong",
info: "bg-accent",
violet: "bg-violet",
neutral: "bg-neutral",
};
/** 重要時程的一項:彩色圓點、標題與一行說明,日期靠右(風格稿「重要時程提醒」)。 */
function TimeItem({
dot,
label,
note,
value,
testId,
}: {
dot: Dot;
label: string;
note: string;
value: string;
testId?: string;
}) {
return (
<div className="flex justify-between gap-4 py-2">
<dt className="text-muted">{label}</dt>
<dd className="text-right font-medium" data-testid={testId}>
<div className="flex flex-wrap items-start gap-x-3 gap-y-1 rounded-control border border-border px-4 py-3">
<dt className="flex min-w-0 flex-1 basis-44 items-start gap-3">
<span aria-hidden="true" className={`mt-1.5 size-3 shrink-0 rounded-full ${DOTS[dot]}`} />
<span className="min-w-0">
<span className="block font-semibold">{label}</span>
<span className="block text-sm text-muted">{note}</span>
</span>
</dt>
<dd
className="ml-6 shrink-0 text-sm font-semibold sm:ml-0 sm:text-right"
data-testid={testId}
>
{value}
</dd>
</div>
@@ -27,6 +63,7 @@ function TimeRow({ label, value, testId }: { label: string; value: string; testI
/** 員工區塊:只有本人的案件(getEmployeeDashboard 已在查詢層過濾)。 */
export function EmployeeSection({ data, timeZone }: { data: EmployeeDashboard; timeZone: string }) {
const { current, previous } = data;
const payoutMonthLabel = monthLabel(current.payoutMonth);
return (
<section aria-label="我的申請" className="space-y-6" data-testid="employee-section">
{data.revisions.length > 0 && (
@@ -48,150 +85,190 @@ export function EmployeeSection({ data, timeZone }: { data: EmployeeDashboard; t
</div>
)}
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-4">
<Card title={`${monthLabel(current.month)}申請`}>
<dl className="space-y-2">
<div className="flex justify-between">
<dt className="text-muted">已送出</dt>
<dd className="font-semibold" data-testid="month-count">
{data.monthCount} 件
</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted">預估補助</dt>
<dd>
<MoneyDisplay amount={data.monthEstimate} kind="estimate" emphasis />
</dd>
</div>
</dl>
<p className="mt-3 text-sm text-muted">實際補助於月結後確認。</p>
</Card>
<div className="grid gap-6 lg:grid-cols-2 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1.2fr)]">
{data.quota ? (
<QuotaCard
title={`${data.departmentName ?? "部門"}${monthLabel(current.month)}補助使用情況`}
quota={data.quota}
link={{ href: "/help", label: "查看說明" }}
/>
) : null}
<Card title="重要時程">
<dl className="divide-y divide-border" data-testid="timeline-reminder">
<TimeRow
<Card title="支援的 AI 工具">
<ul
className="grid grid-cols-[repeat(auto-fill,minmax(10rem,1fr))] gap-3"
data-testid="platforms"
>
{data.platforms.map((p) => {
const display = platformDisplay(p);
return (
<li
key={p}
className="flex items-start gap-3 rounded-control border border-border px-3 py-3"
>
<PlatformIcon platform={p} size={34} />
<span className="min-w-0">
<span className="block font-semibold break-words">{p}</span>
{display.vendor && (
<span className="block text-sm text-muted">{display.vendor}</span>
)}
{display.uses && (
<span className="mt-1 block text-xs text-muted">{display.uses}</span>
)}
</span>
</li>
);
})}
</ul>
</Card>
<Card title="重要時程提醒" icon="calendar" className="lg:col-span-2 xl:col-span-1">
<dl data-testid="timeline-reminder" className="space-y-3">
<TimeItem
dot="warning"
label={`${monthLabel(current.month)}刷卡申請截止`}
note="請把握時間提出申請。"
value={formatDateWithWeekday(current.employeeDeadline, timeZone)}
testId="employee-deadline"
/>
<TimeRow
<TimeItem
dot="info"
label="部長提交截止"
note="部長完成月結後進入核定流程。"
value={formatDateWithWeekday(current.managerDeadline, timeZone)}
testId="manager-deadline"
/>
<TimeRow
<TimeItem
dot="violet"
label="薪資發放"
note={`核定後於 ${payoutMonthLabel}薪資發放。`}
value={formatMonth(current.payoutMonth)}
testId="payout-month"
/>
{previous.employeeOpen ? (
<TimeRow
<TimeItem
dot="neutral"
label={`${monthLabel(previous.month)}刷卡申請截止`}
note="上個月刷卡的申請仍可送出。"
value={formatDateWithWeekday(previous.employeeDeadline, timeZone)}
/>
) : !data.previousSettled ? (
<TimeRow
<TimeItem
dot="neutral"
label={`${monthLabel(previous.month)}部長提交截止`}
note="上個月的月結尚未完成。"
value={formatDateWithWeekday(previous.managerDeadline, timeZone)}
/>
) : null}
</dl>
</Card>
<Card title="支援的 AI 工具">
<ul className="flex flex-wrap gap-2" data-testid="platforms">
{data.platforms.map((p) => (
<li
key={p}
className="rounded-full border border-border bg-canvas px-3 py-1 text-sm font-medium"
>
{p}
</li>
))}
</ul>
</Card>
</div>
<Card title="最近申請">
{data.total === 0 ? (
<EmptyState
title="還沒有申請紀錄"
description="訂閱了工作用的 AI 工具嗎?送出申請後可在這裡追蹤進度。"
action={
<Link href="/applications/new" className="font-medium text-primary">
開始申請
</Link>
}
/>
) : (
<>
<DataTable<RecentApplication>
caption="最近申請"
rows={data.recent}
rowKey={(r) => r.id}
empty={{ title: "還沒有申請紀錄" }}
columns={[
{
key: "date",
header: "申請日期",
render: (r) => formatDate(r.date, timeZone),
},
{
key: "platform",
header: "平台/方案",
essential: true,
render: (r) => `${r.platform ?? "--"}${r.planName ? `/${r.planName}` : ""}`,
},
{
key: "paid",
header: "付款金額",
align: "right",
render: (r) => <MoneyDisplay amount={r.twdAmount} />,
},
{
key: "amount",
header: "補助金額",
align: "right",
essential: true,
render: (r) => (
<SubsidyAmount
status={r.status}
estimate={r.estimate}
finalAmount={r.finalAmount}
/>
),
},
{
key: "status",
header: "狀態",
essential: true,
render: (r) => <StatusBadge status={r.status} />,
},
{
key: "link",
header: "詳情",
render: (r) => (
<Link href={`/applications/${r.id}`} className="text-primary">
查看詳情
</Link>
),
},
]}
<div className="grid gap-6 xl:grid-cols-[minmax(0,1.75fr)_minmax(0,1fr)]">
<Card
title="最近的申請紀錄"
link={
data.total > 0
? { href: "/applications", label: `查看全部(${data.total} 筆)` }
: undefined
}
>
<p className="-mt-2 mb-4 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted">
<span>
{monthLabel(current.month)}已送出{" "}
<span className="font-semibold text-ink" data-testid="month-count">
{data.monthCount} 件
</span>
</span>
<span className="inline-flex items-center gap-1.5">
預估補助
<MoneyDisplay amount={data.monthEstimate} kind="estimate" emphasis />
</span>
<span>實際補助於月結後確認。</span>
</p>
{data.total === 0 ? (
<EmptyState
title="還沒有申請紀錄"
description="訂閱了工作用的 AI 工具嗎?送出申請後可在這裡追蹤進度。"
action={
<ButtonLink href="/applications/new" variant="secondary" size="sm" arrow>
開始申請
</ButtonLink>
}
/>
{data.total > data.recent.length && (
<p className="mt-4 text-right">
<Link href="/applications" className="font-medium text-primary">
查看全部({data.total} 筆)
</Link>
</p>
)}
</>
)}
</Card>
) : (
<>
<DataTable<RecentApplication>
caption="最近申請"
rows={data.recent}
rowKey={(r) => r.id}
empty={{ title: "還沒有申請紀錄" }}
columns={[
{
key: "date",
header: "申請日期",
render: (r) => formatDate(r.date, timeZone),
},
{
key: "platform",
header: "平台/方案",
essential: true,
render: (r) => (
<span className="flex items-center gap-3">
<PlatformIcon platform={r.platform} size={30} />
<span className="min-w-0 text-left">
<span className="block font-medium">{r.platform ?? "--"}</span>
{r.planName && (
<span className="block text-sm text-muted">{r.planName}</span>
)}
</span>
</span>
),
},
{
key: "paid",
header: "付款金額",
align: "right",
render: (r) => <MoneyDisplay amount={r.twdAmount} />,
},
{
key: "amount",
header: "補助金額",
align: "right",
essential: true,
render: (r) => (
<SubsidyAmount
status={r.status}
estimate={r.estimate}
finalAmount={r.finalAmount}
/>
),
},
{
key: "status",
header: "申請狀態",
essential: true,
render: (r) => <StatusBadge status={r.status} />,
},
{
key: "link",
header: "操作",
render: (r) => (
<Link href={`/applications/${r.id}`} className={buttonClass("ghost", "sm")}>
查看詳情
</Link>
),
},
]}
/>
</>
)}
</Card>
<div
data-testid="good-ideas"
className="relative hidden aspect-[469/278] self-start overflow-hidden rounded-card shadow-card md:block"
>
<Illustration name="goodIdeas" className="absolute inset-0 h-full w-full object-cover" />
</div>
</div>
</section>
);
}
+9 -8
View File
@@ -1,5 +1,6 @@
import Link from "next/link";
import { Card } from "@/components/page-header";
import { buttonClass } from "@/components/ui/button";
import { MoneyDisplay } from "@/components/ui/money-display";
import { QuotaCard } from "@/components/ui/quota-card";
import { formatDate, formatDateWithWeekday } from "@/lib/format";
@@ -26,19 +27,19 @@ export function ManagerSection({ data, timeZone }: { data: ManagerDashboard; tim
className="space-y-6"
data-testid={`manager-section-${data.departmentId}`}
>
<h2 className="text-xl font-semibold">{data.departmentName}|主管待辦</h2>
<h2 className="text-2xl font-bold tracking-tight">{data.departmentName}|主管待辦</h2>
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
<Card title="待處理">
<dl className="grid grid-cols-2 gap-4">
<div>
<dt className="text-sm text-muted">待審核</dt>
<dd className="text-2xl font-semibold" data-testid="pending-review">
<dt className="text-muted">待審核</dt>
<dd className="text-figure font-bold" data-testid="pending-review">
{data.pendingReview}
</dd>
</div>
<div>
<dt className="text-sm text-muted">待補件</dt>
<dd className="text-2xl font-semibold" data-testid="needs-revision">
<dt className="text-muted">待補件</dt>
<dd className="text-figure font-bold" data-testid="needs-revision">
{data.needsRevision}
</dd>
</div>
@@ -47,12 +48,12 @@ export function ManagerSection({ data, timeZone }: { data: ManagerDashboard; tim
{settlementText(data, timeZone)}
</p>
<p className="mt-4 flex flex-wrap gap-4">
<Link href="/department/review" className="font-medium text-primary">
<Link href="/department/review" className={buttonClass("secondary", "sm")}>
前往部門審核
</Link>
<Link
href={`/department/settlement?department=${data.departmentId}&month=${data.settlementMonth}`}
className="font-medium text-primary"
className={buttonClass("secondary", "sm")}
>
前往部門月結
</Link>
@@ -73,7 +74,7 @@ export function ManagerSection({ data, timeZone }: { data: ManagerDashboard; tim
href={`/department/review?id=${p.id}`}
className="flex flex-wrap items-baseline justify-between gap-2"
>
<span className="font-medium text-primary">
<span className="font-medium text-accent">
{p.applicantName}|{p.platform ?? "--"}
</span>
<span className="text-sm text-muted">
+11 -7
View File
@@ -1,6 +1,6 @@
import Link from "next/link";
import { PageHeader } from "@/components/page-header";
import { Alert } from "@/components/ui/alert";
import { ButtonLink } from "@/components/ui/button";
import { DEPARTMENT_REQUIRED_MESSAGE, requireRouteAccess } from "@/server/auth/current-user";
import {
getAdminDashboard,
@@ -29,16 +29,20 @@ export default async function DashboardPage() {
return (
<div className="space-y-8">
<PageHeader
size="hero"
illustration="heroHome"
title={`您好,${user.name ?? user.employeeNo}`}
description="善用 AI 工具,提升工作效率,創造更多可能。補助於每月月結後依部門額度統一確認。"
description={
<>
善用 AI 工具,提升工作效率,創造更多可能。
<span className="mt-1 block text-base">補助於每月月結後依部門額度統一確認。</span>
</>
}
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"
>
<ButtonLink href="/applications/new" size="lg" arrow>
開始申請
</Link>
</ButtonLink>
) : undefined
}
/>
+2 -5
View File
@@ -12,6 +12,7 @@ import { requireRouteAccess } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import { ReviewDetail, loadReviewable } from "./review-detail";
import { ReviewQueue } from "./review-queue";
import { pillClass } from "@/components/ui/button";
const EMPTY_TEXT: Record<ReviewFilter, string> = {
pending: "目前沒有待審核的申請。",
@@ -47,11 +48,7 @@ export default async function DepartmentReviewPage({
key={key}
href={`/department/review?status=${key}`}
aria-current={key === filter ? "page" : undefined}
className={`rounded-control border px-4 py-2 font-medium ${
key === filter
? "border-primary bg-primary text-on-primary"
: "border-border-strong bg-surface"
}`}
className={pillClass(key === filter)}
>
{REVIEW_FILTERS[key].label}({counts[key]})
</Link>
@@ -9,11 +9,10 @@ import { useToast } from "@/components/ui/toast";
import type { ReviewAction } from "@/lib/application-lifecycle";
import type { ApplicationStatus } from "@/lib/application-status";
import { reviewAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
const primary =
"inline-flex items-center justify-center rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover disabled:opacity-60";
const secondary =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-5 py-2.5 font-medium disabled:opacity-60";
const primary = buttonClass("primary");
const secondary = buttonClass("secondary");
const DONE_MESSAGE: Record<ReviewAction, string> = {
approve: "已核准",
@@ -9,6 +9,8 @@ import { StatusBadge, ToneBadge } from "@/components/ui/status-badge";
import type { ApplicationStatus } from "@/lib/application-status";
import { formatMonth } from "@/lib/format";
import { batchApproveAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
import { PlatformIcon } from "@/components/ui/platform-icon";
export interface QueueItem {
id: number;
@@ -85,7 +87,7 @@ export function ReviewQueue({
type="button"
disabled={chosen.length === 0 || pending}
onClick={approveSelected}
className="rounded-control border border-border-strong bg-surface px-4 py-2 font-medium disabled:opacity-50"
className={buttonClass("secondary")}
>
{pending ? "處理中…" : "批次核准"}
</button>
@@ -97,6 +99,7 @@ export function ReviewQueue({
const body = (
<>
<span className="flex flex-wrap items-center gap-2">
<PlatformIcon platform={item.platform} size={24} />
<span className="font-medium">{label}</span>
<StatusBadge status={item.status} />
{item.selfReview && <ToneBadge tone="info">主管自行審核</ToneBadge>}
@@ -8,6 +8,7 @@ import { StatusBadge } from "@/components/ui/status-badge";
import { useToast } from "@/components/ui/toast";
import type { ApplicationStatus } from "@/lib/application-status";
import { expireRejectAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
export const DEFAULT_EXPIRE_REASON = "逾期未完成補件";
@@ -67,7 +68,7 @@ function BlockingItem({ item, canExpire }: { item: Item; canExpire: boolean }) {
<button
type="button"
onClick={() => setOpen(true)}
className="rounded-control border border-border-strong px-3 py-1 text-sm text-danger"
className={buttonClass("danger-outline", "sm")}
>
逾期不核准
</button>
@@ -91,7 +92,7 @@ function BlockingItem({ item, canExpire }: { item: Item; canExpire: boolean }) {
type="button"
disabled={pending}
onClick={() => setOpen(false)}
className="rounded-control border border-border-strong px-4 py-2"
className={buttonClass("secondary")}
>
取消
</button>
@@ -99,7 +100,7 @@ function BlockingItem({ item, canExpire }: { item: Item; canExpire: boolean }) {
type="button"
disabled={pending}
onClick={confirm}
className="rounded-control bg-danger px-4 py-2 font-medium text-on-primary disabled:opacity-60"
className={buttonClass("danger")}
>
確定不核准
</button>
@@ -21,7 +21,7 @@ export function MonthSwitch({
const deptId = useId();
const go = (dept: number, m: string) =>
router.push(`/department/settlement?department=${dept}&month=${m}`);
const select = "rounded-control border border-border-strong bg-surface px-3 py-2";
const select = "rounded-control border border-border-strong bg-surface px-4 py-2.5";
return (
<div className="flex flex-wrap items-end gap-4">
+3 -3
View File
@@ -31,7 +31,7 @@ function Stat({ label, children }: { label: string; children: React.ReactNode })
return (
<div>
<dt className="text-sm text-muted">{label}</dt>
<dd className="mt-1 text-lg font-semibold">{children}</dd>
<dd className="mt-1 text-2xl font-bold tracking-tight">{children}</dd>
</div>
);
}
@@ -143,10 +143,10 @@ export default async function DepartmentSettlementPage({
<section
aria-label="部門額度"
data-testid="quota-card"
className="rounded-card bg-surface p-5 shadow-card md:p-6"
className="rounded-card bg-surface p-5 shadow-card md:p-7"
>
<div className="mb-4 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold">
<h2 className="text-xl font-bold">
{v.departmentName}|{formatMonth(month)} 部門額度
</h2>
{v.isLate && <ToneBadge tone="warning">逾期提交</ToneBadge>}
@@ -7,11 +7,10 @@ import { Alert } from "@/components/ui/alert";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { useToast } from "@/components/ui/toast";
import { recalculateAction, submitSettlementAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
const primary =
"inline-flex items-center justify-center rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary hover:bg-primary-hover disabled:opacity-60";
const secondary =
"inline-flex items-center justify-center rounded-control border border-border-strong bg-surface px-5 py-2.5 font-medium disabled:opacity-60";
const primary = buttonClass("primary");
const secondary = buttonClass("secondary");
export const SUBMIT_CONFIRM_TEXT = "提交後本月份名單將鎖定,如需更正須由管理者退回。確定提交?";
@@ -6,6 +6,7 @@ import { listActiveAttachments } from "@/server/attachments/service";
import { getDb } from "@/server/db/client";
import { requireEffectiveRuleVersion } from "@/server/rules/params";
import { createDemoDraftAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
/** FileUploader/FilePreview 示範:綁定登入者自己的一筆草稿。 */
export function AttachmentsDemo({ userId, demoApp }: { userId: number; demoApp?: string }) {
@@ -36,10 +37,7 @@ export function AttachmentsDemo({ userId, demoApp }: { userId: number; demoApp?:
<p className="text-muted">
附件一定綁定一筆申請。建立一筆示範草稿後即可試用上傳、預覽、替換與刪除。
</p>
<button
type="submit"
className="rounded-control border border-border-strong bg-surface px-4 py-2"
>
<button type="submit" className={buttonClass("secondary")}>
建立示範草稿
</button>
</form>
+42 -14
View File
@@ -1,5 +1,9 @@
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/page-header";
import { Card, PageHeader } from "@/components/page-header";
import { Button } from "@/components/ui/button";
import { MoneyDisplay } from "@/components/ui/money-display";
import { PlatformIcon } from "@/components/ui/platform-icon";
import { ToneBadge } from "@/components/ui/status-badge";
import { AttachmentsDemo } from "./attachments-demo";
import { SampleForm } from "./sample-form";
import { requireRouteAccess } from "@/server/auth/current-user";
@@ -26,8 +30,12 @@ const COLORS = [
["violet-soft", ""],
["neutral", "中性"],
["neutral-soft", ""],
["deco-blue", "側欄裝飾"],
["deco-yellow", "側欄裝飾"],
] as const;
const PLATFORMS = ["ChatGPT", "Claude", "Gemini", "其他", "Perplexity"];
/** 設計 tokens 展示頁:開發時對照風格稿用,只在開發登入模式開放。 */
export default async function DesignTokensPage({
searchParams,
@@ -40,8 +48,7 @@ export default async function DesignTokensPage({
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>
<Card title="色彩">
<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">
@@ -54,21 +61,42 @@ export default async function DesignTokensPage({
</li>
))}
</ul>
</section>
<section className="rounded-card bg-surface p-6 shadow-card">
<h2 className="mb-4 text-lg font-semibold">字級與按鈕</h2>
</Card>
<Card title="字級與按鈕" icon="clipboard" link={{ href: "/help", label: "查看說明" }}>
<p className="text-hero font-extrabold tracking-tight">您好,王小明</p>
<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">
<p className="mt-4">
<MoneyDisplay amount={450} size="figure" emphasis />
</p>
<div className="mt-4 flex flex-wrap gap-3">
<Button arrow>主要操作</Button>
<Button variant="secondary" icon="save">
次要操作
</button>
</Button>
<Button variant="ghost">文字按鈕</Button>
<Button variant="danger">不可逆操作</Button>
<Button variant="danger-outline" size="sm">
刪除
</Button>
</div>
</section>
<div className="mt-4 flex flex-wrap gap-2">
<ToneBadge tone="warning">待審核</ToneBadge>
<ToneBadge tone="success">已通過</ToneBadge>
<ToneBadge tone="info">已核定</ToneBadge>
<ToneBadge tone="violet">已發放</ToneBadge>
</div>
</Card>
<Card title="AI 平台圖示">
<ul className="flex flex-wrap gap-6">
{PLATFORMS.map((p) => (
<li key={p} className="flex items-center gap-2">
<PlatformIcon platform={p} />
{p}
</li>
))}
</ul>
</Card>
<SampleForm />
{user.departmentId !== null && <AttachmentsDemo userId={user.id} demoApp={demoApp} />}
</div>
+3 -8
View File
@@ -8,6 +8,7 @@ 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";
import { buttonClass } from "@/components/ui/button";
const REQUIRED = [
{ field: "sample-plan", message: "請填寫訂閱方案" },
@@ -99,10 +100,7 @@ export function SampleForm() {
<StickyActions>
<ConfirmDialog
trigger={
<button
type="button"
className="rounded-control border border-border-strong bg-surface px-5 py-2.5"
>
<button type="button" className={buttonClass("secondary")}>
不核准(範例)
</button>
}
@@ -112,10 +110,7 @@ export function SampleForm() {
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 type="submit" className={buttonClass("primary")}>
送出
</button>
</StickyActions>
@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { useToast } from "@/components/ui/toast";
import { markAllReadAction } from "./actions";
import { buttonClass } from "@/components/ui/button";
export function MarkAllReadButton() {
const router = useRouter();
@@ -21,7 +22,7 @@ export function MarkAllReadButton() {
router.refresh();
})
}
className="rounded-control bg-primary px-5 py-2.5 font-medium text-on-primary disabled:opacity-60"
className={buttonClass("primary")}
>
全部標為已讀
</button>
+9 -7
View File
@@ -1,12 +1,14 @@
import Link from "next/link";
import { AuthShell } from "@/components/auth-shell";
import { ButtonLink } from "@/components/ui/button";
// requireRole/requireRouteAccess 呼叫 forbidden() 時顯示(HTTP 403)。暫時樣式,由 add-app-shell 統一。
// requireRole/requireRouteAccess 呼叫 forbidden() 時顯示(HTTP 403)。
export default function Forbidden() {
return (
<main>
<h1>無權限</h1>
<p>您沒有權限存取這個頁面。如需權限,請洽系統管理員。</p>
<Link href="/dashboard">回首頁</Link>
</main>
<AuthShell title="無權限">
<p className="text-muted">您沒有權限存取這個頁面。如需權限,請洽系統管理員。</p>
<ButtonLink href="/dashboard" arrow className="self-start">
回首頁
</ButtonLink>
</AuthShell>
);
}
+37 -11
View File
@@ -7,9 +7,9 @@
*/
@theme {
/* 色彩 */
--color-canvas: #f6f7f9; /* 頁面底色(淺灰分區) */
--color-canvas: #f7f8fa; /* 頁面底色(淺灰分區) */
--color-surface: #ffffff; /* 卡片、側欄、頂部列 */
--color-border: #e5e7eb;
--color-border: #e8eaef;
--color-border-strong: #d1d5db;
--color-ink: #1d2330; /* 主要文字 */
--color-muted: #6b7280; /* 次要文字、說明 */
@@ -30,28 +30,41 @@
--color-violet-soft: #efe9fd;
--color-neutral: #4b5563;
--color-neutral-soft: #eef0f3;
--color-hero-from: #fff6df; /* 頁首暖色漸層(取代風格稿的插圖) */
--color-hero-from: #fff6df; /* 頁首暖色漸層(插圖左側淡入的底色) */
--color-hero-to: #f6f7f9;
--color-deco-blue: #dbe8fb; /* 側欄底部波浪、Logo */
--color-deco-blue-strong: #8fb4f2;
--color-deco-yellow: #fdeec4;
--color-deco-yellow-strong: #f9d77e;
/* AI 平台圖示(只用在 PlatformIcon) */
--color-brand-chatgpt: #10a37f;
--color-brand-claude: #d97757;
--color-brand-gemini-from: #4796e3;
--color-brand-gemini-to: #9177c7;
/* 字型:系統中文字型,不從外部下載(CI 無法連外部字型服務) */
--font-sans:
system-ui, -apple-system, "PingFang TC", "Microsoft JhengHei", "Noto Sans TC", sans-serif;
/* 字級 */
/* 字級:頁首大標題(首頁問候、新增申請)、一般頁面標題、金額等數字強調 */
--text-hero: 3.25rem;
--text-hero--line-height: 1.15;
--text-display: 2.25rem;
--text-display--line-height: 1.2;
--text-figure: 2rem;
--text-figure--line-height: 1.15;
/* 圓角 */
--radius-control: 0.625rem; /* 輸入框、按鈕 */
--radius-card: 1rem; /* 卡片 */
--radius-control: 0.75rem; /* 輸入框、按鈕 */
--radius-card: 1.25rem; /* 卡片 */
/* 陰影 */
--shadow-card: 0 1px 2px rgb(16 24 40 / 0.04), 0 2px 8px rgb(16 24 40 / 0.05);
--shadow-card: 0 1px 2px rgb(16 24 40 / 0.03), 0 8px 24px rgb(16 24 40 / 0.06);
--shadow-overlay: 0 12px 32px rgb(16 24 40 / 0.18);
/* 版面 */
--spacing-sidebar: 15rem;
--spacing-topbar: 3.75rem;
--spacing-topbar: 4.5rem;
}
@layer base {
@@ -74,7 +87,7 @@
border: 1px solid var(--color-border-strong);
border-radius: var(--radius-control);
background: var(--color-surface);
padding: 0.45rem 0.75rem;
padding: 0.6rem 0.875rem;
}
button {
cursor: pointer;
@@ -87,15 +100,28 @@
th,
td {
border-bottom: 1px solid var(--color-border);
padding: 0.6rem 0.75rem;
padding: 0.75rem;
text-align: left;
vertical-align: top;
vertical-align: middle;
}
/* 表頭為淺灰圓角列(風格稿「最近的申請紀錄」) */
th {
color: var(--color-muted);
font-weight: 500;
font-size: 0.875rem;
}
thead th {
background: var(--color-canvas);
border-bottom: 0;
}
thead th:first-child {
border-top-left-radius: var(--radius-control);
border-bottom-left-radius: var(--radius-control);
}
thead th:last-child {
border-top-right-radius: var(--radius-control);
border-bottom-right-radius: var(--radius-control);
}
h2 {
font-size: 1.125rem;
font-weight: 600;
+16 -10
View File
@@ -1,5 +1,9 @@
import { asc } from "drizzle-orm";
import { notFound } from "next/navigation";
import { AuthShell } from "@/components/auth-shell";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Field, inputClass } from "@/components/ui/field";
import { isDevLoginEnabled } from "@/server/auth/dev-login";
import { getDb } from "@/server/db/client";
import { users } from "@/server/db/schema";
@@ -13,7 +17,7 @@ const ERROR_MESSAGES: Record<string, string> = {
inactive: "帳號已停用,請洽人資。",
};
// 暫時樣式:全站框架與設計 tokens 由 add-app-shell 建立。
/** 開發登入(只在 AUTH_MODE=dev 開放):以員工編號直接登入。 */
export default async function DevLoginPage({
searchParams,
}: {
@@ -28,14 +32,14 @@ export default async function DevLoginPage({
.all();
return (
<main>
<h1>開發登入</h1>
<p>只在非正式環境提供:以員工編號直接登入,不經公司帳號驗證。</p>
{error && <p role="alert">{ERROR_MESSAGES[error] ?? "登入失敗。"}</p>}
<form action={devLoginAction}>
<AuthShell title="開發登入">
<p className="text-muted">只在非正式環境提供:以員工編號直接登入,不經公司帳號驗證。</p>
{error && <Alert tone="danger">{ERROR_MESSAGES[error] ?? "登入失敗。"}</Alert>}
<form action={devLoginAction} className="space-y-4">
<input type="hidden" name="returnTo" value={returnTo ?? ""} />
<label htmlFor="employeeNo">員工編號</label>
<input id="employeeNo" name="employeeNo" list="known-employees" required />
<Field id="employeeNo" label="員工編號" required>
<input name="employeeNo" list="known-employees" required className={inputClass} />
</Field>
<datalist id="known-employees">
{existing.map((u) => (
<option key={u.employeeNo} value={u.employeeNo}>
@@ -44,8 +48,10 @@ export default async function DevLoginPage({
</option>
))}
</datalist>
<button type="submit">登入</button>
<Button type="submit" size="lg" arrow className="w-full">
登入
</Button>
</form>
</main>
</AuthShell>
);
}
+20 -13
View File
@@ -1,4 +1,6 @@
import Link from "next/link";
import { AuthShell } from "@/components/auth-shell";
import { Alert } from "@/components/ui/alert";
import { buttonClass, ButtonLink } from "@/components/ui/button";
import { getEnv, oidcConfigured } from "@/server/env";
export const dynamic = "force-dynamic";
@@ -10,7 +12,7 @@ const ERROR_MESSAGES: Record<string, string> = {
not_configured: "公司登入尚未設定,目前無法登入,請洽系統管理員。",
};
// 暫時樣式:全站框架與設計 tokens 由 add-app-shell 建立。
/** 登入頁:只提供公司帳號登入(開發模式改為員工編號登入)。 */
export default async function LoginPage({
searchParams,
}: {
@@ -25,24 +27,29 @@ export default async function LoginPage({
: "/api/auth/login";
return (
<main>
<h1>AI 補助申請系統</h1>
{error && <p role="alert">{ERROR_MESSAGES[error] ?? ERROR_MESSAGES.failed}</p>}
<AuthShell title="AI 補助申請系統">
<p className="text-lg text-muted">善用 AI 工具,提升工作效率,創造更多可能。</p>
{error && <Alert tone="danger">{ERROR_MESSAGES[error] ?? ERROR_MESSAGES.failed}</Alert>}
{devMode ? (
<p>
目前為開發登入模式。
<Link
<div className="space-y-3">
<p className="text-muted">目前為開發登入模式。</p>
<ButtonLink
href={returnTo ? `/login/dev?returnTo=${encodeURIComponent(returnTo)}` : "/login/dev"}
size="lg"
arrow
className="w-full"
>
以員工編號登入
</Link>
</p>
</ButtonLink>
</div>
) : loginAvailable ? (
// 一般連結即可:/api/auth/login 會 303 導向 Authentik。
<a href={loginHref}>以公司帳號登入</a>
<a href={loginHref} className={buttonClass("primary", "lg", "w-full")}>
以公司帳號登入
</a>
) : (
!error && <p role="alert">{ERROR_MESSAGES.not_configured}</p>
!error && <Alert tone="danger">{ERROR_MESSAGES.not_configured}</Alert>
)}
</main>
</AuthShell>
);
}
+48
View File
@@ -0,0 +1,48 @@
import type { ReactNode } from "react";
import { BrandLogo } from "@/components/brand-logo";
import { Illustration } from "@/components/illustration";
/**
* 未登入頁面(登入、開發登入)的外框:與內頁相同的色彩與卡片風格,
* 桌機左側為「Good Ideas」插圖,右側為登入卡片;手機只有卡片。
*/
export function AuthShell({ title, children }: { title: string; children: ReactNode }) {
return (
<main className="relative grid min-h-dvh place-items-center overflow-hidden bg-gradient-to-br from-hero-from via-canvas to-canvas px-4 py-10">
<svg
aria-hidden="true"
focusable="false"
viewBox="0 0 400 300"
preserveAspectRatio="none"
className="absolute right-0 bottom-0 h-72 w-2/3 max-w-xl"
>
<path
d="M400 40C320 20 260 120 200 170S60 250 0 300h400z"
className="fill-deco-yellow opacity-60"
/>
<path
d="M400 120c-80 0-140 60-200 110S80 290 40 300h360z"
className="fill-deco-blue opacity-70"
/>
</svg>
<div className="relative grid w-full max-w-4xl overflow-hidden rounded-card bg-surface shadow-overlay lg:grid-cols-[1.1fr_1fr]">
<div className="relative hidden lg:block">
<Illustration
name="goodIdeas"
priority
className="absolute inset-0 h-full w-full object-cover object-left"
/>
</div>
<div className="flex flex-col gap-6 p-8 md:p-10">
<div>
<BrandLogo size={52} />
<p className="mt-3 text-sm text-muted">AI Subsidy Application System</p>
<h1 className="mt-1 text-3xl font-extrabold tracking-tight">{title}</h1>
</div>
{children}
<p className="mt-auto text-xs text-muted">© 2026 AI 補助申請系統</p>
</div>
</div>
</main>
);
}
+20
View File
@@ -0,0 +1,20 @@
/** 系統 Logo:淺藍與淺黃兩個重疊的雲朵圓形(依風格稿重畫)。裝飾用,名稱由旁邊的文字提供。 */
export function BrandLogo({ size = 44 }: { size?: number }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 48 48"
aria-hidden="true"
focusable="false"
className="shrink-0"
>
<circle cx="31" cy="15" r="11" className="fill-deco-yellow-strong opacity-80" />
<path
d="M14 42a10 10 0 0 1-1.6-19.9A12 12 0 0 1 35.5 24 9 9 0 0 1 34 42z"
className="fill-deco-blue-strong opacity-90"
/>
<path d="M13 42a8 8 0 0 1-.4-16A10 10 0 0 1 22 18v24z" className="fill-accent opacity-55" />
</svg>
);
}
+17 -1
View File
@@ -17,7 +17,14 @@ type IconName =
| "inbox"
| "calendar"
| "upload"
| "file";
| "file"
| "arrow-right"
| "calculator"
| "lightbulb"
| "clipboard"
| "save"
| "more"
| "send";
const PATHS: Record<IconName, string> = {
home: "M3 10.5 12 3l9 7.5M5 9.5V21h5v-6h4v6h5V9.5",
@@ -49,6 +56,15 @@ const PATHS: Record<IconName, string> = {
calendar: "M3 5h18v16H3zM16 3v4M8 3v4M3 10h18",
upload: "M12 16V4M7 9l5-5 5 5M4 16v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3",
file: "M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9zM14 3v6h6",
"arrow-right": "M5 12h14M13 6l6 6-6 6",
calculator:
"M7 3h10a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 7h7M8.5 11h.01M12 11h.01M15.5 11h.01M8.5 14.5h.01M12 14.5h.01M15.5 14.5h.01M8.5 18h7",
lightbulb:
"M9 18h6M10 21h4M12 3a6 6 0 0 0-3.9 10.6c.6.6.9 1.4.9 2.4h6c0-1 .3-1.8.9-2.4A6 6 0 0 0 12 3z",
clipboard: "M9 3h6v3H9zM8 4.5H6v16.5h12V4.5h-2M9 11h6M9 15h4",
save: "M5 3h11l3 3v15H5zM8 3v5h7V3M8 21v-7h8v7",
more: "M5 12h.01M12 12h.01M19 12h.01",
send: "M22 2 11 13M22 2l-7 20-4-9-9-4z",
};
export function Icon({ name, ...props }: { name: IconName } & SVGProps<SVGSVGElement>) {
+39
View File
@@ -0,0 +1,39 @@
import Image from "next/image";
/**
* 裝飾插圖(自風格稿裁切,放在 public/images/)。純裝飾:alt 為空、對輔助技術隱藏,
* 預設在手機寬度隱藏。換成高解析素材時直接取代同名檔案即可。
*/
export const ILLUSTRATIONS = {
heroHome: { src: "/images/hero-home.webp", width: 572, height: 258 },
heroApplication: { src: "/images/hero-application.webp", width: 376, height: 180 },
goodIdeas: { src: "/images/good-ideas.webp", width: 469, height: 278 },
notesBooks: { src: "/images/notes-books.webp", width: 332, height: 219 },
} as const;
export type IllustrationName = keyof typeof ILLUSTRATIONS;
export function Illustration({
name,
className = "",
priority = false,
}: {
name: IllustrationName;
className?: string;
priority?: boolean;
}) {
const { src, width, height } = ILLUSTRATIONS[name];
return (
<Image
src={src}
width={width}
height={height}
alt=""
aria-hidden="true"
unoptimized
priority={priority}
data-illustration={name}
className={`pointer-events-none select-none ${className}`}
/>
);
}
+101 -13
View File
@@ -1,35 +1,98 @@
import type { ReactNode } from "react";
import Link from "next/link";
import type { ComponentProps, ReactNode } from "react";
import { Icon } from "@/components/icons";
import { Illustration, type IllustrationName } from "@/components/illustration";
type IconName = ComponentProps<typeof Icon>["name"];
/**
* 內容標題列(介面規劃 §2.1):頁面名稱+簡短說明+主要操作。
* 主要操作在手機寬度改為畫面底部固定操作列,長表單捲動時仍看得到(app-shell spec)。
*
* - `size="hero"`:首頁與新增申請的大標題(風格稿),主要操作放在說明下方。
* - `illustration`:右側裝飾插圖,左緣以漸層淡入底色;手機寬度隱藏,不遮蓋文字與按鈕。
* - `aside`:標題列右側的輔助內容(例如完成進度),在插圖之前。
*/
export function PageHeader({
title,
description,
actions,
size = "default",
illustration,
aside,
}: {
title: string;
description?: ReactNode;
actions?: ReactNode;
size?: "default" | "hero";
illustration?: IllustrationName;
aside?: ReactNode;
}) {
const hero = size === "hero";
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>}
<header
data-size={size}
className={`relative mb-6 overflow-hidden rounded-card bg-gradient-to-br from-hero-from via-hero-from/60 to-hero-to ${
hero ? "px-5 py-7 md:px-10 md:py-10" : "px-5 py-6 md:px-8 md:py-7"
}`}
>
{illustration && (
<div
aria-hidden="true"
className="absolute inset-y-0 right-0 hidden w-[45%] max-w-[36rem] mask-l-from-60% mask-l-to-100% lg:block"
>
<Illustration
name={illustration}
priority
className="h-full w-full object-cover object-right"
/>
</div>
)}
<div
className={`relative flex flex-col gap-5 ${
hero
? "xl:flex-row xl:items-center xl:justify-between xl:gap-8"
: "md:flex-row md:items-end md:justify-between md:gap-6"
} ${illustration ? "lg:pr-[38%] xl:pr-[30%]" : ""}`}
>
<div className="min-w-0">
<h1
className={`font-extrabold tracking-tight ${
hero ? "text-3xl md:text-hero" : "text-2xl md:text-display"
}`}
>
{title}
</h1>
{description && (
<p className={`mt-3 text-muted ${hero ? "text-lg md:text-xl" : "md:text-lg"}`}>
{description}
</p>
)}
{hero && actions && (
<div className="mt-6">
<StickyActions>{actions}</StickyActions>
</div>
)}
</div>
{aside && <div className="relative shrink-0">{aside}</div>}
{!hero && actions && <StickyActions>{actions}</StickyActions>}
</div>
{actions && <StickyActions>{actions}</StickyActions>}
</header>
);
}
/** 主要操作區:桌機與平板在原位,手機固定在畫面底部。 */
export function StickyActions({ children }: { children: ReactNode }) {
export function StickyActions({
children,
className = "",
}: {
children: ReactNode;
className?: string;
}) {
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"
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 ${className}`}
>
{children}
</div>
@@ -39,8 +102,8 @@ export function StickyActions({ children }: { children: ReactNode }) {
/** 主內容+右側輔助區(規則摘要、截止日、試算…)。桌機並排,較窄時輔助區移到下方。 */
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>
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_21rem]">
<div className="min-w-0 space-y-6">{children}</div>
<aside aria-label="輔助資訊" className="space-y-6">
{aside}
</aside>
@@ -48,19 +111,44 @@ export function WithAside({ children, aside }: { children: ReactNode; aside: Rea
);
}
/** 白色圓角卡片。 */
/**
* 白色圓角卡片。`icon` 放在標題前(風格稿的「申請資料」「補助試算」),
* `link` 為標題列右側的次要連結(「查看詳情 →」「查看全部 →」)。
*/
export function Card({
title,
icon,
link,
children,
className = "",
}: {
title?: string;
icon?: IconName;
link?: { href: string; label: 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>}
<section className={`min-w-0 rounded-card bg-surface p-5 shadow-card md:p-7 ${className}`}>
{(title || link) && (
<div className="mb-5 flex items-center justify-between gap-4">
{title && (
<h2 className="flex items-center gap-2.5 text-xl font-bold">
{icon && <Icon name={icon} className="size-6 text-ink" />}
{title}
</h2>
)}
{link && (
<Link
href={link.href}
className="inline-flex shrink-0 items-center gap-1 text-sm text-muted hover:text-ink"
>
{link.label}
<Icon name="arrow-right" className="size-4" />
</Link>
)}
</div>
)}
{children}
</section>
);
+57 -29
View File
@@ -5,6 +5,7 @@ import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { BrandLogo } from "@/components/brand-logo";
import { Icon } from "@/components/icons";
import { Toaster } from "@/components/ui/toast";
import { activeNavHref, type NavItem } from "@/lib/navigation";
@@ -46,7 +47,7 @@ export function AppFrame({
<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 ${
className={`sticky top-0 hidden h-dvh shrink-0 flex-col overflow-hidden border-r border-border bg-surface md:flex ${
collapsed ? "w-[4.5rem]" : "w-sidebar"
}`}
>
@@ -59,7 +60,7 @@ export function AppFrame({
<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"
className="fixed inset-y-0 left-0 z-50 flex w-[17rem] max-w-[85vw] flex-col overflow-hidden bg-surface shadow-overlay md:hidden"
>
<Dialog.Title className="sr-only">主要導覽</Dialog.Title>
<Dialog.Close
@@ -79,7 +80,7 @@ export function AppFrame({
</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">
<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-8">
<button
type="button"
className="rounded-control p-2 text-muted hover:bg-canvas md:hidden"
@@ -98,7 +99,7 @@ export function AppFrame({
<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">
<span className="sr-only lg:not-sr-only lg:text-sm lg:whitespace-nowrap lg:text-muted xl:sr-only">
AI 補助申請系統
</span>
@@ -116,7 +117,7 @@ export function AppFrame({
</div>
</header>
<main id="main" className="flex-1 px-4 pt-5 pb-28 md:px-8 md:pt-6 md:pb-10">
<main id="main" className="flex-1 px-4 pt-5 pb-28 md:px-6 md:pt-6 md:pb-10 xl:px-8">
<Toaster>{children}</Toaster>
</main>
</div>
@@ -139,25 +140,21 @@ function SidebarContent({
return (
<>
<div
className={`flex items-center gap-3 px-5 pt-6 pb-5 ${collapsed ? "justify-center px-0" : ""}`}
data-testid="sidebar-brand"
className={`px-5 pt-7 pb-6 ${collapsed ? "flex 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>
<BrandLogo size={collapsed ? 36 : 48} />
{!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>
<p className="mt-2 leading-tight">
<span className="block text-xl font-bold tracking-tight">AI 補助申請系統</span>
<span className="mt-1 block text-xs text-muted">AI Subsidy Application System</span>
</p>
)}
</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" : ""}>
<ul key={index} className={index > 0 ? "mx-2 mt-5 border-t border-border pt-5" : ""}>
{items.map((item) => {
const current = item.href === active;
return (
@@ -167,15 +164,15 @@ function SidebarContent({
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] ${
className={`mb-1.5 flex items-center gap-3.5 rounded-control px-4 py-3 text-[1.05rem] ${
collapsed ? "justify-center" : ""
} ${
current
? "bg-accent-soft font-semibold text-ink"
: "text-ink/80 hover:bg-canvas hover:text-ink"
? "bg-accent-soft font-bold text-ink"
: "text-ink/85 hover:bg-canvas hover:text-ink"
}`}
>
<Icon name={item.icon} className={current ? "text-accent" : "text-muted"} />
<Icon name={item.icon} className="size-[1.375rem] text-ink" />
<span className={collapsed ? "sr-only" : ""}>{item.label}</span>
</Link>
</li>
@@ -186,16 +183,47 @@ function SidebarContent({
)}
</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
data-testid="sidebar-footer"
className="relative mt-auto px-5 pt-16 pb-6 text-xs text-muted"
>
<SidebarWave />
<div className="relative">
<p>Good People</p>
<p>Make a Brighter Tomorrow.</p>
<span aria-hidden="true" className="mt-3 block h-px w-6 bg-muted/50" />
<p className="mt-6">© 2026 AI 補助申請系統</p>
<p>All rights reserved.</p>
</div>
</div>
)}
</>
);
}
/** 側欄底部的淺藍、淺黃波浪(風格稿裝飾,依色塊重畫)。 */
function SidebarWave() {
return (
<svg
aria-hidden="true"
focusable="false"
viewBox="0 0 240 260"
preserveAspectRatio="none"
className="absolute inset-x-0 bottom-0 h-[17rem] w-full"
>
<path
d="M0 70C55 20 120 40 150 90s60 80 90 70V260H0z"
className="fill-deco-yellow opacity-70"
/>
<path
d="M0 30C40 10 80 60 110 120s70 100 130 110V260H0z"
className="fill-deco-blue opacity-80"
/>
<path d="M0 160c60-30 130 10 240 40V260H0z" className="fill-surface opacity-70" />
</svg>
);
}
const menuContent = "z-50 min-w-56 rounded-card border border-border bg-surface p-2 shadow-overlay";
export interface NotificationSummary {
@@ -300,15 +328,15 @@ function UserMenu({ user, today }: { user: FrameUser; today: string }) {
>
<span
aria-hidden="true"
className="grid size-9 place-items-center rounded-full bg-accent-soft font-semibold text-accent"
className="grid size-11 place-items-center rounded-full bg-gradient-to-br from-deco-blue to-deco-yellow text-lg font-bold text-ink"
>
{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">
<span className="hidden text-left leading-tight whitespace-nowrap sm:block">
<span className="block font-semibold" data-testid="user-name">
{user.name}
</span>
<span className="block text-xs text-muted" data-testid="user-department">
<span className="block text-sm text-muted" data-testid="user-department">
{user.department}
</span>
</span>
+1 -1
View File
@@ -28,7 +28,7 @@ export function Alert({
return (
<div
role={tone === "danger" ? "alert" : "status"}
className={`flex gap-3 rounded-control border px-4 py-3 text-ink ${t.box}`}
className={`flex gap-3 rounded-card border px-5 py-4 text-ink ${t.box}`}
>
<Icon name={t.icon} className={`mt-0.5 shrink-0 ${t.iconClass}`} />
<div>
+59
View File
@@ -0,0 +1,59 @@
// @vitest-environment jsdom
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Button, ButtonLink, buttonClass } from "./button";
import { PlatformIcon } from "./platform-icon";
afterEach(cleanup);
describe("Button", () => {
it("預設為 type=button 的主要按鈕,可加箭頭與前置圖示", () => {
const onClick = vi.fn();
render(
<Button icon="save" arrow onClick={onClick}>
儲存草稿
</Button>,
);
const button = screen.getByRole("button", { name: "儲存草稿" });
expect(button.getAttribute("type")).toBe("button");
expect(button.className).toContain("bg-primary");
expect(button.querySelectorAll("svg")).toHaveLength(2);
button.click();
expect(onClick).toHaveBeenCalledOnce();
});
it("各樣式輸出完整的 token 類別", () => {
expect(buttonClass("secondary")).toContain("border-border-strong");
expect(buttonClass("danger", "sm")).toContain("bg-danger");
expect(buttonClass("danger", "sm")).toContain("text-sm");
expect(buttonClass("ghost", "md", "w-full")).toMatch(/w-full$/);
});
it("ButtonLink 是帶按鈕樣式的連結", () => {
render(
<ButtonLink href="/applications/new" size="lg" arrow>
開始申請
</ButtonLink>,
);
const link = screen.getByRole("link", { name: "開始申請" });
expect(link.getAttribute("href")).toBe("/applications/new");
expect(link.className).toContain("text-lg");
});
});
describe("PlatformIcon", () => {
it("依平台名稱選圖示,且對輔助技術隱藏", () => {
const { container } = render(
<>
<PlatformIcon platform="Claude" />
<PlatformIcon platform="Perplexity" />
</>,
);
const icons = container.querySelectorAll("[data-platform-icon]");
expect([...icons].map((i) => i.getAttribute("data-platform-icon"))).toEqual([
"claude",
"other",
]);
for (const icon of icons) expect(icon.getAttribute("aria-hidden")).toBe("true");
});
});
+107
View File
@@ -0,0 +1,107 @@
import Link from "next/link";
import type { ButtonHTMLAttributes, ComponentProps, ReactNode } from "react";
import { Icon } from "@/components/icons";
/**
* 按鈕樣式(風格稿:深藍黑主要按鈕、白底細框次要按鈕,大圓角)。
* 一個畫面只有一個 primary;不可逆操作用 danger 並搭配 ConfirmDialog。
* 需要把樣式交給其他元件(例如對話框的觸發按鈕)時用 `buttonClass`。
*/
export type ButtonVariant = "primary" | "secondary" | "ghost" | "danger" | "danger-outline";
export type ButtonSize = "sm" | "md" | "lg";
const BASE =
"inline-flex items-center justify-center gap-2 rounded-control font-medium whitespace-nowrap transition-colors disabled:cursor-not-allowed disabled:opacity-60 aria-disabled:pointer-events-none aria-disabled:opacity-60";
const VARIANTS: Record<ButtonVariant, string> = {
primary: "bg-primary text-on-primary shadow-card hover:bg-primary-hover",
secondary: "border border-border-strong bg-surface text-ink hover:bg-canvas",
ghost: "text-accent hover:bg-accent-soft",
danger: "bg-danger text-on-primary hover:bg-danger/90",
"danger-outline": "border border-border-strong bg-surface text-danger hover:bg-danger-soft",
};
const SIZES: Record<ButtonSize, string> = {
sm: "px-3 py-1.5 text-sm",
md: "px-5 py-2.5",
lg: "px-7 py-3.5 text-lg",
};
export function buttonClass(
variant: ButtonVariant = "primary",
size: ButtonSize = "md",
className = "",
): string {
return `${BASE} ${VARIANTS[variant]} ${SIZES[size]} ${className}`.trim();
}
type IconName = ComponentProps<typeof Icon>["name"];
interface StyleProps {
variant?: ButtonVariant;
size?: ButtonSize;
/** 文字前的圖示(例如儲存草稿的磁片)。 */
icon?: IconName;
/** 文字後加「→」箭頭(風格稿的「開始申請 →」「下一步 →」)。 */
arrow?: boolean;
}
function Content({
icon,
arrow,
children,
}: Pick<StyleProps, "icon" | "arrow"> & { children: ReactNode }) {
return (
<>
{icon && <Icon name={icon} />}
{children}
{arrow && <Icon name="arrow-right" />}
</>
);
}
export function Button({
variant,
size,
icon,
arrow,
className,
children,
type = "button",
...props
}: StyleProps & ButtonHTMLAttributes<HTMLButtonElement>) {
return (
<button type={type} className={buttonClass(variant, size, className)} {...props}>
<Content icon={icon} arrow={arrow}>
{children}
</Content>
</button>
);
}
export function ButtonLink({
variant,
size,
icon,
arrow,
className,
children,
...props
}: StyleProps & ComponentProps<typeof Link>) {
return (
<Link className={buttonClass(variant, size, className)} {...props}>
<Content icon={icon} arrow={arrow}>
{children}
</Content>
</Link>
);
}
/** 篩選切換的膠囊(狀態、月份等篩選列);選中者為深色。搭配 aria-current 標示目前的篩選。 */
export function pillClass(active: boolean): string {
return `inline-flex items-center rounded-full border px-4 py-1.5 text-sm font-medium whitespace-nowrap transition-colors ${
active
? "border-primary bg-primary text-on-primary"
: "border-border-strong bg-surface text-ink hover:bg-canvas"
}`;
}
+5 -10
View File
@@ -2,6 +2,7 @@
import * as Dialog from "@radix-ui/react-dialog";
import { useState, type ReactNode } from "react";
import { buttonClass } from "./button";
/**
* 重要或不可逆操作的確認視窗(不核准、提交月結、最終核定、標記已發放…)。
@@ -45,17 +46,13 @@ export function ConfirmDialog({
<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"
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-7 shadow-overlay"
>
<Dialog.Title className="text-lg font-semibold">{title}</Dialog.Title>
<Dialog.Title className="text-xl font-bold">{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"
>
<button type="button" disabled={pending} className={buttonClass("secondary")}>
{cancelLabel}
</button>
</Dialog.Close>
@@ -63,9 +60,7 @@ export function ConfirmDialog({
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"
}`}
className={buttonClass(destructive ? "danger" : "primary")}
>
{pending ? "處理中…" : confirmLabel}
</button>
+8 -5
View File
@@ -37,16 +37,16 @@ export function DataTable<T>({
return (
<>
<div className={`overflow-x-auto ${tableClass}`} data-testid="table-mode">
<div className={`relative 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">
<tr className="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" : ""}`}
className={`px-4 py-3 font-medium ${c.align === "right" ? "text-right" : ""}`}
>
{c.header}
</th>
@@ -59,7 +59,7 @@ export function DataTable<T>({
{columns.map((c) => (
<td
key={c.key}
className={`px-3 py-3 align-top ${c.align === "right" ? "text-right" : ""}`}
className={`px-4 py-4 align-middle ${c.align === "right" ? "text-right" : ""}`}
>
{c.render(row)}
</td>
@@ -71,7 +71,10 @@ export function DataTable<T>({
</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">
<li
key={rowKey(row)}
className="rounded-card border border-border bg-surface p-4 shadow-card"
>
<dl className="space-y-1.5">
{cardColumns.map((c) => (
<div key={c.key} className="flex justify-between gap-4">
+4 -2
View File
@@ -14,9 +14,11 @@ export function EmptyState({
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"
className="flex flex-col items-center gap-2 rounded-card border border-dashed border-border-strong bg-canvas/60 px-6 py-10 text-center"
>
<Icon name="inbox" width={32} height={32} className="text-muted" />
<span className="mb-1 grid size-14 place-items-center rounded-full bg-accent-soft text-accent">
<Icon name="inbox" width={28} height={28} />
</span>
<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>}
+3 -3
View File
@@ -31,8 +31,8 @@ export function Field({
})
: children;
return (
<div className="flex flex-col gap-1.5" data-field={id}>
<label htmlFor={id} className="text-sm font-medium">
<div className="flex flex-col gap-2" data-field={id}>
<label htmlFor={id} className="font-medium">
{label}
{required && (
<span className="ml-0.5 text-danger" aria-hidden="true">
@@ -58,4 +58,4 @@ export function Field({
/** 輸入框的共用樣式。 */
export const inputClass =
"w-full rounded-control border border-border-strong bg-surface px-3 py-2 text-ink placeholder:text-muted/70";
"w-full rounded-control border border-border-strong bg-surface px-4 py-2.5 text-ink placeholder:text-muted/70 focus:border-accent";
+2 -1
View File
@@ -2,6 +2,7 @@
import * as Dialog from "@radix-ui/react-dialog";
import { Icon } from "@/components/icons";
import { buttonClass } from "./button";
export interface PreviewableFile {
id: number;
@@ -35,7 +36,7 @@ export function FilePreview({
<Dialog.Trigger asChild>
<button
type="button"
className="rounded-control border border-border-strong bg-surface px-3 py-1.5 text-sm hover:bg-canvas"
className={buttonClass("secondary", "sm")}
aria-label={`${triggerLabel}${label}`}
>
{triggerLabel}
+33 -14
View File
@@ -14,6 +14,7 @@ import {
type AttachmentFormat,
type AttachmentKind,
} from "@/lib/attachments";
import { buttonClass } from "./button";
import { ConfirmDialog } from "./confirm-dialog";
import { FilePreview } from "./file-preview";
import { useToast } from "./toast";
@@ -156,8 +157,8 @@ export function FileUploader({
const errorId = `${fieldId}-error`;
return (
<div className="flex flex-col gap-1.5" data-field={fieldId} data-testid={`uploader-${kind}`}>
<p className="text-sm font-medium">
<div className="flex flex-col gap-2" data-field={fieldId} data-testid={`uploader-${kind}`}>
<p className="font-medium">
{label}
{editable && (
<>
@@ -171,14 +172,14 @@ export function FileUploader({
{file && !uploading ? (
<div
className={`flex flex-wrap items-center gap-3 rounded-control border px-4 py-3 ${
shownError ? "border-danger" : "border-border-strong"
className={`flex flex-wrap items-center gap-3 rounded-control border bg-surface px-4 py-3 ${
shownError ? "border-danger" : "border-border"
}`}
>
<Icon name="file" className="shrink-0 text-accent" />
<FileTypeMark mimeType={file.mimeType} />
<p className="min-w-0 flex-1" data-testid={`uploaded-${kind}`}>
<span className="font-medium break-all">{file.originalName}</span>{" "}
<span className="text-sm text-muted">{formatFileSize(file.sizeBytes)}</span>
<span className="block font-medium break-all">{file.originalName}</span>{" "}
<span className="block text-sm text-muted">{formatFileSize(file.sizeBytes)}</span>
</p>
<div className="flex shrink-0 gap-2">
<FilePreview file={file} label={label} />
@@ -187,7 +188,7 @@ export function FileUploader({
<button
type="button"
onClick={() => inputRef.current?.click()}
className="rounded-control border border-border-strong bg-surface px-3 py-1.5 text-sm hover:bg-canvas"
className={buttonClass("secondary", "sm")}
aria-label={`替換${label}`}
>
替換
@@ -196,7 +197,7 @@ export function FileUploader({
trigger={
<button
type="button"
className="rounded-control border border-border-strong bg-surface px-3 py-1.5 text-sm text-danger hover:bg-canvas"
className={buttonClass("danger-outline", "sm")}
aria-label={`刪除${label}`}
>
刪除
@@ -222,15 +223,15 @@ export function FileUploader({
onDragLeave={() => setDragging(false)}
onDrop={onDrop}
data-testid={`dropzone-${kind}`}
className={`flex cursor-pointer flex-col items-center gap-1 rounded-control border-2 border-dashed px-4 py-6 text-center transition-colors ${
className={`flex cursor-pointer flex-col items-center gap-1.5 rounded-control border-2 border-dashed px-4 py-6 text-center transition-colors ${
dragging
? "border-accent bg-accent-soft"
: shownError
? "border-danger bg-danger-soft/40"
: "border-border-strong hover:border-accent"
: "border-border-strong bg-canvas/60 hover:border-accent hover:bg-accent-soft/40"
}`}
>
<Icon name="upload" className="text-accent" />
<Icon name="upload" className="size-6 text-ink" />
{uploading ? (
<span role="status" className="w-full max-w-xs">
<span className="block text-sm">
@@ -250,7 +251,9 @@ export function FileUploader({
)}
</label>
) : (
<p className="rounded-control border border-border px-4 py-3 text-sm text-muted">未上傳</p>
<p className="rounded-control border border-dashed border-border-strong bg-canvas/60 px-4 py-3 text-sm text-muted">
未上傳
</p>
)}
{editable && (
@@ -287,7 +290,7 @@ export function FileUploader({
<button
type="button"
onClick={() => state.retry && void upload(state.retry)}
className="rounded-control border border-danger/40 px-3 py-1 text-danger"
className={buttonClass("danger-outline", "sm")}
>
重試
</button>
@@ -297,3 +300,19 @@ export function FileUploader({
</div>
);
}
/** 檔案類型標記:PDF 為紅色、圖片為藍色(風格稿的檔案列)。 */
function FileTypeMark({ mimeType }: { mimeType: string }) {
const pdf = mimeType === "application/pdf";
return (
<span
aria-hidden="true"
className={`relative grid h-10 w-9 shrink-0 place-items-end justify-center rounded-md pb-1 text-[0.625rem] font-bold text-on-primary ${
pdf ? "bg-danger" : "bg-info"
}`}
>
<Icon name="file" className="absolute top-1 size-4 opacity-70" />
{pdf ? "PDF" : "IMG"}
</span>
);
}
+10 -1
View File
@@ -8,16 +8,25 @@ export function MoneyDisplay({
amount,
kind,
emphasis = false,
size = "md",
className = "",
}: {
amount: number | null | undefined;
kind?: "estimate" | "final";
emphasis?: boolean;
/** figure:卡片中的大字數字(風格稿的額度與試算金額)。 */
size?: "md" | "figure";
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>
<span
className={`${emphasis ? "font-semibold text-success" : ""} ${
size === "figure" ? "text-figure font-bold tracking-tight" : ""
}`}
>
{formatMoney(amount)}
</span>
{kind && (
<span className="rounded-full bg-neutral-soft px-1.5 text-xs font-medium text-neutral">
{kind === "estimate" ? "預估" : "最終"}
+3 -3
View File
@@ -41,8 +41,8 @@ export function MonthPicker({
}) {
const id = useId();
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={id} className="text-sm font-medium">
<div className="flex flex-col gap-2">
<label htmlFor={id} className="font-medium">
{label}
</label>
<select
@@ -51,7 +51,7 @@ export function MonthPicker({
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"
className="rounded-control border border-border-strong bg-surface px-4 py-2.5"
>
{monthsBetween(min, max).map((month) => (
<option key={month} value={month}>
+99
View File
@@ -0,0 +1,99 @@
import { useId } from "react";
import { platformDisplay, type PlatformIconKind } from "@/lib/platform-display";
/**
* AI 平台圖示(簡化圖形,只用來輔助辨識)。一律搭配文字名稱,圖示本身 aria-hidden。
* 已知平台:ChatGPT、Claude、Gemini;其他平台(含「其他」與後台新增的平台)為「…」通用圖示。
*/
export function PlatformIcon({
platform,
size = 36,
className = "",
}: {
platform: string | null | undefined;
size?: number;
className?: string;
}) {
const kind = platformDisplay(platform).icon;
return (
<span
aria-hidden="true"
data-platform-icon={kind}
className={`inline-grid shrink-0 place-items-center ${FRAME[kind]} ${className}`}
style={{ width: size, height: size }}
>
<Glyph kind={kind} size={Math.round(size * 0.68)} />
</span>
);
}
const FRAME: Record<PlatformIconKind, string> = {
chatgpt: "rounded-[28%] bg-brand-chatgpt text-on-primary",
claude: "text-brand-claude",
gemini: "",
other: "rounded-[28%] bg-accent-soft text-accent",
};
function Glyph({ kind, size }: { kind: PlatformIconKind; size: number }) {
const gradientId = useId();
const common = { width: size, height: size, viewBox: "0 0 24 24", focusable: false } as const;
switch (kind) {
case "chatgpt":
// 三個交錯的圓角環,近似 OpenAI 的結形標誌
return (
<svg {...common} fill="none" stroke="currentColor" strokeWidth="1.7">
{[0, 60, 120].map((deg) => (
<rect
key={deg}
x="7.5"
y="3.5"
width="9"
height="17"
rx="4.5"
transform={`rotate(${deg} 12 12)`}
/>
))}
</svg>
);
case "claude":
// 放射狀的星芒
return (
<svg {...common} fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
{Array.from({ length: 12 }, (_, i) => i * 30).map((deg, i) => (
<line
key={deg}
x1="12"
y1={i % 2 === 0 ? 2.5 : 4.5}
x2="12"
y2="10"
transform={`rotate(${deg} 12 12)`}
/>
))}
</svg>
);
case "gemini":
// 四角星,藍紫漸層
return (
<svg {...common}>
<defs>
<linearGradient id={gradientId} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" className="[stop-color:var(--color-brand-gemini-from)]" />
<stop offset="1" className="[stop-color:var(--color-brand-gemini-to)]" />
</linearGradient>
</defs>
<path
d="M12 1.5C12.6 7 17 11.4 22.5 12 17 12.6 12.6 17 12 22.5 11.4 17 7 12.6 1.5 12 7 11.4 11.4 7 12 1.5Z"
fill={`url(#${gradientId})`}
/>
</svg>
);
default:
return (
<svg {...common} fill="currentColor">
<circle cx="6" cy="12" r="1.9" />
<circle cx="12" cy="12" r="1.9" />
<circle cx="18" cy="12" r="1.9" />
</svg>
);
}
}
+67 -37
View File
@@ -1,3 +1,5 @@
import Link from "next/link";
import { Icon } from "@/components/icons";
import type { QuotaReference } from "@/domain/dashboard";
import { MoneyDisplay } from "./money-display";
@@ -5,57 +7,85 @@ export const QUOTA_REFERENCE_NOTE =
"實際補助於當月結算後依全體通過案件與部門額度統一確認,可能因其他申請而變動。";
/**
* 部門額度卡(reference 變體,dashboard spec):「目前已通過可補助總額/部門月上限」+「參考」標籤與說明。
* 標籤與說明固定綁在元件上,不可移除,避免讓額度看起來先到先得;超過上限時進度條封頂並提示比例分配,
* 不顯示負數剩餘額度。
* 部門額度卡(reference 變體,dashboard spec):大字並列「已通過可補助總額」與「部門本月額度」,
* 下方進度條與「已使用 N%」,並固定附上「參考」標籤與說明,避免讓額度看起來先到先得。
* 超過上限時進度條封頂並提示比例分配;不顯示「剩餘可用額度」,也不顯示負數。
*/
export function QuotaCard({ title, quota }: { title: string; quota: QuotaReference }) {
export function QuotaCard({
title,
quota,
link,
}: {
title: string;
quota: QuotaReference;
/** 標題列右側的「查看詳情 →」。 */
link?: { href: string; label: string };
}) {
return (
<section
aria-label={title}
data-testid="quota-card"
className="rounded-card bg-surface p-5 shadow-card md:p-6"
className="min-w-0 rounded-card bg-surface p-5 shadow-card md:p-7"
>
<div className="flex items-center gap-2">
<h2 className="text-lg font-semibold">{title}</h2>
<span className="rounded-full bg-info-soft px-2 py-0.5 text-xs font-medium text-info">
參考
</span>
<div className="flex items-start justify-between gap-3">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-xl font-bold">{title}</h2>
<span className="rounded-full bg-info-soft px-2.5 py-0.5 text-xs font-medium text-info">
參考
</span>
</div>
{link && (
<Link
href={link.href}
className="inline-flex shrink-0 items-center gap-1 text-sm text-muted hover:text-ink"
>
{link.label}
<Icon name="arrow-right" className="size-4" />
</Link>
)}
</div>
{quota.configured ? (
<>
<p className="mt-3 text-lg">
<MoneyDisplay amount={quota.approvedTotal} />
<span className="mx-1 text-muted">/</span>
<MoneyDisplay amount={quota.cap} />
<span className="ml-1 text-sm text-muted">(參考)</span>
</p>
<div
role="progressbar"
aria-label="已通過可補助總額占部門月上限"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.min(100, quota.percent)}
className="mt-3 h-2 overflow-hidden rounded-full bg-canvas"
>
<dl className="mt-5 grid grid-cols-2 divide-x divide-border">
<div className="pr-4">
<dt className="text-muted">已通過可補助總額</dt>
<dd className="mt-1">
<MoneyDisplay amount={quota.approvedTotal} size="figure" />
</dd>
</div>
<div className="pl-4">
<dt className="text-muted">部門本月額度</dt>
<dd className="mt-1">
<MoneyDisplay amount={quota.cap} size="figure" />
</dd>
</div>
</dl>
<div className="mt-6 flex items-center gap-4">
<div
className={`h-full rounded-full ${quota.overCap ? "bg-warning" : "bg-accent"}`}
style={{ width: `${Math.min(100, quota.percent)}%` }}
/>
role="progressbar"
aria-label="已通過可補助總額占部門月上限"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.min(100, quota.percent)}
className="h-3 flex-1 overflow-hidden rounded-full bg-canvas"
>
<div
className={`h-full rounded-full ${quota.overCap ? "bg-warning" : "bg-accent"}`}
style={{ width: `${Math.min(100, quota.percent)}%` }}
/>
</div>
<p className="shrink-0 font-medium">已使用 {quota.percent}%</p>
</div>
<p className="mt-2 text-sm">
已使用 {quota.percent}%
{quota.overCap && (
<span className="ml-2 text-warning">
已超過月上限,月結時將依每人可補助金額占比分配。
</span>
)}
</p>
{quota.overCap && (
<p className="mt-2 text-sm text-warning">
已超過月上限,月結時將依每人可補助金額占比分配。
</p>
)}
</>
) : (
<p className="mt-3 text-muted">本月額度尚未設定</p>
<p className="mt-5 text-muted">本月額度尚未設定</p>
)}
<p className="mt-3 text-sm text-muted">{QUOTA_REFERENCE_NOTE}</p>
<p className="mt-4 text-sm text-muted">{QUOTA_REFERENCE_NOTE}</p>
</section>
);
}
+5 -10
View File
@@ -2,6 +2,7 @@
import * as Dialog from "@radix-ui/react-dialog";
import { useId, useState, type ReactNode } from "react";
import { buttonClass } from "./button";
import { Field, inputClass } from "./field";
/**
@@ -81,9 +82,9 @@ export function ReasonDialog({
<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 max-h-[calc(100vh-2rem)] w-[min(32rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-card bg-surface p-6 shadow-overlay"
className="fixed top-1/2 left-1/2 z-50 max-h-[calc(100vh-2rem)] w-[min(32rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-card bg-surface p-7 shadow-overlay"
>
<Dialog.Title className="text-lg font-semibold">{title}</Dialog.Title>
<Dialog.Title className="text-xl font-bold">{title}</Dialog.Title>
<Dialog.Description className="mt-2 text-muted">{description}</Dialog.Description>
<div className="mt-4 space-y-4">
{children}
@@ -107,11 +108,7 @@ export function ReasonDialog({
</div>
<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"
>
<button type="button" disabled={pending} className={buttonClass("secondary")}>
取消
</button>
</Dialog.Close>
@@ -119,9 +116,7 @@ export function ReasonDialog({
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"
}`}
className={buttonClass(destructive ? "danger" : "primary")}
>
{pending ? "處理中…" : confirmLabel}
</button>
+1 -1
View File
@@ -24,7 +24,7 @@ export function ToneBadge({ tone, children }: { tone: StatusTone; children: stri
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]}`}
className={`inline-flex items-center rounded-full px-3 py-1 text-sm font-medium whitespace-nowrap ${TONE_CLASSES[tone]}`}
>
{children}
</span>
+1 -1
View File
@@ -37,7 +37,7 @@ export function Toaster({ children }: { children: ReactNode }) {
<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]}`}
className={`pointer-events-auto rounded-card px-5 py-3.5 text-sm font-medium text-on-primary shadow-overlay ${TONE_CLASSES[m.tone]}`}
>
{m.text}
</p>
+31
View File
@@ -3,6 +3,7 @@ import {
EMPTY_FORM_VALUES,
fromCents,
sectionProgress,
stepProgress,
toCents,
validateApplication,
type ApplicationFormValues,
@@ -204,3 +205,33 @@ describe("金額與進度輔助", () => {
expect(sectionProgress(valid, ["invoice", "card_statement"])).toEqual({ done: 6, total: 6 });
});
});
describe("stepProgress", () => {
const states = (...args: Parameters<typeof stepProgress>) =>
stepProgress(...args).map((s) => `${s.label}:${s.state}`);
it("空白表單:申請資料進行中,其餘未開始", () => {
expect(states(EMPTY_FORM_VALUES, [])).toEqual([
"申請資料:current",
"上傳證明文件:todo",
"確認送出:todo",
]);
});
it("申請資料已填、尚未上傳:上傳證明文件進行中", () => {
expect(states({ ...valid, declared: false }, [])).toEqual([
"申請資料:done",
"上傳證明文件:current",
"確認送出:todo",
]);
});
it("全部完成;只缺一類附件時上傳仍進行中", () => {
expect(states(valid, ["invoice", "card_statement"])).toEqual([
"申請資料:done",
"上傳證明文件:done",
"確認送出:done",
]);
expect(states(valid, ["invoice"])[1]).toBe("上傳證明文件:current");
});
});
+39 -12
View File
@@ -305,21 +305,48 @@ export function formValuesFrom(form: FormData): ApplicationFormValues {
};
}
/** 完成進度:六個區塊中已完成幾個(介面以「完成進度」取代風格稿的步驟條)。 */
/** 六個區塊是否已填(只看必填欄位有沒有值,格式由送出驗證負責)。 */
function sectionsFilled(values: ApplicationFormValues, attachments: readonly AttachmentKind[]) {
const filled = (s: string) => s.trim() !== "";
return {
applicant: true, // 申請人資訊(自動帶入)
subscription:
filled(values.platform) &&
filled(values.planName) &&
(values.platform !== OTHER_PLATFORM || filled(values.platformOther)),
amount: filled(values.twdAmount) && filled(values.cardDate),
purpose: filled(values.purpose) && filled(values.outcome),
attachments: ATTACHMENT_KINDS.every((k) => attachments.includes(k)),
declared: values.declared,
};
}
/** 完成進度:六個區塊中已完成幾個。 */
export function sectionProgress(
values: ApplicationFormValues,
attachments: readonly AttachmentKind[],
): { done: number; total: number } {
const filled = (s: string) => s.trim() !== "";
const sections = [
true, // 申請人資訊(自動帶入)
filled(values.platform) &&
filled(values.planName) &&
(values.platform !== OTHER_PLATFORM || filled(values.platformOther)),
filled(values.twdAmount) && filled(values.cardDate),
filled(values.purpose) && filled(values.outcome),
ATTACHMENT_KINDS.every((k) => attachments.includes(k)),
values.declared,
];
const sections = Object.values(sectionsFilled(values, attachments));
return { done: sections.filter(Boolean).length, total: sections.length };
}
export const FORM_STEPS = ["申請資料", "上傳證明文件", "確認送出"] as const;
export type StepState = "done" | "current" | "todo";
/**
* 頁首的三段完成進度(取代風格稿的步驟條;單頁表單,不是 Wizard):
* 申請資料(訂閱、金額日期、用途)→ 上傳證明文件(兩類附件)→ 確認送出(勾選聲明)。
* 第一個未完成的段落為「進行中」。
*/
export function stepProgress(
values: ApplicationFormValues,
attachments: readonly AttachmentKind[],
): { label: (typeof FORM_STEPS)[number]; state: StepState }[] {
const s = sectionsFilled(values, attachments);
const done = [s.subscription && s.amount && s.purpose, s.attachments, s.declared];
const current = done.indexOf(false);
return FORM_STEPS.map((label, i) => ({
label,
state: done[i] ? "done" : i === current ? "current" : "todo",
}));
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { platformDisplay } from "./platform-display";
describe("platformDisplay", () => {
it("已知平台不分大小寫對應專屬圖示與廠商", () => {
expect(platformDisplay("ChatGPT")).toMatchObject({ icon: "chatgpt", vendor: "OpenAI" });
expect(platformDisplay("chatgpt plus")).toMatchObject({ icon: "chatgpt" });
expect(platformDisplay("CLAUDE")).toMatchObject({ icon: "claude", vendor: "Anthropic" });
expect(platformDisplay(" Gemini ")).toMatchObject({ icon: "gemini", vendor: "Google" });
});
it("「其他」用通用圖示並有副標", () => {
expect(platformDisplay("其他")).toEqual({
icon: "other",
vendor: "More Platforms",
uses: "更多優質工具持續支援",
});
});
it("後台新增或未知的平台用通用圖示、不顯示廠商", () => {
expect(platformDisplay("Perplexity")).toEqual({ icon: "other", vendor: null, uses: null });
expect(platformDisplay("")).toEqual({ icon: "other", vendor: null, uses: null });
expect(platformDisplay(null)).toEqual({ icon: "other", vendor: null, uses: null });
});
});
+42
View File
@@ -0,0 +1,42 @@
import { OTHER_PLATFORM } from "./rule-params";
/**
* AI 平台的顯示資訊(圖示、廠商、用途短語)。只用在畫面上:平台仍以名稱字串儲存,
* 後台新增的平台沒有專屬圖示,一律用通用圖示、不顯示廠商。
*/
export type PlatformIconKind = "chatgpt" | "claude" | "gemini" | "other";
export interface PlatformDisplay {
icon: PlatformIconKind;
/** 廠商或英文副標,未知平台為 null。 */
vendor: string | null;
/** 首頁「支援的 AI 工具」的用途短語,未知平台為 null。 */
uses: string | null;
}
const KNOWN: { match: RegExp; display: PlatformDisplay }[] = [
{
match: /chatgpt|openai/i,
display: { icon: "chatgpt", vendor: "OpenAI", uses: "對話・寫作・數據分析" },
},
{
match: /claude|anthropic/i,
display: { icon: "claude", vendor: "Anthropic", uses: "長文分析・文件整理" },
},
{ match: /gemini/i, display: { icon: "gemini", vendor: "Google", uses: "多模態・創意生成" } },
];
const OTHER: PlatformDisplay = {
icon: "other",
vendor: "More Platforms",
uses: "更多優質工具持續支援",
};
const UNKNOWN: PlatformDisplay = { icon: "other", vendor: null, uses: null };
/** 依平台名稱(不分大小寫)取得顯示資訊。 */
export function platformDisplay(name: string | null | undefined): PlatformDisplay {
const value = name?.trim() ?? "";
if (value === OTHER_PLATFORM) return OTHER;
return KNOWN.find((k) => k.match.test(value))?.display ?? UNKNOWN;
}
+2 -2
View File
@@ -16,6 +16,6 @@ export function proxy(request: NextRequest) {
}
export const config = {
// 登入流程、健康檢查、Next.js 內部資源與靜態檔不需要登入。
matcher: ["/((?!login|api/auth|api/health|_next/static|_next/image|favicon.ico).*)"],
// 登入流程、健康檢查、Next.js 內部資源與靜態檔(public/images 的裝飾插圖)不需要登入。
matcher: ["/((?!login|api/auth|api/health|_next/static|_next/image|images/|favicon.ico).*)"],
};
+11 -1
View File
@@ -17,9 +17,19 @@ export const CARD = {
export const today = () =>
new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Taipei" }).format(new Date());
/** 平台以圖示卡片(radio)選擇;點選卡片文字所在的 label。 */
export async function choosePlatform(page: Page, name: string) {
await page
.getByRole("radiogroup", { name: /選擇 AI 平台/ })
.locator("label")
.filter({ hasText: new RegExp(`^${name}$`) })
.click();
await expect(page.getByRole("radio", { name, exact: true })).toBeChecked();
}
// 金額用偶數(898):settings.spec 會把全站取整方式改為四捨五入,平行執行時奇數金額的試算會不穩定。
export async function fillComplete(page: Page) {
await page.getByLabel("AI 平台").selectOption("ChatGPT");
await choosePlatform(page, "ChatGPT");
await page.getByLabel("訂閱方案/項目").fill("ChatGPT Plus");
await page.getByLabel("實際台幣支付金額").fill("898");
await page.getByLabel("刷卡日期").fill(today());
+51 -12
View File
@@ -1,6 +1,13 @@
import { expect, test, type Page } from "@playwright/test";
import { auditActionsFor, createEmployee, simulateApproved, simulateReturnForRevision } from "./db";
import { PDF, fillComplete, submitNew, today, uploadBoth } from "./application-helpers";
import {
PDF,
choosePlatform,
fillComplete,
submitNew,
today,
uploadBoth,
} from "./application-helpers";
import { loginAs } from "./helpers";
// 每個測試用自己建立的員工,平行執行時互不影響。
@@ -17,16 +24,17 @@ test.describe("新增申請頁", () => {
await expect(page.getByLabel("申請人")).toHaveValue("林小美");
await expect(page.getByLabel("部門")).toHaveValue("設計部(示範)");
await expect(page.getByLabel("申請人")).toHaveAttribute("readonly", "");
await expect(page.getByLabel("AI 平台")).toHaveValue("");
await expect(page.getByLabel("AI 平台").locator("option").first()).toHaveText("請選擇平台");
const platforms = page.getByRole("radiogroup", { name: /選擇 AI 平台/ });
await expect(platforms.getByRole("radio")).not.toHaveCount(0);
await expect(platforms.getByRole("radio", { checked: true })).toHaveCount(0);
const other = page.getByLabel("其他平台名稱");
await expect(other).toBeHidden();
await page.getByLabel("AI 平台").selectOption("其他");
await choosePlatform(page, "其他");
await expect(other).toBeVisible();
await page.getByRole("button", { name: "送出申請" }).click();
await expect(page.getByText("請完成「其他平台名稱」後再送出。").first()).toBeVisible();
await page.getByLabel("AI 平台").selectOption("Claude");
await choosePlatform(page, "Claude");
await expect(other).toBeHidden();
});
@@ -52,7 +60,7 @@ test.describe("新增申請頁", () => {
test("三項缺漏:頁首「尚有 3 項資料需完成」並聚焦工作用途說明", async ({ page }) => {
await loginAs(page, createEmployee(), "/applications/new");
await page.getByLabel("AI 平台").selectOption("ChatGPT");
await choosePlatform(page, "ChatGPT");
await page.getByLabel("訂閱方案/項目").fill("ChatGPT Plus");
await page.getByLabel("實際台幣支付金額").fill("898");
await page.getByLabel("刷卡日期").fill(today());
@@ -70,6 +78,33 @@ test.describe("新增申請頁", () => {
await expect(page.getByText("請勾選聲明確認後再送出。")).toHaveCount(2);
});
test("Desktop 三欄+頁首完成進度;方向鍵切換平台", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await loginAs(page, createEmployee(), "/applications/new");
const left = (await page.getByRole("heading", { name: "申請資料" }).boundingBox())!.x;
const middle = (await page.getByRole("complementary", { name: "補助摘要" }).boundingBox())!.x;
const right = (await page.getByRole("region", { name: "申請注意事項" }).boundingBox())!.x;
expect(left).toBeLessThan(middle);
expect(middle).toBeLessThan(right);
const steps = page.getByTestId("progress-steps").getByRole("listitem");
await expect(steps).toHaveCount(3);
await expect(steps.nth(0)).toHaveAttribute("data-state", "current");
await fillComplete(page);
await page.getByLabel("我確認以上資料真實,且訂閱用途符合工作需求。").uncheck();
await expect(steps.nth(0)).toHaveAttribute("data-state", "done");
await expect(steps.nth(1)).toHaveAttribute("data-state", "current");
await expect(steps.nth(2)).toHaveAttribute("data-state", "todo");
await expect(steps.nth(1)).toContainText("上傳證明文件(進行中)");
// 已選 ChatGPT:方向鍵移到下一個平台
await page.getByRole("radio", { name: "ChatGPT", exact: true }).focus();
await page.keyboard.press("ArrowRight");
await expect(page.getByRole("radio", { name: "Claude", exact: true })).toBeChecked();
await expect(page.getByRole("radio", { name: "ChatGPT", exact: true })).not.toBeChecked();
});
test("用途少於 20 字提示但不阻擋;字數計數", async ({ page }) => {
await loginAs(page, createEmployee(), "/applications/new");
await page.getByLabel("工作用途說明").fill("整理會議紀錄");
@@ -103,7 +138,7 @@ test.describe("我的申請與詳情", () => {
const other = await browser.newContext();
const otherPage = await other.newPage();
await loginAs(otherPage, createEmployee(), "/applications/new");
await otherPage.getByLabel("AI 平台").selectOption("Claude");
await choosePlatform(otherPage, "Claude");
await otherPage.getByLabel("訂閱方案/項目").fill("Claude Pro");
await otherPage.getByRole("button", { name: "儲存草稿" }).click();
await expect(otherPage.getByText("已儲存草稿")).toBeVisible();
@@ -121,11 +156,15 @@ test.describe("我的申請與詳情", () => {
await expect(row).toContainText("--");
await expect(row).toContainText("待審核");
await page.getByLabel("狀態").selectOption({ label: "待補件" });
await page.getByRole("button", { name: "篩選" }).click();
const statusFilter = page.getByRole("navigation", { name: "依狀態篩選" });
await statusFilter.getByRole("link", { name: "待補件" }).click();
await expect(page).toHaveURL(/status=needs_revision/);
await expect(page.getByText("沒有符合條件的申請")).toBeVisible();
await page.getByLabel("狀態").selectOption({ label: "待審核" });
await page.getByRole("button", { name: "篩選" }).click();
await statusFilter.getByRole("link", { name: "待審核" }).click();
await expect(statusFilter.getByRole("link", { name: "待審核" })).toHaveAttribute(
"aria-current",
"true",
);
await expect(table.locator("tbody tr")).toHaveCount(1);
// 他人案件無法開啟
@@ -169,7 +208,7 @@ test.describe("我的申請與詳情", () => {
test("刪除從未送出的草稿需確認", async ({ page }) => {
await loginAs(page, createEmployee(), "/applications/new");
await page.getByLabel("AI 平台").selectOption("Gemini");
await choosePlatform(page, "Gemini");
await page.getByLabel("訂閱方案/項目").fill("Gemini Advanced");
await page.getByRole("button", { name: "儲存草稿" }).click();
await expect(page).toHaveURL(/\/applications\/\d+\/edit$/);
+9
View File
@@ -35,6 +35,13 @@ test("員工:只看到本人資料、待補件提醒、額度卡(參考)
const quota = section.getByTestId("quota-card");
await expect(quota).toContainText("參考");
await expect(section).not.toContainText("剩餘");
// 版面順序:待補件提醒在額度卡之前;Desktop 顯示頁首插圖與 Good Ideas 圖卡
const alertBox = await alert.boundingBox();
const quotaBox = await quota.boundingBox();
expect(alertBox!.y).toBeLessThan(quotaBox!.y);
await expect(page.locator('[data-illustration="heroHome"]')).toBeVisible();
await expect(section.getByTestId("good-ideas")).toBeVisible();
await expect(quota).toContainText("實際補助於當月結算後依全體通過案件與部門額度統一確認");
await expect(section.getByTestId("platforms")).toContainText("ChatGPT");
await expect(section.getByTestId("platforms")).toContainText("其他");
@@ -66,6 +73,8 @@ test("沒有申請:最近申請顯示空狀態與開始申請引導;手機
const section = page.getByTestId("employee-section");
await expect(section.getByText("還沒有申請紀錄")).toBeVisible();
await expect(section.getByRole("link", { name: "開始申請" })).toBeVisible();
await expect(page.locator('[data-illustration="heroHome"]')).toBeHidden();
await expect(section.getByTestId("good-ideas")).toBeHidden();
expect(await noHorizontalScroll(page)).toBe(true);
});
+18
View File
@@ -19,6 +19,24 @@ test.describe("全站框架", () => {
await expect(page.getByText("目前沒有通知")).toBeVisible();
});
test("側欄顯示品牌與底部標語;長頁面捲到底時側欄仍填滿視窗", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await loginAs(page, DEMO.employee, "/help");
const sidebar = page.getByRole("complementary", { name: "側欄" });
await expect(sidebar.getByTestId("sidebar-brand")).toContainText("AI 補助申請系統");
await expect(sidebar.getByTestId("sidebar-brand")).toContainText(
"AI Subsidy Application System",
);
await expect(sidebar.getByTestId("sidebar-footer")).toContainText("© 2026 AI 補助申請系統");
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight));
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
const box = await sidebar.boundingBox();
expect(box?.y).toBe(0);
expect(box?.height).toBe(900);
await expect(sidebar.getByTestId("sidebar-footer")).toBeInViewport();
});
test("未登入開啟 /applications 時導向登入頁", async ({ page }) => {
await page.goto("/applications");
await expect(page).toHaveURL(/\/login\?returnTo=%2Fapplications$/);