Files
aisubsidy/CLAUDE.md
T
pkgsp50777_楊舒諠andClaude Opus 5.5 2f3044e763 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]>
2026-10-13 11:21:27 +08:00

28 KiB
Raw Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project status

AI 補助申請系統 (AI subscription subsidy system): an internal web app for employees to claim 50% reimbursement of work-related AI subscriptions (ChatGPT / Claude / Gemini / other), with manager review, monthly department settlement, and HR/finance payout tracking.

Stack: Next.js 16 (App Router, TypeScript strict, full-stack) + SQLite (better-sqlite3 + Drizzle ORM), Zod, Vitest, Playwright; single-instance deployment, attachments on local disk (see openspec/changes/plan-system-roadmap/design.md D3). The project skeleton exists; business features are built change by change per the roadmap. Node 24 / npm 11.

Next.js 16 has breaking changes vs. older versions — read AGENTS.md and the guides in node_modules/next/dist/docs/ before writing Next.js code.

Git repository on branch main; remote origin = company Gitea https://gitea.moonshine-studio.net/pkgsp50777/aisubsidy.git (HTTPS only, no SSH; push auth via git-credential-oauth configured for that host — first push opens a browser for Authentik login, so the user runs it). Pushing to main triggers Gitea Actions and deploys to the vibe platform. Files use LF line endings (.gitattributes); Prettier checks this.

Commands

First-time setup: npm ci → copy .env.example to .env and set SESSION_SECRET (≥32 chars; keep AUTH_MODE=dev) → npm run db:migrate → npm run db:seed (dev mode also creates demo departments and users D0001–D0006) → npm run dev → log in at /login/dev with a demo employee number.

Command Purpose
npm run dev / build / start Next.js dev server / production build / start
npm run lint · npm run format · npm run format:check · npm run typecheck ESLint · Prettier write · Prettier check · tsc --noEmit
npm test Vitest unit + integration tests
npx vitest run <path> Run a single test file (e.g. npx vitest run src/server/backup.test.ts)
npm run test:e2e:prepare Build + reset/migrate/seed the separate e2e DB (data/e2e/). Re-run after code changes
npm run test:e2e Playwright against next start on port 3100 (no rebuild)
npx playwright test <file> Single e2e file (e.g. npx playwright test tests/e2e/home.spec.ts)
npm run db:generate Generate a SQL migration from Drizzle schema changes (commit it; never use drizzle-kit push)
npm run db:migrate · npm run db:seed Apply migrations · idempotent seed
npm run notifications:remind Generate today's deadline reminders now (also runs hourly in the server; same-day reruns don't duplicate)
npm run backup Online SQLite backup + attachments copy to BACKUP_DIR; see docs/operations/backup.md

CI is .gitea/workflows/ci.yaml, generated from the vibe-deploy containerize template — don't hand-edit it; re-run /vibe-deploy:containerize (only {{TEST_COMMAND}} is project-specific: docker build --target test ., i.e. the Dockerfile test stage runs lint, format:check, typecheck, npm test). Then it builds the image, smoke-tests it with no secrets until the HEALTHCHECK is healthy, and on the default branch publishes the image and creates a deployment. E2E is not in CI (user decision) — run it locally before pushing. E2E helpers: tests/e2e/helpers.ts (loginAs(page, employeeNo), demo users). Parallel e2e tests share one DB — use fresh employee numbers/department names instead of mutating demo users.

If Playwright's browser download fails (CDN returns 403 on this machine), set PLAYWRIGHT_CHANNEL=chrome (or msedge) to use the installed browser. On this machine Playwright may hang after the tests finish (Chrome profile cleanup); results are already printed by then.

Deployment (vibe platform)

  • Files: Dockerfile (stages deps → test → build → runtime; Next.js output: "standalone", runs as node UID 1000, port 3000, HEALTHCHECK hits /api/health), .dockerignore, compose.yaml (local container check only, AUTH_MODE=dev), vibe.yaml (port, health path, persistence at /app/data, auth.mode: oidc, required secret names).
  • App name aisubsidy → https://aisubsidy-vibe.moonshine-studio.net. Runtime secrets (vibe.yaml environment.required): SESSION_SECRET, APP_URL, BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS — values live in the developer's local .env and are handed to the Deployment API by /vibe-deploy:deploy-site; never commit them. Adding a new required env var means updating vibe.yaml.
  • The app must start and pass the health check with no secrets at all (CI smoke test): missing SESSION_SECRET → random + warning; missing OIDC settings in oidc mode → login disabled + warning. Keep new config degrading the same way instead of exiting.
  • Migrations run on startup (src/instrumentation.ts → migrateOnStartup); the image has no tsx. Migration SQL is copied into the image explicitly (standalone tracing doesn't include it).
  • /api/health must stay public (excluded in src/proxy.ts).

Authentication & authorization

  • Login is company Authentik OIDC only (AUTH_MODE=oidc, default), with prompt=login (always re-enter credentials) and local-only logout (doesn't sign out of other company systems) — both user decisions. The vibe platform injects OIDC_ISSUER / OIDC_CLIENT_ID / OIDC_CLIENT_SECRET (reserved names — never put them in the repo); APP_URL builds the redirect URI ${APP_URL}/api/auth/callback/authentik. No passwords anywhere.
  • AUTH_MODE=dev enables /login/dev (log in by employee number) for local dev and e2e. Startup refuses AUTH_MODE=dev when OIDC_ISSUER is present; in oidc mode /login/dev and its action return 404. Never key behavior off NODE_ENV for this.
  • Accounts are created on first login by provisionOnLogin (src/server/auth/provision.ts): employee role, department pending until a sysadmin assigns one or a roster CSV pre-assigns it. BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS grants sysadmin on login.
  • Every page must start with await requireRouteAccess("<route pattern>") (src/server/auth/current-user.ts); the pattern must exist in ROUTE_RULES (src/lib/access.ts) — unlisted routes are denied, and the sidebar (buildNavigation) is generated from the same table. Don't rely on a shared layout for the check (layouts don't re-run on client navigation). src/proxy.ts only redirects requests without a session cookie.
  • Every Server Action / Route Handler must call requireRole(...) itself — actions can be invoked directly. Denials use forbidden() → src/app/forbidden.tsx (HTTP 403; experimental.authInterrupts is on).
  • Application queries must go through scopeApplications(user, managedDepartmentIds(db, user)) (src/server/auth/scope.ts); review permission through canReview (only managers of the application's department; self-review allowed but flagged 「主管自行審核」). Creating an application must call requireDepartment(user).
  • Org data lives in src/server/org/ (departments, accounts, roster CSV import). Department membership on a date (for headcount snapshots) is departmentMembersAt(db, departmentId, "YYYY-MM-DD"), based on user_department_history.

Audit trail (操作紀錄)

  • Every write operation must record an audit entry inside the same transaction: recordAudit(tx, auditContext, { action, targetType, targetId, before, after, comment }) (src/server/audit/record.ts). The first parameter only accepts a withTransaction tx (type-enforced), so the business write and the record succeed or fail together. audit_logs is append-only — DB triggers reject UPDATE/DELETE.
  • before/after hold only the fields relevant to the action (use changedFields in src/server/org/diff.ts); skip the record when nothing changed. Never put tokens or secrets in them.
  • New action: add "<target>.<verb>": "中文標籤" to AUDIT_ACTIONS (and a new target type to AUDIT_TARGET_TYPES if needed) in src/lib/audit-actions.ts — the /admin/audit-log filters are generated from it.
  • Server services take an AuditContext parameter; in Server Actions build it with await auditContextFor(user) (src/server/audit/action-context.ts, current user + request IP via requestIp).
  • Tests: seedAuditActor(db) + testAuditContext() and expectAudit(db, action, targetId) / auditRows(...) from src/server/testing/audit.ts.
  • /admin/audit-log is for sysadmins and admins with users.can_view_audit_log (granted on /admin/accounts); route rules support such flags via grants in ROUTE_RULES.

Rule parameters & headcount (rule-settings)

  • Never hard-code rule values (quota, 50% ratio, rounding, deadlines, platforms, attachment limits). Read them from versioned parameters: getEffectiveRuleVersion(db, at) / requireEffectiveRuleVersion (src/server/rules/params.ts); the schema and defaults are in src/lib/rule-params.ts. Versions are append-only (DB triggers).
  • Deadlines: deriveDeadlines(db, cardDate, tz) — uses the version effective at the end of the card month; pure date math in src/domain/deadlines.ts.
  • Platform options: platformOptions(params) (always appends 「其他」). Applications must store the platform name itself, not a reference into the parameter list.
  • Department cap: getDepartmentCap(db, departmentId, month, tz) is read-only and returns 「尚未建立人數快照」 when missing — call ensureMonthSnapshots first where a snapshot must exist (settlement). Snapshots count members at 00:00 on the 1st (from user_department_history).
  • Settlement submit/return must call setSnapshotLocked(tx, audit, departmentId, month, locked) inside its transaction.
  • An initial parameter version is created by ensureDefaultRuleVersion at startup and in seed.

Applications & attachments

  • Application state changes go only through applyTransition(tx, audit, …) (src/server/applications/lifecycle.ts) inside withTransaction: it re-reads the status, checks the transition table, actor role and comment, runs an optional guard, then writes status + application_transitions (timeline, append-only) + audit. New transitions (approve/return/reject, settlement…) are added to TRANSITIONS in src/lib/application-lifecycle.ts plus an audit action — never update applications.status directly.
  • Form rules live once in src/lib/application-form.ts (validateApplication, draft vs submit mode), shared by the client form and the server services (src/server/applications/service.ts: saveDraft, submitApplication, withdrawApplication, deleteDraft). Submit re-validates, checks both attachments and the deadline, and records rule_version_id; estimates use that version (estimateFor).
  • applications.department_id is the applicant's department at creation and never follows later transfers. Deleting a never-submitted draft is a soft delete (deleted_at); deleted drafts don't exist for queries (getApplicationDetail, getApplicationAccess).
  • Attachments: service in src/server/attachments/service.ts (upload streams with magic-number format check and size limit from rule params, replace/delete mark superseded_at and keep the file, attachmentCompleteness, authorizeAttachmentRead). Files live under ATTACHMENTS_DIR with random keys and are served only by GET /api/attachments/:id (same 404 for missing/unauthorized). UI: FileUploader / FilePreview (see docs/ui-guide.md).
  • Review (src/server/applications/review.ts, reviewer.ts): reviewers are the managers of the application's department (resolveReviewers / reviewDecision, same data as canReview); a department without a manager has no reviewer — cases wait and /admin/departments lists them (user decision: admins never review). Review UI: /department/review (desktop list + detail via ?id=) and /department/review/:id (mobile). Pass expectedStatus to applyTransition from UI actions so races return 「案件狀態已變更,請重新整理」.
  • E2E: create isolated users with createEmployee(), or a department with its own manager via createTeam(), and ready-to-review cases with insertPendingApplication() (tests/e2e/db.ts); states from later changes can be simulated there. Shared form steps live in tests/e2e/application-helpers.ts.

Department settlement (月結)

  • Calculation is pure in src/domain/settlement.ts:
    • personalEligible: sum first, then ratio and rounding.
    • allocate: largest remainder; ties broken by userId; total == cap when over cap.
    • splitAcrossApplications: per-case final amounts.
    • All integer math. Never use floats for money.
  • Service in src/server/settlement/service.ts:
    • prepareSettlementMonth promotes cases and lazily creates snapshots as 「系統」.
    • getSettlementView returns the stored result, or a live preview that is not written.
    • recalculateSettlement overwrites the open trial and records audit.
    • submitCheck and submitSettlement: one transaction that recalculates, writes snapshots, moves cases settle → submitted with final_amount, calls setSnapshotLocked, and sets is_late.
    • Settlements use the rule version effective at calculation time and store it.
  • Approved → pending settlement is time-based:
    • promoteApprovedToPendingSettlement is idempotent. The SYSTEM_ACTOR transition promote runs it.
    • Triggers: page open, approve after the deadline (promoteIfDue in the same transaction), and an hourly timer (startBackgroundJobs in src/instrumentation.ts).
    • After the deadline, needs_revision cases can be expire_rejected. The reason is required.
  • Locking after submit:
    • isSettlementLocked (src/server/settlement/lock.ts) is checked in applyTransition and when editing a case. Any new write path for a case or settlement must check it too.
    • DB triggers reject changes to amounts/allocations of non-open settlements. Only status may change.
  • E2E: monthsAgo(2) is always past the submission deadline. Control the cap with setHeadcount(departmentId, month, n) before opening the page. insertPendingApplication takes cardDate / twdAmount / status.
  • Admin side (src/server/settlement/company.ts, payouts.ts; pages /admin/settlements, /admin/settlements/:departmentId/:month, /admin/payments). Admin role only; the services also check it.
    • Settlement status: open → submitted → finalized → paid. A return goes submitted → open and unlocks the snapshot.
    • Every submit appends a settlement_submissions version. Versions are append-only; return info is written once.
    • finalizeSettlement creates payout_records. Only people with final > 0 get one. payoutMonth = card month + 2. Pay item is fixed 「其他獎金」.
    • markPayoutsPaid moves cases to paid. When all records are paid, the settlement becomes paid.
    • Payout items leave pending only once (→ paid / failed / cancelled; DB trigger). Corrections are below.
    • Multi-step settlement writes use abortableTransaction + SettlementAbort (src/server/settlement/transaction.ts), so a mid-way failure rolls everything back.
    • Payout export columns live in PAYOUT_EXPORT_COLUMNS (src/lib/payouts.ts) and are shared by Excel (exceljs) and CSV.

Settlement corrections (更正)

  • After finalize, never change settlements, allocations or original payout records. Changes are append-only rows in settlement_corrections (src/server/settlement/corrections.ts; pure rules in src/domain/corrections.ts). Admin only, reason required, one admin is enough.
  • Types:
    • adjustment (補發): positive amount only, payout month ≥ current month. Blocked when the department's corrected total would exceed the settlement's snapshot cap.
    • revoke (撤銷): only when nothing for that person/settlement is paid. Cancels their pending items, cannot be cancelled. There is no recovery and no negative payout item (user decision: overpayment does not happen).
    • reschedule (改期): only for a failed payout item. Always the next payout month (reschedulePayoutMonth), never chosen.
  • Corrected amount = original final + active adjustment/revoke amounts. Reschedule moves money only.
  • Adjustments and reschedules also create a payout_records row (kind, correction_id). Payout list totals count only pending + paid.
  • A settlement becomes paid through settleIfComplete: no pending original/reschedule items, and every failed item has an active reschedule.
  • Export columns 9–11 (項目類型, 更正編號, 原發放月份) are documented in docs/operations/payout-export.md. A test keeps that doc in sync with PAYOUT_EXPORT_COLUMNS. Only append new columns.
  • Dialogs that need a reason use ReasonDialog (src/components/ui/reason-dialog.tsx).

Duplicate detection & notifications

  • Duplicate detection:
    • The pure rule is findDuplicates (src/domain/duplicates.ts). Server side lives in src/server/applications/duplicates.ts.
    • submitApplication checks inside its transaction. If unconfirmed, it returns duplicates and writes nothing. The UI shows DuplicateDialog and resubmits with confirmDuplicate=1.
    • The result is stored on the case (duplicate_of_json, confirmer, time) and shown as 「疑似重複」 in review.
    • Test helpers that submit identical cases for one user must pass confirmDuplicate: true. Attachment test hashes are unique per file.
  • Notifications (src/server/notifications/): in-app only, no email.
    • Event notifications are written inside the business transaction:
      • applyTransition calls notifyTransition.
      • The settlement services call notifySettlement* / notifyPayoutPaid.
      • New events go in events.ts, plus a type in NOTIFICATION_TYPES (src/lib/notifications.ts).
    • Only the recipient can read a notification. /notifications/:id marks it read, then redirects. It returns 404 for anyone else.
    • The top-bar bell polls the notificationSummary server action every 60 seconds and on navigation.
    • Daily deadline reminders: runDailyReminders. Reminders are deduped by (recipient, type, target, Taipei date).
      • startBackgroundJobs (src/server/startup.ts) runs them at startup and hourly, from 08:00 Asia/Taipei.
      • Manual trigger: npm run notifications:remind. It is safe to rerun the same day.
  • Route Handlers must return new Response(..., { status: 404 }). Don't call notFound() there: it breaks the response instead of returning 404.

Dashboard

  • /dashboard is composed per role: admin section first, then one manager section per managed department, then the employee section.
  • Data comes from src/server/dashboard/queries.ts. Permissions are filtered in each query.
  • Logic lives in src/domain/dashboard.ts: resolveCurrentCycle and quotaReference. quotaReference reuses the settlement personalEligible.
  • Show department quota only through QuotaCard. Its 「參考」 tag and explanation are built in; never show a bare "remaining quota".
  • Show case amounts through SubsidyAmount: 預估 before submission, 最終 after.

UI (app-shell)

  • Read docs/ui-guide.md before building pages. Logged-in pages live under src/app/(app)/ (shared frame: topbar, role-based sidebar); don't render <main>; start with PageHeader; one primary action per view.
  • Styling: Tailwind CSS v4 with design tokens in src/app/globals.css (@theme) — use token classes (bg-primary, text-muted, rounded-card…), never hard-coded colors, never dynamically built class names.
  • Formatting only via src/lib/format.ts / MoneyDisplay / StatusBadge (status labels from src/lib/application-status.ts); shared components in src/components/ui/ (ConfirmDialog for irreversible actions, Field/ErrorSummary for forms, DataTable for lists).
  • 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

  • src/app/ — Next.js routes (pages, Route Handlers).
  • src/domain/ — pure business logic (settlement math, state machine, month/deadline rules). No I/O, no implicit "now" (callers pass time in). Must not import @/server/*, next or next/* — enforced by ESLint no-restricted-imports.
  • src/server/ — server-only: env.ts (Zod-validated env, fails fast on startup via src/instrumentation.ts), db/client.ts (single shared connection: WAL, foreign_keys, busy_timeout), db/transaction.ts (withTransaction = BEGIN IMMEDIATE; wrap multi-row writes in it), db/schema/ (one file per capability, re-exported from index.ts), db/migrations/ (generated, don't hand-edit), db/seed.ts (must stay idempotent), testing/test-db.ts (createTestDatabase() temp DB with migrations for integration tests).
  • src/lib/ — shared client/server code (Zod schemas, formatting). Must not import @/server/*.
  • src/components/ — shared UI components.
  • scripts/ — CLI entry points run with tsx; import ./load-env first so .env is loaded like Next.js does.
  • Unit/integration tests live next to the code as *.test.ts; e2e tests in tests/e2e/.

Source-of-truth documents (docs/)

  • AI補助申請系統_規格文件_v1.0.docx — business rules, roles, statuses, calculation, audit, MVP acceptance criteria, open decisions (§20).
  • AI補助申請系統_表單結構與前端介面規劃_v1.0.docx — frontend IA, per-field validation, page layouts, routes, shared components, MVP priorities (P0/P1/P2), frontend acceptance criteria.
  • 風格2_首頁.png, 風格2_新增申請頁.png — chosen visual style mockups (dashboard, new application page).

Python is available via the py -3 launcher (also C:\Python\Python310); .docx text can be extracted with Python (zipfile → word/document.xml, strip tags) or PowerShell (System.IO.Compression.ZipFile). Write extracted Chinese text to a UTF-8 file and read that — piping it through the console garbles it (cp950).

Workflow: OpenSpec (spec-driven)

Changes go through OpenSpec (openspec/config.yaml, schema spec-driven). Specs live in openspec/specs/ (identity-access, org-directory, audit-trail, app-shell, rule-settings, headcount-snapshot, application-attachments, subsidy-application, application-lifecycle, application-review, settlement-calculation, department-settlement, company-settlement, payout-management, duplicate-detection, notifications, dashboard, settlement-correction so far — read the relevant one before changing that behavior; later changes modify them via delta specs), proposed changes in openspec/changes/, completed ones in openspec/changes/archive/. Use the bundled skills/commands rather than ad-hoc edits:

  • /opsx:explore — think through requirements before committing to a change
  • /opsx:propose — create a change with proposal, design, specs and tasks
  • /opsx:apply — implement a change's tasks
  • /opsx:sync — merge delta specs into main specs
  • /opsx:archive — finalize a completed change

Domain rules that are easy to get wrong

  • Month attribution is by 刷卡日期 (card charge date) only — never invoice date, service period, or submission date. It drives the application month and both deadlines.
  • Deadlines: employee submission by the 20th of the following month; department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
  • Personal amount = sum of the month's approved TWD amounts × 50%, integer TWD, rounding configurable (default round half-up). TWD amount from the card statement is the basis; foreign-currency amount is reference only.
  • Department monthly cap = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a monthly snapshot, not live headcount. Unused quota does not carry over.
  • Over cap → pro-rata: final = personal ÷ dept_total × cap. Rounding remainders are allocated by largest fractional part so the total never exceeds the cap (spec example: 450/850 of 1,300 with cap 1,000 → 346/654).
  • Approval ≠ payout. Managers review work purpose only; amounts are settled at month end across all approved cases. UI must never make the quota look first-come-first-served, and must label pre-settlement amounts as 「預估」 vs 「最終」.
  • Statuses: 草稿 → 待主管審核 → (待補件 ↔ resubmit) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 → 已發放; plus 撤回. Return/reject require a comment.
  • Locking & audit: after a department head submits settlement, data is locked; corrections go through admin rollback or correction records, never overwriting history. Snapshots, parameters and settlement results must be versioned/retained; every state transition logs actor and time.
  • All rule parameters (per-person quota, 50% ratio, deadlines, platforms, rounding, attachment limits) are admin-configurable, not hard-coded.

Roles

Employee, department manager/head (own department only), admin / HR-finance (all departments, final approval, payout; does not judge work purpose), system admin (settings, accounts, audit log). Routes in the frontend plan: /dashboard, /applications[/new|/:id], /department/review, /department/settlement, /admin/settlements|payments|settings|audit-log.

UI conventions (from the frontend plan)

Desktop-first internal tool with RWD; white/light-grey with dark blue brand color. Money as NT$ + thousands separators, dates YYYY/MM/DD, months YYYY/MM. Status badges always include text (not color alone). Labels always visible (no placeholder-as-label). One primary action per view; destructive/irreversible actions (不核准, settlement submit, final approval, mark paid) require a confirm dialog. Planned shared components: StatusBadge, MoneyDisplay, MonthPicker, FileUploader, FilePreview, ReviewTimeline, QuotaCard, ConfirmDialog, EmptyState, ErrorSummary.